file_id
stringlengths
5
8
content
stringlengths
131
14.4k
repo
stringlengths
9
59
path
stringlengths
8
120
token_length
int64
53
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
40
3.27k
comment-tokens-Qwen/Qwen2-7B
int64
2
459
file-tokens-bigcode/starcoder2-7b
int64
53
3.49k
comment-tokens-bigcode/starcoder2-7b
int64
3
483
file-tokens-google/codegemma-7b
int64
49
3.61k
comment-tokens-google/codegemma-7b
int64
3
465
file-tokens-ibm-granite/granite-8b-code-base
int64
53
3.49k
comment-tokens-ibm-granite/granite-8b-code-base
int64
3
483
file-tokens-meta-llama/CodeLlama-7b-hf
int64
68
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
57071_8
package cn.com.xiaoyaoji.entity; /** * 导入类型 * @author: zhoujingjie * @Date: 17/4/16 */ public class ImportType { //pdf public static final String IMPORT_PDF = "import.pdf"; //postman public static final String IMPORT_POSTMAN = "import.postman"; //word public static final String IMPORT_WORD = "import.word"; //excel public static final String IMPORT_EXCEL = "import.excel"; //chm public static final String IMPORT_CHM = "import.chm"; //markdown public static final String IMPORT_MARKDOWN = "import.markdown"; //epub public static final String IMPORT_EPUB = "import.epub"; //印象笔记 public static final String IMPORT_YXNOTE = "import.yxnote"; //有道笔记 public static final String IMPORT_YDNOTE = "import.ydnote"; }
Bin-mario/xiaoyaoji
xiaoyaoji-web/src/main/java/cn/com/xiaoyaoji/entity/ImportType.java
228
//印象笔记
line_comment
zh-cn
package cn.com.xiaoyaoji.entity; /** * 导入类型 * @author: zhoujingjie * @Date: 17/4/16 */ public class ImportType { //pdf public static final String IMPORT_PDF = "import.pdf"; //postman public static final String IMPORT_POSTMAN = "import.postman"; //word public static final String IMPORT_WORD = "import.word"; //excel public static final String IMPORT_EXCEL = "import.excel"; //chm public static final String IMPORT_CHM = "import.chm"; //markdown public static final String IMPORT_MARKDOWN = "import.markdown"; //epub public static final String IMPORT_EPUB = "import.epub"; //印象 <SUF> public static final String IMPORT_YXNOTE = "import.yxnote"; //有道笔记 public static final String IMPORT_YDNOTE = "import.ydnote"; }
0
215
3
228
5
237
3
228
5
297
9
false
false
false
false
false
true
18339_18
import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.util.Calendar; import java.util.Date; /* 日期类(Date,Calendar) >前面两代日期类的不足分析 JDK1.0中包含了一个java.util.Date类,但是它的大多数方法已经在JDK1.1引入Calendar类之后被弃用了。 而Calendar也存在如下问题∶ 1)可变性∶像日期和时间这样的类应该是不可变的。 2)偏移性∶Date中的年份是从1900开始的,而月份都从0开始。 3)格式化格式化只对Date有用,Calendar则不行。 4)此外,它们也不是线程安全的;不能处理闰秒等(每隔2天,多出1s)。 >LocalDate(日期/年月日)、LocalTime(时间/时分秒)、LocalDateTime(日期时间/年月日时分秒)JDK8加入 LocalDate只包含日期,可以获取日期字段LocalTime只包含时间,可以获取时间字段 LocalDateTime包含日期+时间,可以获取日期和时间字段 第三代日期类常用方法 ·使用DateTimeFormatter来格式化日期 ·LocalDateTime类 ·MonthDay类∶检查重复事件 ·是否是闰年 ·增加日期的某个部分 ·使用plus方法测试增加时间的某个部分 ·使用minus方法测试查看一年前和一年后的日期 * */ public class Date01 { public static void main(String[] args) { //1. 获取当前系统时间 //2. 这里的 Date 类是在 java.util 包 //3. 默认输出的日期格式是国外的方式, 因此通常需要对格式进行转换 Date d1 = new Date(); //获取当前系统时间 System.out.println("当前日期=" + d1); Date d2 = new Date(9234567); //通过指定毫秒数得到时间 System.out.println("d2=" + d2); //获取某个时间对应的毫秒数 //1. 创建 SimpleDateFormat 对象,可以指定相应的格式 //2. 这里的格式使用的字母是规定好,不能乱写 SimpleDateFormat sdf = new SimpleDateFormat("yyyy 年 MM 月 dd 日 hh:mm:ss E"); String format = sdf.format(d1); // format:将日期转换成指定格式的字符串 System.out.println("当前日期=" + format); //1. 可以把一个格式化的 String 转成对应的 Date //2. 得到 Date 仍然在输出时,还是按照国外的形式,如果希望指定格式输出,需要转换 //3. 在把 String -> Date , 使用的 sdf 格式需要和你给的 String 的格式一样,否则会抛出转换异常 String s = "1996 年 01 月 01 日 10:20:30 星期一"; Date parse = null; try { parse = sdf.parse(s); } catch (ParseException e) { e.printStackTrace(); } System.out.println("parse=" + sdf.format(parse)); //1. Calendar 是一个抽象类, 并且构造器是 private //2. 可以通过 getInstance() 来获取实例 //3. 提供大量的方法和字段提供给程序员 //4. Calendar 没有提供对应的格式化的类,因此需要程序员自己组合来输出(灵活) //5. 如果我们需要按照 24 小时进制来获取时间, Calendar.HOUR ==改成=> Calendar.HOUR_OF_DAY Calendar c = Calendar.getInstance(); //创建日历类对象//比较简单,自由 System.out.println("c=" + c); //2.获取日历对象的某个日历字段 System.out.println("年:" + c.get(Calendar.YEAR)); // 这里为什么要 + 1, 因为 Calendar 返回月时候,是按照 0 开始编号 System.out.println("月:" + (c.get(Calendar.MONTH) + 1)); System.out.println("日:" + c.get(Calendar.DAY_OF_MONTH)); System.out.println("小时:" + c.get(Calendar.HOUR)); System.out.println("分钟:" + c.get(Calendar.MINUTE)); System.out.println("秒:" + c.get(Calendar.SECOND)); //Calender 没有专门的格式化方法,所以使用时需要自己来组合显示 System.out.println(c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 1) + "-" + c.get(Calendar.DAY_OF_MONTH) + " " + c.get(Calendar.HOUR_OF_DAY) + ":" + c.get(Calendar.MINUTE) + ":" + c.get(Calendar.SECOND)); //第三代日期 //1. 使用 now() 返回表示当前日期时间的 对象 LocalDateTime ldt = LocalDateTime.now(); //LocalDate.now();//LocalTime.now() System.out.println(ldt); //2. 使用 DateTimeFormatter 对象来进行格式化 // 创建 DateTimeFormatter 对象 DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); String format1 = dateTimeFormatter.format(ldt); System.out.println("格式化的日期=" + format1); System.out.println("年=" + ldt.getYear()); System.out.println("月=" + ldt.getMonth()); System.out.println("月=" + ldt.getMonthValue()); System.out.println("日=" + ldt.getDayOfMonth()); System.out.println("时=" + ldt.getHour()); System.out.println("分=" + ldt.getMinute()); System.out.println("秒=" + ldt.getSecond()); LocalDate now = LocalDate.now(); //可以获取年月日 LocalTime now2 = LocalTime.now();//获取到时分秒 //提供 plus 和 minus 方法可以对当前时间进行加或者减 //看看 890 天后,是什么时候 把 年月日-时分秒 LocalDateTime localDateTime = ldt.plusDays(890); System.out.println("890 天后=" + dateTimeFormatter.format(localDateTime)); //看看在 3456 分钟前是什么时候,把 年月日-时分秒输出 LocalDateTime localDateTime2 = ldt.minusMinutes(3456); System.out.println("3456 分钟前 日期=" + dateTimeFormatter.format(localDateTime2)); } }
BinGBanG21/JavaBing
JavaSE/Date01/src/Date01.java
1,576
//创建日历类对象//比较简单,自由
line_comment
zh-cn
import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.util.Calendar; import java.util.Date; /* 日期类(Date,Calendar) >前面两代日期类的不足分析 JDK1.0中包含了一个java.util.Date类,但是它的大多数方法已经在JDK1.1引入Calendar类之后被弃用了。 而Calendar也存在如下问题∶ 1)可变性∶像日期和时间这样的类应该是不可变的。 2)偏移性∶Date中的年份是从1900开始的,而月份都从0开始。 3)格式化格式化只对Date有用,Calendar则不行。 4)此外,它们也不是线程安全的;不能处理闰秒等(每隔2天,多出1s)。 >LocalDate(日期/年月日)、LocalTime(时间/时分秒)、LocalDateTime(日期时间/年月日时分秒)JDK8加入 LocalDate只包含日期,可以获取日期字段LocalTime只包含时间,可以获取时间字段 LocalDateTime包含日期+时间,可以获取日期和时间字段 第三代日期类常用方法 ·使用DateTimeFormatter来格式化日期 ·LocalDateTime类 ·MonthDay类∶检查重复事件 ·是否是闰年 ·增加日期的某个部分 ·使用plus方法测试增加时间的某个部分 ·使用minus方法测试查看一年前和一年后的日期 * */ public class Date01 { public static void main(String[] args) { //1. 获取当前系统时间 //2. 这里的 Date 类是在 java.util 包 //3. 默认输出的日期格式是国外的方式, 因此通常需要对格式进行转换 Date d1 = new Date(); //获取当前系统时间 System.out.println("当前日期=" + d1); Date d2 = new Date(9234567); //通过指定毫秒数得到时间 System.out.println("d2=" + d2); //获取某个时间对应的毫秒数 //1. 创建 SimpleDateFormat 对象,可以指定相应的格式 //2. 这里的格式使用的字母是规定好,不能乱写 SimpleDateFormat sdf = new SimpleDateFormat("yyyy 年 MM 月 dd 日 hh:mm:ss E"); String format = sdf.format(d1); // format:将日期转换成指定格式的字符串 System.out.println("当前日期=" + format); //1. 可以把一个格式化的 String 转成对应的 Date //2. 得到 Date 仍然在输出时,还是按照国外的形式,如果希望指定格式输出,需要转换 //3. 在把 String -> Date , 使用的 sdf 格式需要和你给的 String 的格式一样,否则会抛出转换异常 String s = "1996 年 01 月 01 日 10:20:30 星期一"; Date parse = null; try { parse = sdf.parse(s); } catch (ParseException e) { e.printStackTrace(); } System.out.println("parse=" + sdf.format(parse)); //1. Calendar 是一个抽象类, 并且构造器是 private //2. 可以通过 getInstance() 来获取实例 //3. 提供大量的方法和字段提供给程序员 //4. Calendar 没有提供对应的格式化的类,因此需要程序员自己组合来输出(灵活) //5. 如果我们需要按照 24 小时进制来获取时间, Calendar.HOUR ==改成=> Calendar.HOUR_OF_DAY Calendar c = Calendar.getInstance(); //创建 <SUF> System.out.println("c=" + c); //2.获取日历对象的某个日历字段 System.out.println("年:" + c.get(Calendar.YEAR)); // 这里为什么要 + 1, 因为 Calendar 返回月时候,是按照 0 开始编号 System.out.println("月:" + (c.get(Calendar.MONTH) + 1)); System.out.println("日:" + c.get(Calendar.DAY_OF_MONTH)); System.out.println("小时:" + c.get(Calendar.HOUR)); System.out.println("分钟:" + c.get(Calendar.MINUTE)); System.out.println("秒:" + c.get(Calendar.SECOND)); //Calender 没有专门的格式化方法,所以使用时需要自己来组合显示 System.out.println(c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 1) + "-" + c.get(Calendar.DAY_OF_MONTH) + " " + c.get(Calendar.HOUR_OF_DAY) + ":" + c.get(Calendar.MINUTE) + ":" + c.get(Calendar.SECOND)); //第三代日期 //1. 使用 now() 返回表示当前日期时间的 对象 LocalDateTime ldt = LocalDateTime.now(); //LocalDate.now();//LocalTime.now() System.out.println(ldt); //2. 使用 DateTimeFormatter 对象来进行格式化 // 创建 DateTimeFormatter 对象 DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); String format1 = dateTimeFormatter.format(ldt); System.out.println("格式化的日期=" + format1); System.out.println("年=" + ldt.getYear()); System.out.println("月=" + ldt.getMonth()); System.out.println("月=" + ldt.getMonthValue()); System.out.println("日=" + ldt.getDayOfMonth()); System.out.println("时=" + ldt.getHour()); System.out.println("分=" + ldt.getMinute()); System.out.println("秒=" + ldt.getSecond()); LocalDate now = LocalDate.now(); //可以获取年月日 LocalTime now2 = LocalTime.now();//获取到时分秒 //提供 plus 和 minus 方法可以对当前时间进行加或者减 //看看 890 天后,是什么时候 把 年月日-时分秒 LocalDateTime localDateTime = ldt.plusDays(890); System.out.println("890 天后=" + dateTimeFormatter.format(localDateTime)); //看看在 3456 分钟前是什么时候,把 年月日-时分秒输出 LocalDateTime localDateTime2 = ldt.minusMinutes(3456); System.out.println("3456 分钟前 日期=" + dateTimeFormatter.format(localDateTime2)); } }
0
1,435
10
1,576
11
1,570
11
1,576
11
2,149
22
false
false
false
false
false
true
23523_1
package keyWords; public class Volatile { // 防止字分裂 // 字分裂就是:比如long、double都是64位,在32位计算机上,就要分两次更新一个值,可能在中途由于上下文的切换,就导致读值错误 // 可见性 // 阻止变量被编译器优化,也就是不会被缓存。变量值发生改变,就会直接写入主存,读的时候也只从主存里面拿 // 阻止 happens before // java会对指令进行重排序来优化性能,这种重排序就叫 happens before ,先行发生保证 // volatile操作,也叫 内存栅栏 memory barrier,该操作之前的读写等操作不会被重排序到volatile操作之后,对应其后面的操作也不会排到前面 // 先行发生保证,会把一些其他非volatile变量也刷新到主存,隐式把这些非volatile变量变成了volatile变量 // 不建议使用volatile,使用Atomic变量 public volatile long val; public Volatile(long val) { this.val = val; } public void sumsum() { for (int i = 0; i < 5; i++) { // 自增操作不是一个原子操作 System.out.println(val++); } } public static void main(String[] args) { Volatile aVolatile = new Volatile(0); aVolatile.sumsum(); } }
BinchaoPeng/JavaLearn
src/main/java/keyWords/Volatile.java
339
// 字分裂就是:比如long、double都是64位,在32位计算机上,就要分两次更新一个值,可能在中途由于上下文的切换,就导致读值错误
line_comment
zh-cn
package keyWords; public class Volatile { // 防止字分裂 // 字分 <SUF> // 可见性 // 阻止变量被编译器优化,也就是不会被缓存。变量值发生改变,就会直接写入主存,读的时候也只从主存里面拿 // 阻止 happens before // java会对指令进行重排序来优化性能,这种重排序就叫 happens before ,先行发生保证 // volatile操作,也叫 内存栅栏 memory barrier,该操作之前的读写等操作不会被重排序到volatile操作之后,对应其后面的操作也不会排到前面 // 先行发生保证,会把一些其他非volatile变量也刷新到主存,隐式把这些非volatile变量变成了volatile变量 // 不建议使用volatile,使用Atomic变量 public volatile long val; public Volatile(long val) { this.val = val; } public void sumsum() { for (int i = 0; i < 5; i++) { // 自增操作不是一个原子操作 System.out.println(val++); } } public static void main(String[] args) { Volatile aVolatile = new Volatile(0); aVolatile.sumsum(); } }
0
325
42
339
50
331
42
339
50
511
70
false
false
false
false
false
true
45849_5
package com.hu.dao.impl; import com.hu.dao.ExpenseDao; import com.hu.entity.Employee; import com.hu.entity.ExpImage; import com.hu.entity.Expense; import com.hu.entity.ExpenseItem; import com.hu.util.JdbcUtil; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; /** * @author 胡冰 * @version 1.0 * @create 2020-06-11 22:55 * @decription **/ public class ExpenseDaoImpl implements ExpenseDao { @Override public void save(Expense expense) { String sql = "insert into expense values(?,?,?,?,?,?,?,?)"; Object[] params = {expense.getExpId(), expense.getEmpId(), expense.getTotalAmount(), new java.sql.Date(expense.getExpTime().getTime()), expense.getExpDesc(), expense.getNextAuditorId(), expense.getLastResult(), expense.getStatus()}; JdbcUtil.executeUpdate(sql, params); } /** * 此处简写了,仅仅为审核功能而写 * 如果具体点儿。可以结合 findExp() 方法 */ @Override public List<Expense> findByAuditorId(String auditorId) { String sql = " select exp.* ,emp.realName " + " from expense exp , employee emp " + " where exp.empid = emp.empid " + " and nextauditor = ? "; Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; List<Expense> list = new ArrayList<Expense>(); try { conn = JdbcUtil.getConnection(); pstmt = conn.prepareStatement(sql); pstmt.setString(1, auditorId); rs = pstmt.executeQuery(); while (rs.next()) { int expId = rs.getInt("expId"); String empId = rs.getString("empId"); double totalAmount = rs.getDouble("totalAmount"); Date expTime = rs.getDate("expTime"); String expDesc = rs.getString("expDesc"); String nextAuditorId = auditorId; String lastResult = rs.getString("lastResult"); String status = rs.getString("status"); String realName = rs.getString("realName"); Employee emp = new Employee(); emp.setEmpId(empId); emp.setRealName(realName); Expense exp = new Expense(expId, empId, totalAmount, expTime, expDesc, nextAuditorId, lastResult, status, emp, null); list.add(exp); } } catch (SQLException e) { e.printStackTrace(); } finally { JdbcUtil.closeAll(conn, pstmt, rs); } return list; } @Override public void update(Expense expense) { String sql = "update expense set nextauditor = ?,lastresult=?,status =? where expid=?"; Object params[] = {expense.getNextAuditorId(), expense.getLastResult(), expense.getStatus(), expense.getExpId()}; JdbcUtil.executeUpdate(sql, params); } @Override public Expense findById(int expId) { String sql = "select * from expense where expId = ?"; Object[] params = {expId}; List<Map<String, Object>> maps = JdbcUtil.executeQuery(sql, params); if (maps.size() == 0) { return null; } Map<String, Object> map = maps.get(0); Expense exp = new Expense(); exp.setExpId(expId); map.forEach((key, value) -> { if ("empId".equalsIgnoreCase(key)) { exp.setEmpId((String) value); } if ("totalAmount".equalsIgnoreCase(key)) { exp.setTotalAmount((Double)value); } if ("expTime".equalsIgnoreCase(key)) { exp.setExpTime((Date) value); } if ("expDesc".equalsIgnoreCase(key)) { exp.setExpDesc((String) value); } if ("nextAuditor".equalsIgnoreCase(key)) { exp.setNextAuditorId((String) value); } if ("lastResult".equalsIgnoreCase(key)) { exp.setLastResult((String) value); } if ("status".equalsIgnoreCase(key)) { exp.setStatus((String) value); } }); return exp; } @Override public int findExpId() { String sql = " select max(expid) next from expense"; List<Map<String, Object>> maps = JdbcUtil.executeQuery(sql, null); Map<String, Object> map = maps.get(0); int value=0; for (String key : map.keySet()) { value = (Integer) map.get(key); } int next = value + 1; return next; } @Override public List<Expense> findExp(String empId2, String status2, java.sql.Date expTime2) { StringBuilder sql = new StringBuilder("select exp.* ,item.type,item.amount,item.itemdesc,image.realname,image.filename,image.filetype " + " from expense exp " + " JOIN expenseitem item on exp.expid = item.expid " + " join expimage image on exp.expid = image.expid " + " where 1=1"); if (empId2 != null & !"".equals(empId2)) { sql.append(" and exp.empid = '" + empId2 + "' "); } if (status2 != null & !"".equals(status2)) { sql.append(" and exp.`status`= '" + status2 + "' "); } if (expTime2 != null) { DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String sdtDate = sdf.format(expTime2); sql.append(" and exp.exptime >='" + expTime2 + "'"); } Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; List<Expense> expenseList = new ArrayList<Expense>(); List<ExpenseItem> expenseItemList = new ArrayList<ExpenseItem>(); List<ExpImage> imageList = new ArrayList<ExpImage>(); try { conn = JdbcUtil.getConnection(); pstmt = conn.prepareStatement(sql.toString()); rs = pstmt.executeQuery(); while (rs.next()) { //expense 各个字段 int expId = rs.getInt("expId"); String empId = rs.getString("empId"); double totalAmount = rs.getDouble("totalAmount"); Date expTime = rs.getDate("expTime"); String expDesc = rs.getString("expDesc"); String nextAuditorId = rs.getString("nextAuditor"); String lastResult = rs.getString("lastResult"); String status = rs.getString("status"); //expenseitem 各个字段 String type = rs.getString("type"); double amount = rs.getDouble("amount"); String itemDesc = rs.getString("itemDesc"); //expimage 各个字段 String realName = rs.getString("realName"); String filename = rs.getString("filename"); String filetype = rs.getString("filetype"); // ExpImage expImage = new ExpImage(realName, filename, filetype); expImage.setExpId(expId); ExpenseItem expenseItem = new ExpenseItem(type, amount, itemDesc); expenseItem.setExpId(expId); Expense exp = new Expense(expId, empId, totalAmount, expTime, expDesc, nextAuditorId, lastResult, status); expenseList.add(exp); expenseItemList.add(expenseItem); imageList.add(expImage); } //去除重复 for ( int i = 0 ; i < expenseList.size() - 1 ; i ++ ) { for ( int j = expenseList.size() - 1 ; j > i; j -- ) { if (expenseList.get(j).equals(expenseList.get(i))) { expenseList.remove(j); } } } // /* for (ExpenseItem item: expenseItemList){ System.out.println(item); }*/ for (int i=0;i<expenseList.size();i++){ List<ExpenseItem> itemList = new ArrayList<ExpenseItem>(); for (int j=0;j<expenseItemList.size();j++){ if(expenseList.get(i).getExpId()==expenseItemList.get(j).getExpId()){ itemList.add(expenseItemList.get(j)); } } expenseList.get(i).setItemList(itemList); for (int k=0;k<imageList.size();k++){ if(expenseList.get(i).getExpId()==imageList.get(k).getExpId()){ expenseList.get(i).setExpImage(imageList.get(k)); } } } } catch (SQLException e) { e.printStackTrace(); } finally { JdbcUtil.closeAll(conn, pstmt, rs); } return expenseList; } }
BingBuLiang/PersonnelManagement_OA
src/com/hu/dao/impl/ExpenseDaoImpl.java
2,220
//去除重复
line_comment
zh-cn
package com.hu.dao.impl; import com.hu.dao.ExpenseDao; import com.hu.entity.Employee; import com.hu.entity.ExpImage; import com.hu.entity.Expense; import com.hu.entity.ExpenseItem; import com.hu.util.JdbcUtil; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; /** * @author 胡冰 * @version 1.0 * @create 2020-06-11 22:55 * @decription **/ public class ExpenseDaoImpl implements ExpenseDao { @Override public void save(Expense expense) { String sql = "insert into expense values(?,?,?,?,?,?,?,?)"; Object[] params = {expense.getExpId(), expense.getEmpId(), expense.getTotalAmount(), new java.sql.Date(expense.getExpTime().getTime()), expense.getExpDesc(), expense.getNextAuditorId(), expense.getLastResult(), expense.getStatus()}; JdbcUtil.executeUpdate(sql, params); } /** * 此处简写了,仅仅为审核功能而写 * 如果具体点儿。可以结合 findExp() 方法 */ @Override public List<Expense> findByAuditorId(String auditorId) { String sql = " select exp.* ,emp.realName " + " from expense exp , employee emp " + " where exp.empid = emp.empid " + " and nextauditor = ? "; Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; List<Expense> list = new ArrayList<Expense>(); try { conn = JdbcUtil.getConnection(); pstmt = conn.prepareStatement(sql); pstmt.setString(1, auditorId); rs = pstmt.executeQuery(); while (rs.next()) { int expId = rs.getInt("expId"); String empId = rs.getString("empId"); double totalAmount = rs.getDouble("totalAmount"); Date expTime = rs.getDate("expTime"); String expDesc = rs.getString("expDesc"); String nextAuditorId = auditorId; String lastResult = rs.getString("lastResult"); String status = rs.getString("status"); String realName = rs.getString("realName"); Employee emp = new Employee(); emp.setEmpId(empId); emp.setRealName(realName); Expense exp = new Expense(expId, empId, totalAmount, expTime, expDesc, nextAuditorId, lastResult, status, emp, null); list.add(exp); } } catch (SQLException e) { e.printStackTrace(); } finally { JdbcUtil.closeAll(conn, pstmt, rs); } return list; } @Override public void update(Expense expense) { String sql = "update expense set nextauditor = ?,lastresult=?,status =? where expid=?"; Object params[] = {expense.getNextAuditorId(), expense.getLastResult(), expense.getStatus(), expense.getExpId()}; JdbcUtil.executeUpdate(sql, params); } @Override public Expense findById(int expId) { String sql = "select * from expense where expId = ?"; Object[] params = {expId}; List<Map<String, Object>> maps = JdbcUtil.executeQuery(sql, params); if (maps.size() == 0) { return null; } Map<String, Object> map = maps.get(0); Expense exp = new Expense(); exp.setExpId(expId); map.forEach((key, value) -> { if ("empId".equalsIgnoreCase(key)) { exp.setEmpId((String) value); } if ("totalAmount".equalsIgnoreCase(key)) { exp.setTotalAmount((Double)value); } if ("expTime".equalsIgnoreCase(key)) { exp.setExpTime((Date) value); } if ("expDesc".equalsIgnoreCase(key)) { exp.setExpDesc((String) value); } if ("nextAuditor".equalsIgnoreCase(key)) { exp.setNextAuditorId((String) value); } if ("lastResult".equalsIgnoreCase(key)) { exp.setLastResult((String) value); } if ("status".equalsIgnoreCase(key)) { exp.setStatus((String) value); } }); return exp; } @Override public int findExpId() { String sql = " select max(expid) next from expense"; List<Map<String, Object>> maps = JdbcUtil.executeQuery(sql, null); Map<String, Object> map = maps.get(0); int value=0; for (String key : map.keySet()) { value = (Integer) map.get(key); } int next = value + 1; return next; } @Override public List<Expense> findExp(String empId2, String status2, java.sql.Date expTime2) { StringBuilder sql = new StringBuilder("select exp.* ,item.type,item.amount,item.itemdesc,image.realname,image.filename,image.filetype " + " from expense exp " + " JOIN expenseitem item on exp.expid = item.expid " + " join expimage image on exp.expid = image.expid " + " where 1=1"); if (empId2 != null & !"".equals(empId2)) { sql.append(" and exp.empid = '" + empId2 + "' "); } if (status2 != null & !"".equals(status2)) { sql.append(" and exp.`status`= '" + status2 + "' "); } if (expTime2 != null) { DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String sdtDate = sdf.format(expTime2); sql.append(" and exp.exptime >='" + expTime2 + "'"); } Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; List<Expense> expenseList = new ArrayList<Expense>(); List<ExpenseItem> expenseItemList = new ArrayList<ExpenseItem>(); List<ExpImage> imageList = new ArrayList<ExpImage>(); try { conn = JdbcUtil.getConnection(); pstmt = conn.prepareStatement(sql.toString()); rs = pstmt.executeQuery(); while (rs.next()) { //expense 各个字段 int expId = rs.getInt("expId"); String empId = rs.getString("empId"); double totalAmount = rs.getDouble("totalAmount"); Date expTime = rs.getDate("expTime"); String expDesc = rs.getString("expDesc"); String nextAuditorId = rs.getString("nextAuditor"); String lastResult = rs.getString("lastResult"); String status = rs.getString("status"); //expenseitem 各个字段 String type = rs.getString("type"); double amount = rs.getDouble("amount"); String itemDesc = rs.getString("itemDesc"); //expimage 各个字段 String realName = rs.getString("realName"); String filename = rs.getString("filename"); String filetype = rs.getString("filetype"); // ExpImage expImage = new ExpImage(realName, filename, filetype); expImage.setExpId(expId); ExpenseItem expenseItem = new ExpenseItem(type, amount, itemDesc); expenseItem.setExpId(expId); Expense exp = new Expense(expId, empId, totalAmount, expTime, expDesc, nextAuditorId, lastResult, status); expenseList.add(exp); expenseItemList.add(expenseItem); imageList.add(expImage); } //去除 <SUF> for ( int i = 0 ; i < expenseList.size() - 1 ; i ++ ) { for ( int j = expenseList.size() - 1 ; j > i; j -- ) { if (expenseList.get(j).equals(expenseList.get(i))) { expenseList.remove(j); } } } // /* for (ExpenseItem item: expenseItemList){ System.out.println(item); }*/ for (int i=0;i<expenseList.size();i++){ List<ExpenseItem> itemList = new ArrayList<ExpenseItem>(); for (int j=0;j<expenseItemList.size();j++){ if(expenseList.get(i).getExpId()==expenseItemList.get(j).getExpId()){ itemList.add(expenseItemList.get(j)); } } expenseList.get(i).setItemList(itemList); for (int k=0;k<imageList.size();k++){ if(expenseList.get(i).getExpId()==imageList.get(k).getExpId()){ expenseList.get(i).setExpImage(imageList.get(k)); } } } } catch (SQLException e) { e.printStackTrace(); } finally { JdbcUtil.closeAll(conn, pstmt, rs); } return expenseList; } }
0
1,960
3
2,220
4
2,352
3
2,220
4
2,658
5
false
false
false
false
false
true
47254_36
package enumerated; import java.util.*; import net.mindview.util.*; import static enumerated.Input.*; import static net.mindview.util.Print.*; enum Category { //使用Category枚举对贩卖机的状态进行了分类 MONEY(NICKEL/*5美分*/, DIME/*10美分*/, QUARTER/*25美分*/, DOLLAR/*100美分,即1美元*/){}, //金额 ITEM_SELECTION(TOOTHPASTE/*牙膏*/, CHIPS/*薯片*/, SODA/*苏打*/, SOAP/*香皂*/){}, //商品选项 QUIT_TRANSACTION(ABORT_TRANSACTION){}, //退出交易 SHUT_DOWN(STOP){}; //关闭 private Input[] values; Category(Input... types) { values = types; } private static EnumMap<Input,Category> categories = new EnumMap<Input,Category>(Input.class); static { for(Category c : Category.class.getEnumConstants()) { //获取Category枚举类的所有实例,c是Category枚举类的一个实例 for(Input type : c.values) { //type是c实例中成员变量values中的Input枚举类的一个实例 categories.put(type, c); //以Input贩卖机输入指令为key,类目为value } } } public static Category categorize(Input input) { return categories.get(input); } } /** * @version 1.0 * @Description: * @author: bingyu * @date: 2021/6/25 */ public class VendingMachine { //贩卖机 private static State state = State.RESTING; //贩卖机的状态,默认是休眠的 private static int amount = 0; //金额 private static Input selection = null; //选项 enum StateDuration { TRANSIENT } // enum1:状态持续时间枚举 enum State { // enum2:贩卖机的状态枚举 RESTING { //休眠 void next(Input input) { switch(Category.categorize(input)) { //根据输入指令取出对应的类目 case MONEY: //如果输入的是金额选项,则增加金额, amount += input.amount(); state = ADDING_MONEY; //贩卖机状态变为"投币状态" break; case SHUT_DOWN: //如果输入的是停止命令,则贩卖机状态变为"终止状态" state = TERMINAL; default: } } }, ADDING_MONEY { //投币状态 void next(Input input) { switch(Category.categorize(input)) { case MONEY: //输入金额 amount += input.amount(); break; case ITEM_SELECTION: //输入选择商品指令 selection = input; if(amount < selection.amount()) { //判断付出的金额和商品的金额 print("Insufficient money for " + selection); //付出的金额<商品金额 金额不足 } else { state = DISPENSING; //付出的金额 > 商品金额 状态变更为"可取出商品状态" } break; case QUIT_TRANSACTION: //如果是输入的"退出交易指令" state = GIVING_CHANGE; //状态变更为"找钱,即将原来投进去的钱退出来" break; case SHUT_DOWN: //输入的关闭指定 state = TERMINAL; //状态变更为"终止状态" default: } } }, DISPENSING(StateDuration.TRANSIENT) { //可取出商品状态 void next() { print("here is your " + selection); //这是你的商品选项 amount -= selection.amount(); //扣除商品等价金额 state = GIVING_CHANGE; //状态变更为"找零钱" } }, GIVING_CHANGE(StateDuration.TRANSIENT) { //"找零钱状态"(注意因为这个枚举实例是用的带参构造器,所有它的isTransient=true) void next() { if(amount > 0) { print("Your change: " + amount); //找零 amount = 0; //将机器里的金额置0 } state = RESTING; //上面工作完成,状态变更为"休眠状态" } }, TERMINAL { void output() { print("Halted"); } }; //终止状态 private boolean isTransient = false; //枚举State用来判断是否是瞬时状态 State() {} State(StateDuration trans) { isTransient = true; } void next(Input input) { //只允许非瞬时状态的输入指定调用该方法(因为只有非瞬时状态枚举实例会重写该方法),否则就会抛异常 throw new RuntimeException("Only call " + "next(Input input) for non-transient states"); } void next() { //只允许瞬时状态的输入指令调用该方法(因为只有瞬时状态枚举实例会重写该方法),否则就会抛异常 throw new RuntimeException("Only call next() for " + "StateDuration.TRANSIENT states"); } void output() { print(amount); } } //State枚举结束 /** * 该方法永远不会停止,因为gen.next()不会返回stop命令 * @param gen */ static void run(Generator<Input> gen) { while(state != State.TERMINAL) { //状态不是终止,就一直进行 Input input = gen.next(); state.next(input); //执行下一步命令 while(state.isTransient) { //如果枚举状态是瞬时的就执行下一步 state.next(); } state.output(); //状态输出 } } public static void main(String[] args) { Generator<Input> gen = new RandomInputGenerator(); if(args.length == 1) { gen = new FileInputGenerator(args[0]); } run(gen); } } //VendingMachine结束 class RandomInputGenerator implements Generator<Input> { public Input next() { return Input.randomSelection(); //随机生成一个输入指令(但是不包括Stop)返回 } } // Create Inputs from a file of ‘;’-separated strings: class FileInputGenerator implements Generator<Input> { private Iterator<String> input; public FileInputGenerator(String fileName) { input = new TextFile(fileName, ";").iterator(); } public Input next() { if(!input.hasNext()) { return null; } return Enum.valueOf(Input.class, input.next().trim()); } }
BingYu-track/Thinking-In-Java-Learning
src/enumerated/VendingMachine.java
1,556
//状态变更为"找零钱"
line_comment
zh-cn
package enumerated; import java.util.*; import net.mindview.util.*; import static enumerated.Input.*; import static net.mindview.util.Print.*; enum Category { //使用Category枚举对贩卖机的状态进行了分类 MONEY(NICKEL/*5美分*/, DIME/*10美分*/, QUARTER/*25美分*/, DOLLAR/*100美分,即1美元*/){}, //金额 ITEM_SELECTION(TOOTHPASTE/*牙膏*/, CHIPS/*薯片*/, SODA/*苏打*/, SOAP/*香皂*/){}, //商品选项 QUIT_TRANSACTION(ABORT_TRANSACTION){}, //退出交易 SHUT_DOWN(STOP){}; //关闭 private Input[] values; Category(Input... types) { values = types; } private static EnumMap<Input,Category> categories = new EnumMap<Input,Category>(Input.class); static { for(Category c : Category.class.getEnumConstants()) { //获取Category枚举类的所有实例,c是Category枚举类的一个实例 for(Input type : c.values) { //type是c实例中成员变量values中的Input枚举类的一个实例 categories.put(type, c); //以Input贩卖机输入指令为key,类目为value } } } public static Category categorize(Input input) { return categories.get(input); } } /** * @version 1.0 * @Description: * @author: bingyu * @date: 2021/6/25 */ public class VendingMachine { //贩卖机 private static State state = State.RESTING; //贩卖机的状态,默认是休眠的 private static int amount = 0; //金额 private static Input selection = null; //选项 enum StateDuration { TRANSIENT } // enum1:状态持续时间枚举 enum State { // enum2:贩卖机的状态枚举 RESTING { //休眠 void next(Input input) { switch(Category.categorize(input)) { //根据输入指令取出对应的类目 case MONEY: //如果输入的是金额选项,则增加金额, amount += input.amount(); state = ADDING_MONEY; //贩卖机状态变为"投币状态" break; case SHUT_DOWN: //如果输入的是停止命令,则贩卖机状态变为"终止状态" state = TERMINAL; default: } } }, ADDING_MONEY { //投币状态 void next(Input input) { switch(Category.categorize(input)) { case MONEY: //输入金额 amount += input.amount(); break; case ITEM_SELECTION: //输入选择商品指令 selection = input; if(amount < selection.amount()) { //判断付出的金额和商品的金额 print("Insufficient money for " + selection); //付出的金额<商品金额 金额不足 } else { state = DISPENSING; //付出的金额 > 商品金额 状态变更为"可取出商品状态" } break; case QUIT_TRANSACTION: //如果是输入的"退出交易指令" state = GIVING_CHANGE; //状态变更为"找钱,即将原来投进去的钱退出来" break; case SHUT_DOWN: //输入的关闭指定 state = TERMINAL; //状态变更为"终止状态" default: } } }, DISPENSING(StateDuration.TRANSIENT) { //可取出商品状态 void next() { print("here is your " + selection); //这是你的商品选项 amount -= selection.amount(); //扣除商品等价金额 state = GIVING_CHANGE; //状态 <SUF> } }, GIVING_CHANGE(StateDuration.TRANSIENT) { //"找零钱状态"(注意因为这个枚举实例是用的带参构造器,所有它的isTransient=true) void next() { if(amount > 0) { print("Your change: " + amount); //找零 amount = 0; //将机器里的金额置0 } state = RESTING; //上面工作完成,状态变更为"休眠状态" } }, TERMINAL { void output() { print("Halted"); } }; //终止状态 private boolean isTransient = false; //枚举State用来判断是否是瞬时状态 State() {} State(StateDuration trans) { isTransient = true; } void next(Input input) { //只允许非瞬时状态的输入指定调用该方法(因为只有非瞬时状态枚举实例会重写该方法),否则就会抛异常 throw new RuntimeException("Only call " + "next(Input input) for non-transient states"); } void next() { //只允许瞬时状态的输入指令调用该方法(因为只有瞬时状态枚举实例会重写该方法),否则就会抛异常 throw new RuntimeException("Only call next() for " + "StateDuration.TRANSIENT states"); } void output() { print(amount); } } //State枚举结束 /** * 该方法永远不会停止,因为gen.next()不会返回stop命令 * @param gen */ static void run(Generator<Input> gen) { while(state != State.TERMINAL) { //状态不是终止,就一直进行 Input input = gen.next(); state.next(input); //执行下一步命令 while(state.isTransient) { //如果枚举状态是瞬时的就执行下一步 state.next(); } state.output(); //状态输出 } } public static void main(String[] args) { Generator<Input> gen = new RandomInputGenerator(); if(args.length == 1) { gen = new FileInputGenerator(args[0]); } run(gen); } } //VendingMachine结束 class RandomInputGenerator implements Generator<Input> { public Input next() { return Input.randomSelection(); //随机生成一个输入指令(但是不包括Stop)返回 } } // Create Inputs from a file of ‘;’-separated strings: class FileInputGenerator implements Generator<Input> { private Iterator<String> input; public FileInputGenerator(String fileName) { input = new TextFile(fileName, ";").iterator(); } public Input next() { if(!input.hasNext()) { return null; } return Enum.valueOf(Input.class, input.next().trim()); } }
0
1,407
9
1,557
10
1,580
9
1,556
10
2,172
17
false
false
false
false
false
true
58841_4
package com.hbh.service; import java.util.List; import org.apache.ibatis.annotations.Param; import com.hbh.entity.Type; import com.hbh.entity.TypeExample; /** * @Author Binvor * @Date 2019年3月25日下午2:24:36 * @Des 类别管理 */ public interface ITypeService { // 删除 int delete(String protypeid); //插入 int insert(Type record); //查询所有 List<Type> getall(); //根据主键查询 Type selectByid(String protypeid); //更新 boolean update(Type record); // 按条件查询 List<Type> getbyparams(String protypeid,String typename); }
BinvorWin/market
market/src/main/java/com/hbh/service/ITypeService.java
201
//根据主键查询
line_comment
zh-cn
package com.hbh.service; import java.util.List; import org.apache.ibatis.annotations.Param; import com.hbh.entity.Type; import com.hbh.entity.TypeExample; /** * @Author Binvor * @Date 2019年3月25日下午2:24:36 * @Des 类别管理 */ public interface ITypeService { // 删除 int delete(String protypeid); //插入 int insert(Type record); //查询所有 List<Type> getall(); //根据 <SUF> Type selectByid(String protypeid); //更新 boolean update(Type record); // 按条件查询 List<Type> getbyparams(String protypeid,String typename); }
0
157
6
195
5
191
5
195
5
233
12
false
false
false
false
false
true
32006_7
package glorydark.lockershop.items; import cn.nukkit.Player; import cn.nukkit.Server; import cn.nukkit.form.element.ElementButtonImageData; import cn.nukkit.math.Vector3f; import cn.nukkit.network.protocol.SpawnParticleEffectPacket; import cn.nukkit.utils.Config; import glorydark.lockershop.MainClass; import lombok.Data; import java.util.Calendar; import java.util.HashMap; import java.util.Map; @Data public class particleItem implements purchaseItem{ String name; String displayName; String description; String identifier; String category; ElementButtonImageData iconData; double needMoney; boolean isAllowToUse; //可使用 boolean isPurchasable; //可购买 long duration; public particleItem(String name, String displayName, String description, String category, ElementButtonImageData iconData, String identifier, double needMoney, boolean isAllowToUse, boolean isPurchasable, long duration){ this.name = name; this.description = description; this.displayName = displayName.replace("\\n", "\n"); this.identifier = identifier; this.needMoney = needMoney; this.isAllowToUse = isAllowToUse; this.isPurchasable = isPurchasable; this.duration = duration; this.iconData = iconData; this.category = category; } public void equip(Player player){ equip(player, true); } public void equip(Player player, boolean save){ if(isAllowToUse) { if (save) { MainClass.setDisplayParticle(player.getName(), this.getName()); } MainClass.players.put(player, System.currentTimeMillis()+5000); MainClass.particlesCache.put(player, MainClass.getDisplayParticle(player)); player.sendMessage("§a已装备粒子:" + this.getDisplayName()); }else{ player.sendMessage("§c§l[提示] 该粒子暂时不可用!"); } } public void remove(Player player){ //移除 MainClass.particlesCache.remove(player); MainClass.setDisplayParticle(player.getName(), ""); player.sendMessage("§a已卸载粒子:"+this.getDisplayName()); } public boolean claim(String player, String claimer, boolean purchase, Object... params){ if(MainClass.getUnlockedCapes(player).contains(this.getName())){ Player p = Server.getInstance().getPlayer(player); if(p != null){ p.sendMessage("§c§l[提示] 您已拥有此粒子!"); } return false; } if(purchase){ if(!isPurchasable) { Player p = Server.getInstance().getPlayer(player); if (p != null) { p.sendMessage("§c§l[提示] 该粒子暂时不可购买!"); } return false; } if(MainClass.economyAPI.myMoney(player) >= needMoney) { MainClass.economyAPI.reduceMoney(player, needMoney); }else{ Player p = Server.getInstance().getPlayer(player); if(p != null){ p.sendMessage("§a§l[提示] 您的货币不足"); } return false; } } Config config = new Config(MainClass.path+"/players/"+player+".yml", Config.YAML); Map<String, Object> map = new HashMap<>(); map.put("reducedMoney", needMoney); map.put("date", getDate()); map.put("claimer", claimer); if (duration == 0) { map.put("due", 0); } else { long end; if(params.length != 1) { end = System.currentTimeMillis() + duration; }else{ if(params[0].toString().equals("0")) { end = 0; }else{ end = System.currentTimeMillis() + Long.parseLong(params[0].toString()); } } map.put("due", end); map.put("dueString", getDate(end)); } config.set("particles."+name, map); config.save(); Player p = Server.getInstance().getPlayer(player); if(p != null){ p.sendMessage("§a§l[提示] 您获得了粒子:§e"+getDisplayName()+"§a,快去使用吧!"); } return true; } public static String getDate(){ Calendar c1=Calendar.getInstance(); return c1.get(Calendar.YEAR)+"年"+(c1.get(Calendar.MONTH)+1)+ "月"+c1.get(Calendar.DAY_OF_MONTH)+"日 "+c1.get(Calendar.HOUR_OF_DAY)+ ":"+c1.get(Calendar.MINUTE)+":"+c1.get(Calendar.SECOND); } public static String getDate(Long time){ if(time == 0){ return "永久"; } Calendar c1=new Calendar.Builder().build(); c1.setTimeInMillis(time); return c1.get(Calendar.YEAR)+"年"+(c1.get(Calendar.MONTH)+1)+ "月"+c1.get(Calendar.DAY_OF_MONTH)+"日 "+c1.get(Calendar.HOUR_OF_DAY)+ ":"+c1.get(Calendar.MINUTE)+":"+c1.get(Calendar.SECOND); } // @author: wode490390 public void addCustomParticle(Player p){ if(isAllowToUse) { SpawnParticleEffectPacket pk = new SpawnParticleEffectPacket(); // 此数据包用于调用客户端的颗粒效果 pk.position = new Vector3f((float) p.getX(), (float) p.getY(), (float) p.getZ()); // 生成颗粒效果的位置 pk.identifier = this.getIdentifier(); // 颗粒效果定义符, 必须和材质包内设定的一样, 否则不会显示 pk.dimensionId = 0; // 维度ID, 填玩家所在世界维度的即可, 默认为 0 (0: 主世界, 1: 地狱, 2: 末地) pk.uniqueEntityId = -1; // 某实体的UUID, 目前无需理会, 默认为 -1 p.dataPacket(pk); } } }
BirdsStudio/LockerShop
src/main/java/glorydark/lockershop/items/particleItem.java
1,517
// 某实体的UUID, 目前无需理会, 默认为 -1
line_comment
zh-cn
package glorydark.lockershop.items; import cn.nukkit.Player; import cn.nukkit.Server; import cn.nukkit.form.element.ElementButtonImageData; import cn.nukkit.math.Vector3f; import cn.nukkit.network.protocol.SpawnParticleEffectPacket; import cn.nukkit.utils.Config; import glorydark.lockershop.MainClass; import lombok.Data; import java.util.Calendar; import java.util.HashMap; import java.util.Map; @Data public class particleItem implements purchaseItem{ String name; String displayName; String description; String identifier; String category; ElementButtonImageData iconData; double needMoney; boolean isAllowToUse; //可使用 boolean isPurchasable; //可购买 long duration; public particleItem(String name, String displayName, String description, String category, ElementButtonImageData iconData, String identifier, double needMoney, boolean isAllowToUse, boolean isPurchasable, long duration){ this.name = name; this.description = description; this.displayName = displayName.replace("\\n", "\n"); this.identifier = identifier; this.needMoney = needMoney; this.isAllowToUse = isAllowToUse; this.isPurchasable = isPurchasable; this.duration = duration; this.iconData = iconData; this.category = category; } public void equip(Player player){ equip(player, true); } public void equip(Player player, boolean save){ if(isAllowToUse) { if (save) { MainClass.setDisplayParticle(player.getName(), this.getName()); } MainClass.players.put(player, System.currentTimeMillis()+5000); MainClass.particlesCache.put(player, MainClass.getDisplayParticle(player)); player.sendMessage("§a已装备粒子:" + this.getDisplayName()); }else{ player.sendMessage("§c§l[提示] 该粒子暂时不可用!"); } } public void remove(Player player){ //移除 MainClass.particlesCache.remove(player); MainClass.setDisplayParticle(player.getName(), ""); player.sendMessage("§a已卸载粒子:"+this.getDisplayName()); } public boolean claim(String player, String claimer, boolean purchase, Object... params){ if(MainClass.getUnlockedCapes(player).contains(this.getName())){ Player p = Server.getInstance().getPlayer(player); if(p != null){ p.sendMessage("§c§l[提示] 您已拥有此粒子!"); } return false; } if(purchase){ if(!isPurchasable) { Player p = Server.getInstance().getPlayer(player); if (p != null) { p.sendMessage("§c§l[提示] 该粒子暂时不可购买!"); } return false; } if(MainClass.economyAPI.myMoney(player) >= needMoney) { MainClass.economyAPI.reduceMoney(player, needMoney); }else{ Player p = Server.getInstance().getPlayer(player); if(p != null){ p.sendMessage("§a§l[提示] 您的货币不足"); } return false; } } Config config = new Config(MainClass.path+"/players/"+player+".yml", Config.YAML); Map<String, Object> map = new HashMap<>(); map.put("reducedMoney", needMoney); map.put("date", getDate()); map.put("claimer", claimer); if (duration == 0) { map.put("due", 0); } else { long end; if(params.length != 1) { end = System.currentTimeMillis() + duration; }else{ if(params[0].toString().equals("0")) { end = 0; }else{ end = System.currentTimeMillis() + Long.parseLong(params[0].toString()); } } map.put("due", end); map.put("dueString", getDate(end)); } config.set("particles."+name, map); config.save(); Player p = Server.getInstance().getPlayer(player); if(p != null){ p.sendMessage("§a§l[提示] 您获得了粒子:§e"+getDisplayName()+"§a,快去使用吧!"); } return true; } public static String getDate(){ Calendar c1=Calendar.getInstance(); return c1.get(Calendar.YEAR)+"年"+(c1.get(Calendar.MONTH)+1)+ "月"+c1.get(Calendar.DAY_OF_MONTH)+"日 "+c1.get(Calendar.HOUR_OF_DAY)+ ":"+c1.get(Calendar.MINUTE)+":"+c1.get(Calendar.SECOND); } public static String getDate(Long time){ if(time == 0){ return "永久"; } Calendar c1=new Calendar.Builder().build(); c1.setTimeInMillis(time); return c1.get(Calendar.YEAR)+"年"+(c1.get(Calendar.MONTH)+1)+ "月"+c1.get(Calendar.DAY_OF_MONTH)+"日 "+c1.get(Calendar.HOUR_OF_DAY)+ ":"+c1.get(Calendar.MINUTE)+":"+c1.get(Calendar.SECOND); } // @author: wode490390 public void addCustomParticle(Player p){ if(isAllowToUse) { SpawnParticleEffectPacket pk = new SpawnParticleEffectPacket(); // 此数据包用于调用客户端的颗粒效果 pk.position = new Vector3f((float) p.getX(), (float) p.getY(), (float) p.getZ()); // 生成颗粒效果的位置 pk.identifier = this.getIdentifier(); // 颗粒效果定义符, 必须和材质包内设定的一样, 否则不会显示 pk.dimensionId = 0; // 维度ID, 填玩家所在世界维度的即可, 默认为 0 (0: 主世界, 1: 地狱, 2: 末地) pk.uniqueEntityId = -1; // 某实 <SUF> p.dataPacket(pk); } } }
0
1,294
18
1,517
19
1,555
16
1,517
19
1,892
25
false
false
false
false
false
true
20080_4
package Link; import javafx.application.Application; import javafx.geometry.HPos; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.image.Image; import javafx.scene.layout.*; import javafx.scene.media.Media; import javafx.scene.media.MediaPlayer; import javafx.scene.paint.Color; import javafx.stage.Stage; import java.io.File; public class Main extends Application { TextArea News = new TextArea(); int fig_num = 33; File file = new File("music/bgm1.mp3"); String url = file.toURI().toString(); Media media = new Media(url); MediaPlayer mplayer = new MediaPlayer(media); public void start(Stage stage){ //-------------------------------定义面板------------------------------------ VBox vBox = new VBox(); vBox.setAlignment(Pos.CENTER); BorderPane bp = new BorderPane(); BorderPane Note = new BorderPane(); News.setMinHeight(190); News.setMaxWidth(150); Note.setTop(News); //播放bgm mplayer.setCycleCount(MediaPlayer.INDEFINITE); mplayer.play(); //------------------------------------开始界面,设置中心面板和背景图---------------------------------- bp.setCenter(vBox); bp.setStyle("-fx-background-image: url(" + "file:pic/bg3.jpeg" + "); " + "-fx-background-position: center center; " + "-fx-background-repeat: stretch;" + "-fx-background-color: transparent;"); //------------------------------进入连连看面板-------------------------- Board bo = new Board(4,6,fig_num);//默认界面 vBox.getChildren().add(bo.getVbox());//获取连连看面板 bp.setCenter(vBox); //------------------------------------上方菜单---------------------------------- MenuBar menuBar = new MenuBar(); Menu menu = new Menu("正常模式难度"); Menu menu1 = new Menu("记忆模式难度"); Menu menu2 = new Menu("图片数量"); Menu menu3 = new Menu("其他"); MenuItem bt_ease = new MenuItem("简单(4*4)"); MenuItem bt_mid = new MenuItem("中等(6*6)"); MenuItem bt_high = new MenuItem("困难(8*8)"); MenuItem bt_ghost = new MenuItem("炼狱(10*10)"); MenuItem bt_free = new MenuItem("自定义"); MenuItem bt_one = new MenuItem("简单(4*4)"); MenuItem bt_two = new MenuItem("中等(6*6)"); MenuItem bt_free1 = new MenuItem("自定义"); MenuItem bt_other1 = new MenuItem("NOTE"); //-----------------------------正常模式的按钮设置-------------------------- bt_ease.setOnAction(e->{ Board bo_ease = new Board(4,4,fig_num); reset(bp,vBox,bo_ease); }); bt_mid.setOnAction(e->{ Board bo_mid = new Board(6,6,fig_num); reset(bp,vBox,bo_mid); }); bt_high.setOnAction(e->{ Board bo_high = new Board(8,8,fig_num); reset(bp,vBox,bo_high); }); bt_ghost.setOnAction(e->{ Board bo_ghost = new Board(10,10,fig_num); reset(bp,vBox,bo_ghost); }); bt_free.setOnAction(e->{ Stage stage1 = new Stage(); BorderPane root = new BorderPane(); Scene scene = new Scene(root, 380, 180, Color.WHITE); GridPane in_put = new GridPane(); in_put.setPadding(new Insets(5)); in_put.setHgap(5); in_put.setVgap(5); ColumnConstraints column1 = new ColumnConstraints(100); ColumnConstraints column2 = new ColumnConstraints(50, 150, 300); column2.setHgrow(Priority.ALWAYS); in_put.getColumnConstraints().addAll(column1, column2); Label in_row = new Label("行"); Label in_column = new Label("列"); TextField in_row_num = new TextField(); TextField in_column_num = new TextField(); Button be_Sure = new Button("确认"); GridPane.setHalignment(in_row, HPos.RIGHT); GridPane.setHalignment(in_column, HPos.RIGHT); GridPane.setHalignment(in_row_num, HPos.LEFT); GridPane.setHalignment(in_column_num, HPos.LEFT); GridPane.setHalignment(be_Sure, HPos.RIGHT); in_put.add(in_row, 0, 0); in_put.add(in_column, 0, 1); in_put.add(in_row_num, 1, 0); in_put.add(in_column_num, 1, 1); in_put.add(be_Sure, 1, 2); be_Sure.setOnMouseClicked(e1->{ int real_r = Integer.parseInt(in_row_num.getText()); int real_c = Integer.parseInt(in_column_num.getText()); if(real_c % 2 == 0 || real_r % 2 ==0){ Board free_bo = new Board(real_r,real_c,fig_num); reset(bp,vBox,free_bo); stage1.close(); } }); root.setCenter(in_put); stage1.setScene(scene); stage1.show(); }); //-----------------------------记忆模式的按钮设置---------------------------------- bt_one.setOnAction(e->{ Board_Remember br = new Board_Remember(4,4,fig_num); reset(bp,vBox,br); }); bt_two.setOnAction(e->{ Board_Remember br = new Board_Remember(6,6,fig_num); reset(bp,vBox,br); }); bt_free1.setOnAction(e->{ Stage stage1 = new Stage(); BorderPane root = new BorderPane(); Scene scene = new Scene(root, 380, 150, Color.WHITE); GridPane in_put = new GridPane(); in_put.setPadding(new Insets(5)); in_put.setHgap(5); in_put.setVgap(5); ColumnConstraints column1 = new ColumnConstraints(100); ColumnConstraints column2 = new ColumnConstraints(50, 150, 300); column2.setHgrow(Priority.ALWAYS); in_put.getColumnConstraints().addAll(column1, column2); Label in_row = new Label("行"); Label in_column = new Label("列"); TextField in_row_num = new TextField(); TextField in_column_num = new TextField(); Button be_Sure = new Button("确认"); GridPane.setHalignment(in_row, HPos.RIGHT); GridPane.setHalignment(in_column, HPos.RIGHT); GridPane.setHalignment(in_row_num, HPos.LEFT); GridPane.setHalignment(in_column_num, HPos.LEFT); GridPane.setHalignment(be_Sure, HPos.RIGHT); in_put.add(in_row, 0, 0); in_put.add(in_column, 0, 1); in_put.add(in_row_num, 1, 0); in_put.add(in_column_num, 1, 1); in_put.add(be_Sure, 1, 2); be_Sure.setOnMouseClicked(e1->{ int real_r = Integer.parseInt(in_row_num.getText()); int real_c = Integer.parseInt(in_column_num.getText()); if(real_c % 2 == 0 || real_r % 2 ==0){ Board_Remember free_bo = new Board_Remember(real_r,real_c,fig_num); reset(bp,vBox,free_bo); stage1.close(); } }); root.setCenter(in_put); stage1.setScene(scene); stage1.show(); }); bt_other1.setOnAction(e->{ Stage stage1 = new Stage(); Pane pane = new Pane(); pane.getChildren().addAll(News); Scene scene = new Scene(pane,400,200); stage1.setScene(scene); stage1.show(); }); //----------------------------------菜单布局----------------------------- menu.getItems().addAll(bt_ease,bt_mid,bt_high,bt_ghost,bt_free); menu1.getItems().addAll(bt_one,bt_two,bt_free1); //改变全局变量的图片数量,要重新设置。 for(int i = 10 ; i <= 33; i++){ MenuItem bts = new MenuItem(""+i); int k = i; bts.setOnAction(e->fig_num=k); menu2.getItems().add(bts); } menu3.getItems().addAll(bt_other1); menuBar.getMenus().addAll(menu,menu1,menu2,menu3); //------------------------------------布置场景-------------------------------- bp.setTop(menuBar); final Scene scene = new Scene(bp,1000, 600); stage.setScene(scene); stage.setTitle("LiNK_LiNK"); stage.getIcons().add(new Image("file:pic/"+(int)(1+Math.random()*33)+".jpg")); stage.show(); } //-----------------------------------------刷新游戏界面--------------------------- public void reset(BorderPane bp,VBox vBox,Board bo){ vBox.getChildren().clear(); vBox.getChildren().add(bo.getVbox()); bp.setCenter(vBox); } }
BitComing/Java_Homework_miniGame
src/Link/Main.java
2,403
//默认界面
line_comment
zh-cn
package Link; import javafx.application.Application; import javafx.geometry.HPos; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.image.Image; import javafx.scene.layout.*; import javafx.scene.media.Media; import javafx.scene.media.MediaPlayer; import javafx.scene.paint.Color; import javafx.stage.Stage; import java.io.File; public class Main extends Application { TextArea News = new TextArea(); int fig_num = 33; File file = new File("music/bgm1.mp3"); String url = file.toURI().toString(); Media media = new Media(url); MediaPlayer mplayer = new MediaPlayer(media); public void start(Stage stage){ //-------------------------------定义面板------------------------------------ VBox vBox = new VBox(); vBox.setAlignment(Pos.CENTER); BorderPane bp = new BorderPane(); BorderPane Note = new BorderPane(); News.setMinHeight(190); News.setMaxWidth(150); Note.setTop(News); //播放bgm mplayer.setCycleCount(MediaPlayer.INDEFINITE); mplayer.play(); //------------------------------------开始界面,设置中心面板和背景图---------------------------------- bp.setCenter(vBox); bp.setStyle("-fx-background-image: url(" + "file:pic/bg3.jpeg" + "); " + "-fx-background-position: center center; " + "-fx-background-repeat: stretch;" + "-fx-background-color: transparent;"); //------------------------------进入连连看面板-------------------------- Board bo = new Board(4,6,fig_num);//默认 <SUF> vBox.getChildren().add(bo.getVbox());//获取连连看面板 bp.setCenter(vBox); //------------------------------------上方菜单---------------------------------- MenuBar menuBar = new MenuBar(); Menu menu = new Menu("正常模式难度"); Menu menu1 = new Menu("记忆模式难度"); Menu menu2 = new Menu("图片数量"); Menu menu3 = new Menu("其他"); MenuItem bt_ease = new MenuItem("简单(4*4)"); MenuItem bt_mid = new MenuItem("中等(6*6)"); MenuItem bt_high = new MenuItem("困难(8*8)"); MenuItem bt_ghost = new MenuItem("炼狱(10*10)"); MenuItem bt_free = new MenuItem("自定义"); MenuItem bt_one = new MenuItem("简单(4*4)"); MenuItem bt_two = new MenuItem("中等(6*6)"); MenuItem bt_free1 = new MenuItem("自定义"); MenuItem bt_other1 = new MenuItem("NOTE"); //-----------------------------正常模式的按钮设置-------------------------- bt_ease.setOnAction(e->{ Board bo_ease = new Board(4,4,fig_num); reset(bp,vBox,bo_ease); }); bt_mid.setOnAction(e->{ Board bo_mid = new Board(6,6,fig_num); reset(bp,vBox,bo_mid); }); bt_high.setOnAction(e->{ Board bo_high = new Board(8,8,fig_num); reset(bp,vBox,bo_high); }); bt_ghost.setOnAction(e->{ Board bo_ghost = new Board(10,10,fig_num); reset(bp,vBox,bo_ghost); }); bt_free.setOnAction(e->{ Stage stage1 = new Stage(); BorderPane root = new BorderPane(); Scene scene = new Scene(root, 380, 180, Color.WHITE); GridPane in_put = new GridPane(); in_put.setPadding(new Insets(5)); in_put.setHgap(5); in_put.setVgap(5); ColumnConstraints column1 = new ColumnConstraints(100); ColumnConstraints column2 = new ColumnConstraints(50, 150, 300); column2.setHgrow(Priority.ALWAYS); in_put.getColumnConstraints().addAll(column1, column2); Label in_row = new Label("行"); Label in_column = new Label("列"); TextField in_row_num = new TextField(); TextField in_column_num = new TextField(); Button be_Sure = new Button("确认"); GridPane.setHalignment(in_row, HPos.RIGHT); GridPane.setHalignment(in_column, HPos.RIGHT); GridPane.setHalignment(in_row_num, HPos.LEFT); GridPane.setHalignment(in_column_num, HPos.LEFT); GridPane.setHalignment(be_Sure, HPos.RIGHT); in_put.add(in_row, 0, 0); in_put.add(in_column, 0, 1); in_put.add(in_row_num, 1, 0); in_put.add(in_column_num, 1, 1); in_put.add(be_Sure, 1, 2); be_Sure.setOnMouseClicked(e1->{ int real_r = Integer.parseInt(in_row_num.getText()); int real_c = Integer.parseInt(in_column_num.getText()); if(real_c % 2 == 0 || real_r % 2 ==0){ Board free_bo = new Board(real_r,real_c,fig_num); reset(bp,vBox,free_bo); stage1.close(); } }); root.setCenter(in_put); stage1.setScene(scene); stage1.show(); }); //-----------------------------记忆模式的按钮设置---------------------------------- bt_one.setOnAction(e->{ Board_Remember br = new Board_Remember(4,4,fig_num); reset(bp,vBox,br); }); bt_two.setOnAction(e->{ Board_Remember br = new Board_Remember(6,6,fig_num); reset(bp,vBox,br); }); bt_free1.setOnAction(e->{ Stage stage1 = new Stage(); BorderPane root = new BorderPane(); Scene scene = new Scene(root, 380, 150, Color.WHITE); GridPane in_put = new GridPane(); in_put.setPadding(new Insets(5)); in_put.setHgap(5); in_put.setVgap(5); ColumnConstraints column1 = new ColumnConstraints(100); ColumnConstraints column2 = new ColumnConstraints(50, 150, 300); column2.setHgrow(Priority.ALWAYS); in_put.getColumnConstraints().addAll(column1, column2); Label in_row = new Label("行"); Label in_column = new Label("列"); TextField in_row_num = new TextField(); TextField in_column_num = new TextField(); Button be_Sure = new Button("确认"); GridPane.setHalignment(in_row, HPos.RIGHT); GridPane.setHalignment(in_column, HPos.RIGHT); GridPane.setHalignment(in_row_num, HPos.LEFT); GridPane.setHalignment(in_column_num, HPos.LEFT); GridPane.setHalignment(be_Sure, HPos.RIGHT); in_put.add(in_row, 0, 0); in_put.add(in_column, 0, 1); in_put.add(in_row_num, 1, 0); in_put.add(in_column_num, 1, 1); in_put.add(be_Sure, 1, 2); be_Sure.setOnMouseClicked(e1->{ int real_r = Integer.parseInt(in_row_num.getText()); int real_c = Integer.parseInt(in_column_num.getText()); if(real_c % 2 == 0 || real_r % 2 ==0){ Board_Remember free_bo = new Board_Remember(real_r,real_c,fig_num); reset(bp,vBox,free_bo); stage1.close(); } }); root.setCenter(in_put); stage1.setScene(scene); stage1.show(); }); bt_other1.setOnAction(e->{ Stage stage1 = new Stage(); Pane pane = new Pane(); pane.getChildren().addAll(News); Scene scene = new Scene(pane,400,200); stage1.setScene(scene); stage1.show(); }); //----------------------------------菜单布局----------------------------- menu.getItems().addAll(bt_ease,bt_mid,bt_high,bt_ghost,bt_free); menu1.getItems().addAll(bt_one,bt_two,bt_free1); //改变全局变量的图片数量,要重新设置。 for(int i = 10 ; i <= 33; i++){ MenuItem bts = new MenuItem(""+i); int k = i; bts.setOnAction(e->fig_num=k); menu2.getItems().add(bts); } menu3.getItems().addAll(bt_other1); menuBar.getMenus().addAll(menu,menu1,menu2,menu3); //------------------------------------布置场景-------------------------------- bp.setTop(menuBar); final Scene scene = new Scene(bp,1000, 600); stage.setScene(scene); stage.setTitle("LiNK_LiNK"); stage.getIcons().add(new Image("file:pic/"+(int)(1+Math.random()*33)+".jpg")); stage.show(); } //-----------------------------------------刷新游戏界面--------------------------- public void reset(BorderPane bp,VBox vBox,Board bo){ vBox.getChildren().clear(); vBox.getChildren().add(bo.getVbox()); bp.setCenter(vBox); } }
0
1,989
3
2,403
3
2,507
3
2,403
3
2,883
5
false
false
false
false
false
true
23743_4
package cn.bixin.sona.demo.web.controller; import java.util.Collections; import java.util.List; import java.util.Map; import com.alibaba.fastjson.JSON; import cn.bixin.sona.api.im.RouterRoomMessageService; import cn.bixin.sona.api.im.enums.PriorityEnum; import cn.bixin.sona.api.im.request.RoomMessageRequest; import cn.bixin.sona.api.room.SonaRoomQueryRemoteService; import cn.bixin.sona.common.dto.PageResult; import cn.bixin.sona.common.dto.Response; import cn.bixin.sona.demo.web.message.MessgeInfo; import cn.bixin.sona.demo.web.message.MicMessage; import cn.bixin.sona.demo.web.message.RewardMessage; import cn.bixin.sona.demo.web.message.RewardMessage2; import cn.bixin.sona.demo.web.request.MicRequest; import cn.bixin.sona.demo.web.request.RewardRequest; import cn.bixin.sona.demo.web.response.GiftInfoVO; import cn.bixin.sona.demo.web.response.RoomInfoVO; import cn.bixin.sona.demo.web.response.SeatInfoVO; import cn.bixin.sona.dto.RoomDTO; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import lombok.extern.slf4j.Slf4j; import org.apache.dubbo.config.annotation.DubboReference; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /** * demo */ @Slf4j @RestController @RequestMapping("/sona/demo") public class SonaDemoController { @DubboReference private SonaRoomQueryRemoteService sonaRoomQueryRemoteService; @DubboReference private RouterRoomMessageService routerRoomMessageService; private Map<String, List<SeatInfoVO>> roomSeatMap = Maps.newHashMap(); private static Map<Integer, String> giftMap = Maps.newHashMap(); static { giftMap.put(1, "海豚恋人"); giftMap.put(2, "萌兔兔"); giftMap.put(3, "原谅帽"); giftMap.put(4, "海上城堡"); } /** * 获取房间列表 */ @GetMapping(path = {"/room/list"}) public Response<List<RoomDTO>> getOnlineRoomList() { Response<PageResult<RoomDTO>> response = sonaRoomQueryRemoteService.getOnlineRoomList("0", 100); if (!response.isSuccess()) { return Response.success(Collections.emptyList()); } return Response.success(response.getResult().getList()); } /** * 获取房间列表 */ @GetMapping(path = {"/room/info"}) public Response<RoomInfoVO> getRoomInfo(@RequestParam String roomId) { Response<RoomDTO> response = sonaRoomQueryRemoteService.getRoom(Long.valueOf(roomId)); if (!response.isSuccess() || response.getResult() == null) { return Response.success(null); } RoomDTO roomDTO = response.getResult(); RoomInfoVO vo = new RoomInfoVO(); vo.setName(roomDTO.getName()); vo.setRoomId(roomDTO.getRoomId() + ""); List<SeatInfoVO> seatInfoVOS = roomSeatMap.get(roomDTO.getRoomId() + ""); if (CollectionUtils.isEmpty(seatInfoVOS)) { seatInfoVOS = Lists.newArrayList(); initSeatList(seatInfoVOS); roomSeatMap.put(roomId, seatInfoVOS); } vo.setSeatList(seatInfoVOS); return Response.success(vo); } private void initSeatList(List<SeatInfoVO> seatInfoVOS) { SeatInfoVO s1 = new SeatInfoVO(); s1.setUid(""); s1.setIndex(0); seatInfoVOS.add(s1); SeatInfoVO s2 = new SeatInfoVO(); s2.setIndex(1); s2.setUid(""); seatInfoVOS.add(s2); SeatInfoVO s3 = new SeatInfoVO(); s3.setIndex(2); s3.setUid(""); seatInfoVOS.add(s3); SeatInfoVO s4 = new SeatInfoVO(); s4.setUid(""); s4.setIndex(3); seatInfoVOS.add(s4); SeatInfoVO s5 = new SeatInfoVO(); s5.setUid(""); s5.setIndex(4); seatInfoVOS.add(s5); SeatInfoVO s6 = new SeatInfoVO(); s6.setUid(""); s6.setIndex(5); seatInfoVOS.add(s6); } /** * 获取礼物列表 */ @GetMapping(path = {"/gift/list"}) public Response<List<GiftInfoVO>> getGiftList() { List<GiftInfoVO> list = Lists.newArrayList(); GiftInfoVO gift1 = new GiftInfoVO(); gift1.setGiftId(1); gift1.setGiftName("海豚恋人"); gift1.setPrice(5200); list.add(gift1); GiftInfoVO gift2 = new GiftInfoVO(); gift2.setGiftId(2); gift2.setGiftName("萌兔兔"); gift2.setPrice(100); list.add(gift2); GiftInfoVO gift3 = new GiftInfoVO(); gift3.setGiftId(3); gift3.setGiftName("原谅帽"); gift3.setPrice(200); list.add(gift3); GiftInfoVO gift4 = new GiftInfoVO(); gift4.setGiftId(4); gift4.setGiftName("海上城堡"); gift4.setPrice(400); list.add(gift4); return Response.success(list); } /** * 礼物打赏 */ @PostMapping(path = {"/gift/reward"}) public Response<Boolean> reward(@RequestBody RewardRequest rewardRequest) { RoomMessageRequest request = new RoomMessageRequest(); request.setRoomId(Long.valueOf(rewardRequest.getRoomId())); request.setPriority(PriorityEnum.HIGH); request.setProductCode("CHATROOM"); request.setMsgType("REWARD"); RewardMessage rewardMessage = new RewardMessage(); rewardMessage.setGiftId(rewardRequest.getGiftId()); rewardMessage.setRoomId(rewardRequest.getRoomId()); rewardMessage.setUid(rewardRequest.getToUid()); RewardMessage2 rewardMessage2 = new RewardMessage2(); rewardMessage2.setGiftId(rewardRequest.getGiftId()); rewardMessage2.setFromUid(rewardRequest.getFromUid()); rewardMessage2.setToUid(rewardRequest.getToUid()); rewardMessage2.setRoomId(rewardRequest.getRoomId()); rewardMessage2.setGiftName(giftMap.get(rewardRequest.getGiftId())); MessgeInfo messageInfo = new MessgeInfo(); messageInfo.setData(JSON.toJSONString(rewardMessage)); messageInfo.setMsgType(303); request.setContent(JSON.toJSONString(messageInfo)); routerRoomMessageService.sendChatRoomMessage(request); MessgeInfo messageInfo2 = new MessgeInfo(); messageInfo2.setData(JSON.toJSONString(rewardMessage2)); messageInfo2.setMsgType(304); request.setContent(JSON.toJSONString(messageInfo2)); routerRoomMessageService.sendChatRoomMessage(request); return Response.success(true); } /** * 上下麦 */ @PostMapping(path = {"/room/mic"}) public Response<Boolean> doMic(@RequestBody MicRequest micRequest) { RoomMessageRequest request = new RoomMessageRequest(); request.setRoomId(Long.valueOf(micRequest.getRoomId())); request.setPriority(PriorityEnum.HIGH); request.setProductCode("CHATROOM"); request.setMsgType("MIC"); MicMessage micMessage = new MicMessage(); micMessage.setUid(micRequest.getUid()); micMessage.setRoomId(micRequest.getRoomId()); micMessage.setOperate(micRequest.getOperate()); micMessage.setIndex(micRequest.getIndex()); MessgeInfo messgeInfo = new MessgeInfo(); messgeInfo.setData(JSON.toJSONString(micMessage)); messgeInfo.setMsgType(203); request.setContent(JSON.toJSONString(messgeInfo)); routerRoomMessageService.sendChatRoomMessage(request); String roomId = micRequest.getRoomId(); if (micMessage.getOperate() == 1) { List<SeatInfoVO> seatList = roomSeatMap.get(roomId); if (CollectionUtils.isEmpty(seatList)) { seatList = Lists.newArrayList(); } SeatInfoVO seatInfo = seatList.stream().filter(each -> each.getIndex() == micRequest.getIndex()).findFirst().orElse(null); if (seatInfo == null) { seatInfo = new SeatInfoVO(); seatInfo.setIndex(micMessage.getIndex()); seatInfo.setUid(micRequest.getUid()); seatList.add(seatInfo); } else { seatInfo.setUid(micRequest.getUid()); } roomSeatMap.put(roomId, seatList); } else { List<SeatInfoVO> seatList = roomSeatMap.get(roomId); if (!CollectionUtils.isEmpty(seatList)) { SeatInfoVO seatInfo = seatList.stream().filter(each -> each.getIndex() == micRequest.getIndex()).findFirst().orElse(null); if (seatInfo != null) { seatInfo.setUid(""); } } roomSeatMap.put(roomId, seatList); } return Response.success(true); } }
BixinTech/sona
sona-demo-web/src/main/java/cn/bixin/sona/demo/web/controller/SonaDemoController.java
2,513
/** * 礼物打赏 */
block_comment
zh-cn
package cn.bixin.sona.demo.web.controller; import java.util.Collections; import java.util.List; import java.util.Map; import com.alibaba.fastjson.JSON; import cn.bixin.sona.api.im.RouterRoomMessageService; import cn.bixin.sona.api.im.enums.PriorityEnum; import cn.bixin.sona.api.im.request.RoomMessageRequest; import cn.bixin.sona.api.room.SonaRoomQueryRemoteService; import cn.bixin.sona.common.dto.PageResult; import cn.bixin.sona.common.dto.Response; import cn.bixin.sona.demo.web.message.MessgeInfo; import cn.bixin.sona.demo.web.message.MicMessage; import cn.bixin.sona.demo.web.message.RewardMessage; import cn.bixin.sona.demo.web.message.RewardMessage2; import cn.bixin.sona.demo.web.request.MicRequest; import cn.bixin.sona.demo.web.request.RewardRequest; import cn.bixin.sona.demo.web.response.GiftInfoVO; import cn.bixin.sona.demo.web.response.RoomInfoVO; import cn.bixin.sona.demo.web.response.SeatInfoVO; import cn.bixin.sona.dto.RoomDTO; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import lombok.extern.slf4j.Slf4j; import org.apache.dubbo.config.annotation.DubboReference; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /** * demo */ @Slf4j @RestController @RequestMapping("/sona/demo") public class SonaDemoController { @DubboReference private SonaRoomQueryRemoteService sonaRoomQueryRemoteService; @DubboReference private RouterRoomMessageService routerRoomMessageService; private Map<String, List<SeatInfoVO>> roomSeatMap = Maps.newHashMap(); private static Map<Integer, String> giftMap = Maps.newHashMap(); static { giftMap.put(1, "海豚恋人"); giftMap.put(2, "萌兔兔"); giftMap.put(3, "原谅帽"); giftMap.put(4, "海上城堡"); } /** * 获取房间列表 */ @GetMapping(path = {"/room/list"}) public Response<List<RoomDTO>> getOnlineRoomList() { Response<PageResult<RoomDTO>> response = sonaRoomQueryRemoteService.getOnlineRoomList("0", 100); if (!response.isSuccess()) { return Response.success(Collections.emptyList()); } return Response.success(response.getResult().getList()); } /** * 获取房间列表 */ @GetMapping(path = {"/room/info"}) public Response<RoomInfoVO> getRoomInfo(@RequestParam String roomId) { Response<RoomDTO> response = sonaRoomQueryRemoteService.getRoom(Long.valueOf(roomId)); if (!response.isSuccess() || response.getResult() == null) { return Response.success(null); } RoomDTO roomDTO = response.getResult(); RoomInfoVO vo = new RoomInfoVO(); vo.setName(roomDTO.getName()); vo.setRoomId(roomDTO.getRoomId() + ""); List<SeatInfoVO> seatInfoVOS = roomSeatMap.get(roomDTO.getRoomId() + ""); if (CollectionUtils.isEmpty(seatInfoVOS)) { seatInfoVOS = Lists.newArrayList(); initSeatList(seatInfoVOS); roomSeatMap.put(roomId, seatInfoVOS); } vo.setSeatList(seatInfoVOS); return Response.success(vo); } private void initSeatList(List<SeatInfoVO> seatInfoVOS) { SeatInfoVO s1 = new SeatInfoVO(); s1.setUid(""); s1.setIndex(0); seatInfoVOS.add(s1); SeatInfoVO s2 = new SeatInfoVO(); s2.setIndex(1); s2.setUid(""); seatInfoVOS.add(s2); SeatInfoVO s3 = new SeatInfoVO(); s3.setIndex(2); s3.setUid(""); seatInfoVOS.add(s3); SeatInfoVO s4 = new SeatInfoVO(); s4.setUid(""); s4.setIndex(3); seatInfoVOS.add(s4); SeatInfoVO s5 = new SeatInfoVO(); s5.setUid(""); s5.setIndex(4); seatInfoVOS.add(s5); SeatInfoVO s6 = new SeatInfoVO(); s6.setUid(""); s6.setIndex(5); seatInfoVOS.add(s6); } /** * 获取礼物列表 */ @GetMapping(path = {"/gift/list"}) public Response<List<GiftInfoVO>> getGiftList() { List<GiftInfoVO> list = Lists.newArrayList(); GiftInfoVO gift1 = new GiftInfoVO(); gift1.setGiftId(1); gift1.setGiftName("海豚恋人"); gift1.setPrice(5200); list.add(gift1); GiftInfoVO gift2 = new GiftInfoVO(); gift2.setGiftId(2); gift2.setGiftName("萌兔兔"); gift2.setPrice(100); list.add(gift2); GiftInfoVO gift3 = new GiftInfoVO(); gift3.setGiftId(3); gift3.setGiftName("原谅帽"); gift3.setPrice(200); list.add(gift3); GiftInfoVO gift4 = new GiftInfoVO(); gift4.setGiftId(4); gift4.setGiftName("海上城堡"); gift4.setPrice(400); list.add(gift4); return Response.success(list); } /** * 礼物打 <SUF>*/ @PostMapping(path = {"/gift/reward"}) public Response<Boolean> reward(@RequestBody RewardRequest rewardRequest) { RoomMessageRequest request = new RoomMessageRequest(); request.setRoomId(Long.valueOf(rewardRequest.getRoomId())); request.setPriority(PriorityEnum.HIGH); request.setProductCode("CHATROOM"); request.setMsgType("REWARD"); RewardMessage rewardMessage = new RewardMessage(); rewardMessage.setGiftId(rewardRequest.getGiftId()); rewardMessage.setRoomId(rewardRequest.getRoomId()); rewardMessage.setUid(rewardRequest.getToUid()); RewardMessage2 rewardMessage2 = new RewardMessage2(); rewardMessage2.setGiftId(rewardRequest.getGiftId()); rewardMessage2.setFromUid(rewardRequest.getFromUid()); rewardMessage2.setToUid(rewardRequest.getToUid()); rewardMessage2.setRoomId(rewardRequest.getRoomId()); rewardMessage2.setGiftName(giftMap.get(rewardRequest.getGiftId())); MessgeInfo messageInfo = new MessgeInfo(); messageInfo.setData(JSON.toJSONString(rewardMessage)); messageInfo.setMsgType(303); request.setContent(JSON.toJSONString(messageInfo)); routerRoomMessageService.sendChatRoomMessage(request); MessgeInfo messageInfo2 = new MessgeInfo(); messageInfo2.setData(JSON.toJSONString(rewardMessage2)); messageInfo2.setMsgType(304); request.setContent(JSON.toJSONString(messageInfo2)); routerRoomMessageService.sendChatRoomMessage(request); return Response.success(true); } /** * 上下麦 */ @PostMapping(path = {"/room/mic"}) public Response<Boolean> doMic(@RequestBody MicRequest micRequest) { RoomMessageRequest request = new RoomMessageRequest(); request.setRoomId(Long.valueOf(micRequest.getRoomId())); request.setPriority(PriorityEnum.HIGH); request.setProductCode("CHATROOM"); request.setMsgType("MIC"); MicMessage micMessage = new MicMessage(); micMessage.setUid(micRequest.getUid()); micMessage.setRoomId(micRequest.getRoomId()); micMessage.setOperate(micRequest.getOperate()); micMessage.setIndex(micRequest.getIndex()); MessgeInfo messgeInfo = new MessgeInfo(); messgeInfo.setData(JSON.toJSONString(micMessage)); messgeInfo.setMsgType(203); request.setContent(JSON.toJSONString(messgeInfo)); routerRoomMessageService.sendChatRoomMessage(request); String roomId = micRequest.getRoomId(); if (micMessage.getOperate() == 1) { List<SeatInfoVO> seatList = roomSeatMap.get(roomId); if (CollectionUtils.isEmpty(seatList)) { seatList = Lists.newArrayList(); } SeatInfoVO seatInfo = seatList.stream().filter(each -> each.getIndex() == micRequest.getIndex()).findFirst().orElse(null); if (seatInfo == null) { seatInfo = new SeatInfoVO(); seatInfo.setIndex(micMessage.getIndex()); seatInfo.setUid(micRequest.getUid()); seatList.add(seatInfo); } else { seatInfo.setUid(micRequest.getUid()); } roomSeatMap.put(roomId, seatList); } else { List<SeatInfoVO> seatList = roomSeatMap.get(roomId); if (!CollectionUtils.isEmpty(seatList)) { SeatInfoVO seatInfo = seatList.stream().filter(each -> each.getIndex() == micRequest.getIndex()).findFirst().orElse(null); if (seatInfo != null) { seatInfo.setUid(""); } } roomSeatMap.put(roomId, seatList); } return Response.success(true); } }
0
2,066
11
2,513
12
2,539
10
2,513
12
3,068
16
false
false
false
false
false
true
37940_6
package github.saukiya.pvpaswantedmanager.event; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.PlayerDeathEvent; import github.saukiya.pvpaswantedmanager.JailManager; import github.saukiya.pvpaswantedmanager.util.Config; import github.saukiya.pvpaswantedmanager.util.Data; import github.saukiya.pvpaswantedmanager.util.PlayerData; import github.saukiya.pvpaswantedmanager.util.Message; import github.saukiya.pvpaswantedmanager.util.Money; /*本类由 Saukiya 在 2018年2月14日 上午12:31:13 时创建 *TIM:admin@Saukiya.cn *GitHub:https://github.com/Saukiya **/ public class PlayerDeath implements Listener { @EventHandler public void onPlayerDeathEvent(PlayerDeathEvent event){ Player player = event.getEntity(); if(!Data.isOn(player.getWorld().getName()))return; Player killer = player.getKiller(); Location loc = player.getLocation(); System.out.println(" "); System.out.println(player +" "+ killer); System.out.println(loc); PlayerData playerData = Data.getPlayerData(player.getName()); int playerWantedPoints = playerData.getW_Points(); int playerJailCumulativeNumber = playerData.getJ_CumulativeNumber(); //玩家与玩家之间 if(killer !=null){ PlayerData killerData = Data.getPlayerData(killer.getName()); if(Data.isAsWanted(player.getName(), killerData)){//通缉状态 //处理通缉犯 int jailTime = Integer.valueOf(Config.getConfig(Config.TIMETICK_JAIL_PLAYER_TIMES).replaceAll("[^0-9]", "")); playerData.setJ_Times(playerData.getW_Points()*jailTime); playerData.setW_Points(0); playerData.addJ_CumulativeNumber(); playerData.setA_loc(loc); player.spigot().respawn(); //TODO 传送到指定位置 JailManager.tpJailLocation(player); Data.removeWantedList(player.getName()); Double taskRewardMoney = Double.valueOf(Config.getConfig(Config.TASKREWARD_MONEY)); if(Config.getConfig(Config.ARREST_PUNISH_ENABLED).equalsIgnoreCase("true")){ if(Money.has(player.getName(), playerWantedPoints*taskRewardMoney)){ Money.take(player.getName(), playerWantedPoints*taskRewardMoney); player.sendMessage(Message.getMsg(Message.PLAYER_ARREST_PUNISH, String.valueOf(playerWantedPoints*taskRewardMoney))); }else{ playerData.setJ_Times(playerData.getJ_Times()+(playerWantedPoints*10)); player.sendMessage(Message.getMsg(Message.PLAYER_ARREST_PUNISH_FAIL, String.valueOf(playerWantedPoints*10))); } } //处理逮捕人员 }else{//击杀状态 } } if(playerData.getW_Points()>0)Data.takePlayerLevel(player, playerData.getW_Points()); } }
Bkm016/PAWM-Reloaded
src/github/saukiya/pvpaswantedmanager/event/PlayerDeath.java
860
//击杀状态
line_comment
zh-cn
package github.saukiya.pvpaswantedmanager.event; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.PlayerDeathEvent; import github.saukiya.pvpaswantedmanager.JailManager; import github.saukiya.pvpaswantedmanager.util.Config; import github.saukiya.pvpaswantedmanager.util.Data; import github.saukiya.pvpaswantedmanager.util.PlayerData; import github.saukiya.pvpaswantedmanager.util.Message; import github.saukiya.pvpaswantedmanager.util.Money; /*本类由 Saukiya 在 2018年2月14日 上午12:31:13 时创建 *TIM:admin@Saukiya.cn *GitHub:https://github.com/Saukiya **/ public class PlayerDeath implements Listener { @EventHandler public void onPlayerDeathEvent(PlayerDeathEvent event){ Player player = event.getEntity(); if(!Data.isOn(player.getWorld().getName()))return; Player killer = player.getKiller(); Location loc = player.getLocation(); System.out.println(" "); System.out.println(player +" "+ killer); System.out.println(loc); PlayerData playerData = Data.getPlayerData(player.getName()); int playerWantedPoints = playerData.getW_Points(); int playerJailCumulativeNumber = playerData.getJ_CumulativeNumber(); //玩家与玩家之间 if(killer !=null){ PlayerData killerData = Data.getPlayerData(killer.getName()); if(Data.isAsWanted(player.getName(), killerData)){//通缉状态 //处理通缉犯 int jailTime = Integer.valueOf(Config.getConfig(Config.TIMETICK_JAIL_PLAYER_TIMES).replaceAll("[^0-9]", "")); playerData.setJ_Times(playerData.getW_Points()*jailTime); playerData.setW_Points(0); playerData.addJ_CumulativeNumber(); playerData.setA_loc(loc); player.spigot().respawn(); //TODO 传送到指定位置 JailManager.tpJailLocation(player); Data.removeWantedList(player.getName()); Double taskRewardMoney = Double.valueOf(Config.getConfig(Config.TASKREWARD_MONEY)); if(Config.getConfig(Config.ARREST_PUNISH_ENABLED).equalsIgnoreCase("true")){ if(Money.has(player.getName(), playerWantedPoints*taskRewardMoney)){ Money.take(player.getName(), playerWantedPoints*taskRewardMoney); player.sendMessage(Message.getMsg(Message.PLAYER_ARREST_PUNISH, String.valueOf(playerWantedPoints*taskRewardMoney))); }else{ playerData.setJ_Times(playerData.getJ_Times()+(playerWantedPoints*10)); player.sendMessage(Message.getMsg(Message.PLAYER_ARREST_PUNISH_FAIL, String.valueOf(playerWantedPoints*10))); } } //处理逮捕人员 }else{//击杀 <SUF> } } if(playerData.getW_Points()>0)Data.takePlayerLevel(player, playerData.getW_Points()); } }
0
676
3
860
4
811
4
860
4
1,088
7
false
false
false
false
false
true
36934_2
package icu.cattery.lixworth.blackbe; import cn.nukkit.Player; import cn.nukkit.command.Command; import cn.nukkit.command.CommandSender; import cn.nukkit.event.EventHandler; import cn.nukkit.event.Listener; import cn.nukkit.event.player.PlayerJoinEvent; import cn.nukkit.plugin.PluginBase; import com.google.gson.Gson; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; /** * BlackBE Nukkit Plugin * * BlackBE云黑致力于维护MCBE的服务器环境,用最简单粗暴的方式,让广大服主开服省心、放心 * https://minewiki.net/%E4%BA%91%E9%BB%91:BlackBE%E4%BA%91%E9%BB%91 * * @author LixWorth <lixworth@outlook.com> * @website https://github.com/lixworth/BlackBE-NKPlugin */ public class BlackBE extends PluginBase implements Listener { public static String api_version = "3.2[NE]"; public static String api_domain = "http://api.blackbe.work/openapi"; @Override public void onEnable() { this.getServer().getPluginManager().registerEvents(this, this); this.getLogger().info("BlackBE云黑插件加载完成,API版本" + api_version); } @EventHandler public void onPlayerJoin(PlayerJoinEvent playerJoinEvent) { Player player = playerJoinEvent.getPlayer(); this.getServer().getScheduler().scheduleAsyncTask(this,new QueryTask(this,player)); } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (command.getName().equals("blackbe")) { String message = "本服务器使用BlackBE云黑限制违禁玩家 API版本:" + api_version + "。 BlackBE云黑(https://blackbe.xyz)致力于维护MCBE的服务器环境,用最简单粗暴的方式,让广大服主开服省心、放心。"; if (sender.isPlayer()) { this.getServer().getPlayer(sender.getName()).sendMessage(message); } else { this.getLogger().info(message); } } return true; } }
BlackBEDevelopment/BlackBE-NKPlugin
src/main/java/icu/cattery/lixworth/blackbe/BlackBE.java
590
//blackbe.xyz)致力于维护MCBE的服务器环境,用最简单粗暴的方式,让广大服主开服省心、放心。";
line_comment
zh-cn
package icu.cattery.lixworth.blackbe; import cn.nukkit.Player; import cn.nukkit.command.Command; import cn.nukkit.command.CommandSender; import cn.nukkit.event.EventHandler; import cn.nukkit.event.Listener; import cn.nukkit.event.player.PlayerJoinEvent; import cn.nukkit.plugin.PluginBase; import com.google.gson.Gson; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; /** * BlackBE Nukkit Plugin * * BlackBE云黑致力于维护MCBE的服务器环境,用最简单粗暴的方式,让广大服主开服省心、放心 * https://minewiki.net/%E4%BA%91%E9%BB%91:BlackBE%E4%BA%91%E9%BB%91 * * @author LixWorth <lixworth@outlook.com> * @website https://github.com/lixworth/BlackBE-NKPlugin */ public class BlackBE extends PluginBase implements Listener { public static String api_version = "3.2[NE]"; public static String api_domain = "http://api.blackbe.work/openapi"; @Override public void onEnable() { this.getServer().getPluginManager().registerEvents(this, this); this.getLogger().info("BlackBE云黑插件加载完成,API版本" + api_version); } @EventHandler public void onPlayerJoin(PlayerJoinEvent playerJoinEvent) { Player player = playerJoinEvent.getPlayer(); this.getServer().getScheduler().scheduleAsyncTask(this,new QueryTask(this,player)); } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (command.getName().equals("blackbe")) { String message = "本服务器使用BlackBE云黑限制违禁玩家 API版本:" + api_version + "。 BlackBE云黑(https://bl <SUF> if (sender.isPlayer()) { this.getServer().getPlayer(sender.getName()).sendMessage(message); } else { this.getLogger().info(message); } } return true; } }
0
487
32
590
38
591
33
590
38
728
62
false
false
false
false
false
true
39454_4
package com.peony.lock; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * 显示锁和内置锁问题 * 显示锁:Lock接口的实现类,最常用的就是ReentrantLock,ReentrantReadWriteLock * 内置锁:synchronized */ public class ShowLockAndInnerLockQuestion { public static void main(String[] args) { executeUseInnerLock(); System.out.println("======================"); executeUseShowLock(); } /** * 使用显示锁 * 公平/非公平 * 可重入 */ public static void executeUseShowLock() { // 非公平锁,也是默认的锁,性能更高 // 考虑为什么更高(省去了唤醒线程的时间) Lock nonFairLock = new ReentrantLock(false); nonFairLock.lock(); System.out.println("lock"); try { action("使用显示锁实现线程安全"); } catch (Exception e) { System.out.printf("遇到异常[%s]\n", e.getCause()); } finally { // 显示锁的定时炸弹,如果不关闭锁,则这个锁将一直存在,如果一旦出现问题,这个炸弹爆炸,则很难发现发生 // 错误的地方,因为没有记录当时应当释放锁的位置 // 这也是ReentranLock不能完全替代synchronized的主要原因 System.out.println("unlock"); nonFairLock.unlock(); } } /** * 使用内置锁 * 非公平锁 * 可重入 */ public static void executeUseInnerLock() { synchronized (ShowLockAndInnerLockQuestion.class) { action("使用内置锁实现线程安全"); } } public static void action(String s) throws RuntimeException { System.out.println(s); } }
BlackHe/akoibj
src/main/java/com/peony/lock/ShowLockAndInnerLockQuestion.java
457
// 显示锁的定时炸弹,如果不关闭锁,则这个锁将一直存在,如果一旦出现问题,这个炸弹爆炸,则很难发现发生
line_comment
zh-cn
package com.peony.lock; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * 显示锁和内置锁问题 * 显示锁:Lock接口的实现类,最常用的就是ReentrantLock,ReentrantReadWriteLock * 内置锁:synchronized */ public class ShowLockAndInnerLockQuestion { public static void main(String[] args) { executeUseInnerLock(); System.out.println("======================"); executeUseShowLock(); } /** * 使用显示锁 * 公平/非公平 * 可重入 */ public static void executeUseShowLock() { // 非公平锁,也是默认的锁,性能更高 // 考虑为什么更高(省去了唤醒线程的时间) Lock nonFairLock = new ReentrantLock(false); nonFairLock.lock(); System.out.println("lock"); try { action("使用显示锁实现线程安全"); } catch (Exception e) { System.out.printf("遇到异常[%s]\n", e.getCause()); } finally { // 显示 <SUF> // 错误的地方,因为没有记录当时应当释放锁的位置 // 这也是ReentranLock不能完全替代synchronized的主要原因 System.out.println("unlock"); nonFairLock.unlock(); } } /** * 使用内置锁 * 非公平锁 * 可重入 */ public static void executeUseInnerLock() { synchronized (ShowLockAndInnerLockQuestion.class) { action("使用内置锁实现线程安全"); } } public static void action(String s) throws RuntimeException { System.out.println(s); } }
0
405
29
457
43
452
33
457
43
641
77
false
false
false
false
false
true
48855_4
package com.service; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Iterator; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import com.dao.AssignDao; import com.dao.AuthorDao; import com.dao.MemberDao; import com.dao.PaperDao; import com.dao.PersonDao; import com.dao.ReportDao; import com.service.JspToHtml; import com.vo.Author; import com.vo.Paper; import com.vo.Person; import com.vo.Report; public class ChairService { static public void addMember(Person person,String pc_code) { MemberDao memberdao = new MemberDao(); memberdao.insertMember(person,pc_code); } static public void delMember(int person_id) { MemberDao memberdao = new MemberDao(); memberdao.deleteMember(person_id); } static public void addAssign(String pc_code,int paper_number) { AssignDao assigndao = new AssignDao (); assigndao.assigPaper(pc_code, paper_number); } static public void delAssign(String pc_code,int paper_number) { AssignDao assigndao = new AssignDao (); assigndao.deleteAssign(paper_number, pc_code); } static public boolean accept(String spn) throws IOException, FileNotFoundException { if(spn != null) { int paper_number = Integer.parseInt(spn); PaperDao paperdao = new PaperDao(); PersonDao personDao = new PersonDao(); AuthorDao authordao = new AuthorDao(); Paper paper = paperdao.searchPaper(paper_number); ReportDao reportdao = new ReportDao(); Person conAuthor = null; ArrayList<Author> authorList = authordao.searchAuthor(paper_number); ArrayList <Report> reportList = reportdao.searchReport(paper_number); if(authorList != null) { Iterator <Author> it1 = authorList.iterator(); while(it1.hasNext()){ Author author = it1.next(); Person p = personDao.searchUser(author.getPerson_id()); if(author.getIs_contact().equals("Y")) { conAuthor = p; } } } // 收件人的电子邮件 String to = conAuthor.getEmail(); // 发件人的电子邮件 String from = "xxx@xxx.com"; // 假设你是从本地主机发送电子邮件 String host = "localhost"; // 获取系统属性对象 Properties properties = System.getProperties(); properties.setProperty("mail.user", "xxx@xxx.com"); properties.setProperty("mail.password", "xxxxx"); // 设置邮件服务器 properties.setProperty("mail.smtp.host", host); // 获取默认的Session对象。 Session mailSession = Session.getDefaultInstance(properties); try{ // 创建一个默认的MimeMessage对象。 MimeMessage message = new MimeMessage(mailSession); // 设置 From: 头部的header字段 message.setFrom(new InternetAddress(from)); // 设置 To: 头部的header字段 message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // 设置 Subject: header字段 message.setSubject("论文通知函"); // 现在设置的实际消息 String text = "尊敬的"+conAuthor.getName()+":\r\n" + "\r\n" + "IFIP 2.6的会议程序委员会收到了来自全世界的多篇论文提交。因此,我们必须在许多优秀的提交中做出决定。很荣幸通知您,您的论文《"+paper.getTitle()+"》 编号"+paper.getPaper_number()+"已被本会议接收。 \r\n" + "\r\n" + "谨致问候 \r\n" + "\r\n" + "Fred Lochovsky \r\n" + "程序委员会主席 "; //message.setText(text); // 创建消息部分 BodyPart messageBodyPart = new MimeBodyPart(); // 填充消息 messageBodyPart.setText(text); // 创建多媒体消息 Multipart multipart = new MimeMultipart(); // 设置文本消息部分 multipart.addBodyPart(messageBodyPart); // 附件部分 messageBodyPart = new MimeBodyPart(); if(reportList != null ) { Iterator <Report> it1 = reportList.iterator(); int k=0; while(it1.hasNext()) { k++; Report report = it1.next(); String html=JspToHtml.getCode("http://localhost:8080/CPRMS/report.jsp?paper_number="+report.getPaper_number()+"&pc_code="+report.getPc_code()); File file = new File("D:/report"+k+".html"); if(!file.exists()){ try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8"); writer.write(html); writer.flush(); writer.close(); BodyPart bp = new MimeBodyPart(); String filename = "report"+k+".html"; // 得到数据源 FileDataSource fds = new FileDataSource(file); // 得到附件本身并至入BodyPart bp.setDataHandler(new DataHandler(fds)); bp.setFileName(filename); multipart.addBodyPart(bp); } } message.setContent(multipart); Transport transport = mailSession.getTransport("smtp"); transport.connect("smtp.com","xxxx@xxx.com","xxxxx"); transport.sendMessage(message,message.getAllRecipients()); transport.close(); paperdao.acceptPaper(paper_number); return true; }catch (MessagingException mex) { mex.printStackTrace(); } } return false; } static public boolean reject(String spn) throws IOException, FileNotFoundException { if(spn != null) { int paper_number = Integer.parseInt(spn); PaperDao paperdao = new PaperDao(); PersonDao personDao = new PersonDao(); AuthorDao authordao = new AuthorDao(); Paper paper = paperdao.searchPaper(paper_number); ReportDao reportdao = new ReportDao(); Person conAuthor = null; ArrayList<Author> authorList = authordao.searchAuthor(paper_number); ArrayList <Report> reportList = reportdao.searchReport(paper_number); if(authorList != null) { Iterator <Author> it1 = authorList.iterator(); while(it1.hasNext()){ Author author = it1.next(); Person p = personDao.searchUser(author.getPerson_id()); if(author.getIs_contact().equals("Y")) { conAuthor = p; } } } // 收件人的电子邮件 String to = conAuthor.getEmail(); // 发件人的电子邮件 String from = "xxx@xxx.com"; // 假设你是从本地主机发送电子邮件 String host = "localhost"; // 获取系统属性对象 Properties properties = System.getProperties(); properties.setProperty("mail.user", "xxx@xxx.com"); properties.setProperty("mail.password", "xxxx"); // 设置邮件服务器 properties.setProperty("mail.smtp.host", host); // 获取默认的Session对象。 Session mailSession = Session.getDefaultInstance(properties); try{ // 创建一个默认的MimeMessage对象。 MimeMessage message = new MimeMessage(mailSession); // 设置 From: 头部的header字段 message.setFrom(new InternetAddress(from)); // 设置 To: 头部的header字段 message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // 设置 Subject: header字段 message.setSubject("论文通知函"); // 现在设置的实际消息 String text = "尊敬的"+conAuthor.getName()+":\r\n" + "\r\n" + "IFIP 2.6的会议程序委员会收到了来自全世界的多篇论文提交。因此,我们必须在许多优秀的提交中做出决定。很遗憾地通知您,您的论文《"+paper.getTitle()+"》 编号"+paper.getPaper_number()+"未被本会议接收。 \r\n" + "\r\n" + "谨致问候 \r\n" + "\r\n" + "Fred Lochovsky \r\n" + "程序委员会主席 "; //message.setText(text); // 创建消息部分 BodyPart messageBodyPart = new MimeBodyPart(); // 填充消息 messageBodyPart.setText(text); // 创建多媒体消息 Multipart multipart = new MimeMultipart(); // 设置文本消息部分 multipart.addBodyPart(messageBodyPart); // 附件部分 messageBodyPart = new MimeBodyPart(); if(reportList != null ) { Iterator <Report> it1 = reportList.iterator(); int k=0; while(it1.hasNext()) { k++; Report report = it1.next(); String html=JspToHtml.getCode("http://localhost:8080/CPRMS/report.jsp?paper_number="+report.getPaper_number()+"&pc_code="+report.getPc_code()); File file = new File("D:/report"+k+".html"); if(!file.exists()){ try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8"); writer.write(html); writer.flush(); writer.close(); BodyPart bp = new MimeBodyPart(); String filename = "report"+k+".html"; // 得到数据源 FileDataSource fds = new FileDataSource(file); // 得到附件本身并至入BodyPart bp.setDataHandler(new DataHandler(fds)); bp.setFileName(filename); multipart.addBodyPart(bp); } } message.setContent(multipart); Transport transport = mailSession.getTransport("smtp"); transport.connect("smtp.com","xxx@xxx.com","xxxxxxxx"); transport.sendMessage(message,message.getAllRecipients()); transport.close(); paperdao.rejectPaper(paper_number); return true; }catch (MessagingException mex) { mex.printStackTrace(); } } return false; } }
Blacklth/CPRMS
src/com/service/ChairService.java
2,857
// 设置邮件服务器
line_comment
zh-cn
package com.service; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Iterator; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import com.dao.AssignDao; import com.dao.AuthorDao; import com.dao.MemberDao; import com.dao.PaperDao; import com.dao.PersonDao; import com.dao.ReportDao; import com.service.JspToHtml; import com.vo.Author; import com.vo.Paper; import com.vo.Person; import com.vo.Report; public class ChairService { static public void addMember(Person person,String pc_code) { MemberDao memberdao = new MemberDao(); memberdao.insertMember(person,pc_code); } static public void delMember(int person_id) { MemberDao memberdao = new MemberDao(); memberdao.deleteMember(person_id); } static public void addAssign(String pc_code,int paper_number) { AssignDao assigndao = new AssignDao (); assigndao.assigPaper(pc_code, paper_number); } static public void delAssign(String pc_code,int paper_number) { AssignDao assigndao = new AssignDao (); assigndao.deleteAssign(paper_number, pc_code); } static public boolean accept(String spn) throws IOException, FileNotFoundException { if(spn != null) { int paper_number = Integer.parseInt(spn); PaperDao paperdao = new PaperDao(); PersonDao personDao = new PersonDao(); AuthorDao authordao = new AuthorDao(); Paper paper = paperdao.searchPaper(paper_number); ReportDao reportdao = new ReportDao(); Person conAuthor = null; ArrayList<Author> authorList = authordao.searchAuthor(paper_number); ArrayList <Report> reportList = reportdao.searchReport(paper_number); if(authorList != null) { Iterator <Author> it1 = authorList.iterator(); while(it1.hasNext()){ Author author = it1.next(); Person p = personDao.searchUser(author.getPerson_id()); if(author.getIs_contact().equals("Y")) { conAuthor = p; } } } // 收件人的电子邮件 String to = conAuthor.getEmail(); // 发件人的电子邮件 String from = "xxx@xxx.com"; // 假设你是从本地主机发送电子邮件 String host = "localhost"; // 获取系统属性对象 Properties properties = System.getProperties(); properties.setProperty("mail.user", "xxx@xxx.com"); properties.setProperty("mail.password", "xxxxx"); // 设置 <SUF> properties.setProperty("mail.smtp.host", host); // 获取默认的Session对象。 Session mailSession = Session.getDefaultInstance(properties); try{ // 创建一个默认的MimeMessage对象。 MimeMessage message = new MimeMessage(mailSession); // 设置 From: 头部的header字段 message.setFrom(new InternetAddress(from)); // 设置 To: 头部的header字段 message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // 设置 Subject: header字段 message.setSubject("论文通知函"); // 现在设置的实际消息 String text = "尊敬的"+conAuthor.getName()+":\r\n" + "\r\n" + "IFIP 2.6的会议程序委员会收到了来自全世界的多篇论文提交。因此,我们必须在许多优秀的提交中做出决定。很荣幸通知您,您的论文《"+paper.getTitle()+"》 编号"+paper.getPaper_number()+"已被本会议接收。 \r\n" + "\r\n" + "谨致问候 \r\n" + "\r\n" + "Fred Lochovsky \r\n" + "程序委员会主席 "; //message.setText(text); // 创建消息部分 BodyPart messageBodyPart = new MimeBodyPart(); // 填充消息 messageBodyPart.setText(text); // 创建多媒体消息 Multipart multipart = new MimeMultipart(); // 设置文本消息部分 multipart.addBodyPart(messageBodyPart); // 附件部分 messageBodyPart = new MimeBodyPart(); if(reportList != null ) { Iterator <Report> it1 = reportList.iterator(); int k=0; while(it1.hasNext()) { k++; Report report = it1.next(); String html=JspToHtml.getCode("http://localhost:8080/CPRMS/report.jsp?paper_number="+report.getPaper_number()+"&pc_code="+report.getPc_code()); File file = new File("D:/report"+k+".html"); if(!file.exists()){ try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8"); writer.write(html); writer.flush(); writer.close(); BodyPart bp = new MimeBodyPart(); String filename = "report"+k+".html"; // 得到数据源 FileDataSource fds = new FileDataSource(file); // 得到附件本身并至入BodyPart bp.setDataHandler(new DataHandler(fds)); bp.setFileName(filename); multipart.addBodyPart(bp); } } message.setContent(multipart); Transport transport = mailSession.getTransport("smtp"); transport.connect("smtp.com","xxxx@xxx.com","xxxxx"); transport.sendMessage(message,message.getAllRecipients()); transport.close(); paperdao.acceptPaper(paper_number); return true; }catch (MessagingException mex) { mex.printStackTrace(); } } return false; } static public boolean reject(String spn) throws IOException, FileNotFoundException { if(spn != null) { int paper_number = Integer.parseInt(spn); PaperDao paperdao = new PaperDao(); PersonDao personDao = new PersonDao(); AuthorDao authordao = new AuthorDao(); Paper paper = paperdao.searchPaper(paper_number); ReportDao reportdao = new ReportDao(); Person conAuthor = null; ArrayList<Author> authorList = authordao.searchAuthor(paper_number); ArrayList <Report> reportList = reportdao.searchReport(paper_number); if(authorList != null) { Iterator <Author> it1 = authorList.iterator(); while(it1.hasNext()){ Author author = it1.next(); Person p = personDao.searchUser(author.getPerson_id()); if(author.getIs_contact().equals("Y")) { conAuthor = p; } } } // 收件人的电子邮件 String to = conAuthor.getEmail(); // 发件人的电子邮件 String from = "xxx@xxx.com"; // 假设你是从本地主机发送电子邮件 String host = "localhost"; // 获取系统属性对象 Properties properties = System.getProperties(); properties.setProperty("mail.user", "xxx@xxx.com"); properties.setProperty("mail.password", "xxxx"); // 设置邮件服务器 properties.setProperty("mail.smtp.host", host); // 获取默认的Session对象。 Session mailSession = Session.getDefaultInstance(properties); try{ // 创建一个默认的MimeMessage对象。 MimeMessage message = new MimeMessage(mailSession); // 设置 From: 头部的header字段 message.setFrom(new InternetAddress(from)); // 设置 To: 头部的header字段 message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // 设置 Subject: header字段 message.setSubject("论文通知函"); // 现在设置的实际消息 String text = "尊敬的"+conAuthor.getName()+":\r\n" + "\r\n" + "IFIP 2.6的会议程序委员会收到了来自全世界的多篇论文提交。因此,我们必须在许多优秀的提交中做出决定。很遗憾地通知您,您的论文《"+paper.getTitle()+"》 编号"+paper.getPaper_number()+"未被本会议接收。 \r\n" + "\r\n" + "谨致问候 \r\n" + "\r\n" + "Fred Lochovsky \r\n" + "程序委员会主席 "; //message.setText(text); // 创建消息部分 BodyPart messageBodyPart = new MimeBodyPart(); // 填充消息 messageBodyPart.setText(text); // 创建多媒体消息 Multipart multipart = new MimeMultipart(); // 设置文本消息部分 multipart.addBodyPart(messageBodyPart); // 附件部分 messageBodyPart = new MimeBodyPart(); if(reportList != null ) { Iterator <Report> it1 = reportList.iterator(); int k=0; while(it1.hasNext()) { k++; Report report = it1.next(); String html=JspToHtml.getCode("http://localhost:8080/CPRMS/report.jsp?paper_number="+report.getPaper_number()+"&pc_code="+report.getPc_code()); File file = new File("D:/report"+k+".html"); if(!file.exists()){ try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8"); writer.write(html); writer.flush(); writer.close(); BodyPart bp = new MimeBodyPart(); String filename = "report"+k+".html"; // 得到数据源 FileDataSource fds = new FileDataSource(file); // 得到附件本身并至入BodyPart bp.setDataHandler(new DataHandler(fds)); bp.setFileName(filename); multipart.addBodyPart(bp); } } message.setContent(multipart); Transport transport = mailSession.getTransport("smtp"); transport.connect("smtp.com","xxx@xxx.com","xxxxxxxx"); transport.sendMessage(message,message.getAllRecipients()); transport.close(); paperdao.rejectPaper(paper_number); return true; }catch (MessagingException mex) { mex.printStackTrace(); } } return false; } }
0
2,436
4
2,857
4
3,128
4
2,857
4
4,098
11
false
false
false
false
false
true
1169_6
package com.blankj.subutil.util; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.net.Uri; import android.util.Log; import com.blankj.utilcode.util.AppUtils; import com.blankj.utilcode.util.RomUtils; import com.blankj.utilcode.util.Utils; import java.util.List; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 2019/05/20 * desc : utils about app store * </pre> */ public final class AppStoreUtils { private static final String TAG = "AppStoreUtils"; private static final String GOOGLE_PLAY_APP_STORE_PACKAGE_NAME = "com.android.vending"; /** * 获取跳转到应用商店的 Intent * * @return 跳转到应用商店的 Intent */ public static Intent getAppStoreIntent() { return getAppStoreIntent(Utils.getApp().getPackageName(), false); } /** * 获取跳转到应用商店的 Intent * * @param isIncludeGooglePlayStore 是否包括 Google Play 商店 * @return 跳转到应用商店的 Intent */ public static Intent getAppStoreIntent(boolean isIncludeGooglePlayStore) { return getAppStoreIntent(Utils.getApp().getPackageName(), isIncludeGooglePlayStore); } /** * 获取跳转到应用商店的 Intent * * @param packageName 包名 * @return 跳转到应用商店的 Intent */ public static Intent getAppStoreIntent(final String packageName) { return getAppStoreIntent(packageName, false); } /** * 获取跳转到应用商店的 Intent * <p>优先跳转到手机自带的应用市场</p> * * @param packageName 包名 * @param isIncludeGooglePlayStore 是否包括 Google Play 商店 * @return 跳转到应用商店的 Intent */ public static Intent getAppStoreIntent(final String packageName, boolean isIncludeGooglePlayStore) { if (RomUtils.isSamsung()) {// 三星单独处理跳转三星市场 Intent samsungAppStoreIntent = getSamsungAppStoreIntent(packageName); if (samsungAppStoreIntent != null) return samsungAppStoreIntent; } if (RomUtils.isLeeco()) {// 乐视单独处理跳转乐视市场 Intent leecoAppStoreIntent = getLeecoAppStoreIntent(packageName); if (leecoAppStoreIntent != null) return leecoAppStoreIntent; } Uri uri = Uri.parse("market://details?id=" + packageName); Intent intent = new Intent(); intent.setData(uri); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); List<ResolveInfo> resolveInfos = Utils.getApp().getPackageManager() .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); if (resolveInfos == null || resolveInfos.size() == 0) { Log.e(TAG, "No app store!"); return null; } Intent googleIntent = null; for (ResolveInfo resolveInfo : resolveInfos) { String pkgName = resolveInfo.activityInfo.packageName; if (!GOOGLE_PLAY_APP_STORE_PACKAGE_NAME.equals(pkgName)) { if (AppUtils.isAppSystem(pkgName)) { intent.setPackage(pkgName); return intent; } } else { intent.setPackage(GOOGLE_PLAY_APP_STORE_PACKAGE_NAME); googleIntent = intent; } } if (isIncludeGooglePlayStore && googleIntent != null) { return googleIntent; } intent.setPackage(resolveInfos.get(0).activityInfo.packageName); return intent; } private static Intent getSamsungAppStoreIntent(final String packageName) { Intent intent = new Intent(); intent.setClassName("com.sec.android.app.samsungapps", "com.sec.android.app.samsungapps.Main"); intent.setData(Uri.parse("http://www.samsungapps.com/appquery/appDetail.as?appId=" + packageName)); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (getAvailableIntentSize(intent) > 0) { return intent; } return null; } private static Intent getLeecoAppStoreIntent(final String packageName) { Intent intent = new Intent(); intent.setClassName("com.letv.app.appstore", "com.letv.app.appstore.appmodule.details.DetailsActivity"); intent.setAction("com.letv.app.appstore.appdetailactivity"); intent.putExtra("packageName", packageName); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (getAvailableIntentSize(intent) > 0) { return intent; } return null; } private static int getAvailableIntentSize(final Intent intent) { return Utils.getApp().getPackageManager() .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY) .size(); } }
Blankj/AndroidUtilCode
lib/subutil/src/main/java/com/blankj/subutil/util/AppStoreUtils.java
1,216
// 乐视单独处理跳转乐视市场
line_comment
zh-cn
package com.blankj.subutil.util; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.net.Uri; import android.util.Log; import com.blankj.utilcode.util.AppUtils; import com.blankj.utilcode.util.RomUtils; import com.blankj.utilcode.util.Utils; import java.util.List; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 2019/05/20 * desc : utils about app store * </pre> */ public final class AppStoreUtils { private static final String TAG = "AppStoreUtils"; private static final String GOOGLE_PLAY_APP_STORE_PACKAGE_NAME = "com.android.vending"; /** * 获取跳转到应用商店的 Intent * * @return 跳转到应用商店的 Intent */ public static Intent getAppStoreIntent() { return getAppStoreIntent(Utils.getApp().getPackageName(), false); } /** * 获取跳转到应用商店的 Intent * * @param isIncludeGooglePlayStore 是否包括 Google Play 商店 * @return 跳转到应用商店的 Intent */ public static Intent getAppStoreIntent(boolean isIncludeGooglePlayStore) { return getAppStoreIntent(Utils.getApp().getPackageName(), isIncludeGooglePlayStore); } /** * 获取跳转到应用商店的 Intent * * @param packageName 包名 * @return 跳转到应用商店的 Intent */ public static Intent getAppStoreIntent(final String packageName) { return getAppStoreIntent(packageName, false); } /** * 获取跳转到应用商店的 Intent * <p>优先跳转到手机自带的应用市场</p> * * @param packageName 包名 * @param isIncludeGooglePlayStore 是否包括 Google Play 商店 * @return 跳转到应用商店的 Intent */ public static Intent getAppStoreIntent(final String packageName, boolean isIncludeGooglePlayStore) { if (RomUtils.isSamsung()) {// 三星单独处理跳转三星市场 Intent samsungAppStoreIntent = getSamsungAppStoreIntent(packageName); if (samsungAppStoreIntent != null) return samsungAppStoreIntent; } if (RomUtils.isLeeco()) {// 乐视 <SUF> Intent leecoAppStoreIntent = getLeecoAppStoreIntent(packageName); if (leecoAppStoreIntent != null) return leecoAppStoreIntent; } Uri uri = Uri.parse("market://details?id=" + packageName); Intent intent = new Intent(); intent.setData(uri); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); List<ResolveInfo> resolveInfos = Utils.getApp().getPackageManager() .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); if (resolveInfos == null || resolveInfos.size() == 0) { Log.e(TAG, "No app store!"); return null; } Intent googleIntent = null; for (ResolveInfo resolveInfo : resolveInfos) { String pkgName = resolveInfo.activityInfo.packageName; if (!GOOGLE_PLAY_APP_STORE_PACKAGE_NAME.equals(pkgName)) { if (AppUtils.isAppSystem(pkgName)) { intent.setPackage(pkgName); return intent; } } else { intent.setPackage(GOOGLE_PLAY_APP_STORE_PACKAGE_NAME); googleIntent = intent; } } if (isIncludeGooglePlayStore && googleIntent != null) { return googleIntent; } intent.setPackage(resolveInfos.get(0).activityInfo.packageName); return intent; } private static Intent getSamsungAppStoreIntent(final String packageName) { Intent intent = new Intent(); intent.setClassName("com.sec.android.app.samsungapps", "com.sec.android.app.samsungapps.Main"); intent.setData(Uri.parse("http://www.samsungapps.com/appquery/appDetail.as?appId=" + packageName)); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (getAvailableIntentSize(intent) > 0) { return intent; } return null; } private static Intent getLeecoAppStoreIntent(final String packageName) { Intent intent = new Intent(); intent.setClassName("com.letv.app.appstore", "com.letv.app.appstore.appmodule.details.DetailsActivity"); intent.setAction("com.letv.app.appstore.appdetailactivity"); intent.putExtra("packageName", packageName); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (getAvailableIntentSize(intent) > 0) { return intent; } return null; } private static int getAvailableIntentSize(final Intent intent) { return Utils.getApp().getPackageManager() .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY) .size(); } }
0
1,053
9
1,216
12
1,261
9
1,216
12
1,494
18
false
false
false
false
false
true
691_1
package com.blankj.medium._0067; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 2020/07/07 * desc : * </pre> */ public class Solution { public int uniquePathsWithObstacles(int[][] obstacleGrid) { int m = obstacleGrid.length, n = obstacleGrid[0].length; int[][] dp = new int[m][n]; // 其初始态第 1 列(行)的格子只有从其上(左)边格子走过去这一种走法, // 因此初始化 dp[i][0](dp[0][j])值为 1,且遇到障碍物时后面值都为 0; for (int i = 0; i < m && obstacleGrid[i][0] == 0; i++) { dp[i][0] = 1; } for (int j = 0; j < n && obstacleGrid[0][j] == 0; j++) { dp[0][j] = 1; } for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) { if (obstacleGrid[i][j] == 0) { // 当 (i, j) 有障碍物时,dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; } } } return dp[m - 1][n - 1]; } public static void main(String[] args) { Solution solution = new Solution(); int[][] obstacleGrid = {{0, 0, 0}, {0, 1, 0}, {0, 0, 0}}; System.out.println(solution.uniquePathsWithObstacles(obstacleGrid)); } }
Blankj/awesome-java-leetcode
src/com/blankj/medium/_0067/Solution.java
489
// 其初始态第 1 列(行)的格子只有从其上(左)边格子走过去这一种走法,
line_comment
zh-cn
package com.blankj.medium._0067; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 2020/07/07 * desc : * </pre> */ public class Solution { public int uniquePathsWithObstacles(int[][] obstacleGrid) { int m = obstacleGrid.length, n = obstacleGrid[0].length; int[][] dp = new int[m][n]; // 其初 <SUF> // 因此初始化 dp[i][0](dp[0][j])值为 1,且遇到障碍物时后面值都为 0; for (int i = 0; i < m && obstacleGrid[i][0] == 0; i++) { dp[i][0] = 1; } for (int j = 0; j < n && obstacleGrid[0][j] == 0; j++) { dp[0][j] = 1; } for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) { if (obstacleGrid[i][j] == 0) { // 当 (i, j) 有障碍物时,dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; } } } return dp[m - 1][n - 1]; } public static void main(String[] args) { Solution solution = new Solution(); int[][] obstacleGrid = {{0, 0, 0}, {0, 1, 0}, {0, 0, 0}}; System.out.println(solution.uniquePathsWithObstacles(obstacleGrid)); } }
0
452
33
489
34
498
29
489
34
569
41
false
false
false
false
false
true
19798_6
import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class MD5 { public static String getMD5(String str) throws NoSuchAlgorithmException { try { // 创建加密对象 MessageDigest digest = MessageDigest.getInstance("md5"); // 调用加密对象的方法,加密的动作已经完成 byte[] bs = digest.digest(str.getBytes()); // 接下来,我们要对加密后的结果,进行优化,按照mysql的优化思路走 // mysql的优化思路: // 第一步,将数据全部转换成正数: String hexString = ""; for (byte b : bs) { // 第一步,将数据全部转换成正数: // 解释:为什么采用b&255 /* * b:它本来是一个byte类型的数据(1个字节) 255:是一个int类型的数据(4个字节) * byte类型的数据与int类型的数据进行运算,会自动类型提升为int类型 eg: b: 1001 1100(原始数据) 运算时: b: 0000 0000 * 0000 0000 0000 0000 1001 1100 255: 0000 0000 0000 0000 0000 0000 1111 1111 * 结果:0000 0000 0000 0000 0000 0000 1001 1100 此时的temp是一个int类型的整数 */ int temp = b & 255; // 第二步,将所有的数据转换成16进制的形式 // 注意:转换的时候注意if正数>=0&&<16,那么如果使用Integer.toHexString(),可能会造成缺少位数 // 因此,需要对temp进行判断 if (temp < 16 && temp >= 0) { // 手动补上一个“0” hexString = hexString + "0" + Integer.toHexString(temp); } else { hexString = hexString + Integer.toHexString(temp); } } return hexString; } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } return ""; } }
BlissYang91/note
utils/MD5.java
573
// 解释:为什么采用b&255
line_comment
zh-cn
import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class MD5 { public static String getMD5(String str) throws NoSuchAlgorithmException { try { // 创建加密对象 MessageDigest digest = MessageDigest.getInstance("md5"); // 调用加密对象的方法,加密的动作已经完成 byte[] bs = digest.digest(str.getBytes()); // 接下来,我们要对加密后的结果,进行优化,按照mysql的优化思路走 // mysql的优化思路: // 第一步,将数据全部转换成正数: String hexString = ""; for (byte b : bs) { // 第一步,将数据全部转换成正数: // 解释 <SUF> /* * b:它本来是一个byte类型的数据(1个字节) 255:是一个int类型的数据(4个字节) * byte类型的数据与int类型的数据进行运算,会自动类型提升为int类型 eg: b: 1001 1100(原始数据) 运算时: b: 0000 0000 * 0000 0000 0000 0000 1001 1100 255: 0000 0000 0000 0000 0000 0000 1111 1111 * 结果:0000 0000 0000 0000 0000 0000 1001 1100 此时的temp是一个int类型的整数 */ int temp = b & 255; // 第二步,将所有的数据转换成16进制的形式 // 注意:转换的时候注意if正数>=0&&<16,那么如果使用Integer.toHexString(),可能会造成缺少位数 // 因此,需要对temp进行判断 if (temp < 16 && temp >= 0) { // 手动补上一个“0” hexString = hexString + "0" + Integer.toHexString(temp); } else { hexString = hexString + Integer.toHexString(temp); } } return hexString; } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } return ""; } }
0
553
11
573
11
583
11
573
11
762
21
false
false
false
false
false
true
58365_12
package leetcode.editor.cn; //一场比赛中共有 n 支队伍,按从 0 到 n - 1 编号。 // // 给你一个下标从 0 开始、大小为 n * n 的二维布尔矩阵 grid 。对于满足 0 <= i, j <= n - 1 且 i != j 的所有 i, //j :如果 grid[i][j] == 1,那么 i 队比 j 队 强 ;否则,j 队比 i 队 强 。 // // 在这场比赛中,如果不存在某支强于 a 队的队伍,则认为 a 队将会是 冠军 。 // // 返回这场比赛中将会成为冠军的队伍。 // // // // 示例 1: // // //输入:grid = [[0,1],[0,0]] //输出:0 //解释:比赛中有两支队伍。 //grid[0][1] == 1 表示 0 队比 1 队强。所以 0 队是冠军。 // // // 示例 2: // // //输入:grid = [[0,0,1],[1,0,1],[0,0,0]] //输出:1 //解释:比赛中有三支队伍。 //grid[1][0] == 1 表示 1 队比 0 队强。 //grid[1][2] == 1 表示 1 队比 2 队强。 //所以 1 队是冠军。 // // // // // 提示: // // // n == grid.length // n == grid[i].length // 2 <= n <= 100 // grid[i][j] 的值为 0 或 1 // // 对于所有 i, grid[i][i] 等于 0. // 对于满足 i != j 的所有 i, j ,grid[i][j] != grid[j][i] 均成立 // 生成的输入满足:如果 a 队比 b 队强,b 队比 c 队强,那么 a 队比 c 队强 // // // 👍 8 👎 0 /** * 找到冠军 I * * @author IronSid * @version 1.0 * @since 2024-04-12 01:26:29 */ public class FindChampionISolution { static //leetcode submit region begin(Prohibit modification and deletion) class Solution { public int findChampion(int[][] grid) { int n = grid.length; for (int i = 0; i < n; i++) { int cnt = 0; // 统计比它弱的队的数量 for (int j = 0; j < n; j++) { cnt += grid[i][j]; } if (cnt == n - 1) return i; } return -1; } } //leetcode submit region end(Prohibit modification and deletion) }
BloodSid/LeetCode_Sid
leetcodeEditor/src/main/java/leetcode/editor/cn/FindChampionISolution.java
774
//输出:1
line_comment
zh-cn
package leetcode.editor.cn; //一场比赛中共有 n 支队伍,按从 0 到 n - 1 编号。 // // 给你一个下标从 0 开始、大小为 n * n 的二维布尔矩阵 grid 。对于满足 0 <= i, j <= n - 1 且 i != j 的所有 i, //j :如果 grid[i][j] == 1,那么 i 队比 j 队 强 ;否则,j 队比 i 队 强 。 // // 在这场比赛中,如果不存在某支强于 a 队的队伍,则认为 a 队将会是 冠军 。 // // 返回这场比赛中将会成为冠军的队伍。 // // // // 示例 1: // // //输入:grid = [[0,1],[0,0]] //输出:0 //解释:比赛中有两支队伍。 //grid[0][1] == 1 表示 0 队比 1 队强。所以 0 队是冠军。 // // // 示例 2: // // //输入:grid = [[0,0,1],[1,0,1],[0,0,0]] //输出 <SUF> //解释:比赛中有三支队伍。 //grid[1][0] == 1 表示 1 队比 0 队强。 //grid[1][2] == 1 表示 1 队比 2 队强。 //所以 1 队是冠军。 // // // // // 提示: // // // n == grid.length // n == grid[i].length // 2 <= n <= 100 // grid[i][j] 的值为 0 或 1 // // 对于所有 i, grid[i][i] 等于 0. // 对于满足 i != j 的所有 i, j ,grid[i][j] != grid[j][i] 均成立 // 生成的输入满足:如果 a 队比 b 队强,b 队比 c 队强,那么 a 队比 c 队强 // // // 👍 8 👎 0 /** * 找到冠军 I * * @author IronSid * @version 1.0 * @since 2024-04-12 01:26:29 */ public class FindChampionISolution { static //leetcode submit region begin(Prohibit modification and deletion) class Solution { public int findChampion(int[][] grid) { int n = grid.length; for (int i = 0; i < n; i++) { int cnt = 0; // 统计比它弱的队的数量 for (int j = 0; j < n; j++) { cnt += grid[i][j]; } if (cnt == n - 1) return i; } return -1; } } //leetcode submit region end(Prohibit modification and deletion) }
0
699
4
774
4
711
4
774
4
986
5
false
false
false
false
false
true
19509_6
package com.own.send.server.util; import java.io.UnsupportedEncodingException; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.mail.internet.MimeUtility; /** * @Description: 发送邮件和接收邮件 * @author: Blucezhang */ public class SendMail { public static void sendMail(String email, String title, String content, String iocMailSmtpHost, String iocMailSmtpAuth, String iocSmtp, String iocMailFrom, String iocMailFromUser, String iocMailFromPassWord ) throws AddressException, MessagingException { Properties props = new Properties(); props.put("mail.smtp.host", iocMailSmtpHost); //指定是否需要SMTP验证 props.put("mail.smtp.auth", iocMailSmtpAuth); Session mailSession = Session.getDefaultInstance(props); Transport transport = mailSession.getTransport(iocSmtp); mailSession.setDebug(true);//是否在控制台显示debug信息 Message message = new MimeMessage(mailSession); try { message.setFrom(new InternetAddress(MimeUtility.encodeText(iocMailFrom), "汇金贷")); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); }//发件人 message.setRecipient(Message.RecipientType.TO, new InternetAddress(email));//收件人 message.setSubject(title);//邮件主题 /** 代表正文的bodypart **/ MimeBodyPart text = new MimeBodyPart(); text.setContent(content, "text/html;charset=utf-8"); /** 代表正文所引用的图片的bodypart **/ /* MimeBodyPart image = new MimeBodyPart(); DataHandler dh1 = new DataHandler(new FileDataSource("E:/17.png")); image.setDataHandler(dh1); image.setContentID("17.png");*/ /** 代表附件的bodypart **/ /* MimeBodyPart attach = new MimeBodyPart(); DataHandler dh2 = new DataHandler(new FileDataSource("E:杰克逊.wav")); attach.setDataHandler(dh2); //System.out.println(dh2.getName()); attach.setFileName(MimeUtility.encodeText(dh2.getName())); */ MimeMultipart text_image = new MimeMultipart("related"); text_image.addBodyPart(text); //text_image.addBodyPart(image); MimeBodyPart text_image_body = new MimeBodyPart(); text_image_body.setContent(text_image); /** 封装了所有邮件数据的容器 **/ MimeMultipart multipart = new MimeMultipart("mixed"); multipart.addBodyPart(text_image_body); message.setContent(multipart); message.saveChanges(); transport.connect(iocMailSmtpHost, iocMailFromUser, iocMailFromPassWord); //这个邮箱可随便使用 transport.sendMessage(message, message.getAllRecipients()); transport.close(); } }
Blucezhang/micro-server-own
own-send-server/src/main/java/com/own/send/server/util/SendMail.java
792
//邮件主题
line_comment
zh-cn
package com.own.send.server.util; import java.io.UnsupportedEncodingException; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.mail.internet.MimeUtility; /** * @Description: 发送邮件和接收邮件 * @author: Blucezhang */ public class SendMail { public static void sendMail(String email, String title, String content, String iocMailSmtpHost, String iocMailSmtpAuth, String iocSmtp, String iocMailFrom, String iocMailFromUser, String iocMailFromPassWord ) throws AddressException, MessagingException { Properties props = new Properties(); props.put("mail.smtp.host", iocMailSmtpHost); //指定是否需要SMTP验证 props.put("mail.smtp.auth", iocMailSmtpAuth); Session mailSession = Session.getDefaultInstance(props); Transport transport = mailSession.getTransport(iocSmtp); mailSession.setDebug(true);//是否在控制台显示debug信息 Message message = new MimeMessage(mailSession); try { message.setFrom(new InternetAddress(MimeUtility.encodeText(iocMailFrom), "汇金贷")); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); }//发件人 message.setRecipient(Message.RecipientType.TO, new InternetAddress(email));//收件人 message.setSubject(title);//邮件 <SUF> /** 代表正文的bodypart **/ MimeBodyPart text = new MimeBodyPart(); text.setContent(content, "text/html;charset=utf-8"); /** 代表正文所引用的图片的bodypart **/ /* MimeBodyPart image = new MimeBodyPart(); DataHandler dh1 = new DataHandler(new FileDataSource("E:/17.png")); image.setDataHandler(dh1); image.setContentID("17.png");*/ /** 代表附件的bodypart **/ /* MimeBodyPart attach = new MimeBodyPart(); DataHandler dh2 = new DataHandler(new FileDataSource("E:杰克逊.wav")); attach.setDataHandler(dh2); //System.out.println(dh2.getName()); attach.setFileName(MimeUtility.encodeText(dh2.getName())); */ MimeMultipart text_image = new MimeMultipart("related"); text_image.addBodyPart(text); //text_image.addBodyPart(image); MimeBodyPart text_image_body = new MimeBodyPart(); text_image_body.setContent(text_image); /** 封装了所有邮件数据的容器 **/ MimeMultipart multipart = new MimeMultipart("mixed"); multipart.addBodyPart(text_image_body); message.setContent(multipart); message.saveChanges(); transport.connect(iocMailSmtpHost, iocMailFromUser, iocMailFromPassWord); //这个邮箱可随便使用 transport.sendMessage(message, message.getAllRecipients()); transport.close(); } }
0
684
3
792
3
836
3
792
3
1,012
7
false
false
false
false
false
true
27910_15
package jxau.sms.anping.po; import java.io.Serializable; import java.util.Date; import jxau.sms.chenjiang.po.StuBasicInfo; /** * 医保 * @author anping * 2014-4-13 * TODO */ public class HosInsuranceInfo implements Serializable{ private int hosNo;//编号 private StuBasicInfo student;//学号 private String hosType;//类型 private String hospitalAddress;//住院地址 private Date hospitalDate;//住院日期 private Date leaveDate;//出院日期 private int hosDate;//住院天数 private int localCity;//本市还是转外 private String conditon;//病情 private double cost;//总费用 private Date applyTime;//申请时间 private int accept;//是否受理//数据等于0表示在等待,否则-1不受理1受理 private int collarCard;//是否领卡 0 表示现待受理,1表示已领卡,-1表示未领卡 private Date submitTime;//递交案子时间 private String refuseReason;//未受理原因 private String resultDeal;//处理结果 private String companyRemark;//商业保险备注 private double reimbursementAmount;//医保处已报金额 private int bill;//是否有结算单 private Date getcardTime;//领卡时间 private String jumingRemark;//居民医保备注 private String bankcardID;//银行卡号 private int complete;//除结算单材料是否齐全 private Date insurerTime;//保险公司接案子的时间 private String notinsurerReason;//没有结算的原因 private String baoxiaoRemark;//已报销备注 private String stateRemark;//审核状态备注 private String returnMark;//返回消息备注 private String hosState;//审核状态 public int getHosNo() { return hosNo; } public void setHosNo(int hosNo) { this.hosNo = hosNo; } public StuBasicInfo getStudent() { return student; } public void setStudent(StuBasicInfo student) { this.student = student; } public String getHosType() { return hosType; } public void setHosType(String hosType) { this.hosType = hosType; } public String getHospitalAddress() { return hospitalAddress; } public void setHospitalAddress(String hospitalAddress) { this.hospitalAddress = hospitalAddress; } public Date getHospitalDate() { return hospitalDate; } public void setHospitalDate(Date hospitalDate) { this.hospitalDate = hospitalDate; } public Date getLeaveDate() { return leaveDate; } public void setLeaveDate(Date leaveDate) { this.leaveDate = leaveDate; } public int getHosDate() { return hosDate; } public void setHosDate(int hosDate) { this.hosDate = hosDate; } public int getLocalCity() { return localCity; } public void setLocalCity(int localCity) { this.localCity = localCity; } public String getConditon() { return conditon; } public void setConditon(String conditon) { this.conditon = conditon; } public double getCost() { return cost; } public void setCost(double cost) { this.cost = cost; } public Date getApplyTime() { return applyTime; } public void setApplyTime(Date applyTime) { this.applyTime = applyTime; } public int getAccept() { return accept; } public void setAccept(int accept) { this.accept = accept; } public int getCollarCard() { return collarCard; } public void setCollarCard(int collarCard) { this.collarCard = collarCard; } public Date getSubmitTime() { return submitTime; } public void setSubmitTime(Date submitTime) { this.submitTime = submitTime; } public String getRefuseReason() { return refuseReason; } public void setRefuseReason(String refuseReason) { this.refuseReason = refuseReason; } public String getResultDeal() { return resultDeal; } public void setResultDeal(String resultDeal) { this.resultDeal = resultDeal; } public String getCompanyRemark() { return companyRemark; } public void setCompanyRemark(String companyRemark) { this.companyRemark = companyRemark; } public double getReimbursementAmount() { return reimbursementAmount; } public void setReimbursementAmount(double reimbursementAmount) { this.reimbursementAmount = reimbursementAmount; } public int getBill() { return bill; } public void setBill(int bill) { this.bill = bill; } public Date getGetcardTime() { return getcardTime; } public void setGetcardTime(Date getcardTime) { this.getcardTime = getcardTime; } public String getJumingRemark() { return jumingRemark; } public void setJumingRemark(String jumingRemark) { this.jumingRemark = jumingRemark; } public String getBankcardID() { return bankcardID; } public void setBankcardID(String bankcardID) { this.bankcardID = bankcardID; } public int getComplete() { return complete; } public void setComplete(int complete) { this.complete = complete; } public Date getInsurerTime() { return insurerTime; } public void setInsurerTime(Date insurerTime) { this.insurerTime = insurerTime; } public String getNotinsurerReason() { return notinsurerReason; } public void setNotinsurerReason(String notinsurerReason) { this.notinsurerReason = notinsurerReason; } public String getBaoxiaoRemark() { return baoxiaoRemark; } public void setBaoxiaoRemark(String baoxiaoRemark) { this.baoxiaoRemark = baoxiaoRemark; } public String getStateRemark() { return stateRemark; } public void setStateRemark(String stateRemark) { this.stateRemark = stateRemark; } public String getReturnMark() { return returnMark; } public void setReturnMark(String returnMark) { this.returnMark = returnMark; } public String getHosState() { return hosState; } public void setHosState(String hosState) { this.hosState = hosState; } }
BlueDots/sms
sms/src/jxau/sms/anping/po/HosInsuranceInfo.java
1,819
//是否有结算单
line_comment
zh-cn
package jxau.sms.anping.po; import java.io.Serializable; import java.util.Date; import jxau.sms.chenjiang.po.StuBasicInfo; /** * 医保 * @author anping * 2014-4-13 * TODO */ public class HosInsuranceInfo implements Serializable{ private int hosNo;//编号 private StuBasicInfo student;//学号 private String hosType;//类型 private String hospitalAddress;//住院地址 private Date hospitalDate;//住院日期 private Date leaveDate;//出院日期 private int hosDate;//住院天数 private int localCity;//本市还是转外 private String conditon;//病情 private double cost;//总费用 private Date applyTime;//申请时间 private int accept;//是否受理//数据等于0表示在等待,否则-1不受理1受理 private int collarCard;//是否领卡 0 表示现待受理,1表示已领卡,-1表示未领卡 private Date submitTime;//递交案子时间 private String refuseReason;//未受理原因 private String resultDeal;//处理结果 private String companyRemark;//商业保险备注 private double reimbursementAmount;//医保处已报金额 private int bill;//是否 <SUF> private Date getcardTime;//领卡时间 private String jumingRemark;//居民医保备注 private String bankcardID;//银行卡号 private int complete;//除结算单材料是否齐全 private Date insurerTime;//保险公司接案子的时间 private String notinsurerReason;//没有结算的原因 private String baoxiaoRemark;//已报销备注 private String stateRemark;//审核状态备注 private String returnMark;//返回消息备注 private String hosState;//审核状态 public int getHosNo() { return hosNo; } public void setHosNo(int hosNo) { this.hosNo = hosNo; } public StuBasicInfo getStudent() { return student; } public void setStudent(StuBasicInfo student) { this.student = student; } public String getHosType() { return hosType; } public void setHosType(String hosType) { this.hosType = hosType; } public String getHospitalAddress() { return hospitalAddress; } public void setHospitalAddress(String hospitalAddress) { this.hospitalAddress = hospitalAddress; } public Date getHospitalDate() { return hospitalDate; } public void setHospitalDate(Date hospitalDate) { this.hospitalDate = hospitalDate; } public Date getLeaveDate() { return leaveDate; } public void setLeaveDate(Date leaveDate) { this.leaveDate = leaveDate; } public int getHosDate() { return hosDate; } public void setHosDate(int hosDate) { this.hosDate = hosDate; } public int getLocalCity() { return localCity; } public void setLocalCity(int localCity) { this.localCity = localCity; } public String getConditon() { return conditon; } public void setConditon(String conditon) { this.conditon = conditon; } public double getCost() { return cost; } public void setCost(double cost) { this.cost = cost; } public Date getApplyTime() { return applyTime; } public void setApplyTime(Date applyTime) { this.applyTime = applyTime; } public int getAccept() { return accept; } public void setAccept(int accept) { this.accept = accept; } public int getCollarCard() { return collarCard; } public void setCollarCard(int collarCard) { this.collarCard = collarCard; } public Date getSubmitTime() { return submitTime; } public void setSubmitTime(Date submitTime) { this.submitTime = submitTime; } public String getRefuseReason() { return refuseReason; } public void setRefuseReason(String refuseReason) { this.refuseReason = refuseReason; } public String getResultDeal() { return resultDeal; } public void setResultDeal(String resultDeal) { this.resultDeal = resultDeal; } public String getCompanyRemark() { return companyRemark; } public void setCompanyRemark(String companyRemark) { this.companyRemark = companyRemark; } public double getReimbursementAmount() { return reimbursementAmount; } public void setReimbursementAmount(double reimbursementAmount) { this.reimbursementAmount = reimbursementAmount; } public int getBill() { return bill; } public void setBill(int bill) { this.bill = bill; } public Date getGetcardTime() { return getcardTime; } public void setGetcardTime(Date getcardTime) { this.getcardTime = getcardTime; } public String getJumingRemark() { return jumingRemark; } public void setJumingRemark(String jumingRemark) { this.jumingRemark = jumingRemark; } public String getBankcardID() { return bankcardID; } public void setBankcardID(String bankcardID) { this.bankcardID = bankcardID; } public int getComplete() { return complete; } public void setComplete(int complete) { this.complete = complete; } public Date getInsurerTime() { return insurerTime; } public void setInsurerTime(Date insurerTime) { this.insurerTime = insurerTime; } public String getNotinsurerReason() { return notinsurerReason; } public void setNotinsurerReason(String notinsurerReason) { this.notinsurerReason = notinsurerReason; } public String getBaoxiaoRemark() { return baoxiaoRemark; } public void setBaoxiaoRemark(String baoxiaoRemark) { this.baoxiaoRemark = baoxiaoRemark; } public String getStateRemark() { return stateRemark; } public void setStateRemark(String stateRemark) { this.stateRemark = stateRemark; } public String getReturnMark() { return returnMark; } public void setReturnMark(String returnMark) { this.returnMark = returnMark; } public String getHosState() { return hosState; } public void setHosState(String hosState) { this.hosState = hosState; } }
0
1,404
4
1,819
6
1,731
4
1,819
6
2,100
7
false
false
false
false
false
true
39775_26
package com.ucac.Work.service.impl; import java.util.ArrayList; import java.util.List; import com.ucac.Work.service.WorkService; import com.ucac.dao.EntityDao; import com.ucac.dao.impl.EntityDaoImpl; import com.ucac.exception.DBException; import com.ucac.exception.ErrorException; import com.ucac.po.Applicant; import com.ucac.po.Work; import com.ucac.syw.util.UploadUtils; import com.ucac.vo.QueryResult; import com.ucac.vo.WorkInfo; import com.ucac.vo.WorkResult; import com.ucac.vo.WorkUrl; //chengjiang public class WorkServiceImpl implements WorkService{ private WorkServiceImpl(){} private EntityDao entityDao = EntityDaoImpl.getInstance(); private static class WorkServiceHelp { static final WorkService INSTANCE = new WorkServiceImpl(); } public static WorkService getInstance() { return WorkServiceHelp.INSTANCE; } @Override /** * * 李轶翔 * @todo 比赛结果展示 * @param page 当前为第几页 * @param maxSize 每页的数量 * @param category 类别 1-7 7为全部 * @param sortType 排序方式,0降序,1升序, -1为游客查看界面调用(为降序) * @return * @returntype QueryResult<WorkResult> * QueryResult为自定义容器 * WorkResult为VO,用于指定容器的类型 */ public QueryResult<WorkResult> showWorkResult(int page, int maxSize, int category, int sortType) throws DBException { /** * 该方法调用Entitydao的findAllEntityByCompose方法 */ //用于存放dao方法的返回值 List<WorkResult> list = new ArrayList<WorkResult>(); //作为此service方法的返回值 QueryResult<WorkResult> query = new QueryResult<WorkResult>(); //用于对带有?的sql语句参数赋值 List<Object> parames = new ArrayList<Object>(); //sql语句初始化 String sql = ""; String sqlAll = ""; //判断是否为全部查询 if(category==7){ //排序选择 if(sortType==1){ //后台比赛结果查询界面1 升序 sql = "select a.id applicant_id,a.community_name,a.school,a.category,w.picture_score,w.video_score,w.document_score,w.score,w.ranking from t_applicant a,t_work w where a.id=w.id and w.work_state=1 order by w.ranking asc limit ? , ?;"; }else{ //后台比赛结果查询界面0 降序 //前台比赛结果查询界面-1 降序 sql = "select a.id applicant_id,a.community_name,a.school,a.category,w.picture_score,w.video_score,w.document_score,w.score,w.ranking from t_applicant a,t_work w where a.id=w.id and w.work_state=1 order by w.ranking desc limit ? , ?;"; } //调用dao的方法 try { list = entityDao.findAllEntityByCompose(WorkResult.class,(page-1)*maxSize,maxSize, sql,null); //查询一共有多少条数据 sqlAll ="select count(*) from t_applicant a,t_work w where a.id=w.id and w.work_state=1; "; } catch (DBException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else{ //带有?的赋值 parames.add(category); //sql语句的赋值 if(sortType==1){ //后台比赛结果查询界面1 升序 sql = "select a.id applicant_id,a.community_name,a.school,a.category,w.picture_score,w.video_score,w.document_score,w.score,w.ranking from t_applicant a,t_work w where a.id=w.id and category=? and w.work_state=1 order by w.ranking asc limit ? , ?;"; }else{ //后台比赛结果查询界面0 降序 //前台比赛结果查询界面-1 降序 sql = "select a.id applicant_id,a.community_name,a.school,a.category,w.picture_score,w.video_score,w.document_score,w.score,w.ranking from t_applicant a,t_work w where a.id=w.id and category=? and w.work_state=1 order by w.ranking desc limit ? , ?;"; } list = entityDao.findAllEntityByCompose(WorkResult.class,(page-1)*maxSize,maxSize, sql,parames); //查询一共有多少条数据 sqlAll ="select count(*) from t_applicant a,t_work w where a.id=w.id and category=? and w.work_state=1; "; } int size = entityDao.getAllCount(sqlAll, parames); //对于返回值的赋值处理 query.setResults(list); //数据库中一共有多少条数据 query.setTotalCount(size); return query; } /** * * 李轶翔 * @todo 比赛结果的搜索 * @param schoolName 学校名称 * @param communityName 社团名称 * @return * @throws DBException * @throws ErrorException * @returntype QueryResult<WorkResult> * QueryResult为自定义容器 * WorkResult为VO,用于指定容器的类型 */ @Override public QueryResult<WorkResult> searchWorkResult(String schoolName, String communityName) throws ErrorException, DBException { // TODO Auto-generated method stub //用于存放dao方法的返回值 List<WorkResult> list = new ArrayList<WorkResult>(); //用于对带有?的sql语句参数赋值 List<Object> parames = new ArrayList<Object>(); //返回值初始化 QueryResult<WorkResult> query = new QueryResult<WorkResult>(); // where条件的传入参数 String sql = ""; //搜索结果分页赋值 int page = 1; int maxSize = 500; //判断传入的搜索条件 if(schoolName==""&&communityName==""){ //学校名称和社团名称都为空 sql = "select a.id applicant_id,a.community_name,a.school,a.category,w.picture_score,w.video_score,w.document_score,w.score,w.ranking from t_applicant a,t_work w where a.id=w.id and w.work_state=1 and school like \"%\"?\"%\" and community_name like \"%\"?\"%\" limit ? , ?;"; parames.add("狗屎+狗屎=狗屎"); parames.add("狗屎+狗屎=狗屎"); list = entityDao.findAllEntityByCompose(WorkResult.class,(page-1)*maxSize,maxSize, sql,parames); }else if(schoolName==""&&communityName!=""){ //只根据社团名称查询 sql = "select a.id applicant_id,a.community_name,a.school,a.category,w.picture_score,w.video_score,w.document_score,w.score,w.ranking from t_applicant a,t_work w where a.id=w.id and w.work_state=1 and community_name like \"%\"?\"%\" limit ? , ?;"; parames.add(communityName); list = entityDao.findAllEntityByCompose(WorkResult.class,(page-1)*maxSize,maxSize, sql,parames); }else if(communityName==""&&schoolName!=""){ //只根据学校名称查询 sql = "select a.id applicant_id,a.community_name,a.school,a.category,w.picture_score,w.video_score,w.document_score,w.score,w.ranking from t_applicant a,t_work w where a.id=w.id and w.work_state=1 and school like \"%\"?\"%\" limit ? , ?;"; parames.add(schoolName); list = entityDao.findAllEntityByCompose(WorkResult.class,(page-1)*maxSize,maxSize, sql,parames); } else { //根据学校名称和社团名称查询 sql = "select a.id applicant_id,a.community_name,a.school,a.category,w.picture_score,w.video_score,w.document_score,w.score,w.ranking from t_applicant a,t_work w where a.id=w.id and w.work_state=1 and school like \"%\"?\"%\" and community_name like \"%\"?\"%\" limit ? , ?;"; parames.add(schoolName); parames.add(communityName); list = entityDao.findAllEntityByCompose(WorkResult.class,(page-1)*maxSize,maxSize, sql,parames); } //对于返回值的赋值处理 query.setResults(list); //设置用于分页时一共有多少页 query.setTotalCount((list.size()/maxSize)+1); return query; } @Override public WorkUrl findSpecificWorkById(String id) { WorkUrl wUrl = new WorkUrl(); String path = UploadUtils.getWorksDirectory(); wUrl.setVideoUrl(path+id+"-video.flv"); wUrl.setDocumentUrl(path+id+"-material.doc"); wUrl.setPictureUrl1(path+id+"-pic1.jpg"); wUrl.setPictureUrl2(path+id+"-pic2.jpg"); wUrl.setApplyFormUrl(path+id+"-regForm.doc"); return wUrl; } @Override public int checkWorkContent(List<Applicant> applicants, String assessType) throws ErrorException, DBException { int count = 0; Work work = new Work(); if(assessType.equals("assess")) { for(int i=0;i<applicants.size();i++) { work.setId(applicants.get(i).getId()); work.setWorkState(1); entityDao.update(work); count++; } }else if(assessType.equals("notAssess")){ for(int i=0;i<applicants.size();i++) { work.setId(applicants.get(i).getId()); work.setWorkState(0); entityDao.update(work); count++; } } return count; } @Override public QueryResult<WorkInfo> showWorkInfos(int nowpage,int maxSize) throws DBException { QueryResult<WorkInfo> wResult = new QueryResult<WorkInfo>(); List<WorkInfo> workInfos = null; String sql = "select a.id,community_name,school,a.category,work_state from t_applicant a,t_work b where a.id = b.id limit ?,?"; workInfos = entityDao.findAllEntityByCompose(WorkInfo.class, (nowpage-1)*maxSize, maxSize, sql, null); wResult.setResults(workInfos); wResult.setTotalCount(numofWorkInfo()); return wResult; } @Override public int numofWorkInfo() throws DBException { List<WorkInfo> workInfos = new ArrayList<WorkInfo>(); String sql = "select a.id,community_name,school,a.category,work_state from t_applicant a,t_work b where a.id = b.id limit ?,?"; workInfos = entityDao.findAllEntityByCompose(WorkInfo.class, 0, 10000, sql, null); return workInfos.size(); } }
BlueDots/ucac
uacc/src/com/ucac/Work/service/impl/WorkServiceImpl.java
3,043
//用于对带有?的sql语句参数赋值
line_comment
zh-cn
package com.ucac.Work.service.impl; import java.util.ArrayList; import java.util.List; import com.ucac.Work.service.WorkService; import com.ucac.dao.EntityDao; import com.ucac.dao.impl.EntityDaoImpl; import com.ucac.exception.DBException; import com.ucac.exception.ErrorException; import com.ucac.po.Applicant; import com.ucac.po.Work; import com.ucac.syw.util.UploadUtils; import com.ucac.vo.QueryResult; import com.ucac.vo.WorkInfo; import com.ucac.vo.WorkResult; import com.ucac.vo.WorkUrl; //chengjiang public class WorkServiceImpl implements WorkService{ private WorkServiceImpl(){} private EntityDao entityDao = EntityDaoImpl.getInstance(); private static class WorkServiceHelp { static final WorkService INSTANCE = new WorkServiceImpl(); } public static WorkService getInstance() { return WorkServiceHelp.INSTANCE; } @Override /** * * 李轶翔 * @todo 比赛结果展示 * @param page 当前为第几页 * @param maxSize 每页的数量 * @param category 类别 1-7 7为全部 * @param sortType 排序方式,0降序,1升序, -1为游客查看界面调用(为降序) * @return * @returntype QueryResult<WorkResult> * QueryResult为自定义容器 * WorkResult为VO,用于指定容器的类型 */ public QueryResult<WorkResult> showWorkResult(int page, int maxSize, int category, int sortType) throws DBException { /** * 该方法调用Entitydao的findAllEntityByCompose方法 */ //用于存放dao方法的返回值 List<WorkResult> list = new ArrayList<WorkResult>(); //作为此service方法的返回值 QueryResult<WorkResult> query = new QueryResult<WorkResult>(); //用于对带有?的sql语句参数赋值 List<Object> parames = new ArrayList<Object>(); //sql语句初始化 String sql = ""; String sqlAll = ""; //判断是否为全部查询 if(category==7){ //排序选择 if(sortType==1){ //后台比赛结果查询界面1 升序 sql = "select a.id applicant_id,a.community_name,a.school,a.category,w.picture_score,w.video_score,w.document_score,w.score,w.ranking from t_applicant a,t_work w where a.id=w.id and w.work_state=1 order by w.ranking asc limit ? , ?;"; }else{ //后台比赛结果查询界面0 降序 //前台比赛结果查询界面-1 降序 sql = "select a.id applicant_id,a.community_name,a.school,a.category,w.picture_score,w.video_score,w.document_score,w.score,w.ranking from t_applicant a,t_work w where a.id=w.id and w.work_state=1 order by w.ranking desc limit ? , ?;"; } //调用dao的方法 try { list = entityDao.findAllEntityByCompose(WorkResult.class,(page-1)*maxSize,maxSize, sql,null); //查询一共有多少条数据 sqlAll ="select count(*) from t_applicant a,t_work w where a.id=w.id and w.work_state=1; "; } catch (DBException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else{ //带有?的赋值 parames.add(category); //sql语句的赋值 if(sortType==1){ //后台比赛结果查询界面1 升序 sql = "select a.id applicant_id,a.community_name,a.school,a.category,w.picture_score,w.video_score,w.document_score,w.score,w.ranking from t_applicant a,t_work w where a.id=w.id and category=? and w.work_state=1 order by w.ranking asc limit ? , ?;"; }else{ //后台比赛结果查询界面0 降序 //前台比赛结果查询界面-1 降序 sql = "select a.id applicant_id,a.community_name,a.school,a.category,w.picture_score,w.video_score,w.document_score,w.score,w.ranking from t_applicant a,t_work w where a.id=w.id and category=? and w.work_state=1 order by w.ranking desc limit ? , ?;"; } list = entityDao.findAllEntityByCompose(WorkResult.class,(page-1)*maxSize,maxSize, sql,parames); //查询一共有多少条数据 sqlAll ="select count(*) from t_applicant a,t_work w where a.id=w.id and category=? and w.work_state=1; "; } int size = entityDao.getAllCount(sqlAll, parames); //对于返回值的赋值处理 query.setResults(list); //数据库中一共有多少条数据 query.setTotalCount(size); return query; } /** * * 李轶翔 * @todo 比赛结果的搜索 * @param schoolName 学校名称 * @param communityName 社团名称 * @return * @throws DBException * @throws ErrorException * @returntype QueryResult<WorkResult> * QueryResult为自定义容器 * WorkResult为VO,用于指定容器的类型 */ @Override public QueryResult<WorkResult> searchWorkResult(String schoolName, String communityName) throws ErrorException, DBException { // TODO Auto-generated method stub //用于存放dao方法的返回值 List<WorkResult> list = new ArrayList<WorkResult>(); //用于 <SUF> List<Object> parames = new ArrayList<Object>(); //返回值初始化 QueryResult<WorkResult> query = new QueryResult<WorkResult>(); // where条件的传入参数 String sql = ""; //搜索结果分页赋值 int page = 1; int maxSize = 500; //判断传入的搜索条件 if(schoolName==""&&communityName==""){ //学校名称和社团名称都为空 sql = "select a.id applicant_id,a.community_name,a.school,a.category,w.picture_score,w.video_score,w.document_score,w.score,w.ranking from t_applicant a,t_work w where a.id=w.id and w.work_state=1 and school like \"%\"?\"%\" and community_name like \"%\"?\"%\" limit ? , ?;"; parames.add("狗屎+狗屎=狗屎"); parames.add("狗屎+狗屎=狗屎"); list = entityDao.findAllEntityByCompose(WorkResult.class,(page-1)*maxSize,maxSize, sql,parames); }else if(schoolName==""&&communityName!=""){ //只根据社团名称查询 sql = "select a.id applicant_id,a.community_name,a.school,a.category,w.picture_score,w.video_score,w.document_score,w.score,w.ranking from t_applicant a,t_work w where a.id=w.id and w.work_state=1 and community_name like \"%\"?\"%\" limit ? , ?;"; parames.add(communityName); list = entityDao.findAllEntityByCompose(WorkResult.class,(page-1)*maxSize,maxSize, sql,parames); }else if(communityName==""&&schoolName!=""){ //只根据学校名称查询 sql = "select a.id applicant_id,a.community_name,a.school,a.category,w.picture_score,w.video_score,w.document_score,w.score,w.ranking from t_applicant a,t_work w where a.id=w.id and w.work_state=1 and school like \"%\"?\"%\" limit ? , ?;"; parames.add(schoolName); list = entityDao.findAllEntityByCompose(WorkResult.class,(page-1)*maxSize,maxSize, sql,parames); } else { //根据学校名称和社团名称查询 sql = "select a.id applicant_id,a.community_name,a.school,a.category,w.picture_score,w.video_score,w.document_score,w.score,w.ranking from t_applicant a,t_work w where a.id=w.id and w.work_state=1 and school like \"%\"?\"%\" and community_name like \"%\"?\"%\" limit ? , ?;"; parames.add(schoolName); parames.add(communityName); list = entityDao.findAllEntityByCompose(WorkResult.class,(page-1)*maxSize,maxSize, sql,parames); } //对于返回值的赋值处理 query.setResults(list); //设置用于分页时一共有多少页 query.setTotalCount((list.size()/maxSize)+1); return query; } @Override public WorkUrl findSpecificWorkById(String id) { WorkUrl wUrl = new WorkUrl(); String path = UploadUtils.getWorksDirectory(); wUrl.setVideoUrl(path+id+"-video.flv"); wUrl.setDocumentUrl(path+id+"-material.doc"); wUrl.setPictureUrl1(path+id+"-pic1.jpg"); wUrl.setPictureUrl2(path+id+"-pic2.jpg"); wUrl.setApplyFormUrl(path+id+"-regForm.doc"); return wUrl; } @Override public int checkWorkContent(List<Applicant> applicants, String assessType) throws ErrorException, DBException { int count = 0; Work work = new Work(); if(assessType.equals("assess")) { for(int i=0;i<applicants.size();i++) { work.setId(applicants.get(i).getId()); work.setWorkState(1); entityDao.update(work); count++; } }else if(assessType.equals("notAssess")){ for(int i=0;i<applicants.size();i++) { work.setId(applicants.get(i).getId()); work.setWorkState(0); entityDao.update(work); count++; } } return count; } @Override public QueryResult<WorkInfo> showWorkInfos(int nowpage,int maxSize) throws DBException { QueryResult<WorkInfo> wResult = new QueryResult<WorkInfo>(); List<WorkInfo> workInfos = null; String sql = "select a.id,community_name,school,a.category,work_state from t_applicant a,t_work b where a.id = b.id limit ?,?"; workInfos = entityDao.findAllEntityByCompose(WorkInfo.class, (nowpage-1)*maxSize, maxSize, sql, null); wResult.setResults(workInfos); wResult.setTotalCount(numofWorkInfo()); return wResult; } @Override public int numofWorkInfo() throws DBException { List<WorkInfo> workInfos = new ArrayList<WorkInfo>(); String sql = "select a.id,community_name,school,a.category,work_state from t_applicant a,t_work b where a.id = b.id limit ?,?"; workInfos = entityDao.findAllEntityByCompose(WorkInfo.class, 0, 10000, sql, null); return workInfos.size(); } }
0
2,535
13
3,019
12
3,061
11
3,019
12
4,003
22
false
false
false
false
false
true
7972_40
package com.sp.questionnaire.utils; import com.sp.questionnaire.entity.Paper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Date; import java.util.Properties; /* * Author: Seven * Email : cpwu@foxmail.com * 2018-09-15 Saturday 08:11 */ @Service public class MailUtils { // 发件人的 邮箱 和 密码(替换为自己的邮箱和密码) // PS: 某些邮箱服务器为了增加邮箱本身密码的安全性,给 SMTP 客户端设置了独立密码(有的邮箱称为“授权码”), // 对于开启了独立密码的邮箱, 这里的邮箱密码必需使用这个独立密码(授权码)。 public static String myEmailAccount = "your@qq.com"; public static String myEmailPassword = "pkqifoxowfikdcfg"; // 发件人邮箱的 SMTP 服务器地址, 必须准确, 不同邮件服务器地址不同, 一般(只是一般, 绝非绝对)格式为: smtp.xxx.com // 网易163邮箱的 SMTP 服务器地址为: smtp.163.com // QQ邮箱的为smtp.qq.com public static String myEmailSMTPHost = "smtp.qq.com"; private String senderName = "在线问卷系统"; private String themeActivate = "在线问卷系统账号激活通知"; private String themePaperStart = "问卷生效通知"; private String themePaperEnd = "问卷结束通知"; @Value("${mail.ActivatePrefix}") private String url; @Value("${mail.startPaperPrefix}") private String paperUrl; @Value("${home.url}") private String homeUrl; @Autowired private CommonUtils commonUtils; public void sendActivateMail(String receiveMailAccount, String nickName, String randomCode) throws MessagingException { StringBuffer content = new StringBuffer(); content.append("<b>您已在本系统成功注册账号<br>昵称为:").append(nickName).append("<br><br>") .append("现在<a href='").append(url).append(randomCode).append("'>点击这里激活账号</a>即可开始使用!") .append("</b><br>如非本人操作,请忽略本邮件。"); mailSettings(senderName, themeActivate, receiveMailAccount, nickName, content.toString()); } public void sendPaperStartMail(String receiveMailAccount, String nickName, Paper paper) throws MessagingException { StringBuffer content = new StringBuffer(); content.append("<b>尊敬的").append(nickName).append("<br><br>") .append("您于").append(commonUtils.getFormatDateTime(paper.getCreateTime())) .append("创建的标题为“").append(paper.getTitle()).append("”的问卷,已经可以正式答卷了,快点分享出去吧!<br><br>") .append("现在<a href='").append(paperUrl).append(paper.getId()).append("'>点击这里</a>即可查看问卷详情!</b>") .append("<br><br>使用提示:打开链接后可复制问卷链接或直接分享给他人,亦可<a href='").append(homeUrl).append("'>登录账号</a>查看更多信息。"); mailSettings(senderName, themePaperStart, receiveMailAccount, nickName, content.toString()); } public void sendPaperEndMail(String receiveMailAccount, String nickName, Paper paper) throws MessagingException { StringBuffer content = new StringBuffer(); content.append("<b>尊敬的").append(nickName).append("<br><br>") .append("您于").append(commonUtils.getFormatDateTime(paper.getCreateTime())) .append("创建的标题为“").append(paper.getTitle()).append("”的问卷,已经结束了!<br><br>") .append("现在<a href='").append(homeUrl).append(paper.getId()).append("'>登录账号</a>即可查看问卷数据详情!</b>") .append("<br><br>使用提示:为便于显示请使用电脑查看。"); mailSettings(senderName, themePaperEnd, receiveMailAccount, nickName, content.toString()); } //(session, myEmailAccount, receiveMailAccount, "发件人名字","收件人名字","同志","标题","内容:2943<a href='http://www.baidu.com'>Baidu</a>"); public void mailSettings(String senderName, String theme, String receiveMailAccount, String nickName, String content) throws MessagingException { // 1. 创建参数配置, 用于连接邮件服务器的参数配置 Properties props = new Properties(); // 参数配置 props.setProperty("mail.transport.protocol", "smtp"); // 使用的协议(JavaMail规范要求) props.setProperty("mail.smtp.host", myEmailSMTPHost); // 发件人的邮箱的 SMTP 服务器地址 props.setProperty("mail.smtp.auth", "true"); // 需要请求认证 // PS: 某些邮箱服务器要求 SMTP 连接需要使用 SSL 安全认证 (为了提高安全性, 邮箱支持SSL连接, 也可以自己开启), // 如果无法连接邮件服务器, 仔细查看控制台打印的 log, 如果有有类似 “连接失败, 要求 SSL 安全连接” 等错误, // 打开下面 /* ... */ 之间的注释代码, 开启 SSL 安全连接。 // SMTP 服务器的端口 (非 SSL 连接的端口一般默认为 25, 可以不添加, 如果开启了 SSL 连接, // 需要改为对应邮箱的 SMTP 服务器的端口, 具体可查看对应邮箱服务的帮助, // QQ邮箱的SMTP(SLL)端口为465或587, 其他邮箱自行去查看) final String smtpPort = "465"; props.setProperty("mail.smtp.port", smtpPort); props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.setProperty("mail.smtp.socketFactory.fallback", "false"); props.setProperty("mail.smtp.socketFactory.port", smtpPort); // 2. 根据配置创建会话对象, 用于和邮件服务器交互 Session session = Session.getDefaultInstance(props); session.setDebug(false); // 设置为debug模式, 可以查看详细的发送 log // 3. 创建一封邮件, // Session session, String sendMail,String receiveMail, String sender, String recipients, String theme, String content //session,发件人邮箱,收件人邮箱,发件人名字,收件人名字,邮件标题,邮件内容 MimeMessage message = null; try { message = createMimeMessage(session, myEmailAccount, receiveMailAccount, senderName, nickName, theme, content); } catch (Exception e) { e.printStackTrace(); } //发第二条 /*receiveMailAccount = "youEmail@qq.com"; MimeMessage message2 = createMimeMessage(session, myEmailAccount, receiveMailAccount, "发件人名字","收件人名字","标题","内容:134"); */ // 4. 根据 Session 获取邮件传输对象 Transport transport = session.getTransport(); // 5. 使用 邮箱账号 和 密码 连接邮件服务器, 这里认证的邮箱必须与 message 中的发件人邮箱一致, 否则报错 // // PS_01: 成败的判断关键在此一句, 如果连接服务器失败, 都会在控制台输出相应失败原因的 log, // 仔细查看失败原因, 有些邮箱服务器会返回错误码或查看错误类型的链接, 根据给出的错误 // 类型到对应邮件服务器的帮助网站上查看具体失败原因。 // // PS_02: 连接失败的原因通常为以下几点, 仔细检查代码: // (1) 邮箱没有开启 SMTP 服务; // (2) 邮箱密码错误, 例如某些邮箱开启了独立密码; // (3) 邮箱服务器要求必须要使用 SSL 安全连接; // (4) 请求过于频繁或其他原因, 被邮件服务器拒绝服务; // (5) 如果以上几点都确定无误, 到邮件服务器网站查找帮助。 // // PS_03: 仔细看log, 认真看log, 看懂log, 错误原因都在log已说明。 transport.connect(myEmailAccount, myEmailPassword); // 6. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人 transport.sendMessage(message, message.getAllRecipients()); //transport.sendMessage(message2, message2.getAllRecipients()); // 7. 关闭连接 transport.close(); } /** * 创建一封只包含文本的简单邮件 * * @param session 和服务器交互的会话 * @param senderMailAccount 发件人邮箱 * @param receiverMailAccount 收件人邮箱 * @return * @throws Exception */ //session,发件人邮箱,收件人邮箱,发件人名字,收件人名字,称呼(例:***同学,老师等),邮件标题,邮件内容 public MimeMessage createMimeMessage( Session session, String senderMailAccount, String receiverMailAccount, String senderName, String receiverName, String theme, String content) throws Exception { // 1. 创建一封邮件 MimeMessage message = new MimeMessage(session); // 2. From: 发件人 message.setFrom(new InternetAddress(senderMailAccount, senderName, "UTF-8")); // 3. To: 收件人(可以增加多个收件人、抄送、密送) message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiverMailAccount, receiverName, "UTF-8")); // 4. Subject: 邮件主题 message.setSubject(theme, "UTF-8"); // 5. Content: 邮件正文(可以使用html标签) message.setContent(content, "text/html;charset=UTF-8"); // 6. 设置发件时间 message.setSentDate(new Date()); // 7. 保存设置 message.saveChanges(); return message; } }
BlueDriver/questionnaire_online
src/main/java/com/sp/questionnaire/utils/MailUtils.java
2,511
// 7. 关闭连接
line_comment
zh-cn
package com.sp.questionnaire.utils; import com.sp.questionnaire.entity.Paper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Date; import java.util.Properties; /* * Author: Seven * Email : cpwu@foxmail.com * 2018-09-15 Saturday 08:11 */ @Service public class MailUtils { // 发件人的 邮箱 和 密码(替换为自己的邮箱和密码) // PS: 某些邮箱服务器为了增加邮箱本身密码的安全性,给 SMTP 客户端设置了独立密码(有的邮箱称为“授权码”), // 对于开启了独立密码的邮箱, 这里的邮箱密码必需使用这个独立密码(授权码)。 public static String myEmailAccount = "your@qq.com"; public static String myEmailPassword = "pkqifoxowfikdcfg"; // 发件人邮箱的 SMTP 服务器地址, 必须准确, 不同邮件服务器地址不同, 一般(只是一般, 绝非绝对)格式为: smtp.xxx.com // 网易163邮箱的 SMTP 服务器地址为: smtp.163.com // QQ邮箱的为smtp.qq.com public static String myEmailSMTPHost = "smtp.qq.com"; private String senderName = "在线问卷系统"; private String themeActivate = "在线问卷系统账号激活通知"; private String themePaperStart = "问卷生效通知"; private String themePaperEnd = "问卷结束通知"; @Value("${mail.ActivatePrefix}") private String url; @Value("${mail.startPaperPrefix}") private String paperUrl; @Value("${home.url}") private String homeUrl; @Autowired private CommonUtils commonUtils; public void sendActivateMail(String receiveMailAccount, String nickName, String randomCode) throws MessagingException { StringBuffer content = new StringBuffer(); content.append("<b>您已在本系统成功注册账号<br>昵称为:").append(nickName).append("<br><br>") .append("现在<a href='").append(url).append(randomCode).append("'>点击这里激活账号</a>即可开始使用!") .append("</b><br>如非本人操作,请忽略本邮件。"); mailSettings(senderName, themeActivate, receiveMailAccount, nickName, content.toString()); } public void sendPaperStartMail(String receiveMailAccount, String nickName, Paper paper) throws MessagingException { StringBuffer content = new StringBuffer(); content.append("<b>尊敬的").append(nickName).append("<br><br>") .append("您于").append(commonUtils.getFormatDateTime(paper.getCreateTime())) .append("创建的标题为“").append(paper.getTitle()).append("”的问卷,已经可以正式答卷了,快点分享出去吧!<br><br>") .append("现在<a href='").append(paperUrl).append(paper.getId()).append("'>点击这里</a>即可查看问卷详情!</b>") .append("<br><br>使用提示:打开链接后可复制问卷链接或直接分享给他人,亦可<a href='").append(homeUrl).append("'>登录账号</a>查看更多信息。"); mailSettings(senderName, themePaperStart, receiveMailAccount, nickName, content.toString()); } public void sendPaperEndMail(String receiveMailAccount, String nickName, Paper paper) throws MessagingException { StringBuffer content = new StringBuffer(); content.append("<b>尊敬的").append(nickName).append("<br><br>") .append("您于").append(commonUtils.getFormatDateTime(paper.getCreateTime())) .append("创建的标题为“").append(paper.getTitle()).append("”的问卷,已经结束了!<br><br>") .append("现在<a href='").append(homeUrl).append(paper.getId()).append("'>登录账号</a>即可查看问卷数据详情!</b>") .append("<br><br>使用提示:为便于显示请使用电脑查看。"); mailSettings(senderName, themePaperEnd, receiveMailAccount, nickName, content.toString()); } //(session, myEmailAccount, receiveMailAccount, "发件人名字","收件人名字","同志","标题","内容:2943<a href='http://www.baidu.com'>Baidu</a>"); public void mailSettings(String senderName, String theme, String receiveMailAccount, String nickName, String content) throws MessagingException { // 1. 创建参数配置, 用于连接邮件服务器的参数配置 Properties props = new Properties(); // 参数配置 props.setProperty("mail.transport.protocol", "smtp"); // 使用的协议(JavaMail规范要求) props.setProperty("mail.smtp.host", myEmailSMTPHost); // 发件人的邮箱的 SMTP 服务器地址 props.setProperty("mail.smtp.auth", "true"); // 需要请求认证 // PS: 某些邮箱服务器要求 SMTP 连接需要使用 SSL 安全认证 (为了提高安全性, 邮箱支持SSL连接, 也可以自己开启), // 如果无法连接邮件服务器, 仔细查看控制台打印的 log, 如果有有类似 “连接失败, 要求 SSL 安全连接” 等错误, // 打开下面 /* ... */ 之间的注释代码, 开启 SSL 安全连接。 // SMTP 服务器的端口 (非 SSL 连接的端口一般默认为 25, 可以不添加, 如果开启了 SSL 连接, // 需要改为对应邮箱的 SMTP 服务器的端口, 具体可查看对应邮箱服务的帮助, // QQ邮箱的SMTP(SLL)端口为465或587, 其他邮箱自行去查看) final String smtpPort = "465"; props.setProperty("mail.smtp.port", smtpPort); props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.setProperty("mail.smtp.socketFactory.fallback", "false"); props.setProperty("mail.smtp.socketFactory.port", smtpPort); // 2. 根据配置创建会话对象, 用于和邮件服务器交互 Session session = Session.getDefaultInstance(props); session.setDebug(false); // 设置为debug模式, 可以查看详细的发送 log // 3. 创建一封邮件, // Session session, String sendMail,String receiveMail, String sender, String recipients, String theme, String content //session,发件人邮箱,收件人邮箱,发件人名字,收件人名字,邮件标题,邮件内容 MimeMessage message = null; try { message = createMimeMessage(session, myEmailAccount, receiveMailAccount, senderName, nickName, theme, content); } catch (Exception e) { e.printStackTrace(); } //发第二条 /*receiveMailAccount = "youEmail@qq.com"; MimeMessage message2 = createMimeMessage(session, myEmailAccount, receiveMailAccount, "发件人名字","收件人名字","标题","内容:134"); */ // 4. 根据 Session 获取邮件传输对象 Transport transport = session.getTransport(); // 5. 使用 邮箱账号 和 密码 连接邮件服务器, 这里认证的邮箱必须与 message 中的发件人邮箱一致, 否则报错 // // PS_01: 成败的判断关键在此一句, 如果连接服务器失败, 都会在控制台输出相应失败原因的 log, // 仔细查看失败原因, 有些邮箱服务器会返回错误码或查看错误类型的链接, 根据给出的错误 // 类型到对应邮件服务器的帮助网站上查看具体失败原因。 // // PS_02: 连接失败的原因通常为以下几点, 仔细检查代码: // (1) 邮箱没有开启 SMTP 服务; // (2) 邮箱密码错误, 例如某些邮箱开启了独立密码; // (3) 邮箱服务器要求必须要使用 SSL 安全连接; // (4) 请求过于频繁或其他原因, 被邮件服务器拒绝服务; // (5) 如果以上几点都确定无误, 到邮件服务器网站查找帮助。 // // PS_03: 仔细看log, 认真看log, 看懂log, 错误原因都在log已说明。 transport.connect(myEmailAccount, myEmailPassword); // 6. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人 transport.sendMessage(message, message.getAllRecipients()); //transport.sendMessage(message2, message2.getAllRecipients()); // 7. <SUF> transport.close(); } /** * 创建一封只包含文本的简单邮件 * * @param session 和服务器交互的会话 * @param senderMailAccount 发件人邮箱 * @param receiverMailAccount 收件人邮箱 * @return * @throws Exception */ //session,发件人邮箱,收件人邮箱,发件人名字,收件人名字,称呼(例:***同学,老师等),邮件标题,邮件内容 public MimeMessage createMimeMessage( Session session, String senderMailAccount, String receiverMailAccount, String senderName, String receiverName, String theme, String content) throws Exception { // 1. 创建一封邮件 MimeMessage message = new MimeMessage(session); // 2. From: 发件人 message.setFrom(new InternetAddress(senderMailAccount, senderName, "UTF-8")); // 3. To: 收件人(可以增加多个收件人、抄送、密送) message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiverMailAccount, receiverName, "UTF-8")); // 4. Subject: 邮件主题 message.setSubject(theme, "UTF-8"); // 5. Content: 邮件正文(可以使用html标签) message.setContent(content, "text/html;charset=UTF-8"); // 6. 设置发件时间 message.setSentDate(new Date()); // 7. 保存设置 message.saveChanges(); return message; } }
0
2,360
7
2,511
7
2,518
6
2,511
7
3,671
11
false
false
false
false
false
true
22711_1
package android.study.leer.coolweather.util; import java.util.Random; /** * Created by Leer on 2017/6/26. */ public class DayWords { //注意种子数和生成随机数的区间无关 private static Random mRandom = new Random(); private static String[] mDayWords = new String[]{ "聪明人是快乐的,自以为聪明的才烦恼。帮助别人减轻三分烦恼,自己就会享受七分快乐", "每个人都有潜在的能量,只是很容易被习惯所掩盖,被时间所迷离,被惰性所消磨", "有理想在的地方,地狱就是天堂。有希望在的地方,痛苦也成欢乐", "不要对挫折叹气,姑且把这一切看成是在你成大事之前,必须经受的准备工作", "河流之所以能够到达目的地,是因为它懂得怎样避开障碍", "一个成功的竞争者应该经得起风雨,应该具有抗挫折的能力。在竞争中流泪是弱者,只有在困境中奋起,才能成为强者", "成功沒有捷径,历史上有成就的人,总是敢于行动,也会经常失败。不要让对失败的恐惧,绊住你尝试新事物的脚步", "学会理解,因为只有理解别人,才会被别人理解", "学会忘记,因为只有忘记已经失去的才能立足当前,展望未来", "学会快乐,因为只有开心度过每一天,活得才精彩" }; public static String getDayWord() { int index = mRandom.nextInt(10); if (index < 0) { index = 0; } else if (index > mDayWords.length - 1) { index = mDayWords.length-1; } return mDayWords[index]; } }
BlueLeer/XiaoTianQi
app/src/main/java/android/study/leer/coolweather/util/DayWords.java
526
//注意种子数和生成随机数的区间无关
line_comment
zh-cn
package android.study.leer.coolweather.util; import java.util.Random; /** * Created by Leer on 2017/6/26. */ public class DayWords { //注意 <SUF> private static Random mRandom = new Random(); private static String[] mDayWords = new String[]{ "聪明人是快乐的,自以为聪明的才烦恼。帮助别人减轻三分烦恼,自己就会享受七分快乐", "每个人都有潜在的能量,只是很容易被习惯所掩盖,被时间所迷离,被惰性所消磨", "有理想在的地方,地狱就是天堂。有希望在的地方,痛苦也成欢乐", "不要对挫折叹气,姑且把这一切看成是在你成大事之前,必须经受的准备工作", "河流之所以能够到达目的地,是因为它懂得怎样避开障碍", "一个成功的竞争者应该经得起风雨,应该具有抗挫折的能力。在竞争中流泪是弱者,只有在困境中奋起,才能成为强者", "成功沒有捷径,历史上有成就的人,总是敢于行动,也会经常失败。不要让对失败的恐惧,绊住你尝试新事物的脚步", "学会理解,因为只有理解别人,才会被别人理解", "学会忘记,因为只有忘记已经失去的才能立足当前,展望未来", "学会快乐,因为只有开心度过每一天,活得才精彩" }; public static String getDayWord() { int index = mRandom.nextInt(10); if (index < 0) { index = 0; } else if (index > mDayWords.length - 1) { index = mDayWords.length-1; } return mDayWords[index]; } }
0
384
11
526
14
433
11
526
14
746
19
false
false
false
false
false
true
64482_5
/** * 设置游戏难度及开始新游戏 */ package Controller; import Model.Sudoku; import View.*; public class Game { private static Window window; public static Sudoku sudoku; // 游戏难度,设定一个 0 ~ 1 之间的小数,表示初始数独的完成度 // 程序保证所有数独一定有至少一个正确答案 // 完成度越高游戏越简单,对计算机性能要求越高,建议设置最高 0.45 private static double percent = 0.36; // 创建游戏 private Game() { GameTimer.init(); sudoku = new Sudoku(percent); window = new Window(); } // 新游戏 public static void next() { GameTimer.init(); sudoku.next(); window.next(); } // 游戏答案 public static void solve() { sudoku.solve(0); window.stop(); } // 获取游戏时间 public static String getTime() { String gameTime = GameTimer.getTime(); GameTimer.updateTime(); return gameTime; } public static void main(String[] args) { new Game(); } }
BlueSky-07/Sudoku-Java-Swing-Game
Controller/Game.java
282
// 新游戏
line_comment
zh-cn
/** * 设置游戏难度及开始新游戏 */ package Controller; import Model.Sudoku; import View.*; public class Game { private static Window window; public static Sudoku sudoku; // 游戏难度,设定一个 0 ~ 1 之间的小数,表示初始数独的完成度 // 程序保证所有数独一定有至少一个正确答案 // 完成度越高游戏越简单,对计算机性能要求越高,建议设置最高 0.45 private static double percent = 0.36; // 创建游戏 private Game() { GameTimer.init(); sudoku = new Sudoku(percent); window = new Window(); } // 新游 <SUF> public static void next() { GameTimer.init(); sudoku.next(); window.next(); } // 游戏答案 public static void solve() { sudoku.solve(0); window.stop(); } // 获取游戏时间 public static String getTime() { String gameTime = GameTimer.getTime(); GameTimer.updateTime(); return gameTime; } public static void main(String[] args) { new Game(); } }
0
253
3
282
4
287
3
282
4
414
9
false
false
false
false
false
true
53951_9
/* 输出信息到控制台 System.out.println(...); 在Java中怎么接收键盘的输入? 以下代码目前看不懂,在学习面向对象之后才能够理解 */ public class KeyInput{ public static void main(String[] args){ //创建一个键盘扫描器对象 java.util.Scanner s = new java.util.Scanner(System.in);//s是变量名,可以修改,其他不能修改 //接受用户的输入,从键盘上接收一个int类型 int userInputNum = s.nextInt();//代码执行到这里的时候会暂停下来 //等待用户的输入,用户可以从键盘上输入一个整数,然后回车,回车之后变量userInputnum就有值了, //保存的是用户输入的数字.userInputnum的作用就是接受用户的输入的 System.out.println("您输入的数字是:" + userInputNum); //从键盘上接受字符串 String str = s.next();//同样,程序运行到此处会停下来,等待用户输入字符串 System.out.println("您输入了:" + str); //更加完整的 System.out.print("请输入用户名:"); String name = s.next(); System.out.println("欢迎" + name + "回来!"); } }
Bluuur/MarkdownNotes
Java/JavaSECode/HomeWork/src/KeyInput.java
320
//更加完整的
line_comment
zh-cn
/* 输出信息到控制台 System.out.println(...); 在Java中怎么接收键盘的输入? 以下代码目前看不懂,在学习面向对象之后才能够理解 */ public class KeyInput{ public static void main(String[] args){ //创建一个键盘扫描器对象 java.util.Scanner s = new java.util.Scanner(System.in);//s是变量名,可以修改,其他不能修改 //接受用户的输入,从键盘上接收一个int类型 int userInputNum = s.nextInt();//代码执行到这里的时候会暂停下来 //等待用户的输入,用户可以从键盘上输入一个整数,然后回车,回车之后变量userInputnum就有值了, //保存的是用户输入的数字.userInputnum的作用就是接受用户的输入的 System.out.println("您输入的数字是:" + userInputNum); //从键盘上接受字符串 String str = s.next();//同样,程序运行到此处会停下来,等待用户输入字符串 System.out.println("您输入了:" + str); //更加 <SUF> System.out.print("请输入用户名:"); String name = s.next(); System.out.println("欢迎" + name + "回来!"); } }
0
264
3
320
5
292
3
320
5
489
8
false
false
false
false
false
true
18644_4
package lab11.graphs; import java.util.PriorityQueue; /** * @author Josh Hug */ public class MazeAStarPath extends MazeExplorer { private int s; private int t; private boolean targetFound = false; private Maze maze; public MazeAStarPath(Maze m, int sourceX, int sourceY, int targetX, int targetY) { super(m); maze = m; s = maze.xyTo1D(sourceX, sourceY); t = maze.xyTo1D(targetX, targetY); distTo[s] = 0; edgeTo[s] = s; } /** Estimate of the distance from v to the target. */ private int h(int v) { int size=maze.N(); int v_X = v % size + 1; int v_Y = v / size + 1; int target_X = t % size + 1; int target_Y = t / size + 1; return Math.abs(target_X - v_X) + Math.abs(target_Y - v_Y); } /** Finds vertex estimated to be closest to target. */ private int findMinimumUnmarked() { return -1; /* You do not have to use this method. */ } private class Node implements Comparable<Node>{ public int vertice; public Node parent; public int moves; public int priority; Node(int v,int moves,Node parent){ this.vertice = v; this.moves=moves; this.parent = parent; this.priority = h(v) + moves; } @Override public int compareTo(Node o) { return this.priority - o.priority; } } //标记图中哪些点已经访问过(指曾经以该点为中心向四周探索的点,即从优先队列中出队的点) private boolean book[]=new boolean[marked.length]; /** Performs an A star search from vertex s. */ private void astar(int s) { marked[s] = true; announce(); PriorityQueue<Node>pq=new PriorityQueue<>(); pq.offer(new Node(s, 0, null)); while (!pq.isEmpty() && h(pq.peek().vertice) != 0) { Node v = pq.poll(); book[v.vertice]=true; for (int w : maze.adj(v.vertice)) { //曾经加入过优先队列的点没有访问的意义 if ((v.parent == null || w != v.parent.vertice) && book[w] == false) { book[w] = true; pq.offer(new Node(w, v.moves + 1, v)); marked[w] = true; edgeTo[w] = v.vertice; distTo[w] = distTo[v.vertice] + 1; announce(); } } } } @Override public void solve() { astar(s); } }
BoL0150/Berkeley-cs61b
lab11/lab11/graphs/MazeAStarPath.java
732
//标记图中哪些点已经访问过(指曾经以该点为中心向四周探索的点,即从优先队列中出队的点)
line_comment
zh-cn
package lab11.graphs; import java.util.PriorityQueue; /** * @author Josh Hug */ public class MazeAStarPath extends MazeExplorer { private int s; private int t; private boolean targetFound = false; private Maze maze; public MazeAStarPath(Maze m, int sourceX, int sourceY, int targetX, int targetY) { super(m); maze = m; s = maze.xyTo1D(sourceX, sourceY); t = maze.xyTo1D(targetX, targetY); distTo[s] = 0; edgeTo[s] = s; } /** Estimate of the distance from v to the target. */ private int h(int v) { int size=maze.N(); int v_X = v % size + 1; int v_Y = v / size + 1; int target_X = t % size + 1; int target_Y = t / size + 1; return Math.abs(target_X - v_X) + Math.abs(target_Y - v_Y); } /** Finds vertex estimated to be closest to target. */ private int findMinimumUnmarked() { return -1; /* You do not have to use this method. */ } private class Node implements Comparable<Node>{ public int vertice; public Node parent; public int moves; public int priority; Node(int v,int moves,Node parent){ this.vertice = v; this.moves=moves; this.parent = parent; this.priority = h(v) + moves; } @Override public int compareTo(Node o) { return this.priority - o.priority; } } //标记 <SUF> private boolean book[]=new boolean[marked.length]; /** Performs an A star search from vertex s. */ private void astar(int s) { marked[s] = true; announce(); PriorityQueue<Node>pq=new PriorityQueue<>(); pq.offer(new Node(s, 0, null)); while (!pq.isEmpty() && h(pq.peek().vertice) != 0) { Node v = pq.poll(); book[v.vertice]=true; for (int w : maze.adj(v.vertice)) { //曾经加入过优先队列的点没有访问的意义 if ((v.parent == null || w != v.parent.vertice) && book[w] == false) { book[w] = true; pq.offer(new Node(w, v.moves + 1, v)); marked[w] = true; edgeTo[w] = v.vertice; distTo[w] = distTo[v.vertice] + 1; announce(); } } } } @Override public void solve() { astar(s); } }
0
635
33
732
38
770
32
732
38
876
59
false
false
false
false
false
true
29832_4
package com.wolf.routermanager.bean; import java.io.Serializable; import java.io.UnsupportedEncodingException; /** * 存储已连接的用户信息的javabean * * @author 狼骑兵 * @date 2014-06-25 */ @SuppressWarnings("serial") public class WifiUserBean implements Serializable{ private int id; /** * 机器名,如android-2223643254353 */ private String userName; /** * mac地址 */ private String macAddress; /** * ip地址 */ private String ipAddress; /** * 已经持续使用的时间 */ private String validTime; /** * 接受数据包数 */ private String receiveData; /** * 发送数据包数 */ private String outputData; /** * 信任时的别名 */ private boolean otherName; /** * 厂商 */ private String company; public String getCompany() { return company; } public void setCompany(String company) { this.company = company; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUserName() { if(userName!=null){ try { return new String(userName.getBytes("ISO-8859-1"), "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } return "未知"; } public void setUserName(String userName) { this.userName = userName; } public String getMacAddress() { return macAddress; } public void setMacAddress(String macAddress) { this.macAddress = macAddress; } public String getIpAddress() { return ipAddress; } public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; } public boolean getOtherName() { return otherName; } public void setOtherName(boolean otherName) { this.otherName = otherName; } public String getValidTime() { return validTime; } public void setValidTime(String validTime) { this.validTime = validTime; } public String getReceiveData() { return receiveData; } public void setReceiveData(String receiveData) { this.receiveData = receiveData; } public String getOutputData() { return outputData; } public void setOutputData(String outputData) { this.outputData = outputData; } }
BobsWang/RouterManager
src/com/wolf/routermanager/bean/WifiUserBean.java
693
/** * 已经持续使用的时间 */
block_comment
zh-cn
package com.wolf.routermanager.bean; import java.io.Serializable; import java.io.UnsupportedEncodingException; /** * 存储已连接的用户信息的javabean * * @author 狼骑兵 * @date 2014-06-25 */ @SuppressWarnings("serial") public class WifiUserBean implements Serializable{ private int id; /** * 机器名,如android-2223643254353 */ private String userName; /** * mac地址 */ private String macAddress; /** * ip地址 */ private String ipAddress; /** * 已经持 <SUF>*/ private String validTime; /** * 接受数据包数 */ private String receiveData; /** * 发送数据包数 */ private String outputData; /** * 信任时的别名 */ private boolean otherName; /** * 厂商 */ private String company; public String getCompany() { return company; } public void setCompany(String company) { this.company = company; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUserName() { if(userName!=null){ try { return new String(userName.getBytes("ISO-8859-1"), "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } return "未知"; } public void setUserName(String userName) { this.userName = userName; } public String getMacAddress() { return macAddress; } public void setMacAddress(String macAddress) { this.macAddress = macAddress; } public String getIpAddress() { return ipAddress; } public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; } public boolean getOtherName() { return otherName; } public void setOtherName(boolean otherName) { this.otherName = otherName; } public String getValidTime() { return validTime; } public void setValidTime(String validTime) { this.validTime = validTime; } public String getReceiveData() { return receiveData; } public void setReceiveData(String receiveData) { this.receiveData = receiveData; } public String getOutputData() { return outputData; } public void setOutputData(String outputData) { this.outputData = outputData; } }
0
555
12
693
11
699
12
693
11
821
19
false
false
false
false
false
true
29851_3
package com.lc.nio; 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 NioServe2 { public static void main(String[] args) throws Exception { //创建ServerSocketChannel -> ServerSocket ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); //得到一个Selecor对象 Selector selector = Selector.open(); //绑定一个端口6666, 在服务器端监听 serverSocketChannel.socket().bind(new InetSocketAddress(6666)); //设置为非阻塞 serverSocketChannel.configureBlocking(false); //把 serverSocketChannel 注册到 selector 关心 事件为 OP_ACCEPT pos_1 serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); System.out.println("注册后的selectionkey 数量=" + selector.keys().size()); // 1 //循环等待客户端连接 while (true) { //这里我们等待1秒,如果没有事件发生, 返回 if (selector.select(1000) == 0) { //没有事件发生 System.out.println("服务器等待了1秒,无连接"); continue; } //如果返回的>0, 就获取到相关的 selectionKey集合 //1.如果返回的>0, 表示已经获取到关注的事件 //2. selector.selectedKeys() 返回关注事件的集合 // 通过 selectionKeys 反向获取通道 Set<SelectionKey> selectionKeys = selector.selectedKeys(); System.out.println("selectionKeys 数量 = " + selectionKeys.size()); //遍历 Set<SelectionKey>, 使用迭代器遍历 Iterator<SelectionKey> keyIterator = selectionKeys.iterator(); while (keyIterator.hasNext()) { //获取到SelectionKey SelectionKey key = keyIterator.next(); //根据key 对应的通道发生的事件做相应处理 if (key.isAcceptable()) { //如果是 OP_ACCEPT, 有新的客户端连接 //该该客户端生成一个 SocketChannel SocketChannel socketChannel = serverSocketChannel.accept(); System.out.println("客户端连接成功 生成了一个 socketChannel " + socketChannel.hashCode()); //将 SocketChannel 设置为非阻塞 socketChannel.configureBlocking(false); //将socketChannel 注册到selector, 关注事件为 OP_READ, 同时给socketChannel //关联一个Buffer socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024)); System.out.println("客户端连接后 ,注册的selectionkey 数量=" + selector.keys().size()); //2,3,4.. } if (key.isReadable()) { //发生 OP_READ //通过key 反向获取到对应channel SocketChannel channel = (SocketChannel) key.channel(); //获取到该channel关联的buffer ByteBuffer buffer = (ByteBuffer) key.attachment(); channel.read(buffer); System.out.println("form 客户端 " + new String(buffer.array())); } //手动从集合中移动当前的selectionKey, 防止重复操作 keyIterator.remove(); } } } }
Bocolvchao/springcloudstudy
netty-project/src/main/java/com/lc/nio/NioServe2.java
760
//设置为非阻塞
line_comment
zh-cn
package com.lc.nio; 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 NioServe2 { public static void main(String[] args) throws Exception { //创建ServerSocketChannel -> ServerSocket ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); //得到一个Selecor对象 Selector selector = Selector.open(); //绑定一个端口6666, 在服务器端监听 serverSocketChannel.socket().bind(new InetSocketAddress(6666)); //设置 <SUF> serverSocketChannel.configureBlocking(false); //把 serverSocketChannel 注册到 selector 关心 事件为 OP_ACCEPT pos_1 serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); System.out.println("注册后的selectionkey 数量=" + selector.keys().size()); // 1 //循环等待客户端连接 while (true) { //这里我们等待1秒,如果没有事件发生, 返回 if (selector.select(1000) == 0) { //没有事件发生 System.out.println("服务器等待了1秒,无连接"); continue; } //如果返回的>0, 就获取到相关的 selectionKey集合 //1.如果返回的>0, 表示已经获取到关注的事件 //2. selector.selectedKeys() 返回关注事件的集合 // 通过 selectionKeys 反向获取通道 Set<SelectionKey> selectionKeys = selector.selectedKeys(); System.out.println("selectionKeys 数量 = " + selectionKeys.size()); //遍历 Set<SelectionKey>, 使用迭代器遍历 Iterator<SelectionKey> keyIterator = selectionKeys.iterator(); while (keyIterator.hasNext()) { //获取到SelectionKey SelectionKey key = keyIterator.next(); //根据key 对应的通道发生的事件做相应处理 if (key.isAcceptable()) { //如果是 OP_ACCEPT, 有新的客户端连接 //该该客户端生成一个 SocketChannel SocketChannel socketChannel = serverSocketChannel.accept(); System.out.println("客户端连接成功 生成了一个 socketChannel " + socketChannel.hashCode()); //将 SocketChannel 设置为非阻塞 socketChannel.configureBlocking(false); //将socketChannel 注册到selector, 关注事件为 OP_READ, 同时给socketChannel //关联一个Buffer socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024)); System.out.println("客户端连接后 ,注册的selectionkey 数量=" + selector.keys().size()); //2,3,4.. } if (key.isReadable()) { //发生 OP_READ //通过key 反向获取到对应channel SocketChannel channel = (SocketChannel) key.channel(); //获取到该channel关联的buffer ByteBuffer buffer = (ByteBuffer) key.attachment(); channel.read(buffer); System.out.println("form 客户端 " + new String(buffer.array())); } //手动从集合中移动当前的selectionKey, 防止重复操作 keyIterator.remove(); } } } }
0
718
6
760
5
791
4
760
5
1,081
11
false
false
false
false
false
true
55182_1
//归并排序虽然是nlogn的时间复杂度,但是它需要用到额外的O(n)的空间 //这是它不优于快排的原因 public class Solution { public void sortIntegers2(int[] A) { if(A==null||A.length==0){ return ; } int [] temp=new int[A.length]; mergeSort(A,0,A.length-1,temp); } public void mergeSort(int []nums,int start,int end,int[] temp){ if(start>=end) return; mergeSort(nums,start,(start+end)/2,temp); mergeSort(nums,(start+end)/2 + 1,end,temp); merge(nums,start,end,temp); } public void merge(int []nums,int start,int end,int[]temp){ int mid=(start+end)/2; int left=start; int right=mid+1; int i=left; while(left<=mid&&right<=end){ if(nums[left]<nums[right]){ temp[i++]=nums[left++]; } else{ temp[i++]=nums[right++]; } } while(left<=mid){ temp[i++]=nums[left++]; } while(right<=end){ temp[i++]=nums[right++]; } for(int j=start;j<=end;j++){ nums[j]=temp[j]; } } }
BoogieStreet/jiuzhangsuanfa
mergeSort.java
350
//这是它不优于快排的原因
line_comment
zh-cn
//归并排序虽然是nlogn的时间复杂度,但是它需要用到额外的O(n)的空间 //这是 <SUF> public class Solution { public void sortIntegers2(int[] A) { if(A==null||A.length==0){ return ; } int [] temp=new int[A.length]; mergeSort(A,0,A.length-1,temp); } public void mergeSort(int []nums,int start,int end,int[] temp){ if(start>=end) return; mergeSort(nums,start,(start+end)/2,temp); mergeSort(nums,(start+end)/2 + 1,end,temp); merge(nums,start,end,temp); } public void merge(int []nums,int start,int end,int[]temp){ int mid=(start+end)/2; int left=start; int right=mid+1; int i=left; while(left<=mid&&right<=end){ if(nums[left]<nums[right]){ temp[i++]=nums[left++]; } else{ temp[i++]=nums[right++]; } } while(left<=mid){ temp[i++]=nums[left++]; } while(right<=end){ temp[i++]=nums[right++]; } for(int j=start;j<=end;j++){ nums[j]=temp[j]; } } }
0
287
8
350
10
381
9
350
10
441
20
false
false
false
false
false
true
33101_8
package com.bc.cache.controller; import com.bc.cache.entity.GoodsInventory; import com.bc.cache.request.Request; import com.bc.cache.request.impl.GoodsInventoryCacheRefreshRequest; import com.bc.cache.request.impl.GoodsInventoryDbUpdateRequest; import com.bc.cache.response.Response; import com.bc.cache.service.GoodsInventoryService; import com.bc.cache.service.RequestAsyncProcessService; import io.swagger.annotations.ApiOperation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; /** * 库存控制器 * * @author zhou */ @RestController @RequestMapping("goodsInventory") public class GoodsInventoryController { /** * 日志 */ private static final Logger logger = LoggerFactory.getLogger(GoodsInventoryController.class); @Resource private GoodsInventoryService goodsInventoryService; @Resource private RequestAsyncProcessService requestAsyncProcessService; /** * 更新商品库存 */ @ApiOperation(value = "修改商品库存", notes = "修改商品库存") @PutMapping(value = "/") public Response updateProductInventory(@RequestParam Integer goodsId, @RequestParam Long inventoryCount) { GoodsInventory goodsInventory = new GoodsInventory(goodsId, inventoryCount); logger.info("接收到更新商品库存的请求,商品id: " + goodsInventory.getGoodsId() + ", 商品库存数量: " + goodsInventory.getInventoryCount()); Response response; try { Request request = new GoodsInventoryDbUpdateRequest( goodsInventory, goodsInventoryService); requestAsyncProcessService.process(request); response = new Response(Response.SUCCESS); } catch (Exception e) { e.printStackTrace(); response = new Response(Response.FAILURE); } return response; } /** * 获取商品库存 */ @ApiOperation(value = "获取商品库存", notes = "获取商品库存") @GetMapping(value = "/") public GoodsInventory getGoodsInventory(Integer goodsId) { logger.info("接收到一个商品库存的读请求,商品id: " + goodsId); GoodsInventory goodsInventory; try { Request request = new GoodsInventoryCacheRefreshRequest( goodsId, goodsInventoryService); requestAsyncProcessService.process(request); // 将请求扔给service异步去处理以后,就需要while(true)一会儿,在这里hang住 // 去尝试等待前面有商品库存更新的操作,同时缓存刷新的操作,将最新的数据刷新到缓存中 long startTime = System.currentTimeMillis(); long endTime; long waitTime = 0L; // 等待超过200ms没有从缓存中获取到结果 while (true) { // 一般公司里面,面向用户的读请求控制在200ms就可以了 if (waitTime > 200) { break; } // 尝试去redis中读取一次商品库存的缓存数据 goodsInventory = goodsInventoryService.getGoodsInventoryCache(goodsId); // 如果读取到了结果,那么就返回 if (goodsInventory != null) { logger.info("在200ms内读取到了redis中的库存缓存,商品id: " + goodsInventory.getGoodsId() + ", 商品库存数量: " + goodsInventory.getInventoryCount()); return goodsInventory; } // 如果没有读取到结果,那么等待一段时间 else { Thread.sleep(20); endTime = System.currentTimeMillis(); waitTime = endTime - startTime; } } // 直接尝试从数据库中读取数据 goodsInventory = goodsInventoryService.findGoodsInventory(goodsId); if (goodsInventory != null) { // 将缓存刷新一下 goodsInventoryService.setGoodsInventoryCache(goodsInventory); return goodsInventory; } } catch (Exception e) { e.printStackTrace(); } return new GoodsInventory(goodsId, -1L); } }
BooksCup/cache-aside-pattern
src/main/java/com/bc/cache/controller/GoodsInventoryController.java
945
// 尝试去redis中读取一次商品库存的缓存数据
line_comment
zh-cn
package com.bc.cache.controller; import com.bc.cache.entity.GoodsInventory; import com.bc.cache.request.Request; import com.bc.cache.request.impl.GoodsInventoryCacheRefreshRequest; import com.bc.cache.request.impl.GoodsInventoryDbUpdateRequest; import com.bc.cache.response.Response; import com.bc.cache.service.GoodsInventoryService; import com.bc.cache.service.RequestAsyncProcessService; import io.swagger.annotations.ApiOperation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; /** * 库存控制器 * * @author zhou */ @RestController @RequestMapping("goodsInventory") public class GoodsInventoryController { /** * 日志 */ private static final Logger logger = LoggerFactory.getLogger(GoodsInventoryController.class); @Resource private GoodsInventoryService goodsInventoryService; @Resource private RequestAsyncProcessService requestAsyncProcessService; /** * 更新商品库存 */ @ApiOperation(value = "修改商品库存", notes = "修改商品库存") @PutMapping(value = "/") public Response updateProductInventory(@RequestParam Integer goodsId, @RequestParam Long inventoryCount) { GoodsInventory goodsInventory = new GoodsInventory(goodsId, inventoryCount); logger.info("接收到更新商品库存的请求,商品id: " + goodsInventory.getGoodsId() + ", 商品库存数量: " + goodsInventory.getInventoryCount()); Response response; try { Request request = new GoodsInventoryDbUpdateRequest( goodsInventory, goodsInventoryService); requestAsyncProcessService.process(request); response = new Response(Response.SUCCESS); } catch (Exception e) { e.printStackTrace(); response = new Response(Response.FAILURE); } return response; } /** * 获取商品库存 */ @ApiOperation(value = "获取商品库存", notes = "获取商品库存") @GetMapping(value = "/") public GoodsInventory getGoodsInventory(Integer goodsId) { logger.info("接收到一个商品库存的读请求,商品id: " + goodsId); GoodsInventory goodsInventory; try { Request request = new GoodsInventoryCacheRefreshRequest( goodsId, goodsInventoryService); requestAsyncProcessService.process(request); // 将请求扔给service异步去处理以后,就需要while(true)一会儿,在这里hang住 // 去尝试等待前面有商品库存更新的操作,同时缓存刷新的操作,将最新的数据刷新到缓存中 long startTime = System.currentTimeMillis(); long endTime; long waitTime = 0L; // 等待超过200ms没有从缓存中获取到结果 while (true) { // 一般公司里面,面向用户的读请求控制在200ms就可以了 if (waitTime > 200) { break; } // 尝试 <SUF> goodsInventory = goodsInventoryService.getGoodsInventoryCache(goodsId); // 如果读取到了结果,那么就返回 if (goodsInventory != null) { logger.info("在200ms内读取到了redis中的库存缓存,商品id: " + goodsInventory.getGoodsId() + ", 商品库存数量: " + goodsInventory.getInventoryCount()); return goodsInventory; } // 如果没有读取到结果,那么等待一段时间 else { Thread.sleep(20); endTime = System.currentTimeMillis(); waitTime = endTime - startTime; } } // 直接尝试从数据库中读取数据 goodsInventory = goodsInventoryService.findGoodsInventory(goodsId); if (goodsInventory != null) { // 将缓存刷新一下 goodsInventoryService.setGoodsInventoryCache(goodsInventory); return goodsInventory; } } catch (Exception e) { e.printStackTrace(); } return new GoodsInventory(goodsId, -1L); } }
0
847
16
945
14
981
13
945
14
1,304
27
false
false
false
false
false
true
51000_8
package org.bran.module; import java.awt.Font; import java.sql.ResultSet; import java.sql.SQLException; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import org.bran.db.DBOperation; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.PiePlot; import org.jfree.chart.title.TextTitle; import org.jfree.data.general.DefaultPieDataset; /** * *<p>Title: MyChartPanel.java</p> *<p>Description:图标显示面板 </p> * @author BranSummer * @date 2017年6月4日 */ public class MyChartPanel extends JPanel { //ChartPanel private ChartPanel chartPanel; //列表框 private JList list; String[] elements={"图书类型饼图","读者类型图","借阅条形图"}; /** * constructor */ public MyChartPanel(DBOperation db){ super(); //分割面板 竖直分割 JSplitPane sp=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); this.add(sp); //创建列表框 JScrollPane leftPanel=new JScrollPane(); list=new JList<String>(elements); list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); list.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent arg0) { //TODO } }); leftPanel.setViewportView(list); //创建图表面板 //创建一个默认的饼图 ResultSet rs=null; DefaultPieDataset pdSet=new DefaultPieDataset(); // pdSet.setValue("计算机", 50); // pdSet.setValue("小说", 80); // pdSet.setValue("文学", 30); // pdSet.setValue("艺术", 20); try { rs=db.executeQuery("select booksort,count(booksort) as count from book group by booksort"); while(rs.next()){ pdSet.setValue(rs.getString("booksort"), rs.getInt("count")); } } catch (SQLException e) { e.printStackTrace(); } JFreeChart chart=ChartFactory.createPieChart("demo", pdSet, true,true,false); PiePlot plot=(PiePlot) chart.getPlot(); plot.setLabelFont(new Font("黑体", Font.PLAIN, 20)); TextTitle textTitle = chart.getTitle(); textTitle.setFont(new Font("黑体", Font.PLAIN, 20)); chart.getLegend().setItemFont(new Font("宋体", Font.PLAIN, 12)); chartPanel=new ChartPanel(chart); //加入分割面板 sp.add(leftPanel, JSplitPane.LEFT); sp.add(chartPanel, JSplitPane.RIGHT); } public static void main(String[] args) { JFrame test=new JFrame("test"); test.setSize(600, 400); test.getContentPane().add(new MyChartPanel(new DBOperation())); test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); test.setVisible(true); } }
BranSummer/library-management-sys
src/main/java/org/bran/module/MyChartPanel.java
911
//创建一个默认的饼图
line_comment
zh-cn
package org.bran.module; import java.awt.Font; import java.sql.ResultSet; import java.sql.SQLException; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import org.bran.db.DBOperation; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.PiePlot; import org.jfree.chart.title.TextTitle; import org.jfree.data.general.DefaultPieDataset; /** * *<p>Title: MyChartPanel.java</p> *<p>Description:图标显示面板 </p> * @author BranSummer * @date 2017年6月4日 */ public class MyChartPanel extends JPanel { //ChartPanel private ChartPanel chartPanel; //列表框 private JList list; String[] elements={"图书类型饼图","读者类型图","借阅条形图"}; /** * constructor */ public MyChartPanel(DBOperation db){ super(); //分割面板 竖直分割 JSplitPane sp=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); this.add(sp); //创建列表框 JScrollPane leftPanel=new JScrollPane(); list=new JList<String>(elements); list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); list.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent arg0) { //TODO } }); leftPanel.setViewportView(list); //创建图表面板 //创建 <SUF> ResultSet rs=null; DefaultPieDataset pdSet=new DefaultPieDataset(); // pdSet.setValue("计算机", 50); // pdSet.setValue("小说", 80); // pdSet.setValue("文学", 30); // pdSet.setValue("艺术", 20); try { rs=db.executeQuery("select booksort,count(booksort) as count from book group by booksort"); while(rs.next()){ pdSet.setValue(rs.getString("booksort"), rs.getInt("count")); } } catch (SQLException e) { e.printStackTrace(); } JFreeChart chart=ChartFactory.createPieChart("demo", pdSet, true,true,false); PiePlot plot=(PiePlot) chart.getPlot(); plot.setLabelFont(new Font("黑体", Font.PLAIN, 20)); TextTitle textTitle = chart.getTitle(); textTitle.setFont(new Font("黑体", Font.PLAIN, 20)); chart.getLegend().setItemFont(new Font("宋体", Font.PLAIN, 12)); chartPanel=new ChartPanel(chart); //加入分割面板 sp.add(leftPanel, JSplitPane.LEFT); sp.add(chartPanel, JSplitPane.RIGHT); } public static void main(String[] args) { JFrame test=new JFrame("test"); test.setSize(600, 400); test.getContentPane().add(new MyChartPanel(new DBOperation())); test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); test.setVisible(true); } }
0
714
7
911
7
893
6
911
7
1,106
12
false
false
false
false
false
true
29984_1
package cn.breadnicecat.candycraftce.item.items; import cn.breadnicecat.candycraftce.item.CItems; import cn.breadnicecat.candycraftce.misc.muitlblocks.VectorPortalShape; import cn.breadnicecat.candycraftce.utils.LevelUtils; import cn.breadnicecat.candycraftce.utils.TickUtils; import com.google.common.collect.Lists; import com.mojang.serialization.JsonOps; import net.minecraft.ChatFormatting; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.NbtOps; import net.minecraft.nbt.NbtUtils; import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerLevel; import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; import net.minecraft.util.GsonHelper; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.InteractionResultHolder; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.*; import net.minecraft.world.item.context.UseOnContext; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Arrays; import java.util.List; import java.util.Optional; import static cn.breadnicecat.candycraftce.block.blocks.CaramelPortalBlock.CONFIG; import static net.minecraft.ChatFormatting.RED; import static net.minecraft.ChatFormatting.YELLOW; /** * Created in 2023/7/30 14:12 * Project: candycraftce * * @author <a href="https://github.com/Bread-Nicecat">Bread_NiceCat</a> * <p> * <hr> **/ public class IIDebugItem extends Item { private final String FUN_ORD_KEY = "fun_ord"; private final String USED_TIMES_KEY = "used_times"; private final Component CUR_FUN = Component.literal("当前模式: ").withStyle(ChatFormatting.LIGHT_PURPLE); private final Component SWITCH_FUN = Component.literal("对空气 SHIFT+右键 切换模式").withStyle(YELLOW); public IIDebugItem() { super(new Properties().stacksTo(1).rarity(Rarity.EPIC)); } @Override public @NotNull InteractionResultHolder<ItemStack> use(Level level, Player player, InteractionHand usedHand) { ItemStack item = player.getItemInHand(usedHand); if (level.isClientSide) return InteractionResultHolder.success(item); if (player.isShiftKeyDown() && usedHand == InteractionHand.MAIN_HAND) { //切换模式 CompoundTag tag = item.getOrCreateTag(); int ord = getFunOrd(tag); if (player.isShiftKeyDown()) { if (--ord < 0) { ord = FUNCTIONS.size() - 1; } } else if (++ord >= FUNCTIONS.size()) { ord = 0; } IIIDebugFunction fun = FUNCTIONS.get(ord); player.sendSystemMessage(CUR_FUN.copy().append(fun.getName())); tag.putInt(FUN_ORD_KEY, ord); return InteractionResultHolder.consume(item); } return InteractionResultHolder.fail(item); } @Override public @NotNull InteractionResult useOn(UseOnContext pContext) { Player player = pContext.getPlayer(); if (player == null || !player.isCreative()) { return InteractionResult.FAIL; } Level level = pContext.getLevel(); if (level.isClientSide()) { return InteractionResult.SUCCESS; } BlockPos pos = pContext.getClickedPos(); ItemStack item = pContext.getItemInHand(); CompoundTag tag = item.getOrCreateTag(); int ord = getFunOrd(tag); IIIDebugFunction fun = FUNCTIONS.get(ord); String ord_s = String.valueOf(ord); CompoundTag nbt = tag.getCompound(ord_s); fun.onRightClickOn(level.getBlockState(pos), (ServerLevel) level, pos, pContext.getClickedFace(), player, item, nbt); tag.put(ord_s, nbt); { int used = (tag.contains(USED_TIMES_KEY) ? tag.getInt(USED_TIMES_KEY) : 0) + 1; tag.putInt(USED_TIMES_KEY, used); if (used > 0 && used % 666 == 0) { LevelUtils.spawnItemEntity(level, pos, CItems.RECORD_o.getDefaultInstance().setHoverName(Component.literal("头发").withStyle(RED))); LevelUtils.spawnItemEntity(level, pos, Items.JUKEBOX.getDefaultInstance()); level.playSound(player, pos, SoundEvents.FIREWORK_ROCKET_LARGE_BLAST_FAR, SoundSource.BLOCKS); player.sendSystemMessage(Component.literal("随着你日日夜夜的对Mod进行调试, 你逐渐觉得使用用Debug工具越来越顺手了。 嗯?什么东西掉下来了?").withStyle(YELLOW)); } } return InteractionResult.CONSUME; } public boolean canAttackBlock(@NotNull BlockState pState, @NotNull Level pLevel, @NotNull BlockPos pPos, @NotNull Player pPlayer) { if (!pLevel.isClientSide()) { ItemStack item = pPlayer.getItemInHand(InteractionHand.MAIN_HAND); CompoundTag tag = item.getOrCreateTag(); int ord = getFunOrd(tag); IIIDebugFunction fun = FUNCTIONS.get(ord); String ord_s = String.valueOf(ord); CompoundTag nbt = tag.getCompound(ord_s); fun.onLeftClickOn(pState, (ServerLevel) pLevel, pPos, pPlayer, item, nbt); tag.put(ord_s, nbt); } return false; } public boolean isFoil(@NotNull ItemStack pStack) { return true; } @Override public void appendHoverText(ItemStack stack, @Nullable Level level, List<Component> tooltips, TooltipFlag isAdvanced) { CompoundTag root = stack.getOrCreateTag(); int ord = getFunOrd(root); IIIDebugFunction fun = FUNCTIONS.get(ord); tooltips.add(CUR_FUN.copy().append(fun.getName())); tooltips.add(SWITCH_FUN); CompoundTag nbt = root.getCompound(String.valueOf(ord)); fun.appendExtraHoverText(stack, level, tooltips, isAdvanced, nbt); } @Override public @NotNull Component getName(ItemStack stack) { return super.getName(stack).copy().append("(").append(FUNCTIONS.get(getFunOrd(stack.getOrCreateTag())).getName()).append(")"); } private int getFunOrd(CompoundTag tag) { return tag.getInt(FUN_ORD_KEY) % FUNCTIONS.size(); } //============================================================// private static final IIIDebugFunction DF_RELATIVE = new IIIDebugFunction() { private static final String ZERO = "zero"; private static final Component NAME = Component.literal("坐标测算"); private static final Component SET = Component.literal("左键 调零").withStyle(YELLOW); private static final Component RESET = Component.literal("SHIFT+左键 清除调零").withStyle(YELLOW); private static final Component GET = Component.literal("右键 获取相对坐标").withStyle(YELLOW); @Override public Component getName() { return NAME; } @Override public void onRightClickOn(@NotNull BlockState state, @NotNull ServerLevel level, @NotNull BlockPos pos, Direction clickedFace, @NotNull Player player, ItemStack item, CompoundTag nbt) { int[] zero = nbt.contains(ZERO) ? nbt.getIntArray(ZERO) : new int[]{0, 0, 0}; player.sendSystemMessage(NAME.copy().append(" 坐标: %d,%d,%d".formatted(pos.getX() - zero[0], pos.getY() - zero[1], pos.getZ() - zero[2])).withStyle(YELLOW)); } @Override public void onLeftClickOn(@NotNull BlockState state, @NotNull ServerLevel level, @NotNull BlockPos pos, @NotNull Player player, ItemStack item, CompoundTag nbt) { int[] po = player.isShiftKeyDown() ? new int[]{0, 0, 0} : new int[]{pos.getX(), pos.getY(), pos.getZ()}; nbt.putIntArray(ZERO, po); player.sendSystemMessage(NAME.copy().append(" 调零: %s".formatted(Arrays.toString(po))).withStyle(ChatFormatting.GREEN)); } @Override public void appendExtraHoverText(ItemStack stack, @Nullable Level level, List<Component> tooltips, TooltipFlag isAdvanced, CompoundTag nbt) { tooltips.add(SET); tooltips.add(RESET); tooltips.add(GET); int[] zero = nbt.contains(ZERO) ? nbt.getIntArray(ZERO) : new int[]{0, 0, 0}; tooltips.add(Component.literal("当前零点: " + Arrays.toString(zero)).withStyle(ChatFormatting.GREEN)); } }; private static final IIIDebugFunction DF_DETECT_PORTAL = new IIIDebugFunction() { private static final Component NAME = Component.literal("传送门测试"); private static final Component TEST = Component.literal("右键传送门框架检测").withStyle(YELLOW); @Override public Component getName() { return NAME; } @Override public void onRightClickOn(@NotNull BlockState state, @NotNull ServerLevel level, @NotNull BlockPos pos, Direction clickedFace, @NotNull Player player, ItemStack item, CompoundTag nbt) { long stt = System.nanoTime(); Optional<VectorPortalShape> portal = Optional.empty(); if (CONFIG.isFrame(state)) { portal = VectorPortalShape.findPortalOnFrame(level, pos, CONFIG); } float ttt = (System.nanoTime() - stt) / 1E6F; if (portal.isPresent()) { VectorPortalShape shape = portal.get(); level.playSound(null, pos, SoundEvents.NOTE_BLOCK_PLING.value(), SoundSource.BLOCKS); player.sendSystemMessage(NAME.copy().append(" 框架已找到").withStyle(ChatFormatting.GREEN)); //colorful outputs player.sendSystemMessage(NbtUtils.toPrettyComponent(JsonOps.COMPRESSED.convertTo(NbtOps.INSTANCE, GsonHelper.parse(shape.toString())))); // player.sendSystemMessage(Component.literal(shape.toString())); } else { level.playSound(null, pos, SoundEvents.FIRE_EXTINGUISH, SoundSource.BLOCKS); player.sendSystemMessage(NAME.copy().append(" 未找到正确的传送门框架").withStyle(RED)); } player.sendSystemMessage(NAME.copy().append(" 共耗时: " + ttt + " ms (" + ttt / TickUtils.MS_PER_TICK + " tick)").withStyle(ChatFormatting.GOLD)); } @Override public void appendExtraHoverText(ItemStack stack, @Nullable Level level, List<Component> tooltips, TooltipFlag isAdvanced, CompoundTag nbt) { tooltips.add(TEST); } }; //============================================================// public static final List<IIIDebugFunction> FUNCTIONS = Lists.newArrayList( DF_RELATIVE, DF_DETECT_PORTAL ); public interface IIIDebugFunction { Component getName(); default void onRightClickOn(@NotNull BlockState state, @NotNull ServerLevel level, @NotNull BlockPos pos, Direction clickedFace, @NotNull Player player, ItemStack item, CompoundTag nbt) { } default void onLeftClickOn(@NotNull BlockState state, @NotNull ServerLevel level, @NotNull BlockPos pos, @NotNull Player player, ItemStack item, CompoundTag nbt) { } default void appendExtraHoverText(ItemStack stack, @Nullable Level level, List<Component> tooltips, TooltipFlag isAdvanced, CompoundTag nbt) { } } }
Bread-NiceCat/CandyCraftCE
common/src/main/java/cn/breadnicecat/candycraftce/item/items/IIDebugItem.java
3,075
//切换模式
line_comment
zh-cn
package cn.breadnicecat.candycraftce.item.items; import cn.breadnicecat.candycraftce.item.CItems; import cn.breadnicecat.candycraftce.misc.muitlblocks.VectorPortalShape; import cn.breadnicecat.candycraftce.utils.LevelUtils; import cn.breadnicecat.candycraftce.utils.TickUtils; import com.google.common.collect.Lists; import com.mojang.serialization.JsonOps; import net.minecraft.ChatFormatting; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.NbtOps; import net.minecraft.nbt.NbtUtils; import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerLevel; import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; import net.minecraft.util.GsonHelper; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.InteractionResultHolder; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.*; import net.minecraft.world.item.context.UseOnContext; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Arrays; import java.util.List; import java.util.Optional; import static cn.breadnicecat.candycraftce.block.blocks.CaramelPortalBlock.CONFIG; import static net.minecraft.ChatFormatting.RED; import static net.minecraft.ChatFormatting.YELLOW; /** * Created in 2023/7/30 14:12 * Project: candycraftce * * @author <a href="https://github.com/Bread-Nicecat">Bread_NiceCat</a> * <p> * <hr> **/ public class IIDebugItem extends Item { private final String FUN_ORD_KEY = "fun_ord"; private final String USED_TIMES_KEY = "used_times"; private final Component CUR_FUN = Component.literal("当前模式: ").withStyle(ChatFormatting.LIGHT_PURPLE); private final Component SWITCH_FUN = Component.literal("对空气 SHIFT+右键 切换模式").withStyle(YELLOW); public IIDebugItem() { super(new Properties().stacksTo(1).rarity(Rarity.EPIC)); } @Override public @NotNull InteractionResultHolder<ItemStack> use(Level level, Player player, InteractionHand usedHand) { ItemStack item = player.getItemInHand(usedHand); if (level.isClientSide) return InteractionResultHolder.success(item); if (player.isShiftKeyDown() && usedHand == InteractionHand.MAIN_HAND) { //切换 <SUF> CompoundTag tag = item.getOrCreateTag(); int ord = getFunOrd(tag); if (player.isShiftKeyDown()) { if (--ord < 0) { ord = FUNCTIONS.size() - 1; } } else if (++ord >= FUNCTIONS.size()) { ord = 0; } IIIDebugFunction fun = FUNCTIONS.get(ord); player.sendSystemMessage(CUR_FUN.copy().append(fun.getName())); tag.putInt(FUN_ORD_KEY, ord); return InteractionResultHolder.consume(item); } return InteractionResultHolder.fail(item); } @Override public @NotNull InteractionResult useOn(UseOnContext pContext) { Player player = pContext.getPlayer(); if (player == null || !player.isCreative()) { return InteractionResult.FAIL; } Level level = pContext.getLevel(); if (level.isClientSide()) { return InteractionResult.SUCCESS; } BlockPos pos = pContext.getClickedPos(); ItemStack item = pContext.getItemInHand(); CompoundTag tag = item.getOrCreateTag(); int ord = getFunOrd(tag); IIIDebugFunction fun = FUNCTIONS.get(ord); String ord_s = String.valueOf(ord); CompoundTag nbt = tag.getCompound(ord_s); fun.onRightClickOn(level.getBlockState(pos), (ServerLevel) level, pos, pContext.getClickedFace(), player, item, nbt); tag.put(ord_s, nbt); { int used = (tag.contains(USED_TIMES_KEY) ? tag.getInt(USED_TIMES_KEY) : 0) + 1; tag.putInt(USED_TIMES_KEY, used); if (used > 0 && used % 666 == 0) { LevelUtils.spawnItemEntity(level, pos, CItems.RECORD_o.getDefaultInstance().setHoverName(Component.literal("头发").withStyle(RED))); LevelUtils.spawnItemEntity(level, pos, Items.JUKEBOX.getDefaultInstance()); level.playSound(player, pos, SoundEvents.FIREWORK_ROCKET_LARGE_BLAST_FAR, SoundSource.BLOCKS); player.sendSystemMessage(Component.literal("随着你日日夜夜的对Mod进行调试, 你逐渐觉得使用用Debug工具越来越顺手了。 嗯?什么东西掉下来了?").withStyle(YELLOW)); } } return InteractionResult.CONSUME; } public boolean canAttackBlock(@NotNull BlockState pState, @NotNull Level pLevel, @NotNull BlockPos pPos, @NotNull Player pPlayer) { if (!pLevel.isClientSide()) { ItemStack item = pPlayer.getItemInHand(InteractionHand.MAIN_HAND); CompoundTag tag = item.getOrCreateTag(); int ord = getFunOrd(tag); IIIDebugFunction fun = FUNCTIONS.get(ord); String ord_s = String.valueOf(ord); CompoundTag nbt = tag.getCompound(ord_s); fun.onLeftClickOn(pState, (ServerLevel) pLevel, pPos, pPlayer, item, nbt); tag.put(ord_s, nbt); } return false; } public boolean isFoil(@NotNull ItemStack pStack) { return true; } @Override public void appendHoverText(ItemStack stack, @Nullable Level level, List<Component> tooltips, TooltipFlag isAdvanced) { CompoundTag root = stack.getOrCreateTag(); int ord = getFunOrd(root); IIIDebugFunction fun = FUNCTIONS.get(ord); tooltips.add(CUR_FUN.copy().append(fun.getName())); tooltips.add(SWITCH_FUN); CompoundTag nbt = root.getCompound(String.valueOf(ord)); fun.appendExtraHoverText(stack, level, tooltips, isAdvanced, nbt); } @Override public @NotNull Component getName(ItemStack stack) { return super.getName(stack).copy().append("(").append(FUNCTIONS.get(getFunOrd(stack.getOrCreateTag())).getName()).append(")"); } private int getFunOrd(CompoundTag tag) { return tag.getInt(FUN_ORD_KEY) % FUNCTIONS.size(); } //============================================================// private static final IIIDebugFunction DF_RELATIVE = new IIIDebugFunction() { private static final String ZERO = "zero"; private static final Component NAME = Component.literal("坐标测算"); private static final Component SET = Component.literal("左键 调零").withStyle(YELLOW); private static final Component RESET = Component.literal("SHIFT+左键 清除调零").withStyle(YELLOW); private static final Component GET = Component.literal("右键 获取相对坐标").withStyle(YELLOW); @Override public Component getName() { return NAME; } @Override public void onRightClickOn(@NotNull BlockState state, @NotNull ServerLevel level, @NotNull BlockPos pos, Direction clickedFace, @NotNull Player player, ItemStack item, CompoundTag nbt) { int[] zero = nbt.contains(ZERO) ? nbt.getIntArray(ZERO) : new int[]{0, 0, 0}; player.sendSystemMessage(NAME.copy().append(" 坐标: %d,%d,%d".formatted(pos.getX() - zero[0], pos.getY() - zero[1], pos.getZ() - zero[2])).withStyle(YELLOW)); } @Override public void onLeftClickOn(@NotNull BlockState state, @NotNull ServerLevel level, @NotNull BlockPos pos, @NotNull Player player, ItemStack item, CompoundTag nbt) { int[] po = player.isShiftKeyDown() ? new int[]{0, 0, 0} : new int[]{pos.getX(), pos.getY(), pos.getZ()}; nbt.putIntArray(ZERO, po); player.sendSystemMessage(NAME.copy().append(" 调零: %s".formatted(Arrays.toString(po))).withStyle(ChatFormatting.GREEN)); } @Override public void appendExtraHoverText(ItemStack stack, @Nullable Level level, List<Component> tooltips, TooltipFlag isAdvanced, CompoundTag nbt) { tooltips.add(SET); tooltips.add(RESET); tooltips.add(GET); int[] zero = nbt.contains(ZERO) ? nbt.getIntArray(ZERO) : new int[]{0, 0, 0}; tooltips.add(Component.literal("当前零点: " + Arrays.toString(zero)).withStyle(ChatFormatting.GREEN)); } }; private static final IIIDebugFunction DF_DETECT_PORTAL = new IIIDebugFunction() { private static final Component NAME = Component.literal("传送门测试"); private static final Component TEST = Component.literal("右键传送门框架检测").withStyle(YELLOW); @Override public Component getName() { return NAME; } @Override public void onRightClickOn(@NotNull BlockState state, @NotNull ServerLevel level, @NotNull BlockPos pos, Direction clickedFace, @NotNull Player player, ItemStack item, CompoundTag nbt) { long stt = System.nanoTime(); Optional<VectorPortalShape> portal = Optional.empty(); if (CONFIG.isFrame(state)) { portal = VectorPortalShape.findPortalOnFrame(level, pos, CONFIG); } float ttt = (System.nanoTime() - stt) / 1E6F; if (portal.isPresent()) { VectorPortalShape shape = portal.get(); level.playSound(null, pos, SoundEvents.NOTE_BLOCK_PLING.value(), SoundSource.BLOCKS); player.sendSystemMessage(NAME.copy().append(" 框架已找到").withStyle(ChatFormatting.GREEN)); //colorful outputs player.sendSystemMessage(NbtUtils.toPrettyComponent(JsonOps.COMPRESSED.convertTo(NbtOps.INSTANCE, GsonHelper.parse(shape.toString())))); // player.sendSystemMessage(Component.literal(shape.toString())); } else { level.playSound(null, pos, SoundEvents.FIRE_EXTINGUISH, SoundSource.BLOCKS); player.sendSystemMessage(NAME.copy().append(" 未找到正确的传送门框架").withStyle(RED)); } player.sendSystemMessage(NAME.copy().append(" 共耗时: " + ttt + " ms (" + ttt / TickUtils.MS_PER_TICK + " tick)").withStyle(ChatFormatting.GOLD)); } @Override public void appendExtraHoverText(ItemStack stack, @Nullable Level level, List<Component> tooltips, TooltipFlag isAdvanced, CompoundTag nbt) { tooltips.add(TEST); } }; //============================================================// public static final List<IIIDebugFunction> FUNCTIONS = Lists.newArrayList( DF_RELATIVE, DF_DETECT_PORTAL ); public interface IIIDebugFunction { Component getName(); default void onRightClickOn(@NotNull BlockState state, @NotNull ServerLevel level, @NotNull BlockPos pos, Direction clickedFace, @NotNull Player player, ItemStack item, CompoundTag nbt) { } default void onLeftClickOn(@NotNull BlockState state, @NotNull ServerLevel level, @NotNull BlockPos pos, @NotNull Player player, ItemStack item, CompoundTag nbt) { } default void appendExtraHoverText(ItemStack stack, @Nullable Level level, List<Component> tooltips, TooltipFlag isAdvanced, CompoundTag nbt) { } } }
0
2,586
3
3,074
3
3,101
3
3,075
3
3,888
5
false
false
false
false
false
true
39582_2
package swingDemo; import javax.swing.*; public class JComboxDemo { public static void main(String[] args) { // 创建窗口 JFrame jframe=new JFrame("选择界面"); // 创建面板 JPanel jPanel=new JPanel(); // 创建标签 JLabel jLabel=new JLabel("证件类型"); // 创建下拉列表框 JComboBox com=new JComboBox(); // 在下拉列表框中添加自组 com.addItem("军人证"); com.addItem("身份证"); com.addItem("学生证"); com.addItem("士兵证"); // 将组键添加到面板中 jPanel.add(jLabel); jPanel.add(com); // 将面板添加到窗口中 jframe.add(jPanel); jframe.setSize(300,400); jframe.setVisible(true); jframe.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); jframe.setLocationRelativeTo(null); } }
Breeze1203/study-essay
javaEE/src/swingDemo/JComboxDemo.java
233
// 创建标签
line_comment
zh-cn
package swingDemo; import javax.swing.*; public class JComboxDemo { public static void main(String[] args) { // 创建窗口 JFrame jframe=new JFrame("选择界面"); // 创建面板 JPanel jPanel=new JPanel(); // 创建 <SUF> JLabel jLabel=new JLabel("证件类型"); // 创建下拉列表框 JComboBox com=new JComboBox(); // 在下拉列表框中添加自组 com.addItem("军人证"); com.addItem("身份证"); com.addItem("学生证"); com.addItem("士兵证"); // 将组键添加到面板中 jPanel.add(jLabel); jPanel.add(com); // 将面板添加到窗口中 jframe.add(jPanel); jframe.setSize(300,400); jframe.setVisible(true); jframe.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); jframe.setLocationRelativeTo(null); } }
0
195
3
233
3
236
3
233
3
332
8
false
false
false
false
false
true
13506_10
/*- * << * DBus * == * Copyright (C) 2016 - 2019 Bridata * == * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * >> */ package com.creditease.dbus.heartbeat.util; public class Constants { private Constants() { } public static final String SYS_PROPS_LOG_TYPE = "log.type"; public static final String SYS_PROPS_LOG4J_CONFIG = "log4j.configuration"; public static final String SYS_PROPS_LOG_BASE_PATH = "logs.base.path"; public static final String SYS_PROPS_LOG_HOME = "logs.home"; public static final String CONFIG_DB_KEY = "dbus.conf"; public static final String CONFIG_DB_TYPE_ORA = "oracle"; public static final String CONFIG_DB_TYPE_MYSQL = "mysql"; public static final String CONFIG_DB_TYPE_DB2 = "db2"; public static final String CONFIG_KAFKA_CONTROL_PAYLOAD_SCHEMA_KEY = "schema"; public static final String CONFIG_KAFKA_CONTROL_PAYLOAD_DB_KEY = "DB"; public static final String GLOBAL_CTRL_TOPIC = "global_ctrl_topic"; /** * 安全相关配置 */ public static final String SECURITY_CONFIG_TRUE_VALUE = "kerberos_kafkaACL"; public static final String SECURITY_CONFIG_KEY = "AuthenticationAndAuthorization"; /** * 心跳邮件报警内容 */ public static final String MAIL_HEART_BEAT = "尊敬的先生/女士您好,Dbus心跳监控发现数据线路:{0}发生异常,报警次数:{1},超时次数:{2},请及时处理."; /** * 全量邮件报警内容 */ public static final String MAIL_FULL_PULLER = "尊敬的先生/女士您好,Dbus全量拉取监控发现拉取表:{0}数据时发生异常,报警次数:{1},超时次数:{2},请及时处理."; public static final String MAIL_FULL_PULLER_NEW = "您好:</br>" + "&nbsp;&nbsp;报警类型:{0}</br>" + "&nbsp;&nbsp;数据源:{1}</br>" + "&nbsp;&nbsp;数据库:{2}</br>" + "&nbsp;&nbsp;表:{3}</br>" + "&nbsp;&nbsp;版本:{4}</br>" + "&nbsp;&nbsp;报警时间:{5}</br>" + "&nbsp;&nbsp;报警环境:{6}</br>" + ",请及时处理.</br></br>" + "详细信息:</br>{7}"; public static final String MAIL_FULL_PULLER_NEW_PROJECT = "您好:</br>" + "&nbsp;&nbsp;报警类型:{0}</br>" + "&nbsp;&nbsp;项目名:{1}</br>" + "&nbsp;&nbsp;数据源:{2}</br>" + "&nbsp;&nbsp;数据库:{3}</br>" + "&nbsp;&nbsp;表:{4}</br>" + "&nbsp;&nbsp;版本:{5}</br>" + "&nbsp;&nbsp;报警时间:{6}</br>" + "&nbsp;&nbsp;报警环境:{7}</br>" + ",请及时处理.</br></br>" + "详细信息:</br>{8}"; /** * 新版心跳邮件报警内容 */ // public static final String MAIL_HEART_BEAT_NEW = "尊敬的先生/女士您好:</br>&nbsp;&nbsp;Dbus心跳监控发现数据源:{0}</br>&nbsp;&nbsp;schema:{1}</br>以下表格中table发生超时,请及时处理.</br></br>{2}"; public static final String MAIL_HEART_BEAT_NEW = "您好:</br>" + "&nbsp;&nbsp;报警类型:{0}</br>" + "&nbsp;&nbsp;数据源:{1}</br>" + "&nbsp;&nbsp;数据库:{2}</br>" + "&nbsp;&nbsp;报警时间:{3}</br>" + "&nbsp;&nbsp;报警环境:{4}</br>" + "以下表格中table发生报警,请及时处理.</br></br>{5}</br></br>{6}"; /** * 数据库主备延时报警邮件内容 */ // public static final String MAIL_MASTER_SLAVE_DELAY = "尊敬的先生/女士您好:</br>&nbsp;&nbsp;Dbus心跳监控发现数据源:{0}</br>&nbsp;&nbsp;schema:{1}</br>所在主备数据库延时过长发生超时,请及时处理."; public static final String MAIL_MASTER_SLAVE_DELAY = "您好:</br>" + "&nbsp;&nbsp;报警类型:{0}</br>" + "&nbsp;&nbsp;数据源:{1}</br>" + "&nbsp;&nbsp;数据库:{2}</br>" + "&nbsp;&nbsp;主备延时:{3}</br>" + "&nbsp;&nbsp;主库时间:{4}</br>" + "&nbsp;&nbsp;备库时间:{5}</br>" + "&nbsp;&nbsp;报警环境:{6}</br>" + "&nbsp;&nbsp;报警时间:{7}</br>" + "请及时处理."; public static final String MAIL_SCHEMA_CHANGE = "您好:</br>" + "&nbsp;&nbsp;报警类型:{0}</br>" + "&nbsp;&nbsp;数据源:{1}</br>" + "&nbsp;&nbsp;数据库:{2}</br>" + "&nbsp;&nbsp;表名:{3}</br>" + "&nbsp;&nbsp;报警时间:{4}</br>" + "&nbsp;&nbsp;报警环境:{5}</br>" + "请及时处理.</br></br>{6}"; /** * 新版心跳邮件报警内容 */ // public static final String MAIL_HEART_BEAT_NEW = "尊敬的先生/女士您好:</br>&nbsp;&nbsp;Dbus心跳监控发现数据源:{0}</br>&nbsp;&nbsp;schema:{1}</br>以下表格中table发生超时,请及时处理.</br></br>{2}"; public static final String MAIL_HEART_BEAT_NEW_PROJECT = "您好:</br>" + "&nbsp;&nbsp;报警类型:{0}</br>" + "&nbsp;&nbsp;项目:{1}</br>" + "&nbsp;&nbsp;拓扑:{2}</br>" + "&nbsp;&nbsp;数据源:{3}</br>" + "&nbsp;&nbsp;数据库:{4}</br>" + "&nbsp;&nbsp;报警时间:{5}</br>" + "&nbsp;&nbsp;报警环境:{6}</br>" + "以下表格中table发生报警,请及时处理.</br></br>{7}"; public static final String PROJECT_EXPIRE_TIME = "您好:</br>" + "&nbsp;&nbsp;报警类型:{0}</br>" + "&nbsp;&nbsp;项目名称:{1}</br>" + "&nbsp;&nbsp;有效期至:{2}</br>" + "&nbsp;&nbsp;剩余:{3}天</br>" + "&nbsp;&nbsp;报警环境:{4}</br>" + "{5}. 请及时处理.</br>"; public static final String MAIL_MYSQL_MASTER_STATUS = "您好:</br>" + "&nbsp;&nbsp;报警类型:{0}</br>" + "&nbsp;&nbsp;数据源:{1}</br>" + "&nbsp;&nbsp;报警时间:{2}</br>" + "&nbsp;&nbsp;报警环境:{3}</br>" + "mysql binlog文件号变小,请及时处理."; /** * SINKER心跳邮件报警内容 */ public static final String MAIL_SINKER_HEART_BEAT_NEW = "您好:</br>" + "&nbsp;&nbsp;报警类型:{0}</br>" + "&nbsp;&nbsp;报警时间:{1}</br>" + "&nbsp;&nbsp;报警环境:{2}</br>" + "以下表格中table发生报警,请及时处理.</br></br>{3}"; }
BriData/DBus
dbus-heartbeat/src/main/java/com/creditease/dbus/heartbeat/util/Constants.java
2,034
/** * SINKER心跳邮件报警内容 */
block_comment
zh-cn
/*- * << * DBus * == * Copyright (C) 2016 - 2019 Bridata * == * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * >> */ package com.creditease.dbus.heartbeat.util; public class Constants { private Constants() { } public static final String SYS_PROPS_LOG_TYPE = "log.type"; public static final String SYS_PROPS_LOG4J_CONFIG = "log4j.configuration"; public static final String SYS_PROPS_LOG_BASE_PATH = "logs.base.path"; public static final String SYS_PROPS_LOG_HOME = "logs.home"; public static final String CONFIG_DB_KEY = "dbus.conf"; public static final String CONFIG_DB_TYPE_ORA = "oracle"; public static final String CONFIG_DB_TYPE_MYSQL = "mysql"; public static final String CONFIG_DB_TYPE_DB2 = "db2"; public static final String CONFIG_KAFKA_CONTROL_PAYLOAD_SCHEMA_KEY = "schema"; public static final String CONFIG_KAFKA_CONTROL_PAYLOAD_DB_KEY = "DB"; public static final String GLOBAL_CTRL_TOPIC = "global_ctrl_topic"; /** * 安全相关配置 */ public static final String SECURITY_CONFIG_TRUE_VALUE = "kerberos_kafkaACL"; public static final String SECURITY_CONFIG_KEY = "AuthenticationAndAuthorization"; /** * 心跳邮件报警内容 */ public static final String MAIL_HEART_BEAT = "尊敬的先生/女士您好,Dbus心跳监控发现数据线路:{0}发生异常,报警次数:{1},超时次数:{2},请及时处理."; /** * 全量邮件报警内容 */ public static final String MAIL_FULL_PULLER = "尊敬的先生/女士您好,Dbus全量拉取监控发现拉取表:{0}数据时发生异常,报警次数:{1},超时次数:{2},请及时处理."; public static final String MAIL_FULL_PULLER_NEW = "您好:</br>" + "&nbsp;&nbsp;报警类型:{0}</br>" + "&nbsp;&nbsp;数据源:{1}</br>" + "&nbsp;&nbsp;数据库:{2}</br>" + "&nbsp;&nbsp;表:{3}</br>" + "&nbsp;&nbsp;版本:{4}</br>" + "&nbsp;&nbsp;报警时间:{5}</br>" + "&nbsp;&nbsp;报警环境:{6}</br>" + ",请及时处理.</br></br>" + "详细信息:</br>{7}"; public static final String MAIL_FULL_PULLER_NEW_PROJECT = "您好:</br>" + "&nbsp;&nbsp;报警类型:{0}</br>" + "&nbsp;&nbsp;项目名:{1}</br>" + "&nbsp;&nbsp;数据源:{2}</br>" + "&nbsp;&nbsp;数据库:{3}</br>" + "&nbsp;&nbsp;表:{4}</br>" + "&nbsp;&nbsp;版本:{5}</br>" + "&nbsp;&nbsp;报警时间:{6}</br>" + "&nbsp;&nbsp;报警环境:{7}</br>" + ",请及时处理.</br></br>" + "详细信息:</br>{8}"; /** * 新版心跳邮件报警内容 */ // public static final String MAIL_HEART_BEAT_NEW = "尊敬的先生/女士您好:</br>&nbsp;&nbsp;Dbus心跳监控发现数据源:{0}</br>&nbsp;&nbsp;schema:{1}</br>以下表格中table发生超时,请及时处理.</br></br>{2}"; public static final String MAIL_HEART_BEAT_NEW = "您好:</br>" + "&nbsp;&nbsp;报警类型:{0}</br>" + "&nbsp;&nbsp;数据源:{1}</br>" + "&nbsp;&nbsp;数据库:{2}</br>" + "&nbsp;&nbsp;报警时间:{3}</br>" + "&nbsp;&nbsp;报警环境:{4}</br>" + "以下表格中table发生报警,请及时处理.</br></br>{5}</br></br>{6}"; /** * 数据库主备延时报警邮件内容 */ // public static final String MAIL_MASTER_SLAVE_DELAY = "尊敬的先生/女士您好:</br>&nbsp;&nbsp;Dbus心跳监控发现数据源:{0}</br>&nbsp;&nbsp;schema:{1}</br>所在主备数据库延时过长发生超时,请及时处理."; public static final String MAIL_MASTER_SLAVE_DELAY = "您好:</br>" + "&nbsp;&nbsp;报警类型:{0}</br>" + "&nbsp;&nbsp;数据源:{1}</br>" + "&nbsp;&nbsp;数据库:{2}</br>" + "&nbsp;&nbsp;主备延时:{3}</br>" + "&nbsp;&nbsp;主库时间:{4}</br>" + "&nbsp;&nbsp;备库时间:{5}</br>" + "&nbsp;&nbsp;报警环境:{6}</br>" + "&nbsp;&nbsp;报警时间:{7}</br>" + "请及时处理."; public static final String MAIL_SCHEMA_CHANGE = "您好:</br>" + "&nbsp;&nbsp;报警类型:{0}</br>" + "&nbsp;&nbsp;数据源:{1}</br>" + "&nbsp;&nbsp;数据库:{2}</br>" + "&nbsp;&nbsp;表名:{3}</br>" + "&nbsp;&nbsp;报警时间:{4}</br>" + "&nbsp;&nbsp;报警环境:{5}</br>" + "请及时处理.</br></br>{6}"; /** * 新版心跳邮件报警内容 */ // public static final String MAIL_HEART_BEAT_NEW = "尊敬的先生/女士您好:</br>&nbsp;&nbsp;Dbus心跳监控发现数据源:{0}</br>&nbsp;&nbsp;schema:{1}</br>以下表格中table发生超时,请及时处理.</br></br>{2}"; public static final String MAIL_HEART_BEAT_NEW_PROJECT = "您好:</br>" + "&nbsp;&nbsp;报警类型:{0}</br>" + "&nbsp;&nbsp;项目:{1}</br>" + "&nbsp;&nbsp;拓扑:{2}</br>" + "&nbsp;&nbsp;数据源:{3}</br>" + "&nbsp;&nbsp;数据库:{4}</br>" + "&nbsp;&nbsp;报警时间:{5}</br>" + "&nbsp;&nbsp;报警环境:{6}</br>" + "以下表格中table发生报警,请及时处理.</br></br>{7}"; public static final String PROJECT_EXPIRE_TIME = "您好:</br>" + "&nbsp;&nbsp;报警类型:{0}</br>" + "&nbsp;&nbsp;项目名称:{1}</br>" + "&nbsp;&nbsp;有效期至:{2}</br>" + "&nbsp;&nbsp;剩余:{3}天</br>" + "&nbsp;&nbsp;报警环境:{4}</br>" + "{5}. 请及时处理.</br>"; public static final String MAIL_MYSQL_MASTER_STATUS = "您好:</br>" + "&nbsp;&nbsp;报警类型:{0}</br>" + "&nbsp;&nbsp;数据源:{1}</br>" + "&nbsp;&nbsp;报警时间:{2}</br>" + "&nbsp;&nbsp;报警环境:{3}</br>" + "mysql binlog文件号变小,请及时处理."; /** * SIN <SUF>*/ public static final String MAIL_SINKER_HEART_BEAT_NEW = "您好:</br>" + "&nbsp;&nbsp;报警类型:{0}</br>" + "&nbsp;&nbsp;报警时间:{1}</br>" + "&nbsp;&nbsp;报警环境:{2}</br>" + "以下表格中table发生报警,请及时处理.</br></br>{3}"; }
0
1,796
13
2,034
14
1,999
14
2,034
14
2,764
27
false
false
false
false
false
true
62246_14
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * problem: 一条线路上有 n 个公交车站,假设在到达第 i 个站点之前,车上总共有 x 个乘客,过了该站点后车上总共有 y 个乘客, * 司机会把 y-x 这个数字,即乘客数量变化值 d_i 记录下来,公交车有固定的载客量 g,若有一份司机的开车日志,车上乘客数量的可能情况有多少种 * * 输入:第一行有两个数字 n 和 g,分别表示站点数量及当前撤了的最大载客数量(1 <= n,g <= 1000) * 第二行共 n 个数字,由空格分开,经过第 i 个公交车站后车上乘客的变化数量 d_i (-1000 <= d_i <= 1000) * 输入数据保证从总站出发时乘客数量大于等于 0 * 输出:输出一个数字,即司机从总站出发时,车上乘客数量的可能性个数。 * * 样例输入一: * 4 10 * 1 2 3 4 * 样例输出一: * 1 * * 样例输入二: * 4 5 * 2 -1 2 1 * 样例输出二: * 2 */ class Main{ private int station = 0; // station 个公交车站 private int carSize = 0; // 固定载客量 private int cases = 0; // 可能的情况数 private int[] d_i; // 乘客数量变化值 private int[] person; public static void main(String [] args){ Main m = new Main(); try { m.init(); // m.printPersonRange(); m.findMinCase(); } catch (Exception e) { e.printStackTrace(); } System.out.println(m.cases); } private void init() throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); /*========= read first line to get variable n and g =========*/ String firstLine = br.readLine(); String[] first = firstLine.split(" "); station = Integer.valueOf(first[0]); carSize = Integer.valueOf(first[1]); cases = carSize+1; // the maximum cases is carSize + 1 ( from 0 to carSize) /*===========================================================*/ /*========= read second line to get variable d_i and initialize person =========*/ d_i = new int[station]; person = new int[(station+1)*2]; // odd means lower, even means upper String secondLine = br.readLine(); String[] second = secondLine.split(" "); for (int i = 0; i < station; i++) { d_i[i] = Integer.valueOf(second[i]); person[i*2] = 0; person[i*2+1] = carSize; } person[station*2] = 0; person[station*2+1] = carSize; /*========================================================*/ int tmp = 0, tmpMax = carSize, tmpMin = 0; tmp = carSize - d_i[0]; // 算出 P0 的最小最大值 person[0*2] = getMax(0, -diff[0]); person[0*2+1] = getMin(carSize, carSize - diff[0]); for(int gap = 1; gap < station; gap++) { for(int i = gap; i < station + 1; i++) { tmpMax = person[(i-gap)*2+1] + personChanged(i-gap, i); tmpMin = person[(i-gap)*2] + personChanged(i-gap, i); if( i < station) { // 最后一个计算的时候没有额外的约束条件了 tmp = carSize - d_i[i]; tmpMax = getMin(tmp, tmpMax); // 取较小的(即取交集) } if( tmpMax < tmpMin ) { // 若上限小于下限,对应的不等式不成立,说明不存在这种情况 cases = 0; return; } tmpMax = getMin(tmpMax, carSize); person[i*2+1] = getMin(person[i*2+1], tmpMax); tmpMin = getMax(0, tmpMin); person[i*2] = getMax(person[i*2], tmpMin); } } } /** * 求出所有站点可能情况的交集 */ private void findMinCase() { int tmpCase; for(int i = 0; i <= station; i++) { tmpCase = person[i*2+1]-person[i*2]+1; if(cases > tmpCase) { cases = tmpCase; } } } /** * 打印出每个站点的可能的人数范围 * @apiNote 第一个站点为总站 */ private void printPersonRange() { for (int i = 0; i < station+1; i++) { System.out.print( person[i*2] + "-" + person[i*2+1]+" "); } System.out.println(); } /** * 计算从 from (include) 到 to (not include) 站点的人数变化 * @apiNote 第一站的序号为 0 * 例如: * 经过四个站点的人数变化为: d_i = { 1, 2, 3, 4, -2, 3 } * personChanged(1, 5) 计算的值为 2 + 3 + 4 + (-2),返回值为 7 */ private int personChanged(int from, int to) { int p = 0; for(int i = from; i < to; i++) p += d_i[i]; return p; } /** * 取 a,b中的最大值 * @param a * @param b * @return */ private int getMax(int a, int b) { return (a > b) ? a : b; } /** * 取 a,b中的最小值 * @param a * @param b * @return */ private int getMin(int a, int b) { return (a<b) ? a: b; } }
BriFuture/blog-code-example
18-06to09/quesion_buscases/Main.java
1,584
// 取较小的(即取交集)
line_comment
zh-cn
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * problem: 一条线路上有 n 个公交车站,假设在到达第 i 个站点之前,车上总共有 x 个乘客,过了该站点后车上总共有 y 个乘客, * 司机会把 y-x 这个数字,即乘客数量变化值 d_i 记录下来,公交车有固定的载客量 g,若有一份司机的开车日志,车上乘客数量的可能情况有多少种 * * 输入:第一行有两个数字 n 和 g,分别表示站点数量及当前撤了的最大载客数量(1 <= n,g <= 1000) * 第二行共 n 个数字,由空格分开,经过第 i 个公交车站后车上乘客的变化数量 d_i (-1000 <= d_i <= 1000) * 输入数据保证从总站出发时乘客数量大于等于 0 * 输出:输出一个数字,即司机从总站出发时,车上乘客数量的可能性个数。 * * 样例输入一: * 4 10 * 1 2 3 4 * 样例输出一: * 1 * * 样例输入二: * 4 5 * 2 -1 2 1 * 样例输出二: * 2 */ class Main{ private int station = 0; // station 个公交车站 private int carSize = 0; // 固定载客量 private int cases = 0; // 可能的情况数 private int[] d_i; // 乘客数量变化值 private int[] person; public static void main(String [] args){ Main m = new Main(); try { m.init(); // m.printPersonRange(); m.findMinCase(); } catch (Exception e) { e.printStackTrace(); } System.out.println(m.cases); } private void init() throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); /*========= read first line to get variable n and g =========*/ String firstLine = br.readLine(); String[] first = firstLine.split(" "); station = Integer.valueOf(first[0]); carSize = Integer.valueOf(first[1]); cases = carSize+1; // the maximum cases is carSize + 1 ( from 0 to carSize) /*===========================================================*/ /*========= read second line to get variable d_i and initialize person =========*/ d_i = new int[station]; person = new int[(station+1)*2]; // odd means lower, even means upper String secondLine = br.readLine(); String[] second = secondLine.split(" "); for (int i = 0; i < station; i++) { d_i[i] = Integer.valueOf(second[i]); person[i*2] = 0; person[i*2+1] = carSize; } person[station*2] = 0; person[station*2+1] = carSize; /*========================================================*/ int tmp = 0, tmpMax = carSize, tmpMin = 0; tmp = carSize - d_i[0]; // 算出 P0 的最小最大值 person[0*2] = getMax(0, -diff[0]); person[0*2+1] = getMin(carSize, carSize - diff[0]); for(int gap = 1; gap < station; gap++) { for(int i = gap; i < station + 1; i++) { tmpMax = person[(i-gap)*2+1] + personChanged(i-gap, i); tmpMin = person[(i-gap)*2] + personChanged(i-gap, i); if( i < station) { // 最后一个计算的时候没有额外的约束条件了 tmp = carSize - d_i[i]; tmpMax = getMin(tmp, tmpMax); // 取较 <SUF> } if( tmpMax < tmpMin ) { // 若上限小于下限,对应的不等式不成立,说明不存在这种情况 cases = 0; return; } tmpMax = getMin(tmpMax, carSize); person[i*2+1] = getMin(person[i*2+1], tmpMax); tmpMin = getMax(0, tmpMin); person[i*2] = getMax(person[i*2], tmpMin); } } } /** * 求出所有站点可能情况的交集 */ private void findMinCase() { int tmpCase; for(int i = 0; i <= station; i++) { tmpCase = person[i*2+1]-person[i*2]+1; if(cases > tmpCase) { cases = tmpCase; } } } /** * 打印出每个站点的可能的人数范围 * @apiNote 第一个站点为总站 */ private void printPersonRange() { for (int i = 0; i < station+1; i++) { System.out.print( person[i*2] + "-" + person[i*2+1]+" "); } System.out.println(); } /** * 计算从 from (include) 到 to (not include) 站点的人数变化 * @apiNote 第一站的序号为 0 * 例如: * 经过四个站点的人数变化为: d_i = { 1, 2, 3, 4, -2, 3 } * personChanged(1, 5) 计算的值为 2 + 3 + 4 + (-2),返回值为 7 */ private int personChanged(int from, int to) { int p = 0; for(int i = from; i < to; i++) p += d_i[i]; return p; } /** * 取 a,b中的最大值 * @param a * @param b * @return */ private int getMax(int a, int b) { return (a > b) ? a : b; } /** * 取 a,b中的最小值 * @param a * @param b * @return */ private int getMin(int a, int b) { return (a<b) ? a: b; } }
0
1,457
11
1,584
12
1,607
10
1,584
12
1,932
16
false
false
false
false
false
true
27922_10
package com.zx.security.core.social.qq.api; import lombok.Data; import lombok.experimental.Accessors; /** * author:ZhengXing * datetime:2018-01-02 21:20 * qq用户信息 * 从文档中获取的字段 * * 使用IDEA的多行编辑,..几秒搞定.舒服 */ @Data @Accessors(chain = true) public class QQUserInfo { private String openId;//用户id 不是返回来的,需要自行添加 private Integer is_lost;//..文档中没有 private Integer ret;//返回码 private String msg;//如果ret<0,会有相应的错误信息提示,返回数据全部用UTF-8编码。 private String nickname;//用户在QQ空间的昵称。 private String figureurl;//大小为30×30像素的QQ空间头像URL。 private String figureurl_1;//大小为50×50像素的QQ空间头像URL。 private String figureurl_2;//大小为100×100像素的QQ空间头像URL。 private String figureurl_qq_1;//大小为40×40像素的QQ头像URL。 private String figureurl_qq_2;//大小为100×100像素的QQ头像URL。需要注意,不是所有的用户都拥有QQ的100x100的头像,但40x40像素则是一定会有。 private String gender;//性别。 如果获取不到则默认返回"男" private String is_yellow_vip;//标识用户是否为黄钻用户(0:不是;1:是)。 private String vip;//标识用户是否为黄钻用户(0:不是;1:是) private String yellow_vip_level;//黄钻等级 private String level;//黄钻等级 private String is_yellow_year_vip;//标识是否为年费黄钻用户(0:不是; 1:是) private String province;//省份 private String city;//城市 private String year;//出生年分 }
BrightStarry/zx-security
zx-security-core/src/main/java/com/zx/security/core/social/qq/api/QQUserInfo.java
497
//大小为100×100像素的QQ头像URL。需要注意,不是所有的用户都拥有QQ的100x100的头像,但40x40像素则是一定会有。
line_comment
zh-cn
package com.zx.security.core.social.qq.api; import lombok.Data; import lombok.experimental.Accessors; /** * author:ZhengXing * datetime:2018-01-02 21:20 * qq用户信息 * 从文档中获取的字段 * * 使用IDEA的多行编辑,..几秒搞定.舒服 */ @Data @Accessors(chain = true) public class QQUserInfo { private String openId;//用户id 不是返回来的,需要自行添加 private Integer is_lost;//..文档中没有 private Integer ret;//返回码 private String msg;//如果ret<0,会有相应的错误信息提示,返回数据全部用UTF-8编码。 private String nickname;//用户在QQ空间的昵称。 private String figureurl;//大小为30×30像素的QQ空间头像URL。 private String figureurl_1;//大小为50×50像素的QQ空间头像URL。 private String figureurl_2;//大小为100×100像素的QQ空间头像URL。 private String figureurl_qq_1;//大小为40×40像素的QQ头像URL。 private String figureurl_qq_2;//大小 <SUF> private String gender;//性别。 如果获取不到则默认返回"男" private String is_yellow_vip;//标识用户是否为黄钻用户(0:不是;1:是)。 private String vip;//标识用户是否为黄钻用户(0:不是;1:是) private String yellow_vip_level;//黄钻等级 private String level;//黄钻等级 private String is_yellow_year_vip;//标识是否为年费黄钻用户(0:不是; 1:是) private String province;//省份 private String city;//城市 private String year;//出生年分 }
0
453
48
497
54
473
47
497
54
665
68
false
false
false
false
false
true
16223_11
package com.makiyo.pojo; import java.io.Serializable; import java.util.Date; import lombok.Data; /** * tb_checkin * @author */ @Data public class TbCheckin implements Serializable { /** * 主键 */ private Integer id; /** * 用户ID */ private Integer userId; /** * 签到地址 */ private String address; /** * 国家 */ private String country; /** * 省份 */ private String province; /** * 城市 */ private String city; /** * 区划 */ private String district; /** * 考勤结果 */ private Byte status; /** * 风险等级 */ private Integer risk; /** * 签到日期 */ private String date; /** * 签到时间 */ private Date createTime; private static final long serialVersionUID = 1L; }
Bruce6230/epidemic-prevention-system
src/main/java/com/makiyo/pojo/TbCheckin.java
230
/** * 签到时间 */
block_comment
zh-cn
package com.makiyo.pojo; import java.io.Serializable; import java.util.Date; import lombok.Data; /** * tb_checkin * @author */ @Data public class TbCheckin implements Serializable { /** * 主键 */ private Integer id; /** * 用户ID */ private Integer userId; /** * 签到地址 */ private String address; /** * 国家 */ private String country; /** * 省份 */ private String province; /** * 城市 */ private String city; /** * 区划 */ private String district; /** * 考勤结果 */ private Byte status; /** * 风险等级 */ private Integer risk; /** * 签到日期 */ private String date; /** * 签到时 <SUF>*/ private Date createTime; private static final long serialVersionUID = 1L; }
0
229
11
230
9
261
10
230
9
327
14
false
false
false
false
false
true
32717_8
package model; /** * 新政政区域划分 * Created by liyonglin on 2017/10/26. */ public class Area { public static final String CHINA = "中国"; public static final String XINJIANG = "新疆维吾尔自治区"; public static final String WLMQ = "乌鲁木齐市"; public static final String KLMY = "克拉玛依市"; public static final String TLF = "吐鲁番市"; public static final String HM = "哈密市"; public static final String HKS = "阿克苏地区"; public static final String KS = "喀什地区"; public static final String HT = "和田地区"; public static final String CJ = "昌吉回族自治州"; public static final String BETLMG = "博尔塔拉蒙古自治州"; public static final String BYGL = "巴音郭楞蒙古自治州"; public static final String KMLSKEKM = "克孜勒苏柯尔克孜自治州"; public static final String YL = "伊犁哈萨克自治州"; /** * 地区综合命名 */ public String formatted_address = ""; /** * 国家 */ public String country = ""; /** * 省份,自治区,直辖市 */ public String province = ""; /** * 市 */ public String city = ""; /** * 区,县 */ public String district = ""; public String town = "";//乡镇 /** * 街道 */ public String street = "";//街道名(行政区划中的街道层级) public String street_number = "";//街道门牌号 @Override public String toString() { return "Area{" + "formatted_address='" + formatted_address + '\'' + ", country='" + country + '\'' + ", province='" + province + '\'' + ", city='" + city + '\'' + ", district='" + district + '\'' + ", town='" + town + '\'' + ", street='" + street + '\'' + ", street_number='" + street_number + '\'' + '}'; } }
BruceLii/BaiduPOI
src/main/java/model/Area.java
538
//街道门牌号
line_comment
zh-cn
package model; /** * 新政政区域划分 * Created by liyonglin on 2017/10/26. */ public class Area { public static final String CHINA = "中国"; public static final String XINJIANG = "新疆维吾尔自治区"; public static final String WLMQ = "乌鲁木齐市"; public static final String KLMY = "克拉玛依市"; public static final String TLF = "吐鲁番市"; public static final String HM = "哈密市"; public static final String HKS = "阿克苏地区"; public static final String KS = "喀什地区"; public static final String HT = "和田地区"; public static final String CJ = "昌吉回族自治州"; public static final String BETLMG = "博尔塔拉蒙古自治州"; public static final String BYGL = "巴音郭楞蒙古自治州"; public static final String KMLSKEKM = "克孜勒苏柯尔克孜自治州"; public static final String YL = "伊犁哈萨克自治州"; /** * 地区综合命名 */ public String formatted_address = ""; /** * 国家 */ public String country = ""; /** * 省份,自治区,直辖市 */ public String province = ""; /** * 市 */ public String city = ""; /** * 区,县 */ public String district = ""; public String town = "";//乡镇 /** * 街道 */ public String street = "";//街道名(行政区划中的街道层级) public String street_number = "";//街道 <SUF> @Override public String toString() { return "Area{" + "formatted_address='" + formatted_address + '\'' + ", country='" + country + '\'' + ", province='" + province + '\'' + ", city='" + city + '\'' + ", district='" + district + '\'' + ", town='" + town + '\'' + ", street='" + street + '\'' + ", street_number='" + street_number + '\'' + '}'; } }
0
477
5
538
7
530
5
538
7
680
8
false
false
false
false
false
true
45126_0
package com.fc.demo1._static; // 诉讼接口 public interface Lawsuit { // 提起诉讼 void submit(); // 法庭辩护 void defend(); }
BufferC/dev01
04-DesignPattern-01-Proxy/src/main/java/com/fc/demo1/_static/Lawsuit.java
53
// 诉讼接口
line_comment
zh-cn
package com.fc.demo1._static; // 诉讼 <SUF> public interface Lawsuit { // 提起诉讼 void submit(); // 法庭辩护 void defend(); }
0
40
4
53
6
49
5
53
6
68
10
false
false
false
false
false
true
53349_3
package sms; import com.aliyuncs.DefaultAcsClient; import com.aliyuncs.IAcsClient; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.exceptions.ServerException; import com.aliyuncs.profile.DefaultProfile; import com.aliyuncs.profile.IClientProfile; import com.aliyuncs.sms.model.v20160927.SingleSendSmsRequest; import com.aliyuncs.sms.model.v20160927.SingleSendSmsResponse; public class SingleSendSms { public static void smsSend(String phone,String modeid,String param) { try { IClientProfile profile = DefaultProfile.getProfile("cn-qingdao", "LTAIiL3nLmMzSuIR", "Q8oLL7wTjmhK4y3z4erWSJbAiP1FLx"); DefaultProfile.addEndpoint("cn-qingdao", "cn-qingdao", "Sms", "sms.aliyuncs.com"); IAcsClient client = new DefaultAcsClient(profile); SingleSendSmsRequest request = new SingleSendSmsRequest(); request.setSignName("冒险家");//控制台创建的签名名称 request.setTemplateCode(modeid);//控制台创建的模板CODE //request.setParamString("{\"name\":\"123\"}");//短信模板中的变量;数字需要转换为字符串;个人用户每个变量长度必须小于15个字符。" request.setParamString(param); request.setRecNum(phone);//接收号码 SingleSendSmsResponse httpResponse = client.getAcsResponse(request); } catch (ServerException e) { e.printStackTrace(); } catch (ClientException e) { e.printStackTrace(); } } public static void main(String args[]) { smsSend("18703996021","SMS_56665270","{\"code\":\"123\",\"product\":\"亲子淘\"}"); } }
BugGirls/camprecruit
src/sms/SingleSendSms.java
472
//接收号码
line_comment
zh-cn
package sms; import com.aliyuncs.DefaultAcsClient; import com.aliyuncs.IAcsClient; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.exceptions.ServerException; import com.aliyuncs.profile.DefaultProfile; import com.aliyuncs.profile.IClientProfile; import com.aliyuncs.sms.model.v20160927.SingleSendSmsRequest; import com.aliyuncs.sms.model.v20160927.SingleSendSmsResponse; public class SingleSendSms { public static void smsSend(String phone,String modeid,String param) { try { IClientProfile profile = DefaultProfile.getProfile("cn-qingdao", "LTAIiL3nLmMzSuIR", "Q8oLL7wTjmhK4y3z4erWSJbAiP1FLx"); DefaultProfile.addEndpoint("cn-qingdao", "cn-qingdao", "Sms", "sms.aliyuncs.com"); IAcsClient client = new DefaultAcsClient(profile); SingleSendSmsRequest request = new SingleSendSmsRequest(); request.setSignName("冒险家");//控制台创建的签名名称 request.setTemplateCode(modeid);//控制台创建的模板CODE //request.setParamString("{\"name\":\"123\"}");//短信模板中的变量;数字需要转换为字符串;个人用户每个变量长度必须小于15个字符。" request.setParamString(param); request.setRecNum(phone);//接收 <SUF> SingleSendSmsResponse httpResponse = client.getAcsResponse(request); } catch (ServerException e) { e.printStackTrace(); } catch (ClientException e) { e.printStackTrace(); } } public static void main(String args[]) { smsSend("18703996021","SMS_56665270","{\"code\":\"123\",\"product\":\"亲子淘\"}"); } }
0
441
3
472
4
510
3
472
4
617
5
false
false
false
false
false
true
65379_25
package org.bukkit.event.entity; import org.bukkit.Chunk; import org.bukkit.entity.LivingEntity; import org.bukkit.event.world.ChunkLoadEvent; import org.jetbrains.annotations.NotNull; /** * 当一个生物体在世界中出生时触发该事件. * <p> * 如果该事件被取消了,那么这个生物将不会出生. */ public class CreatureSpawnEvent extends EntitySpawnEvent { private final SpawnReason spawnReason; public CreatureSpawnEvent(@NotNull final LivingEntity spawnee, @NotNull final SpawnReason spawnReason) { super(spawnee); this.spawnReason = spawnReason; } @NotNull @Override public LivingEntity getEntity() { return (LivingEntity) entity; } /** * 返回生物出生的原因 * <p> * 原文: * Gets the reason for why the creature is being spawned. * * @return 出生原因 */ @NotNull public SpawnReason getSpawnReason() { return spawnReason; } /** * 生成原因的枚举类. */ public enum SpawnReason { /** * 自然生成 */ NATURAL, /** * 当实体因为乘骑而被生成时 (大多是蜘蛛骑士) */ JOCKEY, /** * 当区块产生而生成生物时 * * @deprecated 不再调用, 区块与已经存在的实体一同生成. * 请考虑使用{@link ChunkLoadEvent#isNewChunk()} 和 {@link Chunk#getEntities()} * 以达到类似效果 */ @Deprecated CHUNK_GEN, /** * 当生物由于刷怪箱生成时 */ SPAWNER, /** * 当生物由于蛋生成时 (不是刷怪蛋,是普通的鸡蛋) */ EGG, /** * 当生物由于刷怪蛋生成时 */ SPAWNER_EGG, /** * 当生物由于闪电而生成时 */ LIGHTNING, /** * 当雪人被建造时 */ BUILD_SNOWMAN, /** * 当一个铁傀儡被建造时 */ BUILD_IRONGOLEM, /** * 当一个凋零被建造时 */ BUILD_WITHER, /** * 当村庄生成保卫的铁傀儡时 */ VILLAGE_DEFENSE, /** * 当一个僵尸进攻村庄而生成时. */ VILLAGE_INVASION, /** * When an entity breeds to create a child, this also include Shulker and Allay */ BREEDING, /** * 当史莱姆分裂时 */ SLIME_SPLIT, /** * 当一个实体请求支援时 */ REINFORCEMENTS, /** * 当生物由于地狱传送门而生成时 */ NETHER_PORTAL, /** * 当生物由于投掷器丢出鸡蛋而生成时 */ DISPENSE_EGG, /** * 当一个僵尸感染一个村民时 */ INFECTION, /** * 当村民从僵尸状态痊愈时 */ CURED, /** * 当豹猫为了照顾自己的孩子而出生时 */ OCELOT_BABY, /** * 当一条蠹虫从方块中生成时 */ SILVERFISH_BLOCK, /** * 当一个实体成为其他实体坐骑时 (大多数时是鸡骑士) */ MOUNT, /** * 当实体作为陷阱陷害玩家时 */ TRAP, /** * 由于末影珍珠的使用而生成. */ ENDER_PEARL, /** * When an entity is spawned as a result of the entity it is being * perched on jumping or being damaged */ SHOULDER_ENTITY, /** * 当一个实体溺亡而生成时 */ DROWNED, /** * When an cow is spawned by shearing a mushroom cow */ SHEARED, /** * 由于苦力怕等发生爆炸产生效果云时/When eg an effect cloud is spawned as a result of a creeper exploding */ EXPLOSION, /** * When an entity is spawned as part of a raid */ RAID, /** * When an entity is spawned as part of a patrol */ PATROL, /** * When a bee is released from a beehive/bee nest */ BEEHIVE, /** * When a piglin is converted to a zombified piglin. */ PIGLIN_ZOMBIFIED, /** * When an entity is created by a cast spell. */ SPELL, /** * When an entity is shaking in Powder Snow and a new entity spawns. */ FROZEN, /** * When a tadpole converts to a frog */ METAMORPHOSIS, /** * When an Allay duplicate itself */ DUPLICATION, /** * When a creature is spawned by the "/summon" command */ COMMAND, /** * 当生物被插件生成时 */ CUSTOM, /** * 实体由于其他原因而生成 */ DEFAULT } }
BukkitAPI-Translation-Group/Chinese_BukkitAPI
BukkitApi/org/bukkit/event/entity/CreatureSpawnEvent.java
1,340
/** * 当实体作为陷阱陷害玩家时 */
block_comment
zh-cn
package org.bukkit.event.entity; import org.bukkit.Chunk; import org.bukkit.entity.LivingEntity; import org.bukkit.event.world.ChunkLoadEvent; import org.jetbrains.annotations.NotNull; /** * 当一个生物体在世界中出生时触发该事件. * <p> * 如果该事件被取消了,那么这个生物将不会出生. */ public class CreatureSpawnEvent extends EntitySpawnEvent { private final SpawnReason spawnReason; public CreatureSpawnEvent(@NotNull final LivingEntity spawnee, @NotNull final SpawnReason spawnReason) { super(spawnee); this.spawnReason = spawnReason; } @NotNull @Override public LivingEntity getEntity() { return (LivingEntity) entity; } /** * 返回生物出生的原因 * <p> * 原文: * Gets the reason for why the creature is being spawned. * * @return 出生原因 */ @NotNull public SpawnReason getSpawnReason() { return spawnReason; } /** * 生成原因的枚举类. */ public enum SpawnReason { /** * 自然生成 */ NATURAL, /** * 当实体因为乘骑而被生成时 (大多是蜘蛛骑士) */ JOCKEY, /** * 当区块产生而生成生物时 * * @deprecated 不再调用, 区块与已经存在的实体一同生成. * 请考虑使用{@link ChunkLoadEvent#isNewChunk()} 和 {@link Chunk#getEntities()} * 以达到类似效果 */ @Deprecated CHUNK_GEN, /** * 当生物由于刷怪箱生成时 */ SPAWNER, /** * 当生物由于蛋生成时 (不是刷怪蛋,是普通的鸡蛋) */ EGG, /** * 当生物由于刷怪蛋生成时 */ SPAWNER_EGG, /** * 当生物由于闪电而生成时 */ LIGHTNING, /** * 当雪人被建造时 */ BUILD_SNOWMAN, /** * 当一个铁傀儡被建造时 */ BUILD_IRONGOLEM, /** * 当一个凋零被建造时 */ BUILD_WITHER, /** * 当村庄生成保卫的铁傀儡时 */ VILLAGE_DEFENSE, /** * 当一个僵尸进攻村庄而生成时. */ VILLAGE_INVASION, /** * When an entity breeds to create a child, this also include Shulker and Allay */ BREEDING, /** * 当史莱姆分裂时 */ SLIME_SPLIT, /** * 当一个实体请求支援时 */ REINFORCEMENTS, /** * 当生物由于地狱传送门而生成时 */ NETHER_PORTAL, /** * 当生物由于投掷器丢出鸡蛋而生成时 */ DISPENSE_EGG, /** * 当一个僵尸感染一个村民时 */ INFECTION, /** * 当村民从僵尸状态痊愈时 */ CURED, /** * 当豹猫为了照顾自己的孩子而出生时 */ OCELOT_BABY, /** * 当一条蠹虫从方块中生成时 */ SILVERFISH_BLOCK, /** * 当一个实体成为其他实体坐骑时 (大多数时是鸡骑士) */ MOUNT, /** * 当实体 <SUF>*/ TRAP, /** * 由于末影珍珠的使用而生成. */ ENDER_PEARL, /** * When an entity is spawned as a result of the entity it is being * perched on jumping or being damaged */ SHOULDER_ENTITY, /** * 当一个实体溺亡而生成时 */ DROWNED, /** * When an cow is spawned by shearing a mushroom cow */ SHEARED, /** * 由于苦力怕等发生爆炸产生效果云时/When eg an effect cloud is spawned as a result of a creeper exploding */ EXPLOSION, /** * When an entity is spawned as part of a raid */ RAID, /** * When an entity is spawned as part of a patrol */ PATROL, /** * When a bee is released from a beehive/bee nest */ BEEHIVE, /** * When a piglin is converted to a zombified piglin. */ PIGLIN_ZOMBIFIED, /** * When an entity is created by a cast spell. */ SPELL, /** * When an entity is shaking in Powder Snow and a new entity spawns. */ FROZEN, /** * When a tadpole converts to a frog */ METAMORPHOSIS, /** * When an Allay duplicate itself */ DUPLICATION, /** * When a creature is spawned by the "/summon" command */ COMMAND, /** * 当生物被插件生成时 */ CUSTOM, /** * 实体由于其他原因而生成 */ DEFAULT } }
0
1,174
14
1,335
18
1,331
15
1,335
18
1,831
30
false
false
false
false
false
true
52506_0
package org.bukkit; /** * 一个处理方块更变的代表. 服务器作为一个计算服务器内生物生成和使用代码的 * 直接的接口. */ public interface BlockChangeDelegate { /** * 指定特定坐标方块的类型而不需要进行全世界更新并通知 * <p> * 通过调用World.setTypeId比较安全,但比可能使用World.setRawTypeId * 慢一些. * * @param x X 坐标 * @param y Y 坐标 * @param z Z 坐标 * @param typeId 新方块ID * @return true 如果方块成功设置 * @deprecated Magic value */ @Deprecated public boolean setRawTypeId(int x, int y, int z, int typeId); /** * 指定特定坐标方块的数据而不需要进行全世界更新并通知 * <p> * 通过调用World.setTypeId比较安全,但比可能使用World.setRawTypeId * 慢一些. * * @param x X 坐标 * @param y Y 坐标 * @param z Z 坐标 * @param typeId 新方块ID * @param data 方块数据 * @return true 如果方块成功设置 * @deprecated Magic value */ @Deprecated public boolean setRawTypeIdAndData(int x, int y, int z, int typeId, int data); /** * 设置指定坐标的方块类型. * <p> * 这方式不需要调用World.setRawTypeId,但需要全局更新. * * @param x X 坐标 * @param y Y 坐标 * @param z Z 坐标 * @param typeId 新方块ID * @return true 如果方块成功设置 * @deprecated Magic value */ @Deprecated public boolean setTypeId(int x, int y, int z, int typeId); /** * 设置指定坐标的方块类型和数据. * <p> * 这方式不需要调用World.setRawTypeId,但需要全局更新. * * @param x X 坐标 * @param y Y 坐标 * @param z Z 坐标 * @param typeId 新方块ID * @param data 方块数据 * @return true 如果方块成功设置 * @deprecated Magic value */ @Deprecated public boolean setTypeIdAndData(int x, int y, int z, int typeId, int data); /** * 获取某一位置的方块类型. * * @param x X 坐标 * @param y Y 坐标 * @param z Z 坐标 * @param typeId 新方块ID * @deprecated Magic value */ @Deprecated public int getTypeId(int x, int y, int z); /** * 获取世界的高度. * * @return 世界的高度 */ public int getHeight(); /** * 检查指定的方块是否为空(空气). * * @param x X 坐标 * @param y Y 坐标 * @param z Z 坐标 * @return true 如果方块成功设置 */ public boolean isEmpty(int x, int y, int z); }
BukkitDocChinese/BukkitAPI
src/main/java/org/bukkit/BlockChangeDelegate.java
735
/** * 一个处理方块更变的代表. 服务器作为一个计算服务器内生物生成和使用代码的 * 直接的接口. */
block_comment
zh-cn
package org.bukkit; /** * 一个处 <SUF>*/ public interface BlockChangeDelegate { /** * 指定特定坐标方块的类型而不需要进行全世界更新并通知 * <p> * 通过调用World.setTypeId比较安全,但比可能使用World.setRawTypeId * 慢一些. * * @param x X 坐标 * @param y Y 坐标 * @param z Z 坐标 * @param typeId 新方块ID * @return true 如果方块成功设置 * @deprecated Magic value */ @Deprecated public boolean setRawTypeId(int x, int y, int z, int typeId); /** * 指定特定坐标方块的数据而不需要进行全世界更新并通知 * <p> * 通过调用World.setTypeId比较安全,但比可能使用World.setRawTypeId * 慢一些. * * @param x X 坐标 * @param y Y 坐标 * @param z Z 坐标 * @param typeId 新方块ID * @param data 方块数据 * @return true 如果方块成功设置 * @deprecated Magic value */ @Deprecated public boolean setRawTypeIdAndData(int x, int y, int z, int typeId, int data); /** * 设置指定坐标的方块类型. * <p> * 这方式不需要调用World.setRawTypeId,但需要全局更新. * * @param x X 坐标 * @param y Y 坐标 * @param z Z 坐标 * @param typeId 新方块ID * @return true 如果方块成功设置 * @deprecated Magic value */ @Deprecated public boolean setTypeId(int x, int y, int z, int typeId); /** * 设置指定坐标的方块类型和数据. * <p> * 这方式不需要调用World.setRawTypeId,但需要全局更新. * * @param x X 坐标 * @param y Y 坐标 * @param z Z 坐标 * @param typeId 新方块ID * @param data 方块数据 * @return true 如果方块成功设置 * @deprecated Magic value */ @Deprecated public boolean setTypeIdAndData(int x, int y, int z, int typeId, int data); /** * 获取某一位置的方块类型. * * @param x X 坐标 * @param y Y 坐标 * @param z Z 坐标 * @param typeId 新方块ID * @deprecated Magic value */ @Deprecated public int getTypeId(int x, int y, int z); /** * 获取世界的高度. * * @return 世界的高度 */ public int getHeight(); /** * 检查指定的方块是否为空(空气). * * @param x X 坐标 * @param y Y 坐标 * @param z Z 坐标 * @return true 如果方块成功设置 */ public boolean isEmpty(int x, int y, int z); }
0
787
33
735
36
796
32
735
36
1,098
53
false
false
false
false
false
true
47835_8
package class0103; import java.util.HashMap; import rlgs4.Stack; /** * @Description 算术表达式的中序遍历变成后序遍历 * @author Leon * @date 2016-05-31 17:08:35 */ public class InfixToPostfix { private static HashMap<Character,Integer> priority=new HashMap<Character,Integer>(){ private static final long serialVersionUID = 3714469304942582582L; { put('+', 1); put('-', 1); put('/', 2); put('*', 2); put('(', 0); } }; public static boolean isOperator(char c) { return c=='+'||c=='-'||c=='*'||c=='/'; } /** * 将带有计算的优先级和括号的中序表达式inOrder变成符合前述文法的后序表达式 */ public static String inToPost(String inOrder) { // 保存操作符 Stack<Character> stack = new Stack<Character>(); // postfix expresultsion String result = ""; // 保存s.pop() char tmp; char[] exp = inOrder.trim().toCharArray(); for (char x : exp) { // 如果是操作数,直接输出 if (!isOperator(x) && (x != '(') && (x != ')')) { result = result + x; } else if (x == '(') { stack.push(x); // 入栈 } else if (x == ')') { // 输出栈中的右操作符直到弹出'('为止 tmp = stack.pop(); while (tmp != '(') { result = result + tmp; tmp = stack.pop(); } tmp = '\0'; } else if (isOperator(x)) {// 与栈顶操作符比较优先级 if (!stack.isEmpty()) { tmp = stack.pop(); int prio1 = priority.get(tmp); int prio2 = priority.get(x); while (prio1 >= prio2) { result = result + tmp; // 如果栈顶优先级高则直接合并,出栈并重算 prio1 = -1; if (!stack.isEmpty()) { tmp = stack.pop(); prio1 = priority.get(tmp); } } if ((prio1 < prio2) && (prio1 != -1)) { stack.push(tmp); } } stack.push(x); } } while (!stack.isEmpty()) { tmp = stack.pop(); result = result + tmp; } return result; } public static void main(String[] args) { System.out.println(inToPost("1+2*3-4/5")); } }
BurningBright/algorithms-fourth-edition
src/class0103/InfixToPostfix.java
676
// 如果栈顶优先级高则直接合并,出栈并重算
line_comment
zh-cn
package class0103; import java.util.HashMap; import rlgs4.Stack; /** * @Description 算术表达式的中序遍历变成后序遍历 * @author Leon * @date 2016-05-31 17:08:35 */ public class InfixToPostfix { private static HashMap<Character,Integer> priority=new HashMap<Character,Integer>(){ private static final long serialVersionUID = 3714469304942582582L; { put('+', 1); put('-', 1); put('/', 2); put('*', 2); put('(', 0); } }; public static boolean isOperator(char c) { return c=='+'||c=='-'||c=='*'||c=='/'; } /** * 将带有计算的优先级和括号的中序表达式inOrder变成符合前述文法的后序表达式 */ public static String inToPost(String inOrder) { // 保存操作符 Stack<Character> stack = new Stack<Character>(); // postfix expresultsion String result = ""; // 保存s.pop() char tmp; char[] exp = inOrder.trim().toCharArray(); for (char x : exp) { // 如果是操作数,直接输出 if (!isOperator(x) && (x != '(') && (x != ')')) { result = result + x; } else if (x == '(') { stack.push(x); // 入栈 } else if (x == ')') { // 输出栈中的右操作符直到弹出'('为止 tmp = stack.pop(); while (tmp != '(') { result = result + tmp; tmp = stack.pop(); } tmp = '\0'; } else if (isOperator(x)) {// 与栈顶操作符比较优先级 if (!stack.isEmpty()) { tmp = stack.pop(); int prio1 = priority.get(tmp); int prio2 = priority.get(x); while (prio1 >= prio2) { result = result + tmp; // 如果 <SUF> prio1 = -1; if (!stack.isEmpty()) { tmp = stack.pop(); prio1 = priority.get(tmp); } } if ((prio1 < prio2) && (prio1 != -1)) { stack.push(tmp); } } stack.push(x); } } while (!stack.isEmpty()) { tmp = stack.pop(); result = result + tmp; } return result; } public static void main(String[] args) { System.out.println(inToPost("1+2*3-4/5")); } }
0
634
16
676
16
737
16
676
16
874
31
false
false
false
false
false
true
53097_4
package com.zskx.pemsystem.util; import java.io.IOException; import java.io.InputStream; import java.lang.ref.SoftReference; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Handler; import android.os.Message; import android.util.Log; public class AsyncImageLoader { public static String TAG = "AsyncImageLoader"; private HashMap<String, SoftReference<Drawable>> imageCache; private List<String> loadingUrls=new ArrayList<String>(); Drawable drawable; int i = 0; public AsyncImageLoader() { imageCache = new HashMap<String, SoftReference<Drawable>>(); } /** * 加载图片并处理 * * @param imageUrl * @param imageCallback */ public void loadDrawable(final String imageUrl, final ImageCallback imageCallback) { // Log.i(TAG, "loadDrawable:" + imageUrl); // 异步处理图片 final Handler handler = new Handler() { public void handleMessage(Message message) { if (message.obj != null){ imageCallback.imageLoaded((Drawable) message.obj, imageUrl); } } }; // 如果缓存内含有图片,直接返回缓存内图片 if (imageCache.containsKey(imageUrl)) { SoftReference<Drawable> softReference = imageCache.get(imageUrl); Drawable drawable = softReference.get(); if (drawable != null) { Message message = handler.obtainMessage(0, drawable); handler.sendMessage(message); return; } Log.i(TAG, "hashmap中有這個鑰匙值,但是還沒有獲取到圖片,這兒就到下面去!會出現再次訪問相同數據!"); } // 缓存内没有图片,开启线程下载图片 newThread(imageUrl, handler); System.out.println("i::::" + i); return; } private void newThread(final String imageUrl, final Handler handler) { if(imageUrl != null && !imageUrl.equals("") && !loadingUrls.contains(imageUrl)) new Thread() { @Override public void run() { Drawable drawable = null; if (drawable == null) { drawable = loadImageFromUrl(imageUrl); } // Log.i(TAG, "drawable:" + drawable); if(drawable != null) { loadingUrls.add(imageUrl); imageCache.put(imageUrl, new SoftReference<Drawable>(drawable)); loadingUrls.remove(imageUrl); Message message = handler.obtainMessage(0, drawable); handler.sendMessage(message); drawable = null;// 重置引用。 }else{ i++; if(i <= 3){ newThread(imageUrl, handler); } } drawable = null;// 重置引用。 } }.start(); } /** * 从网络下载图片 * * @param url * @return */ public static Drawable loadImageFromUrl(String url) { Log.i(TAG, "loadImageFromUrl:" + url); URL m; Drawable d = null; try { m = new URL(url); HttpURLConnection hcc = (HttpURLConnection) m.openConnection(); hcc.connect(); if (hcc.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream i = hcc.getInputStream(); Bitmap dd = BitmapFactory.decodeStream(i); BitmapDrawable bd= new BitmapDrawable(dd); d = bd; // d = Drawable.createFromStream(i, "src"); i.close(); } } catch (MalformedURLException e1) { e1.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e2) { e2.printStackTrace(); } catch (OutOfMemoryError e) { e.printStackTrace(); } return d; } /** * 异步处理图片的接口方法 * * @author guokai * */ public interface ImageCallback { public void imageLoaded(Drawable imageDrawable, String imageUrl); } }
Buwder/nibiru-vr-android-app
android/PEMsystem_V1.0/src/com/zskx/pemsystem/util/AsyncImageLoader.java
1,115
// 缓存内没有图片,开启线程下载图片
line_comment
zh-cn
package com.zskx.pemsystem.util; import java.io.IOException; import java.io.InputStream; import java.lang.ref.SoftReference; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Handler; import android.os.Message; import android.util.Log; public class AsyncImageLoader { public static String TAG = "AsyncImageLoader"; private HashMap<String, SoftReference<Drawable>> imageCache; private List<String> loadingUrls=new ArrayList<String>(); Drawable drawable; int i = 0; public AsyncImageLoader() { imageCache = new HashMap<String, SoftReference<Drawable>>(); } /** * 加载图片并处理 * * @param imageUrl * @param imageCallback */ public void loadDrawable(final String imageUrl, final ImageCallback imageCallback) { // Log.i(TAG, "loadDrawable:" + imageUrl); // 异步处理图片 final Handler handler = new Handler() { public void handleMessage(Message message) { if (message.obj != null){ imageCallback.imageLoaded((Drawable) message.obj, imageUrl); } } }; // 如果缓存内含有图片,直接返回缓存内图片 if (imageCache.containsKey(imageUrl)) { SoftReference<Drawable> softReference = imageCache.get(imageUrl); Drawable drawable = softReference.get(); if (drawable != null) { Message message = handler.obtainMessage(0, drawable); handler.sendMessage(message); return; } Log.i(TAG, "hashmap中有這個鑰匙值,但是還沒有獲取到圖片,這兒就到下面去!會出現再次訪問相同數據!"); } // 缓存 <SUF> newThread(imageUrl, handler); System.out.println("i::::" + i); return; } private void newThread(final String imageUrl, final Handler handler) { if(imageUrl != null && !imageUrl.equals("") && !loadingUrls.contains(imageUrl)) new Thread() { @Override public void run() { Drawable drawable = null; if (drawable == null) { drawable = loadImageFromUrl(imageUrl); } // Log.i(TAG, "drawable:" + drawable); if(drawable != null) { loadingUrls.add(imageUrl); imageCache.put(imageUrl, new SoftReference<Drawable>(drawable)); loadingUrls.remove(imageUrl); Message message = handler.obtainMessage(0, drawable); handler.sendMessage(message); drawable = null;// 重置引用。 }else{ i++; if(i <= 3){ newThread(imageUrl, handler); } } drawable = null;// 重置引用。 } }.start(); } /** * 从网络下载图片 * * @param url * @return */ public static Drawable loadImageFromUrl(String url) { Log.i(TAG, "loadImageFromUrl:" + url); URL m; Drawable d = null; try { m = new URL(url); HttpURLConnection hcc = (HttpURLConnection) m.openConnection(); hcc.connect(); if (hcc.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream i = hcc.getInputStream(); Bitmap dd = BitmapFactory.decodeStream(i); BitmapDrawable bd= new BitmapDrawable(dd); d = bd; // d = Drawable.createFromStream(i, "src"); i.close(); } } catch (MalformedURLException e1) { e1.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e2) { e2.printStackTrace(); } catch (OutOfMemoryError e) { e.printStackTrace(); } return d; } /** * 异步处理图片的接口方法 * * @author guokai * */ public interface ImageCallback { public void imageLoaded(Drawable imageDrawable, String imageUrl); } }
0
930
13
1,115
11
1,109
11
1,115
11
1,478
22
false
false
false
false
false
true
36148_0
package org.byron4j.cookbook.designpattern.builder; /** * 晚餐实体类 */ public class Meal { private String sandwich; private String sideOrder; private String drink; private String offer; private double price; @Override public String toString() { return "Meal{" + "sandwich='" + sandwich + '\'' + ", sideOrder='" + sideOrder + '\'' + ", drink='" + drink + '\'' + ", offer='" + offer + '\'' + ", price='" + price + '\'' + '}'; } public void setSandwich(String sandwich) { this.sandwich = sandwich; } public void setSideOrder(String sideOrder) { this.sideOrder = sideOrder; } public void setDrink(String drink) { this.drink = drink; } public void setOffer(String offer) { this.offer = offer; } public void setPrice(double price) { this.price = price; } }
Byron4j/CookBook
src/main/java/org/byron4j/cookbook/designpattern/builder/Meal.java
245
/** * 晚餐实体类 */
block_comment
zh-cn
package org.byron4j.cookbook.designpattern.builder; /** * 晚餐实 <SUF>*/ public class Meal { private String sandwich; private String sideOrder; private String drink; private String offer; private double price; @Override public String toString() { return "Meal{" + "sandwich='" + sandwich + '\'' + ", sideOrder='" + sideOrder + '\'' + ", drink='" + drink + '\'' + ", offer='" + offer + '\'' + ", price='" + price + '\'' + '}'; } public void setSandwich(String sandwich) { this.sandwich = sandwich; } public void setSideOrder(String sideOrder) { this.sideOrder = sideOrder; } public void setDrink(String drink) { this.drink = drink; } public void setOffer(String offer) { this.offer = offer; } public void setPrice(double price) { this.price = price; } }
0
215
10
243
12
254
9
243
12
298
15
false
false
false
false
false
true
59121_3
package com.byronlee; import android.app.Activity; import android.os.Bundle; import android.view.Window; import android.view.WindowManager; public class main extends Activity{ public void onCreat(Bundle savedInstanceState){ super.onCreate(savedInstanceState); //强制全屏 //首先去掉title,就是没有title 那一行,但是还不是全屏 requestWindowFeature(Window.FEATURE_NO_TITLE); // 禁止屏幕休眠 getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); //去掉状态栏 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); } }
Byronlee/ByronleeTeeter
src/com/byronlee/main.java
200
//去掉状态栏
line_comment
zh-cn
package com.byronlee; import android.app.Activity; import android.os.Bundle; import android.view.Window; import android.view.WindowManager; public class main extends Activity{ public void onCreat(Bundle savedInstanceState){ super.onCreate(savedInstanceState); //强制全屏 //首先去掉title,就是没有title 那一行,但是还不是全屏 requestWindowFeature(Window.FEATURE_NO_TITLE); // 禁止屏幕休眠 getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); //去掉 <SUF> getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); } }
0
140
5
192
6
198
5
192
6
272
11
false
false
false
false
false
true
60179_20
package com.anna.ft_home.view.home; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.graphics.Typeface; import android.os.Bundle; import android.util.DisplayMetrics; import android.util.Log; import android.view.Gravity; import android.view.KeyEvent; import android.view.View; import android.view.WindowManager; import android.widget.ImageView; import androidx.drawerlayout.widget.DrawerLayout; import androidx.localbroadcastmanager.content.LocalBroadcastManager; import androidx.viewpager.widget.ViewPager; import com.alibaba.android.arouter.launcher.ARouter; import com.anna.ft_home.R; import com.anna.ft_home.model.CHANNEL; import com.anna.ft_home.view.home.adapter.HomePagerAdapter; import com.anna.lib_base.module.audio.AudioImpl; import com.anna.lib_base.module.audio.model.CommonAudioBean; import com.anna.lib_base.module.login.LoginImpl; import com.anna.lib_common_ui.base.BaseActivity; import com.anna.lib_common_ui.base.constant.Constant; import com.anna.lib_common_ui.pager_indictor.ScaleTransitionPagerTitleView; import net.lucode.hackware.magicindicator.MagicIndicator; import net.lucode.hackware.magicindicator.ViewPagerHelper; import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator; import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter; import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator; import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView; import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView; import java.util.ArrayList; /** * 首页Activity */ public class HomeActivity extends BaseActivity implements View.OnClickListener { private static final CHANNEL[] CHANNELS = new CHANNEL[]{CHANNEL.MY, CHANNEL.DISCORY, CHANNEL.FRIEND}; private UpdateReceiver mReceiver = null; /* * View */ private DrawerLayout mDrawerLayout; private View mToggleView; private View mSearchView; private ViewPager mViewPager; private HomePagerAdapter mAdapter; private View mDrawerQrcodeView; private View mDrawerShareView; private View unLogginLayout; private ImageView mPhotoView; public static void start(Context context) { Intent intent = new Intent(context, HomeActivity.class); context.startActivity(intent); } /* * data */ private ArrayList<CommonAudioBean> mLists = new ArrayList<>(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); registerBroadcastReceiver(); // EventBus.getDefault().register(this); setContentView(R.layout.activity_main); initView(); initData(); } private void initData() { mLists.add(new CommonAudioBean("100001", "http://sp-sycdn.kuwo.cn/resource/n2/85/58/433900159.mp3", "我走后", "小咪", "生而为人", "为梦想打拼的每一个个体都是闪光的,为梦想打拼的每一个个体都是闪光的,为梦想打拼的每一个个体都是闪光的。", "http://img0.imgtn.bdimg.com/it/u=2329770966,4069416364&fm=26&gp=0.jpg", "4:30")); mLists.add( new CommonAudioBean("100002", "http://sq-sycdn.kuwo.cn/resource/n1/98/51/3777061809.mp3", "勇气", "梁静茹", "勇气", "电影《不能说的秘密》主题曲,尤其以最美的不是下雨天,是与你一起躲过雨的屋檐最为经典", "http://b-ssl.duitang.com/uploads/item/201707/01/20170701182157_5eMn2.jpeg", "4:40")); mLists.add( new CommonAudioBean("100003", "http://sp-sycdn.kuwo.cn/resource/n2/52/80/2933081485.mp3", "灿烂如你", "汪峰", "春天里", "电影《不能说的秘密》主题曲,尤其以最美的不是下雨天,是与你一起躲过雨的屋檐最为经典", "http://img3.imgtn.bdimg.com/it/u=2136332768,653918923&fm=26&gp=0.jpg", "3:20")); mLists.add( new CommonAudioBean("100004", "http://sr-sycdn.kuwo.cn/resource/n2/33/25/2629654819.mp3", "小情歌", "五月天", "小幸运", "电影《不能说的秘密》主题曲,尤其以最美的不是下雨天,是与你一起躲过雨的屋檐最为经典", "http://pic1.win4000.com/mobile/2018-10-08/5bbb0343355a0.jpg", "2:45")); AudioImpl.getInstance().setQueue(mLists); } private void initView() { mDrawerLayout = findViewById(R.id.drawer_layout); mToggleView = findViewById(R.id.toggle_view); mToggleView.setOnClickListener(this); mSearchView = findViewById(R.id.search_view); mSearchView.setOnClickListener(this); //初始化adpater mAdapter = new HomePagerAdapter(getSupportFragmentManager(), CHANNELS); mViewPager = findViewById(R.id.view_pager); mViewPager.setAdapter(mAdapter); initMagicIndicator(); mDrawerQrcodeView = findViewById(R.id.home_qrcode); mDrawerQrcodeView.setOnClickListener(this); mDrawerShareView = findViewById(R.id.home_music); mDrawerShareView.setOnClickListener(this); findViewById(R.id.online_music_view).setOnClickListener(this); findViewById(R.id.check_update_view).setOnClickListener(this); unLogginLayout = findViewById(R.id.unloggin_layout); unLogginLayout.setOnClickListener(this); mPhotoView = findViewById(R.id.avatr_view); findViewById(R.id.exit_layout).setOnClickListener(this); DisplayMetrics dm = new DisplayMetrics(); WindowManager wm = (WindowManager)getSystemService(Context.WINDOW_SERVICE); wm.getDefaultDisplay().getMetrics(dm); Log.d("tag1112:","width:"+dm.widthPixels); } private void initMagicIndicator() { MagicIndicator magicIndicator = findViewById(R.id.magic_indicator); magicIndicator.setBackgroundColor(Color.WHITE); CommonNavigator commonNavigator = new CommonNavigator(this); commonNavigator.setAdjustMode(true); commonNavigator.setAdapter(new CommonNavigatorAdapter() { @Override public int getCount() { return CHANNELS == null ? 0 : CHANNELS.length; } @Override public IPagerTitleView getTitleView(Context context, final int index) { SimplePagerTitleView simplePagerTitleView = new ScaleTransitionPagerTitleView(context); simplePagerTitleView.setText(CHANNELS[index].getKey()); simplePagerTitleView.setTextSize(19); simplePagerTitleView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD)); simplePagerTitleView.setNormalColor(Color.parseColor("#999999")); simplePagerTitleView.setSelectedColor(Color.parseColor("#333333")); simplePagerTitleView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mViewPager.setCurrentItem(index); } }); return simplePagerTitleView; } @Override public IPagerIndicator getIndicator(Context context) { return null; } @Override public float getTitleWeight(Context context, int index) { return 1.0f; } }); magicIndicator.setNavigator(commonNavigator); ViewPagerHelper.bind(magicIndicator, mViewPager); } @Override public void onClick(View v) { int id = v.getId(); if (id == R.id.exit_layout) { finish(); System.exit(0); } else if (id == R.id.unloggin_layout) { if (!LoginImpl.getInstance().hasLogin()) { LoginImpl.getInstance().login(this); } else { mDrawerLayout.closeDrawer(Gravity.LEFT); } } else if (id == R.id.toggle_view) { if (mDrawerLayout.isDrawerOpen(Gravity.LEFT)) { mDrawerLayout.closeDrawer(Gravity.LEFT); } else { mDrawerLayout.openDrawer(Gravity.LEFT); } } else if (id == R.id.home_qrcode) { if (hasPermission(Constant.HARDWEAR_CAMERA_PERMISSION)) { doCameraPermission(); } else { requestPermission(Constant.HARDWEAR_CAMERA_CODE, Constant.HARDWEAR_CAMERA_PERMISSION); } } else if (id == R.id.home_music) {//shareFriend(); goToMusic(); } else if (id == R.id.online_music_view) {//跳到指定webactivity gotoWebView("https://www.imooc.com"); } else if (id == R.id.check_update_view) { checkUpdate(); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { //退出不销毁task中activity moveTaskToBack(true); return true; } return super.onKeyDown(keyCode, event); } @Override protected void onDestroy() { super.onDestroy(); // EventBus.getDefault().unregister(this); unRegisterBroadcastReceiver(); } @Override public void doCameraPermission() { // ARouter.getInstance().build(Constant.Router.ROUTER_CAPTURE_ACTIVIYT).navigation(); } private void goToMusic() { // ARouter.getInstance().build(Constant.Router.ROUTER_MUSIC_ACTIVIYT).navigation(); } private void gotoWebView(String url) { ARouter.getInstance() .build(Constant.Router.ROUTER_WEB_ACTIVIYT) .withString("url", url) .navigation(); } //启动检查更新 private void checkUpdate() { // UpdateHelper.checkUpdate(this); } private void registerBroadcastReceiver() { // if (mReceiver == null) { // mReceiver = new UpdateReceiver(); // LocalBroadcastManager.getInstance(this) // .registerReceiver(mReceiver, new IntentFilter(UpdateHelper.UPDATE_ACTION)); // } } private void unRegisterBroadcastReceiver() { if (mReceiver != null) { LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver); } } /** * 接收Update发送的广播 */ public class UpdateReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { //启动安装页面 // context.startActivity( // Utils.getInstallApkIntent(context, intent.getStringExtra(UpdateHelper.UPDATE_FILE_KEY))); } } // /** // * 处理登陆事件 // */ // @Subscribe(threadMode = ThreadMode.MAIN) // public void onLoginEvent(LoginEvent event) { // unLogginLayout.setVisibility(View.GONE); // mPhotoView.setVisibility(View.VISIBLE); // CustomImageLoader.getInstance() // .displayImageForCircleView(mPhotoView, UserManager.getInstance().getUser().data.photoUrl); // } }
ByteYuhb/anna_music_app
ft_home/src/main/java/com/anna/ft_home/view/home/HomeActivity.java
3,034
//启动检查更新
line_comment
zh-cn
package com.anna.ft_home.view.home; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.graphics.Typeface; import android.os.Bundle; import android.util.DisplayMetrics; import android.util.Log; import android.view.Gravity; import android.view.KeyEvent; import android.view.View; import android.view.WindowManager; import android.widget.ImageView; import androidx.drawerlayout.widget.DrawerLayout; import androidx.localbroadcastmanager.content.LocalBroadcastManager; import androidx.viewpager.widget.ViewPager; import com.alibaba.android.arouter.launcher.ARouter; import com.anna.ft_home.R; import com.anna.ft_home.model.CHANNEL; import com.anna.ft_home.view.home.adapter.HomePagerAdapter; import com.anna.lib_base.module.audio.AudioImpl; import com.anna.lib_base.module.audio.model.CommonAudioBean; import com.anna.lib_base.module.login.LoginImpl; import com.anna.lib_common_ui.base.BaseActivity; import com.anna.lib_common_ui.base.constant.Constant; import com.anna.lib_common_ui.pager_indictor.ScaleTransitionPagerTitleView; import net.lucode.hackware.magicindicator.MagicIndicator; import net.lucode.hackware.magicindicator.ViewPagerHelper; import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator; import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter; import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator; import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView; import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView; import java.util.ArrayList; /** * 首页Activity */ public class HomeActivity extends BaseActivity implements View.OnClickListener { private static final CHANNEL[] CHANNELS = new CHANNEL[]{CHANNEL.MY, CHANNEL.DISCORY, CHANNEL.FRIEND}; private UpdateReceiver mReceiver = null; /* * View */ private DrawerLayout mDrawerLayout; private View mToggleView; private View mSearchView; private ViewPager mViewPager; private HomePagerAdapter mAdapter; private View mDrawerQrcodeView; private View mDrawerShareView; private View unLogginLayout; private ImageView mPhotoView; public static void start(Context context) { Intent intent = new Intent(context, HomeActivity.class); context.startActivity(intent); } /* * data */ private ArrayList<CommonAudioBean> mLists = new ArrayList<>(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); registerBroadcastReceiver(); // EventBus.getDefault().register(this); setContentView(R.layout.activity_main); initView(); initData(); } private void initData() { mLists.add(new CommonAudioBean("100001", "http://sp-sycdn.kuwo.cn/resource/n2/85/58/433900159.mp3", "我走后", "小咪", "生而为人", "为梦想打拼的每一个个体都是闪光的,为梦想打拼的每一个个体都是闪光的,为梦想打拼的每一个个体都是闪光的。", "http://img0.imgtn.bdimg.com/it/u=2329770966,4069416364&fm=26&gp=0.jpg", "4:30")); mLists.add( new CommonAudioBean("100002", "http://sq-sycdn.kuwo.cn/resource/n1/98/51/3777061809.mp3", "勇气", "梁静茹", "勇气", "电影《不能说的秘密》主题曲,尤其以最美的不是下雨天,是与你一起躲过雨的屋檐最为经典", "http://b-ssl.duitang.com/uploads/item/201707/01/20170701182157_5eMn2.jpeg", "4:40")); mLists.add( new CommonAudioBean("100003", "http://sp-sycdn.kuwo.cn/resource/n2/52/80/2933081485.mp3", "灿烂如你", "汪峰", "春天里", "电影《不能说的秘密》主题曲,尤其以最美的不是下雨天,是与你一起躲过雨的屋檐最为经典", "http://img3.imgtn.bdimg.com/it/u=2136332768,653918923&fm=26&gp=0.jpg", "3:20")); mLists.add( new CommonAudioBean("100004", "http://sr-sycdn.kuwo.cn/resource/n2/33/25/2629654819.mp3", "小情歌", "五月天", "小幸运", "电影《不能说的秘密》主题曲,尤其以最美的不是下雨天,是与你一起躲过雨的屋檐最为经典", "http://pic1.win4000.com/mobile/2018-10-08/5bbb0343355a0.jpg", "2:45")); AudioImpl.getInstance().setQueue(mLists); } private void initView() { mDrawerLayout = findViewById(R.id.drawer_layout); mToggleView = findViewById(R.id.toggle_view); mToggleView.setOnClickListener(this); mSearchView = findViewById(R.id.search_view); mSearchView.setOnClickListener(this); //初始化adpater mAdapter = new HomePagerAdapter(getSupportFragmentManager(), CHANNELS); mViewPager = findViewById(R.id.view_pager); mViewPager.setAdapter(mAdapter); initMagicIndicator(); mDrawerQrcodeView = findViewById(R.id.home_qrcode); mDrawerQrcodeView.setOnClickListener(this); mDrawerShareView = findViewById(R.id.home_music); mDrawerShareView.setOnClickListener(this); findViewById(R.id.online_music_view).setOnClickListener(this); findViewById(R.id.check_update_view).setOnClickListener(this); unLogginLayout = findViewById(R.id.unloggin_layout); unLogginLayout.setOnClickListener(this); mPhotoView = findViewById(R.id.avatr_view); findViewById(R.id.exit_layout).setOnClickListener(this); DisplayMetrics dm = new DisplayMetrics(); WindowManager wm = (WindowManager)getSystemService(Context.WINDOW_SERVICE); wm.getDefaultDisplay().getMetrics(dm); Log.d("tag1112:","width:"+dm.widthPixels); } private void initMagicIndicator() { MagicIndicator magicIndicator = findViewById(R.id.magic_indicator); magicIndicator.setBackgroundColor(Color.WHITE); CommonNavigator commonNavigator = new CommonNavigator(this); commonNavigator.setAdjustMode(true); commonNavigator.setAdapter(new CommonNavigatorAdapter() { @Override public int getCount() { return CHANNELS == null ? 0 : CHANNELS.length; } @Override public IPagerTitleView getTitleView(Context context, final int index) { SimplePagerTitleView simplePagerTitleView = new ScaleTransitionPagerTitleView(context); simplePagerTitleView.setText(CHANNELS[index].getKey()); simplePagerTitleView.setTextSize(19); simplePagerTitleView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD)); simplePagerTitleView.setNormalColor(Color.parseColor("#999999")); simplePagerTitleView.setSelectedColor(Color.parseColor("#333333")); simplePagerTitleView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mViewPager.setCurrentItem(index); } }); return simplePagerTitleView; } @Override public IPagerIndicator getIndicator(Context context) { return null; } @Override public float getTitleWeight(Context context, int index) { return 1.0f; } }); magicIndicator.setNavigator(commonNavigator); ViewPagerHelper.bind(magicIndicator, mViewPager); } @Override public void onClick(View v) { int id = v.getId(); if (id == R.id.exit_layout) { finish(); System.exit(0); } else if (id == R.id.unloggin_layout) { if (!LoginImpl.getInstance().hasLogin()) { LoginImpl.getInstance().login(this); } else { mDrawerLayout.closeDrawer(Gravity.LEFT); } } else if (id == R.id.toggle_view) { if (mDrawerLayout.isDrawerOpen(Gravity.LEFT)) { mDrawerLayout.closeDrawer(Gravity.LEFT); } else { mDrawerLayout.openDrawer(Gravity.LEFT); } } else if (id == R.id.home_qrcode) { if (hasPermission(Constant.HARDWEAR_CAMERA_PERMISSION)) { doCameraPermission(); } else { requestPermission(Constant.HARDWEAR_CAMERA_CODE, Constant.HARDWEAR_CAMERA_PERMISSION); } } else if (id == R.id.home_music) {//shareFriend(); goToMusic(); } else if (id == R.id.online_music_view) {//跳到指定webactivity gotoWebView("https://www.imooc.com"); } else if (id == R.id.check_update_view) { checkUpdate(); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { //退出不销毁task中activity moveTaskToBack(true); return true; } return super.onKeyDown(keyCode, event); } @Override protected void onDestroy() { super.onDestroy(); // EventBus.getDefault().unregister(this); unRegisterBroadcastReceiver(); } @Override public void doCameraPermission() { // ARouter.getInstance().build(Constant.Router.ROUTER_CAPTURE_ACTIVIYT).navigation(); } private void goToMusic() { // ARouter.getInstance().build(Constant.Router.ROUTER_MUSIC_ACTIVIYT).navigation(); } private void gotoWebView(String url) { ARouter.getInstance() .build(Constant.Router.ROUTER_WEB_ACTIVIYT) .withString("url", url) .navigation(); } //启动 <SUF> private void checkUpdate() { // UpdateHelper.checkUpdate(this); } private void registerBroadcastReceiver() { // if (mReceiver == null) { // mReceiver = new UpdateReceiver(); // LocalBroadcastManager.getInstance(this) // .registerReceiver(mReceiver, new IntentFilter(UpdateHelper.UPDATE_ACTION)); // } } private void unRegisterBroadcastReceiver() { if (mReceiver != null) { LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver); } } /** * 接收Update发送的广播 */ public class UpdateReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { //启动安装页面 // context.startActivity( // Utils.getInstallApkIntent(context, intent.getStringExtra(UpdateHelper.UPDATE_FILE_KEY))); } } // /** // * 处理登陆事件 // */ // @Subscribe(threadMode = ThreadMode.MAIN) // public void onLoginEvent(LoginEvent event) { // unLogginLayout.setVisibility(View.GONE); // mPhotoView.setVisibility(View.VISIBLE); // CustomImageLoader.getInstance() // .displayImageForCircleView(mPhotoView, UserManager.getInstance().getUser().data.photoUrl); // } }
0
2,478
4
3,034
4
3,079
4
3,034
4
3,594
11
false
false
false
false
false
true
56406_3
package com.chen.LeoBlog.po; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import java.io.Serializable; import java.util.Date; /** * 黑名单 * * @TableName lb_black */ @TableName(value = "lb_black") @Data public class Black implements Serializable { /** * id */ @TableId(type = IdType.AUTO) private Long id; /** * 拉黑目标类型 1.ip 2uid */ private Integer type; /** * 拉黑目标 */ private String target; /** * 创建时间 */ private Date createTime; /** * 修改时间 */ private Date updateTime; @TableField(exist = false) private static final long serialVersionUID = 1L; }
C-176/LeoBlog-back
src/main/java/com/chen/LeoBlog/po/Black.java
235
/** * 拉黑目标 */
block_comment
zh-cn
package com.chen.LeoBlog.po; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import java.io.Serializable; import java.util.Date; /** * 黑名单 * * @TableName lb_black */ @TableName(value = "lb_black") @Data public class Black implements Serializable { /** * id */ @TableId(type = IdType.AUTO) private Long id; /** * 拉黑目标类型 1.ip 2uid */ private Integer type; /** * 拉黑目 <SUF>*/ private String target; /** * 创建时间 */ private Date createTime; /** * 修改时间 */ private Date updateTime; @TableField(exist = false) private static final long serialVersionUID = 1L; }
0
197
11
235
8
248
10
235
8
317
14
false
false
false
false
false
true
56405_4
package com.bandgear.apfree.bean; import java.io.Serializable; public class IPWhite implements Serializable{ /** * ip白名单,对应rule_ipwhite表 * 加入ip白名单的设备会被限速 */ private Integer ap_id;//对应路由器ap_id private Integer id;//唯一标识 private String ip;//目标ip private String netmask;//子网掩码,跟ip结合使用代表某一网段 private Integer enable;//是否可用,0不可用,1可用 public IPWhite(Integer id, String ip, String netmask, Integer enable) { super(); this.id = id; this.ip = ip; this.netmask = netmask; this.enable = enable; } public IPWhite(){}; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public String getNetmask() { return netmask; } public void setNetmask(String netmask) { this.netmask = netmask; } public Integer getEnable() { return enable; } public void setEnable(Integer enable) { this.enable = enable; } public Integer getAp_id() { return ap_id; } public void setAp_id(Integer apId) { ap_id = apId; } }
C-hill/java4wifidog_server
src/com/bandgear/apfree/bean/IPWhite.java
402
//子网掩码,跟ip结合使用代表某一网段
line_comment
zh-cn
package com.bandgear.apfree.bean; import java.io.Serializable; public class IPWhite implements Serializable{ /** * ip白名单,对应rule_ipwhite表 * 加入ip白名单的设备会被限速 */ private Integer ap_id;//对应路由器ap_id private Integer id;//唯一标识 private String ip;//目标ip private String netmask;//子网 <SUF> private Integer enable;//是否可用,0不可用,1可用 public IPWhite(Integer id, String ip, String netmask, Integer enable) { super(); this.id = id; this.ip = ip; this.netmask = netmask; this.enable = enable; } public IPWhite(){}; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public String getNetmask() { return netmask; } public void setNetmask(String netmask) { this.netmask = netmask; } public Integer getEnable() { return enable; } public void setEnable(Integer enable) { this.enable = enable; } public Integer getAp_id() { return ap_id; } public void setAp_id(Integer apId) { ap_id = apId; } }
0
309
14
402
17
397
15
402
17
457
24
false
false
false
false
false
true
50905_20
package com.demo.smartport.Table; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; import static com.baomidou.mybatisplus.annotation.IdType.AUTO; @NoArgsConstructor @AllArgsConstructor @Data @TableName("tb_ship") //船舶绑定数据 public class Ship implements Serializable { //船舶主键/唯一关键静态信息 @TableId(type= AUTO) private Integer id; //(主键)id private String name; //名称 private String letter; //呼号 private String imo; //imo private String mmsi; //mmsi //船舶静态数据 private Integer type; //船舶类型 private Double length; //船长(米) private Double width; //船宽(米) private Double draft; //吃水(米) private String portrait; //船舶预览图url //船舶动态数据 private Integer status; //船舶状态 private Double head; //船首向(度) private Double track; //船迹向(度) private Double speed; //航速(节)ar private String latitude; //纬度(N) private String longitude; //经度(E) private String destination; //目的地 private String arrive; //预到时间(年/月/日 时:分:秒) private String refresh; //更新时间(年/月/日 时:分:秒) }
CANDYFLOSSKKI/smart-port-BillProcessing
smartport/src/main/java/com/demo/smartport/Table/Ship.java
399
//更新时间(年/月/日 时:分:秒)
line_comment
zh-cn
package com.demo.smartport.Table; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; import static com.baomidou.mybatisplus.annotation.IdType.AUTO; @NoArgsConstructor @AllArgsConstructor @Data @TableName("tb_ship") //船舶绑定数据 public class Ship implements Serializable { //船舶主键/唯一关键静态信息 @TableId(type= AUTO) private Integer id; //(主键)id private String name; //名称 private String letter; //呼号 private String imo; //imo private String mmsi; //mmsi //船舶静态数据 private Integer type; //船舶类型 private Double length; //船长(米) private Double width; //船宽(米) private Double draft; //吃水(米) private String portrait; //船舶预览图url //船舶动态数据 private Integer status; //船舶状态 private Double head; //船首向(度) private Double track; //船迹向(度) private Double speed; //航速(节)ar private String latitude; //纬度(N) private String longitude; //经度(E) private String destination; //目的地 private String arrive; //预到时间(年/月/日 时:分:秒) private String refresh; //更新 <SUF> }
0
343
16
399
15
393
15
399
15
532
20
false
false
false
false
false
true
21123_6
class Solution { public int ladderLength(String beginWord, String endWord, List<String> wordList) { // myidea:我分析感觉像是最短路径问题,如果两个单词只有一个字母不一样那么就建立一条无向边,切权值为1,最后记录由beginWord到endWord的路径paths即可 // 实现点1:如何构建图,想法:按照单词的下标对应最终的图邻接矩阵的下标,然后beginWord的下标为n,n是wordList的长度 // int n = wordList.size(); // 大小是n+1的原因是0--n存储的是wordList中的元素,n存储的是beginWorld int[][] graph = new int[n+1][n+1]; // 找到endword在wordList中的下标位置 int end = -1; for(int i = 0;i<n;i++) if(wordList.get(i).equals(endWord)) end = i; // 如果wordList中不包含endWord if(end == -1) return 0; // 初始化graph for(int i = 0;i<n;i++) if(calcDis(beginWord,wordList.get(i))){ graph[n][i] = 1; graph[i][n] = 1; } for(int i = 0;i<n;i++){ for(int j = 0;j<n;j++){ if(i!=j && calcDis(wordList.get(i),wordList.get(j))){ graph[i][j] = 1; graph[j][i] = 1; } } } // 图构建完成之后,接下来就是计算单源最短路径,使用dijskra return dijskra(graph,n,end)==0?0:dijskra(graph,n,end)+1; } // 计算两个单词之间是否只有1个字符不相同,是则为true反之false public boolean calcDis(String s1,String s2){ // 因为题目说了所有的单词具有一样的长度,所以没有必要进行长度的判断 int dis = 0; for(int i = 0;i<s1.length();i++) if(s1.charAt(i) != s2.charAt(i)) dis++; return dis == 1; } // dijskra public int dijskra(int[][] graph,int start,int end){ int n = graph.length; // 存放start到各个下标节点的距离,初始化 int[] distance = new int[n]; for(int i = 0;i<n;i++) distance[i] = graph[start][i]; distance[start] = 0; // 判断start到下标位置的节点是否有最短路径 boolean[] visited = new boolean[n]; visited[start] = true; // 遍历除了start本身节点的所有节点、也就是说循环n-1次 for(int i = 1;i < n;i++){ // 当前最短距离 int minDistance = Integer.MAX_VALUE; // 当前最短距离的节点下标 int minIndex = 1; // 遍历所有的节点,找到距离start的最近的节点 for(int j =0;j < n;j++){ if(!visited[j] && distance[j] != 0 && distance[j]<=minDistance){ minDistance = distance[j]; minIndex = j; } } // 标记最近距离节点已经找到了 visited[minIndex] = true; // 根据刚刚找到的最近距离节点,更新start节点到其他节点的距离 for(int j=0;j< n;j++){ // 如果已更新的最短距离节点可以到达当前便利的节点 if(graph[minIndex][j] == 1){ if(distance[j] != 0) distance[j] = Math.min(distance[j],distance[minIndex] + graph[minIndex][j]); else distance[j] = distance[minIndex] + graph[minIndex][j]; } } } return distance[end]; } }
CAS-IICT/leetcode-algorithm-hack
Word-Ladder/Solution.java
987
// 图构建完成之后,接下来就是计算单源最短路径,使用dijskra
line_comment
zh-cn
class Solution { public int ladderLength(String beginWord, String endWord, List<String> wordList) { // myidea:我分析感觉像是最短路径问题,如果两个单词只有一个字母不一样那么就建立一条无向边,切权值为1,最后记录由beginWord到endWord的路径paths即可 // 实现点1:如何构建图,想法:按照单词的下标对应最终的图邻接矩阵的下标,然后beginWord的下标为n,n是wordList的长度 // int n = wordList.size(); // 大小是n+1的原因是0--n存储的是wordList中的元素,n存储的是beginWorld int[][] graph = new int[n+1][n+1]; // 找到endword在wordList中的下标位置 int end = -1; for(int i = 0;i<n;i++) if(wordList.get(i).equals(endWord)) end = i; // 如果wordList中不包含endWord if(end == -1) return 0; // 初始化graph for(int i = 0;i<n;i++) if(calcDis(beginWord,wordList.get(i))){ graph[n][i] = 1; graph[i][n] = 1; } for(int i = 0;i<n;i++){ for(int j = 0;j<n;j++){ if(i!=j && calcDis(wordList.get(i),wordList.get(j))){ graph[i][j] = 1; graph[j][i] = 1; } } } // 图构 <SUF> return dijskra(graph,n,end)==0?0:dijskra(graph,n,end)+1; } // 计算两个单词之间是否只有1个字符不相同,是则为true反之false public boolean calcDis(String s1,String s2){ // 因为题目说了所有的单词具有一样的长度,所以没有必要进行长度的判断 int dis = 0; for(int i = 0;i<s1.length();i++) if(s1.charAt(i) != s2.charAt(i)) dis++; return dis == 1; } // dijskra public int dijskra(int[][] graph,int start,int end){ int n = graph.length; // 存放start到各个下标节点的距离,初始化 int[] distance = new int[n]; for(int i = 0;i<n;i++) distance[i] = graph[start][i]; distance[start] = 0; // 判断start到下标位置的节点是否有最短路径 boolean[] visited = new boolean[n]; visited[start] = true; // 遍历除了start本身节点的所有节点、也就是说循环n-1次 for(int i = 1;i < n;i++){ // 当前最短距离 int minDistance = Integer.MAX_VALUE; // 当前最短距离的节点下标 int minIndex = 1; // 遍历所有的节点,找到距离start的最近的节点 for(int j =0;j < n;j++){ if(!visited[j] && distance[j] != 0 && distance[j]<=minDistance){ minDistance = distance[j]; minIndex = j; } } // 标记最近距离节点已经找到了 visited[minIndex] = true; // 根据刚刚找到的最近距离节点,更新start节点到其他节点的距离 for(int j=0;j< n;j++){ // 如果已更新的最短距离节点可以到达当前便利的节点 if(graph[minIndex][j] == 1){ if(distance[j] != 0) distance[j] = Math.min(distance[j],distance[minIndex] + graph[minIndex][j]); else distance[j] = distance[minIndex] + graph[minIndex][j]; } } } return distance[end]; } }
0
888
20
987
23
1,019
19
987
23
1,316
34
false
false
false
false
false
true
29804_3
package com.cccll.proxy; import com.cccll.entity.RpcServiceProperties; import com.cccll.remoting.dto.RpcMessageChecker; import com.cccll.remoting.dto.RpcRequest; import com.cccll.remoting.dto.RpcResponse; import com.cccll.remoting.transport.ClientTransport; import com.cccll.remoting.transport.netty.client.NettyClientTransport; import com.cccll.remoting.transport.socket.SocketRpcClient; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.UUID; import java.util.concurrent.CompletableFuture; /** * 动态代理类。当动态代理对象调用一个方法的时候,实际调用的是下面的 invoke 方法。 * 正是因为动态代理才让客户端调用的远程方法像是调用本地方法一样(屏蔽了中间过程) * * @author cccll */ @Slf4j public class RpcClientProxy implements InvocationHandler { /** * 用于发送请求给服务端,对应socket和netty两种实现方式 */ private final ClientTransport clientTransport; private final RpcServiceProperties rpcServiceProperties; public RpcClientProxy(ClientTransport clientTransport, RpcServiceProperties rpcServiceProperties) { this.clientTransport = clientTransport; if (rpcServiceProperties.getGroup() == null) { rpcServiceProperties.setGroup(""); } if (rpcServiceProperties.getVersion() == null) { rpcServiceProperties.setVersion(""); } this.rpcServiceProperties = rpcServiceProperties; } public RpcClientProxy(ClientTransport clientTransport) { this.clientTransport = clientTransport; this.rpcServiceProperties = RpcServiceProperties.builder().group("").version("").build(); } /** * 通过 Proxy.newProxyInstance() 方法获取某个类的代理对象 */ @SuppressWarnings("unchecked") public <T> T getProxy(Class<T> clazz) { return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class<?>[]{clazz}, this); } /** * 当你使用代理对象调用方法的时候实际会调用到这个方法。代理对象就是你通过上面的 getProxy 方法获取到的对象。 */ @SneakyThrows @SuppressWarnings("unchecked") @Override public Object invoke(Object proxy, Method method, Object[] args) { log.info("invoked method: [{}]", method.getName()); //构建rpc请求体 RpcRequest rpcRequest = RpcRequest.builder().methodName(method.getName()) .parameters(args) .interfaceName(method.getDeclaringClass().getName()) .paramTypes(method.getParameterTypes()) .requestId(UUID.randomUUID().toString()) .group(rpcServiceProperties.getGroup()) .version(rpcServiceProperties.getVersion()) .build(); RpcResponse<Object> rpcResponse = null; //根据clientTransport的实际类型,会以不同方式发送rpc请求体,然后得到其rpcResponse,返回 if (clientTransport instanceof NettyClientTransport) { CompletableFuture<RpcResponse<Object>> completableFuture = (CompletableFuture<RpcResponse<Object>>) clientTransport.sendRpcRequest(rpcRequest); //此处有可能会阻塞,但不会一直阻塞,如果请求发生错误,会在添加的 中调用CompletableFuture.completeExceptionally(future.cause()),即可解除阻塞 rpcResponse = completableFuture.get(); } if (clientTransport instanceof SocketRpcClient) { rpcResponse = (RpcResponse<Object>) clientTransport.sendRpcRequest(rpcRequest); } //校验 RpcResponse 和 RpcRequest RpcMessageChecker.check(rpcResponse, rpcRequest); return rpcResponse.getData(); } }
CCCLL/lrpc
lrpc-framework/src/main/java/com/cccll/proxy/RpcClientProxy.java
890
/** * 当你使用代理对象调用方法的时候实际会调用到这个方法。代理对象就是你通过上面的 getProxy 方法获取到的对象。 */
block_comment
zh-cn
package com.cccll.proxy; import com.cccll.entity.RpcServiceProperties; import com.cccll.remoting.dto.RpcMessageChecker; import com.cccll.remoting.dto.RpcRequest; import com.cccll.remoting.dto.RpcResponse; import com.cccll.remoting.transport.ClientTransport; import com.cccll.remoting.transport.netty.client.NettyClientTransport; import com.cccll.remoting.transport.socket.SocketRpcClient; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.UUID; import java.util.concurrent.CompletableFuture; /** * 动态代理类。当动态代理对象调用一个方法的时候,实际调用的是下面的 invoke 方法。 * 正是因为动态代理才让客户端调用的远程方法像是调用本地方法一样(屏蔽了中间过程) * * @author cccll */ @Slf4j public class RpcClientProxy implements InvocationHandler { /** * 用于发送请求给服务端,对应socket和netty两种实现方式 */ private final ClientTransport clientTransport; private final RpcServiceProperties rpcServiceProperties; public RpcClientProxy(ClientTransport clientTransport, RpcServiceProperties rpcServiceProperties) { this.clientTransport = clientTransport; if (rpcServiceProperties.getGroup() == null) { rpcServiceProperties.setGroup(""); } if (rpcServiceProperties.getVersion() == null) { rpcServiceProperties.setVersion(""); } this.rpcServiceProperties = rpcServiceProperties; } public RpcClientProxy(ClientTransport clientTransport) { this.clientTransport = clientTransport; this.rpcServiceProperties = RpcServiceProperties.builder().group("").version("").build(); } /** * 通过 Proxy.newProxyInstance() 方法获取某个类的代理对象 */ @SuppressWarnings("unchecked") public <T> T getProxy(Class<T> clazz) { return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class<?>[]{clazz}, this); } /** * 当你使 <SUF>*/ @SneakyThrows @SuppressWarnings("unchecked") @Override public Object invoke(Object proxy, Method method, Object[] args) { log.info("invoked method: [{}]", method.getName()); //构建rpc请求体 RpcRequest rpcRequest = RpcRequest.builder().methodName(method.getName()) .parameters(args) .interfaceName(method.getDeclaringClass().getName()) .paramTypes(method.getParameterTypes()) .requestId(UUID.randomUUID().toString()) .group(rpcServiceProperties.getGroup()) .version(rpcServiceProperties.getVersion()) .build(); RpcResponse<Object> rpcResponse = null; //根据clientTransport的实际类型,会以不同方式发送rpc请求体,然后得到其rpcResponse,返回 if (clientTransport instanceof NettyClientTransport) { CompletableFuture<RpcResponse<Object>> completableFuture = (CompletableFuture<RpcResponse<Object>>) clientTransport.sendRpcRequest(rpcRequest); //此处有可能会阻塞,但不会一直阻塞,如果请求发生错误,会在添加的 中调用CompletableFuture.completeExceptionally(future.cause()),即可解除阻塞 rpcResponse = completableFuture.get(); } if (clientTransport instanceof SocketRpcClient) { rpcResponse = (RpcResponse<Object>) clientTransport.sendRpcRequest(rpcRequest); } //校验 RpcResponse 和 RpcRequest RpcMessageChecker.check(rpcResponse, rpcRequest); return rpcResponse.getData(); } }
0
790
36
890
34
912
35
890
34
1,185
60
false
false
false
false
false
true
65529_65
package com.example.lishidatiapp.fragment; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.DefaultItemAnimator; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.example.lishidatiapp.R; import com.example.lishidatiapp.RegisterActivity; import com.example.lishidatiapp.activity.EventsAdapter; import com.example.lishidatiapp.bean.BigEvent; import com.example.lishidatiapp.bean.Const; import com.example.lishidatiapp.httpinfo.OkHttpUtils; import com.example.lishidatiapp.interfaces.OnCallBack; import com.example.lishidatiapp.util.JsonUtils; import com.example.lishidatiapp.util.ToastUtils; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; //public class HomeFragment extends Fragment { // EventsAdapter medicationsAdapter; // List<BigEvent> bigEventList; // RecyclerView recyclerView; // View view; // public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // // view = inflater.inflate(R.layout.fragment_home, container, false); // bigEventList=new ArrayList<>(); // // 事件情况 // recyclerView = view.findViewById(R.id.event_recycle); // // ToLiShiList(); // // return view; // } // private void ToLiShiList() { // //// OkHttpUtils okHttpUtils = new OkHttpUtils(); //// okHttpUtils.requestDataFromeGet(Const.getHttpUrl(Const.sql)+"?query=getArticle&key=article"); //// okHttpUtils.setOnCallBack(new OnCallBack() { //// @Override //// public void callSuccessBack(String json) { //// //// try { //// JSONArray jsonArray = new JSONArray(json); //// //// int length = jsonArray.length(); //// int[] array = new int[length]; //// //// for (int i = 0; i < length; i++) { //// JSONObject object= (JSONObject) jsonArray.get(i); //// int id=object.getInt("id"); //// String shortname=object.getString("shortname"); //// String introduce=object.getString("introduce"); //// String photo=object.getString("photo"); //// BigEvent event=new BigEvent(); //// event.setId(id); //// event.setIntroduce(introduce); //// event.setShortname(shortname); //// event.setPhoto(photo); //// bigEventList.add(event); //// } //// LinearLayoutManager manager = new LinearLayoutManager(getContext()); //// manager.setOrientation(LinearLayoutManager.VERTICAL); //// medicationsAdapter = new EventsAdapter(getContext(), bigEventList); //// recyclerView.setAdapter(medicationsAdapter); //// recyclerView.setItemAnimator(new DefaultItemAnimator()); //// recyclerView.setLayoutManager(manager); //// recyclerView.addItemDecoration(new CustomItemDecoration()); //// }catch (Exception e){ //// e.printStackTrace(); //// //链接错误信息 //// ToastUtils.showToast(getContext(), e.toString()); //// } //// } //// @Override //// public void callErrorBack(String json) { //// //链接错误信息 //// ToastUtils.showToast(getContext(), json); //// } //// }); // // } // public static class CustomItemDecoration extends RecyclerView.ItemDecoration { // @Override // public void getItemOffsets(Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) { // // 设置元素之间的偏移量为0,即去掉分割线 // outRect.set(0, 0, 0, 0); // } // } // private static final String ARG_PARAM1 = "param1"; // private static final String ARG_PARAM2 = "param2"; // public static HomeFragment newInstance( String param1, String param2) { // HomeFragment fragment = new HomeFragment(); // Bundle args = new Bundle(); // args.putString(ARG_PARAM1, param1); // args.putString(ARG_PARAM2, param2); // fragment.setArguments(args); // return fragment; // } // //} public class HomeFragment extends Fragment { private final List<BigEvent> bigEventList = new ArrayList<>(); EventsAdapter medicationsAdapter; View view; Context context; void initData() { @SuppressLint("UseCompatLoadingForDrawables") Drawable drawable1 = getResources().getDrawable(R.drawable.mingchao); BigEvent bigEvent1 = new BigEvent(1, "明朝", "1368年-1644年", "明朝是中国历史上最后由汉族建立的大一统王朝, 历经12世、16位皇帝,国祚276年。", drawable1); bigEventList.add(bigEvent1); @SuppressLint("UseCompatLoadingForDrawables") Drawable drawable2 = getResources().getDrawable(R.drawable.jingnan); BigEvent bigEvent2 = new BigEvent(2, "靖难之役", "1399年8月6日", "靖难之役又称靖难之变是中国明朝初年建文帝在位时发生的一场因削藩政策引发的争夺皇位的内战。", drawable2); bigEventList.add(bigEvent2); @SuppressLint("UseCompatLoadingForDrawables") Drawable drawable3 = getResources().getDrawable(R.drawable.nuomandi); BigEvent bigEvent3 = new BigEvent(3, "诺曼底登陆", "1944年", "诺曼底登陆,代号海王行动,是第二次世界大战西方盟军在欧洲西线战场发起的一场大规模攻势。", drawable3); bigEventList.add(bigEvent3); @SuppressLint("UseCompatLoadingForDrawables") Drawable drawable4 = getResources().getDrawable(R.drawable.songlu); BigEvent bigEvent4 = new BigEvent(4, "淞沪会战", "1937年11月", "日军占领北平、天津后,在南方又集中兵力约28万人,陆海空三军联合猛烈进攻上海、南京地区。", drawable4); bigEventList.add(bigEvent4); @SuppressLint("UseCompatLoadingForDrawables") Drawable drawable5 = getResources().getDrawable(R.drawable.zhongtudao); BigEvent bigEvent5 = new BigEvent(5, "中途岛海战", "1942年", "中途岛海战是第二次世界大战中美国海军和日本海军在中途岛附近海域进行的一场大规模海战。", drawable5); bigEventList.add(bigEvent5); } public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_home, container, false); context = view.getContext(); // 事件情况 RecyclerView recyclerView = view.findViewById(R.id.event_recycle); initData(); LinearLayoutManager manager = new LinearLayoutManager(context); manager.setOrientation(LinearLayoutManager.VERTICAL); medicationsAdapter = new EventsAdapter(context, bigEventList); recyclerView.setAdapter(medicationsAdapter); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setLayoutManager(manager); recyclerView.addItemDecoration(new CustomItemDecoration()); return view; } @Override public void onDestroyView() { super.onDestroyView(); } public static class CustomItemDecoration extends RecyclerView.ItemDecoration { @Override public void getItemOffsets(Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) { // 设置元素之间的偏移量为0,即去掉分割线 outRect.set(0, 0, 0, 0); } } private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; public static HomeFragment newInstance(String param1, String param2) { HomeFragment fragment = new HomeFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } }
CCP101/visual-kg-history
android/app/src/main/java/com/example/lishidatiapp/fragment/HomeFragment.java
2,180
// 设置元素之间的偏移量为0,即去掉分割线
line_comment
zh-cn
package com.example.lishidatiapp.fragment; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.DefaultItemAnimator; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.example.lishidatiapp.R; import com.example.lishidatiapp.RegisterActivity; import com.example.lishidatiapp.activity.EventsAdapter; import com.example.lishidatiapp.bean.BigEvent; import com.example.lishidatiapp.bean.Const; import com.example.lishidatiapp.httpinfo.OkHttpUtils; import com.example.lishidatiapp.interfaces.OnCallBack; import com.example.lishidatiapp.util.JsonUtils; import com.example.lishidatiapp.util.ToastUtils; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; //public class HomeFragment extends Fragment { // EventsAdapter medicationsAdapter; // List<BigEvent> bigEventList; // RecyclerView recyclerView; // View view; // public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // // view = inflater.inflate(R.layout.fragment_home, container, false); // bigEventList=new ArrayList<>(); // // 事件情况 // recyclerView = view.findViewById(R.id.event_recycle); // // ToLiShiList(); // // return view; // } // private void ToLiShiList() { // //// OkHttpUtils okHttpUtils = new OkHttpUtils(); //// okHttpUtils.requestDataFromeGet(Const.getHttpUrl(Const.sql)+"?query=getArticle&key=article"); //// okHttpUtils.setOnCallBack(new OnCallBack() { //// @Override //// public void callSuccessBack(String json) { //// //// try { //// JSONArray jsonArray = new JSONArray(json); //// //// int length = jsonArray.length(); //// int[] array = new int[length]; //// //// for (int i = 0; i < length; i++) { //// JSONObject object= (JSONObject) jsonArray.get(i); //// int id=object.getInt("id"); //// String shortname=object.getString("shortname"); //// String introduce=object.getString("introduce"); //// String photo=object.getString("photo"); //// BigEvent event=new BigEvent(); //// event.setId(id); //// event.setIntroduce(introduce); //// event.setShortname(shortname); //// event.setPhoto(photo); //// bigEventList.add(event); //// } //// LinearLayoutManager manager = new LinearLayoutManager(getContext()); //// manager.setOrientation(LinearLayoutManager.VERTICAL); //// medicationsAdapter = new EventsAdapter(getContext(), bigEventList); //// recyclerView.setAdapter(medicationsAdapter); //// recyclerView.setItemAnimator(new DefaultItemAnimator()); //// recyclerView.setLayoutManager(manager); //// recyclerView.addItemDecoration(new CustomItemDecoration()); //// }catch (Exception e){ //// e.printStackTrace(); //// //链接错误信息 //// ToastUtils.showToast(getContext(), e.toString()); //// } //// } //// @Override //// public void callErrorBack(String json) { //// //链接错误信息 //// ToastUtils.showToast(getContext(), json); //// } //// }); // // } // public static class CustomItemDecoration extends RecyclerView.ItemDecoration { // @Override // public void getItemOffsets(Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) { // // 设置元素之间的偏移量为0,即去掉分割线 // outRect.set(0, 0, 0, 0); // } // } // private static final String ARG_PARAM1 = "param1"; // private static final String ARG_PARAM2 = "param2"; // public static HomeFragment newInstance( String param1, String param2) { // HomeFragment fragment = new HomeFragment(); // Bundle args = new Bundle(); // args.putString(ARG_PARAM1, param1); // args.putString(ARG_PARAM2, param2); // fragment.setArguments(args); // return fragment; // } // //} public class HomeFragment extends Fragment { private final List<BigEvent> bigEventList = new ArrayList<>(); EventsAdapter medicationsAdapter; View view; Context context; void initData() { @SuppressLint("UseCompatLoadingForDrawables") Drawable drawable1 = getResources().getDrawable(R.drawable.mingchao); BigEvent bigEvent1 = new BigEvent(1, "明朝", "1368年-1644年", "明朝是中国历史上最后由汉族建立的大一统王朝, 历经12世、16位皇帝,国祚276年。", drawable1); bigEventList.add(bigEvent1); @SuppressLint("UseCompatLoadingForDrawables") Drawable drawable2 = getResources().getDrawable(R.drawable.jingnan); BigEvent bigEvent2 = new BigEvent(2, "靖难之役", "1399年8月6日", "靖难之役又称靖难之变是中国明朝初年建文帝在位时发生的一场因削藩政策引发的争夺皇位的内战。", drawable2); bigEventList.add(bigEvent2); @SuppressLint("UseCompatLoadingForDrawables") Drawable drawable3 = getResources().getDrawable(R.drawable.nuomandi); BigEvent bigEvent3 = new BigEvent(3, "诺曼底登陆", "1944年", "诺曼底登陆,代号海王行动,是第二次世界大战西方盟军在欧洲西线战场发起的一场大规模攻势。", drawable3); bigEventList.add(bigEvent3); @SuppressLint("UseCompatLoadingForDrawables") Drawable drawable4 = getResources().getDrawable(R.drawable.songlu); BigEvent bigEvent4 = new BigEvent(4, "淞沪会战", "1937年11月", "日军占领北平、天津后,在南方又集中兵力约28万人,陆海空三军联合猛烈进攻上海、南京地区。", drawable4); bigEventList.add(bigEvent4); @SuppressLint("UseCompatLoadingForDrawables") Drawable drawable5 = getResources().getDrawable(R.drawable.zhongtudao); BigEvent bigEvent5 = new BigEvent(5, "中途岛海战", "1942年", "中途岛海战是第二次世界大战中美国海军和日本海军在中途岛附近海域进行的一场大规模海战。", drawable5); bigEventList.add(bigEvent5); } public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_home, container, false); context = view.getContext(); // 事件情况 RecyclerView recyclerView = view.findViewById(R.id.event_recycle); initData(); LinearLayoutManager manager = new LinearLayoutManager(context); manager.setOrientation(LinearLayoutManager.VERTICAL); medicationsAdapter = new EventsAdapter(context, bigEventList); recyclerView.setAdapter(medicationsAdapter); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setLayoutManager(manager); recyclerView.addItemDecoration(new CustomItemDecoration()); return view; } @Override public void onDestroyView() { super.onDestroyView(); } public static class CustomItemDecoration extends RecyclerView.ItemDecoration { @Override public void getItemOffsets(Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) { // 设置 <SUF> outRect.set(0, 0, 0, 0); } } private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; public static HomeFragment newInstance(String param1, String param2) { HomeFragment fragment = new HomeFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } }
0
1,735
14
2,180
16
2,097
13
2,180
16
2,581
29
false
false
false
false
false
true
26634_2
// Product.java public class Product { public static String[] TYPES = { "全部", "电脑", "手机", "书籍" }; // 所有类型 private String id; //产品编号 private String name; // 名称 private String type; // 类型 private double price; // 价格 private int number; // 库存 public Product(String line) { String[] args = line.split(";"); id = args[0]; name = args[1]; type = args[2]; price = Double.parseDouble(args[3]); number = Integer.parseInt(args[4]); } public String toString() { return id + ";" + name + ";" + type + ";" + price + ";" + number; } public String getType() { return type; } public String getId() { return id; } public int getNumber() { return number; } }
CColike/Soochow-University-CS
Java/final/Project.java
238
//产品编号
line_comment
zh-cn
// Product.java public class Product { public static String[] TYPES = { "全部", "电脑", "手机", "书籍" }; // 所有类型 private String id; //产品 <SUF> private String name; // 名称 private String type; // 类型 private double price; // 价格 private int number; // 库存 public Product(String line) { String[] args = line.split(";"); id = args[0]; name = args[1]; type = args[2]; price = Double.parseDouble(args[3]); number = Integer.parseInt(args[4]); } public String toString() { return id + ";" + name + ";" + type + ";" + price + ";" + number; } public String getType() { return type; } public String getId() { return id; } public int getNumber() { return number; } }
0
199
3
238
3
234
3
238
3
286
7
false
false
false
false
false
true
56703_4
package art; import java.util.*; import faultZone.FaultZone; import faultZone.FaultZone_Point_Square; import util.*; /** * RRT(2004) * 论文:A revisit of adaptive random testing by restriction, * 大致方法: * 1. 随机选择一个用例进行测试 * 2. 设置一个限制倍数r * 3. 利用r计算以之前测试的用例为中心的排除半径 * 4. 将半径内的所有用例排除,生成新的测试用例域,从中随机选择下一个用例 */ public class RRT extends AbstractART{ double rate = 0.8; //用输入来初始化该算法 public RRT(DomainBoundary inputBoundary) { this.inputBoundary = inputBoundary; } public static void main(String args[]){ int times = 3000;//一次执行,该算法就重复3000次 long sums = 0;// 初始化使用的测试用例数 int temp = 0;// 初始化测试用例落在失效域的使用的测试用例的个数 ArrayList<Integer> result = new ArrayList<>(); //统一p=2,表示计算输入间距离按正常方法计算(各维度距离平方和开平方) double p = Parameters.lp; double failrate = 0.005; int dimension = 2; //二维输入(即一次输入两个参数),两个数值参数的上限(5000)、下限(5000)相同 DomainBoundary bd = new DomainBoundary(dimension, -5000, 5000); for (int i = 1; i <= times; i++) { //指定使用这种fault zone FaultZone fz = new FaultZone_Point_Square(bd, failrate); RRT rrt = new RRT(bd); //小run一下 temp = rrt.runWithFaultZone(fz); result.add(temp); System.out.println("第" + i + "次试验F_Measure:" + temp); sums += temp; } System.out.println("RRT当前参数:dimension = " + dimension + " lp = " + p + " failure-rate = " + failrate); System.out.println("Fm: " + sums / (double) times + " 且最后的Fart/Frt: " + sums / (double) times * failrate);// 平均每次使用的测试用例数 } public Double calR(double rate, Testcase tc){ ArrayList<Double>Tc=tc.list; Double size = Collections.max(Tc) - Collections.min(Tc); System.out.println(size); int len = Tc.size(); Double r = Math.pow(rate*size,1.0/len); return r; } @Override public Testcase bestCandidate() { this.candidate.clear(); Testcase tc = new Testcase(inputBoundary); DomainBoundary newBoundary = inputBoundary; double r = calR(rate , tc); int count = 0; while(count < inputBoundary.getList().size() && ((inputBoundary.getList().get(count).getMin() + r)> tc.getValue(count) || (inputBoundary.getList().get(count).getMax() - r) < tc.getValue(count))) { count++; tc = new Testcase(inputBoundary); } return tc; } @Override public void testEfficiency(int pointNum) { // 计算效率测试 Testcase testcase = new Testcase(inputBoundary); while (total.size() < pointNum) { // 随机生成n个候选的测试用例 total.add(testcase); candidate = new ArrayList<Testcase>(); for (int i = 0; i < 10; i++) { candidate.add(new Testcase(inputBoundary)); } testcase = bestCandidate(); } } }
CDHZAYN/numerical-program-ART
src/art/RRT.java
927
// 初始化测试用例落在失效域的使用的测试用例的个数
line_comment
zh-cn
package art; import java.util.*; import faultZone.FaultZone; import faultZone.FaultZone_Point_Square; import util.*; /** * RRT(2004) * 论文:A revisit of adaptive random testing by restriction, * 大致方法: * 1. 随机选择一个用例进行测试 * 2. 设置一个限制倍数r * 3. 利用r计算以之前测试的用例为中心的排除半径 * 4. 将半径内的所有用例排除,生成新的测试用例域,从中随机选择下一个用例 */ public class RRT extends AbstractART{ double rate = 0.8; //用输入来初始化该算法 public RRT(DomainBoundary inputBoundary) { this.inputBoundary = inputBoundary; } public static void main(String args[]){ int times = 3000;//一次执行,该算法就重复3000次 long sums = 0;// 初始化使用的测试用例数 int temp = 0;// 初始 <SUF> ArrayList<Integer> result = new ArrayList<>(); //统一p=2,表示计算输入间距离按正常方法计算(各维度距离平方和开平方) double p = Parameters.lp; double failrate = 0.005; int dimension = 2; //二维输入(即一次输入两个参数),两个数值参数的上限(5000)、下限(5000)相同 DomainBoundary bd = new DomainBoundary(dimension, -5000, 5000); for (int i = 1; i <= times; i++) { //指定使用这种fault zone FaultZone fz = new FaultZone_Point_Square(bd, failrate); RRT rrt = new RRT(bd); //小run一下 temp = rrt.runWithFaultZone(fz); result.add(temp); System.out.println("第" + i + "次试验F_Measure:" + temp); sums += temp; } System.out.println("RRT当前参数:dimension = " + dimension + " lp = " + p + " failure-rate = " + failrate); System.out.println("Fm: " + sums / (double) times + " 且最后的Fart/Frt: " + sums / (double) times * failrate);// 平均每次使用的测试用例数 } public Double calR(double rate, Testcase tc){ ArrayList<Double>Tc=tc.list; Double size = Collections.max(Tc) - Collections.min(Tc); System.out.println(size); int len = Tc.size(); Double r = Math.pow(rate*size,1.0/len); return r; } @Override public Testcase bestCandidate() { this.candidate.clear(); Testcase tc = new Testcase(inputBoundary); DomainBoundary newBoundary = inputBoundary; double r = calR(rate , tc); int count = 0; while(count < inputBoundary.getList().size() && ((inputBoundary.getList().get(count).getMin() + r)> tc.getValue(count) || (inputBoundary.getList().get(count).getMax() - r) < tc.getValue(count))) { count++; tc = new Testcase(inputBoundary); } return tc; } @Override public void testEfficiency(int pointNum) { // 计算效率测试 Testcase testcase = new Testcase(inputBoundary); while (total.size() < pointNum) { // 随机生成n个候选的测试用例 total.add(testcase); candidate = new ArrayList<Testcase>(); for (int i = 0; i < 10; i++) { candidate.add(new Testcase(inputBoundary)); } testcase = bestCandidate(); } } }
0
863
16
927
17
946
13
927
17
1,203
29
false
false
false
false
false
true
41202_1
package works; public class Example12_1 { public static void main(String args[]) { //主线程 Speak speak1=new Speak("大象"); Speak speak2=new Speak("轿车"); Thread speakElephant =new Thread(speak1); Thread speakCar = new Thread(speak2); speakElephant.start(); //启动线程 speakCar.start(); //启动线程 for(int i=1;i<=15;i++) { System.out.print("主人"+i+" "); } } } class Speak implements Runnable { String name; Speak(String name) { this.name=name; } public void run() { for(int i=1;i<=20;i++) { System.out.print(name+i+" "); } } }
CHANGEA-code/JavaCode
JAVA实验1/src/works/Example12_1.java
222
//启动线程
line_comment
zh-cn
package works; public class Example12_1 { public static void main(String args[]) { //主线程 Speak speak1=new Speak("大象"); Speak speak2=new Speak("轿车"); Thread speakElephant =new Thread(speak1); Thread speakCar = new Thread(speak2); speakElephant.start(); //启动 <SUF> speakCar.start(); //启动线程 for(int i=1;i<=15;i++) { System.out.print("主人"+i+" "); } } } class Speak implements Runnable { String name; Speak(String name) { this.name=name; } public void run() { for(int i=1;i<=20;i++) { System.out.print(name+i+" "); } } }
0
179
5
222
4
226
4
222
4
266
8
false
false
false
false
false
true
63372_4
package pojo; import java.util.Date; import com.alibaba.fastjson.annotation.JSONField; public class BillSummary { private Integer totalCount=0;// 当日开桌数 private Double cash=0.0;// 现金 private Double mobilePay=0.0;// 移动支付 private Double byBank=0.0;// 刷卡 private Double debtorMoney=0.0;// 挂账 private Double discountMoney=0.0;// 折扣 private Double totalMoney=0.0;// 当日实际收入 private Double realMoney=0.0;// 实际收入 @JSONField(format="yyyy-MM-dd") private Date todayDate;// 当日日期 public BillSummary() { }; public Integer getTotalCount() { return totalCount; } public void setTotalCount(Integer totalCount) { this.totalCount = totalCount; } public Double getCash() { return cash; } public void setCash(Double cash) { this.cash = cash; } public Double getMobilePay() { return mobilePay; } public void setMobilePay(Double mobilePay) { this.mobilePay = mobilePay; } public Double getByBank() { return byBank; } public void setByBank(Double byBank) { this.byBank = byBank; } public Double getDebtorMoney() { return debtorMoney; } public void setDebtorMoney(Double debtor) { this.debtorMoney = debtor; } public Double getDiscountMoney() { return discountMoney; } public void setDiscountMoney(Double discountMoney) { this.discountMoney = discountMoney; } public Double getTotalMoney() { return totalMoney; } public void setTotalMoney(Double totalMoney) { this.totalMoney = totalMoney; } public Double getRealMoney() { return realMoney; } public void setRealMoney(Double realMoney) { this.realMoney = realMoney; } public Date getTodayDate() { return todayDate; } public void setTodayDate(Date todayDate) { this.todayDate = todayDate; } }
CHANGEX929/RCMS
src/pojo/BillSummary.java
588
// 当日日期
line_comment
zh-cn
package pojo; import java.util.Date; import com.alibaba.fastjson.annotation.JSONField; public class BillSummary { private Integer totalCount=0;// 当日开桌数 private Double cash=0.0;// 现金 private Double mobilePay=0.0;// 移动支付 private Double byBank=0.0;// 刷卡 private Double debtorMoney=0.0;// 挂账 private Double discountMoney=0.0;// 折扣 private Double totalMoney=0.0;// 当日实际收入 private Double realMoney=0.0;// 实际收入 @JSONField(format="yyyy-MM-dd") private Date todayDate;// 当日 <SUF> public BillSummary() { }; public Integer getTotalCount() { return totalCount; } public void setTotalCount(Integer totalCount) { this.totalCount = totalCount; } public Double getCash() { return cash; } public void setCash(Double cash) { this.cash = cash; } public Double getMobilePay() { return mobilePay; } public void setMobilePay(Double mobilePay) { this.mobilePay = mobilePay; } public Double getByBank() { return byBank; } public void setByBank(Double byBank) { this.byBank = byBank; } public Double getDebtorMoney() { return debtorMoney; } public void setDebtorMoney(Double debtor) { this.debtorMoney = debtor; } public Double getDiscountMoney() { return discountMoney; } public void setDiscountMoney(Double discountMoney) { this.discountMoney = discountMoney; } public Double getTotalMoney() { return totalMoney; } public void setTotalMoney(Double totalMoney) { this.totalMoney = totalMoney; } public Double getRealMoney() { return realMoney; } public void setRealMoney(Double realMoney) { this.realMoney = realMoney; } public Date getTodayDate() { return todayDate; } public void setTodayDate(Date todayDate) { this.todayDate = todayDate; } }
0
453
4
588
4
556
4
588
4
707
6
false
false
false
false
false
true
22536_8
package com.wzb.member.entity; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import java.io.Serializable; import lombok.Data; import lombok.EqualsAndHashCode; /** * <p> * * </p> * * @author wzb */ @Data @EqualsAndHashCode(callSuper = false) @TableName("tb_teacher") public class Teacher implements Serializable { private static final long serialVersionUID = 1L; /** * 主键 */ @TableId(value = "id", type = IdType.AUTO) private Integer id; /** * 教工号 */ private String tchNum; /** * 姓名 */ private String name; /** * email */ private String email; /** * 手机号码 */ private String mobile; /** * 办公室 */ private String office; /** * 职级 */ private Integer level; /** * 所在组号 */ private Integer teamId; /** * 账户id */ private Integer uid; /** * 所在组名 * * @TableField(exist = false): 标识它不是tb_teacher表中字段,不然会报错 */ @TableField(exist = false) private String teamName; }
CHRIS-WiNG/LAB-mms
wzb-member-api/src/main/java/com/wzb/member/entity/Teacher.java
362
/** * 所在组号 */
block_comment
zh-cn
package com.wzb.member.entity; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import java.io.Serializable; import lombok.Data; import lombok.EqualsAndHashCode; /** * <p> * * </p> * * @author wzb */ @Data @EqualsAndHashCode(callSuper = false) @TableName("tb_teacher") public class Teacher implements Serializable { private static final long serialVersionUID = 1L; /** * 主键 */ @TableId(value = "id", type = IdType.AUTO) private Integer id; /** * 教工号 */ private String tchNum; /** * 姓名 */ private String name; /** * email */ private String email; /** * 手机号码 */ private String mobile; /** * 办公室 */ private String office; /** * 职级 */ private Integer level; /** * 所在组 <SUF>*/ private Integer teamId; /** * 账户id */ private Integer uid; /** * 所在组名 * * @TableField(exist = false): 标识它不是tb_teacher表中字段,不然会报错 */ @TableField(exist = false) private String teamName; }
0
317
11
354
9
381
11
354
9
481
12
false
false
false
false
false
true
42269_4
/** * @Package: site.ckylin.tools.varutils * @author: CKylinMC * @description: * @date: 2020-08-11 13:05 */ package site.ckylin.tools.varutils; public class Is { /** * 判断字符串是否为空 * * @param value the value * @return the boolean */ public static boolean empty(String value) { if (value == null) return true; return value.trim().length() < 1; } /** * 检查字符串是否不是数字 * <a href="https://www.cnblogs.com/gaoyoubo/archive/2010/09/15/1965080.html">参考自 "Java实现isNaN - Me疯子_(~ 的博客"</a> * * @param value the value * @return the boolean */ public static boolean NaN(String value) { boolean flag = false; if (value != null && !"".equals(value.trim())) { //如果没有小数点 if (!value.contains(".")) { if (!value.matches("\\d+")) { //不是数字 flag = true; } } else if (value.indexOf(".") == 1) { String[] s_arr = value.split("\\."); String s1 = s_arr[0]; String s2 = s_arr[1]; if ((!s1.matches("\\d+")) || (!s2.matches("\\d+"))) { //不是数字 flag = true; } } } else { flag = true; } return flag; } }
CKylinMC/Helper
src/site/ckylin/tools/varutils/Is.java
400
//不是数字
line_comment
zh-cn
/** * @Package: site.ckylin.tools.varutils * @author: CKylinMC * @description: * @date: 2020-08-11 13:05 */ package site.ckylin.tools.varutils; public class Is { /** * 判断字符串是否为空 * * @param value the value * @return the boolean */ public static boolean empty(String value) { if (value == null) return true; return value.trim().length() < 1; } /** * 检查字符串是否不是数字 * <a href="https://www.cnblogs.com/gaoyoubo/archive/2010/09/15/1965080.html">参考自 "Java实现isNaN - Me疯子_(~ 的博客"</a> * * @param value the value * @return the boolean */ public static boolean NaN(String value) { boolean flag = false; if (value != null && !"".equals(value.trim())) { //如果没有小数点 if (!value.contains(".")) { if (!value.matches("\\d+")) { //不是 <SUF> flag = true; } } else if (value.indexOf(".") == 1) { String[] s_arr = value.split("\\."); String s1 = s_arr[0]; String s2 = s_arr[1]; if ((!s1.matches("\\d+")) || (!s2.matches("\\d+"))) { //不是数字 flag = true; } } } else { flag = true; } return flag; } }
0
376
3
400
3
430
3
400
3
482
5
false
false
false
false
false
true
40698_40
package src.client; import java.nio.file.Files; import java.nio.file.Paths; import java.io.*; import java.awt.event.*; import java.awt.*; import javax.swing.*; import javax.swing.text.BadLocationException; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.StyleConstants; //聊天功能 public class WorkChat implements Runnable{ DataOutputStream outputToClient = ClientMain.outputToServer; String friendName; JFrame frame = new JFrame(); JTextPane outframe = new JTextPane(); JTextField inframe = new JTextField(); JScrollPane scrollPane;//滚动输出框 JPanel inputPanel = new JPanel();//输入框 boolean isWindowOpen = false;//记录窗口是否打开 WorkChat(String friendName) { this.friendName = friendName; } //首次开启与对方的聊天窗口 public void run() { // 设置窗口 frame.setTitle(friendName); frame.setLocation(350, 200); frame.setLayout(new BorderLayout()); // 输出框 outframe.setEditable(false); scrollPane = new JScrollPane(outframe); frame.add(scrollPane, BorderLayout.CENTER); // 输入框 inputPanel.setLayout(new BorderLayout()); inputPanel.add(inframe, BorderLayout.CENTER); inframe.addActionListener(new inframeListener()); JButton fileButton = new JButton("选择文件"); fileButton.addActionListener(new FileButtonListener()); inputPanel.add(fileButton, BorderLayout.EAST); frame.add(inputPanel, BorderLayout.SOUTH); frame.addWindowListener(new CloseChat()); frame.setSize(600, 400); frame.setVisible(true); isWindowOpen = true; } //再次开启与对方的聊天窗口,组件不需要再设置 public void createWindow(){ // 设置窗口 frame.setTitle(friendName); frame.setLocation(350, 200); frame.setLayout(new BorderLayout()); // 输出框 frame.add(scrollPane, BorderLayout.CENTER); // 输入框 frame.add(inputPanel, BorderLayout.SOUTH); frame.setSize(600, 400); frame.setVisible(true); isWindowOpen = true; } // 监听输入框,负责发送信息 private class inframeListener implements ActionListener { public void actionPerformed(ActionEvent e) { String tempStr = inframe.getText().trim(); // 得到输入框输入的字符串 inframe.setText(""); try { //告诉服务端这是一个消息 outputToClient.writeUTF("send-message"); outputToClient.writeUTF(friendName); //消息内容 outputToClient.writeUTF(tempStr); outputToClient.flush(); //显示在自己的窗口上 outframe.getStyledDocument().insertString(outframe.getStyledDocument().getLength(), "我:\n", new SimpleAttributeSet(){{ StyleConstants.setForeground(this, Color.BLUE); }}); outframe.getStyledDocument().insertString(outframe.getStyledDocument().getLength(), tempStr+"\n\n", null); } catch (IOException e1) { e1.printStackTrace(); } catch (BadLocationException e1) { e1.printStackTrace(); } } } //响应按钮,负责发送文件 private class FileButtonListener implements ActionListener { public void actionPerformed(ActionEvent e){ JFileChooser fileChooser = new JFileChooser();//选择文件 fileChooser.setCurrentDirectory(new File("src/client/image")); int returnValue = fileChooser.showOpenDialog(null); if (returnValue == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile();//选择好的文件 try { outputToClient.writeUTF("send-file"); //告诉服务器这是一个文件 outputToClient.writeUTF(friendName); byte[] fileBytes = Files.readAllBytes(file.toPath()); outputToClient.writeUTF(file.getName()); // 发送文件名 outputToClient.writeInt(fileBytes.length); // 发送文件长度 outputToClient.write(fileBytes); // 发送文件内容 outputToClient.flush(); //图片类型的文件需要显示 if(isImageFile(file.getName())){ outframe.getStyledDocument().insertString(outframe.getStyledDocument().getLength(), "我: \n", new SimpleAttributeSet(){{ StyleConstants.setForeground(this, Color.BLUE); }}); String imagePath = file.getPath(); showImage(imagePath); }else{ outframe.getStyledDocument().insertString(outframe.getStyledDocument().getLength(), "我发送了文件: " + file.getName() + "\n\n", new SimpleAttributeSet(){{ StyleConstants.setForeground(this, Color.BLUE); }}); } } catch (IOException e2) { e2.printStackTrace(); } catch (BadLocationException e1) { e1.printStackTrace(); } } } } //接收信息并展示 public void showMessage(String str) throws BadLocationException{ if(str.equals("quit")){//接收到quit说明对方关闭了聊天 outframe.getStyledDocument().insertString(outframe.getStyledDocument().getLength(), "系统消息:对方已退出聊天\n\n", new SimpleAttributeSet(){{ StyleConstants.setForeground(this, Color.BLUE); }}); }else{ outframe.getStyledDocument().insertString(outframe.getStyledDocument().getLength(), "对方:\n", new SimpleAttributeSet(){{ StyleConstants.setForeground(this, Color.BLUE); }}); outframe.getStyledDocument().insertString(outframe.getStyledDocument().getLength(), str+"\n\n", null); } } //接收文件 public void handleFile(String fileName, int fileLength, byte[] fileBytes) throws IOException, BadLocationException{ //保存文件到本地 String savePath = "C:\\Users\\蔡乐\\Desktop\\" + fileName; Files.write(Paths.get(savePath), fileBytes); //若文件是图片,显示图片 if (isImageFile(fileName)) { outframe.getStyledDocument().insertString(outframe.getStyledDocument().getLength(), "对方: \n", new SimpleAttributeSet(){{ StyleConstants.setForeground(this, Color.BLUE); }}); showImage(savePath); } else outframe.getStyledDocument().insertString(outframe.getStyledDocument().getLength(), "已接收到文件:" + fileName + "\n\n", new SimpleAttributeSet(){{ StyleConstants.setForeground(this, Color.BLUE); }}); } //判断文件是否为图片 private boolean isImageFile(String fileName) { String extension = fileName.substring(fileName.lastIndexOf(".") + 1); return extension.equalsIgnoreCase("jpg") || extension.equalsIgnoreCase("png") || extension.equalsIgnoreCase("bmp"); } //显示图片 private void showImage(String savePath) throws BadLocationException{ ImageIcon icon = new ImageIcon(savePath); // 创建图标,使用指定路径的图像文件 Image image = icon.getImage(); // 获取图标的图像 Image scaledImage = image.getScaledInstance(100, 100, Image.SCALE_SMOOTH); // 将图像缩放 ImageIcon scaledIcon = new ImageIcon(scaledImage); // 创建一个新的图标,使用缩放后的图像 JLabel imageLabel = new JLabel(scaledIcon); // 创建一个标签,用于显示 imageLabel.addMouseListener(new ImageClickListener(savePath)); // 点击放大图片 outframe.setCaretPosition(outframe.getDocument().getLength()); // 设置光标位置到末尾 outframe.insertComponent(imageLabel); // 图像标签添加到文本框中 outframe.getStyledDocument().insertString(outframe.getStyledDocument().getLength(), "\n\n", null); } //点击放大图片 private class ImageClickListener extends MouseAdapter { private String imagePath; public ImageClickListener(String path) { this.imagePath = path; } public void mouseClicked(MouseEvent e) { ImageIcon icon = new ImageIcon(imagePath); Image image = icon.getImage(); // 获取原始图片 int width = image.getWidth(null); // 获取原始图片宽度 int height = image.getHeight(null); // 获取原始图片高度 // 设置图片的最大宽度和高度 int maxWidth = 300; int maxHeight = 300; // 如果图片宽度或高度超过最大值,则按比例缩放 if (width > maxWidth || height > maxHeight) { if (width > height) { height = (int) (height * ((double) maxWidth / width)); width = maxWidth; } else { width = (int) (width * ((double) maxHeight / height)); height = maxHeight; } image = image.getScaledInstance(width, height, Image.SCALE_SMOOTH); } //弹出窗口展示放大图片 ImageIcon scaledIcon = new ImageIcon(image); JLabel label = new JLabel(); label.setIcon(scaledIcon); JOptionPane.showMessageDialog(null, label, "Scaled Image", JOptionPane.PLAIN_MESSAGE); } } //关闭聊天 class CloseChat extends WindowAdapter { public void windowClosing(WindowEvent e) { try { outputToClient.writeUTF("send-message"); outputToClient.writeUTF(friendName); outputToClient.writeUTF("quit"); outputToClient.flush(); isWindowOpen = false; outframe.getStyledDocument().insertString(outframe.getStyledDocument().getLength(), "你退出了上次聊天\n\n", new SimpleAttributeSet(){{ StyleConstants.setForeground(this, Color.BLUE); }}); } catch (IOException e1) { e1.printStackTrace(); } catch (BadLocationException e1) { e1.printStackTrace(); } } } }
CLan-nad/CL
CL-javaChat/src/client/WorkChat.java
2,320
//点击放大图片
line_comment
zh-cn
package src.client; import java.nio.file.Files; import java.nio.file.Paths; import java.io.*; import java.awt.event.*; import java.awt.*; import javax.swing.*; import javax.swing.text.BadLocationException; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.StyleConstants; //聊天功能 public class WorkChat implements Runnable{ DataOutputStream outputToClient = ClientMain.outputToServer; String friendName; JFrame frame = new JFrame(); JTextPane outframe = new JTextPane(); JTextField inframe = new JTextField(); JScrollPane scrollPane;//滚动输出框 JPanel inputPanel = new JPanel();//输入框 boolean isWindowOpen = false;//记录窗口是否打开 WorkChat(String friendName) { this.friendName = friendName; } //首次开启与对方的聊天窗口 public void run() { // 设置窗口 frame.setTitle(friendName); frame.setLocation(350, 200); frame.setLayout(new BorderLayout()); // 输出框 outframe.setEditable(false); scrollPane = new JScrollPane(outframe); frame.add(scrollPane, BorderLayout.CENTER); // 输入框 inputPanel.setLayout(new BorderLayout()); inputPanel.add(inframe, BorderLayout.CENTER); inframe.addActionListener(new inframeListener()); JButton fileButton = new JButton("选择文件"); fileButton.addActionListener(new FileButtonListener()); inputPanel.add(fileButton, BorderLayout.EAST); frame.add(inputPanel, BorderLayout.SOUTH); frame.addWindowListener(new CloseChat()); frame.setSize(600, 400); frame.setVisible(true); isWindowOpen = true; } //再次开启与对方的聊天窗口,组件不需要再设置 public void createWindow(){ // 设置窗口 frame.setTitle(friendName); frame.setLocation(350, 200); frame.setLayout(new BorderLayout()); // 输出框 frame.add(scrollPane, BorderLayout.CENTER); // 输入框 frame.add(inputPanel, BorderLayout.SOUTH); frame.setSize(600, 400); frame.setVisible(true); isWindowOpen = true; } // 监听输入框,负责发送信息 private class inframeListener implements ActionListener { public void actionPerformed(ActionEvent e) { String tempStr = inframe.getText().trim(); // 得到输入框输入的字符串 inframe.setText(""); try { //告诉服务端这是一个消息 outputToClient.writeUTF("send-message"); outputToClient.writeUTF(friendName); //消息内容 outputToClient.writeUTF(tempStr); outputToClient.flush(); //显示在自己的窗口上 outframe.getStyledDocument().insertString(outframe.getStyledDocument().getLength(), "我:\n", new SimpleAttributeSet(){{ StyleConstants.setForeground(this, Color.BLUE); }}); outframe.getStyledDocument().insertString(outframe.getStyledDocument().getLength(), tempStr+"\n\n", null); } catch (IOException e1) { e1.printStackTrace(); } catch (BadLocationException e1) { e1.printStackTrace(); } } } //响应按钮,负责发送文件 private class FileButtonListener implements ActionListener { public void actionPerformed(ActionEvent e){ JFileChooser fileChooser = new JFileChooser();//选择文件 fileChooser.setCurrentDirectory(new File("src/client/image")); int returnValue = fileChooser.showOpenDialog(null); if (returnValue == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile();//选择好的文件 try { outputToClient.writeUTF("send-file"); //告诉服务器这是一个文件 outputToClient.writeUTF(friendName); byte[] fileBytes = Files.readAllBytes(file.toPath()); outputToClient.writeUTF(file.getName()); // 发送文件名 outputToClient.writeInt(fileBytes.length); // 发送文件长度 outputToClient.write(fileBytes); // 发送文件内容 outputToClient.flush(); //图片类型的文件需要显示 if(isImageFile(file.getName())){ outframe.getStyledDocument().insertString(outframe.getStyledDocument().getLength(), "我: \n", new SimpleAttributeSet(){{ StyleConstants.setForeground(this, Color.BLUE); }}); String imagePath = file.getPath(); showImage(imagePath); }else{ outframe.getStyledDocument().insertString(outframe.getStyledDocument().getLength(), "我发送了文件: " + file.getName() + "\n\n", new SimpleAttributeSet(){{ StyleConstants.setForeground(this, Color.BLUE); }}); } } catch (IOException e2) { e2.printStackTrace(); } catch (BadLocationException e1) { e1.printStackTrace(); } } } } //接收信息并展示 public void showMessage(String str) throws BadLocationException{ if(str.equals("quit")){//接收到quit说明对方关闭了聊天 outframe.getStyledDocument().insertString(outframe.getStyledDocument().getLength(), "系统消息:对方已退出聊天\n\n", new SimpleAttributeSet(){{ StyleConstants.setForeground(this, Color.BLUE); }}); }else{ outframe.getStyledDocument().insertString(outframe.getStyledDocument().getLength(), "对方:\n", new SimpleAttributeSet(){{ StyleConstants.setForeground(this, Color.BLUE); }}); outframe.getStyledDocument().insertString(outframe.getStyledDocument().getLength(), str+"\n\n", null); } } //接收文件 public void handleFile(String fileName, int fileLength, byte[] fileBytes) throws IOException, BadLocationException{ //保存文件到本地 String savePath = "C:\\Users\\蔡乐\\Desktop\\" + fileName; Files.write(Paths.get(savePath), fileBytes); //若文件是图片,显示图片 if (isImageFile(fileName)) { outframe.getStyledDocument().insertString(outframe.getStyledDocument().getLength(), "对方: \n", new SimpleAttributeSet(){{ StyleConstants.setForeground(this, Color.BLUE); }}); showImage(savePath); } else outframe.getStyledDocument().insertString(outframe.getStyledDocument().getLength(), "已接收到文件:" + fileName + "\n\n", new SimpleAttributeSet(){{ StyleConstants.setForeground(this, Color.BLUE); }}); } //判断文件是否为图片 private boolean isImageFile(String fileName) { String extension = fileName.substring(fileName.lastIndexOf(".") + 1); return extension.equalsIgnoreCase("jpg") || extension.equalsIgnoreCase("png") || extension.equalsIgnoreCase("bmp"); } //显示图片 private void showImage(String savePath) throws BadLocationException{ ImageIcon icon = new ImageIcon(savePath); // 创建图标,使用指定路径的图像文件 Image image = icon.getImage(); // 获取图标的图像 Image scaledImage = image.getScaledInstance(100, 100, Image.SCALE_SMOOTH); // 将图像缩放 ImageIcon scaledIcon = new ImageIcon(scaledImage); // 创建一个新的图标,使用缩放后的图像 JLabel imageLabel = new JLabel(scaledIcon); // 创建一个标签,用于显示 imageLabel.addMouseListener(new ImageClickListener(savePath)); // 点击放大图片 outframe.setCaretPosition(outframe.getDocument().getLength()); // 设置光标位置到末尾 outframe.insertComponent(imageLabel); // 图像标签添加到文本框中 outframe.getStyledDocument().insertString(outframe.getStyledDocument().getLength(), "\n\n", null); } //点击 <SUF> private class ImageClickListener extends MouseAdapter { private String imagePath; public ImageClickListener(String path) { this.imagePath = path; } public void mouseClicked(MouseEvent e) { ImageIcon icon = new ImageIcon(imagePath); Image image = icon.getImage(); // 获取原始图片 int width = image.getWidth(null); // 获取原始图片宽度 int height = image.getHeight(null); // 获取原始图片高度 // 设置图片的最大宽度和高度 int maxWidth = 300; int maxHeight = 300; // 如果图片宽度或高度超过最大值,则按比例缩放 if (width > maxWidth || height > maxHeight) { if (width > height) { height = (int) (height * ((double) maxWidth / width)); width = maxWidth; } else { width = (int) (width * ((double) maxHeight / height)); height = maxHeight; } image = image.getScaledInstance(width, height, Image.SCALE_SMOOTH); } //弹出窗口展示放大图片 ImageIcon scaledIcon = new ImageIcon(image); JLabel label = new JLabel(); label.setIcon(scaledIcon); JOptionPane.showMessageDialog(null, label, "Scaled Image", JOptionPane.PLAIN_MESSAGE); } } //关闭聊天 class CloseChat extends WindowAdapter { public void windowClosing(WindowEvent e) { try { outputToClient.writeUTF("send-message"); outputToClient.writeUTF(friendName); outputToClient.writeUTF("quit"); outputToClient.flush(); isWindowOpen = false; outframe.getStyledDocument().insertString(outframe.getStyledDocument().getLength(), "你退出了上次聊天\n\n", new SimpleAttributeSet(){{ StyleConstants.setForeground(this, Color.BLUE); }}); } catch (IOException e1) { e1.printStackTrace(); } catch (BadLocationException e1) { e1.printStackTrace(); } } } }
0
2,061
5
2,299
6
2,419
5
2,299
6
3,073
8
false
false
false
false
false
true
40904_4
package top.guoziyang.rpc.util; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.net.JarURLConnection; import java.net.URL; import java.net.URLDecoder; import java.util.Enumeration; import java.util.LinkedHashSet; import java.util.Set; import java.util.jar.JarEntry; import java.util.jar.JarFile; /** * @author ziyang */ public class ReflectUtil { public static String getStackTrace() { StackTraceElement[] stack = new Throwable().getStackTrace(); return stack[stack.length - 1].getClassName(); } public static Set<Class<?>> getClasses(String packageName) { Set<Class<?>> classes = new LinkedHashSet<>(); boolean recursive = true; String packageDirName = packageName.replace('.', '/'); Enumeration<URL> dirs; try { dirs = Thread.currentThread().getContextClassLoader().getResources( packageDirName); // 循环迭代下去 while (dirs.hasMoreElements()) { // 获取下一个元素 URL url = dirs.nextElement(); // 得到协议的名称 String protocol = url.getProtocol(); // 如果是以文件的形式保存在服务器上 if ("file".equals(protocol)) { // 获取包的物理路径 String filePath = URLDecoder.decode(url.getFile(), "UTF-8"); // 以文件的方式扫描整个包下的文件 并添加到集合中 findAndAddClassesInPackageByFile(packageName, filePath, recursive, classes); } else if ("jar".equals(protocol)) { // 如果是jar包文件 // 定义一个JarFile JarFile jar; try { // 获取jar jar = ((JarURLConnection) url.openConnection()) .getJarFile(); // 从此jar包 得到一个枚举类 Enumeration<JarEntry> entries = jar.entries(); // 同样的进行循环迭代 while (entries.hasMoreElements()) { // 获取jar里的一个实体 可以是目录 和一些jar包里的其他文件 如META-INF等文件 JarEntry entry = entries.nextElement(); String name = entry.getName(); // 如果是以/开头的 if (name.charAt(0) == '/') { // 获取后面的字符串 name = name.substring(1); } // 如果前半部分和定义的包名相同 if (name.startsWith(packageDirName)) { int idx = name.lastIndexOf('/'); // 如果以"/"结尾 是一个包 if (idx != -1) { // 获取包名 把"/"替换成"." packageName = name.substring(0, idx) .replace('/', '.'); } // 如果可以迭代下去 并且是一个包 if ((idx != -1) || recursive) { // 如果是一个.class文件 而且不是目录 if (name.endsWith(".class") && !entry.isDirectory()) { // 去掉后面的".class" 获取真正的类名 String className = name.substring( packageName.length() + 1, name .length() - 6); try { // 添加到classes classes.add(Class .forName(packageName + '.' + className)); } catch (ClassNotFoundException e) { // log // .error("添加用户自定义视图类错误 找不到此类的.class文件"); e.printStackTrace(); } } } } } } catch (IOException e) { // log.error("在扫描用户定义视图时从jar包获取文件出错"); e.printStackTrace(); } } } } catch (IOException e) { e.printStackTrace(); } return classes; } private static void findAndAddClassesInPackageByFile(String packageName, String packagePath, final boolean recursive, Set<Class<?>> classes) { // 获取此包的目录 建立一个File File dir = new File(packagePath); // 如果不存在或者 也不是目录就直接返回 if (!dir.exists() || !dir.isDirectory()) { // log.warn("用户定义包名 " + packageName + " 下没有任何文件"); return; } // 如果存在 就获取包下的所有文件 包括目录 File[] dirfiles = dir.listFiles(new FileFilter() { // 自定义过滤规则 如果可以循环(包含子目录) 或则是以.class结尾的文件(编译好的java类文件) public boolean accept(File file) { return (recursive && file.isDirectory()) || (file.getName().endsWith(".class")); } }); // 循环所有文件 for (File file : dirfiles) { // 如果是目录 则继续扫描 if (file.isDirectory()) { findAndAddClassesInPackageByFile(packageName + "." + file.getName(), file.getAbsolutePath(), recursive, classes); } else { // 如果是java类文件 去掉后面的.class 只留下类名 String className = file.getName().substring(0, file.getName().length() - 6); try { // 添加到集合中去 //classes.add(Class.forName(packageName + '.' + className)); //经过回复同学的提醒,这里用forName有一些不好,会触发static方法,没有使用classLoader的load干净 classes.add(Thread.currentThread().getContextClassLoader().loadClass(packageName + '.' + className)); } catch (ClassNotFoundException e) { // log.error("添加用户自定义视图类错误 找不到此类的.class文件"); e.printStackTrace(); } } } } }
CN-GuoZiyang/My-RPC-Framework
rpc-common/src/main/java/top/guoziyang/rpc/util/ReflectUtil.java
1,282
// 如果是以文件的形式保存在服务器上
line_comment
zh-cn
package top.guoziyang.rpc.util; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.net.JarURLConnection; import java.net.URL; import java.net.URLDecoder; import java.util.Enumeration; import java.util.LinkedHashSet; import java.util.Set; import java.util.jar.JarEntry; import java.util.jar.JarFile; /** * @author ziyang */ public class ReflectUtil { public static String getStackTrace() { StackTraceElement[] stack = new Throwable().getStackTrace(); return stack[stack.length - 1].getClassName(); } public static Set<Class<?>> getClasses(String packageName) { Set<Class<?>> classes = new LinkedHashSet<>(); boolean recursive = true; String packageDirName = packageName.replace('.', '/'); Enumeration<URL> dirs; try { dirs = Thread.currentThread().getContextClassLoader().getResources( packageDirName); // 循环迭代下去 while (dirs.hasMoreElements()) { // 获取下一个元素 URL url = dirs.nextElement(); // 得到协议的名称 String protocol = url.getProtocol(); // 如果 <SUF> if ("file".equals(protocol)) { // 获取包的物理路径 String filePath = URLDecoder.decode(url.getFile(), "UTF-8"); // 以文件的方式扫描整个包下的文件 并添加到集合中 findAndAddClassesInPackageByFile(packageName, filePath, recursive, classes); } else if ("jar".equals(protocol)) { // 如果是jar包文件 // 定义一个JarFile JarFile jar; try { // 获取jar jar = ((JarURLConnection) url.openConnection()) .getJarFile(); // 从此jar包 得到一个枚举类 Enumeration<JarEntry> entries = jar.entries(); // 同样的进行循环迭代 while (entries.hasMoreElements()) { // 获取jar里的一个实体 可以是目录 和一些jar包里的其他文件 如META-INF等文件 JarEntry entry = entries.nextElement(); String name = entry.getName(); // 如果是以/开头的 if (name.charAt(0) == '/') { // 获取后面的字符串 name = name.substring(1); } // 如果前半部分和定义的包名相同 if (name.startsWith(packageDirName)) { int idx = name.lastIndexOf('/'); // 如果以"/"结尾 是一个包 if (idx != -1) { // 获取包名 把"/"替换成"." packageName = name.substring(0, idx) .replace('/', '.'); } // 如果可以迭代下去 并且是一个包 if ((idx != -1) || recursive) { // 如果是一个.class文件 而且不是目录 if (name.endsWith(".class") && !entry.isDirectory()) { // 去掉后面的".class" 获取真正的类名 String className = name.substring( packageName.length() + 1, name .length() - 6); try { // 添加到classes classes.add(Class .forName(packageName + '.' + className)); } catch (ClassNotFoundException e) { // log // .error("添加用户自定义视图类错误 找不到此类的.class文件"); e.printStackTrace(); } } } } } } catch (IOException e) { // log.error("在扫描用户定义视图时从jar包获取文件出错"); e.printStackTrace(); } } } } catch (IOException e) { e.printStackTrace(); } return classes; } private static void findAndAddClassesInPackageByFile(String packageName, String packagePath, final boolean recursive, Set<Class<?>> classes) { // 获取此包的目录 建立一个File File dir = new File(packagePath); // 如果不存在或者 也不是目录就直接返回 if (!dir.exists() || !dir.isDirectory()) { // log.warn("用户定义包名 " + packageName + " 下没有任何文件"); return; } // 如果存在 就获取包下的所有文件 包括目录 File[] dirfiles = dir.listFiles(new FileFilter() { // 自定义过滤规则 如果可以循环(包含子目录) 或则是以.class结尾的文件(编译好的java类文件) public boolean accept(File file) { return (recursive && file.isDirectory()) || (file.getName().endsWith(".class")); } }); // 循环所有文件 for (File file : dirfiles) { // 如果是目录 则继续扫描 if (file.isDirectory()) { findAndAddClassesInPackageByFile(packageName + "." + file.getName(), file.getAbsolutePath(), recursive, classes); } else { // 如果是java类文件 去掉后面的.class 只留下类名 String className = file.getName().substring(0, file.getName().length() - 6); try { // 添加到集合中去 //classes.add(Class.forName(packageName + '.' + className)); //经过回复同学的提醒,这里用forName有一些不好,会触发static方法,没有使用classLoader的load干净 classes.add(Thread.currentThread().getContextClassLoader().loadClass(packageName + '.' + className)); } catch (ClassNotFoundException e) { // log.error("添加用户自定义视图类错误 找不到此类的.class文件"); e.printStackTrace(); } } } } }
0
1,202
9
1,282
10
1,374
9
1,282
10
1,872
18
false
false
false
false
false
true
20613_3
import android.media.MediaPlayer; import com.mandala.Exception.MediaPlayerProxyException; import java.util.ArrayList; import java.util.List; /** * 播放语音代理类 * 理论上这个类可以做下载,先获得文件后,再播放本地文件,减少流量使用 * 不做了 * Created by W_Q on 13-10-14. */ public class MediaPlayerProxy { private MediaPlayer player; private static MediaPlayerProxy proxy = new MediaPlayerProxy(); private List<PlayState> list; //单纯的播放动画集合 private PlayState mState; //正在播放的 private String mPlayPath; private String TAG = getClass().getSimpleName(); private PlayLengthListener playLengthListener; //播放时长监听器 private boolean isNew; //用于注销时长监听 private Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { if (MediaPlayerProxy.this.playLengthListener != null) { MediaPlayerProxy.this.playLengthListener.currentLength(player.getCurrentPosition()); sendEmptyMessageDelayed(0,1000); }else{ return; } } }; private MediaPlayerProxy(){ player = new MediaPlayer(); list = new ArrayList<PlayState>(); player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mediaPlayer) { player.start(); //准备结束后,开始播放 if (mState!=null){ mState.play(); MLog.e(TAG,"mState.play()"); } if (playLengthListener!=null){ handler.sendEmptyMessageDelayed(0,1000); } } }); player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mediaPlayer) { player.stop();//播放结束 player.reset(); mPlayPath = null; playLengthListener = null; if (mState!=null){ mState.stop(); mState.setState(PlayState.NORMAL); } } }); } /** * 获得播放代理 * @return */ public static MediaPlayerProxy getProxy(){ return proxy; } /** * 仅仅在布局复用的时候调用 * @param mState * @param listener */ public void setPlayState(PlayState mState,PlayLengthListener listener){ this.mState = mState; this.playLengthListener = listener; } /** * 带有时长监听的播放 * @param state * @param listener * @param path * @return */ public boolean play(PlayState state,PlayLengthListener listener,String path){ this.playLengthListener = listener; isNew = true; return play(state, path); } /** * 播放(停止)语音 * @param state 播放对象接口 * @param path 播放路径 */ public boolean play(PlayState state,String path){ this.mState = state; mPlayPath = path; PlayState current = null; if (isNew){ isNew = false; }else { playLengthListener = null; } for (PlayState s:list){ if (s.getState() == PlayState.PLAY){ current = s; break; } } if (current!=null){ stop(); current.stop(); current.setState(PlayState.NORMAL);//停止后,再 if (current.equals(state))//再次点击还是自己,说明是想停止播放 return true; } boolean err = false; try { play(path); //实际播放 } catch (MediaPlayerProxyException e) { e.printStackTrace(); err = true; }finally { if (err){ //播放失败,调用停止播放的接口 state.setState(PlayState.NORMAL); state.stop(); return false; }else{ //设置播放状态 // list.add(state); state.setState(PlayState.PLAY); return true; } } } /** * 实际播放的方法 * @param path */ private void play(String path) throws MediaPlayerProxyException { boolean err = false; try { if (path == null||path.equals("")){ throw new MediaPlayerProxyException("路径有问题"); } MLog.i(TAG,"想要播放的音频路径"+path); player.setDataSource(path); } catch (Exception e) { err = true; //e.printStackTrace(); }finally { if (err){ player.reset(); try { player.setDataSource(path); } catch (Exception e) { //e.printStackTrace(); throw new MediaPlayerProxyException("路径有问题"); } } } player.prepareAsync(); //异步的准备 } /** * 这个路径是否正在播放 * @param path * @return */ public boolean isPlay(String path){ if (mState == null || mPlayPath == null || !mPlayPath.equals(path+"")){ return false; } if (mPlayPath.equals(path+"")){ // return mState.getState() == PlayState.PLAY; return true; } return false; } /** * 实际的停止方法 */ private void stop(){ player.reset(); } /** * 强制停止方法,用于界面跳转,或特殊场景 */ public void forceStop(){ PlayState mState = null; for (PlayState s:list){ if (s.getState() == PlayState.PLAY){ mState = s; break; } } if (mState!=null){ // 强制停止实现 stop(); mState.stop(); mPlayPath = null; playLengthListener = null; mState.setState(PlayState.NORMAL); } } /** * 添加后才可以播放,需要避免重复添加 * @param state */ public void add(PlayState state){ if (!list.contains(state)) list.add(state); } public void clear(){ list.clear(); } public interface PlayState{ /** * 播放 */ public static final int PLAY = 1; /** * 未播放 */ public static final int NORMAL = 0; /** * 这个方法为了停止动画 */ void stop(); /** * 这个方法为了开启动画 */ void play(); /** * 获取当前item的播放状态 * @return */ int getState(); /** * 设置播放状态 * @param state */ void setState(int state); } public interface PlayLengthListener{ /** * 当前播放到的时长 * @param time */ void currentLength(int time); } public List<PlayState> getList(){ return this.list; } }
CN-fox/MediaPlayerProxy
MediaPlayerProxy.java
1,623
//播放时长监听器
line_comment
zh-cn
import android.media.MediaPlayer; import com.mandala.Exception.MediaPlayerProxyException; import java.util.ArrayList; import java.util.List; /** * 播放语音代理类 * 理论上这个类可以做下载,先获得文件后,再播放本地文件,减少流量使用 * 不做了 * Created by W_Q on 13-10-14. */ public class MediaPlayerProxy { private MediaPlayer player; private static MediaPlayerProxy proxy = new MediaPlayerProxy(); private List<PlayState> list; //单纯的播放动画集合 private PlayState mState; //正在播放的 private String mPlayPath; private String TAG = getClass().getSimpleName(); private PlayLengthListener playLengthListener; //播放 <SUF> private boolean isNew; //用于注销时长监听 private Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { if (MediaPlayerProxy.this.playLengthListener != null) { MediaPlayerProxy.this.playLengthListener.currentLength(player.getCurrentPosition()); sendEmptyMessageDelayed(0,1000); }else{ return; } } }; private MediaPlayerProxy(){ player = new MediaPlayer(); list = new ArrayList<PlayState>(); player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mediaPlayer) { player.start(); //准备结束后,开始播放 if (mState!=null){ mState.play(); MLog.e(TAG,"mState.play()"); } if (playLengthListener!=null){ handler.sendEmptyMessageDelayed(0,1000); } } }); player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mediaPlayer) { player.stop();//播放结束 player.reset(); mPlayPath = null; playLengthListener = null; if (mState!=null){ mState.stop(); mState.setState(PlayState.NORMAL); } } }); } /** * 获得播放代理 * @return */ public static MediaPlayerProxy getProxy(){ return proxy; } /** * 仅仅在布局复用的时候调用 * @param mState * @param listener */ public void setPlayState(PlayState mState,PlayLengthListener listener){ this.mState = mState; this.playLengthListener = listener; } /** * 带有时长监听的播放 * @param state * @param listener * @param path * @return */ public boolean play(PlayState state,PlayLengthListener listener,String path){ this.playLengthListener = listener; isNew = true; return play(state, path); } /** * 播放(停止)语音 * @param state 播放对象接口 * @param path 播放路径 */ public boolean play(PlayState state,String path){ this.mState = state; mPlayPath = path; PlayState current = null; if (isNew){ isNew = false; }else { playLengthListener = null; } for (PlayState s:list){ if (s.getState() == PlayState.PLAY){ current = s; break; } } if (current!=null){ stop(); current.stop(); current.setState(PlayState.NORMAL);//停止后,再 if (current.equals(state))//再次点击还是自己,说明是想停止播放 return true; } boolean err = false; try { play(path); //实际播放 } catch (MediaPlayerProxyException e) { e.printStackTrace(); err = true; }finally { if (err){ //播放失败,调用停止播放的接口 state.setState(PlayState.NORMAL); state.stop(); return false; }else{ //设置播放状态 // list.add(state); state.setState(PlayState.PLAY); return true; } } } /** * 实际播放的方法 * @param path */ private void play(String path) throws MediaPlayerProxyException { boolean err = false; try { if (path == null||path.equals("")){ throw new MediaPlayerProxyException("路径有问题"); } MLog.i(TAG,"想要播放的音频路径"+path); player.setDataSource(path); } catch (Exception e) { err = true; //e.printStackTrace(); }finally { if (err){ player.reset(); try { player.setDataSource(path); } catch (Exception e) { //e.printStackTrace(); throw new MediaPlayerProxyException("路径有问题"); } } } player.prepareAsync(); //异步的准备 } /** * 这个路径是否正在播放 * @param path * @return */ public boolean isPlay(String path){ if (mState == null || mPlayPath == null || !mPlayPath.equals(path+"")){ return false; } if (mPlayPath.equals(path+"")){ // return mState.getState() == PlayState.PLAY; return true; } return false; } /** * 实际的停止方法 */ private void stop(){ player.reset(); } /** * 强制停止方法,用于界面跳转,或特殊场景 */ public void forceStop(){ PlayState mState = null; for (PlayState s:list){ if (s.getState() == PlayState.PLAY){ mState = s; break; } } if (mState!=null){ // 强制停止实现 stop(); mState.stop(); mPlayPath = null; playLengthListener = null; mState.setState(PlayState.NORMAL); } } /** * 添加后才可以播放,需要避免重复添加 * @param state */ public void add(PlayState state){ if (!list.contains(state)) list.add(state); } public void clear(){ list.clear(); } public interface PlayState{ /** * 播放 */ public static final int PLAY = 1; /** * 未播放 */ public static final int NORMAL = 0; /** * 这个方法为了停止动画 */ void stop(); /** * 这个方法为了开启动画 */ void play(); /** * 获取当前item的播放状态 * @return */ int getState(); /** * 设置播放状态 * @param state */ void setState(int state); } public interface PlayLengthListener{ /** * 当前播放到的时长 * @param time */ void currentLength(int time); } public List<PlayState> getList(){ return this.list; } }
0
1,540
7
1,616
7
1,784
6
1,617
7
2,206
15
false
false
false
false
false
true
19086_6
package com.cpucode.linked.list; /** * @author : cpucode * @date : 2021/3/13 * @time : 10:37 * @github : https://github.com/CPU-Code * @csdn : https://blog.csdn.net/qq_44226094 */ public class Josephu { public static void main(String[] args) { } } /** * 创建一个环形的单向链表 */ class CircleSingleLinkedList{ /** * 创建一个first节点,当前没有编号 */ private Boy first = null; /** * 添加小孩节点,构建成一个环形的链表 * @param nums */ public void addBoy(int nums){ // nums 做一个数据校验 if (nums < 1){ System.out.println("nums的值不正确"); return; } // 辅助指针,帮助构建环形链表 Boy curBoy = null; // 使用for来创建我们的环形链表 for (int i = 1; i < nums; i++) { // 根据编号,创建小孩节点 Boy boy = new Boy(i); // 如果是第一个小孩 if (i == 1){ first = boy; // 构成环 first.setNext(first); // 让curBoy指向第一个小孩 curBoy = first; }else { curBoy.setNext(boy); boy.setNext(first); curBoy = boy; } } } /** * 遍历当前的环形链表 */ public void showBoy(){ // 如果是第一个小孩 if (first == null){ System.out.println("没有任何小孩~~"); return; } // 因为first不能动,因此我们仍然使用一个辅助指针完成遍历 Boy curBoy = first; while (true){ System.out.printf("小孩的编号 %d \\n", curBoy.getNo()); // 说明已经遍历完毕 if (curBoy.getNext() == first){ break; } // curBoy后移 curBoy = curBoy.getNext(); } } /** * 根据用户的输入,计算出小孩出圈的顺序 * @param startNo 表示从第几个小孩开始数数 * @param countNum 表示数几下 * @param nums 表示最初有多少小孩在圈中 */ public void countBoy(int startNo, int countNum, int nums){ // 先对数据进行校验 if (first == null || startNo < 1 || startNo > nums){ System.out.println("参数输入有误, 请重新输入"); return; } // 创建要给辅助指针,帮助完成小孩出圈 Boy helper = first; // 需求创建一个辅助指针(变量) helper , 事先应该指向环形链表的最后这个节点 while (true){ if (helper.getNext() == first){ break; } helper = helper.getNext(); } //小孩报数前,先让 first 和 helper 移动 k - 1次 for(int j = 0; j < startNo - 1; j++) { first = first.getNext(); helper = helper.getNext(); } //当小孩报数时,让first 和 helper 指针同时 的移动 m - 1 次, 然后出圈 //这里是一个循环操作,知道圈中只有一个节点 while(true) { if(helper == first) { //说明圈中只有一个节点 break; } //让 first 和 helper 指针同时 的移动 countNum - 1 for(int j = 0; j < countNum - 1; j++) { first = first.getNext(); helper = helper.getNext(); } //这时first指向的节点,就是要出圈的小孩节点 System.out.printf("小孩%d出圈\n", first.getNo()); //这时将first指向的小孩节点出圈 first = first.getNext(); helper.setNext(first); } System.out.printf("最后留在圈中的小孩编号%d \n", first.getNo()); } } /** * 创建一个Boy类,表示一个节点 */ class Boy{ /** * 编号 */ private int no; /** * 指向下一个节点,默认null */ private Boy next; public Boy(int no){ this.no = no; } public int getNo() { return no; } public void setNo(int no) { this.no = no; } public Boy getNext() { return next; } public void setNext(Boy next) { this.next = next; } @Override public String toString() { return "Boy{" + "no=" + no + '}'; } }
CPU-Code/java
data_algorithm/link_list/src/main/java/com/cpucode/linked/list/Josephu.java
1,189
// 使用for来创建我们的环形链表
line_comment
zh-cn
package com.cpucode.linked.list; /** * @author : cpucode * @date : 2021/3/13 * @time : 10:37 * @github : https://github.com/CPU-Code * @csdn : https://blog.csdn.net/qq_44226094 */ public class Josephu { public static void main(String[] args) { } } /** * 创建一个环形的单向链表 */ class CircleSingleLinkedList{ /** * 创建一个first节点,当前没有编号 */ private Boy first = null; /** * 添加小孩节点,构建成一个环形的链表 * @param nums */ public void addBoy(int nums){ // nums 做一个数据校验 if (nums < 1){ System.out.println("nums的值不正确"); return; } // 辅助指针,帮助构建环形链表 Boy curBoy = null; // 使用 <SUF> for (int i = 1; i < nums; i++) { // 根据编号,创建小孩节点 Boy boy = new Boy(i); // 如果是第一个小孩 if (i == 1){ first = boy; // 构成环 first.setNext(first); // 让curBoy指向第一个小孩 curBoy = first; }else { curBoy.setNext(boy); boy.setNext(first); curBoy = boy; } } } /** * 遍历当前的环形链表 */ public void showBoy(){ // 如果是第一个小孩 if (first == null){ System.out.println("没有任何小孩~~"); return; } // 因为first不能动,因此我们仍然使用一个辅助指针完成遍历 Boy curBoy = first; while (true){ System.out.printf("小孩的编号 %d \\n", curBoy.getNo()); // 说明已经遍历完毕 if (curBoy.getNext() == first){ break; } // curBoy后移 curBoy = curBoy.getNext(); } } /** * 根据用户的输入,计算出小孩出圈的顺序 * @param startNo 表示从第几个小孩开始数数 * @param countNum 表示数几下 * @param nums 表示最初有多少小孩在圈中 */ public void countBoy(int startNo, int countNum, int nums){ // 先对数据进行校验 if (first == null || startNo < 1 || startNo > nums){ System.out.println("参数输入有误, 请重新输入"); return; } // 创建要给辅助指针,帮助完成小孩出圈 Boy helper = first; // 需求创建一个辅助指针(变量) helper , 事先应该指向环形链表的最后这个节点 while (true){ if (helper.getNext() == first){ break; } helper = helper.getNext(); } //小孩报数前,先让 first 和 helper 移动 k - 1次 for(int j = 0; j < startNo - 1; j++) { first = first.getNext(); helper = helper.getNext(); } //当小孩报数时,让first 和 helper 指针同时 的移动 m - 1 次, 然后出圈 //这里是一个循环操作,知道圈中只有一个节点 while(true) { if(helper == first) { //说明圈中只有一个节点 break; } //让 first 和 helper 指针同时 的移动 countNum - 1 for(int j = 0; j < countNum - 1; j++) { first = first.getNext(); helper = helper.getNext(); } //这时first指向的节点,就是要出圈的小孩节点 System.out.printf("小孩%d出圈\n", first.getNo()); //这时将first指向的小孩节点出圈 first = first.getNext(); helper.setNext(first); } System.out.printf("最后留在圈中的小孩编号%d \n", first.getNo()); } } /** * 创建一个Boy类,表示一个节点 */ class Boy{ /** * 编号 */ private int no; /** * 指向下一个节点,默认null */ private Boy next; public Boy(int no){ this.no = no; } public int getNo() { return no; } public void setNo(int no) { this.no = no; } public Boy getNext() { return next; } public void setNext(Boy next) { this.next = next; } @Override public String toString() { return "Boy{" + "no=" + no + '}'; } }
0
1,123
10
1,189
9
1,225
9
1,189
9
1,653
19
false
false
false
false
false
true
32519_11
package com.huoniao.oc.xunfeivoice; /** * Created by Mr PJ.Lei 2018/02/04. */ import android.content.Context; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.widget.Toast; import com.huoniao.oc.MyApplication; import com.iflytek.cloud.ErrorCode; import com.iflytek.cloud.InitListener; import com.iflytek.cloud.SpeechConstant; import com.iflytek.cloud.SpeechError; import com.iflytek.cloud.SpeechSynthesizer; import com.iflytek.cloud.SynthesizerListener; /** * 语音合成的类 发音人明细http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=367 * * @author kongqw */ public class KqwSpeechCompound { // Log标签 private static final String TAG = "KqwSpeechCompound"; // 上下文 private Context mContext; // 语音合成对象 private static SpeechSynthesizer mTts; /** * 发音人 */ public final static String[] COLOUD_VOICERS_ENTRIES = {"小燕", "小宇", "凯瑟琳", "亨利", "玛丽", "小研", "小琪", "小峰", "小梅", "小莉", "小蓉", "小芸", "小坤", "小强 ", "小莹", "小新", "楠楠", "老孙",}; public final static String[] COLOUD_VOICERS_VALUE = {"xiaoyan", "xiaoyu", "catherine", "henry", "vimary", "vixy", "xiaoqi", "vixf", "xiaomei", "xiaolin", "xiaorong", "xiaoqian", "xiaokun", "xiaoqiang", "vixying", "xiaoxin", "nannan", "vils",}; /** * 构造方法 * * @param context */ public KqwSpeechCompound(Context context) { Log.d("tag54", "初始化失败,错ss 误码:" ); // 上下文 mContext = context; // 初始化合成对象 mTts = SpeechSynthesizer.createSynthesizer(mContext, new InitListener() { @Override public void onInit(int code) { if (code != ErrorCode.SUCCESS) { Log.d("tag54", "初始化失败,错误码:" + code); } Log.d("tag54", "初始化失败,q错误码:" + code); } }); } /** * 开始合成 * * @param text */ public void speaking(String text) { // 非空判断 if (TextUtils.isEmpty(text)) { return; } if(mTts==null){ Toast.makeText(MyApplication.mContext, "创建对象失败", Toast.LENGTH_SHORT).show(); return; } int code = mTts.startSpeaking(text, mTtsListener); Log.d("tag54","-----"+code+"++++++++++"); if (code != ErrorCode.SUCCESS) { if (code == ErrorCode.ERROR_COMPONENT_NOT_INSTALLED) { Toast.makeText(mContext, "没有安装语音+ code = " + code, Toast.LENGTH_SHORT).show(); } else { Toast.makeText(mContext, "语音合成失败,错误码: " + code, Toast.LENGTH_SHORT).show(); } } } /* * 停止语音播报 */ public static void stopSpeaking() { // 对象非空并且正在说话 if (null != mTts && mTts.isSpeaking()) { // 停止说话 mTts.stopSpeaking(); } } /** * 判断当前有没有说话 * * @return */ public static boolean isSpeaking() { if (null != mTts) { return mTts.isSpeaking(); } else { return false; } } /** * 合成回调监听。 */ private SynthesizerListener mTtsListener = new SynthesizerListener() { @Override public void onSpeakBegin() { Log.i(TAG, "开始播放"); } @Override public void onSpeakPaused() { Log.i(TAG, "暂停播放"); } @Override public void onSpeakResumed() { Log.i(TAG, "继续播放"); } @Override public void onBufferProgress(int percent, int beginPos, int endPos, String info) { // TODO 缓冲的进度 Log.i(TAG, "缓冲 : " + percent); } @Override public void onSpeakProgress(int percent, int beginPos, int endPos) { // TODO 说话的进度 Log.i(TAG, "合成 : " + percent); } @Override public void onCompleted(SpeechError error) { if (error == null) { Log.i(TAG, "播放完成"); } else if (error != null) { Log.i(TAG, error.getPlainDescription(true)); } } @Override public void onEvent(int eventType, int arg1, int arg2, Bundle obj) { } }; /** * 参数设置 * * @return */ private void setParam() { // 清空参数 mTts.setParameter(SpeechConstant.PARAMS, null); // 引擎类型 网络 mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD); // 设置发音人 mTts.setParameter(SpeechConstant.VOICE_NAME, COLOUD_VOICERS_VALUE[0]); // 设置语速 mTts.setParameter(SpeechConstant.SPEED, "50"); // 设置音调 mTts.setParameter(SpeechConstant.PITCH, "50"); // 设置音量 mTts.setParameter(SpeechConstant.VOLUME, "100"); // 设置播放器音频流类型 mTts.setParameter(SpeechConstant.STREAM_TYPE, "3"); // mTts.setParameter(SpeechConstant.TTS_AUDIO_PATH, Environment.getExternalStorageDirectory() + "/KRobot/wavaudio.pcm"); // 背景音乐 1有 0 无 // mTts.setParameter("bgs", "1"); } }
CQ173/Android_OC_1.14
app/src/main/java/com/huoniao/oc/xunfeivoice/KqwSpeechCompound.java
1,554
/* * 停止语音播报 */
block_comment
zh-cn
package com.huoniao.oc.xunfeivoice; /** * Created by Mr PJ.Lei 2018/02/04. */ import android.content.Context; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.widget.Toast; import com.huoniao.oc.MyApplication; import com.iflytek.cloud.ErrorCode; import com.iflytek.cloud.InitListener; import com.iflytek.cloud.SpeechConstant; import com.iflytek.cloud.SpeechError; import com.iflytek.cloud.SpeechSynthesizer; import com.iflytek.cloud.SynthesizerListener; /** * 语音合成的类 发音人明细http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=367 * * @author kongqw */ public class KqwSpeechCompound { // Log标签 private static final String TAG = "KqwSpeechCompound"; // 上下文 private Context mContext; // 语音合成对象 private static SpeechSynthesizer mTts; /** * 发音人 */ public final static String[] COLOUD_VOICERS_ENTRIES = {"小燕", "小宇", "凯瑟琳", "亨利", "玛丽", "小研", "小琪", "小峰", "小梅", "小莉", "小蓉", "小芸", "小坤", "小强 ", "小莹", "小新", "楠楠", "老孙",}; public final static String[] COLOUD_VOICERS_VALUE = {"xiaoyan", "xiaoyu", "catherine", "henry", "vimary", "vixy", "xiaoqi", "vixf", "xiaomei", "xiaolin", "xiaorong", "xiaoqian", "xiaokun", "xiaoqiang", "vixying", "xiaoxin", "nannan", "vils",}; /** * 构造方法 * * @param context */ public KqwSpeechCompound(Context context) { Log.d("tag54", "初始化失败,错ss 误码:" ); // 上下文 mContext = context; // 初始化合成对象 mTts = SpeechSynthesizer.createSynthesizer(mContext, new InitListener() { @Override public void onInit(int code) { if (code != ErrorCode.SUCCESS) { Log.d("tag54", "初始化失败,错误码:" + code); } Log.d("tag54", "初始化失败,q错误码:" + code); } }); } /** * 开始合成 * * @param text */ public void speaking(String text) { // 非空判断 if (TextUtils.isEmpty(text)) { return; } if(mTts==null){ Toast.makeText(MyApplication.mContext, "创建对象失败", Toast.LENGTH_SHORT).show(); return; } int code = mTts.startSpeaking(text, mTtsListener); Log.d("tag54","-----"+code+"++++++++++"); if (code != ErrorCode.SUCCESS) { if (code == ErrorCode.ERROR_COMPONENT_NOT_INSTALLED) { Toast.makeText(mContext, "没有安装语音+ code = " + code, Toast.LENGTH_SHORT).show(); } else { Toast.makeText(mContext, "语音合成失败,错误码: " + code, Toast.LENGTH_SHORT).show(); } } } /* * 停止语 <SUF>*/ public static void stopSpeaking() { // 对象非空并且正在说话 if (null != mTts && mTts.isSpeaking()) { // 停止说话 mTts.stopSpeaking(); } } /** * 判断当前有没有说话 * * @return */ public static boolean isSpeaking() { if (null != mTts) { return mTts.isSpeaking(); } else { return false; } } /** * 合成回调监听。 */ private SynthesizerListener mTtsListener = new SynthesizerListener() { @Override public void onSpeakBegin() { Log.i(TAG, "开始播放"); } @Override public void onSpeakPaused() { Log.i(TAG, "暂停播放"); } @Override public void onSpeakResumed() { Log.i(TAG, "继续播放"); } @Override public void onBufferProgress(int percent, int beginPos, int endPos, String info) { // TODO 缓冲的进度 Log.i(TAG, "缓冲 : " + percent); } @Override public void onSpeakProgress(int percent, int beginPos, int endPos) { // TODO 说话的进度 Log.i(TAG, "合成 : " + percent); } @Override public void onCompleted(SpeechError error) { if (error == null) { Log.i(TAG, "播放完成"); } else if (error != null) { Log.i(TAG, error.getPlainDescription(true)); } } @Override public void onEvent(int eventType, int arg1, int arg2, Bundle obj) { } }; /** * 参数设置 * * @return */ private void setParam() { // 清空参数 mTts.setParameter(SpeechConstant.PARAMS, null); // 引擎类型 网络 mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD); // 设置发音人 mTts.setParameter(SpeechConstant.VOICE_NAME, COLOUD_VOICERS_VALUE[0]); // 设置语速 mTts.setParameter(SpeechConstant.SPEED, "50"); // 设置音调 mTts.setParameter(SpeechConstant.PITCH, "50"); // 设置音量 mTts.setParameter(SpeechConstant.VOLUME, "100"); // 设置播放器音频流类型 mTts.setParameter(SpeechConstant.STREAM_TYPE, "3"); // mTts.setParameter(SpeechConstant.TTS_AUDIO_PATH, Environment.getExternalStorageDirectory() + "/KRobot/wavaudio.pcm"); // 背景音乐 1有 0 无 // mTts.setParameter("bgs", "1"); } }
0
1,408
12
1,554
11
1,591
12
1,554
11
1,970
20
false
false
false
false
false
true
47493_6
package search; import android.os.Bundle; import android.widget.Button; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.PagerSnapHelper; import androidx.recyclerview.widget.RecyclerView; import com.example.smartstore.R; import java.util.ArrayList; import java.util.List; //import cn.student0.manager.RepeatLayoutManager; public class search extends AppCompatActivity { private RecyclerView recyclerView; private InfiniteScrollAdapter adapter; private List<info> dataList; private Button search_btn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.search); recyclerView = findViewById(R.id.recyclerView); search_btn = findViewById(R.id.search_return_btn); recyclerView.invalidate(); // 标记View为需要重新绘制 recyclerView.requestLayout(); // 请求重新测量和布局 //动态添加收纳点 *************** InfiniteScrollLayoutManager layoutManager = new InfiniteScrollLayoutManager(this, LinearLayoutManager.HORIZONTAL, false); recyclerView.setLayoutManager(layoutManager); //存储某一场景下,所拥有的空间数目 dataList = new ArrayList<>(); dataList.add(new info("小女儿的房间","可可爱爱的小女儿")); dataList.add(new info("阳台","适合休息,有花有草有小鸟")); dataList.add(new info("客厅","重要的门面,一定要保持干净")); dataList.add(new info("厕所","容易滋生细菌,要定期打扫")); // 设置无限循环的项数 int infiniteItemCount = 0; adapter = new InfiniteScrollAdapter(dataList, infiniteItemCount); // 设置适配器 recyclerView.setAdapter(adapter); PagerSnapHelper snapHelper = new PagerSnapHelper(); snapHelper.attachToRecyclerView(recyclerView); //更新界面 recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); recyclerView.invalidate(); // 标记View为需要重新绘制 recyclerView.requestLayout(); // 请求重新测量和布局 } public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); recyclerView.invalidate(); // 标记View为需要重新绘制 recyclerView.requestLayout(); // 请求重新测量和布局 } }); //动态添加收纳点 *************** //返回主界面 *************** search_btn.setOnClickListener(v -> { InfiniteScrollAdapter.tmp.clear(); finish(); }); } public void onBackPressed(){ InfiniteScrollAdapter.tmp.clear(); finish(); } //返回主界面 *************** }
CQU-computer/SmartStore
app/src/main/java/search/search.java
705
// 设置适配器
line_comment
zh-cn
package search; import android.os.Bundle; import android.widget.Button; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.PagerSnapHelper; import androidx.recyclerview.widget.RecyclerView; import com.example.smartstore.R; import java.util.ArrayList; import java.util.List; //import cn.student0.manager.RepeatLayoutManager; public class search extends AppCompatActivity { private RecyclerView recyclerView; private InfiniteScrollAdapter adapter; private List<info> dataList; private Button search_btn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.search); recyclerView = findViewById(R.id.recyclerView); search_btn = findViewById(R.id.search_return_btn); recyclerView.invalidate(); // 标记View为需要重新绘制 recyclerView.requestLayout(); // 请求重新测量和布局 //动态添加收纳点 *************** InfiniteScrollLayoutManager layoutManager = new InfiniteScrollLayoutManager(this, LinearLayoutManager.HORIZONTAL, false); recyclerView.setLayoutManager(layoutManager); //存储某一场景下,所拥有的空间数目 dataList = new ArrayList<>(); dataList.add(new info("小女儿的房间","可可爱爱的小女儿")); dataList.add(new info("阳台","适合休息,有花有草有小鸟")); dataList.add(new info("客厅","重要的门面,一定要保持干净")); dataList.add(new info("厕所","容易滋生细菌,要定期打扫")); // 设置无限循环的项数 int infiniteItemCount = 0; adapter = new InfiniteScrollAdapter(dataList, infiniteItemCount); // 设置 <SUF> recyclerView.setAdapter(adapter); PagerSnapHelper snapHelper = new PagerSnapHelper(); snapHelper.attachToRecyclerView(recyclerView); //更新界面 recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); recyclerView.invalidate(); // 标记View为需要重新绘制 recyclerView.requestLayout(); // 请求重新测量和布局 } public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); recyclerView.invalidate(); // 标记View为需要重新绘制 recyclerView.requestLayout(); // 请求重新测量和布局 } }); //动态添加收纳点 *************** //返回主界面 *************** search_btn.setOnClickListener(v -> { InfiniteScrollAdapter.tmp.clear(); finish(); }); } public void onBackPressed(){ InfiniteScrollAdapter.tmp.clear(); finish(); } //返回主界面 *************** }
0
546
5
705
5
680
4
705
5
933
9
false
false
false
false
false
true
18654_2
package CR553.Pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class History { private Long id; private String ds; //日期 private Long confirm;//累计确诊 private Long confirm_add;//今日累计确诊 private Long suspect;//疑似 private Long suspect_add;//今日新增疑似 private Long heal;//治愈 private Long heal_add;//当日新增治愈 private Long dead;//死亡 private Long dead_add;//今日新增死亡 }
CR553/Project01
src/main/java/CR553/Pojo/History.java
147
//今日新增疑似
line_comment
zh-cn
package CR553.Pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class History { private Long id; private String ds; //日期 private Long confirm;//累计确诊 private Long confirm_add;//今日累计确诊 private Long suspect;//疑似 private Long suspect_add;//今日 <SUF> private Long heal;//治愈 private Long heal_add;//当日新增治愈 private Long dead;//死亡 private Long dead_add;//今日新增死亡 }
0
114
4
147
6
138
5
147
6
205
13
false
false
false
false
false
true
17737_6
package util; import java.io.File; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileWriter; public class ChangeNum { private static String result=""; public static void processString(String str){ String [] res=str.split("\t"); for (String string : res) { result=result+"<td align=\"left\">"+string+"</td>\r\n"; } result+="\r\n"; } public static void main(String args[]){ try { // 防止文件建立或读取失败,用catch捕捉错误并打印,也可以throw /* 读入TXT文件 */ String pathname = "/Users/jessexu/Documents/Myeclipse/SQLvsNOSQL/input.txt"; // 绝对路径或相对路径都可以,这里是绝对路径,写入文件时演示相对路径 File filename = new File(pathname); // 要读取以上路径的input。txt文件 InputStreamReader reader = new InputStreamReader( new FileInputStream(filename)); // 建立一个输入流对象reader BufferedReader br = new BufferedReader(reader); // 建立一个对象,它把文件内容转成计算机能读懂的语言 String line = ""; line = br.readLine(); while (line != null) { line = br.readLine(); // 一次读入一行数据 if (line!=null) { processString(line.trim()); } } /* 写入Txt文件 */ File writename = new File("/Users/jessexu/Documents/Myeclipse/SQLvsNOSQL/output.txt"); // 相对路径,如果没有则要建立一个新的output。txt文件 writename.createNewFile(); // 创建新文件 BufferedWriter out = new BufferedWriter(new FileWriter(writename)); out.write(result); // \r\n即为换行 out.flush(); // 把缓存区内容压入文件 out.close(); // 最后记得关闭文件 } catch (Exception e) { e.printStackTrace(); } } }
CSC510/SQLvsNOSQL
ChangeNum.java
511
// 一次读入一行数据
line_comment
zh-cn
package util; import java.io.File; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileWriter; public class ChangeNum { private static String result=""; public static void processString(String str){ String [] res=str.split("\t"); for (String string : res) { result=result+"<td align=\"left\">"+string+"</td>\r\n"; } result+="\r\n"; } public static void main(String args[]){ try { // 防止文件建立或读取失败,用catch捕捉错误并打印,也可以throw /* 读入TXT文件 */ String pathname = "/Users/jessexu/Documents/Myeclipse/SQLvsNOSQL/input.txt"; // 绝对路径或相对路径都可以,这里是绝对路径,写入文件时演示相对路径 File filename = new File(pathname); // 要读取以上路径的input。txt文件 InputStreamReader reader = new InputStreamReader( new FileInputStream(filename)); // 建立一个输入流对象reader BufferedReader br = new BufferedReader(reader); // 建立一个对象,它把文件内容转成计算机能读懂的语言 String line = ""; line = br.readLine(); while (line != null) { line = br.readLine(); // 一次 <SUF> if (line!=null) { processString(line.trim()); } } /* 写入Txt文件 */ File writename = new File("/Users/jessexu/Documents/Myeclipse/SQLvsNOSQL/output.txt"); // 相对路径,如果没有则要建立一个新的output。txt文件 writename.createNewFile(); // 创建新文件 BufferedWriter out = new BufferedWriter(new FileWriter(writename)); out.write(result); // \r\n即为换行 out.flush(); // 把缓存区内容压入文件 out.close(); // 最后记得关闭文件 } catch (Exception e) { e.printStackTrace(); } } }
0
461
8
511
9
534
8
511
9
707
13
false
false
false
false
false
true
37808_45
package com.crystalneko.toneko.event; import com.crystalneko.toneko.ToNeko; import com.crystalneko.toneko.api.NekoQuery; import com.crystalneko.toneko.utils.ConfigFileUtils; import com.crystalneko.tonekocommon.Stats; import org.bukkit.NamespacedKey; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.persistence.PersistentDataType; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.cneko.ctlib.common.util.ChatPrefix; import java.io.File; import java.util.Objects; import java.util.Random; public class PlayerEventListenerBase implements Listener { @EventHandler public void onPlayerJoin(PlayerJoinEvent event) { NekoQuery query = new NekoQuery(event.getPlayer().getName()); Player player = event.getPlayer(); if(query.hasOwner()) { //添加前缀 ChatPrefix.addPrivatePrefix(player.getName(), ToNeko.getMessage("other.neko")); } } @EventHandler public void onPlayerQuit(PlayerQuitEvent event){ NekoQuery query = new NekoQuery(event.getPlayer().getName()); Player player = event.getPlayer(); if(query.hasOwner()) { //删除前缀 ChatPrefix.removePrivatePrefix(player.getName(), ToNeko.getMessage("other.neko")); } } @EventHandler public void onPlayerDeath(PlayerDeathEvent event) { File dataFile = new File( "plugins/toNeko/nekos.yml"); // 加载数据文件 YamlConfiguration data = YamlConfiguration.loadConfiguration(dataFile); // 处理玩家死亡事件的逻辑 Player player = event.getEntity(); if (player.getKiller() instanceof Player) { // 获取击杀者 Player killer = player.getKiller(); // 获取击杀者使用的物品 ItemStack itemStack = killer.getInventory().getItemInMainHand(); // 获取物品的ItemMeta对象 ItemMeta itemMeta = itemStack.getItemMeta(); //定义NBT标签 NamespacedKey key = new NamespacedKey(ToNeko.pluginInstance, "neko"); // 检查物品是否含有该自定义NBT标签 if (itemMeta.getPersistentDataContainer().has(key, PersistentDataType.STRING)) { // 读取NBT标签的值 String nbtValue = itemMeta.getPersistentDataContainer().get(key, PersistentDataType.STRING); //判断NBT是否正确 if (Objects.equals(nbtValue, "true")){ //判断玩家是否为猫娘 if(data.getString(player.getName() + ".owner") != null) { //发送死亡提示 String deathMessage = "猫娘 " + player.getName() + " 被 " + killer.getName() + " §f撅死了!"; event.setDeathMessage(deathMessage); //判断是否为主人 if(killer.getName().equals(data.getString(player.getName() + ".owner"))){ //生成随机数 Random random = new Random(); int randomNumber = random.nextInt(7) + 3; //检查配置是否存在 ConfigFileUtils.createNewKey(player.getName() + "." + "xp", 0, data, dataFile); //减去值 int xpValue = data.getInt(player.getName() + ".xp") - randomNumber; ConfigFileUtils.setValue(player.getName() + ".xp",xpValue,dataFile); player.sendMessage(ToNeko.getMessage("death.sub-xp",new String[]{killer.getName(), String.valueOf(randomNumber)})); killer.sendMessage(ToNeko.getMessage("death.sub-xp",new String[]{player.getName(), String.valueOf(randomNumber)})); } } } } } } @EventHandler public void onPlayerAttack(EntityDamageByEntityEvent event) { try { // 检查是否是玩家被攻击 if (event.getEntity() instanceof Player player) { if (event.getDamager() instanceof Player killer) { //创建数据文件实例 File dataFile = new File("plugins/toNeko/nekos.yml"); // 加载数据文件 YamlConfiguration data = YamlConfiguration.loadConfiguration(dataFile); // 获取击杀者 // 检查击杀者手中的物品是否为空或非武器 ItemStack itemStack = killer.getInventory().getItemInMainHand(); if (!itemStack.getType().isItem()) { return; } // 获取物品的ItemMeta对象 ItemMeta itemMeta = itemStack.getItemMeta(); //定义NBT标签 NamespacedKey key = new NamespacedKey(ToNeko.pluginInstance, "neko"); NamespacedKey key2 = new NamespacedKey(ToNeko.pluginInstance, "nekolevel"); // 检查物品是否含有该自定义NBT标签 if (itemMeta != null && itemMeta.getPersistentDataContainer().has(key, PersistentDataType.STRING)) { // 读取NBT标签的值 String nbtValue = itemMeta.getPersistentDataContainer().get(key, PersistentDataType.STRING); //判断NBT是否正确 if (Objects.requireNonNull(nbtValue).equalsIgnoreCase("true")) { if (data.getString(player.getName() + ".owner") != null) { PotionEffectType effectType = PotionEffectType.WEAKNESS; // 虚弱效果的类型 int duration = 200; // 持续时间 int amplifier = 0; // 效果强度 givePlayerPotionEffect(player, effectType, duration, amplifier); //判断是否为主人 if (killer.getName().equals(data.getString(player.getName() + ".owner"))) { //生成随机数 Random random = new Random(); int randomNumber = random.nextInt(6) - 2; //检查配置是否存在 ConfigFileUtils.createNewKey(player.getName() + "." + "xp", 0, data, dataFile); //加上值 int xpValue = data.getInt(player.getName() + ".xp") + randomNumber; ConfigFileUtils.setValue(player.getName() + ".xp", xpValue, dataFile); player.sendMessage(ToNeko.getMessage("attack.add-xp", new String[]{killer.getName(), String.valueOf(randomNumber)})); killer.sendMessage(ToNeko.getMessage("attack.add-xp", new String[]{player.getName(), String.valueOf(randomNumber)})); } //发送撅人音效 player.getWorld().playSound(player.getLocation(), "toneko.neko.stick", 1, 1); killer.getWorld().playSound(player.getLocation(), "toneko.neko.stick", 1, 1); // 添加统计 addStatistic(player.getName(), killer.getName()); } } } else if (itemMeta != null && itemMeta.getPersistentDataContainer().has(key2, PersistentDataType.INTEGER)) { int nbtValue2 = itemMeta.getPersistentDataContainer().get(key2, PersistentDataType.INTEGER); if (nbtValue2 == 2) { PotionEffectType effectType = PotionEffectType.WEAKNESS; // 虚弱效果的类型 PotionEffectType effectType2 = PotionEffectType.BLINDNESS; //失明 PotionEffectType effectType3 = PotionEffectType.SLOW; //缓慢 PotionEffectType effectType4 = PotionEffectType.DARKNESS; //黑暗 int duration = 1000; // 持续时间 int amplifier = 3; // 效果强度 givePlayerPotionEffect(player, effectType, duration, amplifier); givePlayerPotionEffect(player, effectType2, duration, amplifier); givePlayerPotionEffect(player, effectType3, duration, amplifier); givePlayerPotionEffect(player, effectType4, duration, amplifier); //判断是否为主人 if (killer.getName().equals(data.getString(player.getName() + ".owner"))) { //生成随机数 Random random = new Random(); int randomNumber = random.nextInt(14) + 2; //检查配置是否存在 ConfigFileUtils.createNewKey(player.getName() + "." + "xp", 0, data, dataFile); //加上值 int xpValue = data.getInt(player.getName() + ".xp") + randomNumber + 10; ConfigFileUtils.setValue(player.getName() + ".xp", xpValue, dataFile); player.sendMessage(ToNeko.getMessage("attack.add-xp", new String[]{killer.getName(), String.valueOf(randomNumber)})); killer.sendMessage(ToNeko.getMessage("attack.add-xp", new String[]{player.getName(), String.valueOf(randomNumber)})); // 添加统计 addStatistic(player.getName(), killer.getName()); } //发送撅人音效 player.getWorld().playSound(player.getLocation(), "toneko.neko.stick.level2", 1, 1); killer.getWorld().playSound(player.getLocation(), "toneko.neko.stick.level2", 1, 1); } } } } }catch(Exception ignored){ } } // 给予玩家药水效果的方法 private void givePlayerPotionEffect(Player player, PotionEffectType type, int duration, int amplifier) { PotionEffect effect = new PotionEffect(type, duration, amplifier); player.addPotionEffect(effect); } //判断是否满足统计条件 // 这段代码目前暂无用处 /*public static Boolean isStatistic(String name, int threshold){ if (!statistics.containsKey(name)) { statistics.put(name, 1); // 如果名称不存在,则将其赋值为1 } else { int value = statistics.get(name); // 获取名称对应的值 value++; // 假设每次更新值加1 statistics.put(name, value); // 更新值 // 判断值是否达到阈值 if (value >= threshold) { statistics.remove(name); // 清除值 return true; } } return false; }*/ public void addStatistic(String neko,String player ){ Stats.stick(player,neko); } }
CSneko/toNeko
src/main/java/com/crystalneko/toneko/event/PlayerEventListenerBase.java
2,557
// 给予玩家药水效果的方法
line_comment
zh-cn
package com.crystalneko.toneko.event; import com.crystalneko.toneko.ToNeko; import com.crystalneko.toneko.api.NekoQuery; import com.crystalneko.toneko.utils.ConfigFileUtils; import com.crystalneko.tonekocommon.Stats; import org.bukkit.NamespacedKey; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.persistence.PersistentDataType; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.cneko.ctlib.common.util.ChatPrefix; import java.io.File; import java.util.Objects; import java.util.Random; public class PlayerEventListenerBase implements Listener { @EventHandler public void onPlayerJoin(PlayerJoinEvent event) { NekoQuery query = new NekoQuery(event.getPlayer().getName()); Player player = event.getPlayer(); if(query.hasOwner()) { //添加前缀 ChatPrefix.addPrivatePrefix(player.getName(), ToNeko.getMessage("other.neko")); } } @EventHandler public void onPlayerQuit(PlayerQuitEvent event){ NekoQuery query = new NekoQuery(event.getPlayer().getName()); Player player = event.getPlayer(); if(query.hasOwner()) { //删除前缀 ChatPrefix.removePrivatePrefix(player.getName(), ToNeko.getMessage("other.neko")); } } @EventHandler public void onPlayerDeath(PlayerDeathEvent event) { File dataFile = new File( "plugins/toNeko/nekos.yml"); // 加载数据文件 YamlConfiguration data = YamlConfiguration.loadConfiguration(dataFile); // 处理玩家死亡事件的逻辑 Player player = event.getEntity(); if (player.getKiller() instanceof Player) { // 获取击杀者 Player killer = player.getKiller(); // 获取击杀者使用的物品 ItemStack itemStack = killer.getInventory().getItemInMainHand(); // 获取物品的ItemMeta对象 ItemMeta itemMeta = itemStack.getItemMeta(); //定义NBT标签 NamespacedKey key = new NamespacedKey(ToNeko.pluginInstance, "neko"); // 检查物品是否含有该自定义NBT标签 if (itemMeta.getPersistentDataContainer().has(key, PersistentDataType.STRING)) { // 读取NBT标签的值 String nbtValue = itemMeta.getPersistentDataContainer().get(key, PersistentDataType.STRING); //判断NBT是否正确 if (Objects.equals(nbtValue, "true")){ //判断玩家是否为猫娘 if(data.getString(player.getName() + ".owner") != null) { //发送死亡提示 String deathMessage = "猫娘 " + player.getName() + " 被 " + killer.getName() + " §f撅死了!"; event.setDeathMessage(deathMessage); //判断是否为主人 if(killer.getName().equals(data.getString(player.getName() + ".owner"))){ //生成随机数 Random random = new Random(); int randomNumber = random.nextInt(7) + 3; //检查配置是否存在 ConfigFileUtils.createNewKey(player.getName() + "." + "xp", 0, data, dataFile); //减去值 int xpValue = data.getInt(player.getName() + ".xp") - randomNumber; ConfigFileUtils.setValue(player.getName() + ".xp",xpValue,dataFile); player.sendMessage(ToNeko.getMessage("death.sub-xp",new String[]{killer.getName(), String.valueOf(randomNumber)})); killer.sendMessage(ToNeko.getMessage("death.sub-xp",new String[]{player.getName(), String.valueOf(randomNumber)})); } } } } } } @EventHandler public void onPlayerAttack(EntityDamageByEntityEvent event) { try { // 检查是否是玩家被攻击 if (event.getEntity() instanceof Player player) { if (event.getDamager() instanceof Player killer) { //创建数据文件实例 File dataFile = new File("plugins/toNeko/nekos.yml"); // 加载数据文件 YamlConfiguration data = YamlConfiguration.loadConfiguration(dataFile); // 获取击杀者 // 检查击杀者手中的物品是否为空或非武器 ItemStack itemStack = killer.getInventory().getItemInMainHand(); if (!itemStack.getType().isItem()) { return; } // 获取物品的ItemMeta对象 ItemMeta itemMeta = itemStack.getItemMeta(); //定义NBT标签 NamespacedKey key = new NamespacedKey(ToNeko.pluginInstance, "neko"); NamespacedKey key2 = new NamespacedKey(ToNeko.pluginInstance, "nekolevel"); // 检查物品是否含有该自定义NBT标签 if (itemMeta != null && itemMeta.getPersistentDataContainer().has(key, PersistentDataType.STRING)) { // 读取NBT标签的值 String nbtValue = itemMeta.getPersistentDataContainer().get(key, PersistentDataType.STRING); //判断NBT是否正确 if (Objects.requireNonNull(nbtValue).equalsIgnoreCase("true")) { if (data.getString(player.getName() + ".owner") != null) { PotionEffectType effectType = PotionEffectType.WEAKNESS; // 虚弱效果的类型 int duration = 200; // 持续时间 int amplifier = 0; // 效果强度 givePlayerPotionEffect(player, effectType, duration, amplifier); //判断是否为主人 if (killer.getName().equals(data.getString(player.getName() + ".owner"))) { //生成随机数 Random random = new Random(); int randomNumber = random.nextInt(6) - 2; //检查配置是否存在 ConfigFileUtils.createNewKey(player.getName() + "." + "xp", 0, data, dataFile); //加上值 int xpValue = data.getInt(player.getName() + ".xp") + randomNumber; ConfigFileUtils.setValue(player.getName() + ".xp", xpValue, dataFile); player.sendMessage(ToNeko.getMessage("attack.add-xp", new String[]{killer.getName(), String.valueOf(randomNumber)})); killer.sendMessage(ToNeko.getMessage("attack.add-xp", new String[]{player.getName(), String.valueOf(randomNumber)})); } //发送撅人音效 player.getWorld().playSound(player.getLocation(), "toneko.neko.stick", 1, 1); killer.getWorld().playSound(player.getLocation(), "toneko.neko.stick", 1, 1); // 添加统计 addStatistic(player.getName(), killer.getName()); } } } else if (itemMeta != null && itemMeta.getPersistentDataContainer().has(key2, PersistentDataType.INTEGER)) { int nbtValue2 = itemMeta.getPersistentDataContainer().get(key2, PersistentDataType.INTEGER); if (nbtValue2 == 2) { PotionEffectType effectType = PotionEffectType.WEAKNESS; // 虚弱效果的类型 PotionEffectType effectType2 = PotionEffectType.BLINDNESS; //失明 PotionEffectType effectType3 = PotionEffectType.SLOW; //缓慢 PotionEffectType effectType4 = PotionEffectType.DARKNESS; //黑暗 int duration = 1000; // 持续时间 int amplifier = 3; // 效果强度 givePlayerPotionEffect(player, effectType, duration, amplifier); givePlayerPotionEffect(player, effectType2, duration, amplifier); givePlayerPotionEffect(player, effectType3, duration, amplifier); givePlayerPotionEffect(player, effectType4, duration, amplifier); //判断是否为主人 if (killer.getName().equals(data.getString(player.getName() + ".owner"))) { //生成随机数 Random random = new Random(); int randomNumber = random.nextInt(14) + 2; //检查配置是否存在 ConfigFileUtils.createNewKey(player.getName() + "." + "xp", 0, data, dataFile); //加上值 int xpValue = data.getInt(player.getName() + ".xp") + randomNumber + 10; ConfigFileUtils.setValue(player.getName() + ".xp", xpValue, dataFile); player.sendMessage(ToNeko.getMessage("attack.add-xp", new String[]{killer.getName(), String.valueOf(randomNumber)})); killer.sendMessage(ToNeko.getMessage("attack.add-xp", new String[]{player.getName(), String.valueOf(randomNumber)})); // 添加统计 addStatistic(player.getName(), killer.getName()); } //发送撅人音效 player.getWorld().playSound(player.getLocation(), "toneko.neko.stick.level2", 1, 1); killer.getWorld().playSound(player.getLocation(), "toneko.neko.stick.level2", 1, 1); } } } } }catch(Exception ignored){ } } // 给予 <SUF> private void givePlayerPotionEffect(Player player, PotionEffectType type, int duration, int amplifier) { PotionEffect effect = new PotionEffect(type, duration, amplifier); player.addPotionEffect(effect); } //判断是否满足统计条件 // 这段代码目前暂无用处 /*public static Boolean isStatistic(String name, int threshold){ if (!statistics.containsKey(name)) { statistics.put(name, 1); // 如果名称不存在,则将其赋值为1 } else { int value = statistics.get(name); // 获取名称对应的值 value++; // 假设每次更新值加1 statistics.put(name, value); // 更新值 // 判断值是否达到阈值 if (value >= threshold) { statistics.remove(name); // 清除值 return true; } } return false; }*/ public void addStatistic(String neko,String player ){ Stats.stick(player,neko); } }
0
2,238
9
2,557
11
2,541
8
2,557
11
3,300
19
false
false
false
false
false
true
45307_1
public class BubbleSort //它重复地走访过要排序的数列,一次比较两个元素,如果他们的顺序错误就把他们交换过来。 //走访数列的工作是重复地进行直到没有再需要交换,也就是说该数列已经排序完成。 //速度:O(N^2) { public static void main (String[] args) { int[]arr = {7, 3, 13, 21, 9, 16, 5, 31}; mystery(arr); for (int i = 0; i < arr.length ; ++i) { System.out.print(arr [i] + " "); } } static void mystery(int[] a) { for (int stop = a.length - 1; stop > 0; --stop) { boolean inversion = false; for (int i = 0; i < stop;++i) //通过两两左右比较,把最大的放到最后一个位置上,在stop--,找到第二大 { if (a[i] > a[i+1]) //如果前者大于后者就swap { inversion = true; int tmp = a[i]; a[i] = a[i+1]; a[i+1] = tmp; } } if (!inversion) { break; } } } }
CU2018/CS445-Data-Structure-Java
Sort/BubbleSort.java
367
//走访数列的工作是重复地进行直到没有再需要交换,也就是说该数列已经排序完成。
line_comment
zh-cn
public class BubbleSort //它重复地走访过要排序的数列,一次比较两个元素,如果他们的顺序错误就把他们交换过来。 //走访 <SUF> //速度:O(N^2) { public static void main (String[] args) { int[]arr = {7, 3, 13, 21, 9, 16, 5, 31}; mystery(arr); for (int i = 0; i < arr.length ; ++i) { System.out.print(arr [i] + " "); } } static void mystery(int[] a) { for (int stop = a.length - 1; stop > 0; --stop) { boolean inversion = false; for (int i = 0; i < stop;++i) //通过两两左右比较,把最大的放到最后一个位置上,在stop--,找到第二大 { if (a[i] > a[i+1]) //如果前者大于后者就swap { inversion = true; int tmp = a[i]; a[i] = a[i+1]; a[i+1] = tmp; } } if (!inversion) { break; } } } }
0
311
23
367
28
351
24
367
28
492
44
false
false
false
false
false
true
28421_0
import java.util.HashSet; public class Flight { public int flight_type=1; //=1代表是国内航班, // =2代表去区域1的航程, // =3代表去区域2的航程, // =4代表去区域3的航程, // =5除上述区域的地方 public String startPosition="中国"; public String endPosition="美国"; public int seat_type=1; //=1代表头等舱, // =2代表公务舱, // =3经济舱, // =4代表明珠经济舱, // 暂时不设婴儿舱 Flight(String startPosition,String endPosition,int seat_type){ this.seat_type=seat_type; HashSet AreaSet1=new HashSet(); HashSet AreaSet2=new HashSet(); HashSet AreaSet3=new HashSet(); AreaSet1.add("日本");AreaSet1.add("美洲");AreaSet1.add("澳新");AreaSet1.add("俄罗斯");AreaSet1.add("新加坡");AreaSet1.add("迪拜"); AreaSet2.add("乌兹别克斯坦");AreaSet2.add("塔吉克斯坦");AreaSet2.add("哈萨克斯坦");AreaSet2.add("吉尔吉斯斯坦");AreaSet2.add("土库曼斯坦");AreaSet2.add("伊朗"); AreaSet2.add("巴基斯坦");AreaSet2.add("阿塞拜疆");AreaSet2.add("格鲁吉亚"); AreaSet3.add("内罗毕");AreaSet3.add("土耳其"); if(startPosition.equals("中国(除兰州/乌鲁木齐)")){ if(endPosition.equals("中国(除兰州/乌鲁木齐)")){flight_type=1;} else if(AreaSet1.contains(endPosition)){flight_type=2;} else if(AreaSet2.contains(endPosition)){flight_type=3;} else if(AreaSet3.contains(endPosition)){flight_type=4;} else flight_type=5; } } }
CUGzca/CUGSECourses
软件测试/SoftwareTest1/src/Flight.java
542
//=1代表是国内航班,
line_comment
zh-cn
import java.util.HashSet; public class Flight { public int flight_type=1; //=1 <SUF> // =2代表去区域1的航程, // =3代表去区域2的航程, // =4代表去区域3的航程, // =5除上述区域的地方 public String startPosition="中国"; public String endPosition="美国"; public int seat_type=1; //=1代表头等舱, // =2代表公务舱, // =3经济舱, // =4代表明珠经济舱, // 暂时不设婴儿舱 Flight(String startPosition,String endPosition,int seat_type){ this.seat_type=seat_type; HashSet AreaSet1=new HashSet(); HashSet AreaSet2=new HashSet(); HashSet AreaSet3=new HashSet(); AreaSet1.add("日本");AreaSet1.add("美洲");AreaSet1.add("澳新");AreaSet1.add("俄罗斯");AreaSet1.add("新加坡");AreaSet1.add("迪拜"); AreaSet2.add("乌兹别克斯坦");AreaSet2.add("塔吉克斯坦");AreaSet2.add("哈萨克斯坦");AreaSet2.add("吉尔吉斯斯坦");AreaSet2.add("土库曼斯坦");AreaSet2.add("伊朗"); AreaSet2.add("巴基斯坦");AreaSet2.add("阿塞拜疆");AreaSet2.add("格鲁吉亚"); AreaSet3.add("内罗毕");AreaSet3.add("土耳其"); if(startPosition.equals("中国(除兰州/乌鲁木齐)")){ if(endPosition.equals("中国(除兰州/乌鲁木齐)")){flight_type=1;} else if(AreaSet1.contains(endPosition)){flight_type=2;} else if(AreaSet2.contains(endPosition)){flight_type=3;} else if(AreaSet3.contains(endPosition)){flight_type=4;} else flight_type=5; } } }
0
421
6
542
10
512
7
542
10
676
13
false
false
false
false
false
true
5094_20
/* * {EasyGank} Copyright (C) {2015} {CaMnter} * * This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. * This is free software, and you are welcome to redistribute it * under certain conditions; type `show c' for details. * * The hypothetical commands `show w' and `show c' should show the appropriate * parts of the General Public License. Of course, your program's commands * might be different; for a GUI interface, you would use an "about box". * * You should also get your employer (if you work as a programmer) or school, * if any, to sign a "copyright disclaimer" for the program, if necessary. * For more information on this, and how to apply and follow the GNU GPL, see * <http://www.gnu.org/licenses/>. * * The GNU General Public License does not permit incorporating your program * into proprietary programs. If your program is a subroutine library, you * may consider it more useful to permit linking proprietary applications with * the library. If this is what you want to do, use the GNU Lesser General * Public License instead of this License. But first, please read * <http://www.gnu.org/philosophy/why-not-lgpl.html>. */ package com.camnter.easygank.presenter; import com.anupcowkur.reservoir.ReservoirGetCallback; import com.camnter.easygank.bean.BaseGankData; import com.camnter.easygank.bean.GankDaily; import com.camnter.easygank.constant.Constant; import com.camnter.easygank.core.mvp.BasePresenter; import com.camnter.easygank.gank.GankApi; import com.camnter.easygank.gank.GankType; import com.camnter.easygank.gank.GankTypeDict; import com.camnter.easygank.presenter.iview.MainView; import com.camnter.easygank.utils.DateUtils; import com.camnter.easygank.utils.ReservoirUtils; import com.google.gson.reflect.TypeToken; import com.orhanobut.logger.Logger; import java.io.Serializable; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import rx.Subscriber; /** * Description:MainPresenter * Created by:CaMnter * Time:2016-01-03 18:09 */ public class MainPresenter extends BasePresenter<MainView> { private EasyDate currentDate; private int page; private ReservoirUtils reservoirUtils; /** * 查每日干货需要的特殊的类 */ public class EasyDate implements Serializable { private Calendar calendar; public EasyDate(Calendar calendar) { this.calendar = calendar; } public int getYear() { return calendar.get(Calendar.YEAR); } public int getMonth() { return calendar.get(Calendar.MONTH) + 1; } public int getDay() { return calendar.get(Calendar.DAY_OF_MONTH); } public List<EasyDate> getPastTime() { List<EasyDate> easyDates = new ArrayList<>(); for (int i = 0; i < GankApi.DEFAULT_DAILY_SIZE; i++) { /* * - (page * DateUtils.ONE_DAY) 翻到哪页再找 一页有DEFAULT_DAILY_SIZE这么长 * - i * DateUtils.ONE_DAY 往前一天一天 找呀找 */ long time = this.calendar.getTimeInMillis() - ((page - 1) * GankApi.DEFAULT_DAILY_SIZE * DateUtils.ONE_DAY) - i * DateUtils.ONE_DAY; Calendar c = Calendar.getInstance(); c.setTimeInMillis(time); EasyDate date = new EasyDate(c); easyDates.add(date); } return easyDates; } } public MainPresenter() { this.reservoirUtils = new ReservoirUtils(); long time = System.currentTimeMillis(); Calendar mCalendar = Calendar.getInstance(); mCalendar.setTimeInMillis(time); this.currentDate = new EasyDate(mCalendar); this.page = 1; } /** * 设置查询第几页 * * @param page page */ public void setPage(int page) { this.page = page; } /** * 获取当前页数量 * * @return page */ public int getPage() { return page; } /** * 查询每日数据 * * @param refresh 是否是刷新 * @param oldPage olaPage==GankTypeDict.DONT_SWITCH表示不是切换数据 */ public void getDaily(final boolean refresh, final int oldPage) { /* * 切换数据源的话,尝试页数1 */ if (oldPage != GankTypeDict.DONT_SWITCH) { this.page = 1; } this.mCompositeSubscription.add(this.mDataManager.getDailyDataByNetwork(this.currentDate) .subscribe(new Subscriber<List<GankDaily>>() { @Override public void onCompleted() { if (MainPresenter.this.mCompositeSubscription != null) MainPresenter.this.mCompositeSubscription.remove(this); } @Override public void onError(Throwable e) { try { Logger.d(e.getMessage()); } catch (Throwable e1) { e1.getMessage(); } finally { if (refresh) { Type resultType = new TypeToken<List<GankDaily>>() { }.getType(); MainPresenter.this.reservoirUtils.get(GankType.daily + "", resultType, new ReservoirGetCallback<List<GankDaily>>() { @Override public void onSuccess(List<GankDaily> object) { // 有缓存显示缓存数据 if (oldPage != GankTypeDict.DONT_SWITCH) { if (MainPresenter.this.getMvpView() != null) MainPresenter.this.getMvpView().onSwitchSuccess(GankType.daily); } if (MainPresenter.this.getMvpView() != null) MainPresenter.this.getMvpView().onGetDailySuccess(object, refresh); if (MainPresenter.this.getMvpView() != null) MainPresenter.this.getMvpView().onFailure(e); } @Override public void onFailure(Exception e) { MainPresenter.this.switchFailure(oldPage, e); } }); } else { // MainPresenter.this.switchFailure(oldPage, e); // 加载更多失败 MainPresenter.this.getMvpView().onFailure(e); } } } @Override public void onNext(List<GankDaily> dailyData) { /* * 如果是切换数据源 * page=1加载成功了 * 即刚才的loadPage */ if (oldPage != GankTypeDict.DONT_SWITCH) { if (MainPresenter.this.getMvpView() != null) MainPresenter.this.getMvpView().onSwitchSuccess(GankType.daily); } // 刷新缓存 if (refresh) MainPresenter.this.reservoirUtils.refresh(GankType.daily + "", dailyData); if (MainPresenter.this.getMvpView() != null) MainPresenter.this.getMvpView().onGetDailySuccess(dailyData, refresh); } })); } /** * * 查询 ( Android、iOS、前端、拓展资源、福利、休息视频 ) * * @param type GankType * @param refresh 是否是刷新 * @param oldPage olaPage==GankTypeDict.DONT_SWITCH表示不是切换数据 */ public void getData(final int type, final boolean refresh, final int oldPage) { /* * 切换数据源的话,尝试页数1 */ if (oldPage != GankTypeDict.DONT_SWITCH) { this.page = 1; } String gankType = GankTypeDict.type2UrlTypeDict.get(type); if (gankType == null) return; this.mCompositeSubscription.add(this.mDataManager.getDataByNetWork(gankType, GankApi.DEFAULT_DATA_SIZE, this.page) .subscribe(new Subscriber<ArrayList<BaseGankData>>() { @Override public void onCompleted() { if (MainPresenter.this.mCompositeSubscription != null) MainPresenter.this.mCompositeSubscription.remove(this); } @Override public void onError(Throwable e) { try { Logger.d(e.getMessage()); } catch (Throwable e1) { e1.getMessage(); } finally { if (refresh) { Type resultType = new TypeToken<ArrayList<BaseGankData>>() { }.getType(); MainPresenter.this.reservoirUtils.get(type + "", resultType, new ReservoirGetCallback<ArrayList<BaseGankData>>() { @Override public void onSuccess(ArrayList<BaseGankData> object) { // 有缓存显示缓存数据 if (oldPage != GankTypeDict.DONT_SWITCH) { if (MainPresenter.this.getMvpView() != null) MainPresenter.this.getMvpView().onSwitchSuccess(type); } if (MainPresenter.this.getMvpView() != null) MainPresenter.this.getMvpView().onGetDataSuccess(object, refresh); if (MainPresenter.this.getMvpView() != null) MainPresenter.this.getMvpView().onFailure(e); } @Override public void onFailure(Exception e) { MainPresenter.this.switchFailure(oldPage, e); } }); } else { // MainPresenter.this.switchFailure(oldPage, e); // 加载更多失败 MainPresenter.this.getMvpView().onFailure(e); } } } @Override public void onNext(ArrayList<BaseGankData> baseGankData) { /* * 如果是切换数据源 * page=1加载成功了 * 即刚才的loadPage */ if (oldPage != GankTypeDict.DONT_SWITCH) { if (MainPresenter.this.getMvpView() != null) MainPresenter.this.getMvpView().onSwitchSuccess(type); } // 刷新缓存 if (refresh) MainPresenter.this.reservoirUtils.refresh(type + "", baseGankData); if (MainPresenter.this.getMvpView() != null) MainPresenter.this.getMvpView().onGetDataSuccess(baseGankData, refresh); } })); } public void switchType(int type) { /* * 记录没切换前的数据的页数 * 以防切换数据后,网络又跪导致的page对不上问题 */ int oldPage = this.page; switch (type) { case GankType.daily: this.getDaily(true, oldPage); break; case GankType.android: case GankType.ios: case GankType.js: case GankType.resources: case GankType.welfare: case GankType.video: case GankType.app: this.getData(type, true, oldPage); break; } } public void getDailyDetail(final GankDaily.DailyResults results) { this.mCompositeSubscription.add(this.mDataManager.getDailyDetailByDailyResults(results) .subscribe(new Subscriber<ArrayList<ArrayList<BaseGankData>>>() { @Override public void onCompleted() { if (MainPresenter.this.mCompositeSubscription != null) MainPresenter.this.mCompositeSubscription.remove(this); } @Override public void onError(Throwable e) { try { Logger.d(e.getMessage()); } catch (Throwable e1) { e1.getMessage(); } } @Override public void onNext(ArrayList<ArrayList<BaseGankData>> detail) { if (MainPresenter.this.getMvpView() != null) { // 相信福利一定有 MainPresenter.this.getMvpView().getDailyDetail( DateUtils.date2String(results.welfareData.get(0).publishedAt.getTime(), Constant.DAILY_DATE_FORMAT), detail ); } } })); } /** * 切换分类失败 * * @param oldPage oldPage */ private void switchFailure(int oldPage, Throwable e) { /* * 如果是切换数据源 * 刚才尝试的page=1失败了的请求 * 加载失败 * 会影响到原来页面的page * 在这里执行复原page操作 */ if (oldPage != GankTypeDict.DONT_SWITCH) MainPresenter.this.page = oldPage; if (MainPresenter.this.getMvpView() != null) MainPresenter.this.getMvpView().onFailure(e); } }
CaMnter/EasyGank
app/src/main/java/com/camnter/easygank/presenter/MainPresenter.java
3,126
/* * 记录没切换前的数据的页数 * 以防切换数据后,网络又跪导致的page对不上问题 */
block_comment
zh-cn
/* * {EasyGank} Copyright (C) {2015} {CaMnter} * * This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. * This is free software, and you are welcome to redistribute it * under certain conditions; type `show c' for details. * * The hypothetical commands `show w' and `show c' should show the appropriate * parts of the General Public License. Of course, your program's commands * might be different; for a GUI interface, you would use an "about box". * * You should also get your employer (if you work as a programmer) or school, * if any, to sign a "copyright disclaimer" for the program, if necessary. * For more information on this, and how to apply and follow the GNU GPL, see * <http://www.gnu.org/licenses/>. * * The GNU General Public License does not permit incorporating your program * into proprietary programs. If your program is a subroutine library, you * may consider it more useful to permit linking proprietary applications with * the library. If this is what you want to do, use the GNU Lesser General * Public License instead of this License. But first, please read * <http://www.gnu.org/philosophy/why-not-lgpl.html>. */ package com.camnter.easygank.presenter; import com.anupcowkur.reservoir.ReservoirGetCallback; import com.camnter.easygank.bean.BaseGankData; import com.camnter.easygank.bean.GankDaily; import com.camnter.easygank.constant.Constant; import com.camnter.easygank.core.mvp.BasePresenter; import com.camnter.easygank.gank.GankApi; import com.camnter.easygank.gank.GankType; import com.camnter.easygank.gank.GankTypeDict; import com.camnter.easygank.presenter.iview.MainView; import com.camnter.easygank.utils.DateUtils; import com.camnter.easygank.utils.ReservoirUtils; import com.google.gson.reflect.TypeToken; import com.orhanobut.logger.Logger; import java.io.Serializable; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import rx.Subscriber; /** * Description:MainPresenter * Created by:CaMnter * Time:2016-01-03 18:09 */ public class MainPresenter extends BasePresenter<MainView> { private EasyDate currentDate; private int page; private ReservoirUtils reservoirUtils; /** * 查每日干货需要的特殊的类 */ public class EasyDate implements Serializable { private Calendar calendar; public EasyDate(Calendar calendar) { this.calendar = calendar; } public int getYear() { return calendar.get(Calendar.YEAR); } public int getMonth() { return calendar.get(Calendar.MONTH) + 1; } public int getDay() { return calendar.get(Calendar.DAY_OF_MONTH); } public List<EasyDate> getPastTime() { List<EasyDate> easyDates = new ArrayList<>(); for (int i = 0; i < GankApi.DEFAULT_DAILY_SIZE; i++) { /* * - (page * DateUtils.ONE_DAY) 翻到哪页再找 一页有DEFAULT_DAILY_SIZE这么长 * - i * DateUtils.ONE_DAY 往前一天一天 找呀找 */ long time = this.calendar.getTimeInMillis() - ((page - 1) * GankApi.DEFAULT_DAILY_SIZE * DateUtils.ONE_DAY) - i * DateUtils.ONE_DAY; Calendar c = Calendar.getInstance(); c.setTimeInMillis(time); EasyDate date = new EasyDate(c); easyDates.add(date); } return easyDates; } } public MainPresenter() { this.reservoirUtils = new ReservoirUtils(); long time = System.currentTimeMillis(); Calendar mCalendar = Calendar.getInstance(); mCalendar.setTimeInMillis(time); this.currentDate = new EasyDate(mCalendar); this.page = 1; } /** * 设置查询第几页 * * @param page page */ public void setPage(int page) { this.page = page; } /** * 获取当前页数量 * * @return page */ public int getPage() { return page; } /** * 查询每日数据 * * @param refresh 是否是刷新 * @param oldPage olaPage==GankTypeDict.DONT_SWITCH表示不是切换数据 */ public void getDaily(final boolean refresh, final int oldPage) { /* * 切换数据源的话,尝试页数1 */ if (oldPage != GankTypeDict.DONT_SWITCH) { this.page = 1; } this.mCompositeSubscription.add(this.mDataManager.getDailyDataByNetwork(this.currentDate) .subscribe(new Subscriber<List<GankDaily>>() { @Override public void onCompleted() { if (MainPresenter.this.mCompositeSubscription != null) MainPresenter.this.mCompositeSubscription.remove(this); } @Override public void onError(Throwable e) { try { Logger.d(e.getMessage()); } catch (Throwable e1) { e1.getMessage(); } finally { if (refresh) { Type resultType = new TypeToken<List<GankDaily>>() { }.getType(); MainPresenter.this.reservoirUtils.get(GankType.daily + "", resultType, new ReservoirGetCallback<List<GankDaily>>() { @Override public void onSuccess(List<GankDaily> object) { // 有缓存显示缓存数据 if (oldPage != GankTypeDict.DONT_SWITCH) { if (MainPresenter.this.getMvpView() != null) MainPresenter.this.getMvpView().onSwitchSuccess(GankType.daily); } if (MainPresenter.this.getMvpView() != null) MainPresenter.this.getMvpView().onGetDailySuccess(object, refresh); if (MainPresenter.this.getMvpView() != null) MainPresenter.this.getMvpView().onFailure(e); } @Override public void onFailure(Exception e) { MainPresenter.this.switchFailure(oldPage, e); } }); } else { // MainPresenter.this.switchFailure(oldPage, e); // 加载更多失败 MainPresenter.this.getMvpView().onFailure(e); } } } @Override public void onNext(List<GankDaily> dailyData) { /* * 如果是切换数据源 * page=1加载成功了 * 即刚才的loadPage */ if (oldPage != GankTypeDict.DONT_SWITCH) { if (MainPresenter.this.getMvpView() != null) MainPresenter.this.getMvpView().onSwitchSuccess(GankType.daily); } // 刷新缓存 if (refresh) MainPresenter.this.reservoirUtils.refresh(GankType.daily + "", dailyData); if (MainPresenter.this.getMvpView() != null) MainPresenter.this.getMvpView().onGetDailySuccess(dailyData, refresh); } })); } /** * * 查询 ( Android、iOS、前端、拓展资源、福利、休息视频 ) * * @param type GankType * @param refresh 是否是刷新 * @param oldPage olaPage==GankTypeDict.DONT_SWITCH表示不是切换数据 */ public void getData(final int type, final boolean refresh, final int oldPage) { /* * 切换数据源的话,尝试页数1 */ if (oldPage != GankTypeDict.DONT_SWITCH) { this.page = 1; } String gankType = GankTypeDict.type2UrlTypeDict.get(type); if (gankType == null) return; this.mCompositeSubscription.add(this.mDataManager.getDataByNetWork(gankType, GankApi.DEFAULT_DATA_SIZE, this.page) .subscribe(new Subscriber<ArrayList<BaseGankData>>() { @Override public void onCompleted() { if (MainPresenter.this.mCompositeSubscription != null) MainPresenter.this.mCompositeSubscription.remove(this); } @Override public void onError(Throwable e) { try { Logger.d(e.getMessage()); } catch (Throwable e1) { e1.getMessage(); } finally { if (refresh) { Type resultType = new TypeToken<ArrayList<BaseGankData>>() { }.getType(); MainPresenter.this.reservoirUtils.get(type + "", resultType, new ReservoirGetCallback<ArrayList<BaseGankData>>() { @Override public void onSuccess(ArrayList<BaseGankData> object) { // 有缓存显示缓存数据 if (oldPage != GankTypeDict.DONT_SWITCH) { if (MainPresenter.this.getMvpView() != null) MainPresenter.this.getMvpView().onSwitchSuccess(type); } if (MainPresenter.this.getMvpView() != null) MainPresenter.this.getMvpView().onGetDataSuccess(object, refresh); if (MainPresenter.this.getMvpView() != null) MainPresenter.this.getMvpView().onFailure(e); } @Override public void onFailure(Exception e) { MainPresenter.this.switchFailure(oldPage, e); } }); } else { // MainPresenter.this.switchFailure(oldPage, e); // 加载更多失败 MainPresenter.this.getMvpView().onFailure(e); } } } @Override public void onNext(ArrayList<BaseGankData> baseGankData) { /* * 如果是切换数据源 * page=1加载成功了 * 即刚才的loadPage */ if (oldPage != GankTypeDict.DONT_SWITCH) { if (MainPresenter.this.getMvpView() != null) MainPresenter.this.getMvpView().onSwitchSuccess(type); } // 刷新缓存 if (refresh) MainPresenter.this.reservoirUtils.refresh(type + "", baseGankData); if (MainPresenter.this.getMvpView() != null) MainPresenter.this.getMvpView().onGetDataSuccess(baseGankData, refresh); } })); } public void switchType(int type) { /* * 记录没 <SUF>*/ int oldPage = this.page; switch (type) { case GankType.daily: this.getDaily(true, oldPage); break; case GankType.android: case GankType.ios: case GankType.js: case GankType.resources: case GankType.welfare: case GankType.video: case GankType.app: this.getData(type, true, oldPage); break; } } public void getDailyDetail(final GankDaily.DailyResults results) { this.mCompositeSubscription.add(this.mDataManager.getDailyDetailByDailyResults(results) .subscribe(new Subscriber<ArrayList<ArrayList<BaseGankData>>>() { @Override public void onCompleted() { if (MainPresenter.this.mCompositeSubscription != null) MainPresenter.this.mCompositeSubscription.remove(this); } @Override public void onError(Throwable e) { try { Logger.d(e.getMessage()); } catch (Throwable e1) { e1.getMessage(); } } @Override public void onNext(ArrayList<ArrayList<BaseGankData>> detail) { if (MainPresenter.this.getMvpView() != null) { // 相信福利一定有 MainPresenter.this.getMvpView().getDailyDetail( DateUtils.date2String(results.welfareData.get(0).publishedAt.getTime(), Constant.DAILY_DATE_FORMAT), detail ); } } })); } /** * 切换分类失败 * * @param oldPage oldPage */ private void switchFailure(int oldPage, Throwable e) { /* * 如果是切换数据源 * 刚才尝试的page=1失败了的请求 * 加载失败 * 会影响到原来页面的page * 在这里执行复原page操作 */ if (oldPage != GankTypeDict.DONT_SWITCH) MainPresenter.this.page = oldPage; if (MainPresenter.this.getMvpView() != null) MainPresenter.this.getMvpView().onFailure(e); } }
0
2,736
34
3,126
33
3,326
33
3,126
33
4,084
55
false
false
false
false
false
true
18730_34
import java.util.ArrayList; import java.util.Random; import java.util.Scanner; public class App { public static void main(String[] args) { Scanner sc = new Scanner(System.in); ArrayList<User> list = new ArrayList<>(); while (true) { System.out.println("欢迎来到学生管理系统"); System.out.println("请选择操作:1.登录 2.注册 3.忘记密码"); String choose = sc.next(); switch (choose) { case "1" -> login(list); case "2" -> register(list); case "3" -> forgetPassword(list); case "4" -> { System.out.println("谢谢使用,再见"); System.exit(0); } default -> System.out.println("没有这个选项"); } } } private static void login(ArrayList<User> list) { Scanner sc = new Scanner(System.in); for (int i = 0; true; i++) { System.out.println("请输入用户名:"); String username = sc.next(); //判断用户名是否存在 boolean flag = contains(list, username); if (!flag) { System.out.println("用户名:" + username + "未注册,请先注册再登录!"); return; } System.out.println("请输入密码:"); String password = sc.next(); while (true) { String rightCode = getCode(); System.out.println("请输入当前正确的验证码为:" + rightCode); System.out.println(rightCode); System.out.println("请输入验证码:"); String code = sc.next(); if (code.equalsIgnoreCase(rightCode)) { System.out.println("验证码输入正确"); break; } else { System.out.println("验证码输入错误"); } } //验证用户名和密码是否正确 //判断集合中是否包含当前用户名和密码 //定义方法验证用户名和密码是否正确 //封装思想:把零散的数据封装成一个对象 //传递参数的时候传递一个整体就行,不需要管这些零散的数据 User useInfo = new User(username, password, null, null); boolean result = checkUserInfo(list, useInfo); if (result) { System.out.println("登录成功!进入学生管理系统."); //创建对象,调用方法,启动学生管理系统 StudentSystem ss = new StudentSystem(); ss.startStudentSystem(); break; } else { System.out.println("登录失败,用户名或密码错误!"); if (i == 2) { System.out.println("当前账号" + username + "被锁定,请联系客服:+86 17854255163"); //当前账户锁定之后,直接结束方法 return; } else { System.out.println("用户名或密码错误,还剩下" + (2 - i) + "次机会"); } } } } private static boolean checkUserInfo(ArrayList<User> list, User useInfo) { //遍历集合,判断用户是否存在,如果存在登录成功,如果不存在登录失败 for (User user : list) { if (user.getUsername().equals(useInfo.getUsername()) && user.getPassword().equals(useInfo.getPassword())) { return true; } } return false; } private static void register(ArrayList<User> list) { //1.键盘录入用户名 Scanner sc = new Scanner(System.in); String username; String password; String personID; String phoneNumber; while (true) { System.out.println("请输入用户名:"); username = sc.next(); //开发细节:先验证格式是否正确,再验证是否唯一 //所有的数据都是存在数据库中的 boolean flag = checkUsername(username); if (!flag) { System.out.println("用户名格式不满足条件,需重新输入:"); continue; } //此时格式满足,校验用户名是否唯一 //username到集合中判断是否有存在的 boolean flag2 = contains(list, username); if (flag2) { //用户名已存在,无法注册,需要重新注册 System.out.println("用户名" + username + "已存在,请重新输入"); } else { //不存在,用户名可以使用,继续录入其他数据 System.out.println("用户名" + username + "可用"); break; } } //2.键盘录入密码 while (true) { System.out.println("请输入要注册的密码:"); password = sc.next(); System.out.println("请再次输入一次密码:"); String againPassword = sc.next(); if (!password.equals(againPassword)) { System.out.println("两次密码输入错误,请重新输入"); } else { System.out.println("密码一致,继续录入其他数据"); break; } } //3.键盘录入身份证号码 while (true) { System.out.println("请输入身份证号码"); personID = sc.next(); boolean flag = checkPersonID(personID); if (flag) { System.out.println("身份证号码满足要求."); break; } else { System.out.println("身份证号码格式有误,请重新输入:"); } } //4.键盘录入手机号码 while (true) { System.out.println("请输入手机号码:"); phoneNumber = sc.next(); boolean flag = checkPhoneNumber(phoneNumber); if (flag) { System.out.println("手机号码格式正确"); break; } else { System.out.println("手机号码格式有误,请重新输入:"); } } //把用户信息添加到集合中 User u = new User(username, password, personID, phoneNumber); list.add(u); System.out.println("注册成功!"); printList(list); } private static void printList(ArrayList<User> list) { for (User user : list) { System.out.println(user.getUsername() + ", " + user.getPassword() + ", " + user.getPersonID() + ", " + user.getPhoneNumber()); } } private static boolean checkPhoneNumber(String phoneNumber) { //验证长度为11位 if (phoneNumber.length() != 11) { return false; } //不能以数字0为开头 if (phoneNumber.startsWith("0")) { return false; } //必须都是数字,遍历 for (int i = 0; i < phoneNumber.length(); i++) { char c = phoneNumber.charAt(i); if (!(c >= '0' && c <= '9')) { return false; } } return true; } private static void forgetPassword(ArrayList<User> list) { Scanner sc = new Scanner(System.in); System.out.println("请输入用户名:"); String username = sc.next(); boolean flag = contains(list, username); if (!flag) { System.out.println("当前用户" + username + "未注册,请先注册"); return; } //键盘录入身份证和手机号 System.out.println("请输入身份证号码:"); String personID = sc.next(); System.out.println("请输入手机号码:"); String phoneNumber = sc.next(); //比较输入的身份证和手机号是否正确 //取出用户对象by索引 int index = findIndex(list, username); User user = list.get(index); //比较用户对象中的手机号码和身份证 if (!user.getPersonID().equalsIgnoreCase(personID) && user.getPhoneNumber().equals(phoneNumber)) { System.out.println("身份证号码或手机号码有误,不能修改密码"); return; } //代码执行到这里,所有数据验证成功,直接修改密码即可. String password; while (true) { System.out.println("请输入新的密码"); password = sc.next(); System.out.println("请确认新密码"); String againPassword = sc.next(); if (password.equals(againPassword)) { System.out.println("两次密码输入一致"); break; } else { System.out.println("两次密码输入不一致,请重新输入"); } } //直接修改 user.setPassword(password); System.out.println("密码修改成功"); } private static int findIndex(ArrayList<User> list, String username) { for (int i = 0; i < list.size(); i++) { User user = list.get(i); if (user.getUsername().equals(username)) { return i; } } return -1; } private static boolean checkPersonID(String personID) { if (personID.length() != 18) { return false; } boolean flag = personID.startsWith("0"); if (flag) { return false; } for (int i = 0; i < personID.length() - 1; i++) { char c = personID.charAt(i); if (!(c >= '0' && c <= '9')) { return false; } } char endChar = personID.charAt(personID.length() - 1); return (endChar >= '0' && endChar <= '9') || (endChar == 'x') || (endChar == 'X'); } private static boolean contains(ArrayList<User> list, String username) { //循环遍历集合,得到每一个用户对象,拿出用户对象的用户名进行比较 for (User user : list) { String rightUsername = user.getUsername(); if (rightUsername.equals(username)) { return true; } } return false; } private static boolean checkUsername(String username) { //1.校验长度 int length = username.length(); if (length < 3 || length > 15) { return false; } //2.1长度符合要求,校验字母和数字的组合 // 循环得到每一个字符 for (int i = 0; i < username.length(); i++) { char c = username.charAt(i); if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'))) { return false; } } //执行到这里,表示用户名满足长度和内容的要求(字母+数字) //2.2校验不能是纯数字 //统计在用户名中,有多少字母 int count = 0; for (int i = 0; i < username.length(); i++) { char c = username.charAt(i); if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) { count++; break; } } return count > 0; } private static String getCode() { //1.创建一个集合,添加所有的大小写字母 //不能加数字,结果会导致验证码数字出现多次 ArrayList<Character> list2 = new ArrayList<>(); for (int i = 0; i < 26; i++) { list2.add((char) ('a' + i)); list2.add((char) ('A' + i)); } //2.随机抽取四个字符 StringBuilder sb = new StringBuilder(); Random r = new Random(); for (int i = 0; i < 4; i++) { //获取随机索引 int index = r.nextInt(list2.size()); char c = list2.get(index); sb.append(c); } //3.把随机数字添加到末尾 int number = r.nextInt(10); sb.append(number); //4.修改字符串中的内容:将字符串变成字符数组,在数组中修改,再创建一个新的字符串 char[] arr = sb.toString().toCharArray(); int randomIndex = r.nextInt(5); //最大索引与随机索引的元素进行交换 char temp = arr[randomIndex]; arr[randomIndex] = arr[arr.length - 1]; arr[arr.length - 1] = temp; return new String(arr); } }
CaesarLT/StudentManagementSystem
App.java
2,862
//2.2校验不能是纯数字
line_comment
zh-cn
import java.util.ArrayList; import java.util.Random; import java.util.Scanner; public class App { public static void main(String[] args) { Scanner sc = new Scanner(System.in); ArrayList<User> list = new ArrayList<>(); while (true) { System.out.println("欢迎来到学生管理系统"); System.out.println("请选择操作:1.登录 2.注册 3.忘记密码"); String choose = sc.next(); switch (choose) { case "1" -> login(list); case "2" -> register(list); case "3" -> forgetPassword(list); case "4" -> { System.out.println("谢谢使用,再见"); System.exit(0); } default -> System.out.println("没有这个选项"); } } } private static void login(ArrayList<User> list) { Scanner sc = new Scanner(System.in); for (int i = 0; true; i++) { System.out.println("请输入用户名:"); String username = sc.next(); //判断用户名是否存在 boolean flag = contains(list, username); if (!flag) { System.out.println("用户名:" + username + "未注册,请先注册再登录!"); return; } System.out.println("请输入密码:"); String password = sc.next(); while (true) { String rightCode = getCode(); System.out.println("请输入当前正确的验证码为:" + rightCode); System.out.println(rightCode); System.out.println("请输入验证码:"); String code = sc.next(); if (code.equalsIgnoreCase(rightCode)) { System.out.println("验证码输入正确"); break; } else { System.out.println("验证码输入错误"); } } //验证用户名和密码是否正确 //判断集合中是否包含当前用户名和密码 //定义方法验证用户名和密码是否正确 //封装思想:把零散的数据封装成一个对象 //传递参数的时候传递一个整体就行,不需要管这些零散的数据 User useInfo = new User(username, password, null, null); boolean result = checkUserInfo(list, useInfo); if (result) { System.out.println("登录成功!进入学生管理系统."); //创建对象,调用方法,启动学生管理系统 StudentSystem ss = new StudentSystem(); ss.startStudentSystem(); break; } else { System.out.println("登录失败,用户名或密码错误!"); if (i == 2) { System.out.println("当前账号" + username + "被锁定,请联系客服:+86 17854255163"); //当前账户锁定之后,直接结束方法 return; } else { System.out.println("用户名或密码错误,还剩下" + (2 - i) + "次机会"); } } } } private static boolean checkUserInfo(ArrayList<User> list, User useInfo) { //遍历集合,判断用户是否存在,如果存在登录成功,如果不存在登录失败 for (User user : list) { if (user.getUsername().equals(useInfo.getUsername()) && user.getPassword().equals(useInfo.getPassword())) { return true; } } return false; } private static void register(ArrayList<User> list) { //1.键盘录入用户名 Scanner sc = new Scanner(System.in); String username; String password; String personID; String phoneNumber; while (true) { System.out.println("请输入用户名:"); username = sc.next(); //开发细节:先验证格式是否正确,再验证是否唯一 //所有的数据都是存在数据库中的 boolean flag = checkUsername(username); if (!flag) { System.out.println("用户名格式不满足条件,需重新输入:"); continue; } //此时格式满足,校验用户名是否唯一 //username到集合中判断是否有存在的 boolean flag2 = contains(list, username); if (flag2) { //用户名已存在,无法注册,需要重新注册 System.out.println("用户名" + username + "已存在,请重新输入"); } else { //不存在,用户名可以使用,继续录入其他数据 System.out.println("用户名" + username + "可用"); break; } } //2.键盘录入密码 while (true) { System.out.println("请输入要注册的密码:"); password = sc.next(); System.out.println("请再次输入一次密码:"); String againPassword = sc.next(); if (!password.equals(againPassword)) { System.out.println("两次密码输入错误,请重新输入"); } else { System.out.println("密码一致,继续录入其他数据"); break; } } //3.键盘录入身份证号码 while (true) { System.out.println("请输入身份证号码"); personID = sc.next(); boolean flag = checkPersonID(personID); if (flag) { System.out.println("身份证号码满足要求."); break; } else { System.out.println("身份证号码格式有误,请重新输入:"); } } //4.键盘录入手机号码 while (true) { System.out.println("请输入手机号码:"); phoneNumber = sc.next(); boolean flag = checkPhoneNumber(phoneNumber); if (flag) { System.out.println("手机号码格式正确"); break; } else { System.out.println("手机号码格式有误,请重新输入:"); } } //把用户信息添加到集合中 User u = new User(username, password, personID, phoneNumber); list.add(u); System.out.println("注册成功!"); printList(list); } private static void printList(ArrayList<User> list) { for (User user : list) { System.out.println(user.getUsername() + ", " + user.getPassword() + ", " + user.getPersonID() + ", " + user.getPhoneNumber()); } } private static boolean checkPhoneNumber(String phoneNumber) { //验证长度为11位 if (phoneNumber.length() != 11) { return false; } //不能以数字0为开头 if (phoneNumber.startsWith("0")) { return false; } //必须都是数字,遍历 for (int i = 0; i < phoneNumber.length(); i++) { char c = phoneNumber.charAt(i); if (!(c >= '0' && c <= '9')) { return false; } } return true; } private static void forgetPassword(ArrayList<User> list) { Scanner sc = new Scanner(System.in); System.out.println("请输入用户名:"); String username = sc.next(); boolean flag = contains(list, username); if (!flag) { System.out.println("当前用户" + username + "未注册,请先注册"); return; } //键盘录入身份证和手机号 System.out.println("请输入身份证号码:"); String personID = sc.next(); System.out.println("请输入手机号码:"); String phoneNumber = sc.next(); //比较输入的身份证和手机号是否正确 //取出用户对象by索引 int index = findIndex(list, username); User user = list.get(index); //比较用户对象中的手机号码和身份证 if (!user.getPersonID().equalsIgnoreCase(personID) && user.getPhoneNumber().equals(phoneNumber)) { System.out.println("身份证号码或手机号码有误,不能修改密码"); return; } //代码执行到这里,所有数据验证成功,直接修改密码即可. String password; while (true) { System.out.println("请输入新的密码"); password = sc.next(); System.out.println("请确认新密码"); String againPassword = sc.next(); if (password.equals(againPassword)) { System.out.println("两次密码输入一致"); break; } else { System.out.println("两次密码输入不一致,请重新输入"); } } //直接修改 user.setPassword(password); System.out.println("密码修改成功"); } private static int findIndex(ArrayList<User> list, String username) { for (int i = 0; i < list.size(); i++) { User user = list.get(i); if (user.getUsername().equals(username)) { return i; } } return -1; } private static boolean checkPersonID(String personID) { if (personID.length() != 18) { return false; } boolean flag = personID.startsWith("0"); if (flag) { return false; } for (int i = 0; i < personID.length() - 1; i++) { char c = personID.charAt(i); if (!(c >= '0' && c <= '9')) { return false; } } char endChar = personID.charAt(personID.length() - 1); return (endChar >= '0' && endChar <= '9') || (endChar == 'x') || (endChar == 'X'); } private static boolean contains(ArrayList<User> list, String username) { //循环遍历集合,得到每一个用户对象,拿出用户对象的用户名进行比较 for (User user : list) { String rightUsername = user.getUsername(); if (rightUsername.equals(username)) { return true; } } return false; } private static boolean checkUsername(String username) { //1.校验长度 int length = username.length(); if (length < 3 || length > 15) { return false; } //2.1长度符合要求,校验字母和数字的组合 // 循环得到每一个字符 for (int i = 0; i < username.length(); i++) { char c = username.charAt(i); if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'))) { return false; } } //执行到这里,表示用户名满足长度和内容的要求(字母+数字) //2. <SUF> //统计在用户名中,有多少字母 int count = 0; for (int i = 0; i < username.length(); i++) { char c = username.charAt(i); if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) { count++; break; } } return count > 0; } private static String getCode() { //1.创建一个集合,添加所有的大小写字母 //不能加数字,结果会导致验证码数字出现多次 ArrayList<Character> list2 = new ArrayList<>(); for (int i = 0; i < 26; i++) { list2.add((char) ('a' + i)); list2.add((char) ('A' + i)); } //2.随机抽取四个字符 StringBuilder sb = new StringBuilder(); Random r = new Random(); for (int i = 0; i < 4; i++) { //获取随机索引 int index = r.nextInt(list2.size()); char c = list2.get(index); sb.append(c); } //3.把随机数字添加到末尾 int number = r.nextInt(10); sb.append(number); //4.修改字符串中的内容:将字符串变成字符数组,在数组中修改,再创建一个新的字符串 char[] arr = sb.toString().toCharArray(); int randomIndex = r.nextInt(5); //最大索引与随机索引的元素进行交换 char temp = arr[randomIndex]; arr[randomIndex] = arr[arr.length - 1]; arr[arr.length - 1] = temp; return new String(arr); } }
0
2,599
11
2,859
11
3,082
10
2,859
11
3,928
17
false
false
false
false
false
true
64712_8
package array; /** * 动态数组 * <p> * 思想: 新建一个新的数组,容量需要进行扩大, * 然后让成员变量数组指针指向新建的数组,原来的数组 * 没有指针指向,会被Java 垃圾回收器回收 * <p> * 时间复杂度分析: * 增: O(n) * 删: O(n) * 改: 已知索引O(1),未知索引:O(n) * 查:已知索引O(1),未知索引:O(n) * <p> * 添加操作: 均摊时间复杂度 * <p> * 复杂度震荡: capacity = n * addLast 扩容 之后紧接着 removeLast 两次时间复杂度 O(n) * removeLast * 原因: removeLast 时resize() 过于着急 * 解决方案:Lazy 缩容时候 当size == capacity/4 才将capacity减半 空间换时间 */ public class DynamicArray<E> { private E[] data; private int size; /** * @param capacity 传数组的容量 */ public DynamicArray(int capacity) { data = (E[]) new Object[capacity]; size = 0; } public DynamicArray() { this(10); } public DynamicArray(E[] eArray) { data = (E[]) new Object[eArray.length]; for (int i = 0; i < eArray.length; i++) { data[i] = eArray[i]; } size = eArray.length; } /** * @return 数组长度 */ public int getSize() { return size; } /** * @return 当前数组容量 */ public int getCapacity() { return data.length; } /** * @return 是否为空 */ public boolean isEmpty() { return size == 0; } /** * 均摊时间复杂度 * O(1) * * @param e 向所有元素后添加一个新元素 */ public void addLast(E e) { add(size, e); } /** * @param e 向所有元素第一个添加一个新元素 O(n) */ public void addFirst(E e) { add(0, e); } /** * 指定位置添加元素 * <p> * 时间复杂度,index取值的概率是一样的 * 每个元素期望是多少,平均时间度O(n/2) ~~ O(n), * 时间复杂度 : * 需要按照最坏的方案计算, * 考虑最好的意义不大 * * @param index 指定位置 * @param e 元素 */ public void add(int index, E e) { if (index < 0 || index > size) { throw new IllegalArgumentException("Add Failed"); } if (size == data.length) { resize(2 * data.length); } //每一个元素向后一个位置 for (int i = size - 1; i >= index; i--) { data[i + 1] = data[i]; } data[index] = e; size++; } /** * 数组扩容 : * 思想,数组当前长度或大或小,不理想,最好是倍数 * <p> * ArrayList 扩容是原来Size的1.5倍数 * <p> * 时间复杂度:O(n) * <p> * 均摊时间复杂度: 假设capacity = 8, 并且每一次添加操作都是用addLast, * 9次addLast 操作,触发一次resize,总共进行了17次基本操作,平均每次addLast * 就执行2次基本操作(扩容倍数), * 假设capacity = n,n+1次addLast,触发resize,总共进行2n+1次基本操作 * 平均每次addLast就执行2次基本操作(扩容倍数), * * @param newCapacity 新数组长度 */ private void resize(int newCapacity) { E[] newData = (E[]) new Object[newCapacity]; for (int i = 0; i < size; i++) { newData[i] = data[i]; } data = newData; } /** * 删除一个 * * @param e 删除元素 */ public void removeElement(E e) { int index = find(e); if (index != -1) { remove(index); } } /** * 时间复杂度:O(n) * * @return */ public E removeFirst() { return remove(0); } /** * 均摊时间复杂度 * O(1) * * @return */ public E removeLast() { return remove(size - 1); } /** * 时间复杂度:O(n) * * @param index 删除索引元素 */ public E remove(int index) { if (index < 0 || index >= size) { throw new IllegalArgumentException("Remove Failed"); } E ret = data[index]; for (int i = index + 1; i < size; i++) { data[i - 1] = data[i]; } size--; data[size] = null; if (size == data.length / 4 && data.length / 2 != 0) { resize(data.length / 2); } return ret; } /** * 时间复杂度:O(1): 支持随机索引 * * @param index 索引 * @param e 索引对应元素 */ public void set(int index, E e) { if (index < 0 || index >= size) { throw new IllegalArgumentException("Set Failed"); } data[index] = e; } /** * @param index 索引 * @return 索引对应元素 */ public E get(int index) { if (index < 0 || index >= size) { throw new IllegalArgumentException("Get Failed"); } return data[index]; } public E getLast() { return get(size - 1); } public E getFirst() { return get(0); } /** * 时间复杂度:O(n) * * @return 是否包含 */ public boolean contains(E e) { for (int i = 0; i < size; i++) { if (e.equals(data[i])) { return true; } } return false; } /** * 时间复杂度:O(n) * * @return 元素的索引 */ public int find(E e) { for (int i = 0; i < size; i++) { if (e.equals(data[i])) { return i; } } return -1; } /** * 交换 */ public void swap(int i, int j) { if (i < 0 || i >= size || j < 0 || j >= size) { throw new IllegalArgumentException("Index is illegal"); } E temp = data[i]; data[i] = data[j]; data[j] = temp; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append(String.format("Array:Size = %d , capacity = %d \n", size, data.length)); builder.append("["); for (int i = 0; i < size; i++) { builder.append(data[i]); if (i != size - 1) { builder.append(", "); } } builder.append("]"); return builder.toString(); } }
CaiPeng/JavaDataStructure
src/array/DynamicArray.java
1,857
//每一个元素向后一个位置
line_comment
zh-cn
package array; /** * 动态数组 * <p> * 思想: 新建一个新的数组,容量需要进行扩大, * 然后让成员变量数组指针指向新建的数组,原来的数组 * 没有指针指向,会被Java 垃圾回收器回收 * <p> * 时间复杂度分析: * 增: O(n) * 删: O(n) * 改: 已知索引O(1),未知索引:O(n) * 查:已知索引O(1),未知索引:O(n) * <p> * 添加操作: 均摊时间复杂度 * <p> * 复杂度震荡: capacity = n * addLast 扩容 之后紧接着 removeLast 两次时间复杂度 O(n) * removeLast * 原因: removeLast 时resize() 过于着急 * 解决方案:Lazy 缩容时候 当size == capacity/4 才将capacity减半 空间换时间 */ public class DynamicArray<E> { private E[] data; private int size; /** * @param capacity 传数组的容量 */ public DynamicArray(int capacity) { data = (E[]) new Object[capacity]; size = 0; } public DynamicArray() { this(10); } public DynamicArray(E[] eArray) { data = (E[]) new Object[eArray.length]; for (int i = 0; i < eArray.length; i++) { data[i] = eArray[i]; } size = eArray.length; } /** * @return 数组长度 */ public int getSize() { return size; } /** * @return 当前数组容量 */ public int getCapacity() { return data.length; } /** * @return 是否为空 */ public boolean isEmpty() { return size == 0; } /** * 均摊时间复杂度 * O(1) * * @param e 向所有元素后添加一个新元素 */ public void addLast(E e) { add(size, e); } /** * @param e 向所有元素第一个添加一个新元素 O(n) */ public void addFirst(E e) { add(0, e); } /** * 指定位置添加元素 * <p> * 时间复杂度,index取值的概率是一样的 * 每个元素期望是多少,平均时间度O(n/2) ~~ O(n), * 时间复杂度 : * 需要按照最坏的方案计算, * 考虑最好的意义不大 * * @param index 指定位置 * @param e 元素 */ public void add(int index, E e) { if (index < 0 || index > size) { throw new IllegalArgumentException("Add Failed"); } if (size == data.length) { resize(2 * data.length); } //每一 <SUF> for (int i = size - 1; i >= index; i--) { data[i + 1] = data[i]; } data[index] = e; size++; } /** * 数组扩容 : * 思想,数组当前长度或大或小,不理想,最好是倍数 * <p> * ArrayList 扩容是原来Size的1.5倍数 * <p> * 时间复杂度:O(n) * <p> * 均摊时间复杂度: 假设capacity = 8, 并且每一次添加操作都是用addLast, * 9次addLast 操作,触发一次resize,总共进行了17次基本操作,平均每次addLast * 就执行2次基本操作(扩容倍数), * 假设capacity = n,n+1次addLast,触发resize,总共进行2n+1次基本操作 * 平均每次addLast就执行2次基本操作(扩容倍数), * * @param newCapacity 新数组长度 */ private void resize(int newCapacity) { E[] newData = (E[]) new Object[newCapacity]; for (int i = 0; i < size; i++) { newData[i] = data[i]; } data = newData; } /** * 删除一个 * * @param e 删除元素 */ public void removeElement(E e) { int index = find(e); if (index != -1) { remove(index); } } /** * 时间复杂度:O(n) * * @return */ public E removeFirst() { return remove(0); } /** * 均摊时间复杂度 * O(1) * * @return */ public E removeLast() { return remove(size - 1); } /** * 时间复杂度:O(n) * * @param index 删除索引元素 */ public E remove(int index) { if (index < 0 || index >= size) { throw new IllegalArgumentException("Remove Failed"); } E ret = data[index]; for (int i = index + 1; i < size; i++) { data[i - 1] = data[i]; } size--; data[size] = null; if (size == data.length / 4 && data.length / 2 != 0) { resize(data.length / 2); } return ret; } /** * 时间复杂度:O(1): 支持随机索引 * * @param index 索引 * @param e 索引对应元素 */ public void set(int index, E e) { if (index < 0 || index >= size) { throw new IllegalArgumentException("Set Failed"); } data[index] = e; } /** * @param index 索引 * @return 索引对应元素 */ public E get(int index) { if (index < 0 || index >= size) { throw new IllegalArgumentException("Get Failed"); } return data[index]; } public E getLast() { return get(size - 1); } public E getFirst() { return get(0); } /** * 时间复杂度:O(n) * * @return 是否包含 */ public boolean contains(E e) { for (int i = 0; i < size; i++) { if (e.equals(data[i])) { return true; } } return false; } /** * 时间复杂度:O(n) * * @return 元素的索引 */ public int find(E e) { for (int i = 0; i < size; i++) { if (e.equals(data[i])) { return i; } } return -1; } /** * 交换 */ public void swap(int i, int j) { if (i < 0 || i >= size || j < 0 || j >= size) { throw new IllegalArgumentException("Index is illegal"); } E temp = data[i]; data[i] = data[j]; data[j] = temp; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append(String.format("Array:Size = %d , capacity = %d \n", size, data.length)); builder.append("["); for (int i = 0; i < size; i++) { builder.append(data[i]); if (i != size - 1) { builder.append(", "); } } builder.append("]"); return builder.toString(); } }
0
1,788
7
1,857
8
1,993
7
1,857
8
2,444
12
false
false
false
false
false
true
54948_47
package com.cgfay.landmark; /** * 关键点索引(106个关键点 + 扩展8个关键点) * Created by cain on 2017/11/10. */ public final class FaceLandmark { private FaceLandmark() {} // 左眉毛 public static int leftEyebrowRightCorner = 37; // 左眉毛右边角 public static int leftEyebrowLeftCorner = 33; // 左眉毛左边角 public static int leftEyebrowLeftTopCorner = 34; // 左眉毛左顶角 public static int leftEyebrowRightTopCorner = 36; // 左眉毛右顶角 public static int leftEyebrowUpperMiddle = 35; // 左眉毛上中心 public static int leftEyebrowLowerMiddle = 65; // 左眉毛下中心 // 右眉毛 public static int rightEyebrowRightCorner = 38; // 右眉毛右边角 public static int rightEyebrowLeftCorner = 42; // 右眉毛左上角 public static int rightEyebrowLeftTopCorner = 39; // 右眉毛左顶角 public static int rightEyebrowRightTopCorner = 41; // 右眉毛右顶角 public static int rightEyebrowUpperMiddle = 40; // 右眉毛上中心 public static int rightEyebrowLowerMiddle = 70; // 右眉毛下中心 // 左眼 public static int leftEyeTop = 72; // 左眼球上边 public static int leftEyeCenter = 74; // 左眼球中心 public static int leftEyeBottom = 73; // 左眼球下边 public static int leftEyeLeftCorner = 52; // 左眼左边角 public static int leftEyeRightCorner = 55; // 左眼右边角 // 右眼 public static int rightEyeTop = 75; // 右眼球上边 public static int rightEyeCenter = 77; // 右眼球中心 public static int rightEyeBottom = 76; // 右眼球下边 public static int rightEyeLeftCorner = 58; // 右眼左边角 public static int rightEyeRightCorner = 61; // 右眼右边角 public static int eyeCenter = 43; // 两眼中心 // 鼻子 public static int noseTop = 46; // 鼻尖 public static int noseLeft = 82; // 鼻子左边 public static int noseRight = 83; // 鼻子右边 public static int noseLowerMiddle = 49; // 两鼻孔中心 // 脸边沿 public static int leftCheekEdgeCenter = 4; // 左脸颊边沿中心 public static int rightCheekEdgeCenter = 28; // 右脸颊边沿中心 // 嘴巴 public static int mouthLeftCorner = 84; // 嘴唇左边 public static int mouthRightCorner = 90; // 嘴唇右边 public static int mouthUpperLipTop = 87; // 上嘴唇上中心 public static int mouthUpperLipBottom = 98; // 上嘴唇下中心 public static int mouthLowerLipTop = 102; // 下嘴唇上中心 public static int mouthLowerLipBottom = 93; // 下嘴唇下中心 // 下巴 public static int chinLeft = 14; // 下巴左边 public static int chinRight = 18; // 下巴右边 public static int chinCenter = 16; // 下巴中心 // 扩展的关键点(8个) public static int mouthCenter = 106; // 嘴巴中心 public static int leftEyebrowCenter = 107; // 左眉心 public static int rightEyebrowCenter = 108; // 右眉心 public static int leftHead = 109; // 额头左侧 public static int headCenter = 110; // 额头中心 public static int rightHead = 111; // 额头右侧 public static int leftCheekCenter = 112; // 左脸颊中心 public static int rightCheekCenter = 113; // 右脸颊中心 }
CainKernel/CainCamera
landmarklibrary/src/main/java/com/cgfay/landmark/FaceLandmark.java
1,152
// 额头右侧
line_comment
zh-cn
package com.cgfay.landmark; /** * 关键点索引(106个关键点 + 扩展8个关键点) * Created by cain on 2017/11/10. */ public final class FaceLandmark { private FaceLandmark() {} // 左眉毛 public static int leftEyebrowRightCorner = 37; // 左眉毛右边角 public static int leftEyebrowLeftCorner = 33; // 左眉毛左边角 public static int leftEyebrowLeftTopCorner = 34; // 左眉毛左顶角 public static int leftEyebrowRightTopCorner = 36; // 左眉毛右顶角 public static int leftEyebrowUpperMiddle = 35; // 左眉毛上中心 public static int leftEyebrowLowerMiddle = 65; // 左眉毛下中心 // 右眉毛 public static int rightEyebrowRightCorner = 38; // 右眉毛右边角 public static int rightEyebrowLeftCorner = 42; // 右眉毛左上角 public static int rightEyebrowLeftTopCorner = 39; // 右眉毛左顶角 public static int rightEyebrowRightTopCorner = 41; // 右眉毛右顶角 public static int rightEyebrowUpperMiddle = 40; // 右眉毛上中心 public static int rightEyebrowLowerMiddle = 70; // 右眉毛下中心 // 左眼 public static int leftEyeTop = 72; // 左眼球上边 public static int leftEyeCenter = 74; // 左眼球中心 public static int leftEyeBottom = 73; // 左眼球下边 public static int leftEyeLeftCorner = 52; // 左眼左边角 public static int leftEyeRightCorner = 55; // 左眼右边角 // 右眼 public static int rightEyeTop = 75; // 右眼球上边 public static int rightEyeCenter = 77; // 右眼球中心 public static int rightEyeBottom = 76; // 右眼球下边 public static int rightEyeLeftCorner = 58; // 右眼左边角 public static int rightEyeRightCorner = 61; // 右眼右边角 public static int eyeCenter = 43; // 两眼中心 // 鼻子 public static int noseTop = 46; // 鼻尖 public static int noseLeft = 82; // 鼻子左边 public static int noseRight = 83; // 鼻子右边 public static int noseLowerMiddle = 49; // 两鼻孔中心 // 脸边沿 public static int leftCheekEdgeCenter = 4; // 左脸颊边沿中心 public static int rightCheekEdgeCenter = 28; // 右脸颊边沿中心 // 嘴巴 public static int mouthLeftCorner = 84; // 嘴唇左边 public static int mouthRightCorner = 90; // 嘴唇右边 public static int mouthUpperLipTop = 87; // 上嘴唇上中心 public static int mouthUpperLipBottom = 98; // 上嘴唇下中心 public static int mouthLowerLipTop = 102; // 下嘴唇上中心 public static int mouthLowerLipBottom = 93; // 下嘴唇下中心 // 下巴 public static int chinLeft = 14; // 下巴左边 public static int chinRight = 18; // 下巴右边 public static int chinCenter = 16; // 下巴中心 // 扩展的关键点(8个) public static int mouthCenter = 106; // 嘴巴中心 public static int leftEyebrowCenter = 107; // 左眉心 public static int rightEyebrowCenter = 108; // 右眉心 public static int leftHead = 109; // 额头左侧 public static int headCenter = 110; // 额头中心 public static int rightHead = 111; // 额头 <SUF> public static int leftCheekCenter = 112; // 左脸颊中心 public static int rightCheekCenter = 113; // 右脸颊中心 }
0
1,093
6
1,152
6
1,030
4
1,152
6
1,404
10
false
false
false
false
false
true
62224_2
package top.calivnhaynes.servlet; import jakarta.servlet.ServletException; import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.Date; /** * @author CalvinHaynes * @date 2021/09/05 */ public class CookieDemo02 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //解决中文乱码 req.setCharacterEncoding("utf-8"); resp.setCharacterEncoding("utf-8"); //解决网页中文显示乱码 resp.setContentType("text/html;charset=utf-8"); PrintWriter out = resp.getWriter(); //服务器端从客户端获取Cookie Cookie[] cookies = req.getCookies(); //判断Cookie是否存在 if (cookies != null) { //存在cookie进行的测试:打印上一次访问此站的时间 out.write("本站的创始人是:"); for (Cookie cookie : cookies) { //判断Cookie名字非空拿到它的值并打印 if ("name".equals(cookie.getName())) { System.out.println(URLDecoder.decode(cookie.getValue(), "GBK")); out.write(URLDecoder.decode(cookie.getValue(), "GBK")); } } } else { out.write("这是您第一次访问本站"); } //创建Cookie Cookie name = new Cookie("name", URLEncoder.encode("马丁", "GBK")); //服务器响应给客户端Cookie resp.addCookie(name); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
CalvinHaynes/SSM-Study
SpringMVC-Study/6-Servlet-Cookie-Session/src/main/java/top/calivnhaynes/servlet/CookieDemo02.java
462
//解决网页中文显示乱码
line_comment
zh-cn
package top.calivnhaynes.servlet; import jakarta.servlet.ServletException; import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.Date; /** * @author CalvinHaynes * @date 2021/09/05 */ public class CookieDemo02 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //解决中文乱码 req.setCharacterEncoding("utf-8"); resp.setCharacterEncoding("utf-8"); //解决 <SUF> resp.setContentType("text/html;charset=utf-8"); PrintWriter out = resp.getWriter(); //服务器端从客户端获取Cookie Cookie[] cookies = req.getCookies(); //判断Cookie是否存在 if (cookies != null) { //存在cookie进行的测试:打印上一次访问此站的时间 out.write("本站的创始人是:"); for (Cookie cookie : cookies) { //判断Cookie名字非空拿到它的值并打印 if ("name".equals(cookie.getName())) { System.out.println(URLDecoder.decode(cookie.getValue(), "GBK")); out.write(URLDecoder.decode(cookie.getValue(), "GBK")); } } } else { out.write("这是您第一次访问本站"); } //创建Cookie Cookie name = new Cookie("name", URLEncoder.encode("马丁", "GBK")); //服务器响应给客户端Cookie resp.addCookie(name); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
0
376
7
462
8
471
7
462
8
606
15
false
false
false
false
false
true
58470_15
/** * Description: car-eye车辆管理平台 * 文件名:MultiMedia.java * 版本信息:1.0 * 日期:2015-3-26 * Copyright car-eye 车辆管理平台 Copyright (c) 2015 * 版权所有 */ package com.careye.monitor.domain; /** * @项目名称:car-eye * @类名称:MultiMedia * @类描述: * @创建人:Yuqk * @创建时间:2015-3-26 下午03:22:34 * @修改人:Yuqk * @修改时间:2015-3-26 下午03:22:34 * @修改备注: * @version 1.0 */ public class MultiMedia { private Integer id; private Integer carid; /** 组织机构 **/ private Integer blocid; private String blocname; /** 用户ID **/ private Integer userid; /** 终端号码 **/ private String terminal; /** 车牌号 **/ private String carnumber; /** 多媒体数据ID **/ private Integer dataid; /** 多媒体类型 0:图像;1:音频;2:视频 **/ private Integer mediatype; /** 多媒体格式编码 0:JPEG;1:TIF;2:MP3;3:WAV;4:WMV;其他保留 **/ private Integer format; /** 事件项编码 0:平台下发指令; 1:定时动作; 2:抢劫报警触发; 3:碰撞侧翻报警触发; 4:司机上班签到 5:司机下班签退 6: 空车转重车 7:重车转空车**/ private Integer eventcode; /** * word导出时 显示 */ private String eventcodeStr; /** 通道ID **/ private Integer accessid; /** 摄像头立即拍摄记录表ID **/ private Integer msid; /** 多媒体数据保存路径 **/ private String multimediapath; /** 原始数据包 **/ private String data; /** 创建时间 **/ private String createtime; /** * 媒体id */ private Integer mediaid; private String stime; private String etime; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getBlocid() { return blocid; } public void setBlocid(Integer blocid) { this.blocid = blocid; } public String getBlocname() { return blocname; } public void setBlocname(String blocname) { this.blocname = blocname; } public Integer getUserid() { return userid; } public void setUserid(Integer userid) { this.userid = userid; } public String getTerminal() { return terminal; } public void setTerminal(String terminal) { this.terminal = terminal; } public String getCarnumber() { return carnumber; } public void setCarnumber(String carnumber) { this.carnumber = carnumber; } public Integer getDataid() { return dataid; } public void setDataid(Integer dataid) { this.dataid = dataid; } public Integer getMediatype() { return mediatype; } public void setMediatype(Integer mediatype) { this.mediatype = mediatype; } public Integer getFormat() { return format; } public void setFormat(Integer format) { this.format = format; } public Integer getEventcode() { return eventcode; } public void setEventcode(Integer eventcode) { this.eventcode = eventcode; } public Integer getAccessid() { return accessid; } public void setAccessid(Integer accessid) { this.accessid = accessid; } public Integer getMsid() { return msid; } public void setMsid(Integer msid) { this.msid = msid; } public String getMultimediapath() { return multimediapath; } public void setMultimediapath(String multimediapath) { this.multimediapath = multimediapath; } public String getData() { return data; } public void setData(String data) { this.data = data; } public String getCreatetime() { return createtime; } public void setCreatetime(String createtime) { this.createtime = createtime; } public Integer getMediaid() { return mediaid; } public void setMediaid(Integer mediaid) { this.mediaid = mediaid; } public String getStime() { return stime; } public void setStime(String stime) { this.stime = stime; } public String getEtime() { return etime; } public void setEtime(String etime) { this.etime = etime; } public Integer getCarid() { return carid; } public void setCarid(Integer carid) { this.carid = carid; } public String getEventcodeStr() { return eventcodeStr; } public void setEventcodeStr(String eventcodeStr) { this.eventcodeStr = eventcodeStr; } }
Car-eye-team/Car-eye-server
car-server/web/CarEye/src/com/careye/monitor/domain/MultiMedia.java
1,474
/** 创建时间 **/
block_comment
zh-cn
/** * Description: car-eye车辆管理平台 * 文件名:MultiMedia.java * 版本信息:1.0 * 日期:2015-3-26 * Copyright car-eye 车辆管理平台 Copyright (c) 2015 * 版权所有 */ package com.careye.monitor.domain; /** * @项目名称:car-eye * @类名称:MultiMedia * @类描述: * @创建人:Yuqk * @创建时间:2015-3-26 下午03:22:34 * @修改人:Yuqk * @修改时间:2015-3-26 下午03:22:34 * @修改备注: * @version 1.0 */ public class MultiMedia { private Integer id; private Integer carid; /** 组织机构 **/ private Integer blocid; private String blocname; /** 用户ID **/ private Integer userid; /** 终端号码 **/ private String terminal; /** 车牌号 **/ private String carnumber; /** 多媒体数据ID **/ private Integer dataid; /** 多媒体类型 0:图像;1:音频;2:视频 **/ private Integer mediatype; /** 多媒体格式编码 0:JPEG;1:TIF;2:MP3;3:WAV;4:WMV;其他保留 **/ private Integer format; /** 事件项编码 0:平台下发指令; 1:定时动作; 2:抢劫报警触发; 3:碰撞侧翻报警触发; 4:司机上班签到 5:司机下班签退 6: 空车转重车 7:重车转空车**/ private Integer eventcode; /** * word导出时 显示 */ private String eventcodeStr; /** 通道ID **/ private Integer accessid; /** 摄像头立即拍摄记录表ID **/ private Integer msid; /** 多媒体数据保存路径 **/ private String multimediapath; /** 原始数据包 **/ private String data; /** 创建时 <SUF>*/ private String createtime; /** * 媒体id */ private Integer mediaid; private String stime; private String etime; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getBlocid() { return blocid; } public void setBlocid(Integer blocid) { this.blocid = blocid; } public String getBlocname() { return blocname; } public void setBlocname(String blocname) { this.blocname = blocname; } public Integer getUserid() { return userid; } public void setUserid(Integer userid) { this.userid = userid; } public String getTerminal() { return terminal; } public void setTerminal(String terminal) { this.terminal = terminal; } public String getCarnumber() { return carnumber; } public void setCarnumber(String carnumber) { this.carnumber = carnumber; } public Integer getDataid() { return dataid; } public void setDataid(Integer dataid) { this.dataid = dataid; } public Integer getMediatype() { return mediatype; } public void setMediatype(Integer mediatype) { this.mediatype = mediatype; } public Integer getFormat() { return format; } public void setFormat(Integer format) { this.format = format; } public Integer getEventcode() { return eventcode; } public void setEventcode(Integer eventcode) { this.eventcode = eventcode; } public Integer getAccessid() { return accessid; } public void setAccessid(Integer accessid) { this.accessid = accessid; } public Integer getMsid() { return msid; } public void setMsid(Integer msid) { this.msid = msid; } public String getMultimediapath() { return multimediapath; } public void setMultimediapath(String multimediapath) { this.multimediapath = multimediapath; } public String getData() { return data; } public void setData(String data) { this.data = data; } public String getCreatetime() { return createtime; } public void setCreatetime(String createtime) { this.createtime = createtime; } public Integer getMediaid() { return mediaid; } public void setMediaid(Integer mediaid) { this.mediaid = mediaid; } public String getStime() { return stime; } public void setStime(String stime) { this.stime = stime; } public String getEtime() { return etime; } public void setEtime(String etime) { this.etime = etime; } public Integer getCarid() { return carid; } public void setCarid(Integer carid) { this.carid = carid; } public String getEventcodeStr() { return eventcodeStr; } public void setEventcodeStr(String eventcodeStr) { this.eventcodeStr = eventcodeStr; } }
0
1,190
5
1,474
4
1,430
3
1,474
4
1,772
8
false
false
false
false
false
true
33607_11
package com.shuyu; import android.annotation.TargetApi; import android.graphics.Bitmap; import android.net.Uri; import android.net.http.SslError; import android.os.Build; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.webkit.DownloadListener; import android.webkit.JavascriptInterface; import android.webkit.JsPromptResult; import android.webkit.JsResult; import android.webkit.SslErrorHandler; import android.webkit.ValueCallback; import android.webkit.WebChromeClient; import android.webkit.WebResourceError; import android.webkit.WebResourceRequest; import android.webkit.WebResourceResponse; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.FrameLayout; import android.widget.Toast; import java.util.Set; /** * 演示WebView中的Api说明、js交互的方法,还有注意事项 * <p> * 1、内存泄漏防备 * 2、配置webView * 3、页面加载开始,错误,拦截请求,接受Error等 * 4、页面加载进度,title,图标,js弹框等 * 5、js交互与安全 */ public class APIWebViewActivity extends AppCompatActivity implements View.OnClickListener { FrameLayout mRootLayout; WebView mWebView; Button mButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_api_webview); findViewById(R.id.call_js_function).setOnClickListener(this); //添加webView到布局中 addWebViewToLayout(); //set webView Setting setWebView(); //set webView Client setWebClient(); //set webView chrome setWebViewChromeClient(); //load web loadUrl(); } /** * 主动清空销毁来避免内存泄漏 */ @Override protected void onDestroy() { if (mWebView != null) { mWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null); mWebView.clearHistory(); ((ViewGroup) mWebView.getParent()).removeView(mWebView); mWebView.destroy(); mWebView = null; } super.onDestroy(); } /** * 1、不在xml中定义Webview,而是在需要的时候在Activity中创建 * 使用getApplicationgContext(),避免内存泄漏。 * <p> * 2、当然,你也可以配置webView所在Activity, * 在AndroidManifest中的进程为:android:process=":remote" * 避免泄漏影响主进程 **/ void addWebViewToLayout() { mRootLayout = (FrameLayout) findViewById(R.id.js_root_layout); FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); mWebView = new WebView(getApplicationContext()); mWebView.setLayoutParams(params); mRootLayout.addView(mWebView); } /** * 配置webView */ void setWebView() { //声明WebSettings子类 WebSettings webSettings = mWebView.getSettings(); //支持Javascript交互 webSettings.setJavaScriptEnabled(true); //设置自适应屏幕,两者合用 webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小 webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小 //缩放操作 webSettings.setSupportZoom(true); //支持缩放,默认为true。是下面那个的前提。 webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false,则该WebView不可缩放 webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件 //其他细节操作 //webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //关闭webview中缓存 webSettings.setAllowFileAccess(true); //设置可以访问文件 //对于不需要使用 file 协议的应用,禁用 file 协议;防止文件泄密,file协议即是file:// //webSettings.setAllowFileAccess(false); //webSettings.setAllowFileAccessFromFileURLs(false); //webSettings.setAllowUniversalAccessFromFileURLs(false); webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口 webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片 webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式 mWebView.setDownloadListener(new DownloadListener() { @Override public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) { //网页中触发下载动作 } }); //增加js交互接口 mWebView.addJavascriptInterface(new JsCallAndroidInterface(), "JSCallBackInterface"); } /** * 设置webView的Client,如页面加载开始,错误,拦截请求,接受Error等 */ void setWebClient() { mWebView.setWebViewClient(new WebViewClient() { //拦截页面中的url加载,21以下的 @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (resolveShouldLoadLogic(url)) { return true; } return super.shouldOverrideUrlLoading(view, url); } //拦截页面中的url加载,21以上的 @TargetApi(21) @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { if (resolveShouldLoadLogic(request.getUrl().toString())) { return true; } return super.shouldOverrideUrlLoading(view, request); } //页面开始加载 @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); } //页面加载完成 @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); } //页面加载每一个资源,如图片 @Override public void onLoadResource(WebView view, String url) { super.onLoadResource(view, url); } //监听WebView发出的请求并做相应的处理 //浏览器的渲染以及资源加载都是在一个线程中,如果在shouldInterceptRequest处理时间过长,WebView界面就会阻塞 //21以下的 @Override public WebResourceResponse shouldInterceptRequest(WebView view, String url) { return super.shouldInterceptRequest(view, url); } //监听WebView发出的请求并做相应的处理 //浏览器的渲染以及资源加载都是在一个线程中,如果在shouldInterceptRequest处理时间过长,WebView界面就会阻塞 //21以上的 @Override public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) { return super.shouldInterceptRequest(view, request); } //页面加载出现错误,23以下的 @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { super.onReceivedError(view, errorCode, description, failingUrl); switch (errorCode) { case 404: //view.loadUrl("加载一个错误页面提示,优化体验"); break; } } //页面加载出现错误,23以上的 @TargetApi(23) @Override public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { super.onReceivedError(view, request, error); switch (error.getErrorCode()) { case 404: //view.loadUrl("加载一个错误页面提示,优化体验"); break; } } //https错误 @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { super.onReceivedSslError(view, handler, error); } }); } /** * 设置webView的辅助功能,如页面加载进度,title,图标,js弹框等 */ void setWebViewChromeClient() { mWebView.setWebChromeClient(new WebChromeClient() { //页面加载进度 @Override public void onProgressChanged(WebView view, int newProgress) { super.onProgressChanged(view, newProgress); } //获取标题 @Override public void onReceivedTitle(WebView view, String title) { super.onReceivedTitle(view, title); } //获取图标 @Override public void onReceivedIcon(WebView view, Bitmap icon) { super.onReceivedIcon(view, icon); } //是否支持页面中的js警告弹出框 @Override public boolean onJsAlert(WebView view, String url, String message, JsResult result) { Toast.makeText(APIWebViewActivity.this, message, Toast.LENGTH_SHORT).show(); return super.onJsAlert(view, url, message, result); } //是否支持页面中的js确定弹出框 @Override public boolean onJsConfirm(WebView view, String url, String message, JsResult result) { return super.onJsConfirm(view, url, message, result); } //是否支持页面中的js输入弹出框 @Override public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) { /** * 有时候,为了安全考虑,js的参数回调,会通过这类地方回调回来,然后不弹出框。 */ if(resolveJSPrompt(message)) { return true; } return super.onJsPrompt(view, url, message, defaultValue, result); } }); } /** * 加载url */ void loadUrl() { // 格式规定为:file:///android_asset/文件名.html mWebView.loadUrl("file:///android_asset/localHtml.html"); //方式1. 加载远程网页: //mWebView.loadUrl("http://www.google.com/"); //方式2:加载asset的html页面 //mWebView.loadUrl("file:///android_asset/localHtml.html"); //方式3:加载手机SD的html页面 //mWebView.loadUrl("file:///mnt/sdcard/database/taobao.html"); } /** * 执行网页中的js方法 */ void callJsFunction() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { mWebView.evaluateJavascript("javascript:callJS()", new ValueCallback<String>() { @Override public void onReceiveValue(String value) { //接受返回值 } }); } else { mWebView.loadUrl("javascript:callJS()"); } } /** * js与web交互1 * js 与 原生交互接口 */ private class JsCallAndroidInterface { //@JavascriptInterface注解方法,js端调用,4.2以后安全 //4.2以前,当JS拿到Android这个对象后,就可以调用这个Android对象中所有的方法,包括系统类(java.lang.Runtime 类),从而进行任意代码执行。 @JavascriptInterface public void callback(String msg) { Toast.makeText(APIWebViewActivity.this, "JS方法回调到web了 :" + msg, Toast.LENGTH_SHORT).show(); } } /** * js与web交互2 * 通过 shouldOverrideUrlLoading 与 js交互 */ private boolean resolveShouldLoadLogic(String url) { Uri uri = Uri.parse(url); //解析协议 if (uri.getScheme().equals("js")) { if (uri.getAuthority().equals("Authority")) { //你还可以继续接续参数 //Set<String> collection = uri.getQueryParameterNames(); Toast.makeText(APIWebViewActivity.this, "JS 2方法回调到web了", Toast.LENGTH_SHORT).show(); } return true; } return false; } /** * js与web交互3 * 通过 onJsPrompt 与 js交互 */ private boolean resolveJSPrompt(String message) { Uri uri = Uri.parse(message); if ( uri.getScheme().equals("js")) { if (uri.getAuthority().equals("Authority")) { //Set<String> collection = uri.getQueryParameterNames(); //参数result:代表消息框的返回值(输入值) //result.confirm("JS 3方法回调到web"); Toast.makeText(APIWebViewActivity.this, "JS 3方法回调到web了", Toast.LENGTH_SHORT).show(); } return true; } return false; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.call_js_function: callJsFunction(); break; } } }
CarGuo/CustomActionWebView
app/src/main/java/com/shuyu/APIWebViewActivity.java
3,037
//设置自适应屏幕,两者合用
line_comment
zh-cn
package com.shuyu; import android.annotation.TargetApi; import android.graphics.Bitmap; import android.net.Uri; import android.net.http.SslError; import android.os.Build; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.webkit.DownloadListener; import android.webkit.JavascriptInterface; import android.webkit.JsPromptResult; import android.webkit.JsResult; import android.webkit.SslErrorHandler; import android.webkit.ValueCallback; import android.webkit.WebChromeClient; import android.webkit.WebResourceError; import android.webkit.WebResourceRequest; import android.webkit.WebResourceResponse; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.FrameLayout; import android.widget.Toast; import java.util.Set; /** * 演示WebView中的Api说明、js交互的方法,还有注意事项 * <p> * 1、内存泄漏防备 * 2、配置webView * 3、页面加载开始,错误,拦截请求,接受Error等 * 4、页面加载进度,title,图标,js弹框等 * 5、js交互与安全 */ public class APIWebViewActivity extends AppCompatActivity implements View.OnClickListener { FrameLayout mRootLayout; WebView mWebView; Button mButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_api_webview); findViewById(R.id.call_js_function).setOnClickListener(this); //添加webView到布局中 addWebViewToLayout(); //set webView Setting setWebView(); //set webView Client setWebClient(); //set webView chrome setWebViewChromeClient(); //load web loadUrl(); } /** * 主动清空销毁来避免内存泄漏 */ @Override protected void onDestroy() { if (mWebView != null) { mWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null); mWebView.clearHistory(); ((ViewGroup) mWebView.getParent()).removeView(mWebView); mWebView.destroy(); mWebView = null; } super.onDestroy(); } /** * 1、不在xml中定义Webview,而是在需要的时候在Activity中创建 * 使用getApplicationgContext(),避免内存泄漏。 * <p> * 2、当然,你也可以配置webView所在Activity, * 在AndroidManifest中的进程为:android:process=":remote" * 避免泄漏影响主进程 **/ void addWebViewToLayout() { mRootLayout = (FrameLayout) findViewById(R.id.js_root_layout); FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); mWebView = new WebView(getApplicationContext()); mWebView.setLayoutParams(params); mRootLayout.addView(mWebView); } /** * 配置webView */ void setWebView() { //声明WebSettings子类 WebSettings webSettings = mWebView.getSettings(); //支持Javascript交互 webSettings.setJavaScriptEnabled(true); //设置 <SUF> webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小 webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小 //缩放操作 webSettings.setSupportZoom(true); //支持缩放,默认为true。是下面那个的前提。 webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false,则该WebView不可缩放 webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件 //其他细节操作 //webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //关闭webview中缓存 webSettings.setAllowFileAccess(true); //设置可以访问文件 //对于不需要使用 file 协议的应用,禁用 file 协议;防止文件泄密,file协议即是file:// //webSettings.setAllowFileAccess(false); //webSettings.setAllowFileAccessFromFileURLs(false); //webSettings.setAllowUniversalAccessFromFileURLs(false); webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口 webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片 webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式 mWebView.setDownloadListener(new DownloadListener() { @Override public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) { //网页中触发下载动作 } }); //增加js交互接口 mWebView.addJavascriptInterface(new JsCallAndroidInterface(), "JSCallBackInterface"); } /** * 设置webView的Client,如页面加载开始,错误,拦截请求,接受Error等 */ void setWebClient() { mWebView.setWebViewClient(new WebViewClient() { //拦截页面中的url加载,21以下的 @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (resolveShouldLoadLogic(url)) { return true; } return super.shouldOverrideUrlLoading(view, url); } //拦截页面中的url加载,21以上的 @TargetApi(21) @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { if (resolveShouldLoadLogic(request.getUrl().toString())) { return true; } return super.shouldOverrideUrlLoading(view, request); } //页面开始加载 @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); } //页面加载完成 @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); } //页面加载每一个资源,如图片 @Override public void onLoadResource(WebView view, String url) { super.onLoadResource(view, url); } //监听WebView发出的请求并做相应的处理 //浏览器的渲染以及资源加载都是在一个线程中,如果在shouldInterceptRequest处理时间过长,WebView界面就会阻塞 //21以下的 @Override public WebResourceResponse shouldInterceptRequest(WebView view, String url) { return super.shouldInterceptRequest(view, url); } //监听WebView发出的请求并做相应的处理 //浏览器的渲染以及资源加载都是在一个线程中,如果在shouldInterceptRequest处理时间过长,WebView界面就会阻塞 //21以上的 @Override public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) { return super.shouldInterceptRequest(view, request); } //页面加载出现错误,23以下的 @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { super.onReceivedError(view, errorCode, description, failingUrl); switch (errorCode) { case 404: //view.loadUrl("加载一个错误页面提示,优化体验"); break; } } //页面加载出现错误,23以上的 @TargetApi(23) @Override public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { super.onReceivedError(view, request, error); switch (error.getErrorCode()) { case 404: //view.loadUrl("加载一个错误页面提示,优化体验"); break; } } //https错误 @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { super.onReceivedSslError(view, handler, error); } }); } /** * 设置webView的辅助功能,如页面加载进度,title,图标,js弹框等 */ void setWebViewChromeClient() { mWebView.setWebChromeClient(new WebChromeClient() { //页面加载进度 @Override public void onProgressChanged(WebView view, int newProgress) { super.onProgressChanged(view, newProgress); } //获取标题 @Override public void onReceivedTitle(WebView view, String title) { super.onReceivedTitle(view, title); } //获取图标 @Override public void onReceivedIcon(WebView view, Bitmap icon) { super.onReceivedIcon(view, icon); } //是否支持页面中的js警告弹出框 @Override public boolean onJsAlert(WebView view, String url, String message, JsResult result) { Toast.makeText(APIWebViewActivity.this, message, Toast.LENGTH_SHORT).show(); return super.onJsAlert(view, url, message, result); } //是否支持页面中的js确定弹出框 @Override public boolean onJsConfirm(WebView view, String url, String message, JsResult result) { return super.onJsConfirm(view, url, message, result); } //是否支持页面中的js输入弹出框 @Override public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) { /** * 有时候,为了安全考虑,js的参数回调,会通过这类地方回调回来,然后不弹出框。 */ if(resolveJSPrompt(message)) { return true; } return super.onJsPrompt(view, url, message, defaultValue, result); } }); } /** * 加载url */ void loadUrl() { // 格式规定为:file:///android_asset/文件名.html mWebView.loadUrl("file:///android_asset/localHtml.html"); //方式1. 加载远程网页: //mWebView.loadUrl("http://www.google.com/"); //方式2:加载asset的html页面 //mWebView.loadUrl("file:///android_asset/localHtml.html"); //方式3:加载手机SD的html页面 //mWebView.loadUrl("file:///mnt/sdcard/database/taobao.html"); } /** * 执行网页中的js方法 */ void callJsFunction() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { mWebView.evaluateJavascript("javascript:callJS()", new ValueCallback<String>() { @Override public void onReceiveValue(String value) { //接受返回值 } }); } else { mWebView.loadUrl("javascript:callJS()"); } } /** * js与web交互1 * js 与 原生交互接口 */ private class JsCallAndroidInterface { //@JavascriptInterface注解方法,js端调用,4.2以后安全 //4.2以前,当JS拿到Android这个对象后,就可以调用这个Android对象中所有的方法,包括系统类(java.lang.Runtime 类),从而进行任意代码执行。 @JavascriptInterface public void callback(String msg) { Toast.makeText(APIWebViewActivity.this, "JS方法回调到web了 :" + msg, Toast.LENGTH_SHORT).show(); } } /** * js与web交互2 * 通过 shouldOverrideUrlLoading 与 js交互 */ private boolean resolveShouldLoadLogic(String url) { Uri uri = Uri.parse(url); //解析协议 if (uri.getScheme().equals("js")) { if (uri.getAuthority().equals("Authority")) { //你还可以继续接续参数 //Set<String> collection = uri.getQueryParameterNames(); Toast.makeText(APIWebViewActivity.this, "JS 2方法回调到web了", Toast.LENGTH_SHORT).show(); } return true; } return false; } /** * js与web交互3 * 通过 onJsPrompt 与 js交互 */ private boolean resolveJSPrompt(String message) { Uri uri = Uri.parse(message); if ( uri.getScheme().equals("js")) { if (uri.getAuthority().equals("Authority")) { //Set<String> collection = uri.getQueryParameterNames(); //参数result:代表消息框的返回值(输入值) //result.confirm("JS 3方法回调到web"); Toast.makeText(APIWebViewActivity.this, "JS 3方法回调到web了", Toast.LENGTH_SHORT).show(); } return true; } return false; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.call_js_function: callJsFunction(); break; } } }
0
2,788
9
3,037
12
3,198
9
3,037
12
4,068
19
false
false
false
false
false
true
1495_23
package com.example.gsyvideoplayer; import android.annotation.TargetApi; import android.content.pm.ActivityInfo; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.transition.Transition; import android.view.KeyEvent; import android.view.View; import android.widget.ImageView; import androidx.appcompat.app.AppCompatActivity; import androidx.core.view.ViewCompat; import com.example.gsyvideoplayer.databinding.ActivityPlayBinding; import com.example.gsyvideoplayer.databinding.ActivityPlayTvBinding; import com.example.gsyvideoplayer.listener.OnTransitionListener; import com.example.gsyvideoplayer.model.SwitchVideoModel; import com.shuyu.gsyvideoplayer.GSYVideoManager; import com.shuyu.gsyvideoplayer.utils.OrientationUtils; import java.util.ArrayList; import java.util.List; /** * 单独的视频播放页面 * Created by Bill on 2023/7/25. */ public class PlayTVActivity extends AppCompatActivity { public final static String IMG_TRANSITION = "IMG_TRANSITION"; public final static String TRANSITION = "TRANSITION"; OrientationUtils orientationUtils; private boolean isTransition; private Transition transition; private ActivityPlayTvBinding binding; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivityPlayTvBinding.inflate(getLayoutInflater()); View rootView = binding.getRoot(); setContentView(rootView); isTransition = getIntent().getBooleanExtra(TRANSITION, false); init(); } private void init() { String url = "https://res.exexm.com/cw_145225549855002"; //String url = "http://7xse1z.com1.z0.glb.clouddn.com/1491813192"; //需要路径的 //videoPlayer.setUp(url, true, new File(FileUtils.getPath()), ""); //借用了jjdxm_ijkplayer的URL String source1 = "http://devimages.apple.com.edgekey.net/streaming/examples/bipbop_4x3/gear1/prog_index.m3u8"; String name = "普通"; SwitchVideoModel switchVideoModel = new SwitchVideoModel(name, source1); String source2 = "http://devimages.apple.com.edgekey.net/streaming/examples/bipbop_4x3/gear3/prog_index.m3u8"; String name2 = "清晰"; SwitchVideoModel switchVideoModel2 = new SwitchVideoModel(name2, source2); List<SwitchVideoModel> list = new ArrayList<>(); list.add(switchVideoModel); list.add(switchVideoModel2); binding.videoPlayerTv.setUp(list.get(0).getUrl(), false, "测试视频"); //增加封面 ImageView imageView = new ImageView(this); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setImageResource(R.mipmap.xxx1); binding.videoPlayerTv.setThumbImageView(imageView); //增加title binding.videoPlayerTv.getTitleTextView().setVisibility(View.VISIBLE); //videoPlayer.setShowPauseCover(false); //videoPlayer.setSpeed(2f); //设置返回键 binding.videoPlayerTv.getBackButton().setVisibility(View.VISIBLE); //设置旋转 orientationUtils = new OrientationUtils(this, binding.videoPlayerTv); //设置全屏按键功能,这是使用的是选择屏幕,而不是全屏 binding.videoPlayerTv.getFullscreenButton().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // ------- !!!如果不需要旋转屏幕,可以不调用!!!------- // 不需要屏幕旋转,还需要设置 setNeedOrientationUtils(false) orientationUtils.resolveByClick(); } }); //videoPlayer.setBottomProgressBarDrawable(getResources().getDrawable(R.drawable.video_new_progress)); //videoPlayer.setDialogVolumeProgressBar(getResources().getDrawable(R.drawable.video_new_volume_progress_bg)); //videoPlayer.setDialogProgressBar(getResources().getDrawable(R.drawable.video_new_progress)); //videoPlayer.setBottomShowProgressBarDrawable(getResources().getDrawable(R.drawable.video_new_seekbar_progress), //getResources().getDrawable(R.drawable.video_new_seekbar_thumb)); //videoPlayer.setDialogProgressColor(getResources().getColor(R.color.colorAccent), -11); //是否可以滑动调整 binding.videoPlayerTv.setIsTouchWiget(true); //设置返回按键功能 binding.videoPlayerTv.getBackButton().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); //过渡动画 initTransition(); } @Override protected void onPause() { super.onPause(); binding.videoPlayerTv.onVideoPause(); } @Override protected void onResume() { super.onResume(); binding.videoPlayerTv.onVideoResume(); } @TargetApi(Build.VERSION_CODES.KITKAT) @Override protected void onDestroy() { super.onDestroy(); if (orientationUtils != null) orientationUtils.releaseListener(); } @Override public void onBackPressed() { //先返回正常状态 if (orientationUtils.getScreenType() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) { binding.videoPlayerTv.getFullscreenButton().performClick(); return; } //释放所有 binding.videoPlayerTv.setVideoAllCallBack(null); GSYVideoManager.releaseAllVideos(); if (isTransition && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { super.onBackPressed(); } else { new Handler().postDelayed(new Runnable() { @Override public void run() { finish(); overridePendingTransition(androidx.appcompat.R.anim.abc_fade_in, androidx.appcompat.R.anim.abc_fade_out); } }, 500); } } private void initTransition() { if (isTransition && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { postponeEnterTransition(); ViewCompat.setTransitionName(binding.videoPlayerTv, IMG_TRANSITION); addTransitionListener(); startPostponedEnterTransition(); } else { binding.videoPlayerTv.startPlayLogic(); } } @TargetApi(Build.VERSION_CODES.LOLLIPOP) private boolean addTransitionListener() { transition = getWindow().getSharedElementEnterTransition(); if (transition != null) { transition.addListener(new OnTransitionListener() { @Override public void onTransitionEnd(Transition transition) { super.onTransitionEnd(transition); binding.videoPlayerTv.startPlayLogic(); transition.removeListener(this); } }); return true; } return false; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { binding.videoPlayerTv.onKeyDown(keyCode,event); return super.onKeyDown(keyCode, event); } }
CarGuo/GSYVideoPlayer
app/src/main/java/com/example/gsyvideoplayer/PlayTVActivity.java
1,745
//是否可以滑动调整
line_comment
zh-cn
package com.example.gsyvideoplayer; import android.annotation.TargetApi; import android.content.pm.ActivityInfo; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.transition.Transition; import android.view.KeyEvent; import android.view.View; import android.widget.ImageView; import androidx.appcompat.app.AppCompatActivity; import androidx.core.view.ViewCompat; import com.example.gsyvideoplayer.databinding.ActivityPlayBinding; import com.example.gsyvideoplayer.databinding.ActivityPlayTvBinding; import com.example.gsyvideoplayer.listener.OnTransitionListener; import com.example.gsyvideoplayer.model.SwitchVideoModel; import com.shuyu.gsyvideoplayer.GSYVideoManager; import com.shuyu.gsyvideoplayer.utils.OrientationUtils; import java.util.ArrayList; import java.util.List; /** * 单独的视频播放页面 * Created by Bill on 2023/7/25. */ public class PlayTVActivity extends AppCompatActivity { public final static String IMG_TRANSITION = "IMG_TRANSITION"; public final static String TRANSITION = "TRANSITION"; OrientationUtils orientationUtils; private boolean isTransition; private Transition transition; private ActivityPlayTvBinding binding; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivityPlayTvBinding.inflate(getLayoutInflater()); View rootView = binding.getRoot(); setContentView(rootView); isTransition = getIntent().getBooleanExtra(TRANSITION, false); init(); } private void init() { String url = "https://res.exexm.com/cw_145225549855002"; //String url = "http://7xse1z.com1.z0.glb.clouddn.com/1491813192"; //需要路径的 //videoPlayer.setUp(url, true, new File(FileUtils.getPath()), ""); //借用了jjdxm_ijkplayer的URL String source1 = "http://devimages.apple.com.edgekey.net/streaming/examples/bipbop_4x3/gear1/prog_index.m3u8"; String name = "普通"; SwitchVideoModel switchVideoModel = new SwitchVideoModel(name, source1); String source2 = "http://devimages.apple.com.edgekey.net/streaming/examples/bipbop_4x3/gear3/prog_index.m3u8"; String name2 = "清晰"; SwitchVideoModel switchVideoModel2 = new SwitchVideoModel(name2, source2); List<SwitchVideoModel> list = new ArrayList<>(); list.add(switchVideoModel); list.add(switchVideoModel2); binding.videoPlayerTv.setUp(list.get(0).getUrl(), false, "测试视频"); //增加封面 ImageView imageView = new ImageView(this); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setImageResource(R.mipmap.xxx1); binding.videoPlayerTv.setThumbImageView(imageView); //增加title binding.videoPlayerTv.getTitleTextView().setVisibility(View.VISIBLE); //videoPlayer.setShowPauseCover(false); //videoPlayer.setSpeed(2f); //设置返回键 binding.videoPlayerTv.getBackButton().setVisibility(View.VISIBLE); //设置旋转 orientationUtils = new OrientationUtils(this, binding.videoPlayerTv); //设置全屏按键功能,这是使用的是选择屏幕,而不是全屏 binding.videoPlayerTv.getFullscreenButton().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // ------- !!!如果不需要旋转屏幕,可以不调用!!!------- // 不需要屏幕旋转,还需要设置 setNeedOrientationUtils(false) orientationUtils.resolveByClick(); } }); //videoPlayer.setBottomProgressBarDrawable(getResources().getDrawable(R.drawable.video_new_progress)); //videoPlayer.setDialogVolumeProgressBar(getResources().getDrawable(R.drawable.video_new_volume_progress_bg)); //videoPlayer.setDialogProgressBar(getResources().getDrawable(R.drawable.video_new_progress)); //videoPlayer.setBottomShowProgressBarDrawable(getResources().getDrawable(R.drawable.video_new_seekbar_progress), //getResources().getDrawable(R.drawable.video_new_seekbar_thumb)); //videoPlayer.setDialogProgressColor(getResources().getColor(R.color.colorAccent), -11); //是否 <SUF> binding.videoPlayerTv.setIsTouchWiget(true); //设置返回按键功能 binding.videoPlayerTv.getBackButton().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); //过渡动画 initTransition(); } @Override protected void onPause() { super.onPause(); binding.videoPlayerTv.onVideoPause(); } @Override protected void onResume() { super.onResume(); binding.videoPlayerTv.onVideoResume(); } @TargetApi(Build.VERSION_CODES.KITKAT) @Override protected void onDestroy() { super.onDestroy(); if (orientationUtils != null) orientationUtils.releaseListener(); } @Override public void onBackPressed() { //先返回正常状态 if (orientationUtils.getScreenType() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) { binding.videoPlayerTv.getFullscreenButton().performClick(); return; } //释放所有 binding.videoPlayerTv.setVideoAllCallBack(null); GSYVideoManager.releaseAllVideos(); if (isTransition && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { super.onBackPressed(); } else { new Handler().postDelayed(new Runnable() { @Override public void run() { finish(); overridePendingTransition(androidx.appcompat.R.anim.abc_fade_in, androidx.appcompat.R.anim.abc_fade_out); } }, 500); } } private void initTransition() { if (isTransition && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { postponeEnterTransition(); ViewCompat.setTransitionName(binding.videoPlayerTv, IMG_TRANSITION); addTransitionListener(); startPostponedEnterTransition(); } else { binding.videoPlayerTv.startPlayLogic(); } } @TargetApi(Build.VERSION_CODES.LOLLIPOP) private boolean addTransitionListener() { transition = getWindow().getSharedElementEnterTransition(); if (transition != null) { transition.addListener(new OnTransitionListener() { @Override public void onTransitionEnd(Transition transition) { super.onTransitionEnd(transition); binding.videoPlayerTv.startPlayLogic(); transition.removeListener(this); } }); return true; } return false; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { binding.videoPlayerTv.onKeyDown(keyCode,event); return super.onKeyDown(keyCode, event); } }
0
1,451
6
1,745
6
1,818
5
1,745
6
2,187
13
false
false
false
false
false
true
55285_2
package scut.carson_ho.androidinterview.AlgorithmLearning; /** * Created by Carson_Ho on 17/11/23. */ public class Exam_56_1 { /** * 解题算法 */ public static int findOnceNumber(int[] intArray) throws Exception { // 判断输入数据的合法性 if (intArray == null || intArray.length < 1) { System.out.println("数组为空或者长度不足"); return 0; } // 将和的结果存储到1个大小 = 32的数组中 int[] bitSum = new int[32]; // 1. 将数组所有数字的二进制表示的每1位都加起来 // 将和的结果都放到数组中 for (int i : intArray) { int bitMask = 1; for (int j = 31; j >= 0; --j){ int bit = i & bitMask; if (bit != 0){ bitSum[j] += 1; } bitMask = bitMask << 1; } } //2. 对每1位的和 都对3取余 int result = 0; for (int i = 0; i < 32; i++){ result = result << 1; // 若能被3整除(余数 = 0),则说明包含该位数的数字出现了3次,即 只出现1次的数字二进制表示中对应那位 = 0 // 若不能被3整除(余数 = 1),则说明包含该位数的数字出现了1次,即 只出现1次的数字二进制表示中对应那位 = 1 result += bitSum[i] % 3; } return result; } /** * 测试用例 */ public static void main(String[] args) throws Exception { int[] array1 = {2,4,2,5,2,5,5}; System.out.println("数组中唯一出现一次数字是:" + findOnceNumber(array1)); } }
Carson-Ho/AndroidLearning
app/src/main/java/scut/carson_ho/androidinterview/AlgorithmLearning/Exam_56_1.java
493
// 判断输入数据的合法性
line_comment
zh-cn
package scut.carson_ho.androidinterview.AlgorithmLearning; /** * Created by Carson_Ho on 17/11/23. */ public class Exam_56_1 { /** * 解题算法 */ public static int findOnceNumber(int[] intArray) throws Exception { // 判断 <SUF> if (intArray == null || intArray.length < 1) { System.out.println("数组为空或者长度不足"); return 0; } // 将和的结果存储到1个大小 = 32的数组中 int[] bitSum = new int[32]; // 1. 将数组所有数字的二进制表示的每1位都加起来 // 将和的结果都放到数组中 for (int i : intArray) { int bitMask = 1; for (int j = 31; j >= 0; --j){ int bit = i & bitMask; if (bit != 0){ bitSum[j] += 1; } bitMask = bitMask << 1; } } //2. 对每1位的和 都对3取余 int result = 0; for (int i = 0; i < 32; i++){ result = result << 1; // 若能被3整除(余数 = 0),则说明包含该位数的数字出现了3次,即 只出现1次的数字二进制表示中对应那位 = 0 // 若不能被3整除(余数 = 1),则说明包含该位数的数字出现了1次,即 只出现1次的数字二进制表示中对应那位 = 1 result += bitSum[i] % 3; } return result; } /** * 测试用例 */ public static void main(String[] args) throws Exception { int[] array1 = {2,4,2,5,2,5,5}; System.out.println("数组中唯一出现一次数字是:" + findOnceNumber(array1)); } }
0
480
7
493
7
512
6
493
7
629
12
false
false
false
false
false
true
43679_9
package scut.carson_ho.shootatoffer; import java.util.ArrayList; /** * Created by Carson_Ho on 17/11/24. */ public class Exam_57_1 { /** * 解题算法 */ private static ArrayList<ArrayList<Integer>> findContinuousSequence(int sum) { ArrayList<ArrayList<Integer>> result =new ArrayList<ArrayList<Integer>>(); // 用于存储结果 // 判断输入数据的合法性 if (sum < 3){ System.out.println("输入的数据不合法"); return result; } // 1. 用2个指针分别指向当前序列的最小值 & 最大值 // 指针1(small ): 初始化指向1 // 指针2(big ): 初始化指向2 int start = 1; int end = 2; int curSum = start + end; // 注:对于连续序列求和,考虑到每次操作前后的序列大部分数字相同,只是增加 / 减少1个数字 // 故此处不采用循环求和,而是采用在前1个序列的基础上进行操作,从而减少不必要的运算,提高效率 int mid = (sum + 1) / 2; // 2. 计算 指针1 ~ 指针2 之间数字的和(m) while (start < mid) { // 2.1 若m = 题目输入的s,即 指针1 ~ 指针2 之间数字 即为所求 = 1组解 // 则:输出指针1 ~ 指针2 之间的数字序列、指针2 往后移1位、重复步骤2,继续求解 if (curSum == sum) { // 求和 ArrayList<Integer> list = new ArrayList<>(); for (int i = start; i <= end; i++) { list.add(i); } result.add(list); } // 2.2 若m > 题目输入的s // 则:指针p1后移1位、重复步骤2,直到指针1(small) > (s+1)/2 为止 while (curSum > sum && start < mid) { curSum -= start; start++; if (curSum == sum) { // 求和 ArrayList<Integer> list = new ArrayList<>(); for (int i = start; i <= end; i++) { list.add(i); } result.add(list); } } // 2.3 若m < 题目输入的s // 则,指针p2后移1位、指针1 ~ 指针2 之间数字多1个使得 m 变大 靠近 s,重复步骤2 end++; curSum += end; } return result; } /** * 测试用例 */ public static void main(String[] args){ // 功能测试 System.out.println("功能测试"); System.out.println(findContinuousSequence(15)); // 边界值输入测试:连续序列最小和 = 3 System.out.println("边界值测试"); System.out.println(findContinuousSequence(3)); } }
Carson-Ho/ShootAtOffer
app/src/main/java/scut/carson_ho/shootatoffer/Exam_57_1.java
757
// 2. 计算 指针1 ~ 指针2 之间数字的和(m)
line_comment
zh-cn
package scut.carson_ho.shootatoffer; import java.util.ArrayList; /** * Created by Carson_Ho on 17/11/24. */ public class Exam_57_1 { /** * 解题算法 */ private static ArrayList<ArrayList<Integer>> findContinuousSequence(int sum) { ArrayList<ArrayList<Integer>> result =new ArrayList<ArrayList<Integer>>(); // 用于存储结果 // 判断输入数据的合法性 if (sum < 3){ System.out.println("输入的数据不合法"); return result; } // 1. 用2个指针分别指向当前序列的最小值 & 最大值 // 指针1(small ): 初始化指向1 // 指针2(big ): 初始化指向2 int start = 1; int end = 2; int curSum = start + end; // 注:对于连续序列求和,考虑到每次操作前后的序列大部分数字相同,只是增加 / 减少1个数字 // 故此处不采用循环求和,而是采用在前1个序列的基础上进行操作,从而减少不必要的运算,提高效率 int mid = (sum + 1) / 2; // 2. <SUF> while (start < mid) { // 2.1 若m = 题目输入的s,即 指针1 ~ 指针2 之间数字 即为所求 = 1组解 // 则:输出指针1 ~ 指针2 之间的数字序列、指针2 往后移1位、重复步骤2,继续求解 if (curSum == sum) { // 求和 ArrayList<Integer> list = new ArrayList<>(); for (int i = start; i <= end; i++) { list.add(i); } result.add(list); } // 2.2 若m > 题目输入的s // 则:指针p1后移1位、重复步骤2,直到指针1(small) > (s+1)/2 为止 while (curSum > sum && start < mid) { curSum -= start; start++; if (curSum == sum) { // 求和 ArrayList<Integer> list = new ArrayList<>(); for (int i = start; i <= end; i++) { list.add(i); } result.add(list); } } // 2.3 若m < 题目输入的s // 则,指针p2后移1位、指针1 ~ 指针2 之间数字多1个使得 m 变大 靠近 s,重复步骤2 end++; curSum += end; } return result; } /** * 测试用例 */ public static void main(String[] args){ // 功能测试 System.out.println("功能测试"); System.out.println(findContinuousSequence(15)); // 边界值输入测试:连续序列最小和 = 3 System.out.println("边界值测试"); System.out.println(findContinuousSequence(3)); } }
0
737
26
755
21
767
20
757
21
1,028
30
false
false
false
false
false
true
40241_11
package com.itheima.mobilesafe.utils; import android.app.Activity; import android.app.admin.DevicePolicyManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.widget.Toast; import com.itheima.mobilesafe.receivers.MyDeviceAdminReceiver; /** * Created by Catherine on 2016/8/24. * Soft-World Inc. * catherine919@soft-world.com.tw */ public class MyAdminManager { private Context ctx; private DevicePolicyManager dpm; private ComponentName myAdmin; public MyAdminManager(Context ctx) { this.ctx = ctx; dpm = (DevicePolicyManager) ctx.getSystemService(Context.DEVICE_POLICY_SERVICE); myAdmin = new ComponentName(ctx, MyDeviceAdminReceiver.class); } /** * 取得管理员权限 */ public void getAdminPermission() { // Launch the activity to have the user enable our admin. Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN); intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, myAdmin); intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "哥们开启我可以一键锁屏,解放按钮"); Activity activity = (Activity) ctx; activity.startActivityForResult(intent, Constants.REQUEST_CODE_ENABLE_ADMIN); } /** * 锁屏 */ public void lockScreen() { if (dpm.isAdminActive(myAdmin)) dpm.lockNow(); else Toast.makeText(ctx, "哥们还没开启管理员权限", Toast.LENGTH_SHORT).show(); } /** * 重设锁屏密码 */ public void resetScreenPassword(String password) { if (dpm.isAdminActive(myAdmin)) dpm.resetPassword(password, 0); else Toast.makeText(ctx, "哥们还没开启管理员权限", Toast.LENGTH_SHORT).show(); } /** * 清除锁屏密码 */ public void unlockScreen() { if (dpm.isAdminActive(myAdmin)) { dpm.resetPassword("", 0); } else Toast.makeText(ctx, "哥们还没开启管理员权限", Toast.LENGTH_SHORT).show(); } /** * 清除数据 */ public void wipeData() { if (dpm.isAdminActive(myAdmin)) { dpm.wipeData(DevicePolicyManager.WIPE_EXTERNAL_STORAGE);//清除sd card dpm.wipeData(0);//恢复出厂设置 } else Toast.makeText(ctx, "哥们还没开启管理员权限", Toast.LENGTH_SHORT).show(); } /** * 卸载步骤: * 1. 先变成普通软件(清除管理员权限) * 2. 正常卸载 */ public void unInstall() { removeAdmin(); Intent intent = new Intent(Intent.ACTION_DELETE); intent.setData(Uri.parse("package:" + ctx.getPackageName())); ctx.startActivity(intent); } /** * 检查管理员权限 * * @return */ public boolean isAdmin() { if (dpm.isAdminActive(myAdmin)) return true; else return false; } /** * 清除管理员权限 */ public void removeAdmin() { if (dpm.isAdminActive(myAdmin)) dpm.removeActiveAdmin(myAdmin); } }
Catherine22/MobileManager
app/src/main/java/com/itheima/mobilesafe/utils/MyAdminManager.java
852
/** * 清除管理员权限 */
block_comment
zh-cn
package com.itheima.mobilesafe.utils; import android.app.Activity; import android.app.admin.DevicePolicyManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.widget.Toast; import com.itheima.mobilesafe.receivers.MyDeviceAdminReceiver; /** * Created by Catherine on 2016/8/24. * Soft-World Inc. * catherine919@soft-world.com.tw */ public class MyAdminManager { private Context ctx; private DevicePolicyManager dpm; private ComponentName myAdmin; public MyAdminManager(Context ctx) { this.ctx = ctx; dpm = (DevicePolicyManager) ctx.getSystemService(Context.DEVICE_POLICY_SERVICE); myAdmin = new ComponentName(ctx, MyDeviceAdminReceiver.class); } /** * 取得管理员权限 */ public void getAdminPermission() { // Launch the activity to have the user enable our admin. Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN); intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, myAdmin); intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "哥们开启我可以一键锁屏,解放按钮"); Activity activity = (Activity) ctx; activity.startActivityForResult(intent, Constants.REQUEST_CODE_ENABLE_ADMIN); } /** * 锁屏 */ public void lockScreen() { if (dpm.isAdminActive(myAdmin)) dpm.lockNow(); else Toast.makeText(ctx, "哥们还没开启管理员权限", Toast.LENGTH_SHORT).show(); } /** * 重设锁屏密码 */ public void resetScreenPassword(String password) { if (dpm.isAdminActive(myAdmin)) dpm.resetPassword(password, 0); else Toast.makeText(ctx, "哥们还没开启管理员权限", Toast.LENGTH_SHORT).show(); } /** * 清除锁屏密码 */ public void unlockScreen() { if (dpm.isAdminActive(myAdmin)) { dpm.resetPassword("", 0); } else Toast.makeText(ctx, "哥们还没开启管理员权限", Toast.LENGTH_SHORT).show(); } /** * 清除数据 */ public void wipeData() { if (dpm.isAdminActive(myAdmin)) { dpm.wipeData(DevicePolicyManager.WIPE_EXTERNAL_STORAGE);//清除sd card dpm.wipeData(0);//恢复出厂设置 } else Toast.makeText(ctx, "哥们还没开启管理员权限", Toast.LENGTH_SHORT).show(); } /** * 卸载步骤: * 1. 先变成普通软件(清除管理员权限) * 2. 正常卸载 */ public void unInstall() { removeAdmin(); Intent intent = new Intent(Intent.ACTION_DELETE); intent.setData(Uri.parse("package:" + ctx.getPackageName())); ctx.startActivity(intent); } /** * 检查管理员权限 * * @return */ public boolean isAdmin() { if (dpm.isAdminActive(myAdmin)) return true; else return false; } /** * 清除管 <SUF>*/ public void removeAdmin() { if (dpm.isAdminActive(myAdmin)) dpm.removeActiveAdmin(myAdmin); } }
0
719
11
852
10
888
11
852
10
1,103
17
false
false
false
false
false
true
42249_27
package Http; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; /** * Created by 成刚 on 2016/4/5. */ public class WebService { private static String IP = "10.0.3.2:8080"; /* private static String IP = "192.168.254.1:8080";*/ /*private static String IP = "192.168.43.251:8080";*/ private static HttpURLConnection conn = null; private static InputStream is = null; //手机号+密码 登录功能 public static String executeHttpGet(String username, String password) { String path = "http://" + IP + "/MyProject/LogLet"; path = path + "?username=" + username + "&password=" + password; return getConnection(path); } //根据手机号查找用户 public static String executeHttpFindUserByPhone(String username) { String path = "http://" + IP + "/MyProject/FindUserLet"; path = path + "?username=" + username; return getConnection(path); } // 传入课程难度直接下载数据库课程信息通过Get方式获取HTTP服务器数据,再后来修改传参,可以控制要下载的课程 public static String executeHttpGetCourse(String hard) { String path = "http://" + IP + "/MyProject/GetCourseLet"; path = path + "?hard=" + hard; return getConnection(path); } //密码修改功能,传入手机号+新密码 public static String executeHttpNewPwd(String username, String password) { String path = "http://" + IP + "/MyProject/PwdLet"; path = path + "?username=" + username + "&password=" + password; return getConnection(path); } // 注册功能,传入手机号+密码 public static String executeHttpRegister(String username, String password) { String path = "http://" + IP + "/MyProject/RegLet"; path = path + "?username=" + username + "&password=" + password; return getConnection(path); } // 注册功能,传入手机号+意见 public static String executeHttpFeedBack(String username, String suggestion) { String path = "http://" + IP + "/MyProject/FeedBackLet"; path = path + "?username=" + username + "&suggestion=" + suggestion; return getConnection(path); } //传入手机号获取用户关注的课程 public static String executeHttpGetUserCourseInfo(String username) { String path = "http://" + IP + "/MyProject/GetUserCourseInfoLet"; path = path + "?username=" + username; return getConnection(path); } // 传入手机号+课程,修改用户关注课程的信息 public static String executeHttpSendUserCourseInfo(String username,String jsonstr) { String path = "http://" + IP + "/MyProject/SendUserCourseInfoLet"; path = path + "?jsonstr=" + jsonstr+ "&username=" + username; return getConnection(path); } //传入手机号获取用户测试记录 public static String executeHttpGetUserTestInfo(String username) { String path = "http://" + IP + "/MyProject/GetUserTestInfoLet"; path = path + "?username=" + username; return getConnection(path); } // 传入手机号+课程+时间+难度+得分 public static String executeHttpSendUserTestInfo(String username,String course,String time,int hard,String scores) { String path = "http://" + IP + "/MyProject/SendUserTestInfoLet"; path = path + "?username=" + username + "&course=" + course+ "&time=" + time+ "&hard=" + hard+ "&scores=" + scores; return getConnection(path); } // 在线获取最新app的版本号 public static String executeHttpGetVersion() { String path = "http://" + IP + "/MyProject/VersionLet"; return getConnection(path); } //传入用户的详细资料,添加到数据库 public static String executeHttpUserInfo(String username, String nickname, String introduce, String major, String email) { String path = "http://" + IP + "/MyProject/UserInfoLet"; path = path + "?username=" + username + "&nickname=" + nickname + "&introduce=" + introduce + "&major=" + major + "&email=" + email; return getConnection(path); } public static String getConnection(String path) { try { conn = (HttpURLConnection) new URL(path).openConnection(); conn.setConnectTimeout(3000); // 设置超时时间 conn.setReadTimeout(3000); conn.setDoInput(true); conn.setRequestMethod("GET"); // 设置获取信息方式 conn.setRequestProperty("Charset", "UTF-8"); // 设置接收数据编码格式 if (conn.getResponseCode() == 200) { is = conn.getInputStream(); return parseInfo(is); } } catch (Exception e) { e.printStackTrace(); } finally { // 意外退出时进行连接关闭保护 if (conn != null) { conn.disconnect(); } if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; } // 将输入流转化为 String 型 private static String parseInfo(InputStream inStream) throws Exception { byte[] data = read(inStream); // 转化为字符串 return new String(data, "UTF-8"); } // 将输入流转化为byte型 public static byte[] read(InputStream inStream) throws Exception { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = inStream.read(buffer)) != -1) { outputStream.write(buffer, 0, len); } inStream.close(); return outputStream.toByteArray(); } }
CatterMCG/elearnApp
app/app/src/main/java/Http/WebService.java
1,417
// 设置超时时间
line_comment
zh-cn
package Http; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; /** * Created by 成刚 on 2016/4/5. */ public class WebService { private static String IP = "10.0.3.2:8080"; /* private static String IP = "192.168.254.1:8080";*/ /*private static String IP = "192.168.43.251:8080";*/ private static HttpURLConnection conn = null; private static InputStream is = null; //手机号+密码 登录功能 public static String executeHttpGet(String username, String password) { String path = "http://" + IP + "/MyProject/LogLet"; path = path + "?username=" + username + "&password=" + password; return getConnection(path); } //根据手机号查找用户 public static String executeHttpFindUserByPhone(String username) { String path = "http://" + IP + "/MyProject/FindUserLet"; path = path + "?username=" + username; return getConnection(path); } // 传入课程难度直接下载数据库课程信息通过Get方式获取HTTP服务器数据,再后来修改传参,可以控制要下载的课程 public static String executeHttpGetCourse(String hard) { String path = "http://" + IP + "/MyProject/GetCourseLet"; path = path + "?hard=" + hard; return getConnection(path); } //密码修改功能,传入手机号+新密码 public static String executeHttpNewPwd(String username, String password) { String path = "http://" + IP + "/MyProject/PwdLet"; path = path + "?username=" + username + "&password=" + password; return getConnection(path); } // 注册功能,传入手机号+密码 public static String executeHttpRegister(String username, String password) { String path = "http://" + IP + "/MyProject/RegLet"; path = path + "?username=" + username + "&password=" + password; return getConnection(path); } // 注册功能,传入手机号+意见 public static String executeHttpFeedBack(String username, String suggestion) { String path = "http://" + IP + "/MyProject/FeedBackLet"; path = path + "?username=" + username + "&suggestion=" + suggestion; return getConnection(path); } //传入手机号获取用户关注的课程 public static String executeHttpGetUserCourseInfo(String username) { String path = "http://" + IP + "/MyProject/GetUserCourseInfoLet"; path = path + "?username=" + username; return getConnection(path); } // 传入手机号+课程,修改用户关注课程的信息 public static String executeHttpSendUserCourseInfo(String username,String jsonstr) { String path = "http://" + IP + "/MyProject/SendUserCourseInfoLet"; path = path + "?jsonstr=" + jsonstr+ "&username=" + username; return getConnection(path); } //传入手机号获取用户测试记录 public static String executeHttpGetUserTestInfo(String username) { String path = "http://" + IP + "/MyProject/GetUserTestInfoLet"; path = path + "?username=" + username; return getConnection(path); } // 传入手机号+课程+时间+难度+得分 public static String executeHttpSendUserTestInfo(String username,String course,String time,int hard,String scores) { String path = "http://" + IP + "/MyProject/SendUserTestInfoLet"; path = path + "?username=" + username + "&course=" + course+ "&time=" + time+ "&hard=" + hard+ "&scores=" + scores; return getConnection(path); } // 在线获取最新app的版本号 public static String executeHttpGetVersion() { String path = "http://" + IP + "/MyProject/VersionLet"; return getConnection(path); } //传入用户的详细资料,添加到数据库 public static String executeHttpUserInfo(String username, String nickname, String introduce, String major, String email) { String path = "http://" + IP + "/MyProject/UserInfoLet"; path = path + "?username=" + username + "&nickname=" + nickname + "&introduce=" + introduce + "&major=" + major + "&email=" + email; return getConnection(path); } public static String getConnection(String path) { try { conn = (HttpURLConnection) new URL(path).openConnection(); conn.setConnectTimeout(3000); // 设置 <SUF> conn.setReadTimeout(3000); conn.setDoInput(true); conn.setRequestMethod("GET"); // 设置获取信息方式 conn.setRequestProperty("Charset", "UTF-8"); // 设置接收数据编码格式 if (conn.getResponseCode() == 200) { is = conn.getInputStream(); return parseInfo(is); } } catch (Exception e) { e.printStackTrace(); } finally { // 意外退出时进行连接关闭保护 if (conn != null) { conn.disconnect(); } if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; } // 将输入流转化为 String 型 private static String parseInfo(InputStream inStream) throws Exception { byte[] data = read(inStream); // 转化为字符串 return new String(data, "UTF-8"); } // 将输入流转化为byte型 public static byte[] read(InputStream inStream) throws Exception { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = inStream.read(buffer)) != -1) { outputStream.write(buffer, 0, len); } inStream.close(); return outputStream.toByteArray(); } }
0
1,340
5
1,417
4
1,493
4
1,417
4
1,802
8
false
false
false
false
false
true
8203_0
package me.jbusdriver.ui.widget; import android.opengl.GLES10; public class SampleSizeUtil { private static int textureSize = 0; //存在第二次拿拿不到的情况,所以把拿到的数据用一个static变量保存下来 public static final int getTextureSize() { if (textureSize > 0) { return textureSize; } int[] params = new int[1]; GLES10.glGetIntegerv(GLES10.GL_MAX_TEXTURE_SIZE, params, 0); textureSize = params[0]; return textureSize; } // 将x向上对齐到2的幂指数 private static int roundup2n(int x) { if ((x & (x - 1)) == 0) { return x; } int pos = 0; while (x > 0) { x >>= 1; ++pos; } return 1 << pos; } }
Ccixyj/JBusDriver
app/src/main/java/me/jbusdriver/ui/widget/SampleSizeUtil.java
231
//存在第二次拿拿不到的情况,所以把拿到的数据用一个static变量保存下来
line_comment
zh-cn
package me.jbusdriver.ui.widget; import android.opengl.GLES10; public class SampleSizeUtil { private static int textureSize = 0; //存在 <SUF> public static final int getTextureSize() { if (textureSize > 0) { return textureSize; } int[] params = new int[1]; GLES10.glGetIntegerv(GLES10.GL_MAX_TEXTURE_SIZE, params, 0); textureSize = params[0]; return textureSize; } // 将x向上对齐到2的幂指数 private static int roundup2n(int x) { if ((x & (x - 1)) == 0) { return x; } int pos = 0; while (x > 0) { x >>= 1; ++pos; } return 1 << pos; } }
0
211
18
231
22
246
19
231
22
291
42
false
false
false
false
false
true
14421_2
package com.example.mylibrary; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class MainActivity extends AppCompatActivity { /** * * library 中 * 1、初始化使用R2 * 2、单击事件中不能使用swith case * 3、switch case 转换成if else 如下 * */ /** * 特别注意:当副Module使用R2时候可会报红,没关系,rebuild 就好了 * 强烈建议大家 用插件 Android ButterKnife Zelezny 生成 然后在library中根据每个地方修改成R2 */ /** * 关于资源文件,layout、res 下的资源文件 每一个module 命名必须不同,如果相同运行后跑程序将以主Module资源为准 * 也就是library中资源、布局将会被替换或者忽视。 */ @BindView(R2.id.button) Button button; @BindView(R2.id.button2) Button button2; @BindView(R2.id.textView) TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_library); ButterKnife.bind(this); } /** * 单击事件 * @param view */ @OnClick({R2.id.button, R2.id.button2}) public void onViewClicked(View view) { int i = view.getId(); if (i == R.id.button) { Toast.makeText(MainActivity.this,"点击了副Module",Toast.LENGTH_SHORT).show(); } else if (i == R.id.button2) { finish(); } } }
CeleryIce/ButterKnifeDemo
mylibrary/src/main/java/com/example/mylibrary/MainActivity.java
466
/** * 关于资源文件,layout、res 下的资源文件 每一个module 命名必须不同,如果相同运行后跑程序将以主Module资源为准 * 也就是library中资源、布局将会被替换或者忽视。 */
block_comment
zh-cn
package com.example.mylibrary; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class MainActivity extends AppCompatActivity { /** * * library 中 * 1、初始化使用R2 * 2、单击事件中不能使用swith case * 3、switch case 转换成if else 如下 * */ /** * 特别注意:当副Module使用R2时候可会报红,没关系,rebuild 就好了 * 强烈建议大家 用插件 Android ButterKnife Zelezny 生成 然后在library中根据每个地方修改成R2 */ /** * 关于资 <SUF>*/ @BindView(R2.id.button) Button button; @BindView(R2.id.button2) Button button2; @BindView(R2.id.textView) TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_library); ButterKnife.bind(this); } /** * 单击事件 * @param view */ @OnClick({R2.id.button, R2.id.button2}) public void onViewClicked(View view) { int i = view.getId(); if (i == R.id.button) { Toast.makeText(MainActivity.this,"点击了副Module",Toast.LENGTH_SHORT).show(); } else if (i == R.id.button2) { finish(); } } }
0
399
56
466
56
483
55
466
56
624
98
false
false
false
false
false
true
40952_1
package com.centurywar; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.TimerTask; import com.centurywar.control.ArduinoControl; //定时运行的程序 public class TimingTask extends TimerTask { /** * 从数据为库中查出要运行的程序 */ public static void getTimingBehave() { } public static void insertTimingBehave() { // Behave be = new Behave(); } public void run() { // ArduinoControl.doCommand(1, "34_1_3_3"); Behave be = new Behave(0); // 检测缓存中有木有超时需要加入冲发表的 // this.checkCachedCommands(6, be); List<Behave> needsend = be.getNeedRunInfo(); List<Integer> hasSend = new ArrayList<Integer>(); for (int i = 0; i < needsend.size(); i++) { Behave tembe = needsend.get(i); ArduinoControl.doCommand(tembe.gameuid, tembe.behaveString); hasSend.add(tembe.id); } be.delInfo(hasSend); System.out.println("定时操作发送中……"); } public void clearSocket() { System.out.println("清空没用的连接。。。。"); Main.clearTem(); Main.clearArduino(); Main.clearAndroid(); } /** * 检查缓存中超时的命令,写入send_log表 * * @param timeout * 设置超时时间 单位为秒 * @param behave * behave对象,随时写入重发表 */ public void checkCachedCommands(int timeout, Behave behave) { // 取出缓存的集合 Set<String> cachedKeys = Redis.hkeys("cachedCommands"); // for循环遍历: for (String key : cachedKeys) { String timeStr = Redis.hget("cachedCommands", key); System.out.println(timeStr); Integer sendTime = Integer.parseInt(timeStr); Integer nowTime = new Integer( (int) (System.currentTimeMillis() / 1000)); if (nowTime - sendTime > timeout) { System.out.println("反馈超时,写入重发表:" + key); Redis.hdel("cachedCommands", key); String params[] = key.split(":"); behave.newInfo(Integer.parseInt(params[0]), 11, sendTime, params[1]); } } } }
CenturyWarDesign/Intelligent_Server
src/com/centurywar/TimingTask.java
654
/** * 从数据为库中查出要运行的程序 */
block_comment
zh-cn
package com.centurywar; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.TimerTask; import com.centurywar.control.ArduinoControl; //定时运行的程序 public class TimingTask extends TimerTask { /** * 从数据 <SUF>*/ public static void getTimingBehave() { } public static void insertTimingBehave() { // Behave be = new Behave(); } public void run() { // ArduinoControl.doCommand(1, "34_1_3_3"); Behave be = new Behave(0); // 检测缓存中有木有超时需要加入冲发表的 // this.checkCachedCommands(6, be); List<Behave> needsend = be.getNeedRunInfo(); List<Integer> hasSend = new ArrayList<Integer>(); for (int i = 0; i < needsend.size(); i++) { Behave tembe = needsend.get(i); ArduinoControl.doCommand(tembe.gameuid, tembe.behaveString); hasSend.add(tembe.id); } be.delInfo(hasSend); System.out.println("定时操作发送中……"); } public void clearSocket() { System.out.println("清空没用的连接。。。。"); Main.clearTem(); Main.clearArduino(); Main.clearAndroid(); } /** * 检查缓存中超时的命令,写入send_log表 * * @param timeout * 设置超时时间 单位为秒 * @param behave * behave对象,随时写入重发表 */ public void checkCachedCommands(int timeout, Behave behave) { // 取出缓存的集合 Set<String> cachedKeys = Redis.hkeys("cachedCommands"); // for循环遍历: for (String key : cachedKeys) { String timeStr = Redis.hget("cachedCommands", key); System.out.println(timeStr); Integer sendTime = Integer.parseInt(timeStr); Integer nowTime = new Integer( (int) (System.currentTimeMillis() / 1000)); if (nowTime - sendTime > timeout) { System.out.println("反馈超时,写入重发表:" + key); Redis.hdel("cachedCommands", key); String params[] = key.split(":"); behave.newInfo(Integer.parseInt(params[0]), 11, sendTime, params[1]); } } } }
0
569
18
654
16
645
18
654
16
813
22
false
false
false
false
false
true
31115_4
package com.code.study.structure.queue; /** * @author chaiyym * @createTime 2021/7/19 14:56 */ public class QueueArray implements Queue { //数组的默认容量 public static final int CAPACITY = 1000; //数组的实际容量 protected int capacity; //对象数组 protected Object[] Q; //队首元素的位置 protected int f = 0; //队尾元素的位置 protected int r = 0; public QueueArray() { this(CAPACITY); } public QueueArray(int capacity) { Q = new Object[capacity]; } @Override public int getSize() { return (capacity - f + r) % capacity; } @Override public boolean isEmpty() { return (f == r); } @Override public Object front() throws Exception { if (isEmpty()) { throw new Exception("意外:队列空"); } return Q[f]; } @Override public void enqueue(Object obj) throws Exception { if (getSize() == capacity - 1) { throw new Exception("Queue overflow."); } Q[r] = obj; r = (r + 1) % capacity; } @Override public Object dequeue() throws Exception { Object elem; if (isEmpty()) { throw new Exception("意外:队列空"); } elem = Q[f]; Q[f] = null; f = (f + 1) % capacity; return elem; } @Override public void traversal() { for (int i = f; i < r; i++) { System.out.print(Q[i] + " "); } System.out.println(); } }
Chaiyym/structure_algorithm
src/com/code/study/structure/queue/QueueArray.java
416
//队首元素的位置
line_comment
zh-cn
package com.code.study.structure.queue; /** * @author chaiyym * @createTime 2021/7/19 14:56 */ public class QueueArray implements Queue { //数组的默认容量 public static final int CAPACITY = 1000; //数组的实际容量 protected int capacity; //对象数组 protected Object[] Q; //队首 <SUF> protected int f = 0; //队尾元素的位置 protected int r = 0; public QueueArray() { this(CAPACITY); } public QueueArray(int capacity) { Q = new Object[capacity]; } @Override public int getSize() { return (capacity - f + r) % capacity; } @Override public boolean isEmpty() { return (f == r); } @Override public Object front() throws Exception { if (isEmpty()) { throw new Exception("意外:队列空"); } return Q[f]; } @Override public void enqueue(Object obj) throws Exception { if (getSize() == capacity - 1) { throw new Exception("Queue overflow."); } Q[r] = obj; r = (r + 1) % capacity; } @Override public Object dequeue() throws Exception { Object elem; if (isEmpty()) { throw new Exception("意外:队列空"); } elem = Q[f]; Q[f] = null; f = (f + 1) % capacity; return elem; } @Override public void traversal() { for (int i = f; i < r; i++) { System.out.print(Q[i] + " "); } System.out.println(); } }
0
397
5
416
6
461
5
416
6
520
10
false
false
false
false
false
true
21411_10
package com.time.enums; /** * 特殊时间表达转换(转换特殊时间表达为可解析的时间表达) * * @author Xianjie Wu wuxianjie@ai-strong.com * @date 2019年7月18日 下午6:06:05 */ public enum SpTimeExp { // 大前天(上上上一天) LAST_LAST_LAST_DAY(new String[] { "大前天" }), // 前天(上上一天) LAST_LAST_DAY(new String[] { "前天", "上上日" }), // 昨天(上一天) LAST_DAY(new String[] { "昨天", "昨日", "前一天" }), // 上上上月(上上上一月) // LAST_LAST_LAST_MONTH(new String[] { "去年", "前一年", "上一年" }), // 上上月(上上一月) LAST_LAST_MONTH(new String[] { "上上个月", "上上月" }), // 上月(上一月) LAST_MONTH(new String[] { "上个月", "上一个月", "上一月" }), // 大前年(上上上一年) LAST_LAST_LAST_YEAR(new String[] { "大前年" }), // 前年(上上一年) LAST_LAST_YEAR(new String[] { "前年", "上上一年" }), // 去年(上一年) LAST_YEAR(new String[] {"去年底", "去年", "前一年", "上一年" }); private String[] exps; private SpTimeExp(String[] exps) { this.exps = exps; } public String[] getExps() { return exps; } }
Challenging6/TimePeriod-NLP
src/com/time/enums/SpTimeExp.java
470
// 去年(上一年)
line_comment
zh-cn
package com.time.enums; /** * 特殊时间表达转换(转换特殊时间表达为可解析的时间表达) * * @author Xianjie Wu wuxianjie@ai-strong.com * @date 2019年7月18日 下午6:06:05 */ public enum SpTimeExp { // 大前天(上上上一天) LAST_LAST_LAST_DAY(new String[] { "大前天" }), // 前天(上上一天) LAST_LAST_DAY(new String[] { "前天", "上上日" }), // 昨天(上一天) LAST_DAY(new String[] { "昨天", "昨日", "前一天" }), // 上上上月(上上上一月) // LAST_LAST_LAST_MONTH(new String[] { "去年", "前一年", "上一年" }), // 上上月(上上一月) LAST_LAST_MONTH(new String[] { "上上个月", "上上月" }), // 上月(上一月) LAST_MONTH(new String[] { "上个月", "上一个月", "上一月" }), // 大前年(上上上一年) LAST_LAST_LAST_YEAR(new String[] { "大前年" }), // 前年(上上一年) LAST_LAST_YEAR(new String[] { "前年", "上上一年" }), // 去年 <SUF> LAST_YEAR(new String[] {"去年底", "去年", "前一年", "上一年" }); private String[] exps; private SpTimeExp(String[] exps) { this.exps = exps; } public String[] getExps() { return exps; } }
0
381
9
470
9
437
7
470
9
551
9
false
false
false
false
false
true
5380_3
package com.example.testQRCode; import com.google.zxing.*; import com.google.zxing.client.j2se.BufferedImageLuminanceSource; import com.google.zxing.client.j2se.MatrixToImageConfig; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.BitMatrix; import com.google.zxing.common.HybridBinarizer; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.HashMap; public class QRCode { public static void main(String[] args) throws IOException, WriterException { encode("没事,黑白就能体现出我的高冷风了", "E:/QRCode.png", "E:/load.png"); // encode("没事,黑白就能体现出我的高冷风了", "E:/QRCode.png"); String s = decode("E:/QRCode.png"); System.out.println(s); } private static void encode(String content, String path) throws WriterException, IOException { int x = 500; int y = 500; //0x为16位标识 FF 随后6位为色值 int onColor = 0xFF000000; int offColor = 0xFFFFFFA; String format = "png"; File out = new File(path); HashMap<EncodeHintType, Object> map = new HashMap<>(); map.put(EncodeHintType.CHARACTER_SET, "utf-8"); map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);//Decode 出错,可以适当调节排错率 map.put(EncodeHintType.MARGIN, 1); BitMatrix encode = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, x, y, map); MatrixToImageWriter.writeToPath(encode, format, out.toPath(), new MatrixToImageConfig(onColor, offColor)); } private static void encode(String content, String path, String logoPath) throws WriterException, IOException { int x = 1000; int y = 1000; //0x为16位标识 FF 随后6位为色值 int onColor = 0xFF000000; int offColor = 0xFFFFFFA; String format = "png"; File out = new File(path); HashMap<EncodeHintType, Object> map = new HashMap<>(); map.put(EncodeHintType.CHARACTER_SET, "utf-8"); map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);//Decode 出错,可以适当调节排错率 map.put(EncodeHintType.MARGIN, 1); BitMatrix encode = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, x, y, map); BufferedImage qrCode = MatrixToImageWriter.toBufferedImage(encode, new MatrixToImageConfig(onColor, offColor)); Graphics2D graphics = qrCode.createGraphics(); BufferedImage logo = ImageIO.read(new File(logoPath)); graphics.drawImage(logo, (qrCode.getWidth() - logo.getWidth()) / 2, (qrCode.getHeight() - logo.getHeight()) / 2, null); graphics.dispose(); logo.flush(); ImageIO.write(qrCode, format, out); } public static String decode(String path) throws IOException { File in = new File(path); BufferedImage qrCode = ImageIO.read(in); BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(qrCode))); HashMap<DecodeHintType, Object> map = new HashMap<>(); map.put(DecodeHintType.CHARACTER_SET, "utf-8"); try { Result decode = new MultiFormatReader().decode(binaryBitmap, map); return decode.toString(); } catch (NotFoundException e) { return ""; } } }
ChaoSBYNN/Tools
Java/TestDemo/QRCode/QRCode.java
990
//0x为16位标识 FF 随后6位为色值
line_comment
zh-cn
package com.example.testQRCode; import com.google.zxing.*; import com.google.zxing.client.j2se.BufferedImageLuminanceSource; import com.google.zxing.client.j2se.MatrixToImageConfig; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.BitMatrix; import com.google.zxing.common.HybridBinarizer; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.HashMap; public class QRCode { public static void main(String[] args) throws IOException, WriterException { encode("没事,黑白就能体现出我的高冷风了", "E:/QRCode.png", "E:/load.png"); // encode("没事,黑白就能体现出我的高冷风了", "E:/QRCode.png"); String s = decode("E:/QRCode.png"); System.out.println(s); } private static void encode(String content, String path) throws WriterException, IOException { int x = 500; int y = 500; //0x为16位标识 FF 随后6位为色值 int onColor = 0xFF000000; int offColor = 0xFFFFFFA; String format = "png"; File out = new File(path); HashMap<EncodeHintType, Object> map = new HashMap<>(); map.put(EncodeHintType.CHARACTER_SET, "utf-8"); map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);//Decode 出错,可以适当调节排错率 map.put(EncodeHintType.MARGIN, 1); BitMatrix encode = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, x, y, map); MatrixToImageWriter.writeToPath(encode, format, out.toPath(), new MatrixToImageConfig(onColor, offColor)); } private static void encode(String content, String path, String logoPath) throws WriterException, IOException { int x = 1000; int y = 1000; //0x <SUF> int onColor = 0xFF000000; int offColor = 0xFFFFFFA; String format = "png"; File out = new File(path); HashMap<EncodeHintType, Object> map = new HashMap<>(); map.put(EncodeHintType.CHARACTER_SET, "utf-8"); map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);//Decode 出错,可以适当调节排错率 map.put(EncodeHintType.MARGIN, 1); BitMatrix encode = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, x, y, map); BufferedImage qrCode = MatrixToImageWriter.toBufferedImage(encode, new MatrixToImageConfig(onColor, offColor)); Graphics2D graphics = qrCode.createGraphics(); BufferedImage logo = ImageIO.read(new File(logoPath)); graphics.drawImage(logo, (qrCode.getWidth() - logo.getWidth()) / 2, (qrCode.getHeight() - logo.getHeight()) / 2, null); graphics.dispose(); logo.flush(); ImageIO.write(qrCode, format, out); } public static String decode(String path) throws IOException { File in = new File(path); BufferedImage qrCode = ImageIO.read(in); BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(qrCode))); HashMap<DecodeHintType, Object> map = new HashMap<>(); map.put(DecodeHintType.CHARACTER_SET, "utf-8"); try { Result decode = new MultiFormatReader().decode(binaryBitmap, map); return decode.toString(); } catch (NotFoundException e) { return ""; } } }
0
863
18
990
17
1,007
16
990
17
1,177
22
false
false
false
false
false
true
32283_17
package com.scj.beilu.app.location; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.net.Uri; import android.widget.Toast; import com.scj.beilu.app.R; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import static android.content.Intent.URI_ALLOW_UNSAFE; /** * @author Mingxun * @time on 2019/4/17 16:56 */ public class LoctionNavigationUtil { public final static String BAIDU_PACKAGENAME = "com.baidu.BaiduMap"; public final static String GAODE_PACKAGENAME = "com.autonavi.minimap"; /** * 高德导航 * * @param context * @param location */ public static void gaodeGuide(Context context, double[] location) { if (isAvilible(context, GAODE_PACKAGENAME)) { try { Intent intent = Intent.parseUri("androidamap://navi?sourceApplication=" + context.getResources().getString(R.string.app_name) + "&poiname=我的目的地" + "&lat=" + location[0] + "&lon=" + location[1] + "&dev=0", URI_ALLOW_UNSAFE); context.startActivity(intent); } catch (URISyntaxException e) { e.printStackTrace(); } } else { Toast.makeText(context, "您尚未安装高德地图", Toast.LENGTH_LONG).show(); Uri uri = Uri.parse("market://details?id=com.autonavi.minimap"); Intent intent = new Intent(Intent.ACTION_VIEW, uri); context.startActivity(intent); } } /** * 百度导航 * * @param context * @param location location[0]纬度lat,location[1]经度lon */ public static void baiduGuide(Context context, double[] location) { double[] baiduLoc = GpsUtils.gcj02_To_Bd09(location[0], location[1]); if (isAvilible(context, "com.baidu.BaiduMap")) {//传入指定应用包名 try { //intent = Intent.getIntent("intent://map/direction?origin=latlng:34.264642646862,108.95108518068|name:我家&destination=大雁塔&mode=driving®ion=西安&src=yourCompanyName|yourAppName#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end"); Intent intent = Intent.getIntent("intent://map/direction?" + //"origin=latlng:"+"34.264642646862,108.95108518068&" + //起点 此处不传值默认选择当前位置 "destination=latlng:" + baiduLoc[0] + "," + baiduLoc[1] + "|name:我的目的地" + //终点 "&mode=driving" + //导航路线方式 "&region=" + // "&src=" + context.getResources().getString(R.string.app_name) + "#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end"); context.startActivity(intent); //启动调用 } catch (URISyntaxException e) { e.printStackTrace(); } } else {//未安装 //market为路径,id为包名 //显示手机上所有的market商店 Toast.makeText(context, "您尚未安装百度地图", Toast.LENGTH_LONG).show(); Uri uri = Uri.parse("market://details?id=com.baidu.BaiduMap"); Intent intent = new Intent(Intent.ACTION_VIEW, uri); context.startActivity(intent); } } /** * 检查手机上是否安装了指定的软件 * * @param context * @param packageName:应用包名 * @return */ public static boolean isAvilible(Context context, String packageName) { //获取packagemanager final PackageManager packageManager = context.getPackageManager(); //获取所有已安装程序的包信息 List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0); //用于存储所有已安装程序的包名 List<String> packageNames = new ArrayList<String>(); //从pinfo中将包名字逐一取出,压入pName list中 if (packageInfos != null) { for (int i = 0; i < packageInfos.size(); i++) { String packName = packageInfos.get(i).packageName; packageNames.add(packName); } } //判断packageNames中是否有目标程序的包名,有TRUE,没有FALSE return packageNames.contains(packageName); } }
CharlesMing/beilu-android-open-project
app/src/main/java/com/scj/beilu/app/location/LoctionNavigationUtil.java
1,202
//获取所有已安装程序的包信息
line_comment
zh-cn
package com.scj.beilu.app.location; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.net.Uri; import android.widget.Toast; import com.scj.beilu.app.R; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import static android.content.Intent.URI_ALLOW_UNSAFE; /** * @author Mingxun * @time on 2019/4/17 16:56 */ public class LoctionNavigationUtil { public final static String BAIDU_PACKAGENAME = "com.baidu.BaiduMap"; public final static String GAODE_PACKAGENAME = "com.autonavi.minimap"; /** * 高德导航 * * @param context * @param location */ public static void gaodeGuide(Context context, double[] location) { if (isAvilible(context, GAODE_PACKAGENAME)) { try { Intent intent = Intent.parseUri("androidamap://navi?sourceApplication=" + context.getResources().getString(R.string.app_name) + "&poiname=我的目的地" + "&lat=" + location[0] + "&lon=" + location[1] + "&dev=0", URI_ALLOW_UNSAFE); context.startActivity(intent); } catch (URISyntaxException e) { e.printStackTrace(); } } else { Toast.makeText(context, "您尚未安装高德地图", Toast.LENGTH_LONG).show(); Uri uri = Uri.parse("market://details?id=com.autonavi.minimap"); Intent intent = new Intent(Intent.ACTION_VIEW, uri); context.startActivity(intent); } } /** * 百度导航 * * @param context * @param location location[0]纬度lat,location[1]经度lon */ public static void baiduGuide(Context context, double[] location) { double[] baiduLoc = GpsUtils.gcj02_To_Bd09(location[0], location[1]); if (isAvilible(context, "com.baidu.BaiduMap")) {//传入指定应用包名 try { //intent = Intent.getIntent("intent://map/direction?origin=latlng:34.264642646862,108.95108518068|name:我家&destination=大雁塔&mode=driving®ion=西安&src=yourCompanyName|yourAppName#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end"); Intent intent = Intent.getIntent("intent://map/direction?" + //"origin=latlng:"+"34.264642646862,108.95108518068&" + //起点 此处不传值默认选择当前位置 "destination=latlng:" + baiduLoc[0] + "," + baiduLoc[1] + "|name:我的目的地" + //终点 "&mode=driving" + //导航路线方式 "&region=" + // "&src=" + context.getResources().getString(R.string.app_name) + "#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end"); context.startActivity(intent); //启动调用 } catch (URISyntaxException e) { e.printStackTrace(); } } else {//未安装 //market为路径,id为包名 //显示手机上所有的market商店 Toast.makeText(context, "您尚未安装百度地图", Toast.LENGTH_LONG).show(); Uri uri = Uri.parse("market://details?id=com.baidu.BaiduMap"); Intent intent = new Intent(Intent.ACTION_VIEW, uri); context.startActivity(intent); } } /** * 检查手机上是否安装了指定的软件 * * @param context * @param packageName:应用包名 * @return */ public static boolean isAvilible(Context context, String packageName) { //获取packagemanager final PackageManager packageManager = context.getPackageManager(); //获取 <SUF> List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0); //用于存储所有已安装程序的包名 List<String> packageNames = new ArrayList<String>(); //从pinfo中将包名字逐一取出,压入pName list中 if (packageInfos != null) { for (int i = 0; i < packageInfos.size(); i++) { String packName = packageInfos.get(i).packageName; packageNames.add(packName); } } //判断packageNames中是否有目标程序的包名,有TRUE,没有FALSE return packageNames.contains(packageName); } }
0
1,062
9
1,202
9
1,232
9
1,202
9
1,468
14
false
false
false
false
false
true
31079_5
package chapter07; public class Object01 { public static void main(String[] args) { /** * 1. 类是抽象的,概念的,代表一类事物,比如人类、猫类,即它是数据类型 * 2. 对象是具体的,实际的,代表一个具体事物,即实例 * 3. 类是对象的模板,对象是类的一个个体,对应一个实例 */ // 使用OOP面向对象解决,实例化一只猫 // 1. new Cat() 创建一只猫 // 2. Cat cat1 = new Cat(); 把创建的猫赋值给 cat1 Cat cat1 = new Cat(); cat1.name = "小白"; cat1.age = 3; cat1.color = "橘色"; cat1.weight = 6.; // 创建第二只猫 Cat cat2 = new Cat(); cat2.name = "小花"; cat2.age = 100; cat2.color = "花色"; cat2.weight = 15.; // 怎么使用对象的属性 System.out.println("第一只猫信息:" + cat1.name + " " + cat1.age + " " + cat1.color); // 对象在内存中的存在形式 // 类、数组、接口、String都是引用类型 } } // 使用面向对象的方式 // 定义一个猫类 Cat class Cat { // 属性,也叫成员变量,字段field String name; int age; String color; double weight; String[] master; // 属性可以是基本数据类型,也可以是引用类型(对象,数组) // 行为 }
CharlieHon/Java-base
chapter07/Object01.java
402
// 怎么使用对象的属性
line_comment
zh-cn
package chapter07; public class Object01 { public static void main(String[] args) { /** * 1. 类是抽象的,概念的,代表一类事物,比如人类、猫类,即它是数据类型 * 2. 对象是具体的,实际的,代表一个具体事物,即实例 * 3. 类是对象的模板,对象是类的一个个体,对应一个实例 */ // 使用OOP面向对象解决,实例化一只猫 // 1. new Cat() 创建一只猫 // 2. Cat cat1 = new Cat(); 把创建的猫赋值给 cat1 Cat cat1 = new Cat(); cat1.name = "小白"; cat1.age = 3; cat1.color = "橘色"; cat1.weight = 6.; // 创建第二只猫 Cat cat2 = new Cat(); cat2.name = "小花"; cat2.age = 100; cat2.color = "花色"; cat2.weight = 15.; // 怎么 <SUF> System.out.println("第一只猫信息:" + cat1.name + " " + cat1.age + " " + cat1.color); // 对象在内存中的存在形式 // 类、数组、接口、String都是引用类型 } } // 使用面向对象的方式 // 定义一个猫类 Cat class Cat { // 属性,也叫成员变量,字段field String name; int age; String color; double weight; String[] master; // 属性可以是基本数据类型,也可以是引用类型(对象,数组) // 行为 }
0
382
8
402
6
407
5
402
6
553
13
false
false
false
false
false
true
31393_5
package com.entity; public class ToFocus { private int id;//Id自增 private int userId;//用户ID private int userType;//用户类型(1:医生2:用户) private int type;//关注类型(1:医生2:药品) private int typeId;//关注对象Id private String img;//展示图片 private String name;//名称 private String more;//介绍 public int getId() { return id; } public void setId(int id) { this.id = id; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public int getUserType() { return userType; } public void setUserType(int userType) { this.userType = userType; } public int getType() { return type; } public void setType(int type) { this.type = type; } public int getTypeId() { return typeId; } public void setTypeId(int typeId) { this.typeId = typeId; } public String getImg() { return img; } public void setImg(String img) { this.img = img; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getMore() { return more; } public void setMore(String more) { this.more = more; } }
Charlottenpl/onepill_service
src/main/java/com/entity/ToFocus.java
353
//展示图片
line_comment
zh-cn
package com.entity; public class ToFocus { private int id;//Id自增 private int userId;//用户ID private int userType;//用户类型(1:医生2:用户) private int type;//关注类型(1:医生2:药品) private int typeId;//关注对象Id private String img;//展示 <SUF> private String name;//名称 private String more;//介绍 public int getId() { return id; } public void setId(int id) { this.id = id; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public int getUserType() { return userType; } public void setUserType(int userType) { this.userType = userType; } public int getType() { return type; } public void setType(int type) { this.type = type; } public int getTypeId() { return typeId; } public void setTypeId(int typeId) { this.typeId = typeId; } public String getImg() { return img; } public void setImg(String img) { this.img = img; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getMore() { return more; } public void setMore(String more) { this.more = more; } }
0
323
3
353
3
395
3
353
3
473
5
false
false
false
false
false
true
57828_5
ZookeeperServerMain类: protected void initializeAndRun(String[] args) throws ConfigException, IOException { try { ManagedUtil.registerLog4jMBeans(); } catch (JMException e) { LOG.warn("Unable to register log4j JMX control", e); } ServerConfig config = new ServerConfig(); if (args.length == 1) { config.parse(args[0]); } else { config.parse(args); } runFromConfig(config); } /** * 1.从配置文件zoo.cfg读取信息 */ public void parse(String path) throws ConfigException { QuorumPeerConfig config = new QuorumPeerConfig(); config.parse(path); readFrom(config); } public void parse(String path) throws ConfigException { File configFile = new File(path); LOG.info("Reading configuration from: " + configFile); try { if (!configFile.exists()) { throw new IllegalArgumentException(configFile.toString() + " file is missing"); } Properties cfg = new Properties(); FileInputStream in = new FileInputStream(configFile); try { cfg.load(in); } finally { in.close(); } parseProperties(cfg); } catch (IOException e) { throw new ConfigException("Error processing " + path, e); } catch (IllegalArgumentException e) { throw new ConfigException("Error processing " + path, e); } } /** * 启动 */ public void runFromConfig(ServerConfig config) throws IOException { LOG.info("Starting server"); FileTxnSnapLog txnLog = null; try { // 创建ZookeeperServer对象,并将读取的配置信息赋给ZookeeperServer的属性 ZooKeeperServer zkServer = new ZooKeeperServer(); txnLog = new FileTxnSnapLog(new File(config.dataLogDir), new File(config.dataDir)); zkServer.setTxnLogFactory(txnLog); zkServer.setTickTime(config.tickTime); zkServer.setMinSessionTimeout(config.minSessionTimeout); zkServer.setMaxSessionTimeout(config.maxSessionTimeout); // 默认创建得到NIOServerCnxnFactory类的实例 cnxnFactory = ServerCnxnFactory.createFactory(); /** * 创建ServerSocketChannel实例,注册到Selector上,感兴趣的操作为accept */ cnxnFactory.configure(config.getClientPortAddress(),config.getMaxClientCnxns()); cnxnFactory.startup(zkServer); cnxnFactory.join(); if (zkServer.isRunning()) { zkServer.shutdown(); } } catch (InterruptedException e) { LOG.warn("Server interrupted", e); } finally { if (txnLog != null) { txnLog.close(); } } } public void startup(ZooKeeperServer zks) throws IOException,InterruptedException { /** * 2.启动IO主线程 */ start(); /** * 3.从log和snapshot恢复database和session */ zks.startdata(); /** * 4.启动sessionTracker线程,初始化IO请求的处理链,并启动每个processor线程 */ zks.startup(); setZooKeeperServer(zks); } public void run() { while (!ss.socket().isClosed()) { try { selector.select(1000); Set<SelectionKey> selected; synchronized (this) { selected = selector.selectedKeys(); } ArrayList<SelectionKey> selectedList = new ArrayList<SelectionKey>(selected); Collections.shuffle(selectedList); for (SelectionKey k : selectedList) { if ((k.readyOps() & SelectionKey.OP_ACCEPT) != 0) { SocketChannel sc = ((ServerSocketChannel) k .channel()).accept(); InetAddress ia = sc.socket().getInetAddress(); int cnxncount = getClientCnxnCount(ia); if (maxClientCnxns > 0 && cnxncount >= maxClientCnxns){ LOG.warn("Too many connections from " + ia + " - max is " + maxClientCnxns ); sc.close(); } else { LOG.info("Accepted socket connection from " + sc.socket().getRemoteSocketAddress()); sc.configureBlocking(false); SelectionKey sk = sc.register(selector, SelectionKey.OP_READ); /** * 根据sc和sk创建NIOServerCnxn对象,并将它绑定到sk上 * 这样以后发生了读写操作时,都是调用NIOServerCnxn类里的doIO()方法进行处理 */ NIOServerCnxn cnxn = createConnection(sc, sk); sk.attach(cnxn); addCnxn(cnxn); } } else if ((k.readyOps() & (SelectionKey.OP_READ | SelectionKey.OP_WRITE)) != 0) { NIOServerCnxn c = (NIOServerCnxn) k.attachment(); c.doIO(k); } else { if (LOG.isDebugEnabled()) { LOG.debug("Unexpected ops in select " + k.readyOps()); } } } selected.clear(); } catch (RuntimeException e) { LOG.warn("Ignoring unexpected runtime exception", e); } catch (Exception e) { LOG.warn("Ignoring exception", e); } } closeAll(); LOG.info("NIOServerCnxn factory exited run method"); } public void startdata() throws IOException, InterruptedException { if (zkDb == null) { zkDb = new ZKDatabase(this.txnLogFactory); } if (!zkDb.isInitialized()) { loadData(); } } // '/','/zookeeper','/zookeeper/quota'3个系统节点初始化 public DataTree() { nodes.put("", root); nodes.put(rootZookeeper, root); root.addChild(procChildZookeeper); nodes.put(procZookeeper, procDataNode); procDataNode.addChild(quotaChildZookeeper); nodes.put(quotaZookeeper, quotaDataNode); } /** * Restore sessions and data */ public void loadData() throws IOException, InterruptedException { // 执行恢复,并返回最新的事务ID if(zkDb.isInitialized()){ setZxid(zkDb.getDataTreeLastProcessedZxid()); } else { setZxid(zkDb.loadDataBase()); } // 清理session LinkedList<Long> deadSessions = new LinkedList<Long>(); for (Long session : zkDb.getSessions()) { if (zkDb.getSessionWithTimeOuts().get(session) == null) { deadSessions.add(session); } } zkDb.setDataTreeInit(true); for (long session : deadSessions) { killSession(session, zkDb.getDataTreeLastProcessedZxid()); } } <-------结束了----->
ChaseSuccesser/Zookeeper-SourceAnalysis
001.zookeeper启动.java
1,585
/** * 2.启动IO主线程 */
block_comment
zh-cn
ZookeeperServerMain类: protected void initializeAndRun(String[] args) throws ConfigException, IOException { try { ManagedUtil.registerLog4jMBeans(); } catch (JMException e) { LOG.warn("Unable to register log4j JMX control", e); } ServerConfig config = new ServerConfig(); if (args.length == 1) { config.parse(args[0]); } else { config.parse(args); } runFromConfig(config); } /** * 1.从配置文件zoo.cfg读取信息 */ public void parse(String path) throws ConfigException { QuorumPeerConfig config = new QuorumPeerConfig(); config.parse(path); readFrom(config); } public void parse(String path) throws ConfigException { File configFile = new File(path); LOG.info("Reading configuration from: " + configFile); try { if (!configFile.exists()) { throw new IllegalArgumentException(configFile.toString() + " file is missing"); } Properties cfg = new Properties(); FileInputStream in = new FileInputStream(configFile); try { cfg.load(in); } finally { in.close(); } parseProperties(cfg); } catch (IOException e) { throw new ConfigException("Error processing " + path, e); } catch (IllegalArgumentException e) { throw new ConfigException("Error processing " + path, e); } } /** * 启动 */ public void runFromConfig(ServerConfig config) throws IOException { LOG.info("Starting server"); FileTxnSnapLog txnLog = null; try { // 创建ZookeeperServer对象,并将读取的配置信息赋给ZookeeperServer的属性 ZooKeeperServer zkServer = new ZooKeeperServer(); txnLog = new FileTxnSnapLog(new File(config.dataLogDir), new File(config.dataDir)); zkServer.setTxnLogFactory(txnLog); zkServer.setTickTime(config.tickTime); zkServer.setMinSessionTimeout(config.minSessionTimeout); zkServer.setMaxSessionTimeout(config.maxSessionTimeout); // 默认创建得到NIOServerCnxnFactory类的实例 cnxnFactory = ServerCnxnFactory.createFactory(); /** * 创建ServerSocketChannel实例,注册到Selector上,感兴趣的操作为accept */ cnxnFactory.configure(config.getClientPortAddress(),config.getMaxClientCnxns()); cnxnFactory.startup(zkServer); cnxnFactory.join(); if (zkServer.isRunning()) { zkServer.shutdown(); } } catch (InterruptedException e) { LOG.warn("Server interrupted", e); } finally { if (txnLog != null) { txnLog.close(); } } } public void startup(ZooKeeperServer zks) throws IOException,InterruptedException { /** * 2.启 <SUF>*/ start(); /** * 3.从log和snapshot恢复database和session */ zks.startdata(); /** * 4.启动sessionTracker线程,初始化IO请求的处理链,并启动每个processor线程 */ zks.startup(); setZooKeeperServer(zks); } public void run() { while (!ss.socket().isClosed()) { try { selector.select(1000); Set<SelectionKey> selected; synchronized (this) { selected = selector.selectedKeys(); } ArrayList<SelectionKey> selectedList = new ArrayList<SelectionKey>(selected); Collections.shuffle(selectedList); for (SelectionKey k : selectedList) { if ((k.readyOps() & SelectionKey.OP_ACCEPT) != 0) { SocketChannel sc = ((ServerSocketChannel) k .channel()).accept(); InetAddress ia = sc.socket().getInetAddress(); int cnxncount = getClientCnxnCount(ia); if (maxClientCnxns > 0 && cnxncount >= maxClientCnxns){ LOG.warn("Too many connections from " + ia + " - max is " + maxClientCnxns ); sc.close(); } else { LOG.info("Accepted socket connection from " + sc.socket().getRemoteSocketAddress()); sc.configureBlocking(false); SelectionKey sk = sc.register(selector, SelectionKey.OP_READ); /** * 根据sc和sk创建NIOServerCnxn对象,并将它绑定到sk上 * 这样以后发生了读写操作时,都是调用NIOServerCnxn类里的doIO()方法进行处理 */ NIOServerCnxn cnxn = createConnection(sc, sk); sk.attach(cnxn); addCnxn(cnxn); } } else if ((k.readyOps() & (SelectionKey.OP_READ | SelectionKey.OP_WRITE)) != 0) { NIOServerCnxn c = (NIOServerCnxn) k.attachment(); c.doIO(k); } else { if (LOG.isDebugEnabled()) { LOG.debug("Unexpected ops in select " + k.readyOps()); } } } selected.clear(); } catch (RuntimeException e) { LOG.warn("Ignoring unexpected runtime exception", e); } catch (Exception e) { LOG.warn("Ignoring exception", e); } } closeAll(); LOG.info("NIOServerCnxn factory exited run method"); } public void startdata() throws IOException, InterruptedException { if (zkDb == null) { zkDb = new ZKDatabase(this.txnLogFactory); } if (!zkDb.isInitialized()) { loadData(); } } // '/','/zookeeper','/zookeeper/quota'3个系统节点初始化 public DataTree() { nodes.put("", root); nodes.put(rootZookeeper, root); root.addChild(procChildZookeeper); nodes.put(procZookeeper, procDataNode); procDataNode.addChild(quotaChildZookeeper); nodes.put(quotaZookeeper, quotaDataNode); } /** * Restore sessions and data */ public void loadData() throws IOException, InterruptedException { // 执行恢复,并返回最新的事务ID if(zkDb.isInitialized()){ setZxid(zkDb.getDataTreeLastProcessedZxid()); } else { setZxid(zkDb.loadDataBase()); } // 清理session LinkedList<Long> deadSessions = new LinkedList<Long>(); for (Long session : zkDb.getSessions()) { if (zkDb.getSessionWithTimeOuts().get(session) == null) { deadSessions.add(session); } } zkDb.setDataTreeInit(true); for (long session : deadSessions) { killSession(session, zkDb.getDataTreeLastProcessedZxid()); } } <-------结束了----->
0
1,488
13
1,585
12
1,740
14
1,585
12
2,055
18
false
false
false
false
false
true
22548_11
package com.sicnu.cheer.generalmodule.bean; import com.google.gson.annotations.SerializedName; import java.io.Serializable; import java.util.List; /** * 登录信息 * Created by cheer on 2016/11/7. */ public class LoginInfo implements Serializable { private String office;//办公室 private String birthday;//生日 private String sex;//性别 private String headPic;//头像相对路径 private String officePhone;//办公电话 private String checkPhone;//校验手机号 private String jobNumber;//工号 private String jobTitle;//职务 @SerializedName("username") private String userName;//用户帐号 private String mobilePhone;//手机号码 private String token;//令牌号 private String email;//邮箱 private String userId;//用户编号 @SerializedName("realname") private String realName;//用户真实姓名 private String qq;//QQ号码 private List<Department> departs;//用户所在部门 public String getOffice() { return office; } public void setOffice(String office) { this.office = office; } public String getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getHeadPic() { return headPic; } public void setHeadPic(String headPic) { this.headPic = headPic; } public String getOfficePhone() { return officePhone; } public void setOfficePhone(String officePhone) { this.officePhone = officePhone; } public String getCheckPhone() { return checkPhone; } public void setCheckPhone(String checkPhone) { this.checkPhone = checkPhone; } public String getJobNumber() { return jobNumber; } public void setJobNumber(String jobNumber) { this.jobNumber = jobNumber; } public String getJobTitle() { return jobTitle; } public void setJobTitle(String jobTitle) { this.jobTitle = jobTitle; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getMobilePhone() { return mobilePhone; } public void setMobilePhone(String mobilePhone) { this.mobilePhone = mobilePhone; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getRealName() { return realName; } public void setRealName(String realName) { this.realName = realName; } public String getQq() { return qq; } public void setQq(String qq) { this.qq = qq; } public List<Department> getDeparts() { return departs; } public void setDeparts(List<Department> departs) { this.departs = departs; } }
CheerQY/LeaugeBar_Android
generalmodule/src/main/java/com/sicnu/cheer/generalmodule/bean/LoginInfo.java
803
//用户所在部门
line_comment
zh-cn
package com.sicnu.cheer.generalmodule.bean; import com.google.gson.annotations.SerializedName; import java.io.Serializable; import java.util.List; /** * 登录信息 * Created by cheer on 2016/11/7. */ public class LoginInfo implements Serializable { private String office;//办公室 private String birthday;//生日 private String sex;//性别 private String headPic;//头像相对路径 private String officePhone;//办公电话 private String checkPhone;//校验手机号 private String jobNumber;//工号 private String jobTitle;//职务 @SerializedName("username") private String userName;//用户帐号 private String mobilePhone;//手机号码 private String token;//令牌号 private String email;//邮箱 private String userId;//用户编号 @SerializedName("realname") private String realName;//用户真实姓名 private String qq;//QQ号码 private List<Department> departs;//用户 <SUF> public String getOffice() { return office; } public void setOffice(String office) { this.office = office; } public String getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getHeadPic() { return headPic; } public void setHeadPic(String headPic) { this.headPic = headPic; } public String getOfficePhone() { return officePhone; } public void setOfficePhone(String officePhone) { this.officePhone = officePhone; } public String getCheckPhone() { return checkPhone; } public void setCheckPhone(String checkPhone) { this.checkPhone = checkPhone; } public String getJobNumber() { return jobNumber; } public void setJobNumber(String jobNumber) { this.jobNumber = jobNumber; } public String getJobTitle() { return jobTitle; } public void setJobTitle(String jobTitle) { this.jobTitle = jobTitle; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getMobilePhone() { return mobilePhone; } public void setMobilePhone(String mobilePhone) { this.mobilePhone = mobilePhone; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getRealName() { return realName; } public void setRealName(String realName) { this.realName = realName; } public String getQq() { return qq; } public void setQq(String qq) { this.qq = qq; } public List<Department> getDeparts() { return departs; } public void setDeparts(List<Department> departs) { this.departs = departs; } }
0
745
4
803
4
886
4
803
4
1,054
7
false
false
false
false
false
true
43168_52
package com.tqkj.retrofitrxjavahttp.otherwebsocket; import android.annotation.SuppressLint; import android.app.KeyguardManager; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.graphics.BitmapFactory; import android.graphics.Color; import android.net.Uri; import android.os.Binder; import android.os.Build; import android.os.Handler; import android.os.IBinder; import android.os.PowerManager; import android.util.Log; import android.widget.Toast; import com.tqkj.retrofitrxjavahttp.MainActivity; import com.tqkj.retrofitrxjavahttp.R; import org.java_websocket.enums.ReadyState; import org.java_websocket.handshake.ServerHandshake; import java.net.URI; import androidx.annotation.Nullable; import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationManagerCompat; /** * author : CYS * e-mail : 1584935420@qq.com * date : 2020/10/17 0:36 * desc : * version : 1.0 */ public class JWebSocketClientService extends Service { public JWebSocketClient client; private JWebSocketClientBinder mBinder = new JWebSocketClientBinder(); private static final int GRAY_SERVICE_ID = 1001; //灰色保活 public static class GrayInnerService extends Service { @Override public int onStartCommand(Intent intent, int flags, int startId) { startForeground(GRAY_SERVICE_ID, new Notification()); stopForeground(true); stopSelf(); return super.onStartCommand(intent, flags, startId); } @Nullable @Override public IBinder onBind(Intent intent) { return null; } } PowerManager.WakeLock wakeLock; @SuppressLint("InvalidWakeLockTag") private void acquireWakeLock() { if (null == wakeLock) { PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE); wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "PostLocationService"); if (null != wakeLock) { wakeLock.acquire(10 * 60 * 1000L /*10 minutes*/);//自己加的时间限制 } } } //用于Activity和service通讯 public class JWebSocketClientBinder extends Binder { public JWebSocketClientService getService() { return JWebSocketClientService.this; } } @Nullable @Override public IBinder onBind(Intent intent) { return mBinder; } @Override public int onStartCommand(Intent intent, int flags, int startId) { //初始化websocket initSocketClient(); mHandler.postDelayed(mRunnable, HEART_BEAT_RATE);//开启心跳检测 //设置service为前台服务,提高优先级 if (Build.VERSION.SDK_INT < 18) { //Android4.3以下 ,隐藏Notification上的图标 startForeground(GRAY_SERVICE_ID, new Notification()); } else if (Build.VERSION.SDK_INT > 18 && Build.VERSION.SDK_INT < 25) { //Android4.3 - Android7.0,隐藏Notification上的图标 Intent innerIntent = new Intent(this, GrayInnerService.class); startService(innerIntent); startForeground(GRAY_SERVICE_ID, new Notification()); } else { //Android7.0以上app启动后通知栏会出现一条"正在运行"的通知 startForeground(GRAY_SERVICE_ID, sendNotification("第一次发送的监测通知"));//这里不能直接new Notification();会因为缺少信道报错 } acquireWakeLock(); return START_STICKY; } private void initSocketClient() { Log.e("JWebSocketClientService", "正在初始化"); //URI uri = URI.create("ws://192.168.1.147:8080/examples/websocket/chat");//这个是测试的地址,按需求修改 ws:// ip地址 : 端口号 URI uri = URI.create("ws://echo.websocket.org");//这个是测试的地址,按需求修改 ws:// ip地址 : 端口号 client = new JWebSocketClient(uri) { @Override public void onMessage(String message) { Log.e("JWebSocketClientService", "收到的消息:" + message); Intent intent = new Intent(); intent.setAction("com.tqkj.retrofitrxjavahttp.otherwebsocket.JWebSocketClientService");//待修改 intent.putExtra("message", message); sendBroadcast(intent);//发送广播 checkLockAndShowNotification(message);//发出通知 } @Override public void onOpen(ServerHandshake handshakedata) { super.onOpen(handshakedata); Log.e("JWebSocketClientService", "websocketOnOpen连接成功"); } @Override public void onError(Exception ex) { super.onError(ex); Log.e("JWebSocketClientService", ex.getMessage()); } @Override public void onClose(int code, String reason, boolean remote) { super.onClose(code, reason, remote); Log.e("JWebSocketClientService", reason); } }; connect(); } /** * 连接websocket */ private void connect() { new Thread() { @Override public void run() { try { //connectBlocking多出一个等待操作,会先连接再发送,否则未连接发送会报错 Log.e("JWebSocketClientService", "正在连接到服务器"); client.connectBlocking(); } catch (Exception e) { e.printStackTrace(); Log.e("JWebSocketClientService", e.getMessage()); } } }.start(); } /** * * 发送消息 * * */ public void sendMessage(String msg) { if (null != client) { client.send(msg);//发送消息的服务器 //测试了好久都不起作用。(测试设备的是小米10和vivoNex) // if (client.getReadyState().equals(ReadyState.OPEN)) { // Log.e("JWebSocketClientService", "发送的消息:" + msg); // client.send(msg);//发送消息的服务器 // } else { // Log.e("JWebSocketClientService", "不处于开启状态"); // } } } /** * 断开连接 */ private void closeConnect() { try { if (null != client) { client.close(); } } catch (Exception e) { e.printStackTrace(); Log.e("JWebSocketClientService", e.getMessage()); } finally { client = null; } } // -----------------------------------消息通知-------------------------------------------------------- /** * 检查锁屏状态,如果锁屏,先点亮屏幕 * * @param message */ @SuppressLint("InvalidWakeLockTag") private void checkLockAndShowNotification(String message) { //管理锁屏的一个服务 KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE); if (km.inKeyguardRestrictedInputMode()) {//锁屏 //获取电源管理器对象 PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE); if (!pm.isInteractive()) { PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "bright"); wl.acquire(10 * 60 * 1000L /*10 minutes*/); //点亮屏幕 wl.release(); //任务结束后释放 } sendNotification(message); } else { sendNotification(message); } } /** * 发送通知 * 8.1以上系统开启通知闪退问题,是因为通知要添加信道才行了。 * * @param message */ private Notification sendNotification(String message) { String ChannelId = "webTestId"; String ChannelName = "webServiceTest"; NotificationChannel notificationChannel; Notification notification; Intent intent = new Intent(); intent.setClass(this, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); //添加信道以只会安卓8.1以上消息通知,创建信道 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { notificationChannel = new NotificationChannel( ChannelId, ChannelName, NotificationManager.IMPORTANCE_HIGH); notificationChannel.enableLights(false);//如果使用中的设备支持通知灯,则说明此通知通道是否应显示灯 notificationChannel.setLightColor(Color.RED); notificationChannel.setShowBadge(true);//是否显示角标 notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_SECRET); //描述 notificationChannel.setDescription("websocket"); notificationManager.createNotificationChannel(notificationChannel); //创建通知 notification = new NotificationCompat.Builder(this, ChannelId)//必须添加信道id .setAutoCancel(true) // 设置该通知优先级 .setPriority(NotificationCompat.PRIORITY_MAX) .setSmallIcon(R.drawable.ic_launcher_background)//在android8.0之后的通知没有SmallIcon也会报错。必须加上 .setContentTitle("服务器") .setContentText(message) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setWhen(System.currentTimeMillis()) // 向通知添加声音、闪灯和振动效果 .setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_ALL | Notification.DEFAULT_SOUND) .setContentIntent(pendingIntent) .build(); } else { notification = new Notification.Builder(this) .setAutoCancel(true) // 设置该通知优先级 .setPriority(Notification.PRIORITY_MAX) .setSmallIcon(R.drawable.ic_launcher_background) .setContentTitle("服务器") .setContentText(message) .setVisibility(Notification.VISIBILITY_PUBLIC) .setWhen(System.currentTimeMillis()) // 向通知添加声音、闪灯和振动效果 .setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_ALL | Notification.DEFAULT_SOUND) .setContentIntent(pendingIntent) .build(); } //notification.flags |= Notification.FLAG_NO_CLEAR; //通知开始唤醒 //startForeground(100001, notification);//前台通知,和下面的二取一 notificationManager.notify(100001, notification);//id要保证唯一 return notification; } //-------------------------------------websocket心跳检测------------------------------------------------ private static final long HEART_BEAT_RATE = 10 * 1000;//每隔10秒进行一次对长连接的心跳检测 private final Handler mHandler = new Handler(); private final Runnable mRunnable = new Runnable() { @Override public void run() { Log.e("JWebSocketClientService", "心跳包检测websocket连接状态"); if (client != null) { if (client.isClosed()) { reconnectWs(); Log.e("JWebSocketClientService", "client是关闭的"); } else if (client.isOpen()) { Log.e("JWebSocketClientService", "client是开启的"); } else if (client.isClosing()) { Log.e("JWebSocketClientService", "client是isClosing"); } else if (client.isFlushAndClose()) { Log.e("JWebSocketClientService", "client是isFlushAndClose"); } else if (client.isReuseAddr()) { Log.e("JWebSocketClientService", "client是isReuseAddr"); } else if (client.isTcpNoDelay()) { Log.e("JWebSocketClientService", "client是isTcpNoDelay"); } else { Log.e("JWebSocketClientService", "client不知道在干吗"); } } else { //如果client已为空,重新初始化连接 client = null; initSocketClient(); Log.e("JWebSocketClientService", "client是空的"); } //每隔一定的时间,对长连接进行一次心跳检测 mHandler.postDelayed(mRunnable, HEART_BEAT_RATE); } }; /** * 开启重连 */ private void reconnectWs() { mHandler.removeCallbacks(mRunnable); //子线程异步 new Thread() { @Override public void run() { try { Log.e("JWebSocketClientService", "开启重连"); client.reconnectBlocking(); } catch (InterruptedException e) { e.printStackTrace(); Log.e("JWebSocketClientService", e.getMessage()); } } }.start(); } @Override public void onDestroy() { Log.e("JWebSocketClientService", "onDestroy"); closeConnect(); super.onDestroy(); } public JWebSocketClientService() { } }
ChenBabys/RetrofitRxJavaHttp
app/src/main/java/com/tqkj/retrofitrxjavahttp/otherwebsocket/JWebSocketClientService.java
3,129
//如果client已为空,重新初始化连接
line_comment
zh-cn
package com.tqkj.retrofitrxjavahttp.otherwebsocket; import android.annotation.SuppressLint; import android.app.KeyguardManager; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.graphics.BitmapFactory; import android.graphics.Color; import android.net.Uri; import android.os.Binder; import android.os.Build; import android.os.Handler; import android.os.IBinder; import android.os.PowerManager; import android.util.Log; import android.widget.Toast; import com.tqkj.retrofitrxjavahttp.MainActivity; import com.tqkj.retrofitrxjavahttp.R; import org.java_websocket.enums.ReadyState; import org.java_websocket.handshake.ServerHandshake; import java.net.URI; import androidx.annotation.Nullable; import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationManagerCompat; /** * author : CYS * e-mail : 1584935420@qq.com * date : 2020/10/17 0:36 * desc : * version : 1.0 */ public class JWebSocketClientService extends Service { public JWebSocketClient client; private JWebSocketClientBinder mBinder = new JWebSocketClientBinder(); private static final int GRAY_SERVICE_ID = 1001; //灰色保活 public static class GrayInnerService extends Service { @Override public int onStartCommand(Intent intent, int flags, int startId) { startForeground(GRAY_SERVICE_ID, new Notification()); stopForeground(true); stopSelf(); return super.onStartCommand(intent, flags, startId); } @Nullable @Override public IBinder onBind(Intent intent) { return null; } } PowerManager.WakeLock wakeLock; @SuppressLint("InvalidWakeLockTag") private void acquireWakeLock() { if (null == wakeLock) { PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE); wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "PostLocationService"); if (null != wakeLock) { wakeLock.acquire(10 * 60 * 1000L /*10 minutes*/);//自己加的时间限制 } } } //用于Activity和service通讯 public class JWebSocketClientBinder extends Binder { public JWebSocketClientService getService() { return JWebSocketClientService.this; } } @Nullable @Override public IBinder onBind(Intent intent) { return mBinder; } @Override public int onStartCommand(Intent intent, int flags, int startId) { //初始化websocket initSocketClient(); mHandler.postDelayed(mRunnable, HEART_BEAT_RATE);//开启心跳检测 //设置service为前台服务,提高优先级 if (Build.VERSION.SDK_INT < 18) { //Android4.3以下 ,隐藏Notification上的图标 startForeground(GRAY_SERVICE_ID, new Notification()); } else if (Build.VERSION.SDK_INT > 18 && Build.VERSION.SDK_INT < 25) { //Android4.3 - Android7.0,隐藏Notification上的图标 Intent innerIntent = new Intent(this, GrayInnerService.class); startService(innerIntent); startForeground(GRAY_SERVICE_ID, new Notification()); } else { //Android7.0以上app启动后通知栏会出现一条"正在运行"的通知 startForeground(GRAY_SERVICE_ID, sendNotification("第一次发送的监测通知"));//这里不能直接new Notification();会因为缺少信道报错 } acquireWakeLock(); return START_STICKY; } private void initSocketClient() { Log.e("JWebSocketClientService", "正在初始化"); //URI uri = URI.create("ws://192.168.1.147:8080/examples/websocket/chat");//这个是测试的地址,按需求修改 ws:// ip地址 : 端口号 URI uri = URI.create("ws://echo.websocket.org");//这个是测试的地址,按需求修改 ws:// ip地址 : 端口号 client = new JWebSocketClient(uri) { @Override public void onMessage(String message) { Log.e("JWebSocketClientService", "收到的消息:" + message); Intent intent = new Intent(); intent.setAction("com.tqkj.retrofitrxjavahttp.otherwebsocket.JWebSocketClientService");//待修改 intent.putExtra("message", message); sendBroadcast(intent);//发送广播 checkLockAndShowNotification(message);//发出通知 } @Override public void onOpen(ServerHandshake handshakedata) { super.onOpen(handshakedata); Log.e("JWebSocketClientService", "websocketOnOpen连接成功"); } @Override public void onError(Exception ex) { super.onError(ex); Log.e("JWebSocketClientService", ex.getMessage()); } @Override public void onClose(int code, String reason, boolean remote) { super.onClose(code, reason, remote); Log.e("JWebSocketClientService", reason); } }; connect(); } /** * 连接websocket */ private void connect() { new Thread() { @Override public void run() { try { //connectBlocking多出一个等待操作,会先连接再发送,否则未连接发送会报错 Log.e("JWebSocketClientService", "正在连接到服务器"); client.connectBlocking(); } catch (Exception e) { e.printStackTrace(); Log.e("JWebSocketClientService", e.getMessage()); } } }.start(); } /** * * 发送消息 * * */ public void sendMessage(String msg) { if (null != client) { client.send(msg);//发送消息的服务器 //测试了好久都不起作用。(测试设备的是小米10和vivoNex) // if (client.getReadyState().equals(ReadyState.OPEN)) { // Log.e("JWebSocketClientService", "发送的消息:" + msg); // client.send(msg);//发送消息的服务器 // } else { // Log.e("JWebSocketClientService", "不处于开启状态"); // } } } /** * 断开连接 */ private void closeConnect() { try { if (null != client) { client.close(); } } catch (Exception e) { e.printStackTrace(); Log.e("JWebSocketClientService", e.getMessage()); } finally { client = null; } } // -----------------------------------消息通知-------------------------------------------------------- /** * 检查锁屏状态,如果锁屏,先点亮屏幕 * * @param message */ @SuppressLint("InvalidWakeLockTag") private void checkLockAndShowNotification(String message) { //管理锁屏的一个服务 KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE); if (km.inKeyguardRestrictedInputMode()) {//锁屏 //获取电源管理器对象 PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE); if (!pm.isInteractive()) { PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "bright"); wl.acquire(10 * 60 * 1000L /*10 minutes*/); //点亮屏幕 wl.release(); //任务结束后释放 } sendNotification(message); } else { sendNotification(message); } } /** * 发送通知 * 8.1以上系统开启通知闪退问题,是因为通知要添加信道才行了。 * * @param message */ private Notification sendNotification(String message) { String ChannelId = "webTestId"; String ChannelName = "webServiceTest"; NotificationChannel notificationChannel; Notification notification; Intent intent = new Intent(); intent.setClass(this, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); //添加信道以只会安卓8.1以上消息通知,创建信道 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { notificationChannel = new NotificationChannel( ChannelId, ChannelName, NotificationManager.IMPORTANCE_HIGH); notificationChannel.enableLights(false);//如果使用中的设备支持通知灯,则说明此通知通道是否应显示灯 notificationChannel.setLightColor(Color.RED); notificationChannel.setShowBadge(true);//是否显示角标 notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_SECRET); //描述 notificationChannel.setDescription("websocket"); notificationManager.createNotificationChannel(notificationChannel); //创建通知 notification = new NotificationCompat.Builder(this, ChannelId)//必须添加信道id .setAutoCancel(true) // 设置该通知优先级 .setPriority(NotificationCompat.PRIORITY_MAX) .setSmallIcon(R.drawable.ic_launcher_background)//在android8.0之后的通知没有SmallIcon也会报错。必须加上 .setContentTitle("服务器") .setContentText(message) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setWhen(System.currentTimeMillis()) // 向通知添加声音、闪灯和振动效果 .setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_ALL | Notification.DEFAULT_SOUND) .setContentIntent(pendingIntent) .build(); } else { notification = new Notification.Builder(this) .setAutoCancel(true) // 设置该通知优先级 .setPriority(Notification.PRIORITY_MAX) .setSmallIcon(R.drawable.ic_launcher_background) .setContentTitle("服务器") .setContentText(message) .setVisibility(Notification.VISIBILITY_PUBLIC) .setWhen(System.currentTimeMillis()) // 向通知添加声音、闪灯和振动效果 .setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_ALL | Notification.DEFAULT_SOUND) .setContentIntent(pendingIntent) .build(); } //notification.flags |= Notification.FLAG_NO_CLEAR; //通知开始唤醒 //startForeground(100001, notification);//前台通知,和下面的二取一 notificationManager.notify(100001, notification);//id要保证唯一 return notification; } //-------------------------------------websocket心跳检测------------------------------------------------ private static final long HEART_BEAT_RATE = 10 * 1000;//每隔10秒进行一次对长连接的心跳检测 private final Handler mHandler = new Handler(); private final Runnable mRunnable = new Runnable() { @Override public void run() { Log.e("JWebSocketClientService", "心跳包检测websocket连接状态"); if (client != null) { if (client.isClosed()) { reconnectWs(); Log.e("JWebSocketClientService", "client是关闭的"); } else if (client.isOpen()) { Log.e("JWebSocketClientService", "client是开启的"); } else if (client.isClosing()) { Log.e("JWebSocketClientService", "client是isClosing"); } else if (client.isFlushAndClose()) { Log.e("JWebSocketClientService", "client是isFlushAndClose"); } else if (client.isReuseAddr()) { Log.e("JWebSocketClientService", "client是isReuseAddr"); } else if (client.isTcpNoDelay()) { Log.e("JWebSocketClientService", "client是isTcpNoDelay"); } else { Log.e("JWebSocketClientService", "client不知道在干吗"); } } else { //如果 <SUF> client = null; initSocketClient(); Log.e("JWebSocketClientService", "client是空的"); } //每隔一定的时间,对长连接进行一次心跳检测 mHandler.postDelayed(mRunnable, HEART_BEAT_RATE); } }; /** * 开启重连 */ private void reconnectWs() { mHandler.removeCallbacks(mRunnable); //子线程异步 new Thread() { @Override public void run() { try { Log.e("JWebSocketClientService", "开启重连"); client.reconnectBlocking(); } catch (InterruptedException e) { e.printStackTrace(); Log.e("JWebSocketClientService", e.getMessage()); } } }.start(); } @Override public void onDestroy() { Log.e("JWebSocketClientService", "onDestroy"); closeConnect(); super.onDestroy(); } public JWebSocketClientService() { } }
0
2,792
9
3,129
9
3,303
9
3,129
9
4,128
15
false
false
false
false
false
true
40841_6
/* Leetcode 241. Different Ways to Add Parentheses Given a string expression of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. You may return the answer in any order. The test cases are generated such that the output values fit in a 32-bit integer and the number of different results does not exceed 104. Example 1: Input: expression = "2-1-1" Output: [0,2] Explanation: ((2-1)-1) = 0 (2-(1-1)) = 2 Example 2: Input: expression = "2*3-4*5" Output: [-34,-14,-10,-10,10] Explanation: (2*(3-(4*5))) = -34 ((2*3)-(4*5)) = -14 ((2*(3-4))*5) = -10 (2*((3-4)*5)) = -10 (((2*3)-4)*5) = 10 Constraints: 1 <= expression.length <= 20 expression consists of digits and the operator '+', '-', and '*'. All the integer values in the input expression are in the range [0, 99]. */ /* 思路: Divide Conquer algorithm 分治 + recursion 递归 这是一道非常经典的分支题目,题意是考虑括号的位置,找出和计算所有放入一个括号之后得到的数值 类似于一个二叉树的形式,每当遇到一个符号的时候,就进行分解 Divide 同时递归 ==》 if(c == '+' || c == '*' || c == '-') ==》 ==》 List<Integer> leftP = diffWaysToCompute(expression.substring(0, i));//开头到符号左边 List<Integer> rightP= diffWaysToCompute(expression.substring(i + 1));//符号右边的全部 这样可以把一个长式子,不停的划分为短的, 然后再一个一个计算, 计算完左右两部分后,从左右两部分取出number, 进行Conquer(治疗) for(int leftNumber : leftP){ for(int rightNumber : rightP){}} ==> 每次取出一个数,再根据划分时的符号 进行计算 ==》最后得到一个结果,存入list中。 当遍历完成 就能得到所有加入一个括号之后的总值 */ //Time: O(nlogn) Space: O(n) class Solution { //Divide Conquer algorithm + recursion public List<Integer> diffWaysToCompute(String expression) { //base case if(expression == null || expression.length() == 0){ return new ArrayList<>(); } List<Integer> res = new ArrayList<>(); //travser all the element from expression for(int i = 0; i < expression.length(); i++){ char c = expression.charAt(i); //当遇到任意符号的时候停止 ==> 开始进行divide(分开) if(c == '+' || c == '*' || c == '-'){ List<Integer> leftP = diffWaysToCompute(expression.substring(0, i)); //开头到符号左边 List<Integer> rightP= diffWaysToCompute(expression.substring(i + 1));//符号右边的全部 //计算完左右两部分后,从左右两部分取出number, 进行Conquer(治疗) for(int leftNumber : leftP){ for(int rightNumber : rightP){ //计算两边的值 和 中间的符号 ==》得到一个总的结果 然后存入res的list中 if(c == '+'){ //符号为 '+' res.add(leftNumber + rightNumber); }else if(c == '-'){ //符号 '-' res.add(leftNumber - rightNumber); }else if(c == '*'){ //符号 '*' res.add(leftNumber * rightNumber); } } } } } //如果字符串中没有任何的符号存在,直接存入字符串的integer值 if(res.size() == 0){ res.add(Integer.valueOf(expression)); } return res; } }
ChenHCY/AlgorithmsQuestion
Math Question/241 Different Ways to Add Parentheses.java
1,026
//当遇到任意符号的时候停止 ==> 开始进行divide(分开)
line_comment
zh-cn
/* Leetcode 241. Different Ways to Add Parentheses Given a string expression of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. You may return the answer in any order. The test cases are generated such that the output values fit in a 32-bit integer and the number of different results does not exceed 104. Example 1: Input: expression = "2-1-1" Output: [0,2] Explanation: ((2-1)-1) = 0 (2-(1-1)) = 2 Example 2: Input: expression = "2*3-4*5" Output: [-34,-14,-10,-10,10] Explanation: (2*(3-(4*5))) = -34 ((2*3)-(4*5)) = -14 ((2*(3-4))*5) = -10 (2*((3-4)*5)) = -10 (((2*3)-4)*5) = 10 Constraints: 1 <= expression.length <= 20 expression consists of digits and the operator '+', '-', and '*'. All the integer values in the input expression are in the range [0, 99]. */ /* 思路: Divide Conquer algorithm 分治 + recursion 递归 这是一道非常经典的分支题目,题意是考虑括号的位置,找出和计算所有放入一个括号之后得到的数值 类似于一个二叉树的形式,每当遇到一个符号的时候,就进行分解 Divide 同时递归 ==》 if(c == '+' || c == '*' || c == '-') ==》 ==》 List<Integer> leftP = diffWaysToCompute(expression.substring(0, i));//开头到符号左边 List<Integer> rightP= diffWaysToCompute(expression.substring(i + 1));//符号右边的全部 这样可以把一个长式子,不停的划分为短的, 然后再一个一个计算, 计算完左右两部分后,从左右两部分取出number, 进行Conquer(治疗) for(int leftNumber : leftP){ for(int rightNumber : rightP){}} ==> 每次取出一个数,再根据划分时的符号 进行计算 ==》最后得到一个结果,存入list中。 当遍历完成 就能得到所有加入一个括号之后的总值 */ //Time: O(nlogn) Space: O(n) class Solution { //Divide Conquer algorithm + recursion public List<Integer> diffWaysToCompute(String expression) { //base case if(expression == null || expression.length() == 0){ return new ArrayList<>(); } List<Integer> res = new ArrayList<>(); //travser all the element from expression for(int i = 0; i < expression.length(); i++){ char c = expression.charAt(i); //当遇 <SUF> if(c == '+' || c == '*' || c == '-'){ List<Integer> leftP = diffWaysToCompute(expression.substring(0, i)); //开头到符号左边 List<Integer> rightP= diffWaysToCompute(expression.substring(i + 1));//符号右边的全部 //计算完左右两部分后,从左右两部分取出number, 进行Conquer(治疗) for(int leftNumber : leftP){ for(int rightNumber : rightP){ //计算两边的值 和 中间的符号 ==》得到一个总的结果 然后存入res的list中 if(c == '+'){ //符号为 '+' res.add(leftNumber + rightNumber); }else if(c == '-'){ //符号 '-' res.add(leftNumber - rightNumber); }else if(c == '*'){ //符号 '*' res.add(leftNumber * rightNumber); } } } } } //如果字符串中没有任何的符号存在,直接存入字符串的integer值 if(res.size() == 0){ res.add(Integer.valueOf(expression)); } return res; } }
0
896
15
1,026
18
975
14
1,026
18
1,247
29
false
false
false
false
false
true
58280_8
import java.util.Scanner; import ChessMap.ChessMap; import java.util.concurrent.TimeUnit; import java.lang.Runtime; import settings.AppSettings; public class App { public static boolean Flag = true; public static ChessMap map = new ChessMap(AppSettings.mapSize); public static int Languane = 0 ; /** * @param args 用不着; * @throws Exception 也用不着 * 程序的入口 */ public static void main(String[] args) throws Exception { Languane = input("Languae:(0-EN/1-CH)"); //get runtime Runtime rt = Runtime.getRuntime(); // 输出title print("===", AppSettings.title[Languane] , "===\n"); // 等待3秒 for (int i = 3; i >= 0; i--) { print(i, "\r"); TimeUnit.SECONDS.sleep(1); } // 变量初始化 char Iswin = map.isWin(); long startTime, endTime, usedTime; // 主循环 while (Flag) { Iswin = map.isWin(); /** 获取当前系统时间 */ startTime = System.currentTimeMillis(); // 输出地图,输入棋子坐标 IO map.mapOut(); getIn('r'); // 判断是否获胜 if (Iswin != 'n') { Flag = false; print(Iswin); print(AppSettings.winPrommpt[Languane]); Flag = input(AppSettings.countinuePrompt[Languane]) == 0; map.setUpMap(); Iswin = map.isWin(); continue; } // 结束计时 endTime = System.currentTimeMillis(); usedTime = (endTime - startTime) / 1000; print(AppSettings.timeUsedPrompt[Languane][0], usedTime, AppSettings.timeUsedPrompt[Languane][1],"\n"); startTime = System.currentTimeMillis(); // 输出地图,输入棋子坐标 IO map.mapOut(); getIn('b'); // 判断是否获胜 if (Iswin != 'n') { Flag = false; print(Iswin); print(AppSettings.winPrommpt[Languane]); Flag = input(AppSettings.countinuePrompt[Languane]) == 0; map.setUpMap(); Iswin = map.isWin(); continue; } /** 获取当前的系统时间,与初始时间相减就是程序运行的毫秒数,除以1000就是秒数 */ endTime = System.currentTimeMillis(); usedTime = (endTime - startTime) / 1000; print(AppSettings.timeUsedPrompt[Languane][0], usedTime, AppSettings.timeUsedPrompt[Languane][1],"\n"); } print(AppSettings.sayGoodBye[Languane]); Runtime.getRuntime().exec("clear"); } /** * @param prompt 输出一个字符串为提示 * @return 返回输入的Int数据 * 类比 python 的 input */ private static int input(String prompt) { // 临时变量 int temp; // 打印提示语 print(prompt, ":"); // 新建扫描器,输入 Scanner scanner = new Scanner(System.in); if (scanner.hasNext()) { temp = scanner.nextInt(); } else { temp = -2147483647; } return temp; } /** * @param args 要打印的字符 * 类比 python 的 print */ private static void print(Object... args) { for (Object string : args) { System.out.print(string); } } /** * @param who 落子者 * 用来输入 x , y 坐标 */ public static void getIn(char who) { if (!(map.downChess(input(AppSettings.getInPrompt[Languane][0]), input(AppSettings.getInPrompt[Languane][0]), who))) { print("\033[31m", AppSettings.getInErrorPrompt[Languane], "\n", "\033[m"); getIn(who); return; } return; } }
ChenHongMing666/Gobang
src/App.java
996
// 判断是否获胜
line_comment
zh-cn
import java.util.Scanner; import ChessMap.ChessMap; import java.util.concurrent.TimeUnit; import java.lang.Runtime; import settings.AppSettings; public class App { public static boolean Flag = true; public static ChessMap map = new ChessMap(AppSettings.mapSize); public static int Languane = 0 ; /** * @param args 用不着; * @throws Exception 也用不着 * 程序的入口 */ public static void main(String[] args) throws Exception { Languane = input("Languae:(0-EN/1-CH)"); //get runtime Runtime rt = Runtime.getRuntime(); // 输出title print("===", AppSettings.title[Languane] , "===\n"); // 等待3秒 for (int i = 3; i >= 0; i--) { print(i, "\r"); TimeUnit.SECONDS.sleep(1); } // 变量初始化 char Iswin = map.isWin(); long startTime, endTime, usedTime; // 主循环 while (Flag) { Iswin = map.isWin(); /** 获取当前系统时间 */ startTime = System.currentTimeMillis(); // 输出地图,输入棋子坐标 IO map.mapOut(); getIn('r'); // 判断 <SUF> if (Iswin != 'n') { Flag = false; print(Iswin); print(AppSettings.winPrommpt[Languane]); Flag = input(AppSettings.countinuePrompt[Languane]) == 0; map.setUpMap(); Iswin = map.isWin(); continue; } // 结束计时 endTime = System.currentTimeMillis(); usedTime = (endTime - startTime) / 1000; print(AppSettings.timeUsedPrompt[Languane][0], usedTime, AppSettings.timeUsedPrompt[Languane][1],"\n"); startTime = System.currentTimeMillis(); // 输出地图,输入棋子坐标 IO map.mapOut(); getIn('b'); // 判断是否获胜 if (Iswin != 'n') { Flag = false; print(Iswin); print(AppSettings.winPrommpt[Languane]); Flag = input(AppSettings.countinuePrompt[Languane]) == 0; map.setUpMap(); Iswin = map.isWin(); continue; } /** 获取当前的系统时间,与初始时间相减就是程序运行的毫秒数,除以1000就是秒数 */ endTime = System.currentTimeMillis(); usedTime = (endTime - startTime) / 1000; print(AppSettings.timeUsedPrompt[Languane][0], usedTime, AppSettings.timeUsedPrompt[Languane][1],"\n"); } print(AppSettings.sayGoodBye[Languane]); Runtime.getRuntime().exec("clear"); } /** * @param prompt 输出一个字符串为提示 * @return 返回输入的Int数据 * 类比 python 的 input */ private static int input(String prompt) { // 临时变量 int temp; // 打印提示语 print(prompt, ":"); // 新建扫描器,输入 Scanner scanner = new Scanner(System.in); if (scanner.hasNext()) { temp = scanner.nextInt(); } else { temp = -2147483647; } return temp; } /** * @param args 要打印的字符 * 类比 python 的 print */ private static void print(Object... args) { for (Object string : args) { System.out.print(string); } } /** * @param who 落子者 * 用来输入 x , y 坐标 */ public static void getIn(char who) { if (!(map.downChess(input(AppSettings.getInPrompt[Languane][0]), input(AppSettings.getInPrompt[Languane][0]), who))) { print("\033[31m", AppSettings.getInErrorPrompt[Languane], "\n", "\033[m"); getIn(who); return; } return; } }
0
926
5
996
6
1,060
5
996
6
1,292
10
false
false
false
false
false
true
45313_3
import simbad.sim.Agent; import simbad.sim.LampActuator; import simbad.sim.RangeSensorBelt; import simbad.sim.RobotFactory; import javax.vecmath.Color3f; import javax.vecmath.Point3d; import javax.vecmath.Vector2d; import javax.vecmath.Vector3d; /** * Created by jiajianchen * on 2019/1/7 * 用于定义警察机器人 */ public class PoliceRobot extends Agent { RangeSensorBelt sonars; RangeSensorBelt bumpers; LampActuator lamp;//灯 private MyEnv ev; // 环境实例,用于获取环境中的因素 private double velocity = 0.5; // 速度 private boolean debug = false; // 调试状态 private boolean isLeader = false; // 是否为领航机器人 private Vector2d targetPoint = new Vector2d(0, 0); // 目标点 private static int freeze_time = 0; private static Color3f mLeaderColor = new Color3f(60, 60, 60); private static Color3f mCommonColor = new Color3f(20, 20, 20); public PoliceRobot(Vector3d position, String name) { super(position,name); sonars = RobotFactory.addSonarBeltSensor(this, 8); bumpers = RobotFactory.addBumperBeltSensor(this); lamp = RobotFactory.addLamp(this); setColor(new Color3f(20, 20, 20)); } public void initBehavior() {} void setParams(MyEnv ev, double velocity, boolean debug) { this.ev = ev; this.velocity = velocity; this.debug = debug; } /** * 运动算法 */ public void performBehavior() { if ((getCounter() % 10) == 0) { if (isLeader) setColor(mLeaderColor); else setColor(mCommonColor); if (ev.getThiefState() == 2) { if (debug) System.out.println("盗贼被抓住了!!!"); setRotationalVelocity(0); setTranslationalVelocity(0); } else { if (ev.getThiefState() == 0) walkWithGoal(targetPoint); else walkWithGoal(ev.getThiefRobot().getPosition()); } } } /** * 获取当前位置 */ Vector2d getPosition() { Point3d p = new Point3d(); getCoords(p); return new Vector2d(p.z, p.x); } /** * 设置领航状态 */ void setIsLeader(boolean status) { isLeader = status; } /** * 设置目标点 */ void setTargetPoint(Vector2d targetPoint) { this.targetPoint = targetPoint; } Vector2d getTargetPoint() { return targetPoint; } /** * 判断是否长期静止 */ private boolean isStopForLong(Vector2d pre, Vector2d cur) { if (cur.equals(pre)) { if (freeze_time == 30) // 如果边界设置太小会影响正常的碰撞处理 return true; else { freeze_time++; return false; } } else { freeze_time = 0; return false; } } /** * 向目标移动,避开障碍物 * 人工势场法 */ private void walkWithGoal(Vector2d goal) { setTranslationalVelocity(this.velocity); // 获取速度 Vector3d velocity = this.linearVelocity; // 获取当前运动方向 Vector2d direct = new Vector2d(velocity.z, velocity.x); // 获取当前运动位置 Point3d p = new Point3d(); getCoords(p); Vector2d pos = new Vector2d(p.z, p.x); //获取三方个障碍物的距离 double d0 = sonars.getMeasurement(0);// front声纳,正前方 double d1 = sonars.getMeasurement(1);// frontleft声纳,左前方 double d2 = sonars.getMeasurement(7);// frontright声纳,右前方 // 计算三个方向障碍物的斥力 double rf0 = MyUtil.repelForce(d0); double rf1 = MyUtil.repelForce(d1); double rf2 = MyUtil.repelForce(d2); //计算三个方向障碍物斥力的合力 double k1 = Math.cos(2 * Math.PI / 9); double k2 = Math.sin(2 * Math.PI / 9); Vector2d vf0 = new Vector2d(0 - rf0, 0); Vector2d vf1 = new Vector2d((0 - rf1 * k1), (0 - rf1 * k2)); Vector2d vf2 = new Vector2d((rf2 * k1), (rf2 * k2)); Vector2d composition = new Vector2d(); composition.setX(vf0.x + vf1.x + vf2.x); composition.setY(vf0.y + vf1.y + vf2.y); if (debug) System.out.println("(" + composition.x + "," + composition.y); //给定斥力合力向量 Vector2d repelForceVector = MyUtil.transform(direct, composition); // 计算目标的对机器人的引力 Vector2d toGoal = new Vector2d((goal.x - pos.x), (goal.y - pos.y)); double disGoal = toGoal.length();//和目的的距离 if (debug) System.out.println("distance to goal:" + disGoal); double goalForce = MyUtil.attractForce(disGoal);//计算引力 if (debug) System.out.println("attract force from goal:" + goalForce); Vector2d goalForceVector = new Vector2d( (goalForce * toGoal.x / disGoal), (goalForce * toGoal.y / disGoal)); // 计算斥力和引力的合力 double x = repelForceVector.x + goalForceVector.x; double y = repelForceVector.y + goalForceVector.y; Vector2d allForces = new Vector2d(x, y); if (debug) { System.out.println("total force(" + allForces.x + "," + allForces.y + ")"); System.out.println("force direct(" + direct.x + "," + direct.y + ")"); } // 根据合力的方向和当前运动方向的夹角来判断当前转动角度 double angle = MyUtil.getAngle(direct, allForces); if (debug) System.out.println("angle:" + angle); // 判断转动方向 if (angle < Math.PI) { setRotationalVelocity(angle); } else if (angle > Math.PI) { setRotationalVelocity((angle - 2 * Math.PI)); } // 是否到达目标点 if (checkGoal(new Point3d(goal.x, 0, goal.y))) { // 到达目标点,亮绿灯 停止运动 setTranslationalVelocity(0); setRotationalVelocity(0); // lamp.setOn(true); return; } else { // lamp.setOn(false); setTranslationalVelocity(0.5); } // 检测是否碰撞 if (bumpers.oneHasHit()) { // 机器人身体三个方向和障碍物的距离 double left = sonars.getFrontLeftQuadrantMeasurement(); double right = sonars.getFrontRightQuadrantMeasurement(); double front = sonars.getFrontQuadrantMeasurement(); // 如果接近障碍物 if ((front < 0.7) || (left < 0.7) || (right < 0.7)) { setTranslationalVelocity(0); if (left < right) { setRotationalVelocity(-1 - (0.1 * Math.random()));// 随机向右转 } else { setRotationalVelocity(1 - (0.1 * Math.random()));// 随机向左转 } } } // 判断是否一直不动 // 获取前一次运动位置 getCoords(p); Vector2d cur_pos = new Vector2d(p.z, p.x); if (isStopForLong(pos, cur_pos)) { if (debug) System.out.println(this.name + "卡住了!!!"); setTranslationalVelocity(0); setRotationalVelocity(Math.PI); freeze_time = 0; } } /** * 检查是否到达目标 */ private boolean checkGoal(Point3d goal3d) { // 当前位置 Point3d currentPos = new Point3d(); getCoords(currentPos); Point3d goalPos = new Point3d(goal3d.x, goal3d.y, goal3d.z); // 如果当前距离目标点小于0.5那么即认为是到达 return currentPos.distance(goalPos) <= 0.5; } }
ChenJiaJian96/HuntingGame
main/src/PoliceRobot.java
2,236
// 是否为领航机器人
line_comment
zh-cn
import simbad.sim.Agent; import simbad.sim.LampActuator; import simbad.sim.RangeSensorBelt; import simbad.sim.RobotFactory; import javax.vecmath.Color3f; import javax.vecmath.Point3d; import javax.vecmath.Vector2d; import javax.vecmath.Vector3d; /** * Created by jiajianchen * on 2019/1/7 * 用于定义警察机器人 */ public class PoliceRobot extends Agent { RangeSensorBelt sonars; RangeSensorBelt bumpers; LampActuator lamp;//灯 private MyEnv ev; // 环境实例,用于获取环境中的因素 private double velocity = 0.5; // 速度 private boolean debug = false; // 调试状态 private boolean isLeader = false; // 是否 <SUF> private Vector2d targetPoint = new Vector2d(0, 0); // 目标点 private static int freeze_time = 0; private static Color3f mLeaderColor = new Color3f(60, 60, 60); private static Color3f mCommonColor = new Color3f(20, 20, 20); public PoliceRobot(Vector3d position, String name) { super(position,name); sonars = RobotFactory.addSonarBeltSensor(this, 8); bumpers = RobotFactory.addBumperBeltSensor(this); lamp = RobotFactory.addLamp(this); setColor(new Color3f(20, 20, 20)); } public void initBehavior() {} void setParams(MyEnv ev, double velocity, boolean debug) { this.ev = ev; this.velocity = velocity; this.debug = debug; } /** * 运动算法 */ public void performBehavior() { if ((getCounter() % 10) == 0) { if (isLeader) setColor(mLeaderColor); else setColor(mCommonColor); if (ev.getThiefState() == 2) { if (debug) System.out.println("盗贼被抓住了!!!"); setRotationalVelocity(0); setTranslationalVelocity(0); } else { if (ev.getThiefState() == 0) walkWithGoal(targetPoint); else walkWithGoal(ev.getThiefRobot().getPosition()); } } } /** * 获取当前位置 */ Vector2d getPosition() { Point3d p = new Point3d(); getCoords(p); return new Vector2d(p.z, p.x); } /** * 设置领航状态 */ void setIsLeader(boolean status) { isLeader = status; } /** * 设置目标点 */ void setTargetPoint(Vector2d targetPoint) { this.targetPoint = targetPoint; } Vector2d getTargetPoint() { return targetPoint; } /** * 判断是否长期静止 */ private boolean isStopForLong(Vector2d pre, Vector2d cur) { if (cur.equals(pre)) { if (freeze_time == 30) // 如果边界设置太小会影响正常的碰撞处理 return true; else { freeze_time++; return false; } } else { freeze_time = 0; return false; } } /** * 向目标移动,避开障碍物 * 人工势场法 */ private void walkWithGoal(Vector2d goal) { setTranslationalVelocity(this.velocity); // 获取速度 Vector3d velocity = this.linearVelocity; // 获取当前运动方向 Vector2d direct = new Vector2d(velocity.z, velocity.x); // 获取当前运动位置 Point3d p = new Point3d(); getCoords(p); Vector2d pos = new Vector2d(p.z, p.x); //获取三方个障碍物的距离 double d0 = sonars.getMeasurement(0);// front声纳,正前方 double d1 = sonars.getMeasurement(1);// frontleft声纳,左前方 double d2 = sonars.getMeasurement(7);// frontright声纳,右前方 // 计算三个方向障碍物的斥力 double rf0 = MyUtil.repelForce(d0); double rf1 = MyUtil.repelForce(d1); double rf2 = MyUtil.repelForce(d2); //计算三个方向障碍物斥力的合力 double k1 = Math.cos(2 * Math.PI / 9); double k2 = Math.sin(2 * Math.PI / 9); Vector2d vf0 = new Vector2d(0 - rf0, 0); Vector2d vf1 = new Vector2d((0 - rf1 * k1), (0 - rf1 * k2)); Vector2d vf2 = new Vector2d((rf2 * k1), (rf2 * k2)); Vector2d composition = new Vector2d(); composition.setX(vf0.x + vf1.x + vf2.x); composition.setY(vf0.y + vf1.y + vf2.y); if (debug) System.out.println("(" + composition.x + "," + composition.y); //给定斥力合力向量 Vector2d repelForceVector = MyUtil.transform(direct, composition); // 计算目标的对机器人的引力 Vector2d toGoal = new Vector2d((goal.x - pos.x), (goal.y - pos.y)); double disGoal = toGoal.length();//和目的的距离 if (debug) System.out.println("distance to goal:" + disGoal); double goalForce = MyUtil.attractForce(disGoal);//计算引力 if (debug) System.out.println("attract force from goal:" + goalForce); Vector2d goalForceVector = new Vector2d( (goalForce * toGoal.x / disGoal), (goalForce * toGoal.y / disGoal)); // 计算斥力和引力的合力 double x = repelForceVector.x + goalForceVector.x; double y = repelForceVector.y + goalForceVector.y; Vector2d allForces = new Vector2d(x, y); if (debug) { System.out.println("total force(" + allForces.x + "," + allForces.y + ")"); System.out.println("force direct(" + direct.x + "," + direct.y + ")"); } // 根据合力的方向和当前运动方向的夹角来判断当前转动角度 double angle = MyUtil.getAngle(direct, allForces); if (debug) System.out.println("angle:" + angle); // 判断转动方向 if (angle < Math.PI) { setRotationalVelocity(angle); } else if (angle > Math.PI) { setRotationalVelocity((angle - 2 * Math.PI)); } // 是否到达目标点 if (checkGoal(new Point3d(goal.x, 0, goal.y))) { // 到达目标点,亮绿灯 停止运动 setTranslationalVelocity(0); setRotationalVelocity(0); // lamp.setOn(true); return; } else { // lamp.setOn(false); setTranslationalVelocity(0.5); } // 检测是否碰撞 if (bumpers.oneHasHit()) { // 机器人身体三个方向和障碍物的距离 double left = sonars.getFrontLeftQuadrantMeasurement(); double right = sonars.getFrontRightQuadrantMeasurement(); double front = sonars.getFrontQuadrantMeasurement(); // 如果接近障碍物 if ((front < 0.7) || (left < 0.7) || (right < 0.7)) { setTranslationalVelocity(0); if (left < right) { setRotationalVelocity(-1 - (0.1 * Math.random()));// 随机向右转 } else { setRotationalVelocity(1 - (0.1 * Math.random()));// 随机向左转 } } } // 判断是否一直不动 // 获取前一次运动位置 getCoords(p); Vector2d cur_pos = new Vector2d(p.z, p.x); if (isStopForLong(pos, cur_pos)) { if (debug) System.out.println(this.name + "卡住了!!!"); setTranslationalVelocity(0); setRotationalVelocity(Math.PI); freeze_time = 0; } } /** * 检查是否到达目标 */ private boolean checkGoal(Point3d goal3d) { // 当前位置 Point3d currentPos = new Point3d(); getCoords(currentPos); Point3d goalPos = new Point3d(goal3d.x, goal3d.y, goal3d.z); // 如果当前距离目标点小于0.5那么即认为是到达 return currentPos.distance(goalPos) <= 0.5; } }
0
2,047
6
2,236
7
2,321
6
2,236
7
2,837
12
false
false
false
false
false
true
35470_12
import java.util.ArrayList; import java.util.List; public class Code059_MaxHappy { // 派对的最大快乐值 // 公司的每个员工都符合 Employee 类的描述。 // 整个公司的人员结构可以看作是一棵标准的、 没有环的多叉树。 // 树的头节点是公司唯一的老板。除老板之外的每个员工都有唯一的直接上级。 // 叶节点是没有任何下属的基层员工(nexts列表为空),除基层员工外,每个员工都有一个或多个直接下级。 // 这个公司现在要办party,你可以决定哪些员工来,哪些员工不来. // 规则: // 1.如果某个员工来了,那么这个员工的所有直接下级都不能来 // 2.派对的整体快乐值是所有到场员工快乐值的累加 // 3.你的目标是让派对的整体快乐值尽量大 // 给定一棵多叉树的头节点boss, // 请返回派对的最大快乐值。 public static class Employee { public int happy; // 这名员工可以带来的快乐值 public List<Employee> nexts; // 这名员工有哪些直接下级 public Employee(int happy) { this.happy = happy; // List要在构造器创建 nexts = new ArrayList<>(); } } public static int maxHappy1(Employee boss) { if (boss == null) { return 0; } return process1(boss, false); } // 当前来到的节点叫cur, // up表示cur的上级是否来, // 该函数含义: // 如果up为true,表示在cur上级已经确定来的情况下,cur整棵树能够提供最大的快乐值是多少? // 如果up为false,表示在cur上级已经确定不来的情况下,cur整棵树能够提供最大的快乐值是多少? public static int process1(Employee cur, boolean up) { if (up) { // 如果cur的上级来的话,cur没得选,只能不来 int ans = 0; for (Employee next : cur.nexts) { ans += process1(next, false); } return ans; } else { // 如果cur的上级不来的话,cur可以选,可以来也可以不来 int p1 = cur.happy; // cur 来 int p2 = 0; // cur 不来 for (Employee next : cur.nexts) { p1 += process1(next, true); p2 += process1(next, false); } return Math.max(p1, p2); } } public static int maxHappy2(Employee head) { Info allInfo = process2(head); return Math.max(allInfo.no, allInfo.yes); } public static class Info { public int no; // 当前头节点不来的最大快乐值 public int yes; // 当前头节点来的最大快乐值 public Info(int no, int yes) { this.no = no; this.yes = yes; } } public static Info process2(Employee head) { if (head == null) { return new Info(0, 0); } int no = 0; // 当前节点不选 int yes = head.happy; // 当前节点选中 for (Employee next : head.nexts) { Info nextInfo = process2(next); no += Math.max(nextInfo.no, nextInfo.yes); yes += nextInfo.no; } return new Info(no, yes); } // for test public static Employee generateBoss(int maxLevel, int maxNexts, int maxHappy) { if (Math.random() < 0.05) { return null; } Employee boss = new Employee((int) (Math.random() * (maxHappy + 1))); generateNexts(boss, 1, maxLevel, maxNexts, maxHappy); return boss; } // for test public static void generateNexts(Employee boss, int level, int maxLevel, int maxNexts, int maxHappy) { if (level > maxLevel) { return; } int nextsSize = (int) (Math.random() * (maxNexts + 1)); for (int i = 0; i < nextsSize; i++) { Employee next = new Employee((int) (Math.random() * (maxHappy + 1))); boss.nexts.add(next); generateNexts(next, level + 1, maxLevel, maxNexts, maxHappy); } } // for test public static void main(String[] args) { int maxLevel = 5; int maxNexts = 5; int maxHappy = 100; int testTimes = 1000; for (int i = 0; i < testTimes; i++) { Employee boss = generateBoss(maxLevel, maxNexts, maxHappy); if (maxHappy1(boss) != maxHappy2(boss)){ System.out.println("Oops!"); } } System.out.println("finish!"); } }
ChengYuAlex/algorithm
src/Code059_MaxHappy.java
1,250
// 这名员工可以带来的快乐值
line_comment
zh-cn
import java.util.ArrayList; import java.util.List; public class Code059_MaxHappy { // 派对的最大快乐值 // 公司的每个员工都符合 Employee 类的描述。 // 整个公司的人员结构可以看作是一棵标准的、 没有环的多叉树。 // 树的头节点是公司唯一的老板。除老板之外的每个员工都有唯一的直接上级。 // 叶节点是没有任何下属的基层员工(nexts列表为空),除基层员工外,每个员工都有一个或多个直接下级。 // 这个公司现在要办party,你可以决定哪些员工来,哪些员工不来. // 规则: // 1.如果某个员工来了,那么这个员工的所有直接下级都不能来 // 2.派对的整体快乐值是所有到场员工快乐值的累加 // 3.你的目标是让派对的整体快乐值尽量大 // 给定一棵多叉树的头节点boss, // 请返回派对的最大快乐值。 public static class Employee { public int happy; // 这名 <SUF> public List<Employee> nexts; // 这名员工有哪些直接下级 public Employee(int happy) { this.happy = happy; // List要在构造器创建 nexts = new ArrayList<>(); } } public static int maxHappy1(Employee boss) { if (boss == null) { return 0; } return process1(boss, false); } // 当前来到的节点叫cur, // up表示cur的上级是否来, // 该函数含义: // 如果up为true,表示在cur上级已经确定来的情况下,cur整棵树能够提供最大的快乐值是多少? // 如果up为false,表示在cur上级已经确定不来的情况下,cur整棵树能够提供最大的快乐值是多少? public static int process1(Employee cur, boolean up) { if (up) { // 如果cur的上级来的话,cur没得选,只能不来 int ans = 0; for (Employee next : cur.nexts) { ans += process1(next, false); } return ans; } else { // 如果cur的上级不来的话,cur可以选,可以来也可以不来 int p1 = cur.happy; // cur 来 int p2 = 0; // cur 不来 for (Employee next : cur.nexts) { p1 += process1(next, true); p2 += process1(next, false); } return Math.max(p1, p2); } } public static int maxHappy2(Employee head) { Info allInfo = process2(head); return Math.max(allInfo.no, allInfo.yes); } public static class Info { public int no; // 当前头节点不来的最大快乐值 public int yes; // 当前头节点来的最大快乐值 public Info(int no, int yes) { this.no = no; this.yes = yes; } } public static Info process2(Employee head) { if (head == null) { return new Info(0, 0); } int no = 0; // 当前节点不选 int yes = head.happy; // 当前节点选中 for (Employee next : head.nexts) { Info nextInfo = process2(next); no += Math.max(nextInfo.no, nextInfo.yes); yes += nextInfo.no; } return new Info(no, yes); } // for test public static Employee generateBoss(int maxLevel, int maxNexts, int maxHappy) { if (Math.random() < 0.05) { return null; } Employee boss = new Employee((int) (Math.random() * (maxHappy + 1))); generateNexts(boss, 1, maxLevel, maxNexts, maxHappy); return boss; } // for test public static void generateNexts(Employee boss, int level, int maxLevel, int maxNexts, int maxHappy) { if (level > maxLevel) { return; } int nextsSize = (int) (Math.random() * (maxNexts + 1)); for (int i = 0; i < nextsSize; i++) { Employee next = new Employee((int) (Math.random() * (maxHappy + 1))); boss.nexts.add(next); generateNexts(next, level + 1, maxLevel, maxNexts, maxHappy); } } // for test public static void main(String[] args) { int maxLevel = 5; int maxNexts = 5; int maxHappy = 100; int testTimes = 1000; for (int i = 0; i < testTimes; i++) { Employee boss = generateBoss(maxLevel, maxNexts, maxHappy); if (maxHappy1(boss) != maxHappy2(boss)){ System.out.println("Oops!"); } } System.out.println("finish!"); } }
0
1,149
9
1,250
12
1,281
8
1,250
12
1,649
18
false
false
false
false
false
true
56686_0
package com.meituan.duplicateimage.bean; import java.io.File; /** * 一个对象对应一个图片文件 */ public class ImageFile { public String name; public File mFile; public String mHash;//pHash算法生成的hash值 public float[] mHistogramData;// TODO xiayong 比较耗内存,是否有优化空间 采用分治之类? public int mHeight = -1; public int mWidth = -1; public ImageFile(final File file) { mFile = file; if (!mFile.exists()) { throw new IllegalArgumentException("input file does not exist,please check the path"); } name = mFile.getName(); } }
Chengdu-RD/DuplicateImages
src/com/meituan/duplicateimage/bean/ImageFile.java
168
/** * 一个对象对应一个图片文件 */
block_comment
zh-cn
package com.meituan.duplicateimage.bean; import java.io.File; /** * 一个对 <SUF>*/ public class ImageFile { public String name; public File mFile; public String mHash;//pHash算法生成的hash值 public float[] mHistogramData;// TODO xiayong 比较耗内存,是否有优化空间 采用分治之类? public int mHeight = -1; public int mWidth = -1; public ImageFile(final File file) { mFile = file; if (!mFile.exists()) { throw new IllegalArgumentException("input file does not exist,please check the path"); } name = mFile.getName(); } }
0
153
11
168
12
176
11
168
12
213
18
false
false
false
false
false
true
25869_0
import java.util.Scanner; public class ACM { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int N = 100010; // 假设数组大小最多为100010 int[] w = new int[N]; int n = scanner.nextInt(); // 读取数组大小 for (int i = 0; i < n; i++) { w[i] = scanner.nextInt(); // 读取n个整数 } long sum = 0; for (int i = 0; i < n; i++) { sum += w[i]; } System.out.println(sum); // 输出元素和k /* * import java.util.Scanner; * public class Main{ * public static void main(String args[]){ * Scanner sc = new Scanner(System.in); * int n = sc.nextInt(); * } * } */ }
Chennian-Zhao/JavaSE_Journey
ACM.java
226
// 假设数组大小最多为100010
line_comment
zh-cn
import java.util.Scanner; public class ACM { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int N = 100010; // 假设 <SUF> int[] w = new int[N]; int n = scanner.nextInt(); // 读取数组大小 for (int i = 0; i < n; i++) { w[i] = scanner.nextInt(); // 读取n个整数 } long sum = 0; for (int i = 0; i < n; i++) { sum += w[i]; } System.out.println(sum); // 输出元素和k /* * import java.util.Scanner; * public class Main{ * public static void main(String args[]){ * Scanner sc = new Scanner(System.in); * int n = sc.nextInt(); * } * } */ }
0
208
15
226
15
241
13
226
15
277
19
false
false
false
false
false
true
60134_6
package con; /** * 静态代码块 > 构造代码块 > 构造方法 */ public class CodeBlockTest { public static void main(String[] args) { // Window window3= new Window("window3"); // House house = new House(window3); System.out.println("数量是" + Window.getWindowCount()) ; } } class House{ //构造代码块 static Window window1; Window window2; Window window3; //静态代码块 static{ System.out.println("1c"); window1 = new Window("window1"); System.out.println(window1); } //构造代码块 { System.out.println("2c"); window2 = new Window("window2"); System.out.println(window2); } //方法 public House(){} public House(Window window3){ System.out.println("3c"); this.window3 = window3; System.out.println(window3); } } class Window{ private static int WindowCount; private String name; public void setname(String name){ this.name = name; } public String getname(){ return name; } //构造代码块 { WindowCount++; } public static int getWindowCount(){ return WindowCount; } public Window(){ } public Window(String name){ this.name = name; } /** * 重写toString方法 */ @Override public String toString(){ return "房屋窗户信息{"+ "窗户名称'" + name +'\''+'}'; } }
Chenpeel/Codes
Java/NT/src/inherit/con/CodeBlockTest.java
387
//构造代码块
line_comment
zh-cn
package con; /** * 静态代码块 > 构造代码块 > 构造方法 */ public class CodeBlockTest { public static void main(String[] args) { // Window window3= new Window("window3"); // House house = new House(window3); System.out.println("数量是" + Window.getWindowCount()) ; } } class House{ //构造代码块 static Window window1; Window window2; Window window3; //静态代码块 static{ System.out.println("1c"); window1 = new Window("window1"); System.out.println(window1); } //构造代码块 { System.out.println("2c"); window2 = new Window("window2"); System.out.println(window2); } //方法 public House(){} public House(Window window3){ System.out.println("3c"); this.window3 = window3; System.out.println(window3); } } class Window{ private static int WindowCount; private String name; public void setname(String name){ this.name = name; } public String getname(){ return name; } //构造 <SUF> { WindowCount++; } public static int getWindowCount(){ return WindowCount; } public Window(){ } public Window(String name){ this.name = name; } /** * 重写toString方法 */ @Override public String toString(){ return "房屋窗户信息{"+ "窗户名称'" + name +'\''+'}'; } }
0
355
4
387
4
433
4
387
4
505
8
false
false
false
false
false
true