file_id
stringlengths 5
9
| content
stringlengths 24
16.1k
| repo
stringlengths 8
84
| path
stringlengths 7
167
| token_length
int64 18
3.48k
| original_comment
stringlengths 5
2.57k
| comment_type
stringclasses 2
values | detected_lang
stringclasses 1
value | masked_comment
stringlengths 11
16.1k
| excluded
bool 1
class | file-tokens-Qwen/Qwen2-7B
int64 14
3.27k
| comment-tokens-Qwen/Qwen2-7B
int64 2
1.74k
| file-tokens-bigcode/starcoder2-7b
int64 18
3.48k
| comment-tokens-bigcode/starcoder2-7b
int64 2
2.11k
| file-tokens-google/codegemma-7b
int64 14
3.57k
| comment-tokens-google/codegemma-7b
int64 2
1.75k
| file-tokens-ibm-granite/granite-8b-code-base
int64 18
3.48k
| comment-tokens-ibm-granite/granite-8b-code-base
int64 2
2.11k
| file-tokens-meta-llama/CodeLlama-7b-hf
int64 31
3.93k
| comment-tokens-meta-llama/CodeLlama-7b-hf
int64 4
2.71k
| 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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
35134_5 | package com.zjh.db;
/**
* Created by ZhangJinghao on 2018/8/15.
*/
/**
* ContactInjfoDao 数据库操作类 dao后缀的都是数据库操作类
* <p>
* 我们这里的每一个 增删改查 的方法都通过getWritableDatabase()去实例化了一个数据库,这里必须这么做
* 不客气抽取 成为一个成员变量, 否则报错,若是觉得麻烦可以通过定义方法来置为null和重新赋值
* <p>
* —— 其实dao类在这里做得事情特别简单:
* 1、定义一个构造方法,利用这个方法去实例化一个 数据库帮助类
* 2、编写dao类的对应的 增删改查 方法。
*/
public class DBDao {
private MyDBHelper mMyDBHelper;
public static final String TABLE_PLAYER = "PlayerBean";
/**
* dao类需要实例化数据库Help类,只有得到帮助类的对象我们才可以实例化 SQLiteDatabase
*
* @param context
*/
public DBDao(Context context) {
mMyDBHelper = new MyDBHelper(context);
}
public long insertDate(PlayerBean playerBean) {
// 增删改查每一个方法都要得到数据库,然后操作完成后一定要关闭
// getWritableDatabase(); 执行后数据库文件才会生成
SQLiteDatabase sqLiteDatabase = mMyDBHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(PlayerBean.NAME, playerBean.name);
contentValues.put(PlayerBean.AGE, playerBean.age);
contentValues.put(PlayerBean.ISMALE, playerBean.isMale);
long rowid = sqLiteDatabase.insert(TABLE_PLAYER, null, contentValues);
sqLiteDatabase.close();
return rowid;
}
/**
* 删除的方法
*/
public int deleteDate(String name) {
SQLiteDatabase sqLiteDatabase = mMyDBHelper.getWritableDatabase();
int deleteResult = sqLiteDatabase.delete(TABLE_PLAYER, PlayerBean.NAME + "=?", new String[]{name});
sqLiteDatabase.close();
return deleteResult;
}
/**
* 修改的方法
*/
public int updateData(String name, String newAge) {
SQLiteDatabase sqLiteDatabase = mMyDBHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(PlayerBean.AGE, newAge);
int updateResult = sqLiteDatabase.update(TABLE_PLAYER, contentValues, PlayerBean.NAME + "=?", new String[]{name});
sqLiteDatabase.close();
return updateResult;
}
/**
* 查询的方法
*/
public PlayerBean[] selectData(String name) {
SQLiteDatabase readableDatabase = mMyDBHelper.getReadableDatabase();
// 查询比较特别,涉及到 cursor
Cursor cursor = readableDatabase.rawQuery("" +
"SELECT *\n" +
"FROM [player]\n" +
"WHERE [name] = ?;", new String[]{name});
PlayerBean[] playerInfos = new PlayerBean[cursor.getCount()];
if (cursor.moveToNext()) {
int _id = cursor.getInt(cursor.getColumnIndex(PlayerBean.ID));
String _name = cursor.getString(cursor.getColumnIndex(PlayerBean.NAME));
int _age = cursor.getInt(cursor.getColumnIndex(PlayerBean.AGE));
boolean _isMale = Boolean.valueOf(cursor.getString(cursor.getColumnIndex(PlayerBean.ISMALE)));
playerInfos[cursor.getPosition()] = new PlayerBean(_id, _name, _age, _isMale);
}
cursor.close(); // 记得关闭 corsor
readableDatabase.close(); // 关闭数据库
return playerInfos;
}
} | chinatragedy/GameDataBaseDemo | android/src/com/zjh/db/DBDao.java | 871 | /**
* 删除的方法
*/ | block_comment | zh-cn | package com.zjh.db;
/**
* Created by ZhangJinghao on 2018/8/15.
*/
/**
* ContactInjfoDao 数据库操作类 dao后缀的都是数据库操作类
* <p>
* 我们这里的每一个 增删改查 的方法都通过getWritableDatabase()去实例化了一个数据库,这里必须这么做
* 不客气抽取 成为一个成员变量, 否则报错,若是觉得麻烦可以通过定义方法来置为null和重新赋值
* <p>
* —— 其实dao类在这里做得事情特别简单:
* 1、定义一个构造方法,利用这个方法去实例化一个 数据库帮助类
* 2、编写dao类的对应的 增删改查 方法。
*/
public class DBDao {
private MyDBHelper mMyDBHelper;
public static final String TABLE_PLAYER = "PlayerBean";
/**
* dao类需要实例化数据库Help类,只有得到帮助类的对象我们才可以实例化 SQLiteDatabase
*
* @param context
*/
public DBDao(Context context) {
mMyDBHelper = new MyDBHelper(context);
}
public long insertDate(PlayerBean playerBean) {
// 增删改查每一个方法都要得到数据库,然后操作完成后一定要关闭
// getWritableDatabase(); 执行后数据库文件才会生成
SQLiteDatabase sqLiteDatabase = mMyDBHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(PlayerBean.NAME, playerBean.name);
contentValues.put(PlayerBean.AGE, playerBean.age);
contentValues.put(PlayerBean.ISMALE, playerBean.isMale);
long rowid = sqLiteDatabase.insert(TABLE_PLAYER, null, contentValues);
sqLiteDatabase.close();
return rowid;
}
/**
* 删除的 <SUF>*/
public int deleteDate(String name) {
SQLiteDatabase sqLiteDatabase = mMyDBHelper.getWritableDatabase();
int deleteResult = sqLiteDatabase.delete(TABLE_PLAYER, PlayerBean.NAME + "=?", new String[]{name});
sqLiteDatabase.close();
return deleteResult;
}
/**
* 修改的方法
*/
public int updateData(String name, String newAge) {
SQLiteDatabase sqLiteDatabase = mMyDBHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(PlayerBean.AGE, newAge);
int updateResult = sqLiteDatabase.update(TABLE_PLAYER, contentValues, PlayerBean.NAME + "=?", new String[]{name});
sqLiteDatabase.close();
return updateResult;
}
/**
* 查询的方法
*/
public PlayerBean[] selectData(String name) {
SQLiteDatabase readableDatabase = mMyDBHelper.getReadableDatabase();
// 查询比较特别,涉及到 cursor
Cursor cursor = readableDatabase.rawQuery("" +
"SELECT *\n" +
"FROM [player]\n" +
"WHERE [name] = ?;", new String[]{name});
PlayerBean[] playerInfos = new PlayerBean[cursor.getCount()];
if (cursor.moveToNext()) {
int _id = cursor.getInt(cursor.getColumnIndex(PlayerBean.ID));
String _name = cursor.getString(cursor.getColumnIndex(PlayerBean.NAME));
int _age = cursor.getInt(cursor.getColumnIndex(PlayerBean.AGE));
boolean _isMale = Boolean.valueOf(cursor.getString(cursor.getColumnIndex(PlayerBean.ISMALE)));
playerInfos[cursor.getPosition()] = new PlayerBean(_id, _name, _age, _isMale);
}
cursor.close(); // 记得关闭 corsor
readableDatabase.close(); // 关闭数据库
return playerInfos;
}
} | false | 758 | 8 | 871 | 7 | 872 | 9 | 871 | 7 | 1,165 | 13 | false | false | false | false | false | true |
57361_1 | package evaluate;
import org.nlpcn.commons.lang.util.ObjConver;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.nio.charset.Charset;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
import static evaluate.Test.readWordList;
import static evaluate.Test.test;
/**
* Created by wan on 4/25/2017.
*/
public class config {
final public static String sepSentenceRegex = "[,。?!:]";// 这样搞了之后就断不开了
final public static String sepWordRegex = " +";
final public static double thresholdMI = 10;
final public static double thresholdTF = 3;
final public static double thresholdNeighborEntropy = 1.5;
final public static Integer testSize = 5;
public static final String timeRegx =
"([\\p{IsDigit}-~:兆亿万千百十九八七六五四三二一零○]+" +
"((([年月日]|(世纪)|(年代))[前初中底末]?)|[号时分秒点]|(秒钟)|(点钟)|(月份)|(小时)))";
public static final String pureLetterStringRegex = "([\\p{IsLatin}\\p{IsCyrillic}]+)";
public static final String pureNumStringRegex = "(第?[兆亿万千百\\p{IsDigit},.%∶:/×-+·~]+)";
public static final String letterWithNumStringRegex = "([\\p{IsDigit}\\p{IsCyrillic}\\p{IsLatin}./-·~]+)";
final public static String punctuationStringRegex = "([ °~|■+±\\pP&&[^·-/]]+)";
final public static String newWordExcludeRegex = String.join("|"
, pureNumStringRegex
, pureLetterStringRegex
, timeRegx
, punctuationStringRegex);
public static final String pureChineseStringRegex = "([\\p{IsHan}]+)";
public static final String chineseJoinedStringRegex = "([\\p{IsHan}·-/]+)";
final public static String news = "data/raw/news.txt";
final public static String renmingribao = "data/raw/renminribao.txt";
public static String comment;//report.log里面的注释
public static String newWordRemove;
public static Integer levelNum = 8;
public static Integer maxStringLength = 8;
public static Boolean isShuffle = false;
public static Boolean isNewWordFilter = true;
public static Boolean isCRFsuite = false;//设置用crfsuite还是crf++
public static String algorithmInCRFSuite = "";//crfsuite里面用的算法
public static String newWordFile = "tmp/newword.DBC";
public static String testData = "data/test/test.txt";
public static String trainData = "data/test/train.txt";
public static String totalData = "data/test/total.txt";
public static Set<String> trainModelList = new HashSet<>();
public static Set<String> testModelList = new HashSet<>();
static {
Properties prop = new Properties();
try {
//读取属性文件
FileInputStream input = new FileInputStream(new File("config.properties"));
prop.load(new InputStreamReader(input, Charset.forName("UTF-8"))); ///加载属性列表
Iterator<String> it = prop.stringPropertyNames().iterator();
while (it.hasNext()) {
String key = it.next();
//train和的test哪些模型
if (key.equals("train")) {
String[] tmp = prop.getProperty(key).split(",");
for (String tmp0 : tmp) {
trainModelList.add(tmp0);
}
continue;
}
if (key.equals("test")) {
String[] tmp = prop.getProperty(key).split(",");
for (String tmp0 : tmp)
testModelList.add(tmp0);
continue;
}
Field field = config.class.getField(key);
field.set(null, ObjConver.conversion(prop.getProperty(key), field.getType()));
}
input.close();
} catch (Exception e) {
System.err.println(e);
}
String[] dirList = {
"info"
, "tmp"
, "tmp/crf"
, "data"
, "data/corpus"
, "data/corpus/wordlist"
, "data/model"
, "data/test"
, "data/test/input"
, "data/test/ans"};//初始化的时候要把这些文件夹建起来
for (String dir : dirList)
if (!new File(dir).exists()) {
new File(dir).mkdir();
}
}
public static String removePos(String in) {
return in.replaceAll("/[^/]*$", "");
}
public static String getPos(String in) {
return in.replaceAll("^.*/", "");
}
static public String newWordFileter(String word) {
if (isNewWordFilter)
return word.replaceAll(newWordRemove, "");
return word;
}
public static void main(String... args) {
for (String tmp : new String[]{"21", "20世纪末", "90年代", "5月", "四月中", "三点钟", "03:28"})
System.err.println(tmp + "\t " + tmp.matches(timeRegx));
for (Ner type : Ner.supported) {
test(
readWordList(config.getAnswerFile(config.trainData, type)),
readWordList(config.getAnswerFile(config.testData, type)),
type, "count", "count"
);
}
}
/**
* 确定这个串的类型
* @param word
* @return
*/
static public String category(String word) {
if (word.matches(pureLetterStringRegex))
return "letter";
if (word.matches(pureNumStringRegex))
return "num";
if (word.matches(letterWithNumStringRegex))
return "letter-num";
if (word.matches(pureChineseStringRegex))
return "chinese";
if (word.matches(chineseJoinedStringRegex))
return "chineseWithHyphen";
return "mix_string";
}
public static String getAnswerFile(String inputFile, Ner ner) {
return "data/test/ans/" + inputFile.replaceAll(".*/", "") + "." + ner.name;
}
public static String getInputFile(String inputFile) {
return "data/test/input/" + inputFile.replaceAll(".*/", "") + ".src";
}
public static String getWordListFile(String inputFile) {
return "data/corpus/wordlist/" + inputFile.replaceAll(".*/", "") + ".wordlist";
}
}
| chiyang10000/newWordDetection | src/main/java/evaluate/config.java | 1,784 | // 这样搞了之后就断不开了
| line_comment | zh-cn | package evaluate;
import org.nlpcn.commons.lang.util.ObjConver;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.nio.charset.Charset;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
import static evaluate.Test.readWordList;
import static evaluate.Test.test;
/**
* Created by wan on 4/25/2017.
*/
public class config {
final public static String sepSentenceRegex = "[,。?!:]";// 这样 <SUF>
final public static String sepWordRegex = " +";
final public static double thresholdMI = 10;
final public static double thresholdTF = 3;
final public static double thresholdNeighborEntropy = 1.5;
final public static Integer testSize = 5;
public static final String timeRegx =
"([\\p{IsDigit}-~:兆亿万千百十九八七六五四三二一零○]+" +
"((([年月日]|(世纪)|(年代))[前初中底末]?)|[号时分秒点]|(秒钟)|(点钟)|(月份)|(小时)))";
public static final String pureLetterStringRegex = "([\\p{IsLatin}\\p{IsCyrillic}]+)";
public static final String pureNumStringRegex = "(第?[兆亿万千百\\p{IsDigit},.%∶:/×-+·~]+)";
public static final String letterWithNumStringRegex = "([\\p{IsDigit}\\p{IsCyrillic}\\p{IsLatin}./-·~]+)";
final public static String punctuationStringRegex = "([ °~|■+±\\pP&&[^·-/]]+)";
final public static String newWordExcludeRegex = String.join("|"
, pureNumStringRegex
, pureLetterStringRegex
, timeRegx
, punctuationStringRegex);
public static final String pureChineseStringRegex = "([\\p{IsHan}]+)";
public static final String chineseJoinedStringRegex = "([\\p{IsHan}·-/]+)";
final public static String news = "data/raw/news.txt";
final public static String renmingribao = "data/raw/renminribao.txt";
public static String comment;//report.log里面的注释
public static String newWordRemove;
public static Integer levelNum = 8;
public static Integer maxStringLength = 8;
public static Boolean isShuffle = false;
public static Boolean isNewWordFilter = true;
public static Boolean isCRFsuite = false;//设置用crfsuite还是crf++
public static String algorithmInCRFSuite = "";//crfsuite里面用的算法
public static String newWordFile = "tmp/newword.DBC";
public static String testData = "data/test/test.txt";
public static String trainData = "data/test/train.txt";
public static String totalData = "data/test/total.txt";
public static Set<String> trainModelList = new HashSet<>();
public static Set<String> testModelList = new HashSet<>();
static {
Properties prop = new Properties();
try {
//读取属性文件
FileInputStream input = new FileInputStream(new File("config.properties"));
prop.load(new InputStreamReader(input, Charset.forName("UTF-8"))); ///加载属性列表
Iterator<String> it = prop.stringPropertyNames().iterator();
while (it.hasNext()) {
String key = it.next();
//train和的test哪些模型
if (key.equals("train")) {
String[] tmp = prop.getProperty(key).split(",");
for (String tmp0 : tmp) {
trainModelList.add(tmp0);
}
continue;
}
if (key.equals("test")) {
String[] tmp = prop.getProperty(key).split(",");
for (String tmp0 : tmp)
testModelList.add(tmp0);
continue;
}
Field field = config.class.getField(key);
field.set(null, ObjConver.conversion(prop.getProperty(key), field.getType()));
}
input.close();
} catch (Exception e) {
System.err.println(e);
}
String[] dirList = {
"info"
, "tmp"
, "tmp/crf"
, "data"
, "data/corpus"
, "data/corpus/wordlist"
, "data/model"
, "data/test"
, "data/test/input"
, "data/test/ans"};//初始化的时候要把这些文件夹建起来
for (String dir : dirList)
if (!new File(dir).exists()) {
new File(dir).mkdir();
}
}
public static String removePos(String in) {
return in.replaceAll("/[^/]*$", "");
}
public static String getPos(String in) {
return in.replaceAll("^.*/", "");
}
static public String newWordFileter(String word) {
if (isNewWordFilter)
return word.replaceAll(newWordRemove, "");
return word;
}
public static void main(String... args) {
for (String tmp : new String[]{"21", "20世纪末", "90年代", "5月", "四月中", "三点钟", "03:28"})
System.err.println(tmp + "\t " + tmp.matches(timeRegx));
for (Ner type : Ner.supported) {
test(
readWordList(config.getAnswerFile(config.trainData, type)),
readWordList(config.getAnswerFile(config.testData, type)),
type, "count", "count"
);
}
}
/**
* 确定这个串的类型
* @param word
* @return
*/
static public String category(String word) {
if (word.matches(pureLetterStringRegex))
return "letter";
if (word.matches(pureNumStringRegex))
return "num";
if (word.matches(letterWithNumStringRegex))
return "letter-num";
if (word.matches(pureChineseStringRegex))
return "chinese";
if (word.matches(chineseJoinedStringRegex))
return "chineseWithHyphen";
return "mix_string";
}
public static String getAnswerFile(String inputFile, Ner ner) {
return "data/test/ans/" + inputFile.replaceAll(".*/", "") + "." + ner.name;
}
public static String getInputFile(String inputFile) {
return "data/test/input/" + inputFile.replaceAll(".*/", "") + ".src";
}
public static String getWordListFile(String inputFile) {
return "data/corpus/wordlist/" + inputFile.replaceAll(".*/", "") + ".wordlist";
}
}
| false | 1,453 | 12 | 1,773 | 13 | 1,712 | 11 | 1,773 | 13 | 2,156 | 16 | false | false | false | false | false | true |
58935_0 | package com.example.refuseclassification;
import com.example.refuseclassification.Database.Knowledge;
import org.litepal.LitePal;
import java.util.List;
public class KnowledgeDatabase {
String[] name = {"菠萝", "鸭脖", "鸭脖子", "萝卜", "胡萝卜", "萝卜干", "草", "草莓",
"红肠", "香肠", "鱼肠", "过期食品", "剩菜剩饭", "死老鼠", "麦丽素", "果粒",
"巧克力", "芦荟", "落叶", "乳制品", "鲜肉月饼", "炸鸡腿", "药渣", "毛毛虫", "蜗牛",
"安全套", "按摩棒", "肮脏塑料袋", "旧扫把", "旧拖把", "搅拌棒", "棒骨", "蚌壳",
"保龄球", "爆竹", "纸杯", "扇贝", "鼻毛", "鼻屎", "笔", "冥币",
"尿不湿", "餐巾", "餐纸", "一次性叉子", "掉下来的牙齿", "丁字裤", "耳屎", "飞机杯", "碱性无汞电池",
"安全帽", "棉袄", "白纸", "手办", "包包", "保温杯", "报纸", "电脑设备",
"被单", "本子", "手表", "玻璃", "尺子", "充电宝", "充电器", "空调",
"耳机", "衣服", "乐高", "公仔", "可降解塑料", "酒瓶", "篮球", "红领巾", "泡沫箱",
"阿司匹林", "浴霸灯泡", "避孕药", "温度计", "杀毒剂", "感冒药", "药瓶", "止咳糖浆",
"胶囊", "灯泡", "农药", "油漆", "维生素", "酒精", "指甲油", "铅蓄电池",
"废电池", "打火机", "医用纱布", "医用棉签", "相片", "干电池", "钙片", "针管", "针筒"};
String[] kind = {"湿垃圾", "干垃圾", "可回收物", "有害垃圾"};
public void setKnowledgeDatabase() {
LitePal.getDatabase();
for (int i = 0; i < 100; i++) {
// 获取数据表数据,查询是否有相同数据,防止重复插入
List<Knowledge> knowledges = LitePal.where("id = ?", String.valueOf(i + 1))
.find(Knowledge.class);
if (knowledges == null || knowledges.size()== 0)
if (i < 25)
insert(i + 1, name[i], kind[0]);
else if (i < 50)
insert(i + 1, name[i], kind[1]);
else if (i < 75)
insert(i + 1, name[i], kind[2]);
else
insert(i + 1, name[i], kind[3]);
else
continue;
}
}
public void insert(int id, String name, String kind) {
Knowledge knowledge = new Knowledge();
knowledge.setId(id);
knowledge.setName(name);
knowledge.setKind(kind);
knowledge.save();
}
}
| chl-0537/RefuseClassification | app/src/main/java/com/example/refuseclassification/KnowledgeDatabase.java | 964 | // 获取数据表数据,查询是否有相同数据,防止重复插入 | line_comment | zh-cn | package com.example.refuseclassification;
import com.example.refuseclassification.Database.Knowledge;
import org.litepal.LitePal;
import java.util.List;
public class KnowledgeDatabase {
String[] name = {"菠萝", "鸭脖", "鸭脖子", "萝卜", "胡萝卜", "萝卜干", "草", "草莓",
"红肠", "香肠", "鱼肠", "过期食品", "剩菜剩饭", "死老鼠", "麦丽素", "果粒",
"巧克力", "芦荟", "落叶", "乳制品", "鲜肉月饼", "炸鸡腿", "药渣", "毛毛虫", "蜗牛",
"安全套", "按摩棒", "肮脏塑料袋", "旧扫把", "旧拖把", "搅拌棒", "棒骨", "蚌壳",
"保龄球", "爆竹", "纸杯", "扇贝", "鼻毛", "鼻屎", "笔", "冥币",
"尿不湿", "餐巾", "餐纸", "一次性叉子", "掉下来的牙齿", "丁字裤", "耳屎", "飞机杯", "碱性无汞电池",
"安全帽", "棉袄", "白纸", "手办", "包包", "保温杯", "报纸", "电脑设备",
"被单", "本子", "手表", "玻璃", "尺子", "充电宝", "充电器", "空调",
"耳机", "衣服", "乐高", "公仔", "可降解塑料", "酒瓶", "篮球", "红领巾", "泡沫箱",
"阿司匹林", "浴霸灯泡", "避孕药", "温度计", "杀毒剂", "感冒药", "药瓶", "止咳糖浆",
"胶囊", "灯泡", "农药", "油漆", "维生素", "酒精", "指甲油", "铅蓄电池",
"废电池", "打火机", "医用纱布", "医用棉签", "相片", "干电池", "钙片", "针管", "针筒"};
String[] kind = {"湿垃圾", "干垃圾", "可回收物", "有害垃圾"};
public void setKnowledgeDatabase() {
LitePal.getDatabase();
for (int i = 0; i < 100; i++) {
// 获取 <SUF>
List<Knowledge> knowledges = LitePal.where("id = ?", String.valueOf(i + 1))
.find(Knowledge.class);
if (knowledges == null || knowledges.size()== 0)
if (i < 25)
insert(i + 1, name[i], kind[0]);
else if (i < 50)
insert(i + 1, name[i], kind[1]);
else if (i < 75)
insert(i + 1, name[i], kind[2]);
else
insert(i + 1, name[i], kind[3]);
else
continue;
}
}
public void insert(int id, String name, String kind) {
Knowledge knowledge = new Knowledge();
knowledge.setId(id);
knowledge.setName(name);
knowledge.setKind(kind);
knowledge.save();
}
}
| false | 725 | 14 | 964 | 16 | 802 | 14 | 964 | 16 | 1,277 | 32 | false | false | false | false | false | true |
63629_2 | package sample;
import javafx.application.Platform;
import javafx.scene.input.KeyCode;
import javafx.scene.text.Text;
import java.util.List;
/**
* 游戏盘,精灵控制器
* @author HUPENG
*/
public class GameBoard {
/**
* 游戏过程监听器
* */
private GameListener gameListener;
/**
* 判断是否是服务器
* */
private boolean isServer;
/**
* 自己的精灵
* */
private CharacterSprite myCharacterSprite;
/**
* 对手的精灵
* */
private CharacterSprite opponentCharacterSprite;
/**
* 地图
* */
private Map map;
/**
* 食物精灵
* */
private FoodSprite foodSprite;
/**
* 文字精灵
* */
private TextSprite textSprite;
private boolean isMyCharacterSpriteStop = false;
private boolean isOpponentCharacterSpriteStop = false;
public GameBoard(GameListener gameListener, boolean isServer){
this.gameListener = gameListener;
this.isServer = isServer;
this.map = new Map(new MyMapListener());
if (isServer){
myCharacterSprite = new CharacterSprite(new MyCharacterListener(),2,2,40,40,true);
opponentCharacterSprite = new CharacterSprite(new OpponentCharacterListener(),10,2,40,40,false);
}else{
opponentCharacterSprite = new CharacterSprite(new OpponentCharacterListener(),2,2,40,40,false);
myCharacterSprite = new CharacterSprite(new MyCharacterListener(),10,2,40,40,true);
}
foodSprite = new FoodSprite(40,40);
textSprite = new TextSprite();
if (isServer){
provideFood(null);
}
gameListener.onMyCharacterSpriteCreated(myCharacterSprite);
gameListener.onOpponentCharacterSpriteCreated(opponentCharacterSprite);
gameListener.onFoodSpriteCreated(foodSprite);
gameListener.onTextSpriteCreated(textSprite);
}
public void addLocalKeyCode(KeyCode keyCode){
myCharacterSprite.addKeyCode(keyCode);
}
/**
* 移动对手的精灵
* */
public void moveOpponentCharacterSprite(KeyCode keyCode){
Platform.runLater(new Runnable() {
@Override
public void run() {
//更新JavaFX的主线程的代码放在此处
if(keyCode == KeyCode.LEFT){
opponentCharacterSprite.moveLeft();
}else if(keyCode == KeyCode.RIGHT){
opponentCharacterSprite.moveRight();
}else if(keyCode == KeyCode.UP){
opponentCharacterSprite.moveUp();
}else if(keyCode == KeyCode.DOWN){
opponentCharacterSprite.moveDown();
}
}
});
}
public void removeLocalKeyCode(KeyCode keyCode){
myCharacterSprite.removeKeyCode(keyCode);
}
/**
* 我的人物精灵的走动的回调的监听器
* */
class MyCharacterListener implements CharacterListener{
@Override
public void onMoveRequest(KeyCode keyCode) {
gameListener.onMyCharacterSpriteMoved(keyCode);
}
@Override
public void onMoved(List<Coord> list) {
map.addMyCharacterCoords(list);
}
@Override
public void onBombRequest(int x, int y, boolean isMyCharacterSprite) {
}
}
/**
* 对手的精灵的回调
* */
class OpponentCharacterListener implements CharacterListener{
@Override
public void onMoveRequest(KeyCode keyCode) {
}
@Override
public void onMoved(List<Coord> list) {
map.addOpponentCharacterCoords(list);
}
@Override
public void onBombRequest(int x, int y, boolean isMyCharacterSprite) {
}
}
/**
* 地图回调
* */
class MyMapListener implements MapListener{
@Override
public void onMyDied() {
if (!isMyCharacterSpriteStop){
textSprite.add("我方死亡,我方得分:" + myCharacterSprite.getScore());
myCharacterSprite.stop();
isMyCharacterSpriteStop = true;
if (isOpponentCharacterSpriteStop){
gameOver();
}
}
}
@Override
public void onOpponentDied() {
if (!isOpponentCharacterSpriteStop){
textSprite.add("对方死亡,对方得分:" + opponentCharacterSprite.getScore());
opponentCharacterSprite.stop();
isOpponentCharacterSpriteStop = true;
if (isMyCharacterSpriteStop){
gameOver();
}
}
}
@Override
public void onBothDied() {
if (!isMyCharacterSpriteStop || !isMyCharacterSpriteStop){
opponentCharacterSprite.stop();
myCharacterSprite.stop();
isMyCharacterSpriteStop = true;
isOpponentCharacterSpriteStop = true;
gameOver();
}
}
@Override
public void onMyAteFood(Coord coord) {
// System.out.println("我方吃");
myCharacterSprite.addScore(1);
myCharacterSprite.addSpeed();
myCharacterSprite.addLength(coord);
foodSprite.removeFood(coord);
if (isServer){
provideFood(null);
}
}
@Override
public void onOpponentAteFood(Coord coord) {
// System.out.println("对方吃");
opponentCharacterSprite.addScore(1);
// opponentCharacterSprite.addSpeed();
opponentCharacterSprite.addLength(coord);
foodSprite.removeFood(coord);
if (isServer){
provideFood(null);
}
}
}
/**
* 提供食物
* */
public void provideFood(Coord coord){
if (coord == null){
coord = map.getFreeCoord();
}
map.addFood(coord.x,coord.y);
foodSprite.addFood(coord);
if (isServer){
gameListener.onFoodAdd(coord);
}
}
/**
* 游戏结束
* */
private void gameOver(){
textSprite.add("游戏结束,我方得分:" + myCharacterSprite.getScore()+",对方得分:" + opponentCharacterSprite.getScore());
}
}
| chmod740/TanChiShe | src/sample/GameBoard.java | 1,446 | /**
* 判断是否是服务器
* */ | block_comment | zh-cn | package sample;
import javafx.application.Platform;
import javafx.scene.input.KeyCode;
import javafx.scene.text.Text;
import java.util.List;
/**
* 游戏盘,精灵控制器
* @author HUPENG
*/
public class GameBoard {
/**
* 游戏过程监听器
* */
private GameListener gameListener;
/**
* 判断是 <SUF>*/
private boolean isServer;
/**
* 自己的精灵
* */
private CharacterSprite myCharacterSprite;
/**
* 对手的精灵
* */
private CharacterSprite opponentCharacterSprite;
/**
* 地图
* */
private Map map;
/**
* 食物精灵
* */
private FoodSprite foodSprite;
/**
* 文字精灵
* */
private TextSprite textSprite;
private boolean isMyCharacterSpriteStop = false;
private boolean isOpponentCharacterSpriteStop = false;
public GameBoard(GameListener gameListener, boolean isServer){
this.gameListener = gameListener;
this.isServer = isServer;
this.map = new Map(new MyMapListener());
if (isServer){
myCharacterSprite = new CharacterSprite(new MyCharacterListener(),2,2,40,40,true);
opponentCharacterSprite = new CharacterSprite(new OpponentCharacterListener(),10,2,40,40,false);
}else{
opponentCharacterSprite = new CharacterSprite(new OpponentCharacterListener(),2,2,40,40,false);
myCharacterSprite = new CharacterSprite(new MyCharacterListener(),10,2,40,40,true);
}
foodSprite = new FoodSprite(40,40);
textSprite = new TextSprite();
if (isServer){
provideFood(null);
}
gameListener.onMyCharacterSpriteCreated(myCharacterSprite);
gameListener.onOpponentCharacterSpriteCreated(opponentCharacterSprite);
gameListener.onFoodSpriteCreated(foodSprite);
gameListener.onTextSpriteCreated(textSprite);
}
public void addLocalKeyCode(KeyCode keyCode){
myCharacterSprite.addKeyCode(keyCode);
}
/**
* 移动对手的精灵
* */
public void moveOpponentCharacterSprite(KeyCode keyCode){
Platform.runLater(new Runnable() {
@Override
public void run() {
//更新JavaFX的主线程的代码放在此处
if(keyCode == KeyCode.LEFT){
opponentCharacterSprite.moveLeft();
}else if(keyCode == KeyCode.RIGHT){
opponentCharacterSprite.moveRight();
}else if(keyCode == KeyCode.UP){
opponentCharacterSprite.moveUp();
}else if(keyCode == KeyCode.DOWN){
opponentCharacterSprite.moveDown();
}
}
});
}
public void removeLocalKeyCode(KeyCode keyCode){
myCharacterSprite.removeKeyCode(keyCode);
}
/**
* 我的人物精灵的走动的回调的监听器
* */
class MyCharacterListener implements CharacterListener{
@Override
public void onMoveRequest(KeyCode keyCode) {
gameListener.onMyCharacterSpriteMoved(keyCode);
}
@Override
public void onMoved(List<Coord> list) {
map.addMyCharacterCoords(list);
}
@Override
public void onBombRequest(int x, int y, boolean isMyCharacterSprite) {
}
}
/**
* 对手的精灵的回调
* */
class OpponentCharacterListener implements CharacterListener{
@Override
public void onMoveRequest(KeyCode keyCode) {
}
@Override
public void onMoved(List<Coord> list) {
map.addOpponentCharacterCoords(list);
}
@Override
public void onBombRequest(int x, int y, boolean isMyCharacterSprite) {
}
}
/**
* 地图回调
* */
class MyMapListener implements MapListener{
@Override
public void onMyDied() {
if (!isMyCharacterSpriteStop){
textSprite.add("我方死亡,我方得分:" + myCharacterSprite.getScore());
myCharacterSprite.stop();
isMyCharacterSpriteStop = true;
if (isOpponentCharacterSpriteStop){
gameOver();
}
}
}
@Override
public void onOpponentDied() {
if (!isOpponentCharacterSpriteStop){
textSprite.add("对方死亡,对方得分:" + opponentCharacterSprite.getScore());
opponentCharacterSprite.stop();
isOpponentCharacterSpriteStop = true;
if (isMyCharacterSpriteStop){
gameOver();
}
}
}
@Override
public void onBothDied() {
if (!isMyCharacterSpriteStop || !isMyCharacterSpriteStop){
opponentCharacterSprite.stop();
myCharacterSprite.stop();
isMyCharacterSpriteStop = true;
isOpponentCharacterSpriteStop = true;
gameOver();
}
}
@Override
public void onMyAteFood(Coord coord) {
// System.out.println("我方吃");
myCharacterSprite.addScore(1);
myCharacterSprite.addSpeed();
myCharacterSprite.addLength(coord);
foodSprite.removeFood(coord);
if (isServer){
provideFood(null);
}
}
@Override
public void onOpponentAteFood(Coord coord) {
// System.out.println("对方吃");
opponentCharacterSprite.addScore(1);
// opponentCharacterSprite.addSpeed();
opponentCharacterSprite.addLength(coord);
foodSprite.removeFood(coord);
if (isServer){
provideFood(null);
}
}
}
/**
* 提供食物
* */
public void provideFood(Coord coord){
if (coord == null){
coord = map.getFreeCoord();
}
map.addFood(coord.x,coord.y);
foodSprite.addFood(coord);
if (isServer){
gameListener.onFoodAdd(coord);
}
}
/**
* 游戏结束
* */
private void gameOver(){
textSprite.add("游戏结束,我方得分:" + myCharacterSprite.getScore()+",对方得分:" + opponentCharacterSprite.getScore());
}
}
| false | 1,325 | 12 | 1,446 | 10 | 1,544 | 11 | 1,446 | 10 | 2,021 | 17 | false | false | false | false | false | true |
63791_38 | package com.ahua.leetcode.problems;
import java.util.*;
/**
* @author huajun
* @create 2021-12-14 18:00
*/
/**
* 1462. 课程表 IV
* 你总共需要上 n 门课,课程编号依次为 0 到 n-1 。
* <p>
* 有的课会有直接的先修课程,比如如果想上课程 0 ,你必须先上课程 1 ,那么会以 [1,0] 数对的形式给出先修课程数对。
* <p>
* 给你课程总数 n 和一个直接先修课程数对列表 prerequisite 和一个查询对列表 queries。
* <p>
* 对于每个查询对 queries[i],请判断 queries[i][0] 是否是 queries[i][1] 的先修课程。
* <p>
* 请返回一个布尔值列表,列表中每个元素依次分别对应 queries 每个查询对的判断结果。
* <p>
* 注意:如果课程 a 是课程 b 的先修课程且课程 b 是课程 c 的先修课程,那么课程 a 也是课程 c 的先修课程。
* <p>
* 2 <= n <= 100
* 0 <= prerequisite.length <= (n * (n - 1) / 2)
* 0 <= prerequisite[i][0], prerequisite[i][1] < n
* prerequisite[i][0] != prerequisite[i][1]
* 先修课程图中没有环。
* 先修课程图中没有重复的边。
* 1 <= queries.length <= 10^4
* queries[i][0] != queries[i][1]
*/
public class P1462_CheckIfPrerequisite {
public static void main(String[] args) {
int[][] prerequisites = new int[][]{{1, 0}};
int[][] queries = new int[][]{{0, 1}, {1, 0}};
int[][] prerequisites1 = new int[][]{};
int[][] queries1 = new int[][]{{1, 0}, {0, 1}};
int[][] prerequisites2 = new int[][]{{1, 2}, {1, 0}, {2, 0}};
int[][] queries2 = new int[][]{{1, 0}, {1, 2}};
int[][] prerequisites3 = new int[][]{{1, 0}, {2, 0}};
int[][] queries3 = new int[][]{{0, 1}, {2, 0}};
int[][] prerequisites4 = new int[][]{{0, 1}, {1, 2}, {2, 3}, {3, 4}};
int[][] queries4 = new int[][]{{0, 4}, {4, 0}, {1, 3}, {3, 0}};
P1462_Solution solution = new P1462_Solution();
// [false, true] 课程 0 不是课程 1 的先修课程, 但课程 1 是课程 0 的先修课程
System.out.println(solution.checkIfPrerequisite(2, prerequisites, queries));
// [false, false] 没有先修课程对, 所以每门课程之间是独立的
System.out.println(solution.checkIfPrerequisite(2, prerequisites1, queries1));
// [true, true]
System.out.println(solution.checkIfPrerequisite(3, prerequisites2, queries2));
// [false, true]
System.out.println(solution.checkIfPrerequisite(3, prerequisites3, queries3));
// [true, false, true, false]
System.out.println(solution.checkIfPrerequisite(5, prerequisites4, queries4));
}
}
// 深度优先搜索(递归实现)
// 过程代码, 可删
class P1462_Solution1 {
// 答案链表
List<Boolean> ans;
// 邻接表构造有向图
P1462_CourseNode[] adjList;
// 记忆化是否可达, 1 代表可达, -1 代表不可达, 初始默认值为 0
int[][] isReachable;
// 记录之前的路径, 遍历中记忆化所有的到达情况
Deque<Integer> path;
public List<Boolean> checkIfPrerequisite(int numCourses, int[][] prerequisites, int[][] queries) {
// 答案链表
ans = new ArrayList<>(numCourses);
// 邻接表构造有向图
adjList = new P1462_CourseNode[numCourses];
// 记忆化是否可达
isReachable = new int[numCourses][numCourses];
path = new LinkedList<>();
// 构建邻接表
int from, to;
for (int[] edge : prerequisites) {
from = edge[0];
to = edge[1];
// 记忆可达到
isReachable[from][to] = 1;
isReachable[to][from] = -1;
// 将该边添加进邻接表 adjList
// 采用头插法构造图, 与注释的三行等价
adjList[from] = new P1462_CourseNode(to, adjList[from]);
/*
P1462_CourseNode toNode = new P1462_CourseNode(to);
toNode.next = adjList[from];
adjList[from] = toNode;
*/
}
// DFS
for (int[] query : queries) {
from = query[0];
to = query[1];
if (isReachable[from][to] == 1) {
ans.add(true);
continue;
}
if (dfs(from, to)) {
isReachable[from][to] = 1;
isReachable[to][from] = -1;
}
ans.add(isReachable[from][to] == 1);
}
return ans;
}
private boolean dfs(int from, int to) {
if (from == to) {
return true;
}
if (isReachable[from][to] == 1) {
return true;
}
if (isReachable[from][to] == -1) {
return false;
}
P1462_CourseNode next = adjList[from];
path.offerLast(from);
while (next != null) {
// // 不应该在这里判断, 应该在循环外进行边界条件的判断
// if (isReachable[next.value][to] == 1) {
// path.removeLast();
// return true;
// }
// // 添加下面这一段是错误的
// if (isReachable[next.value][to] == -1) {
// path.removeLast();
// return false;
// }
if (dfs(next.value, to)) {
isReachable[next.value][to] = 1;
isReachable[to][next.value] = -1;
path.removeLast();
return true;
}
// 本打算使用此 path 来记录遍历过的节点之间互相是否可达, 可是如此的话就会增加很多循环遍历 path
// 反而导致了效率更加低下
// 但是如果将 path 定义出来, 不执行以下这三行, 其它的保留, 反而比不定义 path 的空间消耗更低? 这让我感到很不可思议
for (Integer pre : path) {
isReachable[pre][next.value] = 1;
}
next = next.next;
}
path.removeLast();
isReachable[from][to] = -1;
return false;
}
}
// 深度优先搜索(递归实现)
class P1462_Solution {
// 答案链表
List<Boolean> ans;
// 邻接表构造有向图
P1462_CourseNode[] adjList;
// 记忆化是否可达, 1 代表可达, -1 代表不可达, 初始默认值为 0
// 定义为 byte、short、int 貌似差别也并不大
// 最开始定义为 boolean类型, 但是参考了他人的代码, 发现超时不能通过全部案例
int[][] isReachable;
public List<Boolean> checkIfPrerequisite(int numCourses, int[][] prerequisites, int[][] queries) {
// 答案链表
ans = new ArrayList<>(numCourses);
// 邻接表构造有向图
adjList = new P1462_CourseNode[numCourses];
// 记忆化是否可达
isReachable = new int[numCourses][numCourses];
// 构建邻接表
int from, to;
for (int[] edge : prerequisites) {
from = edge[0];
to = edge[1];
// 记忆可达到
isReachable[from][to] = 1;
isReachable[to][from] = -1;
// 将该边添加进邻接表 adjList
// 采用头插法构造图, 与注释的三行等价
adjList[from] = new P1462_CourseNode(to, adjList[from]);
/*
P1462_CourseNode toNode = new P1462_CourseNode(to);
toNode.next = adjList[from];
adjList[from] = toNode;
*/
}
// DFS
for (int[] query : queries) {
from = query[0];
to = query[1];
if (dfs(from, to)) {
isReachable[from][to] = 1;
isReachable[to][from] = -1;
}
ans.add(isReachable[from][to] == 1);
}
return ans;
}
private boolean dfs(int from, int to) {
if (from == to) {
return true;
}
if (isReachable[from][to] == 1) {
return true;
}
if (isReachable[from][to] == -1) {
return false;
}
// 有向边的起点 from -> 终点 next
P1462_CourseNode next = adjList[from];
while (next != null) {
if (dfs(next.value, to)) {
isReachable[next.value][to] = 1;
isReachable[to][next.value] = -1;
return true;
}
next = next.next;
}
isReachable[from][to] = -1;
return false;
}
}
class P1462_CourseNode {
// value 为课程编号
int value;
P1462_CourseNode next;
public P1462_CourseNode(int value) {
this.value = value;
}
public P1462_CourseNode(int value, P1462_CourseNode next) {
this.value = value;
this.next = next;
}
}
// 弗洛伊德(Floyd)算法
// 效率不及 DFS
class P1462_Solution2 {
public List<Boolean> checkIfPrerequisite(int numCourses, int[][] prerequisites, int[][] queries) {
// 记忆化是否可达
boolean[][] isReachable = new boolean[numCourses][numCourses];
for (int[] edge : prerequisites) {
isReachable[edge[0]][edge[1]] = true;
}
// 中转点
for (int k = 0; k < numCourses; k++) {
// 起点
for (int i = 0; i < numCourses; i++) {
// 终点
for (int j = 0; j < numCourses; j++) {
// // 如果可达不执行任何操作, 如果不可达则判断通过中转点 k 是否可达
// if (!isReachable[i][j]) {
// isReachable[i][j] = isReachable[i][k] && isReachable[k][j];
// }
// 与上等价
isReachable[i][j] = isReachable[i][j] || (isReachable[i][k] && isReachable[k][j]);
}
}
}
// 答案链表
List<Boolean> ans = new ArrayList<>();
for (int[] query : queries) {
ans.add(isReachable[query[0]][query[1]]);
}
return ans;
}
} | chnahua/DataStructureAndAlgorithm | src/main/java/com/ahua/leetcode/problems/P1462_CheckIfPrerequisite.java | 3,007 | // 最开始定义为 boolean类型, 但是参考了他人的代码, 发现超时不能通过全部案例 | line_comment | zh-cn | package com.ahua.leetcode.problems;
import java.util.*;
/**
* @author huajun
* @create 2021-12-14 18:00
*/
/**
* 1462. 课程表 IV
* 你总共需要上 n 门课,课程编号依次为 0 到 n-1 。
* <p>
* 有的课会有直接的先修课程,比如如果想上课程 0 ,你必须先上课程 1 ,那么会以 [1,0] 数对的形式给出先修课程数对。
* <p>
* 给你课程总数 n 和一个直接先修课程数对列表 prerequisite 和一个查询对列表 queries。
* <p>
* 对于每个查询对 queries[i],请判断 queries[i][0] 是否是 queries[i][1] 的先修课程。
* <p>
* 请返回一个布尔值列表,列表中每个元素依次分别对应 queries 每个查询对的判断结果。
* <p>
* 注意:如果课程 a 是课程 b 的先修课程且课程 b 是课程 c 的先修课程,那么课程 a 也是课程 c 的先修课程。
* <p>
* 2 <= n <= 100
* 0 <= prerequisite.length <= (n * (n - 1) / 2)
* 0 <= prerequisite[i][0], prerequisite[i][1] < n
* prerequisite[i][0] != prerequisite[i][1]
* 先修课程图中没有环。
* 先修课程图中没有重复的边。
* 1 <= queries.length <= 10^4
* queries[i][0] != queries[i][1]
*/
public class P1462_CheckIfPrerequisite {
public static void main(String[] args) {
int[][] prerequisites = new int[][]{{1, 0}};
int[][] queries = new int[][]{{0, 1}, {1, 0}};
int[][] prerequisites1 = new int[][]{};
int[][] queries1 = new int[][]{{1, 0}, {0, 1}};
int[][] prerequisites2 = new int[][]{{1, 2}, {1, 0}, {2, 0}};
int[][] queries2 = new int[][]{{1, 0}, {1, 2}};
int[][] prerequisites3 = new int[][]{{1, 0}, {2, 0}};
int[][] queries3 = new int[][]{{0, 1}, {2, 0}};
int[][] prerequisites4 = new int[][]{{0, 1}, {1, 2}, {2, 3}, {3, 4}};
int[][] queries4 = new int[][]{{0, 4}, {4, 0}, {1, 3}, {3, 0}};
P1462_Solution solution = new P1462_Solution();
// [false, true] 课程 0 不是课程 1 的先修课程, 但课程 1 是课程 0 的先修课程
System.out.println(solution.checkIfPrerequisite(2, prerequisites, queries));
// [false, false] 没有先修课程对, 所以每门课程之间是独立的
System.out.println(solution.checkIfPrerequisite(2, prerequisites1, queries1));
// [true, true]
System.out.println(solution.checkIfPrerequisite(3, prerequisites2, queries2));
// [false, true]
System.out.println(solution.checkIfPrerequisite(3, prerequisites3, queries3));
// [true, false, true, false]
System.out.println(solution.checkIfPrerequisite(5, prerequisites4, queries4));
}
}
// 深度优先搜索(递归实现)
// 过程代码, 可删
class P1462_Solution1 {
// 答案链表
List<Boolean> ans;
// 邻接表构造有向图
P1462_CourseNode[] adjList;
// 记忆化是否可达, 1 代表可达, -1 代表不可达, 初始默认值为 0
int[][] isReachable;
// 记录之前的路径, 遍历中记忆化所有的到达情况
Deque<Integer> path;
public List<Boolean> checkIfPrerequisite(int numCourses, int[][] prerequisites, int[][] queries) {
// 答案链表
ans = new ArrayList<>(numCourses);
// 邻接表构造有向图
adjList = new P1462_CourseNode[numCourses];
// 记忆化是否可达
isReachable = new int[numCourses][numCourses];
path = new LinkedList<>();
// 构建邻接表
int from, to;
for (int[] edge : prerequisites) {
from = edge[0];
to = edge[1];
// 记忆可达到
isReachable[from][to] = 1;
isReachable[to][from] = -1;
// 将该边添加进邻接表 adjList
// 采用头插法构造图, 与注释的三行等价
adjList[from] = new P1462_CourseNode(to, adjList[from]);
/*
P1462_CourseNode toNode = new P1462_CourseNode(to);
toNode.next = adjList[from];
adjList[from] = toNode;
*/
}
// DFS
for (int[] query : queries) {
from = query[0];
to = query[1];
if (isReachable[from][to] == 1) {
ans.add(true);
continue;
}
if (dfs(from, to)) {
isReachable[from][to] = 1;
isReachable[to][from] = -1;
}
ans.add(isReachable[from][to] == 1);
}
return ans;
}
private boolean dfs(int from, int to) {
if (from == to) {
return true;
}
if (isReachable[from][to] == 1) {
return true;
}
if (isReachable[from][to] == -1) {
return false;
}
P1462_CourseNode next = adjList[from];
path.offerLast(from);
while (next != null) {
// // 不应该在这里判断, 应该在循环外进行边界条件的判断
// if (isReachable[next.value][to] == 1) {
// path.removeLast();
// return true;
// }
// // 添加下面这一段是错误的
// if (isReachable[next.value][to] == -1) {
// path.removeLast();
// return false;
// }
if (dfs(next.value, to)) {
isReachable[next.value][to] = 1;
isReachable[to][next.value] = -1;
path.removeLast();
return true;
}
// 本打算使用此 path 来记录遍历过的节点之间互相是否可达, 可是如此的话就会增加很多循环遍历 path
// 反而导致了效率更加低下
// 但是如果将 path 定义出来, 不执行以下这三行, 其它的保留, 反而比不定义 path 的空间消耗更低? 这让我感到很不可思议
for (Integer pre : path) {
isReachable[pre][next.value] = 1;
}
next = next.next;
}
path.removeLast();
isReachable[from][to] = -1;
return false;
}
}
// 深度优先搜索(递归实现)
class P1462_Solution {
// 答案链表
List<Boolean> ans;
// 邻接表构造有向图
P1462_CourseNode[] adjList;
// 记忆化是否可达, 1 代表可达, -1 代表不可达, 初始默认值为 0
// 定义为 byte、short、int 貌似差别也并不大
// 最开 <SUF>
int[][] isReachable;
public List<Boolean> checkIfPrerequisite(int numCourses, int[][] prerequisites, int[][] queries) {
// 答案链表
ans = new ArrayList<>(numCourses);
// 邻接表构造有向图
adjList = new P1462_CourseNode[numCourses];
// 记忆化是否可达
isReachable = new int[numCourses][numCourses];
// 构建邻接表
int from, to;
for (int[] edge : prerequisites) {
from = edge[0];
to = edge[1];
// 记忆可达到
isReachable[from][to] = 1;
isReachable[to][from] = -1;
// 将该边添加进邻接表 adjList
// 采用头插法构造图, 与注释的三行等价
adjList[from] = new P1462_CourseNode(to, adjList[from]);
/*
P1462_CourseNode toNode = new P1462_CourseNode(to);
toNode.next = adjList[from];
adjList[from] = toNode;
*/
}
// DFS
for (int[] query : queries) {
from = query[0];
to = query[1];
if (dfs(from, to)) {
isReachable[from][to] = 1;
isReachable[to][from] = -1;
}
ans.add(isReachable[from][to] == 1);
}
return ans;
}
private boolean dfs(int from, int to) {
if (from == to) {
return true;
}
if (isReachable[from][to] == 1) {
return true;
}
if (isReachable[from][to] == -1) {
return false;
}
// 有向边的起点 from -> 终点 next
P1462_CourseNode next = adjList[from];
while (next != null) {
if (dfs(next.value, to)) {
isReachable[next.value][to] = 1;
isReachable[to][next.value] = -1;
return true;
}
next = next.next;
}
isReachable[from][to] = -1;
return false;
}
}
class P1462_CourseNode {
// value 为课程编号
int value;
P1462_CourseNode next;
public P1462_CourseNode(int value) {
this.value = value;
}
public P1462_CourseNode(int value, P1462_CourseNode next) {
this.value = value;
this.next = next;
}
}
// 弗洛伊德(Floyd)算法
// 效率不及 DFS
class P1462_Solution2 {
public List<Boolean> checkIfPrerequisite(int numCourses, int[][] prerequisites, int[][] queries) {
// 记忆化是否可达
boolean[][] isReachable = new boolean[numCourses][numCourses];
for (int[] edge : prerequisites) {
isReachable[edge[0]][edge[1]] = true;
}
// 中转点
for (int k = 0; k < numCourses; k++) {
// 起点
for (int i = 0; i < numCourses; i++) {
// 终点
for (int j = 0; j < numCourses; j++) {
// // 如果可达不执行任何操作, 如果不可达则判断通过中转点 k 是否可达
// if (!isReachable[i][j]) {
// isReachable[i][j] = isReachable[i][k] && isReachable[k][j];
// }
// 与上等价
isReachable[i][j] = isReachable[i][j] || (isReachable[i][k] && isReachable[k][j]);
}
}
}
// 答案链表
List<Boolean> ans = new ArrayList<>();
for (int[] query : queries) {
ans.add(isReachable[query[0]][query[1]]);
}
return ans;
}
} | false | 2,804 | 24 | 3,007 | 25 | 3,047 | 21 | 3,007 | 25 | 3,891 | 43 | false | false | false | false | false | true |
24397_1 | package com.hlx.leetcode.day2;
import java.util.HashMap;
import java.util.Map;
/**
* @author Huang Lexin
* @date 2022年02月22日 20:54
*/
public class SwordsmanOfferII005 {
class Solution {
public int maxProduct(String[] words) {
Map<Integer, Integer> map = new HashMap<>();
for (String word : words) {
int stringBitPattern = 0;
for (char c : word.toCharArray()) {
// 每种字符对应于一个位
stringBitPattern |= (1 << (c - 'a'));
}
Integer lastLen = map.getOrDefault(stringBitPattern, 0);
map.put(stringBitPattern, Math.max(lastLen, word.length()));
}
int ans = 0;
for (Map.Entry<Integer, Integer> entry1 : map.entrySet()) {
for (Map.Entry<Integer, Integer> entry2 : map.entrySet()) {
// 当两个字符串之间没有相同的字符的时候, 就说明这两个字符串的相同位撒花姑娘, 一个位为1, 另一个位为0
if ((entry1.getKey() & entry2.getKey()) == 0) {
ans = Math.max(ans, entry1.getValue()*entry2.getValue());
}
}
}
return ans;
}
}
}
| chong-chonga/LeetCode-SwordPointOfferII | src/main/java/com/hlx/leetcode/day2/SwordsmanOfferII005.java | 361 | // 每种字符对应于一个位 | line_comment | zh-cn | package com.hlx.leetcode.day2;
import java.util.HashMap;
import java.util.Map;
/**
* @author Huang Lexin
* @date 2022年02月22日 20:54
*/
public class SwordsmanOfferII005 {
class Solution {
public int maxProduct(String[] words) {
Map<Integer, Integer> map = new HashMap<>();
for (String word : words) {
int stringBitPattern = 0;
for (char c : word.toCharArray()) {
// 每种 <SUF>
stringBitPattern |= (1 << (c - 'a'));
}
Integer lastLen = map.getOrDefault(stringBitPattern, 0);
map.put(stringBitPattern, Math.max(lastLen, word.length()));
}
int ans = 0;
for (Map.Entry<Integer, Integer> entry1 : map.entrySet()) {
for (Map.Entry<Integer, Integer> entry2 : map.entrySet()) {
// 当两个字符串之间没有相同的字符的时候, 就说明这两个字符串的相同位撒花姑娘, 一个位为1, 另一个位为0
if ((entry1.getKey() & entry2.getKey()) == 0) {
ans = Math.max(ans, entry1.getValue()*entry2.getValue());
}
}
}
return ans;
}
}
}
| false | 302 | 10 | 361 | 8 | 347 | 8 | 361 | 8 | 463 | 12 | false | false | false | false | false | true |
62849_8 | package process.utils;
import java.util.HashSet;
public class StringUtil {
//格式化节目名
public static String formatVideoName(String videoName) {
//转换小写
videoName = videoName.toLowerCase().trim();
//中文括号转英文
videoName = videoName.replaceAll("(", "(");
videoName = videoName.replaceAll(")", ")");
//删除停用词字串(有前后顺序)
String[] stopWords = {
"版", "(美) ", "(台) ", "(港) ", "(港 / 台)", "(台 / 港)", "(日本) ",
"(精选) ", "(1080p 4m 新)", "(中文)", "(美版)", "4k", "1080p", "杜比",
"蓝光", "4m", "新4m", "4.5m", "高清", "限时免费", "限时特供", "限免",
"豆友译名", "1元看大片", "原声", "英语", "未删减", "国语", "英文", "中文",
"日文", "粤语", "tv", "国际", "抢先", "完整", "原声", "合集一", "合集二",
"合集三", "合集四", "合集五", "合集", "精切", "方言", "片段1", "片段2",
"片段3", "精选", "花絮", "片段", "泰语", "选段", "普通话", "会员", "日语"};
for (String stopword : stopWords) {
if (videoName.contains(stopword)) {
videoName = videoName.replaceAll(stopword, "");
}
}
//去除分隔符
videoName = videoName.replaceAll("[\\pZ]", "");
//去除标点字符
videoName = videoName.replaceAll("[\\pP]", "");
//去除符号如数学、货币符号
videoName = videoName.replaceAll("[\\pS]", "");
videoName = videoName
.replaceAll(" ", "")
.replaceAll("\t", "")
.replaceAll("\n", "")
.replaceAll("\r", "");
return videoName.trim();
}
//拆分以“|”分隔的字符串为Set
public static HashSet<String> splitToSet(String input) {
//拆分为数组
String[] sarr = input.split("\\|");
//转换为set
HashSet<String> results = new HashSet<>();
for (String str : sarr) {
String substr = str.trim();
if (!substr.equals("")) {
results.add(substr);
}
}
return results;
}
}
| chongshan0/ctrmodel-dataprocess-nuoyou | src/main/java/process/utils/StringUtil.java | 642 | //拆分为数组 | line_comment | zh-cn | package process.utils;
import java.util.HashSet;
public class StringUtil {
//格式化节目名
public static String formatVideoName(String videoName) {
//转换小写
videoName = videoName.toLowerCase().trim();
//中文括号转英文
videoName = videoName.replaceAll("(", "(");
videoName = videoName.replaceAll(")", ")");
//删除停用词字串(有前后顺序)
String[] stopWords = {
"版", "(美) ", "(台) ", "(港) ", "(港 / 台)", "(台 / 港)", "(日本) ",
"(精选) ", "(1080p 4m 新)", "(中文)", "(美版)", "4k", "1080p", "杜比",
"蓝光", "4m", "新4m", "4.5m", "高清", "限时免费", "限时特供", "限免",
"豆友译名", "1元看大片", "原声", "英语", "未删减", "国语", "英文", "中文",
"日文", "粤语", "tv", "国际", "抢先", "完整", "原声", "合集一", "合集二",
"合集三", "合集四", "合集五", "合集", "精切", "方言", "片段1", "片段2",
"片段3", "精选", "花絮", "片段", "泰语", "选段", "普通话", "会员", "日语"};
for (String stopword : stopWords) {
if (videoName.contains(stopword)) {
videoName = videoName.replaceAll(stopword, "");
}
}
//去除分隔符
videoName = videoName.replaceAll("[\\pZ]", "");
//去除标点字符
videoName = videoName.replaceAll("[\\pP]", "");
//去除符号如数学、货币符号
videoName = videoName.replaceAll("[\\pS]", "");
videoName = videoName
.replaceAll(" ", "")
.replaceAll("\t", "")
.replaceAll("\n", "")
.replaceAll("\r", "");
return videoName.trim();
}
//拆分以“|”分隔的字符串为Set
public static HashSet<String> splitToSet(String input) {
//拆分 <SUF>
String[] sarr = input.split("\\|");
//转换为set
HashSet<String> results = new HashSet<>();
for (String str : sarr) {
String substr = str.trim();
if (!substr.equals("")) {
results.add(substr);
}
}
return results;
}
}
| false | 585 | 4 | 642 | 6 | 649 | 4 | 642 | 6 | 800 | 8 | false | false | false | false | false | true |
55545_0 | package com.lchy._11基本通信模型介绍;
/**
目标:基本通信模型的概念介绍。
1.BIO(BLOCK)通信模式:同步阻塞式通信(Socket网络编程也就是上面的通信架构)
--同步: 当前线程要自己进行数据的读写操作(自己去银行取钱)--每个线程维护一个客户端,专门与客户端进行通信
--异步: 当前线程可以去做其他事情,(委托一小弟(操作系统)拿银行卡到银行取钱,然后给你)有一个socket连接(accept)管家,有了消息,就通知到相应线程去处理,
--阻塞: 在数据没有的情况下,还是要继续等待者读。(排队等待)
--非阻塞:在数据没有的情况下,会去做其他事情,一旦有了数据再来获取。(柜台取款,取个号,然后坐那干其他事情)
BIO表示同步阻塞式IO,服务器实现模式为一个连接一个线程,
即客户端有连接请求时服务端就需要启动一个线程进行处理,
如果这个连接不做任何事情会造成不必要的线程开销,当然可以通过线程池机制改善。
同步阻塞:亲自去银行取款,排队等待。 ------性能极差,大量线程,大量阻塞。
同步非阻塞:亲自去银行取款,取号,等待。
异步阻塞: 委托一个小弟(系统),排队等待。
异步非阻塞:委托一个小弟(系统),取号,等待。
2.伪异步通信:引入了线程池。 -----伪异步阻塞的
不需要一个客户端一个线程,可以实现1个线程复用来处理很多个客户端!
这种架构,可以避免系统的死机,因为不会出现很多线程,线程可控
但是高并发下性能还是很差:线程数量少,数据依然是阻塞式的。数据没有来线程还是要等待(重点是等待)!
3.NIO表示同步非阻塞IO,服务器实现模式为请求对应一个线程, -------连接中有数据了,创建线程去读,
即客户端发送的连接请求都会注册到多路复用器(相当于线程池)上
多路复用器轮询到连接有I/O请求时才启动一个线程进行处理。
①1个人专门负责接收客户端:
②1个人(多路复用器)[c1, s2 ,c3 , c4, s2, c3 ,c4] 轮询所有的客户端,发来了数据才会开启线程处理
假如c1连接有数据过来,才新建一个线程处理,
这种架构性能还可以! 举例:斗地主游戏,同时有6万人在线,当有人在思考出什么牌,这个连接是不能断的,处理发消息的线程是可以关闭的。有消息来了才启动线程。
同步:线程①②还是要不断的接收客户端连接,以及处理数据。
非阻塞:如果一个管道没有数据,不需要等待,可以轮询下一个管道是否有数据!
4.AIO表示异步非阻塞IO,服务器实现模式为一个有效请求一个线程, ------数据被底层操作系统已经读好了
客户端的I/O请求都是由操作系统先完成IO操作后再通知服务器应用来启动线程进行处理。
异步:服务端线程接收到了客户端管道以后就交给底层处理它的io通信。
自己可以做其他事情。
非阻塞:底层也是客户端有数据才会处理,有了数据以后处理好通知服务器应用来启动线程进行处理。
小结:
各种模型应用场景:
BIO适用于连接数目比较小且固定的架构,该方式对服务器资源要求比较高,JDK1.4以前的唯一选择。
NIO适用于连接数目多且连接时间比较短(消息短)(轻操作)的架构,如聊天服务器,编程复杂。
JDK 1.4开始支持
AIO适用于连接数目多且连接时间比较长(消息长)(重操作)的架构,如相册服务器,
充分调用操作系统参与并发操作,编程复杂,JDK1.7开始支持
*/
public class NIODemo {
}
| chongyang92/learndemo | Day11Demo/src/com/lchy/_11基本通信模型介绍/NIODemo.java | 1,028 | /**
目标:基本通信模型的概念介绍。
1.BIO(BLOCK)通信模式:同步阻塞式通信(Socket网络编程也就是上面的通信架构)
--同步: 当前线程要自己进行数据的读写操作(自己去银行取钱)--每个线程维护一个客户端,专门与客户端进行通信
--异步: 当前线程可以去做其他事情,(委托一小弟(操作系统)拿银行卡到银行取钱,然后给你)有一个socket连接(accept)管家,有了消息,就通知到相应线程去处理,
--阻塞: 在数据没有的情况下,还是要继续等待者读。(排队等待)
--非阻塞:在数据没有的情况下,会去做其他事情,一旦有了数据再来获取。(柜台取款,取个号,然后坐那干其他事情)
BIO表示同步阻塞式IO,服务器实现模式为一个连接一个线程,
即客户端有连接请求时服务端就需要启动一个线程进行处理,
如果这个连接不做任何事情会造成不必要的线程开销,当然可以通过线程池机制改善。
同步阻塞:亲自去银行取款,排队等待。 ------性能极差,大量线程,大量阻塞。
同步非阻塞:亲自去银行取款,取号,等待。
异步阻塞: 委托一个小弟(系统),排队等待。
异步非阻塞:委托一个小弟(系统),取号,等待。
2.伪异步通信:引入了线程池。 -----伪异步阻塞的
不需要一个客户端一个线程,可以实现1个线程复用来处理很多个客户端!
这种架构,可以避免系统的死机,因为不会出现很多线程,线程可控
但是高并发下性能还是很差:线程数量少,数据依然是阻塞式的。数据没有来线程还是要等待(重点是等待)!
3.NIO表示同步非阻塞IO,服务器实现模式为请求对应一个线程, -------连接中有数据了,创建线程去读,
即客户端发送的连接请求都会注册到多路复用器(相当于线程池)上
多路复用器轮询到连接有I/O请求时才启动一个线程进行处理。
①1个人专门负责接收客户端:
②1个人(多路复用器)[c1, s2 ,c3 , c4, s2, c3 ,c4] 轮询所有的客户端,发来了数据才会开启线程处理
假如c1连接有数据过来,才新建一个线程处理,
这种架构性能还可以! 举例:斗地主游戏,同时有6万人在线,当有人在思考出什么牌,这个连接是不能断的,处理发消息的线程是可以关闭的。有消息来了才启动线程。
同步:线程①②还是要不断的接收客户端连接,以及处理数据。
非阻塞:如果一个管道没有数据,不需要等待,可以轮询下一个管道是否有数据!
4.AIO表示异步非阻塞IO,服务器实现模式为一个有效请求一个线程, ------数据被底层操作系统已经读好了
客户端的I/O请求都是由操作系统先完成IO操作后再通知服务器应用来启动线程进行处理。
异步:服务端线程接收到了客户端管道以后就交给底层处理它的io通信。
自己可以做其他事情。
非阻塞:底层也是客户端有数据才会处理,有了数据以后处理好通知服务器应用来启动线程进行处理。
小结:
各种模型应用场景:
BIO适用于连接数目比较小且固定的架构,该方式对服务器资源要求比较高,JDK1.4以前的唯一选择。
NIO适用于连接数目多且连接时间比较短(消息短)(轻操作)的架构,如聊天服务器,编程复杂。
JDK 1.4开始支持
AIO适用于连接数目多且连接时间比较长(消息长)(重操作)的架构,如相册服务器,
充分调用操作系统参与并发操作,编程复杂,JDK1.7开始支持
*/ | block_comment | zh-cn | package com.lchy._11基本通信模型介绍;
/**
目标: <SUF>*/
public class NIODemo {
}
| false | 967 | 948 | 1,028 | 1,002 | 914 | 890 | 1,028 | 1,002 | 1,823 | 1,792 | true | true | true | true | true | false |
29051_6 | package com.xxl.robot.service.impl;
import com.xxl.robot.app.novel.A小说米读;
import com.xxl.robot.constants.AppConstants;
import com.xxl.robot.dto.PhoneCodeDto;
import com.xxl.robot.service.AppNovelService;
import com.xxl.robot.service.PhoneCodeService;
import lombok.SneakyThrows;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.awt.*;
import java.util.List;
/**
*
* todo app-视频服务接口类接口
*/
@Service
public class AppNovelServiceImpl implements AppNovelService {
private static final org.slf4j.Logger log = LoggerFactory.getLogger(AppNovelServiceImpl.class);
@Autowired
private PhoneCodeService phoneCodeService;
//************************一种类型:签到********************************************************
/**
* todo 1-签到
*/
@SneakyThrows
@Override
@Async
public void start(String robotCode){
Robot robot = new Robot();
log.info("********************米读小说**************************");
List<PhoneCodeDto> dtos = phoneCodeService.getList(robotCode,"米读小说");
A小说米读.handle(robot,robotCode,"米读小说", AppConstants.CHECK_IN,dtos);
}
//************************二种类型:分段(一次性收取,睡觉收取,吃饭,喝水,打卡,种菜,分享,游戏,充电,步行收取)*****************************************
/***
* todo 2.1-早上8:00-9:00 (一次性收取,睡觉收取,吃饭,喝水,打卡,种菜,分享,游戏,充电)
*/
@SneakyThrows
@Override
@Async
public void section1(String robotCode){
}
/**
* todo 2.2-中午11:00-12:00(吃饭,喝水,打卡,种菜,分享,游戏,充电)
*/
@Async
@SneakyThrows
@Override
public void section2(String robotCode){
}
/**
* todo 2.3-下午19:00-20:00(吃饭,喝水,打卡,种菜,分享,游戏,充电)
*/
@Async
@SneakyThrows
@Override
public void section3(String robotCode){
}
/**
* todo 2.4-晚上23:00-24:00(睡觉打卡,吃饭,喝水,打卡,种菜,分享,游戏,充电,步行收取)
*/
@SneakyThrows
@Override
@Async
public void section4(String robotCode){
}
//*************************三种类型:循环(开宝箱,看广告,领红包,看视频,看新闻,看小说,刮卡,抽奖)********************************************************
/**
* todo 3.1-循环收取金币大于200金币
*/
@Async
@SneakyThrows
@Override
public void circulate1(String robotCode){
Robot robot = new Robot();
log.info("********************米读小说**************************");
List<PhoneCodeDto> dtos = phoneCodeService.getList(robotCode,"米读小说");
A小说米读.handle(robot,robotCode,"米读小说", AppConstants.WATCH_NOVELS,dtos);
}
/**
* todo 3.2-循环收取金币小于200金币
*/
@Async
@SneakyThrows
@Override
public void circulate2(String robotCode){
}
}
| chongzi/xxl-robot | src/main/java/com/xxl/robot/service/impl/AppNovelServiceImpl.java | 980 | /**
* todo 2.3-下午19:00-20:00(吃饭,喝水,打卡,种菜,分享,游戏,充电)
*/ | block_comment | zh-cn | package com.xxl.robot.service.impl;
import com.xxl.robot.app.novel.A小说米读;
import com.xxl.robot.constants.AppConstants;
import com.xxl.robot.dto.PhoneCodeDto;
import com.xxl.robot.service.AppNovelService;
import com.xxl.robot.service.PhoneCodeService;
import lombok.SneakyThrows;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.awt.*;
import java.util.List;
/**
*
* todo app-视频服务接口类接口
*/
@Service
public class AppNovelServiceImpl implements AppNovelService {
private static final org.slf4j.Logger log = LoggerFactory.getLogger(AppNovelServiceImpl.class);
@Autowired
private PhoneCodeService phoneCodeService;
//************************一种类型:签到********************************************************
/**
* todo 1-签到
*/
@SneakyThrows
@Override
@Async
public void start(String robotCode){
Robot robot = new Robot();
log.info("********************米读小说**************************");
List<PhoneCodeDto> dtos = phoneCodeService.getList(robotCode,"米读小说");
A小说米读.handle(robot,robotCode,"米读小说", AppConstants.CHECK_IN,dtos);
}
//************************二种类型:分段(一次性收取,睡觉收取,吃饭,喝水,打卡,种菜,分享,游戏,充电,步行收取)*****************************************
/***
* todo 2.1-早上8:00-9:00 (一次性收取,睡觉收取,吃饭,喝水,打卡,种菜,分享,游戏,充电)
*/
@SneakyThrows
@Override
@Async
public void section1(String robotCode){
}
/**
* todo 2.2-中午11:00-12:00(吃饭,喝水,打卡,种菜,分享,游戏,充电)
*/
@Async
@SneakyThrows
@Override
public void section2(String robotCode){
}
/**
* tod <SUF>*/
@Async
@SneakyThrows
@Override
public void section3(String robotCode){
}
/**
* todo 2.4-晚上23:00-24:00(睡觉打卡,吃饭,喝水,打卡,种菜,分享,游戏,充电,步行收取)
*/
@SneakyThrows
@Override
@Async
public void section4(String robotCode){
}
//*************************三种类型:循环(开宝箱,看广告,领红包,看视频,看新闻,看小说,刮卡,抽奖)********************************************************
/**
* todo 3.1-循环收取金币大于200金币
*/
@Async
@SneakyThrows
@Override
public void circulate1(String robotCode){
Robot robot = new Robot();
log.info("********************米读小说**************************");
List<PhoneCodeDto> dtos = phoneCodeService.getList(robotCode,"米读小说");
A小说米读.handle(robot,robotCode,"米读小说", AppConstants.WATCH_NOVELS,dtos);
}
/**
* todo 3.2-循环收取金币小于200金币
*/
@Async
@SneakyThrows
@Override
public void circulate2(String robotCode){
}
}
| false | 770 | 39 | 980 | 46 | 896 | 42 | 980 | 46 | 1,266 | 66 | false | false | false | false | false | true |
8483_5 | /*
* 文件:锥体收集锥体.java
* -------------
* 锥体收集锥体类在一系列垂直塔中收集所有锥体 ,并将
* 它们存放在第一排的最东端。
*/
import stanford.卡雷尔.*;
public class 锥体收集锥体 extends 卡雷尔 {
/**
* 指定程序入口点。
*/
public void run() {
收集所有锥体S();
全部锥体秒();
回家();
}
/**
* 通过沿着第一排移动从每个塔收集锥体 ,在每个角落呼
* 叫收集一个塔。这种方法的后置条件是卡雷尔位于第一排朝东的最东端。
*/
private void 收集所有锥体S() {
while (frontIsClear()) {
收集一个塔();
move();
}
收集一个塔();
}
/**
* 在一个塔中收集锥体 。当收集一个塔被叫时,卡雷尔必
* 须在面向东的第一排。收集一个塔的后置条件是卡雷尔必须再次朝向同一角落的东方。
*/
private void 收集一个塔() {
turnLeft();
收集锥体的行();
turnAround();
move到墙();
turnLeft();
}
/**
* 收集锥体秒的连续行。 锥体行的末尾由不包含锥体 s
* 的角指示。
*/
private void 收集锥体的行() {
while (beepersPresent()) {
pickBeeper();
if (frontIsClear()) {
move();
}
}
}
/**
* 锥体当前角落的所有锥体 。
*/
private void 全部锥体秒() {
while (beepersInBag()) {
putBeeper();
}
}
/**
* 将卡雷尔返回到第一大道和第一排角落的初始位置,朝向东方。这种方法的前提条件是卡雷尔必须在第一排的某处朝东,这在收集所有锥体S的结尾是正确的。
*/
private void 回家() {
turnAround();
move到墙();
turnAround();
}
/** 向前移动卡雷尔,直到被墙挡住。 */
private void move到墙(){
while (frontIsClear()) {
move();
}
}
/** 将卡雷尔变成180度左右 */
private void turnAround(){
turnLeft();
turnLeft();
}
} | chrispiech/codeInternational | templates/java/zh/text/code/beeperTowers.java | 636 | /**
* 锥体当前角落的所有锥体 。
*/ | block_comment | zh-cn | /*
* 文件:锥体收集锥体.java
* -------------
* 锥体收集锥体类在一系列垂直塔中收集所有锥体 ,并将
* 它们存放在第一排的最东端。
*/
import stanford.卡雷尔.*;
public class 锥体收集锥体 extends 卡雷尔 {
/**
* 指定程序入口点。
*/
public void run() {
收集所有锥体S();
全部锥体秒();
回家();
}
/**
* 通过沿着第一排移动从每个塔收集锥体 ,在每个角落呼
* 叫收集一个塔。这种方法的后置条件是卡雷尔位于第一排朝东的最东端。
*/
private void 收集所有锥体S() {
while (frontIsClear()) {
收集一个塔();
move();
}
收集一个塔();
}
/**
* 在一个塔中收集锥体 。当收集一个塔被叫时,卡雷尔必
* 须在面向东的第一排。收集一个塔的后置条件是卡雷尔必须再次朝向同一角落的东方。
*/
private void 收集一个塔() {
turnLeft();
收集锥体的行();
turnAround();
move到墙();
turnLeft();
}
/**
* 收集锥体秒的连续行。 锥体行的末尾由不包含锥体 s
* 的角指示。
*/
private void 收集锥体的行() {
while (beepersPresent()) {
pickBeeper();
if (frontIsClear()) {
move();
}
}
}
/**
* 锥体当 <SUF>*/
private void 全部锥体秒() {
while (beepersInBag()) {
putBeeper();
}
}
/**
* 将卡雷尔返回到第一大道和第一排角落的初始位置,朝向东方。这种方法的前提条件是卡雷尔必须在第一排的某处朝东,这在收集所有锥体S的结尾是正确的。
*/
private void 回家() {
turnAround();
move到墙();
turnAround();
}
/** 向前移动卡雷尔,直到被墙挡住。 */
private void move到墙(){
while (frontIsClear()) {
move();
}
}
/** 将卡雷尔变成180度左右 */
private void turnAround(){
turnLeft();
turnLeft();
}
} | false | 578 | 15 | 636 | 17 | 616 | 16 | 636 | 17 | 894 | 27 | false | false | false | false | false | true |
35150_5 | package com.house.entity;
import lombok.*;
import java.util.Date;
/**
* 房屋实体类
*
* @author chriy
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class House {
/**
* 房屋ID
*/
private int houseId;
/**
* 房屋标题描述西信息
*/
private String houseDesc;
/**
* 几室几厅
*/
private String houseModel;
/**
* 面积
*/
private String houseArea;
/**
* 楼层
*/
private String houseFloor;
/**
* 类型
*/
private String houseType;
/**
* 价格
*/
private int housePrice;
/**
* 地址
*/
private String houseAddress;
/**
* 简介图片
*/
private String houseImage;
/**
* 小区名
*/
private String communityName;
/**
* 联系人
*/
private String houseLinkMan;
/**
* 房屋朝向
*/
private String houseOriented;
/**
* 详细图片
*/
private String houseDetailsImg;
/**
* 发布人员
*/
private String publisher;
/**
* 发布时间
*/
private Date publishTime;
}
| chriy/HouseRentalSystem | src/com/house/entity/House.java | 299 | /**
* 楼层
*/ | block_comment | zh-cn | package com.house.entity;
import lombok.*;
import java.util.Date;
/**
* 房屋实体类
*
* @author chriy
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class House {
/**
* 房屋ID
*/
private int houseId;
/**
* 房屋标题描述西信息
*/
private String houseDesc;
/**
* 几室几厅
*/
private String houseModel;
/**
* 面积
*/
private String houseArea;
/**
* 楼层
<SUF>*/
private String houseFloor;
/**
* 类型
*/
private String houseType;
/**
* 价格
*/
private int housePrice;
/**
* 地址
*/
private String houseAddress;
/**
* 简介图片
*/
private String houseImage;
/**
* 小区名
*/
private String communityName;
/**
* 联系人
*/
private String houseLinkMan;
/**
* 房屋朝向
*/
private String houseOriented;
/**
* 详细图片
*/
private String houseDetailsImg;
/**
* 发布人员
*/
private String publisher;
/**
* 发布时间
*/
private Date publishTime;
}
| false | 298 | 10 | 299 | 9 | 335 | 9 | 299 | 9 | 403 | 14 | false | false | false | false | false | true |
26044_6 | import java.util.Arrays;
/**
* Description: 输出最大连续子序列 以及 求最大子序列之和
* Created by small small su
* Date: 2022/6/7
* Email: surao@foryou56.com
*/
public class MaxArray {
public static int maxSubArray(int[] nums) {
int len = nums.length;
if (len == 0) {
return 0;
}
// dp[i]:以nums[i]结尾的 和最大的 连续子数组的和
int[] dp = new int[len];
dp[0] = nums[0];
int res = nums[0];
int start = 0, end = 0;
for (int i = 1; i < len; i++) {
// dp[i] = Math.max(dp[i - 1] + nums[i], nums[i]);
if (dp[i - 1] > 0) {
dp[i] = dp[i - 1] + nums[i];
} else {
dp[i] = nums[i];
start = i; //最大子序列的开头位置
}
// res = Math.max(res, dp[i]);
if (res < dp[i]) {
end = i; //最大子序列的结尾位置
res = dp[i];
}
System.out.println("i= " + i);
System.out.println("res: " + res);
System.out.println(Arrays.toString(dp));
System.out.println("start:" + start + " end:" + end);
//最大序列的数组
System.out.println(Arrays.toString(Arrays.copyOfRange(nums, start, end + 1)));
System.out.println("");
System.out.println("");
}
return res;
}
public static void main(String[] args) {
int[] a = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
System.out.println(maxSubArray(a) + "");
}
}
| chsring/MergeSort | src/MaxArray.java | 503 | //最大序列的数组 | line_comment | zh-cn | import java.util.Arrays;
/**
* Description: 输出最大连续子序列 以及 求最大子序列之和
* Created by small small su
* Date: 2022/6/7
* Email: surao@foryou56.com
*/
public class MaxArray {
public static int maxSubArray(int[] nums) {
int len = nums.length;
if (len == 0) {
return 0;
}
// dp[i]:以nums[i]结尾的 和最大的 连续子数组的和
int[] dp = new int[len];
dp[0] = nums[0];
int res = nums[0];
int start = 0, end = 0;
for (int i = 1; i < len; i++) {
// dp[i] = Math.max(dp[i - 1] + nums[i], nums[i]);
if (dp[i - 1] > 0) {
dp[i] = dp[i - 1] + nums[i];
} else {
dp[i] = nums[i];
start = i; //最大子序列的开头位置
}
// res = Math.max(res, dp[i]);
if (res < dp[i]) {
end = i; //最大子序列的结尾位置
res = dp[i];
}
System.out.println("i= " + i);
System.out.println("res: " + res);
System.out.println(Arrays.toString(dp));
System.out.println("start:" + start + " end:" + end);
//最大 <SUF>
System.out.println(Arrays.toString(Arrays.copyOfRange(nums, start, end + 1)));
System.out.println("");
System.out.println("");
}
return res;
}
public static void main(String[] args) {
int[] a = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
System.out.println(maxSubArray(a) + "");
}
}
| false | 441 | 5 | 503 | 5 | 528 | 5 | 503 | 5 | 594 | 8 | false | false | false | false | false | true |
52317_1 | package cn.chuanz.util;
import com.github.chuanzh.util.ConfigRead;
public class Constant {
public static String TEXT = "text";
public static String EVENT = "event";
public static String SUBSCRIBE = "subscribe";
public static String UNSUBSCRIBE = "unsubscribe";
public static String TEMPLATESENDJOBFINISH = "TEMPLATESENDJOBFINISH";
public static String TEMPLATEFANMSGREAD = "TEMPLATEFANMSGREAD";
public static String SUCCESS = "success";
/** 航班号*/
public static final int FLIGHT_NUMBER = 1;
/** 航班日期+航班号*/
public static final int FLIGHT_DATE_AND_NUMBER = 2;
/** 起降地*/
public static final int FLIGHT_DEP_AND_ARR = 3;
/** 机场*/
public static final int AIRPORT = 4;
/** 无效*/
public static final int INVALID = 0;
/** 静态图片路径 */
public static String getImgUrl() {
return ConfigRead.readValue("resourceHost") + "/images/";
}
}
| chuanzh/emp | src/main/java/cn/chuanz/util/Constant.java | 282 | /** 航班日期+航班号*/ | block_comment | zh-cn | package cn.chuanz.util;
import com.github.chuanzh.util.ConfigRead;
public class Constant {
public static String TEXT = "text";
public static String EVENT = "event";
public static String SUBSCRIBE = "subscribe";
public static String UNSUBSCRIBE = "unsubscribe";
public static String TEMPLATESENDJOBFINISH = "TEMPLATESENDJOBFINISH";
public static String TEMPLATEFANMSGREAD = "TEMPLATEFANMSGREAD";
public static String SUCCESS = "success";
/** 航班号*/
public static final int FLIGHT_NUMBER = 1;
/** 航班日 <SUF>*/
public static final int FLIGHT_DATE_AND_NUMBER = 2;
/** 起降地*/
public static final int FLIGHT_DEP_AND_ARR = 3;
/** 机场*/
public static final int AIRPORT = 4;
/** 无效*/
public static final int INVALID = 0;
/** 静态图片路径 */
public static String getImgUrl() {
return ConfigRead.readValue("resourceHost") + "/images/";
}
}
| false | 230 | 10 | 282 | 10 | 272 | 8 | 282 | 10 | 354 | 15 | false | false | false | false | false | true |
33598_13 | package com.huawei.classroom.student.h12;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class Home12 {
public Home12() {
// TODO Auto-generated constructor stub
}
/**
* 字符串content是一个超市的历次购物小票的合计,每次购物的明细之间用分号分割,每个商品之间用半角逗号分开
* 请找出 哪n个商品被同时购买的频率最高,将这n个商品名称的集合(set)返回
* @param content,历次购物的明细,例如:炸鸡,可乐,啤酒;薯片,啤酒,炸鸡;啤酒,雪碧,炸鸡
* @param n
* @return 哪n个商品被同时购买的频率最高,将这n个商品名称的集合(set)返回
* 不会出现并列的情况
*/
public Set<String> getFrequentItem(String content,int n) {
String[] lines = content.split(";");
Map<Set<String>, Integer> map = new HashMap<Set<String>, Integer>();
for (int i = 0; i < lines.length; i++) {
String[] items = lines[i].split(",");
//统计一次购物产生的组合数量
System.out.println(lines[i]);
count(items, map,n);
}
Iterator<Set<String>> it = map.keySet().iterator();
Set<String> maxKey = null;
//发现最大值
int maxValue = 0;
int maxCount=1;
while (it.hasNext()) {
Set<String> key = it.next();
if (map.get(key) > maxValue) {
maxValue = map.get(key);
maxKey = key;
maxCount=1;
}else if(map.get(key) == maxValue) {
maxCount++;
}
}
if(maxCount> 1) {
throw new IllegalArgumentException("max count="+maxCount );
}
return maxKey;
}
/**
* 取得一个组合
* @param items 本次购买的商品,每一个元素是一个商品
* @param map
* @param n 统计的商品组合(是1件组合、还是2件组合、还是3件组合)
*/
private void count(String[] items, Map<Set<String>, Integer> map,int n) {
//存放所有的组合all
Set<Set<String>> all=new HashSet<Set<String>>();
//set完全是为了递归使用
Set<String> set=new HashSet<String>();
getAllCombination(items,0, n,all,set);
//统一因为本次购物,产生的组合数量放到map中
Iterator<Set<String>> it = all.iterator();
while(it.hasNext()) {
Set<String> key=it.next();
int total=0;
if(map.containsKey(key)) {
total=map.get(key);
}
total++;
map.put(key,total);
}
}
/**
* 从strs字符串数组中,从start位置开始,取得数量为n个字符串的所有组合,将其放入到all中。其中每个组合放到一个Set<String>中
* 例如如果strs数组是a,b,c;start=0;n=2;则all=<<a,b>;<b,c>;<a,c>>(伪代码 在java里面不能直接这样写)
* @param strs 所有字符串
* @param start 从哪位开始统计
* @param n 字符串组合的数量
* @param all 存放历次组合出来的结果
* @param set 存放本次组合的结果
*/
private void getAllCombination(String[] strs,int start,int n,Set<Set<String>> all,Set<String> set) {
//如果set中已经满足数量=n了,那么本次递归可以结束了
if(set.size()==n) {
Set<String> temp=new HashSet<String>();
temp.addAll(set);
all.add(temp);
Iterator<String> it=temp.iterator();
while(it.hasNext()) {
System.out.print(it.next()+",");
}
System.out.print("\r\n");
return;
}
//如果已经到末尾了,结束本次递归
if(start>=strs.length) {
return;
}
//选择start位的字符串,继续尝试
set.add(strs[start]);
getAllCombination(strs,start+1,n,all,set);
//把start位再移除掉
set.remove(strs[start]);
//第start的字符串先不选择,从下一位开始尝试
getAllCombination(strs,start+1,n,all,set);
}
}
| chuckhooker/TJU-2023-Object_oriented_Programming-Lab | Code/Lab12/Home12.java | 1,244 | //第start的字符串先不选择,从下一位开始尝试 | line_comment | zh-cn | package com.huawei.classroom.student.h12;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class Home12 {
public Home12() {
// TODO Auto-generated constructor stub
}
/**
* 字符串content是一个超市的历次购物小票的合计,每次购物的明细之间用分号分割,每个商品之间用半角逗号分开
* 请找出 哪n个商品被同时购买的频率最高,将这n个商品名称的集合(set)返回
* @param content,历次购物的明细,例如:炸鸡,可乐,啤酒;薯片,啤酒,炸鸡;啤酒,雪碧,炸鸡
* @param n
* @return 哪n个商品被同时购买的频率最高,将这n个商品名称的集合(set)返回
* 不会出现并列的情况
*/
public Set<String> getFrequentItem(String content,int n) {
String[] lines = content.split(";");
Map<Set<String>, Integer> map = new HashMap<Set<String>, Integer>();
for (int i = 0; i < lines.length; i++) {
String[] items = lines[i].split(",");
//统计一次购物产生的组合数量
System.out.println(lines[i]);
count(items, map,n);
}
Iterator<Set<String>> it = map.keySet().iterator();
Set<String> maxKey = null;
//发现最大值
int maxValue = 0;
int maxCount=1;
while (it.hasNext()) {
Set<String> key = it.next();
if (map.get(key) > maxValue) {
maxValue = map.get(key);
maxKey = key;
maxCount=1;
}else if(map.get(key) == maxValue) {
maxCount++;
}
}
if(maxCount> 1) {
throw new IllegalArgumentException("max count="+maxCount );
}
return maxKey;
}
/**
* 取得一个组合
* @param items 本次购买的商品,每一个元素是一个商品
* @param map
* @param n 统计的商品组合(是1件组合、还是2件组合、还是3件组合)
*/
private void count(String[] items, Map<Set<String>, Integer> map,int n) {
//存放所有的组合all
Set<Set<String>> all=new HashSet<Set<String>>();
//set完全是为了递归使用
Set<String> set=new HashSet<String>();
getAllCombination(items,0, n,all,set);
//统一因为本次购物,产生的组合数量放到map中
Iterator<Set<String>> it = all.iterator();
while(it.hasNext()) {
Set<String> key=it.next();
int total=0;
if(map.containsKey(key)) {
total=map.get(key);
}
total++;
map.put(key,total);
}
}
/**
* 从strs字符串数组中,从start位置开始,取得数量为n个字符串的所有组合,将其放入到all中。其中每个组合放到一个Set<String>中
* 例如如果strs数组是a,b,c;start=0;n=2;则all=<<a,b>;<b,c>;<a,c>>(伪代码 在java里面不能直接这样写)
* @param strs 所有字符串
* @param start 从哪位开始统计
* @param n 字符串组合的数量
* @param all 存放历次组合出来的结果
* @param set 存放本次组合的结果
*/
private void getAllCombination(String[] strs,int start,int n,Set<Set<String>> all,Set<String> set) {
//如果set中已经满足数量=n了,那么本次递归可以结束了
if(set.size()==n) {
Set<String> temp=new HashSet<String>();
temp.addAll(set);
all.add(temp);
Iterator<String> it=temp.iterator();
while(it.hasNext()) {
System.out.print(it.next()+",");
}
System.out.print("\r\n");
return;
}
//如果已经到末尾了,结束本次递归
if(start>=strs.length) {
return;
}
//选择start位的字符串,继续尝试
set.add(strs[start]);
getAllCombination(strs,start+1,n,all,set);
//把start位再移除掉
set.remove(strs[start]);
//第s <SUF>
getAllCombination(strs,start+1,n,all,set);
}
}
| false | 1,049 | 14 | 1,244 | 15 | 1,200 | 14 | 1,244 | 15 | 1,667 | 24 | false | false | false | false | false | true |
60190_20 | package graphics2d.chart.bar;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Stroke;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
/**
* 柱状图
* ClassName: BarChart
* Package: graphics2d.chart.bar
* Description:
*
* @Author Chuhezhe
* @Create 2023/11/22 22:54
* @Version 1.0
*/
public class BarPainter {
// 图片宽度
private final int width;
// 图片高度
private final int height;
// img对象
private final BufferedImage img;
// 绘图环境
private final Graphics2D g2d;
// 垂直方向起点
private final int yStart;
// 垂直方向终点
private final int yEnd;
// 直方图数据
private List<Bar> bars;
// 构造函数
public BarPainter(int width, int height, int yStart, int yEnd) {
this.width = width;
this.height = height;
this.img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
this.g2d = (Graphics2D) img.getGraphics();
this.yStart = yStart;
this.yEnd = yEnd;
}
// 添加一项直方图数据
public void addBar(String name, int value) {
if (bars == null) {
bars = new ArrayList<>();
}
bars.add(new Bar(name, value));
}
/**
* 重置屏幕坐标系为笛卡尔坐标系,默认坐标系方向为左上角为原点,水平向右为x正方向,垂直向下为y正方向
*
* void translate(double tx, double ty) tx - 坐标沿X轴方向平移的距离 ty - 坐标在Y轴方向上平移的距离
* void rotate(double theta, double anchorx, double anchory) 通过正角度θ旋转使正X轴上的点朝向正Y轴旋转 anchor旋转锚点坐标
* void scale(double sx, double sy) sx - 坐标沿X轴方向缩放的因子 sy - 坐标沿Y轴方向缩放的因子
*/
private void resetCoordinate() {
AffineTransform trans = new AffineTransform();
trans.translate(0, this.height - this.yStart); // 从左上角移到左下角
trans.rotate(Math.toRadians(180.0), 0, 0); // 从[0,0]正X轴上朝向正Y轴旋转180度
trans.scale(-1, 1); // 水平翻转 同理 trans.scale(1, -1) 为垂直翻转
this.g2d.setTransform(trans);
}
// 绘制图案
public void draw() {
resetCoordinate();
// 设置背景为天蓝色
g2d.setColor(new Color(135, 206, 235));
g2d.fillRect(0, -this.yStart, this.width, this.height);
final int yMax = this.yEnd;
final int barCnt = this.bars.size();
// --往下是竖向网格线
final float stepx = (float) (this.width / barCnt);
final float CW = stepx / 3;// CW:Column Width
// LINE_TYPE_DASHED
Stroke dashed = new BasicStroke(
1,
BasicStroke.CAP_BUTT,
BasicStroke.JOIN_BEVEL,
0,
new float[]{16, 4},
0);
g2d.setColor(Color.gray);
for (int i = 0; i < barCnt; i++) {
float x = i * stepx;
float y = yMax;
g2d.setStroke(new BasicStroke(1.0f));
g2d.drawLine((int) x, 0, (int) x, (int) y);
g2d.setStroke(dashed);
g2d.drawLine((int) (x + CW), 0, (int) (x + CW), (int) y);
g2d.drawLine((int) (x + 2 * CW), 0, (int) (x + 2 * CW), (int) y);
}
// 以最高点定比例
float maxCnt = -1;
for (Bar b : bars) {
if (b.getValue() > maxCnt) {
maxCnt = b.getValue();
}
}
final float ratio = yMax / maxCnt;
// --往下是画横向网格线
final float stepy = (float) (yMax / barCnt);
final float GH = stepy / 3;// GH:Grid Width
for (int i = 0; i <= barCnt; i++) {
float y = i * stepy;
g2d.setStroke(new BasicStroke(1.0f));
g2d.drawLine(0, (int) y, this.width, (int) y);
g2d.setFont(new Font("宋体", Font.BOLD, 16));
g2d.setColor(Color.black);
int yValue = (int) (y * maxCnt / yMax);
putString(g2d, yValue + "", 15, (int) y);
if (i > 0) {
g2d.setStroke(dashed);
g2d.drawLine(0, (int) (y - GH), this.width, (int) (y - GH));
g2d.drawLine(0, (int) (y - 2 * GH), this.width, (int) (y - 2 * GH));
}
}
// --往下是画柱状图
for (int i = 0; i < this.bars.size(); i++) {
Bar bar = this.bars.get(i);
float x = i * stepx + (CW);
float y = 0;
float w = CW;
float h = bar.getValue() * ratio;
g2d.setColor(getColor(i));
g2d.fillRect((int) x, (int) y, (int) (w), (int) (h));
// 在柱子顶写文字
g2d.setFont(new Font("仿宋", Font.BOLD, 16));
g2d.setColor(Color.black);
putString(g2d, bar.getName() + "=" + bar.getValue(), (int) (x + CW / 2), (int) (h - 15));
}
// 写标题
g2d.setFont(new Font("仿宋", Font.BOLD, 36));
g2d.setColor(Color.black);
putString(g2d, "g2d绘制直方图示例", this.width / 2, this.yEnd + 50);
// 写作者
g2d.setFont(new Font("仿宋", Font.BOLD, 12));
g2d.setColor(Color.black);
putString(g2d, "chuhezhe", this.width - 100, -25);
g2d.dispose();// g2d使命完成
}
// 写入图片
public void write2File(String path) {
try {
ImageIO.write(img, "PNG", Files.newOutputStream(Paths.get(path)));
} catch (Exception e) {
e.printStackTrace();
}
}
// 写文字
private void putString(Graphics2D g2d, String text, int x, int y) {
AffineTransform previousTrans = g2d.getTransform();
AffineTransform newtrans = new AffineTransform();
FontMetrics fm2 = g2d.getFontMetrics();
int textWidth = fm2.stringWidth(text);
newtrans.translate(x - textWidth / 2.0, (this.height - this.yStart) - y);
g2d.setTransform(newtrans);
g2d.drawString(text, 0, 0);
g2d.setTransform(previousTrans);
}
// 取一种颜色
private static Color getColor(int idx) {
Color[] colors = {Color.red, Color.yellow, Color.blue, Color.magenta, Color.green, Color.orange, Color.cyan};
int i = idx % colors.length;
return colors[i];
}
public static void main(String[] args) {
BarPainter pm = new BarPainter(1200, 960, 50, 800);
pm.addBar("勇气", 80);
pm.addBar("毅力", 120);
pm.addBar("果敢", 450);
pm.addBar("机敏", 32);
pm.addBar("决心", 360);
pm.addBar("明智", 230);
pm.addBar("忍耐", 420);
pm.draw();
pm.write2File("D:\\WorkSpace_BackEnd\\TestFiles\\graphics2d\\chart\\bar.png");
System.out.println("直方图做成");
}
} | chuhezhe0807/java_learning | Java/src/main/java/graphics2d/chart/bar/BarPainter.java | 2,300 | // --往下是画横向网格线 | line_comment | zh-cn | package graphics2d.chart.bar;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Stroke;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
/**
* 柱状图
* ClassName: BarChart
* Package: graphics2d.chart.bar
* Description:
*
* @Author Chuhezhe
* @Create 2023/11/22 22:54
* @Version 1.0
*/
public class BarPainter {
// 图片宽度
private final int width;
// 图片高度
private final int height;
// img对象
private final BufferedImage img;
// 绘图环境
private final Graphics2D g2d;
// 垂直方向起点
private final int yStart;
// 垂直方向终点
private final int yEnd;
// 直方图数据
private List<Bar> bars;
// 构造函数
public BarPainter(int width, int height, int yStart, int yEnd) {
this.width = width;
this.height = height;
this.img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
this.g2d = (Graphics2D) img.getGraphics();
this.yStart = yStart;
this.yEnd = yEnd;
}
// 添加一项直方图数据
public void addBar(String name, int value) {
if (bars == null) {
bars = new ArrayList<>();
}
bars.add(new Bar(name, value));
}
/**
* 重置屏幕坐标系为笛卡尔坐标系,默认坐标系方向为左上角为原点,水平向右为x正方向,垂直向下为y正方向
*
* void translate(double tx, double ty) tx - 坐标沿X轴方向平移的距离 ty - 坐标在Y轴方向上平移的距离
* void rotate(double theta, double anchorx, double anchory) 通过正角度θ旋转使正X轴上的点朝向正Y轴旋转 anchor旋转锚点坐标
* void scale(double sx, double sy) sx - 坐标沿X轴方向缩放的因子 sy - 坐标沿Y轴方向缩放的因子
*/
private void resetCoordinate() {
AffineTransform trans = new AffineTransform();
trans.translate(0, this.height - this.yStart); // 从左上角移到左下角
trans.rotate(Math.toRadians(180.0), 0, 0); // 从[0,0]正X轴上朝向正Y轴旋转180度
trans.scale(-1, 1); // 水平翻转 同理 trans.scale(1, -1) 为垂直翻转
this.g2d.setTransform(trans);
}
// 绘制图案
public void draw() {
resetCoordinate();
// 设置背景为天蓝色
g2d.setColor(new Color(135, 206, 235));
g2d.fillRect(0, -this.yStart, this.width, this.height);
final int yMax = this.yEnd;
final int barCnt = this.bars.size();
// --往下是竖向网格线
final float stepx = (float) (this.width / barCnt);
final float CW = stepx / 3;// CW:Column Width
// LINE_TYPE_DASHED
Stroke dashed = new BasicStroke(
1,
BasicStroke.CAP_BUTT,
BasicStroke.JOIN_BEVEL,
0,
new float[]{16, 4},
0);
g2d.setColor(Color.gray);
for (int i = 0; i < barCnt; i++) {
float x = i * stepx;
float y = yMax;
g2d.setStroke(new BasicStroke(1.0f));
g2d.drawLine((int) x, 0, (int) x, (int) y);
g2d.setStroke(dashed);
g2d.drawLine((int) (x + CW), 0, (int) (x + CW), (int) y);
g2d.drawLine((int) (x + 2 * CW), 0, (int) (x + 2 * CW), (int) y);
}
// 以最高点定比例
float maxCnt = -1;
for (Bar b : bars) {
if (b.getValue() > maxCnt) {
maxCnt = b.getValue();
}
}
final float ratio = yMax / maxCnt;
// -- <SUF>
final float stepy = (float) (yMax / barCnt);
final float GH = stepy / 3;// GH:Grid Width
for (int i = 0; i <= barCnt; i++) {
float y = i * stepy;
g2d.setStroke(new BasicStroke(1.0f));
g2d.drawLine(0, (int) y, this.width, (int) y);
g2d.setFont(new Font("宋体", Font.BOLD, 16));
g2d.setColor(Color.black);
int yValue = (int) (y * maxCnt / yMax);
putString(g2d, yValue + "", 15, (int) y);
if (i > 0) {
g2d.setStroke(dashed);
g2d.drawLine(0, (int) (y - GH), this.width, (int) (y - GH));
g2d.drawLine(0, (int) (y - 2 * GH), this.width, (int) (y - 2 * GH));
}
}
// --往下是画柱状图
for (int i = 0; i < this.bars.size(); i++) {
Bar bar = this.bars.get(i);
float x = i * stepx + (CW);
float y = 0;
float w = CW;
float h = bar.getValue() * ratio;
g2d.setColor(getColor(i));
g2d.fillRect((int) x, (int) y, (int) (w), (int) (h));
// 在柱子顶写文字
g2d.setFont(new Font("仿宋", Font.BOLD, 16));
g2d.setColor(Color.black);
putString(g2d, bar.getName() + "=" + bar.getValue(), (int) (x + CW / 2), (int) (h - 15));
}
// 写标题
g2d.setFont(new Font("仿宋", Font.BOLD, 36));
g2d.setColor(Color.black);
putString(g2d, "g2d绘制直方图示例", this.width / 2, this.yEnd + 50);
// 写作者
g2d.setFont(new Font("仿宋", Font.BOLD, 12));
g2d.setColor(Color.black);
putString(g2d, "chuhezhe", this.width - 100, -25);
g2d.dispose();// g2d使命完成
}
// 写入图片
public void write2File(String path) {
try {
ImageIO.write(img, "PNG", Files.newOutputStream(Paths.get(path)));
} catch (Exception e) {
e.printStackTrace();
}
}
// 写文字
private void putString(Graphics2D g2d, String text, int x, int y) {
AffineTransform previousTrans = g2d.getTransform();
AffineTransform newtrans = new AffineTransform();
FontMetrics fm2 = g2d.getFontMetrics();
int textWidth = fm2.stringWidth(text);
newtrans.translate(x - textWidth / 2.0, (this.height - this.yStart) - y);
g2d.setTransform(newtrans);
g2d.drawString(text, 0, 0);
g2d.setTransform(previousTrans);
}
// 取一种颜色
private static Color getColor(int idx) {
Color[] colors = {Color.red, Color.yellow, Color.blue, Color.magenta, Color.green, Color.orange, Color.cyan};
int i = idx % colors.length;
return colors[i];
}
public static void main(String[] args) {
BarPainter pm = new BarPainter(1200, 960, 50, 800);
pm.addBar("勇气", 80);
pm.addBar("毅力", 120);
pm.addBar("果敢", 450);
pm.addBar("机敏", 32);
pm.addBar("决心", 360);
pm.addBar("明智", 230);
pm.addBar("忍耐", 420);
pm.draw();
pm.write2File("D:\\WorkSpace_BackEnd\\TestFiles\\graphics2d\\chart\\bar.png");
System.out.println("直方图做成");
}
} | false | 2,052 | 8 | 2,300 | 12 | 2,336 | 10 | 2,300 | 12 | 2,763 | 15 | false | false | false | false | false | true |
23901_0 | import java.util.HashMap;
import java.util.Map;
public class MinWindow {
/**
* 给你一个字符串 s 、一个字符串 t 。返回 s 中涵盖 t 所有字符的最小子串。如果 s 中不存在涵盖 t 所有字符的子串,则返回空字符串 "" 。
* 注意:
* 对于 t 中重复字符,我们寻找的子字符串中该字符数量必须不少于 t 中该字符数量。
* 如果 s 中存在这样的子串,我们保证它是唯一的答案。
* 示例 1:
* 输入:s = "ADOBECODEBANC", t = "ABC"
* 输出:"BANC"
* 解释:最小覆盖子串 "BANC" 包含来自字符串 t 的 'A'、'B' 和 'C'。
*/
public String minWindow(String s, String t){
Map<Character, Integer> hs = new HashMap<>();
Map<Character, Integer> ht = new HashMap<>();
for(int i = 0; i < t.length(); i++){
ht.put(t.charAt(i), ht.getOrDefault(t.charAt(i), 0) + 1);
}
String ans = "";
int len = Integer.MAX_VALUE;
int cnt = 0;
for(int i = 0, j = 0; i < s.length(); i++){
hs.put(s.charAt(i), hs.getOrDefault(s.charAt(i), 0) + 1);
if(ht.containsKey(s.charAt(i)) && hs.get(s.charAt(i)) <= ht.get(s.charAt(i))) cnt++;
while(j < i && (!ht.containsKey(s.charAt(j)) || hs.get(s.charAt(j)) > ht.get(s.charAt(j)))){
int count = hs.get(s.charAt(j)) - 1;
hs.put(s.charAt(j), count);
j++;
}
if(cnt == t.length() && i - j + 1 < len){
len = i - j + 1;
ans = s.substring(j, i + 1);
}
}
return ans;
}
public String minWindow2(String s, String t){
int n = s.length(), tot = 0;
int[] c1 = new int[60], c2 = new int[60];
for(char c : t.toCharArray()){
if(++c1[getIdx(c)] == 1) tot++;
}
String ans = "";
int j = 0;
for(int i = 0; i < n; i++){
int idx1 = getIdx(s.charAt(i));
if(++c2[idx1] == c1[idx1]) tot--;
while(j < i){
int idx2 = getIdx(s.charAt(j));
if(c2[idx2] > c1[idx2] && --c2[idx2] >= 0) j++;
else break;
}
if(tot == 0 && (ans.length() == 0 || ans.length() > i - j + 1)){
ans = s.substring(j, i + 1);
}
}
return ans;
}
int getIdx(char x){
return x >= 'A' && x <= 'Z' ? x - 'A' + 26 : x - 'a';
}
}
| chujian-zoe/leetcode228 | src/MinWindow.java | 811 | /**
* 给你一个字符串 s 、一个字符串 t 。返回 s 中涵盖 t 所有字符的最小子串。如果 s 中不存在涵盖 t 所有字符的子串,则返回空字符串 "" 。
* 注意:
* 对于 t 中重复字符,我们寻找的子字符串中该字符数量必须不少于 t 中该字符数量。
* 如果 s 中存在这样的子串,我们保证它是唯一的答案。
* 示例 1:
* 输入:s = "ADOBECODEBANC", t = "ABC"
* 输出:"BANC"
* 解释:最小覆盖子串 "BANC" 包含来自字符串 t 的 'A'、'B' 和 'C'。
*/ | block_comment | zh-cn | import java.util.HashMap;
import java.util.Map;
public class MinWindow {
/**
* 给你一 <SUF>*/
public String minWindow(String s, String t){
Map<Character, Integer> hs = new HashMap<>();
Map<Character, Integer> ht = new HashMap<>();
for(int i = 0; i < t.length(); i++){
ht.put(t.charAt(i), ht.getOrDefault(t.charAt(i), 0) + 1);
}
String ans = "";
int len = Integer.MAX_VALUE;
int cnt = 0;
for(int i = 0, j = 0; i < s.length(); i++){
hs.put(s.charAt(i), hs.getOrDefault(s.charAt(i), 0) + 1);
if(ht.containsKey(s.charAt(i)) && hs.get(s.charAt(i)) <= ht.get(s.charAt(i))) cnt++;
while(j < i && (!ht.containsKey(s.charAt(j)) || hs.get(s.charAt(j)) > ht.get(s.charAt(j)))){
int count = hs.get(s.charAt(j)) - 1;
hs.put(s.charAt(j), count);
j++;
}
if(cnt == t.length() && i - j + 1 < len){
len = i - j + 1;
ans = s.substring(j, i + 1);
}
}
return ans;
}
public String minWindow2(String s, String t){
int n = s.length(), tot = 0;
int[] c1 = new int[60], c2 = new int[60];
for(char c : t.toCharArray()){
if(++c1[getIdx(c)] == 1) tot++;
}
String ans = "";
int j = 0;
for(int i = 0; i < n; i++){
int idx1 = getIdx(s.charAt(i));
if(++c2[idx1] == c1[idx1]) tot--;
while(j < i){
int idx2 = getIdx(s.charAt(j));
if(c2[idx2] > c1[idx2] && --c2[idx2] >= 0) j++;
else break;
}
if(tot == 0 && (ans.length() == 0 || ans.length() > i - j + 1)){
ans = s.substring(j, i + 1);
}
}
return ans;
}
int getIdx(char x){
return x >= 'A' && x <= 'Z' ? x - 'A' + 26 : x - 'a';
}
}
| false | 699 | 161 | 811 | 175 | 848 | 165 | 811 | 175 | 1,000 | 272 | false | false | false | false | false | true |
31405_26 | package events;
import YibaMod.YibaMod;
import cards.curse.desire;
import cards.curse.snowman;
import com.megacrit.cardcrawl.cards.DamageInfo;
import com.megacrit.cardcrawl.core.CardCrawlGame;
import com.megacrit.cardcrawl.core.Settings;
import com.megacrit.cardcrawl.dungeons.AbstractDungeon;
import com.megacrit.cardcrawl.events.AbstractImageEvent;
import com.megacrit.cardcrawl.helpers.RelicLibrary;
import com.megacrit.cardcrawl.localization.EventStrings;
import com.megacrit.cardcrawl.relics.AbstractRelic;
import com.megacrit.cardcrawl.rooms.AbstractRoom;
import com.megacrit.cardcrawl.vfx.cardManip.ShowCardAndObtainEffect;
public class Restaurant extends AbstractImageEvent {
public static final String ID = "Restaurant";
private static final EventStrings eventStrings = CardCrawlGame.languagePack.getEventString("Restaurant");
public static final String NAME = eventStrings.NAME;
public static final String[] DESCRIPTIONS = eventStrings.DESCRIPTIONS;
public static final String[] OPTIONS = eventStrings.OPTIONS;
private static final String INTRO_MSG = DESCRIPTIONS[0];//进入事件的描述
private static final String Drink_MSG = DESCRIPTIONS[1]; //喝下后的描述
private static final String Eat_MSG = DESCRIPTIONS[2]; //喝下后的剧情,开始吃炸酱面
private static final String EatAfter_MSG = DESCRIPTIONS[3]; //吃下炸酱面的剧情
private static final String Evaluate_MSG = DESCRIPTIONS[4]; //评价
private static final String Evaluate_GOOD_MSG = DESCRIPTIONS[5]; //好评
private static final String Evaluate_NO_MSG = DESCRIPTIONS[6]; //不予置评
private static final String LEAVE = DESCRIPTIONS[7]; //开始离开的剧情描述
private static final String DRINK = OPTIONS[0]; //喝下
private static final String LEAVE_NO_DRINK = OPTIONS[1]; //离开-无视发生
private static final String EAT= OPTIONS[2]; //吃下炸酱面
private static final String LEAVE_NO_EAT = OPTIONS[3]; //不吃面离开,被诅咒
private static final String Evaluate_GOOD = OPTIONS[4]; //好评
private static final String Evaluate_NO = OPTIONS[5]; //不予置评
private int finalDmg;
private int damageTaken;
private CurScreen screen = CurScreen.INTRO;
boolean isIn;
private enum CurScreen {
INTRO, PAGE_1, PAGE_2, PAGE_3, LAST_PAGE, END, HeJiu;
}
public Restaurant() {
super(NAME, INTRO_MSG, "img/events/Restaurant.png");
this.noCardsInRewards = true;
//初次进入
YibaMod.logger.info("进入事件:餐厅");
//进入事件
this.imageEventText.setDialogOption("[进入] #r快点端上来罢 !");
//离开事件
this.imageEventText.setDialogOption(LEAVE_NO_DRINK);
YibaMod.logger.info("设置开场白");
}
public void leave(){
this.imageEventText.clearRemainingOptions();
this.imageEventText.setDialogOption("离开");
this.imageEventText.updateDialogOption(0,"离开");
this.imageEventText.removeDialogOption(1);
//打开地图
openMap();
YibaMod.logger.info("整个事件结束。打开地图了。");
}
//按下按钮
protected void buttonEffect(int buttonPressed) {
switch (this.screen) {
case INTRO:
//一开始进入事件触发的
if(isIn){
//buttonPressed=-1;
isIn=false;
break;
}
if (buttonPressed == 0) {
YibaMod.logger.info("选择端上来");
this.imageEventText.clearAllDialogs();
YibaMod.logger.info("设置喝酒的信息");
this.imageEventText.updateBodyText("“咳,先生,这是我们的 #y迎宾酒 ” NL 你看着面前这杯 #y@泛黄浮着泡沫的酒@ ,你的选择是?");
this.imageEventText.clearRemainingOptions();
this.imageEventText.setDialogOption(DRINK);
this.imageEventText.updateDialogOption(0,DRINK);
this.imageEventText.setDialogOption(LEAVE_NO_DRINK);
this.imageEventText.updateDialogOption(1,LEAVE_NO_DRINK);
YibaMod.logger.info("准备进入HeJiu");
this.screen=CurScreen.HeJiu;
break;
}else {
//离开事件
YibaMod.logger.info("选择离开");
this.imageEventText.updateBodyText("你无视了眼前的景象");
this.screen = CurScreen.END;
leave();
break;
}
case HeJiu:
if(isIn){
//buttonPressed=-1;
isIn=false;
break;
}
this.imageEventText.clearAllDialogs();
if (buttonPressed == 0) {
//喝下酒
YibaMod.logger.info("选择喝下酒");
CardCrawlGame.sound.play("EVENT_TOME");
this.imageEventText.clearAllDialogs();
//设置喝下选项
//更新喝下后的文本
this.imageEventText.updateBodyText(Drink_MSG);
//给予玩家10点伤害
YibaMod.logger.info("喝下酒:受到 10 点伤害");
AbstractDungeon.player.damage(new DamageInfo(null, 10, DamageInfo.DamageType.HP_LOSS));
this.imageEventText.clearAllDialogs();
this.imageEventText.setDialogOption("继续");
isIn=true;
YibaMod.logger.info("设置接下来为:PAGE_1");
this.screen = Restaurant.CurScreen.PAGE_1;
break;
}
case PAGE_1:
//喝下之后触发的
YibaMod.logger.info("进入PAGE_1:喝下酒后");
//CardCrawlGame.sound.play("EVENT_TOME");
this.imageEventText.clearAllDialogs();
this.imageEventText.clearRemainingOptions();
//this.imageEventText.removeDialogOption(1);
//吃下选项
this.imageEventText.setDialogOption(EAT);
//离开选项(被诅咒-三大欲望)
this.imageEventText.setDialogOption(LEAVE_NO_EAT);
this.imageEventText.updateBodyText(Eat_MSG);
if(isIn){
//buttonPressed=-1;
isIn=false;
break;
}
if(buttonPressed==0){
isIn=true;
//继续,前往第二页,触发吃下的剧情
YibaMod.logger.info("选择吃下");
//更新文本-准备吃面
CardCrawlGame.sound.play("EVENT_TOME");
//受到15点伤害
YibaMod.logger.info("吃下:受到15点伤害");
AbstractDungeon.player.damage(new DamageInfo(null, 15, DamageInfo.DamageType.HP_LOSS));
//this.damageTaken += 2;
this.imageEventText.clearAllDialogs();
this.imageEventText.clearRemainingOptions();
//吃完了,开始评价
//更新文本
this.imageEventText.updateBodyText(EatAfter_MSG);
//this.imageEventText.clearAllDialogs();
this.imageEventText.clearRemainingOptions();
this.imageEventText.setDialogOption("继续");
YibaMod.logger.info("前往PAGE_3");
this.screen = Restaurant.CurScreen.PAGE_3;
break;
}else {
isIn=true;
//更新文本提示。
YibaMod.logger.info("[离开] #r被诅咒-食雪汉。");
this.imageEventText.updateBodyText("服务员看起来非常的#y~沮丧~。。。");
//清除选项
this.imageEventText.clearRemainingOptions();
//TODO:塞一张诅咒牌。
AbstractDungeon.effectList.add(new ShowCardAndObtainEffect(new desire(), Settings.WIDTH / 2.0F, Settings.HEIGHT / 2.0F));
//打开地图
this.screen = CurScreen.END;
this.imageEventText.clearRemainingOptions();
this.imageEventText.setDialogOption("离开");
this.imageEventText.updateDialogOption(0,"离开");
this.imageEventText.removeDialogOption(1);
//leave();
break;
}
case PAGE_3:
//评价
YibaMod.logger.info("进入PAGE_3");
this.imageEventText.clearAllDialogs();
this.imageEventText.clearRemainingOptions();
this.imageEventText.setDialogOption(Evaluate_GOOD);
this.imageEventText.setDialogOption(Evaluate_NO);
this.imageEventText.updateBodyText(Evaluate_MSG);
if(isIn){
//buttonPressed=-1;
isIn=false;
break;
}
isIn=true;
if(buttonPressed==0) {
//好评
YibaMod.logger.info("好评");
this.imageEventText.clearAllDialogs();
this.imageEventText.updateBodyText(Evaluate_GOOD_MSG);
//给牛排
AbstractRelic r = (RelicLibrary.getRelic("beef").makeCopy());
(AbstractDungeon.getCurrRoom()).rewards.clear();
AbstractDungeon.getCurrRoom().addRelicToRewards(r);
(AbstractDungeon.getCurrRoom()).phase = AbstractRoom.RoomPhase.COMPLETE;
AbstractDungeon.combatRewardScreen.open();
this.screen = CurScreen.END;
}else {
//不予置评
YibaMod.logger.info("不予置评");
this.imageEventText.clearAllDialogs();
this.imageEventText.updateBodyText(Evaluate_NO_MSG);
//被诅咒-三大欲望
AbstractDungeon.effectList.add(new ShowCardAndObtainEffect(new snowman(), Settings.WIDTH / 2.0F, Settings.HEIGHT / 2.0F));
this.screen = CurScreen.END;
}
//leave();
this.imageEventText.clearRemainingOptions();
this.imageEventText.setDialogOption("离开");
this.imageEventText.updateDialogOption(0,"离开");
this.imageEventText.removeDialogOption(1);
break;
case END:
leave();
break;
}
}
}
| chunk2333/Yiba-mod | src/main/java/events/Restaurant.java | 2,605 | //吃下选项 | line_comment | zh-cn | package events;
import YibaMod.YibaMod;
import cards.curse.desire;
import cards.curse.snowman;
import com.megacrit.cardcrawl.cards.DamageInfo;
import com.megacrit.cardcrawl.core.CardCrawlGame;
import com.megacrit.cardcrawl.core.Settings;
import com.megacrit.cardcrawl.dungeons.AbstractDungeon;
import com.megacrit.cardcrawl.events.AbstractImageEvent;
import com.megacrit.cardcrawl.helpers.RelicLibrary;
import com.megacrit.cardcrawl.localization.EventStrings;
import com.megacrit.cardcrawl.relics.AbstractRelic;
import com.megacrit.cardcrawl.rooms.AbstractRoom;
import com.megacrit.cardcrawl.vfx.cardManip.ShowCardAndObtainEffect;
public class Restaurant extends AbstractImageEvent {
public static final String ID = "Restaurant";
private static final EventStrings eventStrings = CardCrawlGame.languagePack.getEventString("Restaurant");
public static final String NAME = eventStrings.NAME;
public static final String[] DESCRIPTIONS = eventStrings.DESCRIPTIONS;
public static final String[] OPTIONS = eventStrings.OPTIONS;
private static final String INTRO_MSG = DESCRIPTIONS[0];//进入事件的描述
private static final String Drink_MSG = DESCRIPTIONS[1]; //喝下后的描述
private static final String Eat_MSG = DESCRIPTIONS[2]; //喝下后的剧情,开始吃炸酱面
private static final String EatAfter_MSG = DESCRIPTIONS[3]; //吃下炸酱面的剧情
private static final String Evaluate_MSG = DESCRIPTIONS[4]; //评价
private static final String Evaluate_GOOD_MSG = DESCRIPTIONS[5]; //好评
private static final String Evaluate_NO_MSG = DESCRIPTIONS[6]; //不予置评
private static final String LEAVE = DESCRIPTIONS[7]; //开始离开的剧情描述
private static final String DRINK = OPTIONS[0]; //喝下
private static final String LEAVE_NO_DRINK = OPTIONS[1]; //离开-无视发生
private static final String EAT= OPTIONS[2]; //吃下炸酱面
private static final String LEAVE_NO_EAT = OPTIONS[3]; //不吃面离开,被诅咒
private static final String Evaluate_GOOD = OPTIONS[4]; //好评
private static final String Evaluate_NO = OPTIONS[5]; //不予置评
private int finalDmg;
private int damageTaken;
private CurScreen screen = CurScreen.INTRO;
boolean isIn;
private enum CurScreen {
INTRO, PAGE_1, PAGE_2, PAGE_3, LAST_PAGE, END, HeJiu;
}
public Restaurant() {
super(NAME, INTRO_MSG, "img/events/Restaurant.png");
this.noCardsInRewards = true;
//初次进入
YibaMod.logger.info("进入事件:餐厅");
//进入事件
this.imageEventText.setDialogOption("[进入] #r快点端上来罢 !");
//离开事件
this.imageEventText.setDialogOption(LEAVE_NO_DRINK);
YibaMod.logger.info("设置开场白");
}
public void leave(){
this.imageEventText.clearRemainingOptions();
this.imageEventText.setDialogOption("离开");
this.imageEventText.updateDialogOption(0,"离开");
this.imageEventText.removeDialogOption(1);
//打开地图
openMap();
YibaMod.logger.info("整个事件结束。打开地图了。");
}
//按下按钮
protected void buttonEffect(int buttonPressed) {
switch (this.screen) {
case INTRO:
//一开始进入事件触发的
if(isIn){
//buttonPressed=-1;
isIn=false;
break;
}
if (buttonPressed == 0) {
YibaMod.logger.info("选择端上来");
this.imageEventText.clearAllDialogs();
YibaMod.logger.info("设置喝酒的信息");
this.imageEventText.updateBodyText("“咳,先生,这是我们的 #y迎宾酒 ” NL 你看着面前这杯 #y@泛黄浮着泡沫的酒@ ,你的选择是?");
this.imageEventText.clearRemainingOptions();
this.imageEventText.setDialogOption(DRINK);
this.imageEventText.updateDialogOption(0,DRINK);
this.imageEventText.setDialogOption(LEAVE_NO_DRINK);
this.imageEventText.updateDialogOption(1,LEAVE_NO_DRINK);
YibaMod.logger.info("准备进入HeJiu");
this.screen=CurScreen.HeJiu;
break;
}else {
//离开事件
YibaMod.logger.info("选择离开");
this.imageEventText.updateBodyText("你无视了眼前的景象");
this.screen = CurScreen.END;
leave();
break;
}
case HeJiu:
if(isIn){
//buttonPressed=-1;
isIn=false;
break;
}
this.imageEventText.clearAllDialogs();
if (buttonPressed == 0) {
//喝下酒
YibaMod.logger.info("选择喝下酒");
CardCrawlGame.sound.play("EVENT_TOME");
this.imageEventText.clearAllDialogs();
//设置喝下选项
//更新喝下后的文本
this.imageEventText.updateBodyText(Drink_MSG);
//给予玩家10点伤害
YibaMod.logger.info("喝下酒:受到 10 点伤害");
AbstractDungeon.player.damage(new DamageInfo(null, 10, DamageInfo.DamageType.HP_LOSS));
this.imageEventText.clearAllDialogs();
this.imageEventText.setDialogOption("继续");
isIn=true;
YibaMod.logger.info("设置接下来为:PAGE_1");
this.screen = Restaurant.CurScreen.PAGE_1;
break;
}
case PAGE_1:
//喝下之后触发的
YibaMod.logger.info("进入PAGE_1:喝下酒后");
//CardCrawlGame.sound.play("EVENT_TOME");
this.imageEventText.clearAllDialogs();
this.imageEventText.clearRemainingOptions();
//this.imageEventText.removeDialogOption(1);
//吃下 <SUF>
this.imageEventText.setDialogOption(EAT);
//离开选项(被诅咒-三大欲望)
this.imageEventText.setDialogOption(LEAVE_NO_EAT);
this.imageEventText.updateBodyText(Eat_MSG);
if(isIn){
//buttonPressed=-1;
isIn=false;
break;
}
if(buttonPressed==0){
isIn=true;
//继续,前往第二页,触发吃下的剧情
YibaMod.logger.info("选择吃下");
//更新文本-准备吃面
CardCrawlGame.sound.play("EVENT_TOME");
//受到15点伤害
YibaMod.logger.info("吃下:受到15点伤害");
AbstractDungeon.player.damage(new DamageInfo(null, 15, DamageInfo.DamageType.HP_LOSS));
//this.damageTaken += 2;
this.imageEventText.clearAllDialogs();
this.imageEventText.clearRemainingOptions();
//吃完了,开始评价
//更新文本
this.imageEventText.updateBodyText(EatAfter_MSG);
//this.imageEventText.clearAllDialogs();
this.imageEventText.clearRemainingOptions();
this.imageEventText.setDialogOption("继续");
YibaMod.logger.info("前往PAGE_3");
this.screen = Restaurant.CurScreen.PAGE_3;
break;
}else {
isIn=true;
//更新文本提示。
YibaMod.logger.info("[离开] #r被诅咒-食雪汉。");
this.imageEventText.updateBodyText("服务员看起来非常的#y~沮丧~。。。");
//清除选项
this.imageEventText.clearRemainingOptions();
//TODO:塞一张诅咒牌。
AbstractDungeon.effectList.add(new ShowCardAndObtainEffect(new desire(), Settings.WIDTH / 2.0F, Settings.HEIGHT / 2.0F));
//打开地图
this.screen = CurScreen.END;
this.imageEventText.clearRemainingOptions();
this.imageEventText.setDialogOption("离开");
this.imageEventText.updateDialogOption(0,"离开");
this.imageEventText.removeDialogOption(1);
//leave();
break;
}
case PAGE_3:
//评价
YibaMod.logger.info("进入PAGE_3");
this.imageEventText.clearAllDialogs();
this.imageEventText.clearRemainingOptions();
this.imageEventText.setDialogOption(Evaluate_GOOD);
this.imageEventText.setDialogOption(Evaluate_NO);
this.imageEventText.updateBodyText(Evaluate_MSG);
if(isIn){
//buttonPressed=-1;
isIn=false;
break;
}
isIn=true;
if(buttonPressed==0) {
//好评
YibaMod.logger.info("好评");
this.imageEventText.clearAllDialogs();
this.imageEventText.updateBodyText(Evaluate_GOOD_MSG);
//给牛排
AbstractRelic r = (RelicLibrary.getRelic("beef").makeCopy());
(AbstractDungeon.getCurrRoom()).rewards.clear();
AbstractDungeon.getCurrRoom().addRelicToRewards(r);
(AbstractDungeon.getCurrRoom()).phase = AbstractRoom.RoomPhase.COMPLETE;
AbstractDungeon.combatRewardScreen.open();
this.screen = CurScreen.END;
}else {
//不予置评
YibaMod.logger.info("不予置评");
this.imageEventText.clearAllDialogs();
this.imageEventText.updateBodyText(Evaluate_NO_MSG);
//被诅咒-三大欲望
AbstractDungeon.effectList.add(new ShowCardAndObtainEffect(new snowman(), Settings.WIDTH / 2.0F, Settings.HEIGHT / 2.0F));
this.screen = CurScreen.END;
}
//leave();
this.imageEventText.clearRemainingOptions();
this.imageEventText.setDialogOption("离开");
this.imageEventText.updateDialogOption(0,"离开");
this.imageEventText.removeDialogOption(1);
break;
case END:
leave();
break;
}
}
}
| false | 2,222 | 4 | 2,605 | 4 | 2,621 | 4 | 2,605 | 4 | 3,477 | 7 | false | false | false | false | false | true |
59895_5 | import java.io.EOFException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
/**
* 单线程基本处理器,I/O 的读写以及业务的处理均由 Reactor 线程完成
*
* @see Reactor
* @author tongwu.net
*/
public class BasicHandler implements Runnable {
private static final int MAXIN = 1024;
private static final int MAXOUT = 1024;
public SocketChannel socket;
public SelectionKey sk;
ByteBuffer input = ByteBuffer.allocate(MAXIN);
ByteBuffer output = ByteBuffer.allocate(MAXOUT);
// 定义服务的逻辑状态
static final int READING = 0, SENDING = 1, CLOSED = 2;
int state = READING;
public BasicHandler(Selector sel, SocketChannel sc) throws IOException {
socket = sc;
sc.configureBlocking(false); // 设置非阻塞
// Optionally try first read now
sk = socket.register(sel, 0); // 注册通道
sk.interestOps(SelectionKey.OP_READ); // 绑定要处理的事件
sk.attach(this); // 管理事件的处理程序
sel.wakeup(); // 唤醒 select() 方法
}
public BasicHandler(SocketChannel sc){
socket = sc;
}
@Override
public void run() {
try {
if (state == READING)
read(); // 此时通道已经准备好读取字节
else if (state == SENDING)
send(); // 此时通道已经准备好写入字节
} catch (IOException ex) {
// 关闭连接
try {
sk.channel().close();
} catch (IOException ignore) {
}
}
}
/**
* 从通道读取字节
*/
protected void read() throws IOException {
input.clear(); // 清空接收缓冲区
int n = socket.read(input);
if (inputIsComplete(n)) {// 如果读取了完整的数据
process();
// 待发送的数据已经放入发送缓冲区中
// 更改服务的逻辑状态以及要处理的事件类型
sk.interestOps(SelectionKey.OP_WRITE);
}
}
// 缓存每次读取的内容
StringBuilder request = new StringBuilder();
/**
* 当读取到 \r\n 时表示结束
* @param bytes 读取的字节数,-1 通常是连接被关闭,0 非阻塞模式可能返回
* @throws IOException
*/
protected boolean inputIsComplete(int bytes) throws IOException {
if (bytes > 0) {
input.flip(); // 切换成读取模式
while (input.hasRemaining()) {
byte ch = input.get();
if (ch == 3) { // ctrl+c 关闭连接
state = CLOSED;
return true;
} else if (ch == '\r') { // continue
} else if (ch == '\n') {
// 读取到了 \r\n 读取结束
state = SENDING;
return true;
} else {
request.append((char)ch);
}
}
} else if (bytes == -1) {
// -1 客户端关闭了连接
throw new EOFException();
} else {} // bytes == 0 继续读取
return false;
}
/**
* 根据业务处理结果,判断如何响应
* @throws EOFException 用户输入 ctrl+c 主动关闭
*/
protected void process() throws EOFException {
if (state == CLOSED) {
throw new EOFException();
} else if (state == SENDING) {
String requestContent = request.toString(); // 请求内容
byte[] response = requestContent.getBytes(StandardCharsets.UTF_8);
output.put(response);
}
}
protected void send() throws IOException {
int written = -1;
output.flip();// 切换到读取模式,判断是否有数据要发送
if (output.hasRemaining()) {
written = socket.write(output);
}
// 检查连接是否处理完毕,是否断开连接
if (outputIsComplete(written)) {
sk.channel().close();
} else {
// 否则继续读取
state = READING;
// 把提示发到界面
socket.write(ByteBuffer.wrap("\r\nreactor> ".getBytes()));
sk.interestOps(SelectionKey.OP_READ);
}
}
/**
* 当用户输入了一个空行,表示连接可以关闭了
*/
protected boolean outputIsComplete(int written) {
if (written <= 0) {
// 用户只敲了个回车, 断开连接
return true;
}
// 清空旧数据,接着处理后续的请求
output.clear();
request.delete(0, request.length());
return false;
}
}
| chuondev/reactor | BasicHandler.java | 1,241 | // 绑定要处理的事件 | line_comment | zh-cn | import java.io.EOFException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
/**
* 单线程基本处理器,I/O 的读写以及业务的处理均由 Reactor 线程完成
*
* @see Reactor
* @author tongwu.net
*/
public class BasicHandler implements Runnable {
private static final int MAXIN = 1024;
private static final int MAXOUT = 1024;
public SocketChannel socket;
public SelectionKey sk;
ByteBuffer input = ByteBuffer.allocate(MAXIN);
ByteBuffer output = ByteBuffer.allocate(MAXOUT);
// 定义服务的逻辑状态
static final int READING = 0, SENDING = 1, CLOSED = 2;
int state = READING;
public BasicHandler(Selector sel, SocketChannel sc) throws IOException {
socket = sc;
sc.configureBlocking(false); // 设置非阻塞
// Optionally try first read now
sk = socket.register(sel, 0); // 注册通道
sk.interestOps(SelectionKey.OP_READ); // 绑定 <SUF>
sk.attach(this); // 管理事件的处理程序
sel.wakeup(); // 唤醒 select() 方法
}
public BasicHandler(SocketChannel sc){
socket = sc;
}
@Override
public void run() {
try {
if (state == READING)
read(); // 此时通道已经准备好读取字节
else if (state == SENDING)
send(); // 此时通道已经准备好写入字节
} catch (IOException ex) {
// 关闭连接
try {
sk.channel().close();
} catch (IOException ignore) {
}
}
}
/**
* 从通道读取字节
*/
protected void read() throws IOException {
input.clear(); // 清空接收缓冲区
int n = socket.read(input);
if (inputIsComplete(n)) {// 如果读取了完整的数据
process();
// 待发送的数据已经放入发送缓冲区中
// 更改服务的逻辑状态以及要处理的事件类型
sk.interestOps(SelectionKey.OP_WRITE);
}
}
// 缓存每次读取的内容
StringBuilder request = new StringBuilder();
/**
* 当读取到 \r\n 时表示结束
* @param bytes 读取的字节数,-1 通常是连接被关闭,0 非阻塞模式可能返回
* @throws IOException
*/
protected boolean inputIsComplete(int bytes) throws IOException {
if (bytes > 0) {
input.flip(); // 切换成读取模式
while (input.hasRemaining()) {
byte ch = input.get();
if (ch == 3) { // ctrl+c 关闭连接
state = CLOSED;
return true;
} else if (ch == '\r') { // continue
} else if (ch == '\n') {
// 读取到了 \r\n 读取结束
state = SENDING;
return true;
} else {
request.append((char)ch);
}
}
} else if (bytes == -1) {
// -1 客户端关闭了连接
throw new EOFException();
} else {} // bytes == 0 继续读取
return false;
}
/**
* 根据业务处理结果,判断如何响应
* @throws EOFException 用户输入 ctrl+c 主动关闭
*/
protected void process() throws EOFException {
if (state == CLOSED) {
throw new EOFException();
} else if (state == SENDING) {
String requestContent = request.toString(); // 请求内容
byte[] response = requestContent.getBytes(StandardCharsets.UTF_8);
output.put(response);
}
}
protected void send() throws IOException {
int written = -1;
output.flip();// 切换到读取模式,判断是否有数据要发送
if (output.hasRemaining()) {
written = socket.write(output);
}
// 检查连接是否处理完毕,是否断开连接
if (outputIsComplete(written)) {
sk.channel().close();
} else {
// 否则继续读取
state = READING;
// 把提示发到界面
socket.write(ByteBuffer.wrap("\r\nreactor> ".getBytes()));
sk.interestOps(SelectionKey.OP_READ);
}
}
/**
* 当用户输入了一个空行,表示连接可以关闭了
*/
protected boolean outputIsComplete(int written) {
if (written <= 0) {
// 用户只敲了个回车, 断开连接
return true;
}
// 清空旧数据,接着处理后续的请求
output.clear();
request.delete(0, request.length());
return false;
}
}
| false | 1,141 | 8 | 1,241 | 7 | 1,234 | 7 | 1,241 | 7 | 1,756 | 12 | false | false | false | false | false | true |
58562_9 | package com.todayinfo.utils;
import android.app.Activity;
import android.content.Context;
import android.widget.Toast;
import com.jinghua.todayinformation.R;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.bean.SocializeEntity;
import com.umeng.socialize.bean.StatusCode;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners.SnsPostListener;
import com.umeng.socialize.media.QQShareContent;
import com.umeng.socialize.media.QZoneShareContent;
import com.umeng.socialize.media.SinaShareContent;
import com.umeng.socialize.media.TencentWbShareContent;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.sso.QZoneSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;
import com.umeng.socialize.weixin.media.CircleShareContent;
import com.umeng.socialize.weixin.media.WeiXinShareContent;
/**
* 友盟分享工具类
*
* @author zhou.ni 2015年5月13日
*/
public class ShareUtils {
private Context mContext;
// 整个平台的Controller,负责管理整个SDK的配置、操作等处理
private final UMSocialService mController = UMServiceFactory.getUMSocialService(Contacts.DESCRIPTOR);
public ShareUtils(Context context) {
this.mContext = context;
// 配置需要分享的相关平台
configPlatforms();
mController.getConfig().setPlatforms(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE);
}
/**
* 获取分享控制对象
* @return
*/
public UMSocialService getmController() {
return mController;
}
/**
* 设置分享内容
*/
public void setShareProgram(String params,String tile, String context){
String shareTitle = tile;
String shareContext = context;
String shareUrl= createAppShareUrl();
UMImage urlImage = new UMImage(mContext, R.drawable.ic_launcher);
//微信分享
WeiXinShareContent weixinContent = new WeiXinShareContent();
weixinContent.setTitle(shareTitle);
weixinContent.setShareContent(shareContext);
weixinContent.setTargetUrl(shareUrl);
weixinContent.setShareMedia(urlImage);
mController.setShareMedia(weixinContent);
// 设置朋友圈分享的内容
CircleShareContent circleMedia = new CircleShareContent();
circleMedia.setTitle(shareTitle);
circleMedia.setShareContent(shareContext);
circleMedia.setTargetUrl(shareUrl);
circleMedia.setShareMedia(urlImage);
mController.setShareMedia(circleMedia);
// 设置QQ空间分享内容
QZoneShareContent qzone = new QZoneShareContent();
qzone.setTitle(shareTitle);
qzone.setShareContent(shareContext);
qzone.setTargetUrl(shareUrl);
qzone.setShareMedia(urlImage);
mController.setShareMedia(qzone);
//QQ分享
QQShareContent qqShareContent = new QQShareContent();
qqShareContent.setTitle(shareTitle);
qqShareContent.setShareContent(shareContext);
qqShareContent.setTargetUrl(shareUrl);
qqShareContent.setShareMedia(urlImage);
mController.setShareMedia(qqShareContent);
//腾讯微博
TencentWbShareContent tencent = new TencentWbShareContent();
tencent.setTitle(shareTitle);
tencent.setShareContent(shareContext);
tencent.setTargetUrl(shareUrl);
tencent.setShareMedia(urlImage);
mController.setShareMedia(tencent);
//新浪微博
SinaShareContent sinaContent = new SinaShareContent();
sinaContent.setTitle(shareTitle);
sinaContent.setShareContent(shareContext);
sinaContent.setTargetUrl(shareUrl);
sinaContent.setShareMedia(urlImage);
mController.setShareMedia(sinaContent);
}
/**
* 配置分享平台参数
*/
private void configPlatforms() {
// 设置新浪SSO handler
// mController.getConfig().setSsoHandler(new SinaSsoHandler());
// 添加腾讯微博SSO授权
// mController.getConfig().setSsoHandler(new TencentWBSsoHandler());
// 添加QQ、QZone平台
addQQQZonePlatform();
// 添加微信、微信朋友圈平台
addWXPlatform();
}
/**
*
* @功能描述 : 添加QQ平台支持 QQ分享的内容, 包含四种类型, 即单纯的文字、图片、音乐、视频. 参数说明 : title, summary,
* image url中必须至少设置一个, targetUrl必须设置,网页地址必须以"http://"开头 . title :
* 要分享标题 summary : 要分享的文字概述 image url : 图片地址 [以上三个参数至少填写一个] targetUrl
* : 用户点击该分享时跳转到的目标地址 [必填] ( 若不填写则默认设置为友盟主页 )
*
* 参数1为当前Activity,
* 参数2为开发者在QQ互联申请的APP ID,
* 参数3为开发者在QQ互联申请的APP kEY.
* @return
*
*/
private void addQQQZonePlatform() {
String appId = Contacts.QQ_APP_ID;
String appSecret = Contacts.QQ_APP_SECRET;
// 添加QQ支持, 并且设置QQ分享内容的target url
UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler((Activity) mContext, appId, appSecret);
qqSsoHandler.setTargetUrl("http://www.woyouwaimai.com/d");
qqSsoHandler.addToSocialSDK();
// 添加QZone平台
QZoneSsoHandler qZoneSsoHandler = new QZoneSsoHandler((Activity) mContext, appId, appSecret);
qZoneSsoHandler.addToSocialSDK();
}
/**
* @功能描述 : 添加微信平台分享
*
* @return
*/
private void addWXPlatform() {
// 注意:在微信授权的时候,必须传递appSecret
// wx967daebe835fbeac是你在微信开发平台注册应用的AppID, 这里需要替换成你注册的AppID
// String appId = Contacts.APP_ID;
// String appSecret = Contacts.APP_SECRET;
// 添加微信平台
// UMWXHandler wxHandler = new UMWXHandler(mContext, appId, appSecret);
// wxHandler.addToSocialSDK();
// wxHandler.setRefreshTokenAvailable(false);
//
// // 支持微信朋友圈
// UMWXHandler wxCircleHandler = new UMWXHandler(mContext, appId, appSecret);
// wxCircleHandler.setToCircle(true);
// wxCircleHandler.addToSocialSDK();
}
/**
* 直接分享,底层分享接口。如果分享的平台是新浪、腾讯微博、豆瓣、人人,则直接分享,无任何界面弹出; 其它平台分别启动客户端分享</br>
*/
public void directShare(SHARE_MEDIA platform) {
mController.directShare(mContext, platform, new SnsPostListener() {
@Override
public void onStart() {
}
@Override
public void onComplete(SHARE_MEDIA platform, int eCode, SocializeEntity entity) {
String showText = "分享成功";
if (eCode != StatusCode.ST_CODE_SUCCESSED) {
showText = "分享失败 [" + eCode + "]";
}
Toast.makeText(mContext, showText, Toast.LENGTH_SHORT).show();
}
});
}
public String createAppShareUrl(){
String url = "http://android.myapp.com/myapp/detail.htm?apkName=com.jinghua.todayinformation";
return url;
}
}
| chuwuwang/Todayinformation | example/src/com/todayinfo/utils/ShareUtils.java | 1,960 | //腾讯微博 | line_comment | zh-cn | package com.todayinfo.utils;
import android.app.Activity;
import android.content.Context;
import android.widget.Toast;
import com.jinghua.todayinformation.R;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.bean.SocializeEntity;
import com.umeng.socialize.bean.StatusCode;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners.SnsPostListener;
import com.umeng.socialize.media.QQShareContent;
import com.umeng.socialize.media.QZoneShareContent;
import com.umeng.socialize.media.SinaShareContent;
import com.umeng.socialize.media.TencentWbShareContent;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.sso.QZoneSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;
import com.umeng.socialize.weixin.media.CircleShareContent;
import com.umeng.socialize.weixin.media.WeiXinShareContent;
/**
* 友盟分享工具类
*
* @author zhou.ni 2015年5月13日
*/
public class ShareUtils {
private Context mContext;
// 整个平台的Controller,负责管理整个SDK的配置、操作等处理
private final UMSocialService mController = UMServiceFactory.getUMSocialService(Contacts.DESCRIPTOR);
public ShareUtils(Context context) {
this.mContext = context;
// 配置需要分享的相关平台
configPlatforms();
mController.getConfig().setPlatforms(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE);
}
/**
* 获取分享控制对象
* @return
*/
public UMSocialService getmController() {
return mController;
}
/**
* 设置分享内容
*/
public void setShareProgram(String params,String tile, String context){
String shareTitle = tile;
String shareContext = context;
String shareUrl= createAppShareUrl();
UMImage urlImage = new UMImage(mContext, R.drawable.ic_launcher);
//微信分享
WeiXinShareContent weixinContent = new WeiXinShareContent();
weixinContent.setTitle(shareTitle);
weixinContent.setShareContent(shareContext);
weixinContent.setTargetUrl(shareUrl);
weixinContent.setShareMedia(urlImage);
mController.setShareMedia(weixinContent);
// 设置朋友圈分享的内容
CircleShareContent circleMedia = new CircleShareContent();
circleMedia.setTitle(shareTitle);
circleMedia.setShareContent(shareContext);
circleMedia.setTargetUrl(shareUrl);
circleMedia.setShareMedia(urlImage);
mController.setShareMedia(circleMedia);
// 设置QQ空间分享内容
QZoneShareContent qzone = new QZoneShareContent();
qzone.setTitle(shareTitle);
qzone.setShareContent(shareContext);
qzone.setTargetUrl(shareUrl);
qzone.setShareMedia(urlImage);
mController.setShareMedia(qzone);
//QQ分享
QQShareContent qqShareContent = new QQShareContent();
qqShareContent.setTitle(shareTitle);
qqShareContent.setShareContent(shareContext);
qqShareContent.setTargetUrl(shareUrl);
qqShareContent.setShareMedia(urlImage);
mController.setShareMedia(qqShareContent);
//腾讯 <SUF>
TencentWbShareContent tencent = new TencentWbShareContent();
tencent.setTitle(shareTitle);
tencent.setShareContent(shareContext);
tencent.setTargetUrl(shareUrl);
tencent.setShareMedia(urlImage);
mController.setShareMedia(tencent);
//新浪微博
SinaShareContent sinaContent = new SinaShareContent();
sinaContent.setTitle(shareTitle);
sinaContent.setShareContent(shareContext);
sinaContent.setTargetUrl(shareUrl);
sinaContent.setShareMedia(urlImage);
mController.setShareMedia(sinaContent);
}
/**
* 配置分享平台参数
*/
private void configPlatforms() {
// 设置新浪SSO handler
// mController.getConfig().setSsoHandler(new SinaSsoHandler());
// 添加腾讯微博SSO授权
// mController.getConfig().setSsoHandler(new TencentWBSsoHandler());
// 添加QQ、QZone平台
addQQQZonePlatform();
// 添加微信、微信朋友圈平台
addWXPlatform();
}
/**
*
* @功能描述 : 添加QQ平台支持 QQ分享的内容, 包含四种类型, 即单纯的文字、图片、音乐、视频. 参数说明 : title, summary,
* image url中必须至少设置一个, targetUrl必须设置,网页地址必须以"http://"开头 . title :
* 要分享标题 summary : 要分享的文字概述 image url : 图片地址 [以上三个参数至少填写一个] targetUrl
* : 用户点击该分享时跳转到的目标地址 [必填] ( 若不填写则默认设置为友盟主页 )
*
* 参数1为当前Activity,
* 参数2为开发者在QQ互联申请的APP ID,
* 参数3为开发者在QQ互联申请的APP kEY.
* @return
*
*/
private void addQQQZonePlatform() {
String appId = Contacts.QQ_APP_ID;
String appSecret = Contacts.QQ_APP_SECRET;
// 添加QQ支持, 并且设置QQ分享内容的target url
UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler((Activity) mContext, appId, appSecret);
qqSsoHandler.setTargetUrl("http://www.woyouwaimai.com/d");
qqSsoHandler.addToSocialSDK();
// 添加QZone平台
QZoneSsoHandler qZoneSsoHandler = new QZoneSsoHandler((Activity) mContext, appId, appSecret);
qZoneSsoHandler.addToSocialSDK();
}
/**
* @功能描述 : 添加微信平台分享
*
* @return
*/
private void addWXPlatform() {
// 注意:在微信授权的时候,必须传递appSecret
// wx967daebe835fbeac是你在微信开发平台注册应用的AppID, 这里需要替换成你注册的AppID
// String appId = Contacts.APP_ID;
// String appSecret = Contacts.APP_SECRET;
// 添加微信平台
// UMWXHandler wxHandler = new UMWXHandler(mContext, appId, appSecret);
// wxHandler.addToSocialSDK();
// wxHandler.setRefreshTokenAvailable(false);
//
// // 支持微信朋友圈
// UMWXHandler wxCircleHandler = new UMWXHandler(mContext, appId, appSecret);
// wxCircleHandler.setToCircle(true);
// wxCircleHandler.addToSocialSDK();
}
/**
* 直接分享,底层分享接口。如果分享的平台是新浪、腾讯微博、豆瓣、人人,则直接分享,无任何界面弹出; 其它平台分别启动客户端分享</br>
*/
public void directShare(SHARE_MEDIA platform) {
mController.directShare(mContext, platform, new SnsPostListener() {
@Override
public void onStart() {
}
@Override
public void onComplete(SHARE_MEDIA platform, int eCode, SocializeEntity entity) {
String showText = "分享成功";
if (eCode != StatusCode.ST_CODE_SUCCESSED) {
showText = "分享失败 [" + eCode + "]";
}
Toast.makeText(mContext, showText, Toast.LENGTH_SHORT).show();
}
});
}
public String createAppShareUrl(){
String url = "http://android.myapp.com/myapp/detail.htm?apkName=com.jinghua.todayinformation";
return url;
}
}
| false | 1,738 | 3 | 1,960 | 5 | 2,022 | 3 | 1,960 | 5 | 2,664 | 9 | false | false | false | false | false | true |
13821_1 | /**
*
*/
package sophia.foundation.tick;
/**
* <b>游戏世界过去的一个时间间隔tick的监听者</b>
*
* <br>这个名字送给丢失的岁月和姑娘。:)
* <br>也可以"装B",献给马塞尔 普鲁斯特
* <br>要你是美剧迷,也可以赞下Lost
*
* <br>--- 注释?!!
*
* <br>黄昏来临的时候
* <br>我知道 您会在那儿
* <br>这已足够
* <br>命运 让人止步
* <br>却不能夺走我眼中的微笑
* <br>若爱 只是一个答案
* <br>我愿像这些花草
* <br>默默遥望
* <br>-- 摘自遥望2里无名骑士写给娜迪菲尔拉主教的一首诗 :)
* <br>
* <br>
* <br>如果你期望以给定的参数来推算时间,下面的说明你将需要注意:
* 如果因为Thread Context或者别的原因,tick形成了误差,我并没有修正该数值
* 所以给的参数是不可以信任作为游戏消逝的时间计数的。
* <br>
* 另外在{@link TickService#getStartTime()} 你可以获取到游戏世界开始的时间,如果可以,你总是
* 可以推算和比较该tick的实际误差。并总是以{@link TickService#getStartTime()}
* 来获取游戏开始的时间,和System.currentTimeMillis()配合,来获取到实际消逝的
* 游戏时间。<br>
*
* 太慢了,我们去买彩票吧<br>
* <br>-- 熊三山
* <br>-- 抢银行吧。
* <br>-- 拉皮条
*/
public interface LostedTimeListener {
public String name();
/**
* 服务关闭前的回调
*/
public void handleTickClose();
/**
* 参数其实没有意义,但每个时间都在消逝,知道消逝了多少时间很好玩。
* 免费送给所有要在losted time要做处理的代码和写代码的人。
*
* @param tickCount 过去了多少个tick
* @param intervalTime tick的单位时间,毫秒
*/
public void lostedTimeEvent(long tickCounter, long intervalTime);
}
| chuyiwen/LYZR-sever | server/sophia.foundation/src/main/java/sophia/foundation/tick/LostedTimeListener.java | 622 | /**
* 服务关闭前的回调
*/ | block_comment | zh-cn | /**
*
*/
package sophia.foundation.tick;
/**
* <b>游戏世界过去的一个时间间隔tick的监听者</b>
*
* <br>这个名字送给丢失的岁月和姑娘。:)
* <br>也可以"装B",献给马塞尔 普鲁斯特
* <br>要你是美剧迷,也可以赞下Lost
*
* <br>--- 注释?!!
*
* <br>黄昏来临的时候
* <br>我知道 您会在那儿
* <br>这已足够
* <br>命运 让人止步
* <br>却不能夺走我眼中的微笑
* <br>若爱 只是一个答案
* <br>我愿像这些花草
* <br>默默遥望
* <br>-- 摘自遥望2里无名骑士写给娜迪菲尔拉主教的一首诗 :)
* <br>
* <br>
* <br>如果你期望以给定的参数来推算时间,下面的说明你将需要注意:
* 如果因为Thread Context或者别的原因,tick形成了误差,我并没有修正该数值
* 所以给的参数是不可以信任作为游戏消逝的时间计数的。
* <br>
* 另外在{@link TickService#getStartTime()} 你可以获取到游戏世界开始的时间,如果可以,你总是
* 可以推算和比较该tick的实际误差。并总是以{@link TickService#getStartTime()}
* 来获取游戏开始的时间,和System.currentTimeMillis()配合,来获取到实际消逝的
* 游戏时间。<br>
*
* 太慢了,我们去买彩票吧<br>
* <br>-- 熊三山
* <br>-- 抢银行吧。
* <br>-- 拉皮条
*/
public interface LostedTimeListener {
public String name();
/**
* 服务关 <SUF>*/
public void handleTickClose();
/**
* 参数其实没有意义,但每个时间都在消逝,知道消逝了多少时间很好玩。
* 免费送给所有要在losted time要做处理的代码和写代码的人。
*
* @param tickCount 过去了多少个tick
* @param intervalTime tick的单位时间,毫秒
*/
public void lostedTimeEvent(long tickCounter, long intervalTime);
}
| false | 523 | 12 | 622 | 10 | 556 | 11 | 622 | 10 | 891 | 18 | false | false | false | false | false | true |
33448_1 | package com.lanou3g.testdemo.home.gallery.bean;
import java.util.List;
/**
* ┏┓ ┏┓+ +
* ┏┛┻━━━┛┻┓ + +
* ┃ ┃
* ┃ ━ ┃ ++ + + +
* ████━████ ┃+
* ┃ ┃ +
* ┃ ┻ ┃
* ┃ ┃ + +
* ┗━┓ ┏━┛
* ┃ ┃
* ┃ ┃ + + + +
* ┃ ┃ Code is far away from bug with the animal protecting
* ┃ ┃ + 神兽保佑,代码无bug
* ┃ ┃
* ┃ ┃ +
* ┃ ┗━━━┓ + +
* ┃ ┣┓
* ┃ ┏┛
* ┗┓┓┏━┳┓┏┛ + + + +
* ┃┫┫ ┃┫┫
* ┗┻┛ ┗┻┛+ + + +
* <p/>
* Created by 程洪运 on 16/10/17.
*/
public class HomeNameBean {
/**
* code : 200
* data : {"words":["礼物","婚礼礼物","礼物大礼包","成人礼礼物","礼物 男","DlY礼物盒","礼物纸盒","物袋礼","礼物袋盒","礼物男","礼物女生","礼物闺密","足球 礼物","礼物纸","礼物盒","香礼物","男礼物","买礼物","装礼物","礼物书","小礼物","礼物女","礼物的包装","迷你礼物","结果礼物"]}
* message : OK
*/
private int code;
private DataBean data;
private String message;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public DataBean getData() {
return data;
}
public void setData(DataBean data) {
this.data = data;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public static class DataBean {
private List<String> words;
public List<String> getWords() {
return words;
}
public void setWords(List<String> words) {
this.words = words;
}
}
}
| chy198720/TestDemo | app/src/main/java/com/lanou3g/testdemo/home/gallery/bean/HomeNameBean.java | 779 | /**
* code : 200
* data : {"words":["礼物","婚礼礼物","礼物大礼包","成人礼礼物","礼物 男","DlY礼物盒","礼物纸盒","物袋礼","礼物袋盒","礼物男","礼物女生","礼物闺密","足球 礼物","礼物纸","礼物盒","香礼物","男礼物","买礼物","装礼物","礼物书","小礼物","礼物女","礼物的包装","迷你礼物","结果礼物"]}
* message : OK
*/ | block_comment | zh-cn | package com.lanou3g.testdemo.home.gallery.bean;
import java.util.List;
/**
* ┏┓ ┏┓+ +
* ┏┛┻━━━┛┻┓ + +
* ┃ ┃
* ┃ ━ ┃ ++ + + +
* ████━████ ┃+
* ┃ ┃ +
* ┃ ┻ ┃
* ┃ ┃ + +
* ┗━┓ ┏━┛
* ┃ ┃
* ┃ ┃ + + + +
* ┃ ┃ Code is far away from bug with the animal protecting
* ┃ ┃ + 神兽保佑,代码无bug
* ┃ ┃
* ┃ ┃ +
* ┃ ┗━━━┓ + +
* ┃ ┣┓
* ┃ ┏┛
* ┗┓┓┏━┳┓┏┛ + + + +
* ┃┫┫ ┃┫┫
* ┗┻┛ ┗┻┛+ + + +
* <p/>
* Created by 程洪运 on 16/10/17.
*/
public class HomeNameBean {
/**
* cod <SUF>*/
private int code;
private DataBean data;
private String message;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public DataBean getData() {
return data;
}
public void setData(DataBean data) {
this.data = data;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public static class DataBean {
private List<String> words;
public List<String> getWords() {
return words;
}
public void setWords(List<String> words) {
this.words = words;
}
}
}
| false | 654 | 112 | 779 | 178 | 615 | 111 | 779 | 178 | 1,055 | 227 | false | false | false | false | false | true |
44252_16 | package leetcode.editor.cn;//罗马数字包含以下七种字符: I, V, X, L,C,D 和 M。
//
// 字符 数值
//I 1
//V 5
//X 10
//L 50
//C 100
//D 500
//M 1000
//
// 例如, 罗马数字 2 写做 II ,即为两个并列的 1。12 写做 XII ,即为 X + II 。 27 写做 XXVII, 即为 XX + V + I
//I 。
//
// 通常情况下,罗马数字中小的数字在大的数字的右边。但也存在特例,例如 4 不写做 IIII,而是 IV。数字 1 在数字 5 的左边,所表示的数等于大数 5
// 减小数 1 得到的数值 4 。同样地,数字 9 表示为 IX。这个特殊的规则只适用于以下六种情况:
//
//
// I 可以放在 V (5) 和 X (10) 的左边,来表示 4 和 9。
// X 可以放在 L (50) 和 C (100) 的左边,来表示 40 和 90。
// C 可以放在 D (500) 和 M (1000) 的左边,来表示 400 和 900。
//
//
// 给定一个罗马数字,将其转换成整数。输入确保在 1 到 3999 的范围内。
//
// 示例 1:
//
// 输入: "III"
//输出: 3
//
// 示例 2:
//
// 输入: "IV"
//输出: 4
//
// 示例 3:
//
// 输入: "IX"
//输出: 9
//
// 示例 4:
//
// 输入: "LVIII"
//输出: 58
//解释: L = 50, V= 5, III = 3.
//
//
// 示例 5:
//
// 输入: "MCMXCIV"
//输出: 1994
//解释: M = 1000, CM = 900, XC = 90, IV = 4.
// Related Topics 数学 字符串
import org.springframework.util.StringUtils;
//leetcode submit region begin(Prohibit modification and deletion)
class Solution13 {
public static void main(String[] args) {
String s = "MCMXCIV";
System.out.println(new Solution13().romanToInt(s));
// System.out.println(new Solution13().romanToInt("XXVII"));
}
/**
* //I 1
* //V 5
* //X 10
* //L 50
* //C 100
* //D 500
* //M 1000
*/
public int romanToInt(String s) {
int sum = 0;
/*
* I 可以放在 V (5) 和 X (10) 的左边,来表示 4 和 9。
* X 可以放在 L (50) 和 C (100) 的左边,来表示 40 和 90。
* C 可以放在 D (500) 和 M (1000) 的左边,来表示 400 和 900。
*/
if (s.contains("IV")) {
sum += 4;
s = s.replace("IV", "");
}
if (s.contains("IX")) {
sum += 9;
s = s.replace("IX", "");
}
if (s.contains("XL")) {
sum += 40;
s = s.replace("XL", "");
}
if (s.contains("XC")) {
sum += 90;
s = s.replace("XC", "");
}
if (s.contains("CD")) {
sum += 400;
s = s.replace("CD", "");
}
if (s.contains("CM")) {
sum += 900;
s = s.replace("CM", "");
}
char[] chars = s.toCharArray();
for (char c : chars) {
if ('I' == c) {
sum += 1;
}
if ('V' == c) {
sum += 5;
}
if ('X' == c) {
sum += 10;
}
if ('L' == c) {
sum += 50;
}
if ('C' == c) {
sum += 100;
}
if ('D' == c) {
sum += 500;
}
if ('M' == c) {
sum += 1000;
}
}
return sum;
}
}
//leetcode submit region end(Prohibit modification and deletion)
| chywx/JavaSE-chy | src/leetcode/editor/cn/[13]罗马数字转整数.java | 1,212 | // 给定一个罗马数字,将其转换成整数。输入确保在 1 到 3999 的范围内。 | line_comment | zh-cn | package leetcode.editor.cn;//罗马数字包含以下七种字符: I, V, X, L,C,D 和 M。
//
// 字符 数值
//I 1
//V 5
//X 10
//L 50
//C 100
//D 500
//M 1000
//
// 例如, 罗马数字 2 写做 II ,即为两个并列的 1。12 写做 XII ,即为 X + II 。 27 写做 XXVII, 即为 XX + V + I
//I 。
//
// 通常情况下,罗马数字中小的数字在大的数字的右边。但也存在特例,例如 4 不写做 IIII,而是 IV。数字 1 在数字 5 的左边,所表示的数等于大数 5
// 减小数 1 得到的数值 4 。同样地,数字 9 表示为 IX。这个特殊的规则只适用于以下六种情况:
//
//
// I 可以放在 V (5) 和 X (10) 的左边,来表示 4 和 9。
// X 可以放在 L (50) 和 C (100) 的左边,来表示 40 和 90。
// C 可以放在 D (500) 和 M (1000) 的左边,来表示 400 和 900。
//
//
// 给定 <SUF>
//
// 示例 1:
//
// 输入: "III"
//输出: 3
//
// 示例 2:
//
// 输入: "IV"
//输出: 4
//
// 示例 3:
//
// 输入: "IX"
//输出: 9
//
// 示例 4:
//
// 输入: "LVIII"
//输出: 58
//解释: L = 50, V= 5, III = 3.
//
//
// 示例 5:
//
// 输入: "MCMXCIV"
//输出: 1994
//解释: M = 1000, CM = 900, XC = 90, IV = 4.
// Related Topics 数学 字符串
import org.springframework.util.StringUtils;
//leetcode submit region begin(Prohibit modification and deletion)
class Solution13 {
public static void main(String[] args) {
String s = "MCMXCIV";
System.out.println(new Solution13().romanToInt(s));
// System.out.println(new Solution13().romanToInt("XXVII"));
}
/**
* //I 1
* //V 5
* //X 10
* //L 50
* //C 100
* //D 500
* //M 1000
*/
public int romanToInt(String s) {
int sum = 0;
/*
* I 可以放在 V (5) 和 X (10) 的左边,来表示 4 和 9。
* X 可以放在 L (50) 和 C (100) 的左边,来表示 40 和 90。
* C 可以放在 D (500) 和 M (1000) 的左边,来表示 400 和 900。
*/
if (s.contains("IV")) {
sum += 4;
s = s.replace("IV", "");
}
if (s.contains("IX")) {
sum += 9;
s = s.replace("IX", "");
}
if (s.contains("XL")) {
sum += 40;
s = s.replace("XL", "");
}
if (s.contains("XC")) {
sum += 90;
s = s.replace("XC", "");
}
if (s.contains("CD")) {
sum += 400;
s = s.replace("CD", "");
}
if (s.contains("CM")) {
sum += 900;
s = s.replace("CM", "");
}
char[] chars = s.toCharArray();
for (char c : chars) {
if ('I' == c) {
sum += 1;
}
if ('V' == c) {
sum += 5;
}
if ('X' == c) {
sum += 10;
}
if ('L' == c) {
sum += 50;
}
if ('C' == c) {
sum += 100;
}
if ('D' == c) {
sum += 500;
}
if ('M' == c) {
sum += 1000;
}
}
return sum;
}
}
//leetcode submit region end(Prohibit modification and deletion)
| false | 1,133 | 30 | 1,212 | 33 | 1,219 | 26 | 1,212 | 33 | 1,471 | 48 | false | false | false | false | false | true |
64574_32 | package cn.chendahai.chy.pdf;/**
* @author chy
* @date 2020/9/18 0018 上午 10:09
* Description:
*/
import com.itextpdf.text.Anchor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.draw.DottedLineSeparator;
import com.itextpdf.text.pdf.draw.LineSeparator;
import java.io.File;
import java.io.FileOutputStream;
/**
* 功能描述
*
* @author chy
* @date 2020/9/18 0018
*/
public class PdfReport {
// main测试
public static void main(String[] args) throws Exception {
try {
// 1.新建document对象
Document document = new Document(PageSize.A4);// 建立一个Document对象
// 2.建立一个书写器(Writer)与document对象关联
File file = new File("D:\\cn.chendahai.chy.pdf\\PDFDemo.cn.chendahai.chy.pdf");
file.createNewFile();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
writer.setPageEvent(new Watermark("HELLO ITEXTPDF"));// 水印
writer.setPageEvent(new MyHeaderFooter());// 页眉/页脚
// 3.打开文档
document.open();
document.addTitle("Title@PDF-Java");// 标题
document.addAuthor("Author@umiz");// 作者
document.addSubject("Subject@iText cn.chendahai.chy.pdf sample");// 主题
document.addKeywords("Keywords@iTextpdf");// 关键字
document.addCreator("Creator@umiz`s");// 创建者
// 4.向文档中添加内容
new PdfReport().generatePDF(document);
// 5.关闭文档
document.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// 定义全局的字体静态变量
private static Font titlefont;
private static Font headfont;
private static Font keyfont;
private static Font textfont;
// 最大宽度
private static int maxWidth = 520;
// 静态代码块
static {
try {
// 不同字体(这里定义为同一种字体:包含不同字号、不同style)
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
titlefont = new Font(bfChinese, 16, Font.BOLD);
headfont = new Font(bfChinese, 14, Font.BOLD);
keyfont = new Font(bfChinese, 10, Font.BOLD);
textfont = new Font(bfChinese, 10, Font.NORMAL);
} catch (Exception e) {
e.printStackTrace();
}
}
// 生成PDF文件
public void generatePDF(Document document) throws Exception {
// 段落
Paragraph paragraph = new Paragraph("美好的一天从早起开始!", titlefont);
paragraph.setAlignment(1); //设置文字居中 0靠左 1,居中 2,靠右
paragraph.setIndentationLeft(12); //设置左缩进
paragraph.setIndentationRight(12); //设置右缩进
paragraph.setFirstLineIndent(24); //设置首行缩进
paragraph.setLeading(20f); //行间距
paragraph.setSpacingBefore(5f); //设置段落上空白
paragraph.setSpacingAfter(10f); //设置段落下空白
// 直线
Paragraph p1 = new Paragraph();
p1.add(new Chunk(new LineSeparator()));
// 点线
Paragraph p2 = new Paragraph();
p2.add(new Chunk(new DottedLineSeparator()));
// 超链接
Anchor anchor = new Anchor("baidu");
anchor.setReference("www.baidu.com");
// 定位
Anchor gotoP = new Anchor("goto");
gotoP.setReference("#top");
// 添加图片
Image image = Image
.getInstance("https://img-blog.csdn.net/20180801174617455?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl8zNzg0ODcxMA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70");
image.setAlignment(Image.ALIGN_CENTER);
image.scalePercent(40); //依照比例缩放
// 表格
PdfPTable table = createTable(new float[]{40, 120, 120, 120, 80, 80});
table.addCell(createCell("美好的一天", headfont, Element.ALIGN_LEFT, 6, false));
table.addCell(createCell("早上9:00", keyfont, Element.ALIGN_CENTER));
table.addCell(createCell("中午11:00", keyfont, Element.ALIGN_CENTER));
table.addCell(createCell("中午13:00", keyfont, Element.ALIGN_CENTER));
table.addCell(createCell("下午15:00", keyfont, Element.ALIGN_CENTER));
table.addCell(createCell("下午17:00", keyfont, Element.ALIGN_CENTER));
table.addCell(createCell("晚上19:00", keyfont, Element.ALIGN_CENTER));
Integer totalQuantity = 0;
for (int i = 0; i < 5; i++) {
table.addCell(createCell("起床", textfont));
table.addCell(createCell("吃午饭", textfont));
table.addCell(createCell("午休", textfont));
table.addCell(createCell("下午茶", textfont));
table.addCell(createCell("回家", textfont));
table.addCell(createCell("吃晚饭", textfont));
totalQuantity++;
}
table.addCell(createCell("总计", keyfont));
table.addCell(createCell("", textfont));
table.addCell(createCell("", textfont));
table.addCell(createCell("", textfont));
table.addCell(createCell(String.valueOf(totalQuantity) + "件事", textfont));
table.addCell(createCell("", textfont));
document.add(paragraph);
document.add(anchor);
document.add(p2);
document.add(gotoP);
document.add(p1);
document.add(table);
document.add(image);
}
/**------------------------创建表格单元格的方法start----------------------------*/
/**
* 创建单元格(指定字体)
*/
public PdfPCell createCell(String value, Font font) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setPhrase(new Phrase(value, font));
return cell;
}
/**
* 创建单元格(指定字体、水平..)
*/
public PdfPCell createCell(String value, Font font, int align) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(align);
cell.setPhrase(new Phrase(value, font));
return cell;
}
/**
* 创建单元格(指定字体、水平居..、单元格跨x列合并)
*/
public PdfPCell createCell(String value, Font font, int align, int colspan) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(align);
cell.setColspan(colspan);
cell.setPhrase(new Phrase(value, font));
return cell;
}
/**
* 创建单元格(指定字体、水平居..、单元格跨x列合并、设置单元格内边距)
*/
public PdfPCell createCell(String value, Font font, int align, int colspan, boolean boderFlag) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(align);
cell.setColspan(colspan);
cell.setPhrase(new Phrase(value, font));
cell.setPadding(3.0f);
if (!boderFlag) {
cell.setBorder(0);
cell.setPaddingTop(15.0f);
cell.setPaddingBottom(8.0f);
} else if (boderFlag) {
cell.setBorder(0);
cell.setPaddingTop(0.0f);
cell.setPaddingBottom(15.0f);
}
return cell;
}
/**
* 创建单元格(指定字体、水平..、边框宽度:0表示无边框、内边距)
*/
public PdfPCell createCell(String value, Font font, int align, float[] borderWidth, float[] paddingSize, boolean flag) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(align);
cell.setPhrase(new Phrase(value, font));
cell.setBorderWidthLeft(borderWidth[0]);
cell.setBorderWidthRight(borderWidth[1]);
cell.setBorderWidthTop(borderWidth[2]);
cell.setBorderWidthBottom(borderWidth[3]);
cell.setPaddingTop(paddingSize[0]);
cell.setPaddingBottom(paddingSize[1]);
if (flag) {
cell.setColspan(2);
}
return cell;
}
/**------------------------创建表格单元格的方法end----------------------------*/
/**--------------------------创建表格的方法start------------------- ---------*/
/**
* 创建默认列宽,指定列数、水平(居中、右、左)的表格
*/
public PdfPTable createTable(int colNumber, int align) {
PdfPTable table = new PdfPTable(colNumber);
try {
table.setTotalWidth(maxWidth);
table.setLockedWidth(true);
table.setHorizontalAlignment(align);
table.getDefaultCell().setBorder(1);
} catch (Exception e) {
e.printStackTrace();
}
return table;
}
/**
* 创建指定列宽、列数的表格
*/
public PdfPTable createTable(float[] widths) {
PdfPTable table = new PdfPTable(widths);
try {
table.setTotalWidth(maxWidth);
table.setLockedWidth(true);
table.setHorizontalAlignment(Element.ALIGN_CENTER);
table.getDefaultCell().setBorder(1);
} catch (Exception e) {
e.printStackTrace();
}
return table;
}
/**
* 创建空白的表格
*/
public PdfPTable createBlankTable() {
PdfPTable table = new PdfPTable(1);
table.getDefaultCell().setBorder(0);
table.addCell(createCell("", keyfont));
table.setSpacingAfter(20.0f);
table.setSpacingBefore(20.0f);
return table;
}
/**--------------------------创建表格的方法end------------------- ---------*/
}
| chywx/spring-boot-chy | chy-generate-pdf/src/main/java/cn/chendahai/chy/pdf/PdfReport.java | 2,834 | /**
* 创建单元格(指定字体、水平居..、单元格跨x列合并、设置单元格内边距)
*/ | block_comment | zh-cn | package cn.chendahai.chy.pdf;/**
* @author chy
* @date 2020/9/18 0018 上午 10:09
* Description:
*/
import com.itextpdf.text.Anchor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.draw.DottedLineSeparator;
import com.itextpdf.text.pdf.draw.LineSeparator;
import java.io.File;
import java.io.FileOutputStream;
/**
* 功能描述
*
* @author chy
* @date 2020/9/18 0018
*/
public class PdfReport {
// main测试
public static void main(String[] args) throws Exception {
try {
// 1.新建document对象
Document document = new Document(PageSize.A4);// 建立一个Document对象
// 2.建立一个书写器(Writer)与document对象关联
File file = new File("D:\\cn.chendahai.chy.pdf\\PDFDemo.cn.chendahai.chy.pdf");
file.createNewFile();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
writer.setPageEvent(new Watermark("HELLO ITEXTPDF"));// 水印
writer.setPageEvent(new MyHeaderFooter());// 页眉/页脚
// 3.打开文档
document.open();
document.addTitle("Title@PDF-Java");// 标题
document.addAuthor("Author@umiz");// 作者
document.addSubject("Subject@iText cn.chendahai.chy.pdf sample");// 主题
document.addKeywords("Keywords@iTextpdf");// 关键字
document.addCreator("Creator@umiz`s");// 创建者
// 4.向文档中添加内容
new PdfReport().generatePDF(document);
// 5.关闭文档
document.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// 定义全局的字体静态变量
private static Font titlefont;
private static Font headfont;
private static Font keyfont;
private static Font textfont;
// 最大宽度
private static int maxWidth = 520;
// 静态代码块
static {
try {
// 不同字体(这里定义为同一种字体:包含不同字号、不同style)
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
titlefont = new Font(bfChinese, 16, Font.BOLD);
headfont = new Font(bfChinese, 14, Font.BOLD);
keyfont = new Font(bfChinese, 10, Font.BOLD);
textfont = new Font(bfChinese, 10, Font.NORMAL);
} catch (Exception e) {
e.printStackTrace();
}
}
// 生成PDF文件
public void generatePDF(Document document) throws Exception {
// 段落
Paragraph paragraph = new Paragraph("美好的一天从早起开始!", titlefont);
paragraph.setAlignment(1); //设置文字居中 0靠左 1,居中 2,靠右
paragraph.setIndentationLeft(12); //设置左缩进
paragraph.setIndentationRight(12); //设置右缩进
paragraph.setFirstLineIndent(24); //设置首行缩进
paragraph.setLeading(20f); //行间距
paragraph.setSpacingBefore(5f); //设置段落上空白
paragraph.setSpacingAfter(10f); //设置段落下空白
// 直线
Paragraph p1 = new Paragraph();
p1.add(new Chunk(new LineSeparator()));
// 点线
Paragraph p2 = new Paragraph();
p2.add(new Chunk(new DottedLineSeparator()));
// 超链接
Anchor anchor = new Anchor("baidu");
anchor.setReference("www.baidu.com");
// 定位
Anchor gotoP = new Anchor("goto");
gotoP.setReference("#top");
// 添加图片
Image image = Image
.getInstance("https://img-blog.csdn.net/20180801174617455?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl8zNzg0ODcxMA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70");
image.setAlignment(Image.ALIGN_CENTER);
image.scalePercent(40); //依照比例缩放
// 表格
PdfPTable table = createTable(new float[]{40, 120, 120, 120, 80, 80});
table.addCell(createCell("美好的一天", headfont, Element.ALIGN_LEFT, 6, false));
table.addCell(createCell("早上9:00", keyfont, Element.ALIGN_CENTER));
table.addCell(createCell("中午11:00", keyfont, Element.ALIGN_CENTER));
table.addCell(createCell("中午13:00", keyfont, Element.ALIGN_CENTER));
table.addCell(createCell("下午15:00", keyfont, Element.ALIGN_CENTER));
table.addCell(createCell("下午17:00", keyfont, Element.ALIGN_CENTER));
table.addCell(createCell("晚上19:00", keyfont, Element.ALIGN_CENTER));
Integer totalQuantity = 0;
for (int i = 0; i < 5; i++) {
table.addCell(createCell("起床", textfont));
table.addCell(createCell("吃午饭", textfont));
table.addCell(createCell("午休", textfont));
table.addCell(createCell("下午茶", textfont));
table.addCell(createCell("回家", textfont));
table.addCell(createCell("吃晚饭", textfont));
totalQuantity++;
}
table.addCell(createCell("总计", keyfont));
table.addCell(createCell("", textfont));
table.addCell(createCell("", textfont));
table.addCell(createCell("", textfont));
table.addCell(createCell(String.valueOf(totalQuantity) + "件事", textfont));
table.addCell(createCell("", textfont));
document.add(paragraph);
document.add(anchor);
document.add(p2);
document.add(gotoP);
document.add(p1);
document.add(table);
document.add(image);
}
/**------------------------创建表格单元格的方法start----------------------------*/
/**
* 创建单元格(指定字体)
*/
public PdfPCell createCell(String value, Font font) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setPhrase(new Phrase(value, font));
return cell;
}
/**
* 创建单元格(指定字体、水平..)
*/
public PdfPCell createCell(String value, Font font, int align) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(align);
cell.setPhrase(new Phrase(value, font));
return cell;
}
/**
* 创建单元格(指定字体、水平居..、单元格跨x列合并)
*/
public PdfPCell createCell(String value, Font font, int align, int colspan) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(align);
cell.setColspan(colspan);
cell.setPhrase(new Phrase(value, font));
return cell;
}
/**
* 创建单 <SUF>*/
public PdfPCell createCell(String value, Font font, int align, int colspan, boolean boderFlag) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(align);
cell.setColspan(colspan);
cell.setPhrase(new Phrase(value, font));
cell.setPadding(3.0f);
if (!boderFlag) {
cell.setBorder(0);
cell.setPaddingTop(15.0f);
cell.setPaddingBottom(8.0f);
} else if (boderFlag) {
cell.setBorder(0);
cell.setPaddingTop(0.0f);
cell.setPaddingBottom(15.0f);
}
return cell;
}
/**
* 创建单元格(指定字体、水平..、边框宽度:0表示无边框、内边距)
*/
public PdfPCell createCell(String value, Font font, int align, float[] borderWidth, float[] paddingSize, boolean flag) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(align);
cell.setPhrase(new Phrase(value, font));
cell.setBorderWidthLeft(borderWidth[0]);
cell.setBorderWidthRight(borderWidth[1]);
cell.setBorderWidthTop(borderWidth[2]);
cell.setBorderWidthBottom(borderWidth[3]);
cell.setPaddingTop(paddingSize[0]);
cell.setPaddingBottom(paddingSize[1]);
if (flag) {
cell.setColspan(2);
}
return cell;
}
/**------------------------创建表格单元格的方法end----------------------------*/
/**--------------------------创建表格的方法start------------------- ---------*/
/**
* 创建默认列宽,指定列数、水平(居中、右、左)的表格
*/
public PdfPTable createTable(int colNumber, int align) {
PdfPTable table = new PdfPTable(colNumber);
try {
table.setTotalWidth(maxWidth);
table.setLockedWidth(true);
table.setHorizontalAlignment(align);
table.getDefaultCell().setBorder(1);
} catch (Exception e) {
e.printStackTrace();
}
return table;
}
/**
* 创建指定列宽、列数的表格
*/
public PdfPTable createTable(float[] widths) {
PdfPTable table = new PdfPTable(widths);
try {
table.setTotalWidth(maxWidth);
table.setLockedWidth(true);
table.setHorizontalAlignment(Element.ALIGN_CENTER);
table.getDefaultCell().setBorder(1);
} catch (Exception e) {
e.printStackTrace();
}
return table;
}
/**
* 创建空白的表格
*/
public PdfPTable createBlankTable() {
PdfPTable table = new PdfPTable(1);
table.getDefaultCell().setBorder(0);
table.addCell(createCell("", keyfont));
table.setSpacingAfter(20.0f);
table.setSpacingBefore(20.0f);
return table;
}
/**--------------------------创建表格的方法end------------------- ---------*/
}
| false | 2,434 | 30 | 2,834 | 32 | 2,865 | 32 | 2,834 | 32 | 3,505 | 46 | false | false | false | false | false | true |
17417_6 | package step3;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import bean.Porn;
import util.DBConnection;
/**
*
* @ClassName: 91porn
* @Description: 91porn地址解析
* @author zeze
* @date 2016年06月30日 下午7:55:31
*
*/
public class porn91 {
private static String cookie = "incap_ses_434_649914=b6wiYWlZCwyvOk0txuAFBpw0klcAAAAABCNLfzLz0yYsdc/ZwCAMew==; incap_ses_199_649914=HMiecuja1EF/zwrg4f3CAp40klcAAAAAxstF0rtRgLC7l8GwLgddKg==; _gat=1; visid_incap_649914=eSwhoweRTuyfzZcnQLWQTJw0klcAAAAAQUIPAAAAAACu1mAvclWw5XFVzr7y3Hu6; incap_ses_401_649914=36h4WlhcjEzW4AYrA6SQBWo1klcAAAAAhWaF7GkLdpvrgBgY6Kgonw==; _ga=GA1.2.2130541701.1469199521; session=eyJfZnJlc2giOmZhbHNlLCJjc3JmX3Rva2VuIjp7IiBiIjoiTURSbU16VmhOekppWkRVd01tSm1ZVEl4TlRRd1ltVTRNakptTURVM016Tm1ZbUZsTmpOak5BPT0ifX0.CnPHAQ.ZC00C8p69e3CXePhWAIAnQj6bMM";
private static String Token = "1469203344##2709a3bff2e04495d88ee0372e37b6a474221e17";
private static String cookie2 = "incap_ses_434_649914=b6wiYWlZCwyvOk0txuAFBpw0klcAAAAABCNLfzLz0yYsdc/ZwCAMew==; incap_ses_199_649914=HMiecuja1EF/zwrg4f3CAp40klcAAAAAxstF0rtRgLC7l8GwLgddKg==; _gat=1; visid_incap_649914=eSwhoweRTuyfzZcnQLWQTJw0klcAAAAAQUIPAAAAAACu1mAvclWw5XFVzr7y3Hu6; incap_ses_401_649914=36h4WlhcjEzW4AYrA6SQBWo1klcAAAAAhWaF7GkLdpvrgBgY6Kgonw==; _ga=GA1.2.2130541701.1469199521; session=eyJfZnJlc2giOmZhbHNlLCJjc3JmX3Rva2VuIjp7IiBiIjoiTURSbU16VmhOekppWkRVd01tSm1ZVEl4TlRRd1ltVTRNakptTURVM016Tm1ZbUZsTmpOak5BPT0ifX0.CnPHBA.JZpgvatB2fzsd5esaZeu7q0Scqw";
private static int jumpNum=0;
private static String Url = "http://freeget.co/video/extraction";
private static String url001 = null;
private static int cnt0 = 0;
private static String num = null;
private static String title = null;
private static String time = null;
private static String longtime = null;
private static String viewnum = null;
private static String Parurl = null;// "http://www.91porn.com/view_video.php?viewkey=c5ec60d0da8c8fbdb180&page=4&viewtype=basic&category=mr";
public static void main(String[] args) throws InterruptedException {
List<Porn> pornList = new ArrayList<Porn>();
pornList = QueryRemainUrl();
Iterator<Porn> pornsList2 = pornList.iterator();
Porn porn = new Porn();
int cnt = 0;
while (pornsList2.hasNext()) {
porn = (Porn) pornsList2.next();
cnt++;
if(cnt<=jumpNum)continue;//跳过的数目
num = porn.getNum();
title = porn.getTitle();
time = porn.getTime();
longtime = porn.getLongtime();
viewnum = porn.getViewnum();
Parurl = porn.getParurl();
System.out.println(cnt+":"+num + "," + title + "," + time + "," + Parurl);
func_step1();
}
System.out.println("采集结束,总共:" + cnt + "条,成功写入" + cnt0 + "条");
}
private static void func_step1() {
HttpClient httpClient = new HttpClient();
try {
PostMethod postMethod = new PostMethod(Url);
postMethod.getParams().setContentCharset("utf-8");
// 每次访问需授权的网址时需 cookie 作为通行证
postMethod.setRequestHeader("cookie", cookie);
postMethod.setRequestHeader("X-CSRFToken", Token);
postMethod.setRequestHeader("Accept-Language", "zh-CN,zh;q=0.8");
postMethod.setRequestHeader("Host", "freeget.co");
postMethod.setRequestHeader("Referer", "http://freeget.co/");
postMethod.setRequestHeader("User-Agent",
"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0) QQBrowser/9.2.5063.400");
postMethod.setParameter("url", Parurl);
int statusCode = httpClient.executeMethod(postMethod);// 返回状态码200为成功,500为服务器端发生运行错误
System.out.println("返回状态码:" + statusCode);
// 打印出返回数据,检验一下是否成功
if (statusCode == 404) {
System.err.println("未找到对应视频信息,可能该视频尚未收录或已被删除");
}
if (statusCode == 400) {
System.err.println("Bad Request,请更新cookies");
}
String result = postMethod.getResponseBodyAsString();
if (statusCode == 200) {
// 解析成功,取得token和view_key
JSONObject a = new JSONObject(result);
url001 = "http://freeget.co/video/" + a.get("view_key") + "/" + a.get("token");
System.out.println("视频解析地址:" + url001);
func_step2(url001);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static void func_step2(String url) {
HttpClient httpClient = new HttpClient();
try {
GetMethod getMethod = new GetMethod(url);
getMethod.getParams().setContentCharset("utf-8");
getMethod.setRequestHeader("cookie", cookie2);
getMethod.setRequestHeader("Accept-Language", "zh-cn");
getMethod.setRequestHeader("User-Agent",
"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0) QQBrowser/9.2.5063.400");
int statusCode = httpClient.executeMethod(getMethod);// 返回状态码200为成功,500为服务器端发生运行错误
// System.out.println("返回状态码:" + statusCode);
// 打印出返回数据,检验一下是否成功
InputStream inputStream = getMethod.getResponseBodyAsStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer stringBuffer = new StringBuffer();
String str = "";
while ((str = br.readLine()) != null) {
stringBuffer.append(str);
}
if (statusCode == 200) {
Document doc = Jsoup.parse(stringBuffer.toString());
Elements name = doc.select("a");
String playurl = null;
try {
playurl = name.get(4).text();
} catch (Exception e) {
// TODO: handle exception
System.err.println("获取播放地址失败!,请更新cookies!");
}
if (playurl.indexOf("VID") != -1) {
System.out.println("在线播放地址:" + playurl);
UpdataUrl(playurl);
cnt0++;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
// 查询数据库
public static void UpdataUrl(String playurl) {
java.sql.Connection connection = DBConnection.getConnection();
String sql = null;
sql = "update porn set playurl='" + playurl + "',status=1 where id=" + num;
// System.out.println(sql);
java.sql.PreparedStatement pstmt = DBConnection.getPreparedStatement(connection, sql);
try {
pstmt.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBConnection.close(connection, pstmt, null);
}
return;
}
public static List<Porn> QueryRemainUrl() {
java.sql.Connection connection = DBConnection.getConnection();
String sql = "select * from porn where status=0";
java.sql.PreparedStatement pstmt = DBConnection.getPreparedStatement(connection, sql);
List<Porn> pornlist = new ArrayList<Porn>();
System.out.println(sql);
try {
Statement stmt = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
java.sql.ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
Porn porn = new Porn();
porn.setNum(rs.getString(1));
porn.setTitle(rs.getString(2));
porn.setTime(rs.getString(3));
porn.setViewkey(rs.getString(4));
porn.setLongtime(rs.getString(5));
porn.setViewnum(rs.getString(6));
porn.setParurl(rs.getString(7));
pornlist.add(porn);
}
rs.last();
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBConnection.close(connection, pstmt, null);
}
return pornlist;
}
}
| chzeze/Online-Vedio-Extract | porn91.java | 2,869 | // 返回状态码200为成功,500为服务器端发生运行错误 | line_comment | zh-cn | package step3;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import bean.Porn;
import util.DBConnection;
/**
*
* @ClassName: 91porn
* @Description: 91porn地址解析
* @author zeze
* @date 2016年06月30日 下午7:55:31
*
*/
public class porn91 {
private static String cookie = "incap_ses_434_649914=b6wiYWlZCwyvOk0txuAFBpw0klcAAAAABCNLfzLz0yYsdc/ZwCAMew==; incap_ses_199_649914=HMiecuja1EF/zwrg4f3CAp40klcAAAAAxstF0rtRgLC7l8GwLgddKg==; _gat=1; visid_incap_649914=eSwhoweRTuyfzZcnQLWQTJw0klcAAAAAQUIPAAAAAACu1mAvclWw5XFVzr7y3Hu6; incap_ses_401_649914=36h4WlhcjEzW4AYrA6SQBWo1klcAAAAAhWaF7GkLdpvrgBgY6Kgonw==; _ga=GA1.2.2130541701.1469199521; session=eyJfZnJlc2giOmZhbHNlLCJjc3JmX3Rva2VuIjp7IiBiIjoiTURSbU16VmhOekppWkRVd01tSm1ZVEl4TlRRd1ltVTRNakptTURVM016Tm1ZbUZsTmpOak5BPT0ifX0.CnPHAQ.ZC00C8p69e3CXePhWAIAnQj6bMM";
private static String Token = "1469203344##2709a3bff2e04495d88ee0372e37b6a474221e17";
private static String cookie2 = "incap_ses_434_649914=b6wiYWlZCwyvOk0txuAFBpw0klcAAAAABCNLfzLz0yYsdc/ZwCAMew==; incap_ses_199_649914=HMiecuja1EF/zwrg4f3CAp40klcAAAAAxstF0rtRgLC7l8GwLgddKg==; _gat=1; visid_incap_649914=eSwhoweRTuyfzZcnQLWQTJw0klcAAAAAQUIPAAAAAACu1mAvclWw5XFVzr7y3Hu6; incap_ses_401_649914=36h4WlhcjEzW4AYrA6SQBWo1klcAAAAAhWaF7GkLdpvrgBgY6Kgonw==; _ga=GA1.2.2130541701.1469199521; session=eyJfZnJlc2giOmZhbHNlLCJjc3JmX3Rva2VuIjp7IiBiIjoiTURSbU16VmhOekppWkRVd01tSm1ZVEl4TlRRd1ltVTRNakptTURVM016Tm1ZbUZsTmpOak5BPT0ifX0.CnPHBA.JZpgvatB2fzsd5esaZeu7q0Scqw";
private static int jumpNum=0;
private static String Url = "http://freeget.co/video/extraction";
private static String url001 = null;
private static int cnt0 = 0;
private static String num = null;
private static String title = null;
private static String time = null;
private static String longtime = null;
private static String viewnum = null;
private static String Parurl = null;// "http://www.91porn.com/view_video.php?viewkey=c5ec60d0da8c8fbdb180&page=4&viewtype=basic&category=mr";
public static void main(String[] args) throws InterruptedException {
List<Porn> pornList = new ArrayList<Porn>();
pornList = QueryRemainUrl();
Iterator<Porn> pornsList2 = pornList.iterator();
Porn porn = new Porn();
int cnt = 0;
while (pornsList2.hasNext()) {
porn = (Porn) pornsList2.next();
cnt++;
if(cnt<=jumpNum)continue;//跳过的数目
num = porn.getNum();
title = porn.getTitle();
time = porn.getTime();
longtime = porn.getLongtime();
viewnum = porn.getViewnum();
Parurl = porn.getParurl();
System.out.println(cnt+":"+num + "," + title + "," + time + "," + Parurl);
func_step1();
}
System.out.println("采集结束,总共:" + cnt + "条,成功写入" + cnt0 + "条");
}
private static void func_step1() {
HttpClient httpClient = new HttpClient();
try {
PostMethod postMethod = new PostMethod(Url);
postMethod.getParams().setContentCharset("utf-8");
// 每次访问需授权的网址时需 cookie 作为通行证
postMethod.setRequestHeader("cookie", cookie);
postMethod.setRequestHeader("X-CSRFToken", Token);
postMethod.setRequestHeader("Accept-Language", "zh-CN,zh;q=0.8");
postMethod.setRequestHeader("Host", "freeget.co");
postMethod.setRequestHeader("Referer", "http://freeget.co/");
postMethod.setRequestHeader("User-Agent",
"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0) QQBrowser/9.2.5063.400");
postMethod.setParameter("url", Parurl);
int statusCode = httpClient.executeMethod(postMethod);// 返回 <SUF>
System.out.println("返回状态码:" + statusCode);
// 打印出返回数据,检验一下是否成功
if (statusCode == 404) {
System.err.println("未找到对应视频信息,可能该视频尚未收录或已被删除");
}
if (statusCode == 400) {
System.err.println("Bad Request,请更新cookies");
}
String result = postMethod.getResponseBodyAsString();
if (statusCode == 200) {
// 解析成功,取得token和view_key
JSONObject a = new JSONObject(result);
url001 = "http://freeget.co/video/" + a.get("view_key") + "/" + a.get("token");
System.out.println("视频解析地址:" + url001);
func_step2(url001);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static void func_step2(String url) {
HttpClient httpClient = new HttpClient();
try {
GetMethod getMethod = new GetMethod(url);
getMethod.getParams().setContentCharset("utf-8");
getMethod.setRequestHeader("cookie", cookie2);
getMethod.setRequestHeader("Accept-Language", "zh-cn");
getMethod.setRequestHeader("User-Agent",
"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0) QQBrowser/9.2.5063.400");
int statusCode = httpClient.executeMethod(getMethod);// 返回状态码200为成功,500为服务器端发生运行错误
// System.out.println("返回状态码:" + statusCode);
// 打印出返回数据,检验一下是否成功
InputStream inputStream = getMethod.getResponseBodyAsStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer stringBuffer = new StringBuffer();
String str = "";
while ((str = br.readLine()) != null) {
stringBuffer.append(str);
}
if (statusCode == 200) {
Document doc = Jsoup.parse(stringBuffer.toString());
Elements name = doc.select("a");
String playurl = null;
try {
playurl = name.get(4).text();
} catch (Exception e) {
// TODO: handle exception
System.err.println("获取播放地址失败!,请更新cookies!");
}
if (playurl.indexOf("VID") != -1) {
System.out.println("在线播放地址:" + playurl);
UpdataUrl(playurl);
cnt0++;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
// 查询数据库
public static void UpdataUrl(String playurl) {
java.sql.Connection connection = DBConnection.getConnection();
String sql = null;
sql = "update porn set playurl='" + playurl + "',status=1 where id=" + num;
// System.out.println(sql);
java.sql.PreparedStatement pstmt = DBConnection.getPreparedStatement(connection, sql);
try {
pstmt.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBConnection.close(connection, pstmt, null);
}
return;
}
public static List<Porn> QueryRemainUrl() {
java.sql.Connection connection = DBConnection.getConnection();
String sql = "select * from porn where status=0";
java.sql.PreparedStatement pstmt = DBConnection.getPreparedStatement(connection, sql);
List<Porn> pornlist = new ArrayList<Porn>();
System.out.println(sql);
try {
Statement stmt = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
java.sql.ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
Porn porn = new Porn();
porn.setNum(rs.getString(1));
porn.setTitle(rs.getString(2));
porn.setTime(rs.getString(3));
porn.setViewkey(rs.getString(4));
porn.setLongtime(rs.getString(5));
porn.setViewnum(rs.getString(6));
porn.setParurl(rs.getString(7));
pornlist.add(porn);
}
rs.last();
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBConnection.close(connection, pstmt, null);
}
return pornlist;
}
}
| false | 2,503 | 19 | 2,869 | 19 | 2,789 | 19 | 2,869 | 19 | 3,540 | 32 | false | false | false | false | false | true |
44759_1 | package cn.ccy.leetcode.archive_202209;
/**
* @author caochengyin
* @version v 1.0.0
* @date 2022/10/31
* @description https://leetcode.cn/problems/magical-string/
* 双十一大促来啦,开门红!阿弥陀佛,㊗️顺利!
*/
public class MagicalString {
public static void main(String[] args) {
System.out.println(new MagicalString().magicalString(6));
}
//双指针
public int magicalString(int n) {
if (n < 4) {
return 1;
}
char[] s = new char[n];
s[0] = '1';
s[1] = '2';
s[2] = '2';
int res = 1;
int i = 2;
int j = 3;
while (j < n) {
int size = s[i] - '0';
int num = 3 - (s[j - 1] - '0');
while (size > 0 && j < n) {
s[j] = (char) ('0' + num);
if (num == 1) {
++res;
}
++j;
--size;
}
++i;
}
return res;
}
}
| ciao-cao-offical/creek | creek-java/src/main/java/cn/ccy/leetcode/archive_202209/MagicalString.java | 340 | //双指针 | line_comment | zh-cn | package cn.ccy.leetcode.archive_202209;
/**
* @author caochengyin
* @version v 1.0.0
* @date 2022/10/31
* @description https://leetcode.cn/problems/magical-string/
* 双十一大促来啦,开门红!阿弥陀佛,㊗️顺利!
*/
public class MagicalString {
public static void main(String[] args) {
System.out.println(new MagicalString().magicalString(6));
}
//双指 <SUF>
public int magicalString(int n) {
if (n < 4) {
return 1;
}
char[] s = new char[n];
s[0] = '1';
s[1] = '2';
s[2] = '2';
int res = 1;
int i = 2;
int j = 3;
while (j < n) {
int size = s[i] - '0';
int num = 3 - (s[j - 1] - '0');
while (size > 0 && j < n) {
s[j] = (char) ('0' + num);
if (num == 1) {
++res;
}
++j;
--size;
}
++i;
}
return res;
}
}
| false | 308 | 4 | 340 | 3 | 352 | 3 | 340 | 3 | 388 | 6 | false | false | false | false | false | true |
30508_1 | /*
* QAuxiliary - An Xposed module for QQ/TIM
* Copyright (C) 2019-2023 QAuxiliary developers
* https://github.com/cinit/QAuxiliary
*
* This software is non-free but opensource software: you can redistribute it
* and/or modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; either
* version 3 of the License, or any later version and our eula as published
* by QAuxiliary contributors.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* and eula along with this software. If not, see
* <https://www.gnu.org/licenses/>
* <https://github.com/cinit/QAuxiliary/blob/master/LICENSE.md>.
*/
package top.linl.hook;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import cc.ioctl.util.HookUtils;
import de.robv.android.xposed.XC_MethodHook;
import io.github.qauxv.base.annotation.FunctionHookEntry;
import io.github.qauxv.base.annotation.UiItemAgentEntry;
import io.github.qauxv.dsl.FunctionEntryRouter;
import io.github.qauxv.hook.CommonSwitchFunctionHook;
import java.lang.reflect.Method;
import java.util.List;
import java.util.ListIterator;
import top.linl.util.ScreenParamUtils;
import top.linl.util.reflect.ClassUtils;
import top.linl.util.reflect.FieldUtils;
import top.linl.util.reflect.MethodTool;
@FunctionHookEntry
@UiItemAgentEntry
public class SortTroopSettingAppListView extends CommonSwitchFunctionHook {
public static final SortTroopSettingAppListView INSTANCE = new SortTroopSettingAppListView();
@NonNull
@Override
public String[] getUiItemLocation() {
return FunctionEntryRouter.Locations.Auxiliary.GROUP_CATEGORY;
}
@Nullable
@Override
public CharSequence getDescription() {
return "让群设置的群文件在上面而不是在下面";
}
@Override
protected boolean initOnce() throws Exception {
try {
//由于我记得是qq是在8996重构了群设置页面 但是网上并无此版本安装包记录 所以决定采用异常捕获的方法来适配已经重构了群设置页的QQ
Class<?> troopSettingFragmentV2 = ClassUtils.getClass("com.tencent.mobileqq.troop.troopsetting.activity.TroopSettingFragmentV2");
Method onViewCreatedAfterPartInitMethod = MethodTool.find(troopSettingFragmentV2)
.name("onViewCreatedAfterPartInit")
.params(android.view.View.class, android.os.Bundle.class)
.returnType(void.class)
.get();
HookUtils.hookBeforeIfEnabled(this,onViewCreatedAfterPartInitMethod,param -> {
List<Object> partList = FieldUtils.getFirstField(param.thisObject, List.class);
Class<?> troopAppClass = ClassUtils.getClass("com.tencent.mobileqq.troop.troopsetting.part.TroopSettingAppPart");
Class<?> memberInfoPartClass = ClassUtils.getClass("com.tencent.mobileqq.troop.troopsetting.part.TroopSettingMemberInfoPart");
Object troopAppPart = null;
ListIterator<Object> iterator = partList.listIterator();
int memberInfoPartIndex = 0;
boolean isStopSelfIncrementing = false;
while (iterator.hasNext()) {
if (!isStopSelfIncrementing) memberInfoPartIndex++;
Object nextPart = iterator.next();
//定位群成员卡片(part)的位置索引
if (nextPart.getClass() == memberInfoPartClass) {
isStopSelfIncrementing = true;
}
//获取群应用的part
if (nextPart.getClass() == troopAppClass) {
troopAppPart = nextPart;
iterator.remove();
break;
}
}
if (troopAppPart == null) throw new RuntimeException("troop app list is null");
partList.add(memberInfoPartIndex, troopAppPart);
});
return true;
} catch (Exception e) {
//此处可能会在9.0.0前捕获到异常ReflectException : 没有找到类: com.tencent.mobileqq.troop.troopsetting.activity.TroopSettingFragmentV2
}
//如果抛出异常则会进行下面的代码 以保持对旧版本NT的适配
Method doOnCreateMethod = MethodTool.find("com.tencent.mobileqq.troop.troopsetting.activity.TroopSettingActivity")
.returnType(boolean.class)
.params(Bundle.class)
.name("doOnCreate")
.get();
HookUtils.hookAfterIfEnabled(this, doOnCreateMethod, new HookUtils.AfterHookedMethod() {
@Override
public void afterHookedMethod(XC_MethodHook.MethodHookParam param) throws Throwable {
LinearLayout rootView = FieldUtils.getFirstField(param.thisObject, LinearLayout.class);
int troopInfoTextIndex = 0;
View troopAppListView = null;
// View[] views = FieIdUtils.getFirstField(param.thisObject, View[].class);//过于复杂 不如不用
for (int i = 0; i < rootView.getChildCount(); i++) {
View child = rootView.getChildAt(i);
if (child instanceof TextView) {
TextView textView = (TextView) child;
String text = textView.getText().toString();
if (text.equals("群聊信息")) {
troopInfoTextIndex = i;
}
}
if (child instanceof LinearLayout) {
LinearLayout simpleFormItem = (LinearLayout) child;
if (simpleFormItem.getChildAt(0) instanceof RelativeLayout) {
RelativeLayout itemTitle = (RelativeLayout) simpleFormItem.getChildAt(0);
if (itemTitle.getChildAt(0) instanceof TextView) {
TextView titleTextView = (TextView) itemTitle.getChildAt(0);
String titleText = titleTextView.getText().toString();
if (titleText.equals("群应用")) {
troopAppListView = child;
break;
}
}
}
}
}
if (troopAppListView != null && troopInfoTextIndex != 0) {
rootView.removeView(troopAppListView);
//顶部偏移 不然会和群聊成员卡片贴一起 (贴贴
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.topMargin += ScreenParamUtils.dpToPx(rootView.getContext(), 16);
rootView.addView(troopAppListView, troopInfoTextIndex, layoutParams);
}
}
});
return true;
}
@NonNull
@Override
public String getName() {
return "将群应用卡片(群文件)移动到正常位置";
}
}
| cinit/QAuxiliary | app/src/main/java/top/linl/hook/SortTroopSettingAppListView.java | 1,750 | //由于我记得是qq是在8996重构了群设置页面 但是网上并无此版本安装包记录 所以决定采用异常捕获的方法来适配已经重构了群设置页的QQ | line_comment | zh-cn | /*
* QAuxiliary - An Xposed module for QQ/TIM
* Copyright (C) 2019-2023 QAuxiliary developers
* https://github.com/cinit/QAuxiliary
*
* This software is non-free but opensource software: you can redistribute it
* and/or modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; either
* version 3 of the License, or any later version and our eula as published
* by QAuxiliary contributors.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* and eula along with this software. If not, see
* <https://www.gnu.org/licenses/>
* <https://github.com/cinit/QAuxiliary/blob/master/LICENSE.md>.
*/
package top.linl.hook;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import cc.ioctl.util.HookUtils;
import de.robv.android.xposed.XC_MethodHook;
import io.github.qauxv.base.annotation.FunctionHookEntry;
import io.github.qauxv.base.annotation.UiItemAgentEntry;
import io.github.qauxv.dsl.FunctionEntryRouter;
import io.github.qauxv.hook.CommonSwitchFunctionHook;
import java.lang.reflect.Method;
import java.util.List;
import java.util.ListIterator;
import top.linl.util.ScreenParamUtils;
import top.linl.util.reflect.ClassUtils;
import top.linl.util.reflect.FieldUtils;
import top.linl.util.reflect.MethodTool;
@FunctionHookEntry
@UiItemAgentEntry
public class SortTroopSettingAppListView extends CommonSwitchFunctionHook {
public static final SortTroopSettingAppListView INSTANCE = new SortTroopSettingAppListView();
@NonNull
@Override
public String[] getUiItemLocation() {
return FunctionEntryRouter.Locations.Auxiliary.GROUP_CATEGORY;
}
@Nullable
@Override
public CharSequence getDescription() {
return "让群设置的群文件在上面而不是在下面";
}
@Override
protected boolean initOnce() throws Exception {
try {
//由于 <SUF>
Class<?> troopSettingFragmentV2 = ClassUtils.getClass("com.tencent.mobileqq.troop.troopsetting.activity.TroopSettingFragmentV2");
Method onViewCreatedAfterPartInitMethod = MethodTool.find(troopSettingFragmentV2)
.name("onViewCreatedAfterPartInit")
.params(android.view.View.class, android.os.Bundle.class)
.returnType(void.class)
.get();
HookUtils.hookBeforeIfEnabled(this,onViewCreatedAfterPartInitMethod,param -> {
List<Object> partList = FieldUtils.getFirstField(param.thisObject, List.class);
Class<?> troopAppClass = ClassUtils.getClass("com.tencent.mobileqq.troop.troopsetting.part.TroopSettingAppPart");
Class<?> memberInfoPartClass = ClassUtils.getClass("com.tencent.mobileqq.troop.troopsetting.part.TroopSettingMemberInfoPart");
Object troopAppPart = null;
ListIterator<Object> iterator = partList.listIterator();
int memberInfoPartIndex = 0;
boolean isStopSelfIncrementing = false;
while (iterator.hasNext()) {
if (!isStopSelfIncrementing) memberInfoPartIndex++;
Object nextPart = iterator.next();
//定位群成员卡片(part)的位置索引
if (nextPart.getClass() == memberInfoPartClass) {
isStopSelfIncrementing = true;
}
//获取群应用的part
if (nextPart.getClass() == troopAppClass) {
troopAppPart = nextPart;
iterator.remove();
break;
}
}
if (troopAppPart == null) throw new RuntimeException("troop app list is null");
partList.add(memberInfoPartIndex, troopAppPart);
});
return true;
} catch (Exception e) {
//此处可能会在9.0.0前捕获到异常ReflectException : 没有找到类: com.tencent.mobileqq.troop.troopsetting.activity.TroopSettingFragmentV2
}
//如果抛出异常则会进行下面的代码 以保持对旧版本NT的适配
Method doOnCreateMethod = MethodTool.find("com.tencent.mobileqq.troop.troopsetting.activity.TroopSettingActivity")
.returnType(boolean.class)
.params(Bundle.class)
.name("doOnCreate")
.get();
HookUtils.hookAfterIfEnabled(this, doOnCreateMethod, new HookUtils.AfterHookedMethod() {
@Override
public void afterHookedMethod(XC_MethodHook.MethodHookParam param) throws Throwable {
LinearLayout rootView = FieldUtils.getFirstField(param.thisObject, LinearLayout.class);
int troopInfoTextIndex = 0;
View troopAppListView = null;
// View[] views = FieIdUtils.getFirstField(param.thisObject, View[].class);//过于复杂 不如不用
for (int i = 0; i < rootView.getChildCount(); i++) {
View child = rootView.getChildAt(i);
if (child instanceof TextView) {
TextView textView = (TextView) child;
String text = textView.getText().toString();
if (text.equals("群聊信息")) {
troopInfoTextIndex = i;
}
}
if (child instanceof LinearLayout) {
LinearLayout simpleFormItem = (LinearLayout) child;
if (simpleFormItem.getChildAt(0) instanceof RelativeLayout) {
RelativeLayout itemTitle = (RelativeLayout) simpleFormItem.getChildAt(0);
if (itemTitle.getChildAt(0) instanceof TextView) {
TextView titleTextView = (TextView) itemTitle.getChildAt(0);
String titleText = titleTextView.getText().toString();
if (titleText.equals("群应用")) {
troopAppListView = child;
break;
}
}
}
}
}
if (troopAppListView != null && troopInfoTextIndex != 0) {
rootView.removeView(troopAppListView);
//顶部偏移 不然会和群聊成员卡片贴一起 (贴贴
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.topMargin += ScreenParamUtils.dpToPx(rootView.getContext(), 16);
rootView.addView(troopAppListView, troopInfoTextIndex, layoutParams);
}
}
});
return true;
}
@NonNull
@Override
public String getName() {
return "将群应用卡片(群文件)移动到正常位置";
}
}
| false | 1,513 | 44 | 1,750 | 50 | 1,785 | 44 | 1,750 | 50 | 2,164 | 78 | false | false | false | false | false | true |
31713_3 | package com.cipher.pattern.observer.jdk;
/**
* 观察者模式测试类
* Created by cipher on 2017/9/8.
*/
public class Client {
public static void main(String[] args) {
// 创建目标
WeatherStationSubject ws = new WeatherStationSubject();
// 创建观察者
ConcreteObserver girlfriend = new ConcreteObserver("女朋友");
ConcreteObserver mom = new ConcreteObserver("老妈");
// 注册观察者
ws.addObserver(girlfriend);
ws.addObserver(mom);
// 目标发布天气
ws.setWeather("天气晴朗");
}
}
| ciphermagic/java-learn | sandbox/src/main/java/com/cipher/pattern/observer/jdk/Client.java | 161 | // 注册观察者
| line_comment | zh-cn | package com.cipher.pattern.observer.jdk;
/**
* 观察者模式测试类
* Created by cipher on 2017/9/8.
*/
public class Client {
public static void main(String[] args) {
// 创建目标
WeatherStationSubject ws = new WeatherStationSubject();
// 创建观察者
ConcreteObserver girlfriend = new ConcreteObserver("女朋友");
ConcreteObserver mom = new ConcreteObserver("老妈");
// 注册 <SUF>
ws.addObserver(girlfriend);
ws.addObserver(mom);
// 目标发布天气
ws.setWeather("天气晴朗");
}
}
| false | 134 | 6 | 160 | 7 | 152 | 5 | 160 | 7 | 215 | 14 | false | false | false | false | false | true |
60855_3 | package tech.wetech.admin3.common;
import java.security.SecureRandom;
import java.util.Random;
/**
* NanoId,一个小型、安全、对 URL友好的唯一字符串 ID 生成器,特点:
*
* <ul>
* <li>安全:它使用加密、强大的随机 API,并保证符号的正确分配</li>
* <li>体积小:只有 258 bytes 大小(压缩后)、无依赖</li>
* <li>紧凑:它使用比 UUID (A-Za-z0-9_~)更多的符号</li>
* </ul>
*
* <p>
* 此实现的逻辑基于JavaScript的NanoId实现,见:https://github.com/ai/nanoid
*
* @author David Klebanoff
*/
public class NanoId {
/**
* 默认随机数生成器,使用{@link SecureRandom}确保健壮性
*/
private static final SecureRandom DEFAULT_NUMBER_GENERATOR = new SecureRandom();
/**
* 默认随机字母表,使用URL安全的Base64字符
*/
private static final char[] DEFAULT_ALPHABET =
"_-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
/**
* 默认长度
*/
public static final int DEFAULT_SIZE = 21;
/**
* 生成伪随机的NanoId字符串,长度为默认的{@link #DEFAULT_SIZE},使用密码安全的伪随机生成器
*
* @return 伪随机的NanoId字符串
*/
public static String randomNanoId() {
return randomNanoId(DEFAULT_SIZE);
}
/**
* 生成伪随机的NanoId字符串
*
* @param size ID长度
* @return 伪随机的NanoId字符串
*/
public static String randomNanoId(int size) {
return randomNanoId(null, null, size);
}
/**
* 生成伪随机的NanoId字符串
*
* @param random 随机数生成器
* @param alphabet 随机字母表
* @param size ID长度
* @return 伪随机的NanoId字符串
*/
public static String randomNanoId(Random random, char[] alphabet, int size) {
if (random == null) {
random = DEFAULT_NUMBER_GENERATOR;
}
if (alphabet == null) {
alphabet = DEFAULT_ALPHABET;
}
if (alphabet.length == 0 || alphabet.length >= 256) {
throw new IllegalArgumentException("Alphabet must contain between 1 and 255 symbols.");
}
if (size <= 0) {
throw new IllegalArgumentException("Size must be greater than zero.");
}
final int mask = (2 << (int) Math.floor(Math.log(alphabet.length - 1) / Math.log(2))) - 1;
final int step = (int) Math.ceil(1.6 * mask * size / alphabet.length);
final StringBuilder idBuilder = new StringBuilder();
while (true) {
final byte[] bytes = new byte[step];
random.nextBytes(bytes);
for (int i = 0; i < step; i++) {
final int alphabetIndex = bytes[i] & mask;
if (alphabetIndex < alphabet.length) {
idBuilder.append(alphabet[alphabetIndex]);
if (idBuilder.length() == size) {
return idBuilder.toString();
}
}
}
}
}
}
| cjbi/admin3 | admin3-server/src/main/java/tech/wetech/admin3/common/NanoId.java | 826 | /**
* 默认长度
*/ | block_comment | zh-cn | package tech.wetech.admin3.common;
import java.security.SecureRandom;
import java.util.Random;
/**
* NanoId,一个小型、安全、对 URL友好的唯一字符串 ID 生成器,特点:
*
* <ul>
* <li>安全:它使用加密、强大的随机 API,并保证符号的正确分配</li>
* <li>体积小:只有 258 bytes 大小(压缩后)、无依赖</li>
* <li>紧凑:它使用比 UUID (A-Za-z0-9_~)更多的符号</li>
* </ul>
*
* <p>
* 此实现的逻辑基于JavaScript的NanoId实现,见:https://github.com/ai/nanoid
*
* @author David Klebanoff
*/
public class NanoId {
/**
* 默认随机数生成器,使用{@link SecureRandom}确保健壮性
*/
private static final SecureRandom DEFAULT_NUMBER_GENERATOR = new SecureRandom();
/**
* 默认随机字母表,使用URL安全的Base64字符
*/
private static final char[] DEFAULT_ALPHABET =
"_-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
/**
* 默认长 <SUF>*/
public static final int DEFAULT_SIZE = 21;
/**
* 生成伪随机的NanoId字符串,长度为默认的{@link #DEFAULT_SIZE},使用密码安全的伪随机生成器
*
* @return 伪随机的NanoId字符串
*/
public static String randomNanoId() {
return randomNanoId(DEFAULT_SIZE);
}
/**
* 生成伪随机的NanoId字符串
*
* @param size ID长度
* @return 伪随机的NanoId字符串
*/
public static String randomNanoId(int size) {
return randomNanoId(null, null, size);
}
/**
* 生成伪随机的NanoId字符串
*
* @param random 随机数生成器
* @param alphabet 随机字母表
* @param size ID长度
* @return 伪随机的NanoId字符串
*/
public static String randomNanoId(Random random, char[] alphabet, int size) {
if (random == null) {
random = DEFAULT_NUMBER_GENERATOR;
}
if (alphabet == null) {
alphabet = DEFAULT_ALPHABET;
}
if (alphabet.length == 0 || alphabet.length >= 256) {
throw new IllegalArgumentException("Alphabet must contain between 1 and 255 symbols.");
}
if (size <= 0) {
throw new IllegalArgumentException("Size must be greater than zero.");
}
final int mask = (2 << (int) Math.floor(Math.log(alphabet.length - 1) / Math.log(2))) - 1;
final int step = (int) Math.ceil(1.6 * mask * size / alphabet.length);
final StringBuilder idBuilder = new StringBuilder();
while (true) {
final byte[] bytes = new byte[step];
random.nextBytes(bytes);
for (int i = 0; i < step; i++) {
final int alphabetIndex = bytes[i] & mask;
if (alphabetIndex < alphabet.length) {
idBuilder.append(alphabet[alphabetIndex]);
if (idBuilder.length() == size) {
return idBuilder.toString();
}
}
}
}
}
}
| false | 755 | 8 | 826 | 7 | 855 | 9 | 826 | 7 | 1,099 | 12 | false | false | false | false | false | true |
12260_1 | package com.github.cjm0000000.mmt.yixin.api.passive;
import org.springframework.stereotype.Service;
import com.github.cjm0000000.mmt.core.config.MmtConfig;
import com.github.cjm0000000.mmt.core.message.BaseMessage;
import com.github.cjm0000000.mmt.core.message.recv.IVideo;
import com.github.cjm0000000.mmt.core.message.recv.ImageMessage;
import com.github.cjm0000000.mmt.core.message.recv.LinkMessage;
import com.github.cjm0000000.mmt.core.message.recv.LocationMessage;
import com.github.cjm0000000.mmt.core.message.recv.weixin.VoiceMessage;
import com.github.cjm0000000.mmt.core.message.recv.yixin.AudioMessage;
import com.github.cjm0000000.mmt.core.message.recv.yixin.MusicMessage;
import com.github.cjm0000000.mmt.core.service.ServiceType;
import com.github.cjm0000000.mmt.shared.message.process.AbstractPassiveMsgProcessor;
import com.github.cjm0000000.mmt.yixin.YiXin;
import com.github.cjm0000000.mmt.yixin.YiXinException;
/**
* 简单的易信消息机器人
*
* @author lemon
* @version 1.0
*
*/
@Service
public class SimpleYiXinMsgProcessor extends AbstractPassiveMsgProcessor {
@Override
public final ServiceType getServiceType() {
return ServiceType.YIXIN;
}
@Override
public final MmtConfig getConfig(String mmt_token) {
return YiXin.getConfig(mmt_token);
}
@Override
public BaseMessage processAudioMsg(MmtConfig cfg, AudioMessage msg) {
//默认提示消息国际化
return sendTextMessage(msg, "亲,我暂时无法识别语音信息哦,您可以给我发文字消息。");
}
@Override
public BaseMessage processImageMsg(MmtConfig cfg, ImageMessage msg) {
return sendTextMessage(msg, "亲,我暂时无法识别图片信息哦,您可以给我发文字消息。");
}
@Override
public BaseMessage processLinkMsg(MmtConfig cfg, LinkMessage msg) {
return sendTextMessage(msg, "亲,我暂时无法识别链接信息哦,您可以给我发文字消息。");
}
@Override
public BaseMessage processLocationMsg(MmtConfig cfg, LocationMessage msg) {
return sendTextMessage(msg, "亲,我暂时无法识别地理位置信息哦,您可以给我发文字消息。");
}
@Override
public BaseMessage processMusicMsg(MmtConfig cfg, MusicMessage msg) {
return sendTextMessage((BaseMessage) msg, "亲,我暂时无法识别音乐消息哦,您可以给我发文字消息。");
}
@Override
public BaseMessage processVideoMsg(MmtConfig cfg, IVideo msg) {
return sendTextMessage((BaseMessage) msg, "亲,我暂时无法识别视频消息哦,您可以给我发文字消息。");
}
@Override
public final BaseMessage processVoiceMsg(MmtConfig cfg, VoiceMessage msg) {
throw new YiXinException("拜托,这里是易信,哪来的Voice消息。");
}
}
| cjm0000000/mmt | mmt-yixin/src/main/java/com/github/cjm0000000/mmt/yixin/api/passive/SimpleYiXinMsgProcessor.java | 913 | //默认提示消息国际化
| line_comment | zh-cn | package com.github.cjm0000000.mmt.yixin.api.passive;
import org.springframework.stereotype.Service;
import com.github.cjm0000000.mmt.core.config.MmtConfig;
import com.github.cjm0000000.mmt.core.message.BaseMessage;
import com.github.cjm0000000.mmt.core.message.recv.IVideo;
import com.github.cjm0000000.mmt.core.message.recv.ImageMessage;
import com.github.cjm0000000.mmt.core.message.recv.LinkMessage;
import com.github.cjm0000000.mmt.core.message.recv.LocationMessage;
import com.github.cjm0000000.mmt.core.message.recv.weixin.VoiceMessage;
import com.github.cjm0000000.mmt.core.message.recv.yixin.AudioMessage;
import com.github.cjm0000000.mmt.core.message.recv.yixin.MusicMessage;
import com.github.cjm0000000.mmt.core.service.ServiceType;
import com.github.cjm0000000.mmt.shared.message.process.AbstractPassiveMsgProcessor;
import com.github.cjm0000000.mmt.yixin.YiXin;
import com.github.cjm0000000.mmt.yixin.YiXinException;
/**
* 简单的易信消息机器人
*
* @author lemon
* @version 1.0
*
*/
@Service
public class SimpleYiXinMsgProcessor extends AbstractPassiveMsgProcessor {
@Override
public final ServiceType getServiceType() {
return ServiceType.YIXIN;
}
@Override
public final MmtConfig getConfig(String mmt_token) {
return YiXin.getConfig(mmt_token);
}
@Override
public BaseMessage processAudioMsg(MmtConfig cfg, AudioMessage msg) {
//默认 <SUF>
return sendTextMessage(msg, "亲,我暂时无法识别语音信息哦,您可以给我发文字消息。");
}
@Override
public BaseMessage processImageMsg(MmtConfig cfg, ImageMessage msg) {
return sendTextMessage(msg, "亲,我暂时无法识别图片信息哦,您可以给我发文字消息。");
}
@Override
public BaseMessage processLinkMsg(MmtConfig cfg, LinkMessage msg) {
return sendTextMessage(msg, "亲,我暂时无法识别链接信息哦,您可以给我发文字消息。");
}
@Override
public BaseMessage processLocationMsg(MmtConfig cfg, LocationMessage msg) {
return sendTextMessage(msg, "亲,我暂时无法识别地理位置信息哦,您可以给我发文字消息。");
}
@Override
public BaseMessage processMusicMsg(MmtConfig cfg, MusicMessage msg) {
return sendTextMessage((BaseMessage) msg, "亲,我暂时无法识别音乐消息哦,您可以给我发文字消息。");
}
@Override
public BaseMessage processVideoMsg(MmtConfig cfg, IVideo msg) {
return sendTextMessage((BaseMessage) msg, "亲,我暂时无法识别视频消息哦,您可以给我发文字消息。");
}
@Override
public final BaseMessage processVoiceMsg(MmtConfig cfg, VoiceMessage msg) {
throw new YiXinException("拜托,这里是易信,哪来的Voice消息。");
}
}
| false | 747 | 6 | 899 | 8 | 875 | 7 | 899 | 8 | 1,120 | 13 | false | false | false | false | false | true |
46325_12 | package com.jd.platform.hotkey.worker.keylistener;
import cn.hutool.core.date.SystemClock;
import com.github.benmanes.caffeine.cache.Cache;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.jd.platform.hotkey.common.model.HotKeyModel;
import com.jd.platform.hotkey.common.rule.KeyRule;
import com.jd.platform.hotkey.worker.cache.CaffeineCacheHolder;
import com.jd.platform.hotkey.worker.netty.pusher.IPusher;
import com.jd.platform.hotkey.worker.rule.KeyRuleHolder;
import com.jd.platform.hotkey.worker.tool.SlidingWindow;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.List;
/**
* key的新增、删除处理
*
* @author wuweifeng wrote on 2019-12-12
* @version 1.0
*/
@Component
public class KeyListener implements IKeyListener {
@Resource(name = "hotKeyCache")
private Cache<String, Object> hotCache;
@Resource
private List<IPusher> iPushers;
private static final String SPLITER = "-";
private Logger logger = LoggerFactory.getLogger(getClass());
private static final String NEW_KEY_EVENT = "new key created event, key : ";
private static final String DELETE_KEY_EVENT = "key delete event key : ";
@Override
public void newKey(HotKeyModel hotKeyModel, KeyEventOriginal original) {
//cache里的key
String key = buildKey(hotKeyModel);
//判断是不是刚热不久
Object o = hotCache.getIfPresent(key);
if (o != null) {
return;
}
//********** watch here ************//
//该方法会被InitConstant.threadCount个线程同时调用,存在多线程问题
//下面的那句addCount是加了锁的,代表给Key累加数量时是原子性的,不会发生多加、少加的情况,到了设定的阈值一定会hot
//譬如阈值是2,如果多个线程累加,在没hot前,hot的状态肯定是对的,譬如thread1 加1,thread2加1,那么thread2会hot返回true,开启推送
//但是极端情况下,譬如阈值是10,当前是9,thread1走到这里时,加1,返回true,thread2也走到这里,加1,此时是11,返回true,问题来了
//该key会走下面的else两次,也就是2次推送。
//所以出现问题的原因是hotCache.getIfPresent(key)这一句在并发情况下,没return掉,放了两个key+1到addCount这一步时,会有问题
//测试代码在TestBlockQueue类,直接运行可以看到会同时hot
//那么该问题用解决吗,NO,不需要解决,1 首先要发生的条件极其苛刻,很难触发,以京东这样高的并发量,线上我也没见过触发连续2次推送同一个key的
//2 即便触发了,后果也是可以接受的,2次推送而已,毫无影响,客户端无感知。但是如果非要解决,就要对slidingWindow实例加锁了,必然有一些开销
//所以只要保证key数量不多计算就可以,少计算了没事。因为热key必然频率高,漏计几次没事。但非热key,多计算了,被干成了热key就不对了
SlidingWindow slidingWindow = checkWindow(hotKeyModel, key);
//看看hot没
boolean hot = slidingWindow.addCount(hotKeyModel.getCount());
if (!hot) {
//如果没hot,重新put,cache会自动刷新过期时间
CaffeineCacheHolder.getCache(hotKeyModel.getAppName()).put(key, slidingWindow);
} else {
hotCache.put(key, 1);
//删掉该key
CaffeineCacheHolder.getCache(hotKeyModel.getAppName()).invalidate(key);
//开启推送
hotKeyModel.setCreateTime(SystemClock.now());
logger.info(NEW_KEY_EVENT + hotKeyModel.getKey());
//分别推送到各client和etcd
for (IPusher pusher : iPushers) {
pusher.push(hotKeyModel);
}
}
}
@Override
public void removeKey(HotKeyModel hotKeyModel, KeyEventOriginal original) {
//cache里的key
String key = buildKey(hotKeyModel);
hotCache.invalidate(key);
CaffeineCacheHolder.getCache(hotKeyModel.getAppName()).invalidate(key);
//推送所有client删除
hotKeyModel.setCreateTime(SystemClock.now());
logger.info(DELETE_KEY_EVENT + hotKeyModel.getKey());
for (IPusher pusher : iPushers) {
pusher.remove(hotKeyModel);
}
}
/**
* 生成或返回该key的滑窗
*/
private SlidingWindow checkWindow(HotKeyModel hotKeyModel, String key) {
//取该key的滑窗
return (SlidingWindow) CaffeineCacheHolder.getCache(hotKeyModel.getAppName()).get(key, (Function<String, SlidingWindow>) s -> {
//是个新key,获取它的规则
KeyRule keyRule = KeyRuleHolder.getRuleByAppAndKey(hotKeyModel);
return new SlidingWindow(keyRule.getInterval(), keyRule.getThreshold());
});
}
private String buildKey(HotKeyModel hotKeyModel) {
return Joiner.on(SPLITER).join(hotKeyModel.getAppName(), hotKeyModel.getKeyType(), hotKeyModel.getKey());
}
}
| ck-jesse/l2cache | l2cache-jd-hotkey/jd-hotkey-worker/src/main/java/com/jd/platform/hotkey/worker/keylistener/KeyListener.java | 1,420 | //2 即便触发了,后果也是可以接受的,2次推送而已,毫无影响,客户端无感知。但是如果非要解决,就要对slidingWindow实例加锁了,必然有一些开销 | line_comment | zh-cn | package com.jd.platform.hotkey.worker.keylistener;
import cn.hutool.core.date.SystemClock;
import com.github.benmanes.caffeine.cache.Cache;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.jd.platform.hotkey.common.model.HotKeyModel;
import com.jd.platform.hotkey.common.rule.KeyRule;
import com.jd.platform.hotkey.worker.cache.CaffeineCacheHolder;
import com.jd.platform.hotkey.worker.netty.pusher.IPusher;
import com.jd.platform.hotkey.worker.rule.KeyRuleHolder;
import com.jd.platform.hotkey.worker.tool.SlidingWindow;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.List;
/**
* key的新增、删除处理
*
* @author wuweifeng wrote on 2019-12-12
* @version 1.0
*/
@Component
public class KeyListener implements IKeyListener {
@Resource(name = "hotKeyCache")
private Cache<String, Object> hotCache;
@Resource
private List<IPusher> iPushers;
private static final String SPLITER = "-";
private Logger logger = LoggerFactory.getLogger(getClass());
private static final String NEW_KEY_EVENT = "new key created event, key : ";
private static final String DELETE_KEY_EVENT = "key delete event key : ";
@Override
public void newKey(HotKeyModel hotKeyModel, KeyEventOriginal original) {
//cache里的key
String key = buildKey(hotKeyModel);
//判断是不是刚热不久
Object o = hotCache.getIfPresent(key);
if (o != null) {
return;
}
//********** watch here ************//
//该方法会被InitConstant.threadCount个线程同时调用,存在多线程问题
//下面的那句addCount是加了锁的,代表给Key累加数量时是原子性的,不会发生多加、少加的情况,到了设定的阈值一定会hot
//譬如阈值是2,如果多个线程累加,在没hot前,hot的状态肯定是对的,譬如thread1 加1,thread2加1,那么thread2会hot返回true,开启推送
//但是极端情况下,譬如阈值是10,当前是9,thread1走到这里时,加1,返回true,thread2也走到这里,加1,此时是11,返回true,问题来了
//该key会走下面的else两次,也就是2次推送。
//所以出现问题的原因是hotCache.getIfPresent(key)这一句在并发情况下,没return掉,放了两个key+1到addCount这一步时,会有问题
//测试代码在TestBlockQueue类,直接运行可以看到会同时hot
//那么该问题用解决吗,NO,不需要解决,1 首先要发生的条件极其苛刻,很难触发,以京东这样高的并发量,线上我也没见过触发连续2次推送同一个key的
//2 <SUF>
//所以只要保证key数量不多计算就可以,少计算了没事。因为热key必然频率高,漏计几次没事。但非热key,多计算了,被干成了热key就不对了
SlidingWindow slidingWindow = checkWindow(hotKeyModel, key);
//看看hot没
boolean hot = slidingWindow.addCount(hotKeyModel.getCount());
if (!hot) {
//如果没hot,重新put,cache会自动刷新过期时间
CaffeineCacheHolder.getCache(hotKeyModel.getAppName()).put(key, slidingWindow);
} else {
hotCache.put(key, 1);
//删掉该key
CaffeineCacheHolder.getCache(hotKeyModel.getAppName()).invalidate(key);
//开启推送
hotKeyModel.setCreateTime(SystemClock.now());
logger.info(NEW_KEY_EVENT + hotKeyModel.getKey());
//分别推送到各client和etcd
for (IPusher pusher : iPushers) {
pusher.push(hotKeyModel);
}
}
}
@Override
public void removeKey(HotKeyModel hotKeyModel, KeyEventOriginal original) {
//cache里的key
String key = buildKey(hotKeyModel);
hotCache.invalidate(key);
CaffeineCacheHolder.getCache(hotKeyModel.getAppName()).invalidate(key);
//推送所有client删除
hotKeyModel.setCreateTime(SystemClock.now());
logger.info(DELETE_KEY_EVENT + hotKeyModel.getKey());
for (IPusher pusher : iPushers) {
pusher.remove(hotKeyModel);
}
}
/**
* 生成或返回该key的滑窗
*/
private SlidingWindow checkWindow(HotKeyModel hotKeyModel, String key) {
//取该key的滑窗
return (SlidingWindow) CaffeineCacheHolder.getCache(hotKeyModel.getAppName()).get(key, (Function<String, SlidingWindow>) s -> {
//是个新key,获取它的规则
KeyRule keyRule = KeyRuleHolder.getRuleByAppAndKey(hotKeyModel);
return new SlidingWindow(keyRule.getInterval(), keyRule.getThreshold());
});
}
private String buildKey(HotKeyModel hotKeyModel) {
return Joiner.on(SPLITER).join(hotKeyModel.getAppName(), hotKeyModel.getKeyType(), hotKeyModel.getKey());
}
}
| false | 1,225 | 44 | 1,420 | 55 | 1,388 | 44 | 1,420 | 55 | 1,823 | 92 | false | false | false | false | false | true |
63585_1 | import java.util.ArrayList;
/**
* Created by oc on 2017/10/12.
*/
public class State {
Node current;
Graph graph;
boolean[] visited;
ArrayList<String> route;
int shopTime;
int cnt;
public static final int STOP_COUNT = 45;
public State(Graph _graph, Node node) {
graph=_graph;
current=node;
cnt=0;
visited=new boolean[graph.list.size()];
visited[current.id]=true;
route=new ArrayList<>();
route.add(current.toString());
shopTime=-1;
eatItem();
}
public State(State another) {
graph=another.graph;
current=another.current;
visited=another.visited.clone();
route=new ArrayList<>(another.route);
shopTime=another.shopTime;
cnt=another.cnt;
}
public State merge(Node node) {
if (visited[node.id] || !current.linked.contains(node))
return null;
Node another = current.merge(node, visited);
if (another==null) return null;
current=another;
visit(node);
route.add(current.toString());
eatItem();
cnt++;
return this;
}
// 尽可能吃掉周边宝物
public void eatItem() {
boolean has=true;
while (has) {
has=false;
for (Node node: current.linked) {
if (visited[node.id]) continue;
if (!node.shouldEat(graph.shouldEat?current.hero:null)) continue;
has=true;
current=current.merge(node, visited);
if (node.item!=null && (node.item.special&1)!=0)
shopTime=Math.max(shopTime, 0);
visit(node);
break;
}
}
// Use shop
while (graph.shop.useShop(current.hero, shopTime))
shopTime++;
}
public void visit(Node node) {
if (!visited[node.id] && current.linked.remove(node)) {
for (Monster monster: node.monsters)
current.hero.money+=monster.money;
visited[node.id] = true;
}
}
public boolean shouldStop() {
if (cnt>STOP_COUNT) return true;
// Boss被打死?
if (graph.bossId>=0 && visited[graph.bossId]) return true;
return false;
}
public long hash() {
long val=0;
int i=0;
for (Node node: graph.list) {
if (node.doors.isEmpty() && node.monsters.isEmpty()) continue;
if (visited[node.id]) val|=(1L<<i);
i++;
}
return val;
}
public int getScore() {
return current.getScore();
}
}
| ckcz123/magic-tower-AI | AI/src/State.java | 680 | // 尽可能吃掉周边宝物 | line_comment | zh-cn | import java.util.ArrayList;
/**
* Created by oc on 2017/10/12.
*/
public class State {
Node current;
Graph graph;
boolean[] visited;
ArrayList<String> route;
int shopTime;
int cnt;
public static final int STOP_COUNT = 45;
public State(Graph _graph, Node node) {
graph=_graph;
current=node;
cnt=0;
visited=new boolean[graph.list.size()];
visited[current.id]=true;
route=new ArrayList<>();
route.add(current.toString());
shopTime=-1;
eatItem();
}
public State(State another) {
graph=another.graph;
current=another.current;
visited=another.visited.clone();
route=new ArrayList<>(another.route);
shopTime=another.shopTime;
cnt=another.cnt;
}
public State merge(Node node) {
if (visited[node.id] || !current.linked.contains(node))
return null;
Node another = current.merge(node, visited);
if (another==null) return null;
current=another;
visit(node);
route.add(current.toString());
eatItem();
cnt++;
return this;
}
// 尽可 <SUF>
public void eatItem() {
boolean has=true;
while (has) {
has=false;
for (Node node: current.linked) {
if (visited[node.id]) continue;
if (!node.shouldEat(graph.shouldEat?current.hero:null)) continue;
has=true;
current=current.merge(node, visited);
if (node.item!=null && (node.item.special&1)!=0)
shopTime=Math.max(shopTime, 0);
visit(node);
break;
}
}
// Use shop
while (graph.shop.useShop(current.hero, shopTime))
shopTime++;
}
public void visit(Node node) {
if (!visited[node.id] && current.linked.remove(node)) {
for (Monster monster: node.monsters)
current.hero.money+=monster.money;
visited[node.id] = true;
}
}
public boolean shouldStop() {
if (cnt>STOP_COUNT) return true;
// Boss被打死?
if (graph.bossId>=0 && visited[graph.bossId]) return true;
return false;
}
public long hash() {
long val=0;
int i=0;
for (Node node: graph.list) {
if (node.doors.isEmpty() && node.monsters.isEmpty()) continue;
if (visited[node.id]) val|=(1L<<i);
i++;
}
return val;
}
public int getScore() {
return current.getScore();
}
}
| false | 593 | 9 | 680 | 10 | 751 | 7 | 680 | 10 | 816 | 17 | false | false | false | false | false | true |
2303_5 | package com.chuanglan.demo;
import java.io.UnsupportedEncodingException;
import com.alibaba.fastjson.JSON;
import com.chuanglan.model.request.SmsVariableRequest;
import com.chuanglan.model.response.SmsVariableResponse;
import com.chuanglan.util.ChuangLanSmsUtil;
/**
*
* @author tianyh
* @Description:变量短信发送
*/
public class SmsVariableDemo {
public static final String charset = "utf-8";
// 用户平台API账号(非登录账号,示例:N1234567)
public static String account = "";
// 用户平台API密码(非登录密码)
public static String pswd = "";
public static void main(String[] args) throws UnsupportedEncodingException {
//请求地址请登录253云通讯自助通平台查看或者询问您的商务负责人获取
String smsVariableRequestUrl = "http://xxx/msg/variable/json";
//短信内容
String msg = "【253云通讯】尊敬的{$var},您好,您的验证码是{$var},{$var}分钟内有效";
//参数组
String params = "159*******,先生,123456,3;130********,先生,123456,3;";
//状态报告
String report= "true";
SmsVariableRequest smsVariableRequest=new SmsVariableRequest(account, pswd, msg, params, report);
String requestJson = JSON.toJSONString(smsVariableRequest);
System.out.println("before request string is: " + requestJson);
String response = ChuangLanSmsUtil.sendSmsByPost(smsVariableRequestUrl, requestJson);
System.out.println("response after request result is : " + response);
SmsVariableResponse smsVariableResponse = JSON.parseObject(response, SmsVariableResponse.class);
System.out.println("response toString is : " + smsVariableResponse);
}
}
| cl253/chuanglan253-java | src/main/java/com/chuanglan/demo/SmsVariableDemo.java | 475 | //短信内容 | line_comment | zh-cn | package com.chuanglan.demo;
import java.io.UnsupportedEncodingException;
import com.alibaba.fastjson.JSON;
import com.chuanglan.model.request.SmsVariableRequest;
import com.chuanglan.model.response.SmsVariableResponse;
import com.chuanglan.util.ChuangLanSmsUtil;
/**
*
* @author tianyh
* @Description:变量短信发送
*/
public class SmsVariableDemo {
public static final String charset = "utf-8";
// 用户平台API账号(非登录账号,示例:N1234567)
public static String account = "";
// 用户平台API密码(非登录密码)
public static String pswd = "";
public static void main(String[] args) throws UnsupportedEncodingException {
//请求地址请登录253云通讯自助通平台查看或者询问您的商务负责人获取
String smsVariableRequestUrl = "http://xxx/msg/variable/json";
//短信 <SUF>
String msg = "【253云通讯】尊敬的{$var},您好,您的验证码是{$var},{$var}分钟内有效";
//参数组
String params = "159*******,先生,123456,3;130********,先生,123456,3;";
//状态报告
String report= "true";
SmsVariableRequest smsVariableRequest=new SmsVariableRequest(account, pswd, msg, params, report);
String requestJson = JSON.toJSONString(smsVariableRequest);
System.out.println("before request string is: " + requestJson);
String response = ChuangLanSmsUtil.sendSmsByPost(smsVariableRequestUrl, requestJson);
System.out.println("response after request result is : " + response);
SmsVariableResponse smsVariableResponse = JSON.parseObject(response, SmsVariableResponse.class);
System.out.println("response toString is : " + smsVariableResponse);
}
}
| false | 411 | 3 | 475 | 4 | 469 | 3 | 475 | 4 | 598 | 7 | false | false | false | false | false | true |
49821_7 | package com.clam.clipphoto;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.ImageView;
/**
* Created by clam314 on 2017/4/20
*/
public class ImageTouchView extends ImageView {
private float mWidth;
private float mHeight;
private PointF startPoint = new PointF();
private Matrix matrix = new Matrix();
private Matrix currentMatrix = new Matrix();
private int mode = 0;//用于标记模式
private static final int DRAG = 1;//拖动
private static final int ZOOM = 2;//放大
private float startDis = 0;
private PointF midPoint;//中心点
public ImageTouchView(Context context){
super(context);
}
public ImageTouchView(Context context,AttributeSet paramAttributeSet){
super(context,paramAttributeSet);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mWidth = w;
mHeight = h;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
mode = DRAG;
currentMatrix.set(this.getImageMatrix());//记录ImageView当期的移动位置
startPoint.set(event.getX(),event.getY());//开始点
break;
case MotionEvent.ACTION_MOVE://移动事件
if (mode == DRAG) {//图片拖动事件
float dx = event.getX() - startPoint.x;//x轴移动距离
float dy = event.getY() - startPoint.y;//y轴移动距离
matrix.set(currentMatrix);//在当前的位置基础上移动
matrix.postTranslate(dx, dy);
} else if(mode == ZOOM){//图片放大事件
float endDis = distance(event);//结束距离
if(endDis > 10f){
float scale = endDis / startDis;//放大倍数
Log.v("scale=", String.valueOf(scale));
matrix.set(currentMatrix);
matrix.postScale(scale, scale, midPoint.x, midPoint.y);
}
}
break;
case MotionEvent.ACTION_UP:
mode = 0;
break;
//有手指离开屏幕,但屏幕还有触点(手指)
case MotionEvent.ACTION_POINTER_UP:
mode = 0;
break;
//当屏幕上已经有触点(手指),再有一个手指压下屏幕,变成放大模式,计算两点之间中心点的位置
case MotionEvent.ACTION_POINTER_DOWN:
mode = ZOOM;
startDis = distance(event);//计算得到两根手指间的距离
if(startDis > 10f){//避免手指上有两个茧
midPoint = mid(event);//计算两点之间中心点的位置
currentMatrix.set(this.getImageMatrix());//记录当前的缩放倍数
}
break;
}
this.setImageMatrix(matrix);
return true;
}
/**
* 两点之间的距离
*/
private static float distance(MotionEvent event){
//两根手指间的距离
float dx = event.getX(1) - event.getX(0);
float dy = event.getY(1) - event.getY(0);
return (float)Math.sqrt(dx*dx + dy*dy);
}
/**
* 计算两点之间中心点的位置
*/
private static PointF mid(MotionEvent event){
float midx = event.getX(1) + event.getX(0);
float midy = event.getY(1) + event.getY(0);
return new PointF(midx/2, midy/2);
}
/**
*根据裁剪框的位置和大小,截取图片
*
*@param frameView 裁剪框
*/
public Bitmap getBitmap(ClipFrameView frameView) {
if(frameView == null)return null;
setDrawingCacheEnabled(true);
buildDrawingCache();
//判断裁剪框的区域是否超过了View的大小,避免超过大小而报错
int left = frameView.getFramePosition().x > 0 ? (int)frameView.getFramePosition().x : 0;
int top = frameView.getFramePosition().y > 0 ? (int)frameView.getFramePosition().y : 0;
int width = left+frameView.getFrameWidth() < mWidth ? (int)frameView.getFrameWidth() : (int)mWidth;
int height = top+frameView.getFrameHeight() < mHeight ? (int)frameView.getFrameHeight() : (int)mHeight;
//根据裁剪框的位置和大小,截取图片
Bitmap finalBitmap = Bitmap.createBitmap(getDrawingCache(),left,top,width,height);
// 释放资源
destroyDrawingCache();
return finalBitmap;
}
/**
*将图片自动缩放到裁剪框的上部
*
*@param frameView 裁剪框
*/
public void autoFillClipFrame(ClipFrameView frameView){
if(getDrawable() == null || frameView == null)return;
float left = frameView.getFramePosition().x;
float top = frameView.getFramePosition().y;
float width = frameView.getFrameWidth();
float height = frameView.getFrameHeight();
RectF dstRect = new RectF(left,top,left+width,top+height);
RectF srcRect = new RectF(0,0,getDrawable().getIntrinsicWidth(),getDrawable().getMinimumHeight());
Matrix newMatrix = new Matrix();
//将源矩阵矩阵填充到目标矩阵,这里选择对其左上,根据需求可以选其他模式
newMatrix.setRectToRect(srcRect,dstRect, Matrix.ScaleToFit.START);
setImageMatrix(newMatrix);
matrix = newMatrix;
invalidate();
}
/**
*设置图片
*
* @param filePath 图片的完整路径
* @param multiple 倍数,当图片宽或高大于Vie的宽或高multiple倍实行向下采样
*/
public void setImageFile(final String filePath,final int multiple){
post(new Runnable() {
@Override
public void run() {
//为了获取view的大小
Bitmap bitmap = getSmallBitmap(filePath,(int) mWidth,(int)mHeight,multiple);
if(bitmap != null)setImageBitmap(bitmap);
}
});
}
//计算图片的缩放大小
private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight,int multiple) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;//1是不缩放,2是缩小1/2,4是缩小1/4等
if (height > reqHeight *multiple|| width > reqWidth*multiple) {
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
private static Bitmap getSmallBitmap(String filePath, int w, int h,int multiple) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;//true的话,不会真的把bitmap加载到内存,但能获取bitmap的大小信息等
BitmapFactory.decodeFile(filePath, options);
options.inSampleSize = calculateInSampleSize(options, w, h,multiple);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(filePath, options);
}
}
| clam314/ClipPhoto | app/src/main/java/com/clam/clipphoto/ImageTouchView.java | 1,926 | //x轴移动距离 | line_comment | zh-cn | package com.clam.clipphoto;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.ImageView;
/**
* Created by clam314 on 2017/4/20
*/
public class ImageTouchView extends ImageView {
private float mWidth;
private float mHeight;
private PointF startPoint = new PointF();
private Matrix matrix = new Matrix();
private Matrix currentMatrix = new Matrix();
private int mode = 0;//用于标记模式
private static final int DRAG = 1;//拖动
private static final int ZOOM = 2;//放大
private float startDis = 0;
private PointF midPoint;//中心点
public ImageTouchView(Context context){
super(context);
}
public ImageTouchView(Context context,AttributeSet paramAttributeSet){
super(context,paramAttributeSet);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mWidth = w;
mHeight = h;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
mode = DRAG;
currentMatrix.set(this.getImageMatrix());//记录ImageView当期的移动位置
startPoint.set(event.getX(),event.getY());//开始点
break;
case MotionEvent.ACTION_MOVE://移动事件
if (mode == DRAG) {//图片拖动事件
float dx = event.getX() - startPoint.x;//x轴 <SUF>
float dy = event.getY() - startPoint.y;//y轴移动距离
matrix.set(currentMatrix);//在当前的位置基础上移动
matrix.postTranslate(dx, dy);
} else if(mode == ZOOM){//图片放大事件
float endDis = distance(event);//结束距离
if(endDis > 10f){
float scale = endDis / startDis;//放大倍数
Log.v("scale=", String.valueOf(scale));
matrix.set(currentMatrix);
matrix.postScale(scale, scale, midPoint.x, midPoint.y);
}
}
break;
case MotionEvent.ACTION_UP:
mode = 0;
break;
//有手指离开屏幕,但屏幕还有触点(手指)
case MotionEvent.ACTION_POINTER_UP:
mode = 0;
break;
//当屏幕上已经有触点(手指),再有一个手指压下屏幕,变成放大模式,计算两点之间中心点的位置
case MotionEvent.ACTION_POINTER_DOWN:
mode = ZOOM;
startDis = distance(event);//计算得到两根手指间的距离
if(startDis > 10f){//避免手指上有两个茧
midPoint = mid(event);//计算两点之间中心点的位置
currentMatrix.set(this.getImageMatrix());//记录当前的缩放倍数
}
break;
}
this.setImageMatrix(matrix);
return true;
}
/**
* 两点之间的距离
*/
private static float distance(MotionEvent event){
//两根手指间的距离
float dx = event.getX(1) - event.getX(0);
float dy = event.getY(1) - event.getY(0);
return (float)Math.sqrt(dx*dx + dy*dy);
}
/**
* 计算两点之间中心点的位置
*/
private static PointF mid(MotionEvent event){
float midx = event.getX(1) + event.getX(0);
float midy = event.getY(1) + event.getY(0);
return new PointF(midx/2, midy/2);
}
/**
*根据裁剪框的位置和大小,截取图片
*
*@param frameView 裁剪框
*/
public Bitmap getBitmap(ClipFrameView frameView) {
if(frameView == null)return null;
setDrawingCacheEnabled(true);
buildDrawingCache();
//判断裁剪框的区域是否超过了View的大小,避免超过大小而报错
int left = frameView.getFramePosition().x > 0 ? (int)frameView.getFramePosition().x : 0;
int top = frameView.getFramePosition().y > 0 ? (int)frameView.getFramePosition().y : 0;
int width = left+frameView.getFrameWidth() < mWidth ? (int)frameView.getFrameWidth() : (int)mWidth;
int height = top+frameView.getFrameHeight() < mHeight ? (int)frameView.getFrameHeight() : (int)mHeight;
//根据裁剪框的位置和大小,截取图片
Bitmap finalBitmap = Bitmap.createBitmap(getDrawingCache(),left,top,width,height);
// 释放资源
destroyDrawingCache();
return finalBitmap;
}
/**
*将图片自动缩放到裁剪框的上部
*
*@param frameView 裁剪框
*/
public void autoFillClipFrame(ClipFrameView frameView){
if(getDrawable() == null || frameView == null)return;
float left = frameView.getFramePosition().x;
float top = frameView.getFramePosition().y;
float width = frameView.getFrameWidth();
float height = frameView.getFrameHeight();
RectF dstRect = new RectF(left,top,left+width,top+height);
RectF srcRect = new RectF(0,0,getDrawable().getIntrinsicWidth(),getDrawable().getMinimumHeight());
Matrix newMatrix = new Matrix();
//将源矩阵矩阵填充到目标矩阵,这里选择对其左上,根据需求可以选其他模式
newMatrix.setRectToRect(srcRect,dstRect, Matrix.ScaleToFit.START);
setImageMatrix(newMatrix);
matrix = newMatrix;
invalidate();
}
/**
*设置图片
*
* @param filePath 图片的完整路径
* @param multiple 倍数,当图片宽或高大于Vie的宽或高multiple倍实行向下采样
*/
public void setImageFile(final String filePath,final int multiple){
post(new Runnable() {
@Override
public void run() {
//为了获取view的大小
Bitmap bitmap = getSmallBitmap(filePath,(int) mWidth,(int)mHeight,multiple);
if(bitmap != null)setImageBitmap(bitmap);
}
});
}
//计算图片的缩放大小
private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight,int multiple) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;//1是不缩放,2是缩小1/2,4是缩小1/4等
if (height > reqHeight *multiple|| width > reqWidth*multiple) {
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
private static Bitmap getSmallBitmap(String filePath, int w, int h,int multiple) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;//true的话,不会真的把bitmap加载到内存,但能获取bitmap的大小信息等
BitmapFactory.decodeFile(filePath, options);
options.inSampleSize = calculateInSampleSize(options, w, h,multiple);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(filePath, options);
}
}
| false | 1,692 | 5 | 1,926 | 5 | 1,969 | 5 | 1,926 | 5 | 2,458 | 13 | false | false | false | false | false | true |
59076_1 | package com.clam314.lame;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.Toast;
import static android.R.attr.path;
public class MainActivity extends AppCompatActivity {
private MediaRecorderButton btRecorder;
private ImageView btPlayer;
private String filePath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//创建播放时用的动画
AnimationDrawable frameDrawable = (AnimationDrawable) getResources().getDrawable(R.drawable.anim_voice_left);
btPlayer = (ImageView)findViewById(R.id.bt_player);
btPlayer.setImageDrawable(frameDrawable);
//动画显示在第一帧
frameDrawable.selectDrawable(0);
btPlayer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
if(TextUtils.isEmpty(filePath)){
Toast.makeText(v.getContext(),"文件路径错误",Toast.LENGTH_SHORT).show();
}else {
if(v.getTag() != null){
String tag = (String) v.getTag();
//语音正在播放,此时单击停止播放
if("showing".equals(tag)){
//释放资源
MediaPlayUtil.release();
((AnimationDrawable)((ImageView)v).getDrawable()).stop();
((AnimationDrawable)((ImageView)v).getDrawable()).selectDrawable(0);
v.setTag("showed");
return;
}
}
//开始播放语音,并开始动画
((AnimationDrawable)((ImageView)v).getDrawable()).start();
v.setTag("showing");
MediaPlayUtil.init(getApplicationContext());
MediaPlayUtil.playSound(filePath, new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
((AnimationDrawable)((ImageView)v).getDrawable()).stop();
((AnimationDrawable)((ImageView)v).getDrawable()).selectDrawable(0);
v.setTag("showed");
MediaPlayUtil.release();
}
});
}
}
});
btRecorder = (MediaRecorderButton)findViewById(R.id.bt_media_recorder);
btRecorder.setFinishListener(new MediaRecorderButton.RecorderFinishListener() {
@Override
public void onRecorderFinish(int status, String path, String second) {
if(status == MediaRecorderButton.RECORDER_SUCCESS){
filePath = path;
}
}
});
btRecorder.setRecorderStatusListener(new MediaRecorderButton.RecorderStatusListener() {
@Override
public void onStart(int status) {
Toast.makeText(MainActivity.this,"开始录音",Toast.LENGTH_SHORT).show();
}
@Override
public void onEnd(int status) {
//status除了是状态还有录音的秒数
switch (status){
case MediaRecorderButton.END_RECORDER_TOO_SHORT:
Toast.makeText(MainActivity.this,"讲话时间太短啦!",Toast.LENGTH_SHORT).show();
break;
case 10:
Toast.makeText(MainActivity.this,"录音50秒啦,10秒后自动发送",Toast.LENGTH_SHORT).show();
break;
case MediaRecorderButton.END_RECORDER_60S:
Toast.makeText(MainActivity.this,"录音已经自动发送",Toast.LENGTH_SHORT).show();
break;
}
}
});
}
}
| clam314/LameMp3ForAndroid | app/src/main/java/com/clam314/lame/MainActivity.java | 835 | //动画显示在第一帧 | line_comment | zh-cn | package com.clam314.lame;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.Toast;
import static android.R.attr.path;
public class MainActivity extends AppCompatActivity {
private MediaRecorderButton btRecorder;
private ImageView btPlayer;
private String filePath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//创建播放时用的动画
AnimationDrawable frameDrawable = (AnimationDrawable) getResources().getDrawable(R.drawable.anim_voice_left);
btPlayer = (ImageView)findViewById(R.id.bt_player);
btPlayer.setImageDrawable(frameDrawable);
//动画 <SUF>
frameDrawable.selectDrawable(0);
btPlayer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
if(TextUtils.isEmpty(filePath)){
Toast.makeText(v.getContext(),"文件路径错误",Toast.LENGTH_SHORT).show();
}else {
if(v.getTag() != null){
String tag = (String) v.getTag();
//语音正在播放,此时单击停止播放
if("showing".equals(tag)){
//释放资源
MediaPlayUtil.release();
((AnimationDrawable)((ImageView)v).getDrawable()).stop();
((AnimationDrawable)((ImageView)v).getDrawable()).selectDrawable(0);
v.setTag("showed");
return;
}
}
//开始播放语音,并开始动画
((AnimationDrawable)((ImageView)v).getDrawable()).start();
v.setTag("showing");
MediaPlayUtil.init(getApplicationContext());
MediaPlayUtil.playSound(filePath, new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
((AnimationDrawable)((ImageView)v).getDrawable()).stop();
((AnimationDrawable)((ImageView)v).getDrawable()).selectDrawable(0);
v.setTag("showed");
MediaPlayUtil.release();
}
});
}
}
});
btRecorder = (MediaRecorderButton)findViewById(R.id.bt_media_recorder);
btRecorder.setFinishListener(new MediaRecorderButton.RecorderFinishListener() {
@Override
public void onRecorderFinish(int status, String path, String second) {
if(status == MediaRecorderButton.RECORDER_SUCCESS){
filePath = path;
}
}
});
btRecorder.setRecorderStatusListener(new MediaRecorderButton.RecorderStatusListener() {
@Override
public void onStart(int status) {
Toast.makeText(MainActivity.this,"开始录音",Toast.LENGTH_SHORT).show();
}
@Override
public void onEnd(int status) {
//status除了是状态还有录音的秒数
switch (status){
case MediaRecorderButton.END_RECORDER_TOO_SHORT:
Toast.makeText(MainActivity.this,"讲话时间太短啦!",Toast.LENGTH_SHORT).show();
break;
case 10:
Toast.makeText(MainActivity.this,"录音50秒啦,10秒后自动发送",Toast.LENGTH_SHORT).show();
break;
case MediaRecorderButton.END_RECORDER_60S:
Toast.makeText(MainActivity.this,"录音已经自动发送",Toast.LENGTH_SHORT).show();
break;
}
}
});
}
}
| false | 695 | 6 | 835 | 7 | 889 | 6 | 835 | 7 | 1,092 | 11 | false | false | false | false | false | true |
36991_0 | package Graph.SPFA;
import java.util.LinkedList;
import java.util.Queue;
import Graph.basic.EdgePoint;
import Graph.basic.GraphList;
/**
* @author chenxi
* 中国人原创算法,屌炸天
* http://en.wikipedia.org/wiki/Shortest_Path_Faster_Algorithm
* 当然最关键的问题,他能够轻松解决两点之间多条边的问题,而不需要做过多的判断
* 想法超级自然,利用邻接链表的结构来做
*
* 1. 源点入队列
* 2. cur表示队首元素(dis是最新的值),弹出来
* 3. 更新所有和 cur 相连接的点,如果被更新的点,切不在q中,压入q
* 4. q不为空回到步骤2
*
*/
public class SPFA {
public int [] spfa(int s, GraphList g )
{
int dis[] = new int[g.count];
for(int i=0;i<dis.length;i++) dis[i] = Integer.MAX_VALUE;
Queue<Integer> q = new LinkedList<Integer>();
q.offer(s);
dis[s] = 0;
while(!q.isEmpty())
{
int cur = q.poll();
EdgePoint e = g.AdjecentList.get(cur).firstEdge;
while(e!=null)
{
int alter = dis[cur] + e.weight;
if(dis[e.index]> alter)
{
dis[e.index] = alter;
if(!q.contains(e.index))
q.offer(e.index);
}
e = e.next;
}
}
return dis;
}
}
| clarkchen/data_structure | src/main/java/Graph/SPFA/SPFA.java | 454 | /**
* @author chenxi
* 中国人原创算法,屌炸天
* http://en.wikipedia.org/wiki/Shortest_Path_Faster_Algorithm
* 当然最关键的问题,他能够轻松解决两点之间多条边的问题,而不需要做过多的判断
* 想法超级自然,利用邻接链表的结构来做
*
* 1. 源点入队列
* 2. cur表示队首元素(dis是最新的值),弹出来
* 3. 更新所有和 cur 相连接的点,如果被更新的点,切不在q中,压入q
* 4. q不为空回到步骤2
*
*/ | block_comment | zh-cn | package Graph.SPFA;
import java.util.LinkedList;
import java.util.Queue;
import Graph.basic.EdgePoint;
import Graph.basic.GraphList;
/**
* @au <SUF>*/
public class SPFA {
public int [] spfa(int s, GraphList g )
{
int dis[] = new int[g.count];
for(int i=0;i<dis.length;i++) dis[i] = Integer.MAX_VALUE;
Queue<Integer> q = new LinkedList<Integer>();
q.offer(s);
dis[s] = 0;
while(!q.isEmpty())
{
int cur = q.poll();
EdgePoint e = g.AdjecentList.get(cur).firstEdge;
while(e!=null)
{
int alter = dis[cur] + e.weight;
if(dis[e.index]> alter)
{
dis[e.index] = alter;
if(!q.contains(e.index))
q.offer(e.index);
}
e = e.next;
}
}
return dis;
}
}
| false | 364 | 151 | 454 | 170 | 433 | 150 | 454 | 170 | 572 | 232 | false | false | false | false | false | true |
33293_0 | /**
*
*/
package wc3211;
import java.util.*;
/**
* @author chenxi
* 直接给这道题跪了,后来想想确实是大神啊
* 两个人一起洗一堆衣服,给定了每件衣服的时间,求最短时间
* 贪心的思路:将时间排序,两人先一起洗最长时间的衣服,先洗碗的挑选最长时间的衣服进行清洗
* 这个的确无法证明是最优的
*
*
* 背包问题的思路:两个人的清洗时间加起来肯定是总时间,而且一定一个人长一个人短,
* 那就假设男的有一个 sum[i]/2 的包,然后他来捡衣服,要捡的最多
* 剩下的女的来洗,那么女的时间肯定更多,应为男的至多 一半,女的至少一半
*
*/
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner s = new Scanner( System.in);
//m and n;
while (true){
int m,n;
m = s.nextInt();n=s.nextInt();
if(m==0&&n==0) break;
List<String> l = new ArrayList<String>();
int i,j;
for(i=0;i<m;i++)
{
String color = s.next();
l.add(color);
}
List<List<Integer>> time = new ArrayList<List<Integer>>();
for(i=0;i<m;i++)
{
time.add(new ArrayList<Integer>());
}
for(i=0;i<n;i++)
{
int t = s.nextInt();
String color = s.next();
j = l.indexOf(color);
time.get(j).add(t);
}
int sum [] = new int[m];
for(i=0;i<m;i++)
{
for(int v:time.get(i)) sum[i] += v;
}
int rt=0;
List<Integer> temp ;
for(i=0;i<m;i++)
{
temp = time.get(i);
int dp[] = new int[sum[i]/2+1];
for(int c:temp)
{
for(int v = sum[i]/2;v>=c;v--)
{
if(v-c>=0)
dp[v] = max(dp[v],dp[v-c]+c);
}
}
rt += sum[i] - dp[sum[i]/2];
}
System.out.println(rt);
}
}
static int max(int a, int b)
{
return a>b?a:b;
}
}
/*
测试数据
3 5
red blue yellow
2 red
3 blue
4 blue
6 red
3 yellow
1 1
red
5 red
2 1
red green
3 green
3 2
red green yellow
3 green
4 yellow
1 4
red
1 red
8 red
3 red
10 red
1 4
red
1 red
3 red
10 red
8 red
1 5
red
1 red
3 red
10 red
8 red
11 red
1 3
red
11 red
3 red
10 red
1 0
red
3 4
red y g
11 red
1 y
3 g
10 g
*/ | clarkchen/poj | 3211Washing Clothes/wc3211/Main.java | 940 | /**
* @author chenxi
* 直接给这道题跪了,后来想想确实是大神啊
* 两个人一起洗一堆衣服,给定了每件衣服的时间,求最短时间
* 贪心的思路:将时间排序,两人先一起洗最长时间的衣服,先洗碗的挑选最长时间的衣服进行清洗
* 这个的确无法证明是最优的
*
*
* 背包问题的思路:两个人的清洗时间加起来肯定是总时间,而且一定一个人长一个人短,
* 那就假设男的有一个 sum[i]/2 的包,然后他来捡衣服,要捡的最多
* 剩下的女的来洗,那么女的时间肯定更多,应为男的至多 一半,女的至少一半
*
*/ | block_comment | zh-cn | /**
*
*/
package wc3211;
import java.util.*;
/**
* @au <SUF>*/
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner s = new Scanner( System.in);
//m and n;
while (true){
int m,n;
m = s.nextInt();n=s.nextInt();
if(m==0&&n==0) break;
List<String> l = new ArrayList<String>();
int i,j;
for(i=0;i<m;i++)
{
String color = s.next();
l.add(color);
}
List<List<Integer>> time = new ArrayList<List<Integer>>();
for(i=0;i<m;i++)
{
time.add(new ArrayList<Integer>());
}
for(i=0;i<n;i++)
{
int t = s.nextInt();
String color = s.next();
j = l.indexOf(color);
time.get(j).add(t);
}
int sum [] = new int[m];
for(i=0;i<m;i++)
{
for(int v:time.get(i)) sum[i] += v;
}
int rt=0;
List<Integer> temp ;
for(i=0;i<m;i++)
{
temp = time.get(i);
int dp[] = new int[sum[i]/2+1];
for(int c:temp)
{
for(int v = sum[i]/2;v>=c;v--)
{
if(v-c>=0)
dp[v] = max(dp[v],dp[v-c]+c);
}
}
rt += sum[i] - dp[sum[i]/2];
}
System.out.println(rt);
}
}
static int max(int a, int b)
{
return a>b?a:b;
}
}
/*
测试数据
3 5
red blue yellow
2 red
3 blue
4 blue
6 red
3 yellow
1 1
red
5 red
2 1
red green
3 green
3 2
red green yellow
3 green
4 yellow
1 4
red
1 red
8 red
3 red
10 red
1 4
red
1 red
3 red
10 red
8 red
1 5
red
1 red
3 red
10 red
8 red
11 red
1 3
red
11 red
3 red
10 red
1 0
red
3 4
red y g
11 red
1 y
3 g
10 g
*/ | false | 767 | 178 | 940 | 229 | 907 | 169 | 940 | 229 | 1,279 | 316 | false | false | false | false | false | true |
65623_3 | package com.pj.project4sp.role4permission;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* 角色权限中间表
* @author kong
*
*/
@Service
public class SpRolePermissionService {
@Autowired
SpRolePermissionMapper spRolePermissionMapper;
/**
* 获取指定角色的所有权限码 【增加缓存】
*/
@Cacheable(value="api_pcode_list", key="#roleId")
public List<String> getPcodeByRid(long roleId){
return spRolePermissionMapper.getPcodeByRoleId(roleId);
}
/**
* [T] 修改角色的一组权限关系 【清除缓存 】
*/
@Transactional(rollbackFor = Exception.class)
@CacheEvict(value= {"api_pcode_list"}, key="#roleId")
public int updateRoleMenu(long roleId, List<String> pcodeArray){
// 万一为空
if(pcodeArray == null){
pcodeArray = new ArrayList<>();
}
// 先删
spRolePermissionMapper.deleteByRoleId(roleId);
// 再添加
for(String pcode : pcodeArray){
spRolePermissionMapper.add(roleId, pcode);
}
// 返回
return pcodeArray.size();
}
}
| click33/Sa-plus | sp-server/src/main/java/com/pj/project4sp/role4permission/SpRolePermissionService.java | 390 | // 万一为空 | line_comment | zh-cn | package com.pj.project4sp.role4permission;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* 角色权限中间表
* @author kong
*
*/
@Service
public class SpRolePermissionService {
@Autowired
SpRolePermissionMapper spRolePermissionMapper;
/**
* 获取指定角色的所有权限码 【增加缓存】
*/
@Cacheable(value="api_pcode_list", key="#roleId")
public List<String> getPcodeByRid(long roleId){
return spRolePermissionMapper.getPcodeByRoleId(roleId);
}
/**
* [T] 修改角色的一组权限关系 【清除缓存 】
*/
@Transactional(rollbackFor = Exception.class)
@CacheEvict(value= {"api_pcode_list"}, key="#roleId")
public int updateRoleMenu(long roleId, List<String> pcodeArray){
// 万一 <SUF>
if(pcodeArray == null){
pcodeArray = new ArrayList<>();
}
// 先删
spRolePermissionMapper.deleteByRoleId(roleId);
// 再添加
for(String pcode : pcodeArray){
spRolePermissionMapper.add(roleId, pcode);
}
// 返回
return pcodeArray.size();
}
}
| false | 321 | 5 | 390 | 6 | 407 | 5 | 390 | 6 | 482 | 7 | false | false | false | false | false | true |
27833_31 | package com.fly.re.out;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import com.fly.re.model.Column;
/**
* String处理工具包
* @author kongyongshun
*
*/
public class OutUtil {
// 防止 一次有变,到处乱改
//static String path_fly_jdbc = "com.fly.jdbc";
// static String fly = "Fly";
// static String fly_run = "FlyRun";
// static String fly_code = "FlyCode";
// static String sql_fly = "SqlFly";
// static String fly_factory = "FlyFactory";
//
// static String path_fly_util = "com.fly.util";
static String package_fly = "com.fly.jdbc"; // 框架 总包地址
static String package_Page = package_fly + ".pageing"; // Page 包地址
static String package_AjaxJson = "com.pj.utils"; // AjaxJson 包地址
static String class_SqlFly = "SqlFly"; // SqlFly 类名
static String class_SqlFlyFactory = "SqlFlyFactory"; // SqlFlyFactory 类名
static String class_FlyUtil = "FlyUtil"; //FlyUtil 类名
static String class_Page = "Page"; //Page 类名
static String class_SAP = "SAP"; //SAP 类名
static String class_AjaxJson = "AjaxJson"; // AjaxJson 类名
static String import_sqlfly = "import " + package_fly + ".*;"; // sqlfly 本尊导入
static String import_Page = "import " + package_Page + "." + class_Page + ";"; // Page 导入
static String method_add = "add"; // 函数名 增
static String method_delete = "delete"; // 函数名 删
static String method_update = "update"; // 函数名 改
static String method_getById = "getById"; // 函数名 查
static String method_getList = "getList"; // 函数名 查 - 集合
// ===================== 工具型方法 =========================
// 将指定单词首字母大写;
static String wordFirstBig(String str) {
return str.substring(0, 1).toUpperCase() + str.substring(1, str.length());
}
// 将指定单词首字母小写;
static String wordFirstSmall(String str) {
return str.substring(0, 1).toLowerCase() + str.substring(1, str.length());
}
// 去掉字符串最后一个字符
static String strLastDrop(String str) {
try {
return str.substring(0, str.length() - 1);
} catch (StringIndexOutOfBoundsException e) {
return str;
}
}
// 去掉字符串最后x个字符
static String strLastDrop(String str, int x) {
try {
return str.substring(0, str.length() - x);
} catch (StringIndexOutOfBoundsException e) {
return str;
}
}
// 单词大小写转换
// way=方式(1转小写 2转大写,其它不变)
static String wordChangeBigSmall(String str, int way) {
if (way == 1) {
str = str.toLowerCase();
} else if (way == 2) {
str = str.toUpperCase();
}
return str;
}
// 快速组织普通方法注释
static String getNotes(String str) {
return "\t// " + str + " \r\n";
}
// 快速组织文档注释,三行,一缩进
static String getDoc(String str) {
return "\t/**\r\n\t * " + str + " \r\n\t */\r\n";
}
// 指定字符串的getter形式
static String getSetGet(String str) {
if (str == null || str.equals("")) {
return str;
}
if (str.length() == 1 || str.charAt(1) == '_' || str.charAt(1) == '$') {
return wordFirstBig(str);
}
if (Character.isLowerCase(str.charAt(0)) && Character.isLowerCase(str.charAt(1))) {
return wordFirstBig(str);
} else {
return str;
}
}
// 指定字符串的字符串下划线转大写模式
public static String wordEachBig(String str){
String newStr = "";
for (String s : str.split("_")) {
newStr += wordFirstBig(s);
}
return newStr;
}
// 获取字符串,true返回第一个,false返回第2个
public static String getString(boolean bo, String s1, String s2) {
return bo ? s1 : s2;
}
// 获取toString的doc
public static String get_doc_toString() {
return "\r\n\t/* (non-Javadoc)\r\n\t * @see java.lang.Object#toString()\r\n\t */\r\n\t@Override\r\n";
}
// 获取指定字段的 gettet 方法
// 字段名、注释
public static String get_getMethod(Column column) {
String getMethod = OutUtil.getDoc("@return " + column.comment);
getMethod += "\tpublic " + column.javaType + " get" + OutUtil.getSetGet(column.name) +
"(){\r\n\t\treturn " + column.name + ";\r\n\t}";
return getMethod;
}
// 获取指定字段的 settet 方法
// 字段名、注释
public static String get_setMethod(Column column, String class_name) {
String setMethod = OutUtil.getDoc("@param " + column.name + " " + column.comment);
setMethod += "\tpublic " + class_name + " set" + OutUtil.getSetGet(column.name) +
"(" + column.javaType + " " + column.name + ") {\r\n\t\tthis." + column.name +
" = " + column.name + ";\r\n\t\treturn this;\r\n\t}";
return setMethod;
}
// 获取SO的getPage方法代码
public static String get_getPage() {
String str =
"\tpublic Page getPage() {\r\n" +
"\t\tif(this.page == null){\r\n" +
"\t\t\tthis.page = Page.getPage(this.pageNo, this.pageSize);\r\n" +
"\t\t}\r\n" +
"\t\treturn this.page;\r\n" +
"\t}";
return str;
}
// 获取SO的getSortString方法代码
public static String get_getSortString() {
String str = "\tpublic String getSortString(){\r\n" +
"\t\treturn \" order by \" + arr[this.sort_type];\r\n" +
"\t}\r\n";
return str;
}
// 获取getSqlFly()的代码
public static String get_getSqlFly() {
String getfly = "\t// 底层SqlFly对象\r\n\tprivate " + OutUtil.class_SqlFly
+ " getSqlFly() {\r\n\t\treturn " + OutUtil.class_SqlFlyFactory
+ ".getSqlFly();\r\n\t}\r\n\r\n";
return getfly;
}
// ===================== 代码doc相关 markdown =========================
public static String fzDoc(String title, String api, String args_str, String return_str) {
String str = "--- \r\n";
str += "### " + title + "\r\n";
str += "- 接口 \r\n```\r\n\t" + api + "\r\n```\r\n";
str += "- 参数\r\n```\r\n" + args_str + "```\r\n";
str += "- 返回\r\n```\r\n" + return_str + "```\r\n";
str += "\r\n\r\n";
return str;
}
// ===================== 业务方法 =========================
// 输出指定字符串
static void print(String str){
System.out.print(str);
}
// 指定地址,写入指定内容
static void outFile(String filePath, String txt){
File file = new File(filePath);
File fileDir = new File(file.getParent());
if(fileDir.exists() == false){
new File(file.getParent()).mkdirs();
}
try {
file.createNewFile();
Writer fw = new FileWriter(file.getAbsolutePath());
fw.write(txt);
fw.flush();
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// 指定包的Spring工厂类
public static String SpringBeanFC(String projectPath, String packagePath, String fcName){
File wjj = new File(projectPath, packagePath.replace(".", "\\")); // 创建路径
String[] classNameArray = wjj.list();
String _package = "package " + packagePath + ";\r\n\r\n";
String _import = "\r\nimport org.springframework.beans.factory.annotation.Autowired;\r\n";
_import += "import org.springframework.stereotype.Component;\r\n\r\n";
String fc = _package + _import + "/**\r\n* 工厂类\r\n*/\r\n@Component\r\n" + "public class " + fcName + "{\r\n\r\n\r\n"; // 工厂类
for (String className : classNameArray) {
try{
if(className.indexOf(".java")==-1){
continue;
}
className = className.replace(".java","");
String Xxx = wordFirstBig(className); //大写形式
String xXX = wordFirstSmall(className); //小写形式
fc += "\t/** */\r\n";
fc += "\tpublic static "+className+" "+xXX+";\r\n";
fc += "\t@Autowired\r\n";
fc += "\tpublic void set"+Xxx+"("+Xxx+" "+xXX+") {\r\n";
fc += "\t\t" + fcName + "."+xXX+" = "+xXX+";\r\n";
fc += "\t}\r\n\r\n\r\n";
}catch(Exception e){
e.printStackTrace();
}
}
fc += "}";
return fc;
}
// 生成 FC指定一个类型的代码注入体
public static String getFCone(String className, String comment) {
String varName = wordFirstSmall(className);
String str =
"\t/** " + comment + " */\r\n" +
"\tpublic static " + className + " " + varName + ";\r\n" +
"\t@Autowired\r\n" +
"\tpublic void set" + className + "(" + className + " " + varName + ") {\r\n" +
"\t\tFC." + varName + " = " + varName + ";\r\n" +
"\t}\r\n";
return str;
}
}
| click33/sqlfly | sqlfly-dev/src/main/java/com/fly/re/out/OutUtil.java | 2,895 | // way=方式(1转小写 2转大写,其它不变) | line_comment | zh-cn | package com.fly.re.out;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import com.fly.re.model.Column;
/**
* String处理工具包
* @author kongyongshun
*
*/
public class OutUtil {
// 防止 一次有变,到处乱改
//static String path_fly_jdbc = "com.fly.jdbc";
// static String fly = "Fly";
// static String fly_run = "FlyRun";
// static String fly_code = "FlyCode";
// static String sql_fly = "SqlFly";
// static String fly_factory = "FlyFactory";
//
// static String path_fly_util = "com.fly.util";
static String package_fly = "com.fly.jdbc"; // 框架 总包地址
static String package_Page = package_fly + ".pageing"; // Page 包地址
static String package_AjaxJson = "com.pj.utils"; // AjaxJson 包地址
static String class_SqlFly = "SqlFly"; // SqlFly 类名
static String class_SqlFlyFactory = "SqlFlyFactory"; // SqlFlyFactory 类名
static String class_FlyUtil = "FlyUtil"; //FlyUtil 类名
static String class_Page = "Page"; //Page 类名
static String class_SAP = "SAP"; //SAP 类名
static String class_AjaxJson = "AjaxJson"; // AjaxJson 类名
static String import_sqlfly = "import " + package_fly + ".*;"; // sqlfly 本尊导入
static String import_Page = "import " + package_Page + "." + class_Page + ";"; // Page 导入
static String method_add = "add"; // 函数名 增
static String method_delete = "delete"; // 函数名 删
static String method_update = "update"; // 函数名 改
static String method_getById = "getById"; // 函数名 查
static String method_getList = "getList"; // 函数名 查 - 集合
// ===================== 工具型方法 =========================
// 将指定单词首字母大写;
static String wordFirstBig(String str) {
return str.substring(0, 1).toUpperCase() + str.substring(1, str.length());
}
// 将指定单词首字母小写;
static String wordFirstSmall(String str) {
return str.substring(0, 1).toLowerCase() + str.substring(1, str.length());
}
// 去掉字符串最后一个字符
static String strLastDrop(String str) {
try {
return str.substring(0, str.length() - 1);
} catch (StringIndexOutOfBoundsException e) {
return str;
}
}
// 去掉字符串最后x个字符
static String strLastDrop(String str, int x) {
try {
return str.substring(0, str.length() - x);
} catch (StringIndexOutOfBoundsException e) {
return str;
}
}
// 单词大小写转换
// wa <SUF>
static String wordChangeBigSmall(String str, int way) {
if (way == 1) {
str = str.toLowerCase();
} else if (way == 2) {
str = str.toUpperCase();
}
return str;
}
// 快速组织普通方法注释
static String getNotes(String str) {
return "\t// " + str + " \r\n";
}
// 快速组织文档注释,三行,一缩进
static String getDoc(String str) {
return "\t/**\r\n\t * " + str + " \r\n\t */\r\n";
}
// 指定字符串的getter形式
static String getSetGet(String str) {
if (str == null || str.equals("")) {
return str;
}
if (str.length() == 1 || str.charAt(1) == '_' || str.charAt(1) == '$') {
return wordFirstBig(str);
}
if (Character.isLowerCase(str.charAt(0)) && Character.isLowerCase(str.charAt(1))) {
return wordFirstBig(str);
} else {
return str;
}
}
// 指定字符串的字符串下划线转大写模式
public static String wordEachBig(String str){
String newStr = "";
for (String s : str.split("_")) {
newStr += wordFirstBig(s);
}
return newStr;
}
// 获取字符串,true返回第一个,false返回第2个
public static String getString(boolean bo, String s1, String s2) {
return bo ? s1 : s2;
}
// 获取toString的doc
public static String get_doc_toString() {
return "\r\n\t/* (non-Javadoc)\r\n\t * @see java.lang.Object#toString()\r\n\t */\r\n\t@Override\r\n";
}
// 获取指定字段的 gettet 方法
// 字段名、注释
public static String get_getMethod(Column column) {
String getMethod = OutUtil.getDoc("@return " + column.comment);
getMethod += "\tpublic " + column.javaType + " get" + OutUtil.getSetGet(column.name) +
"(){\r\n\t\treturn " + column.name + ";\r\n\t}";
return getMethod;
}
// 获取指定字段的 settet 方法
// 字段名、注释
public static String get_setMethod(Column column, String class_name) {
String setMethod = OutUtil.getDoc("@param " + column.name + " " + column.comment);
setMethod += "\tpublic " + class_name + " set" + OutUtil.getSetGet(column.name) +
"(" + column.javaType + " " + column.name + ") {\r\n\t\tthis." + column.name +
" = " + column.name + ";\r\n\t\treturn this;\r\n\t}";
return setMethod;
}
// 获取SO的getPage方法代码
public static String get_getPage() {
String str =
"\tpublic Page getPage() {\r\n" +
"\t\tif(this.page == null){\r\n" +
"\t\t\tthis.page = Page.getPage(this.pageNo, this.pageSize);\r\n" +
"\t\t}\r\n" +
"\t\treturn this.page;\r\n" +
"\t}";
return str;
}
// 获取SO的getSortString方法代码
public static String get_getSortString() {
String str = "\tpublic String getSortString(){\r\n" +
"\t\treturn \" order by \" + arr[this.sort_type];\r\n" +
"\t}\r\n";
return str;
}
// 获取getSqlFly()的代码
public static String get_getSqlFly() {
String getfly = "\t// 底层SqlFly对象\r\n\tprivate " + OutUtil.class_SqlFly
+ " getSqlFly() {\r\n\t\treturn " + OutUtil.class_SqlFlyFactory
+ ".getSqlFly();\r\n\t}\r\n\r\n";
return getfly;
}
// ===================== 代码doc相关 markdown =========================
public static String fzDoc(String title, String api, String args_str, String return_str) {
String str = "--- \r\n";
str += "### " + title + "\r\n";
str += "- 接口 \r\n```\r\n\t" + api + "\r\n```\r\n";
str += "- 参数\r\n```\r\n" + args_str + "```\r\n";
str += "- 返回\r\n```\r\n" + return_str + "```\r\n";
str += "\r\n\r\n";
return str;
}
// ===================== 业务方法 =========================
// 输出指定字符串
static void print(String str){
System.out.print(str);
}
// 指定地址,写入指定内容
static void outFile(String filePath, String txt){
File file = new File(filePath);
File fileDir = new File(file.getParent());
if(fileDir.exists() == false){
new File(file.getParent()).mkdirs();
}
try {
file.createNewFile();
Writer fw = new FileWriter(file.getAbsolutePath());
fw.write(txt);
fw.flush();
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// 指定包的Spring工厂类
public static String SpringBeanFC(String projectPath, String packagePath, String fcName){
File wjj = new File(projectPath, packagePath.replace(".", "\\")); // 创建路径
String[] classNameArray = wjj.list();
String _package = "package " + packagePath + ";\r\n\r\n";
String _import = "\r\nimport org.springframework.beans.factory.annotation.Autowired;\r\n";
_import += "import org.springframework.stereotype.Component;\r\n\r\n";
String fc = _package + _import + "/**\r\n* 工厂类\r\n*/\r\n@Component\r\n" + "public class " + fcName + "{\r\n\r\n\r\n"; // 工厂类
for (String className : classNameArray) {
try{
if(className.indexOf(".java")==-1){
continue;
}
className = className.replace(".java","");
String Xxx = wordFirstBig(className); //大写形式
String xXX = wordFirstSmall(className); //小写形式
fc += "\t/** */\r\n";
fc += "\tpublic static "+className+" "+xXX+";\r\n";
fc += "\t@Autowired\r\n";
fc += "\tpublic void set"+Xxx+"("+Xxx+" "+xXX+") {\r\n";
fc += "\t\t" + fcName + "."+xXX+" = "+xXX+";\r\n";
fc += "\t}\r\n\r\n\r\n";
}catch(Exception e){
e.printStackTrace();
}
}
fc += "}";
return fc;
}
// 生成 FC指定一个类型的代码注入体
public static String getFCone(String className, String comment) {
String varName = wordFirstSmall(className);
String str =
"\t/** " + comment + " */\r\n" +
"\tpublic static " + className + " " + varName + ";\r\n" +
"\t@Autowired\r\n" +
"\tpublic void set" + className + "(" + className + " " + varName + ") {\r\n" +
"\t\tFC." + varName + " = " + varName + ";\r\n" +
"\t}\r\n";
return str;
}
}
| false | 2,499 | 18 | 2,895 | 19 | 2,942 | 18 | 2,895 | 19 | 3,548 | 23 | false | false | false | false | false | true |
37153_14 | package com.redxun.hr.core.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.Size;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.hibernate.validator.constraints.NotEmpty;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.redxun.core.annotion.table.FieldDefine;
import com.redxun.core.annotion.table.TableDefine;
import com.redxun.core.entity.BaseTenantEntity;
import com.redxun.core.json.JsonDateSerializer;
/**
* <pre>
*
* 描述:HrDutyRegister实体类定义
* TODO: add class/table comments
* 构建组:miweb
* 作者:keith
* 邮箱: keith@redxun.cn
* 日期:2014-2-1-上午12:52:41
* 版权:广州红迅软件有限公司版权所有
* </pre>
*/
@Entity
@Table(name = "HR_DUTY_REGISTER")
@TableDefine(title = "考勤登记记录")
public class HrDutyRegister extends BaseTenantEntity {
public final static String TYPE_INFLAG="1";
public final static String TYPE_OFFFLAG="2";
@FieldDefine(title = "PKID")
@Id
@Column(name = "REGISTER_ID_")
protected String registerId;
/* 登记时间 */
@FieldDefine(title = "登记时间")
@Column(name = "REGISTER_TIME_")
protected java.util.Date registerTime;
/* 登记标识 */
@FieldDefine(title = "登记标识")
@Column(name = "REG_FLAG_")
protected Short regFlag;
/* 迟到或早退分钟 正常上班时为0 */
@FieldDefine(title = "迟到或早退分钟 正常上班时为0")
@Column(name = "REG_MINS_")
protected Long regMins;
/* 迟到原因 */
@FieldDefine(title = "迟到原因")
@Column(name = "REASON_")
@Size(max = 128)
protected String reason;
/* 周几 */
@FieldDefine(title = "周几")
@Column(name = "DAYOFWEEK_")
protected Long dayofweek;
/* 上下班标识 1=签到 2=签退 */
@FieldDefine(title = "上下班标识 1=签到 2=签退")
@Column(name = "IN_OFF_FLAG_")
@Size(max = 8)
@NotEmpty
protected String inOffFlag;
/* 班制ID */
@FieldDefine(title = "班制ID")
@Column(name = "SYSTEM_ID_")
@Size(max = 64)
protected String systemId;
/* 班次ID */
@FieldDefine(title = "班次ID")
@Column(name = "SECTION_ID_")
@Size(max = 64)
protected String sectionId;
/* 日期 */
@FieldDefine(title = "日期")
@Column(name = "DATE_")
protected java.util.Date date;
/* 用户名 */
@FieldDefine(title = "用户名")
@Column(name = "USER_NAME_")
@Size(max = 64)
protected String userName;
/* 经度 */
@FieldDefine(title = "经度")
@Column(name = "LONGITUDE_")
protected Double longitude;
/* 纬度 */
@FieldDefine(title = "纬度")
@Column(name = "LATITUDE_")
protected Double latitude;
/* 地址详情 */
@FieldDefine(title = "地址详情")
@Column(name = "ADDRESSES_")
protected String addresses;
/* 签到备注 */
@FieldDefine(title = "签到备注")
@Column(name = "SIGNREMARK_")
protected String signRemark;
/* 签到距离 */
@FieldDefine(title = "签到距离")
@Column(name = "DISTANCE_")
protected Integer distance;
/**
* Default Empty Constructor for class HrDutyRegister
*/
public HrDutyRegister() {
super();
}
/**
* Default Key Fields Constructor for class HrDutyRegister
*/
public HrDutyRegister(String in_registerId) {
this.setRegisterId(in_registerId);
}
/**
* 登记ID * @return String
*/
public String getRegisterId() {
return this.registerId;
}
/**
* 设置 登记ID
*/
public void setRegisterId(String aValue) {
this.registerId = aValue;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@JsonSerialize(using=JsonDateSerializer.class)
public java.util.Date getDate() {
return date;
}
public void setDate(java.util.Date date) {
this.date = date;
}
public String getSystemId() {
return systemId;
}
public void setSystemId(String systemId) {
this.systemId = systemId;
}
public String getSectionId() {
return sectionId;
}
public void setSectionId(String sectionId) {
this.sectionId = sectionId;
}
/**
* 登记时间 * @return java.util.Date
*/
@JsonSerialize(using=JsonDateSerializer.class)
public java.util.Date getRegisterTime() {
return this.registerTime;
}
/**
* 设置 登记时间
*/
public void setRegisterTime(java.util.Date aValue) {
this.registerTime = aValue;
}
/**
* 登记标识 1=正常登记(上班,下班) 2=迟到 3=早退 4=休息 5=旷工 6=放假 * @return Short
*/
public Short getRegFlag() {
return this.regFlag;
}
/**
* 设置 登记标识 1=正常登记(上班,下班) 2=迟到 3=早退 4=休息 5=旷工 6=放假
*/
public void setRegFlag(Short aValue) {
this.regFlag = aValue;
}
/**
* 迟到或早退分钟 正常上班时为0 * @return Long
*/
public Long getRegMins() {
return this.regMins;
}
/**
* 设置 迟到或早退分钟 正常上班时为0
*/
public void setRegMins(Long aValue) {
this.regMins = aValue;
}
/**
* 迟到原因 * @return String
*/
public String getReason() {
return this.reason;
}
/**
* 设置 迟到原因
*/
public void setReason(String aValue) {
this.reason = aValue;
}
/**
* 周几 * @return Long
*/
public Long getDayofweek() {
return this.dayofweek;
}
/**
* 设置 周几
*/
public void setDayofweek(Long aValue) {
this.dayofweek = aValue;
}
/**
* 上下班标识 1=签到 2=签退 * @return String
*/
public String getInOffFlag() {
return this.inOffFlag;
}
/**
* 设置 上下班标识 1=签到 2=签退
*/
public void setInOffFlag(String aValue) {
this.inOffFlag = aValue;
}
@Override
public String getIdentifyLabel() {
return this.registerId;
}
@Override
public Serializable getPkId() {
return this.registerId;
}
@Override
public void setPkId(Serializable pkId) {
this.registerId = (String) pkId;
}
public Double getLongitude() {
return longitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
public Double getLatitude() {
return latitude;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
public String getAddresses() {
return addresses;
}
public void setAddresses(String addresses) {
this.addresses = addresses;
}
public String getSignRemark() {
return signRemark;
}
public void setSignRemark(String signRemark) {
this.signRemark = signRemark;
}
public Integer getDistance() {
return distance;
}
public void setDistance(Integer distance) {
this.distance = distance;
}
/**
* @see java.lang.Object#equals(Object)
*/
public boolean equals(Object object) {
if (!(object instanceof HrDutyRegister)) {
return false;
}
HrDutyRegister rhs = (HrDutyRegister) object;
return new EqualsBuilder().append(this.registerId, rhs.registerId).append(this.registerTime, rhs.registerTime)
.append(this.regFlag, rhs.regFlag).append(this.regMins, rhs.regMins).append(this.reason, rhs.reason)
.append(this.dayofweek, rhs.dayofweek).append(this.inOffFlag, rhs.inOffFlag)
.append(this.tenantId, rhs.tenantId).append(this.createBy, rhs.createBy)
.append(this.createTime, rhs.createTime).append(this.updateBy, rhs.updateBy)
.append(this.updateTime, rhs.updateTime).isEquals();
}
/**
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
return new HashCodeBuilder(-82280557, -700257973).append(this.registerId).append(this.registerTime)
.append(this.regFlag).append(this.regMins).append(this.reason).append(this.dayofweek)
.append(this.inOffFlag).append(this.tenantId).append(this.createBy).append(this.createTime)
.append(this.updateBy).append(this.updateTime).toHashCode();
}
/**
* @see java.lang.Object#toString()
*/
public String toString() {
return new ToStringBuilder(this).append("registerId", this.registerId).append("registerTime", this.registerTime)
.append("regFlag", this.regFlag).append("regMins", this.regMins).append("reason", this.reason)
.append("dayofweek", this.dayofweek).append("inOffFlag", this.inOffFlag)
.append("tenantId", this.tenantId).append("createBy", this.createBy)
.append("createTime", this.createTime).append("updateBy", this.updateBy)
.append("updateTime", this.updateTime).toString();
}
}
| clickear/jsaas | src/main/java/com/redxun/hr/core/entity/HrDutyRegister.java | 2,923 | /* 签到备注 */ | block_comment | zh-cn | package com.redxun.hr.core.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.Size;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.hibernate.validator.constraints.NotEmpty;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.redxun.core.annotion.table.FieldDefine;
import com.redxun.core.annotion.table.TableDefine;
import com.redxun.core.entity.BaseTenantEntity;
import com.redxun.core.json.JsonDateSerializer;
/**
* <pre>
*
* 描述:HrDutyRegister实体类定义
* TODO: add class/table comments
* 构建组:miweb
* 作者:keith
* 邮箱: keith@redxun.cn
* 日期:2014-2-1-上午12:52:41
* 版权:广州红迅软件有限公司版权所有
* </pre>
*/
@Entity
@Table(name = "HR_DUTY_REGISTER")
@TableDefine(title = "考勤登记记录")
public class HrDutyRegister extends BaseTenantEntity {
public final static String TYPE_INFLAG="1";
public final static String TYPE_OFFFLAG="2";
@FieldDefine(title = "PKID")
@Id
@Column(name = "REGISTER_ID_")
protected String registerId;
/* 登记时间 */
@FieldDefine(title = "登记时间")
@Column(name = "REGISTER_TIME_")
protected java.util.Date registerTime;
/* 登记标识 */
@FieldDefine(title = "登记标识")
@Column(name = "REG_FLAG_")
protected Short regFlag;
/* 迟到或早退分钟 正常上班时为0 */
@FieldDefine(title = "迟到或早退分钟 正常上班时为0")
@Column(name = "REG_MINS_")
protected Long regMins;
/* 迟到原因 */
@FieldDefine(title = "迟到原因")
@Column(name = "REASON_")
@Size(max = 128)
protected String reason;
/* 周几 */
@FieldDefine(title = "周几")
@Column(name = "DAYOFWEEK_")
protected Long dayofweek;
/* 上下班标识 1=签到 2=签退 */
@FieldDefine(title = "上下班标识 1=签到 2=签退")
@Column(name = "IN_OFF_FLAG_")
@Size(max = 8)
@NotEmpty
protected String inOffFlag;
/* 班制ID */
@FieldDefine(title = "班制ID")
@Column(name = "SYSTEM_ID_")
@Size(max = 64)
protected String systemId;
/* 班次ID */
@FieldDefine(title = "班次ID")
@Column(name = "SECTION_ID_")
@Size(max = 64)
protected String sectionId;
/* 日期 */
@FieldDefine(title = "日期")
@Column(name = "DATE_")
protected java.util.Date date;
/* 用户名 */
@FieldDefine(title = "用户名")
@Column(name = "USER_NAME_")
@Size(max = 64)
protected String userName;
/* 经度 */
@FieldDefine(title = "经度")
@Column(name = "LONGITUDE_")
protected Double longitude;
/* 纬度 */
@FieldDefine(title = "纬度")
@Column(name = "LATITUDE_")
protected Double latitude;
/* 地址详情 */
@FieldDefine(title = "地址详情")
@Column(name = "ADDRESSES_")
protected String addresses;
/* 签到备 <SUF>*/
@FieldDefine(title = "签到备注")
@Column(name = "SIGNREMARK_")
protected String signRemark;
/* 签到距离 */
@FieldDefine(title = "签到距离")
@Column(name = "DISTANCE_")
protected Integer distance;
/**
* Default Empty Constructor for class HrDutyRegister
*/
public HrDutyRegister() {
super();
}
/**
* Default Key Fields Constructor for class HrDutyRegister
*/
public HrDutyRegister(String in_registerId) {
this.setRegisterId(in_registerId);
}
/**
* 登记ID * @return String
*/
public String getRegisterId() {
return this.registerId;
}
/**
* 设置 登记ID
*/
public void setRegisterId(String aValue) {
this.registerId = aValue;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@JsonSerialize(using=JsonDateSerializer.class)
public java.util.Date getDate() {
return date;
}
public void setDate(java.util.Date date) {
this.date = date;
}
public String getSystemId() {
return systemId;
}
public void setSystemId(String systemId) {
this.systemId = systemId;
}
public String getSectionId() {
return sectionId;
}
public void setSectionId(String sectionId) {
this.sectionId = sectionId;
}
/**
* 登记时间 * @return java.util.Date
*/
@JsonSerialize(using=JsonDateSerializer.class)
public java.util.Date getRegisterTime() {
return this.registerTime;
}
/**
* 设置 登记时间
*/
public void setRegisterTime(java.util.Date aValue) {
this.registerTime = aValue;
}
/**
* 登记标识 1=正常登记(上班,下班) 2=迟到 3=早退 4=休息 5=旷工 6=放假 * @return Short
*/
public Short getRegFlag() {
return this.regFlag;
}
/**
* 设置 登记标识 1=正常登记(上班,下班) 2=迟到 3=早退 4=休息 5=旷工 6=放假
*/
public void setRegFlag(Short aValue) {
this.regFlag = aValue;
}
/**
* 迟到或早退分钟 正常上班时为0 * @return Long
*/
public Long getRegMins() {
return this.regMins;
}
/**
* 设置 迟到或早退分钟 正常上班时为0
*/
public void setRegMins(Long aValue) {
this.regMins = aValue;
}
/**
* 迟到原因 * @return String
*/
public String getReason() {
return this.reason;
}
/**
* 设置 迟到原因
*/
public void setReason(String aValue) {
this.reason = aValue;
}
/**
* 周几 * @return Long
*/
public Long getDayofweek() {
return this.dayofweek;
}
/**
* 设置 周几
*/
public void setDayofweek(Long aValue) {
this.dayofweek = aValue;
}
/**
* 上下班标识 1=签到 2=签退 * @return String
*/
public String getInOffFlag() {
return this.inOffFlag;
}
/**
* 设置 上下班标识 1=签到 2=签退
*/
public void setInOffFlag(String aValue) {
this.inOffFlag = aValue;
}
@Override
public String getIdentifyLabel() {
return this.registerId;
}
@Override
public Serializable getPkId() {
return this.registerId;
}
@Override
public void setPkId(Serializable pkId) {
this.registerId = (String) pkId;
}
public Double getLongitude() {
return longitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
public Double getLatitude() {
return latitude;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
public String getAddresses() {
return addresses;
}
public void setAddresses(String addresses) {
this.addresses = addresses;
}
public String getSignRemark() {
return signRemark;
}
public void setSignRemark(String signRemark) {
this.signRemark = signRemark;
}
public Integer getDistance() {
return distance;
}
public void setDistance(Integer distance) {
this.distance = distance;
}
/**
* @see java.lang.Object#equals(Object)
*/
public boolean equals(Object object) {
if (!(object instanceof HrDutyRegister)) {
return false;
}
HrDutyRegister rhs = (HrDutyRegister) object;
return new EqualsBuilder().append(this.registerId, rhs.registerId).append(this.registerTime, rhs.registerTime)
.append(this.regFlag, rhs.regFlag).append(this.regMins, rhs.regMins).append(this.reason, rhs.reason)
.append(this.dayofweek, rhs.dayofweek).append(this.inOffFlag, rhs.inOffFlag)
.append(this.tenantId, rhs.tenantId).append(this.createBy, rhs.createBy)
.append(this.createTime, rhs.createTime).append(this.updateBy, rhs.updateBy)
.append(this.updateTime, rhs.updateTime).isEquals();
}
/**
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
return new HashCodeBuilder(-82280557, -700257973).append(this.registerId).append(this.registerTime)
.append(this.regFlag).append(this.regMins).append(this.reason).append(this.dayofweek)
.append(this.inOffFlag).append(this.tenantId).append(this.createBy).append(this.createTime)
.append(this.updateBy).append(this.updateTime).toHashCode();
}
/**
* @see java.lang.Object#toString()
*/
public String toString() {
return new ToStringBuilder(this).append("registerId", this.registerId).append("registerTime", this.registerTime)
.append("regFlag", this.regFlag).append("regMins", this.regMins).append("reason", this.reason)
.append("dayofweek", this.dayofweek).append("inOffFlag", this.inOffFlag)
.append("tenantId", this.tenantId).append("createBy", this.createBy)
.append("createTime", this.createTime).append("updateBy", this.updateBy)
.append("updateTime", this.updateTime).toString();
}
}
| false | 2,298 | 7 | 2,923 | 7 | 2,848 | 5 | 2,923 | 7 | 3,466 | 11 | false | false | false | false | false | true |
59800_6 | package com.onevgo.j2se.enums;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class EnumMain {
public static void main(String[] args) {
// testEnum1();
testEnum2();
}
private static void testEnum1() {
SeasonEnum1 sprint = SeasonEnum1.SPRINT;
log.info("{}", sprint);
log.info("ordinal={}", sprint.ordinal());
SeasonEnum1[] values = SeasonEnum1.values();
for (SeasonEnum1 value : values) {
log.info("{}: {}", value.getSeasonName(), value.getSeasonDesc());
//春天: 春风又绿江南岸
//夏天: 映日荷花别样红
//秋天: 秋水共长天一色
//冬天: 窗含西岭千秋雪
}
log.info("{}", SeasonEnum1.valueOf("SUMMER").getSeasonDesc());
}
private static void testEnum2() {
SeasonEnum2 autumn = SeasonEnum2.AUTUMN;
log.info("{}", autumn);
log.info("ordinal={}", autumn.ordinal());
log.info("name={}", autumn.name());
for (SeasonEnum2 season : SeasonEnum2.values()) {
log.info("{}: {}", season.getSeasonName(), season.getSeasonDesc());
//春天: 春风又绿江南岸
//夏天: 映日荷花别样红
//秋天: 秋水共长天一色
//冬天: 窗含西岭千秋雪
}
log.info(Enum.valueOf(SeasonEnum2.class, "WINTER").getSeasonDesc());
}
}
| cliff363825/TwentyFour | 01_Language/03_Java/j2se/src/main/java/com/onevgo/j2se/enums/EnumMain.java | 434 | //夏天: 映日荷花别样红 | line_comment | zh-cn | package com.onevgo.j2se.enums;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class EnumMain {
public static void main(String[] args) {
// testEnum1();
testEnum2();
}
private static void testEnum1() {
SeasonEnum1 sprint = SeasonEnum1.SPRINT;
log.info("{}", sprint);
log.info("ordinal={}", sprint.ordinal());
SeasonEnum1[] values = SeasonEnum1.values();
for (SeasonEnum1 value : values) {
log.info("{}: {}", value.getSeasonName(), value.getSeasonDesc());
//春天: 春风又绿江南岸
//夏天: 映日荷花别样红
//秋天: 秋水共长天一色
//冬天: 窗含西岭千秋雪
}
log.info("{}", SeasonEnum1.valueOf("SUMMER").getSeasonDesc());
}
private static void testEnum2() {
SeasonEnum2 autumn = SeasonEnum2.AUTUMN;
log.info("{}", autumn);
log.info("ordinal={}", autumn.ordinal());
log.info("name={}", autumn.name());
for (SeasonEnum2 season : SeasonEnum2.values()) {
log.info("{}: {}", season.getSeasonName(), season.getSeasonDesc());
//春天: 春风又绿江南岸
//夏天 <SUF>
//秋天: 秋水共长天一色
//冬天: 窗含西岭千秋雪
}
log.info(Enum.valueOf(SeasonEnum2.class, "WINTER").getSeasonDesc());
}
}
| false | 356 | 10 | 434 | 14 | 404 | 10 | 434 | 14 | 513 | 18 | false | false | false | false | false | true |
18558_1 | package com.gyb.questionnaire.entity;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.Date;
/**
* 调查问卷实体
*
* @author gengyb
* 2020/11/08
*/
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class Questionnaire {
private Long id;
private String name;
private String greeting;
private Date createDate;
private Date publishDate;
private long userId;
private int typeId;
private int questionCount;
private long templateId;
private int invokeCount;
private int status;//0设计中,1已经发布,2已经结束
private int paperCount; //已提交答卷计数
}
| cloudgyb/questionnaire | src/main/java/com/gyb/questionnaire/entity/Questionnaire.java | 188 | //0设计中,1已经发布,2已经结束 | line_comment | zh-cn | package com.gyb.questionnaire.entity;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.Date;
/**
* 调查问卷实体
*
* @author gengyb
* 2020/11/08
*/
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class Questionnaire {
private Long id;
private String name;
private String greeting;
private Date createDate;
private Date publishDate;
private long userId;
private int typeId;
private int questionCount;
private long templateId;
private int invokeCount;
private int status;//0设 <SUF>
private int paperCount; //已提交答卷计数
}
| false | 158 | 12 | 188 | 12 | 193 | 12 | 188 | 12 | 237 | 19 | false | false | false | false | false | true |
51530_13 | package com.javasrc.http;
//自定义一个简单的 http
import java.io.IOException;
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.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;
//--------------------------------------------------------
//下面是普通 socket
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.*;
//--------------------------------------------------------
public class http {
//----------------
//全部页面
static public ArrayList<http_page> page_list = new ArrayList<http_page>(); //实体中的数据
//----------------
//nio 太啰嗦了一点,还是来个简单的线程模式的好了
public static void CreateServer(int port)
{
try {
//ServerSocket ss = new ServerSocket(8888);
ServerSocket ss = new ServerSocket(port);
System.out.println("启动服务器....");
ThreadAccept.StartAccept(ss);
// Socket s = ss.accept();
// System.out.println("客户端:"+s.getInetAddress().getLocalHost()+"已连接到服务器");
// BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
// //读取客户端发送来的消息
// String mess = br.readLine();
// System.out.println("客户端:"+mess);
// BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
// bw.write(mess+"\n");
// bw.flush();
//} catch (IOException e) {
} catch (Exception e) {
e.printStackTrace();
}
}//
}//
//子类
class ThreadAccept implements Runnable{
public ServerSocket ss = null;
@Override
public void run() {
System.out.println("Thread State is:"+Thread.currentThread().getState());
while(true){
try {
//ServerSocket ss = new ServerSocket(8888);
//System.out.println("启动服务器....");
Socket s = ss.accept();
System.out.println("客户端:"+s.getInetAddress().getLocalHost()+"已连接到服务器");
ThreadSocket.StartSocket(s);
//} catch (IOException e) {
} catch (Exception e) {
e.printStackTrace();
}//try
}//while
}//
public static void StartAccept(ServerSocket ss) throws Exception{
ThreadAccept t = new ThreadAccept();
t.ss = ss;
Thread thread = new Thread(t);
thread.start();
}//
}//
//子类
class ThreadSocket implements Runnable{
//public ServerSocket ss = null;
public Socket s = null;
public static void StartSocket(Socket s) throws Exception{
ThreadSocket t = new ThreadSocket();
t.s = s;
Thread thread = new Thread(t);
thread.start();
}//
//--------------------------------------------------------
//是否已处理 http 请求,没有的话就返回 404
int Handled = 0; //Handler/Handled
//----
BufferedReader _br = null;
BufferedWriter _bw = null;
@Override
public void run() {
System.out.println("Thread State is:"+Thread.currentThread().getState());
try {
//ServerSocket ss = new ServerSocket(8888);
//System.out.println("启动服务器....");
//Socket s = ss.accept();
//System.out.println("客户端:"+s.getInetAddress().getLocalHost()+"已连接到服务器");
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
_br = br;
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
_bw = bw;
this.ReadHeads();
//--------
//分配给哪个页面处理类
for (int i = 0; i < http.page_list.size(); i++) {
http_page page = http.page_list.get(i);
//如果路径对上了就用它处理 //按道理换用 map 更快,不过无所谓了,本项目访问压力不大
if (page.http_path.equals(this.http_url_path)) {
//注意这是每次请求都新建的实例
http_page.cur_page _cur_page = new http_page.cur_page();
_cur_page.get_params = this.get_params;
_cur_page.params = this.params;
String response = page.hander(_cur_page);
SendHttpResponse(response);
return;
}//if
}//for
//--------
//没有处理的话就是 404 .其实标准不是这样的,不过目前的浏览器也可以支持
if (0 == Handled){
SendString("HTTP/1.0 200 OK\r\n");
SendString("server: java server http\r\n");
SendString("Access-Control-Allow-Origin: *\r\n"); //跨域
SendString("\r\n");
SendString("404. java server http.");
}//if
if (true) return;
//--------------------------------------------------------
//读取客户端发送来的消息
String mess = br.readLine();
System.out.println("客户端:"+mess);
bw.write("hi you say:" + mess + "\n");
bw.flush();
} catch (Exception e) { // (IOException e)
e.printStackTrace();
}
finally{
//最后关闭了 socket 所以是符合 http 协议的
try { s.close(); }catch(Exception e2) { e2.printStackTrace(); }
}
}//
//--------------------------------------------------------
//发送 http 回应
public void SendHttpResponse(String response) throws Exception
{
//if (0 == Handled){
SendString("HTTP/1.0 200 OK\r\n");
SendString("server: java server http\r\n");
SendString("Access-Control-Allow-Origin: *\r\n"); //跨域
SendString("\r\n");
//SendString("404. java server http.");
//}//if
SendString(response);
}//
//--------------------------------------------------------
//读取一行
public String ReadLine() throws Exception{
//读取客户端发送来的消息
String mess = _br.readLine();
return mess;
}//
public void SendString(String s) throws Exception
{
//_bw.write("hi you say:" + mess + "\n");
_bw.write(s);
_bw.flush();
}//
//读取完整的 http 头信息
Hashtable<String, String> heads = new Hashtable<String, String>();
ArrayList<String> head_lines = new ArrayList<String>(); //头信息的原始数据
ArrayList<String> body_lines = new ArrayList<String>(); //实体中的数据
//----
Hashtable<String, String> get_params = new Hashtable<String, String>(); //get 请求的参数
Hashtable<String, String> params = new Hashtable<String, String>(); //get 和 pos 请求的参数
public String http_url_path = ""; //当前的访问路径,如 "index.jsp"
public void ReadHeads() throws Exception
{
String first_line = ReadLine(); //http 的首行要单独读取
System.out.println(first_line);
for (int i=0; i<1000; i++) //只读取 1000 行的保护
{
String line = ReadLine();
head_lines.add(line);
if (line.length() == 0) break; //空行就表示头信息结束了。如果只处理 get 请求的话就不用处理后面的了
}//for
//--------------------------------------------------------
//简单一点,处理一下首行好了
//GET /index.jsp HTTP/1.1
String[] _first_line = first_line.split(" ");
if (_first_line.length>2){
String url = _first_line[1]; //第二行
String[] _url = ThreadSocket.split_two(url, "?");
url = _url[0]; //"?"问号前面的地是地址
this.http_url_path = url;
String[] request = _url[1].split("&"); //问号后面的是 get 参数
for (int i = 0; i < request.length; i++) {
String param = request[i];
String[] _kv = ThreadSocket.split_two(param, "=");
String key = _kv[0];
String value = _kv[1];
String _value = java.net.URLDecoder.decode(value, "UTF-8");
//get_params.put(key, value);
get_params.put(key, _value); //值要解码 http
params.put(key, _value);
}//
}//if
//--------------------------------------------------------
}//func
//分隔成两行
public static String[] split_two(String s, String ch)
{
String[] lines = new String[]{"", ""};
int pos = s.indexOf(ch, 0);
lines[0] = s; //默认放在第一个位置中
if (pos>-1){ //找到了才分割
lines[0] = s.substring(0, pos);
lines[1] = s.substring(pos + ch.length());
}//if
return lines;
}//
}//class
| clqsrc/sz_ui_align | java_file/http.java | 2,270 | // //读取客户端发送来的消息
| line_comment | zh-cn | package com.javasrc.http;
//自定义一个简单的 http
import java.io.IOException;
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.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;
//--------------------------------------------------------
//下面是普通 socket
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.*;
//--------------------------------------------------------
public class http {
//----------------
//全部页面
static public ArrayList<http_page> page_list = new ArrayList<http_page>(); //实体中的数据
//----------------
//nio 太啰嗦了一点,还是来个简单的线程模式的好了
public static void CreateServer(int port)
{
try {
//ServerSocket ss = new ServerSocket(8888);
ServerSocket ss = new ServerSocket(port);
System.out.println("启动服务器....");
ThreadAccept.StartAccept(ss);
// Socket s = ss.accept();
// System.out.println("客户端:"+s.getInetAddress().getLocalHost()+"已连接到服务器");
// BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
// //读取 <SUF>
// String mess = br.readLine();
// System.out.println("客户端:"+mess);
// BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
// bw.write(mess+"\n");
// bw.flush();
//} catch (IOException e) {
} catch (Exception e) {
e.printStackTrace();
}
}//
}//
//子类
class ThreadAccept implements Runnable{
public ServerSocket ss = null;
@Override
public void run() {
System.out.println("Thread State is:"+Thread.currentThread().getState());
while(true){
try {
//ServerSocket ss = new ServerSocket(8888);
//System.out.println("启动服务器....");
Socket s = ss.accept();
System.out.println("客户端:"+s.getInetAddress().getLocalHost()+"已连接到服务器");
ThreadSocket.StartSocket(s);
//} catch (IOException e) {
} catch (Exception e) {
e.printStackTrace();
}//try
}//while
}//
public static void StartAccept(ServerSocket ss) throws Exception{
ThreadAccept t = new ThreadAccept();
t.ss = ss;
Thread thread = new Thread(t);
thread.start();
}//
}//
//子类
class ThreadSocket implements Runnable{
//public ServerSocket ss = null;
public Socket s = null;
public static void StartSocket(Socket s) throws Exception{
ThreadSocket t = new ThreadSocket();
t.s = s;
Thread thread = new Thread(t);
thread.start();
}//
//--------------------------------------------------------
//是否已处理 http 请求,没有的话就返回 404
int Handled = 0; //Handler/Handled
//----
BufferedReader _br = null;
BufferedWriter _bw = null;
@Override
public void run() {
System.out.println("Thread State is:"+Thread.currentThread().getState());
try {
//ServerSocket ss = new ServerSocket(8888);
//System.out.println("启动服务器....");
//Socket s = ss.accept();
//System.out.println("客户端:"+s.getInetAddress().getLocalHost()+"已连接到服务器");
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
_br = br;
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
_bw = bw;
this.ReadHeads();
//--------
//分配给哪个页面处理类
for (int i = 0; i < http.page_list.size(); i++) {
http_page page = http.page_list.get(i);
//如果路径对上了就用它处理 //按道理换用 map 更快,不过无所谓了,本项目访问压力不大
if (page.http_path.equals(this.http_url_path)) {
//注意这是每次请求都新建的实例
http_page.cur_page _cur_page = new http_page.cur_page();
_cur_page.get_params = this.get_params;
_cur_page.params = this.params;
String response = page.hander(_cur_page);
SendHttpResponse(response);
return;
}//if
}//for
//--------
//没有处理的话就是 404 .其实标准不是这样的,不过目前的浏览器也可以支持
if (0 == Handled){
SendString("HTTP/1.0 200 OK\r\n");
SendString("server: java server http\r\n");
SendString("Access-Control-Allow-Origin: *\r\n"); //跨域
SendString("\r\n");
SendString("404. java server http.");
}//if
if (true) return;
//--------------------------------------------------------
//读取客户端发送来的消息
String mess = br.readLine();
System.out.println("客户端:"+mess);
bw.write("hi you say:" + mess + "\n");
bw.flush();
} catch (Exception e) { // (IOException e)
e.printStackTrace();
}
finally{
//最后关闭了 socket 所以是符合 http 协议的
try { s.close(); }catch(Exception e2) { e2.printStackTrace(); }
}
}//
//--------------------------------------------------------
//发送 http 回应
public void SendHttpResponse(String response) throws Exception
{
//if (0 == Handled){
SendString("HTTP/1.0 200 OK\r\n");
SendString("server: java server http\r\n");
SendString("Access-Control-Allow-Origin: *\r\n"); //跨域
SendString("\r\n");
//SendString("404. java server http.");
//}//if
SendString(response);
}//
//--------------------------------------------------------
//读取一行
public String ReadLine() throws Exception{
//读取客户端发送来的消息
String mess = _br.readLine();
return mess;
}//
public void SendString(String s) throws Exception
{
//_bw.write("hi you say:" + mess + "\n");
_bw.write(s);
_bw.flush();
}//
//读取完整的 http 头信息
Hashtable<String, String> heads = new Hashtable<String, String>();
ArrayList<String> head_lines = new ArrayList<String>(); //头信息的原始数据
ArrayList<String> body_lines = new ArrayList<String>(); //实体中的数据
//----
Hashtable<String, String> get_params = new Hashtable<String, String>(); //get 请求的参数
Hashtable<String, String> params = new Hashtable<String, String>(); //get 和 pos 请求的参数
public String http_url_path = ""; //当前的访问路径,如 "index.jsp"
public void ReadHeads() throws Exception
{
String first_line = ReadLine(); //http 的首行要单独读取
System.out.println(first_line);
for (int i=0; i<1000; i++) //只读取 1000 行的保护
{
String line = ReadLine();
head_lines.add(line);
if (line.length() == 0) break; //空行就表示头信息结束了。如果只处理 get 请求的话就不用处理后面的了
}//for
//--------------------------------------------------------
//简单一点,处理一下首行好了
//GET /index.jsp HTTP/1.1
String[] _first_line = first_line.split(" ");
if (_first_line.length>2){
String url = _first_line[1]; //第二行
String[] _url = ThreadSocket.split_two(url, "?");
url = _url[0]; //"?"问号前面的地是地址
this.http_url_path = url;
String[] request = _url[1].split("&"); //问号后面的是 get 参数
for (int i = 0; i < request.length; i++) {
String param = request[i];
String[] _kv = ThreadSocket.split_two(param, "=");
String key = _kv[0];
String value = _kv[1];
String _value = java.net.URLDecoder.decode(value, "UTF-8");
//get_params.put(key, value);
get_params.put(key, _value); //值要解码 http
params.put(key, _value);
}//
}//if
//--------------------------------------------------------
}//func
//分隔成两行
public static String[] split_two(String s, String ch)
{
String[] lines = new String[]{"", ""};
int pos = s.indexOf(ch, 0);
lines[0] = s; //默认放在第一个位置中
if (pos>-1){ //找到了才分割
lines[0] = s.substring(0, pos);
lines[1] = s.substring(pos + ch.length());
}//if
return lines;
}//
}//class
| false | 2,007 | 10 | 2,243 | 9 | 2,409 | 9 | 2,243 | 9 | 2,949 | 19 | false | false | false | false | false | true |
27309_1 | package com.demo.leetcode.onethousand;
import com.demo.leetcode.datastruct.TreeNode;
public class Leetcode669 {
public static void main(String[] args) {
}
/**
* 直接过,厉害
* @param root
* @param low
* @param high
* @return
*/
public TreeNode trimBST(TreeNode root, int low, int high) {
if (root == null) {
return null;
}
if (root.val < low) {
return trimBST(root.right, low, high);
}
if (root.val > high) {
return trimBST(root.left, low, high);
}
//满足条件
root.left = trimBST(root.left, low, high);
root.right = trimBST(root.right, low, high);
return root;
}
}
| clunyes/LeetcodeTrial | src/com/demo/leetcode/onethousand/Leetcode669.java | 212 | //满足条件 | line_comment | zh-cn | package com.demo.leetcode.onethousand;
import com.demo.leetcode.datastruct.TreeNode;
public class Leetcode669 {
public static void main(String[] args) {
}
/**
* 直接过,厉害
* @param root
* @param low
* @param high
* @return
*/
public TreeNode trimBST(TreeNode root, int low, int high) {
if (root == null) {
return null;
}
if (root.val < low) {
return trimBST(root.right, low, high);
}
if (root.val > high) {
return trimBST(root.left, low, high);
}
//满足 <SUF>
root.left = trimBST(root.left, low, high);
root.right = trimBST(root.right, low, high);
return root;
}
}
| false | 185 | 3 | 212 | 3 | 223 | 3 | 212 | 3 | 254 | 7 | false | false | false | false | false | true |
5549_3 | package com.netease.nim.demo.event;
/**
* 在线状态
*/
public class OnlineState {
/**
* 客户端类型,参照 {@link com.netease.nimlib.sdk.auth.ClientType}
*/
private int onlineClient;
/**
* 网络状态,WIFI,4G,3G,2G
*/
private NetStateCode netState;
/**
* 在线状态,0 在线 1 忙碌 2 离开
*/
private OnlineStateCode onlineState;
public OnlineState(int onlineClient, int netState, int onlineState) {
this.onlineClient = onlineClient;
this.netState = NetStateCode.getNetStateCode(netState);
this.onlineState = OnlineStateCode.getOnlineStateCode(onlineState);
}
public OnlineState(int onlineClient, NetStateCode netState, OnlineStateCode onlineState) {
this.onlineClient = onlineClient;
this.netState = netState;
this.onlineState = onlineState;
}
/**
* 获取在线状态
*
* @return onlineState
*/
public OnlineStateCode getOnlineState() {
return onlineState;
}
/**
* 获取在线客户端类型
*
* @return onlineClient
*/
public int getOnlineClient() {
return onlineClient;
}
/**
* 获取网络状态
*
* @return netState
*/
public NetStateCode getNetState() {
return netState;
}
}
| cmdbug/TChat | app/src/main/java/com/netease/nim/demo/event/OnlineState.java | 346 | /**
* 在线状态,0 在线 1 忙碌 2 离开
*/ | block_comment | zh-cn | package com.netease.nim.demo.event;
/**
* 在线状态
*/
public class OnlineState {
/**
* 客户端类型,参照 {@link com.netease.nimlib.sdk.auth.ClientType}
*/
private int onlineClient;
/**
* 网络状态,WIFI,4G,3G,2G
*/
private NetStateCode netState;
/**
* 在线状 <SUF>*/
private OnlineStateCode onlineState;
public OnlineState(int onlineClient, int netState, int onlineState) {
this.onlineClient = onlineClient;
this.netState = NetStateCode.getNetStateCode(netState);
this.onlineState = OnlineStateCode.getOnlineStateCode(onlineState);
}
public OnlineState(int onlineClient, NetStateCode netState, OnlineStateCode onlineState) {
this.onlineClient = onlineClient;
this.netState = netState;
this.onlineState = onlineState;
}
/**
* 获取在线状态
*
* @return onlineState
*/
public OnlineStateCode getOnlineState() {
return onlineState;
}
/**
* 获取在线客户端类型
*
* @return onlineClient
*/
public int getOnlineClient() {
return onlineClient;
}
/**
* 获取网络状态
*
* @return netState
*/
public NetStateCode getNetState() {
return netState;
}
}
| false | 333 | 26 | 346 | 24 | 380 | 20 | 346 | 24 | 441 | 33 | false | false | false | false | false | true |
52666_0 | import java.util.Scanner;
/**
* @Author: zhanglin
* @Date: 2021/5/29
* @Time: 1:33 PM
*
* 1.停车问题
* 1,0,1,1,0,1,1,1表示停车位的情况,1表示有车,0表示空位,有三种车,分别占1,2,3个宽度的车位,求最少有几辆车,像上面这种情况,就是3辆车。
* 我是遍历一次,看连续有几个1,用1的个数除以3,累加到sum,如果有余数,sum++,感觉思路没有问题,不知道哪里不对,测试用例通过95.46%。
*/
public class 停车问题 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
if (n <= 0) {
System.out.println("0");
return;
}
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
int sum = 0;
int ser = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == 1) {
ser++;
int big = ser / 3;
int middle = ser % 3 / 2;
int small = ser % 3 % 2;
sum += big + middle + small;
} else {
ser = 0;
}
}
System.out.println(sum);
}
}
| cmdmspaint/leetcode-exercise | src/main/huaweiOJ/niuke/停车问题.java | 404 | /**
* @Author: zhanglin
* @Date: 2021/5/29
* @Time: 1:33 PM
*
* 1.停车问题
* 1,0,1,1,0,1,1,1表示停车位的情况,1表示有车,0表示空位,有三种车,分别占1,2,3个宽度的车位,求最少有几辆车,像上面这种情况,就是3辆车。
* 我是遍历一次,看连续有几个1,用1的个数除以3,累加到sum,如果有余数,sum++,感觉思路没有问题,不知道哪里不对,测试用例通过95.46%。
*/ | block_comment | zh-cn | import java.util.Scanner;
/**
* @Au <SUF>*/
public class 停车问题 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
if (n <= 0) {
System.out.println("0");
return;
}
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
int sum = 0;
int ser = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == 1) {
ser++;
int big = ser / 3;
int middle = ser % 3 / 2;
int small = ser % 3 % 2;
sum += big + middle + small;
} else {
ser = 0;
}
}
System.out.println(sum);
}
}
| false | 362 | 158 | 404 | 181 | 409 | 162 | 404 | 181 | 509 | 251 | false | false | false | false | false | true |
23675_4 | package com.cmlanche.bloghelper.ui;
import com.cmlanche.bloghelper.common.Logger;
import com.cmlanche.bloghelper.model.BucketFile;
import com.cmlanche.bloghelper.utils.BucketUtils;
import com.cmlanche.bloghelper.utils.ResManager;
import com.cmlanche.bloghelper.utils.UIUtils;
import com.cmlanche.bloghelper.utils.Utils;
import com.fx.base.mvvm.CustomView;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
/**
* Created by cmlanche on 2017/12/4.
* 图片预览界面
*/
public class PreView extends CustomView {
@FXML
ImageView imageView;
@FXML
Label o_nameLabel;
@FXML
Label o_sizeLabel;
@FXML
Label n_nameLabel;
@FXML
Label n_sizeLabel;
@FXML
Button operationBtn;
@FXML
VBox detailBox;
@FXML
Label tipLabel;
@FXML
Label compressRatioLabel;
private BucketFile bucketFile;
@Override
protected void onViewCreated() {
}
/**
* 加载一个文件到预览界面
*
* @param bucketFile
*/
public void loadFile(BucketFile bucketFile) {
if (bucketFile != null) {
this.bucketFile = bucketFile;
o_nameLabel.setText(bucketFile.getName());
o_sizeLabel.setText(Utils.getSizeName(bucketFile.getSize()));
int status = BucketUtils.getBucketFileStauts(bucketFile);
detailBox.getStyleClass().clear();
detailBox.getStyleClass().add(UIUtils.getStatusBackground(status));
File optimizeFile = new File(BucketUtils.getLocalBucketfileOptimizedFilePath(bucketFile));
long size = 0;
if (optimizeFile.exists()) {
size = FileUtils.sizeOf(optimizeFile);
}
switch (status) {
case BucketUtils.NORMAL:
operationBtn.setVisible(true);
n_nameLabel.setText("-");
n_sizeLabel.setText("-");
compressRatioLabel.setText("-");
operationBtn.setText("下载");
operationBtn.setUserData("download");
break;
case BucketUtils.DOWNLOADED:
operationBtn.setVisible(true);
n_nameLabel.setText("-");
n_sizeLabel.setText("-");
compressRatioLabel.setText("-");
operationBtn.setText("优化");
operationBtn.setUserData("optimize");
break;
case BucketUtils.OPTIMIZEED:
operationBtn.setVisible(true);
n_nameLabel.setText(optimizeFile.getName());
n_sizeLabel.setText(Utils.getSizeName(size));
compressRatioLabel.setText(String.format("-%.2f%%",
(1 - (float) FileUtils.sizeOf(optimizeFile) / bucketFile.getSize()) * 100));
operationBtn.setText("上传");
operationBtn.setUserData("upload");
break;
case BucketUtils.OPTIMIZED_UPLOADED:
n_nameLabel.setText(optimizeFile.getName());
n_sizeLabel.setText(Utils.getSizeName(size));
if (UIUtils.isJpg(bucketFile.getMineType()) || UIUtils.isPng(bucketFile.getMineType())) {
operationBtn.setVisible(false);
} else {
operationBtn.setVisible(true);
}
compressRatioLabel.setText("完美,已经优化并上传了!");
operationBtn.setText("优化");
operationBtn.setUserData("optimize");
break;
}
if (ResManager.getInstance().existImage(bucketFile)) {
// 从压缩的图片中取,如果没有则进行压缩处理
File file;
if (ResManager.getInstance().existOptimizedImage(bucketFile)) {
file = new File(BucketUtils.getLocalBucketfileOptimizedFilePath(bucketFile));
} else {
file = new File(BucketUtils.getLocalBucketFilePath(bucketFile));
}
if (UIUtils.isGif(bucketFile.getMineType())) {
file = new File("cache/cmlanchecom/test.gif");
}
showImage(file, bucketFile.getMineType());
} else {
Logger.info(tag, "未下载:" + bucketFile.getName());
imageView.setImage(null);
}
}
}
/**
* 展示图像
*
* @param file
*/
private void showImage(File file, String mineType) {
if (file.exists()) {
long filesize = FileUtils.sizeOf(file);
if (filesize <= 5 * 1024 * 1024) {
if (UIUtils.isJpg(mineType) || UIUtils.isPng(mineType) || UIUtils.isGif(mineType)) {
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
Image image = new Image(fis);
tipLabel.setVisible(false);
imageView.setVisible(true);
imageView.setImage(image);
fis.close();
} catch (IOException e) {
Logger.error(tag, e.getMessage(), e);
}
} else if (UIUtils.isGif(mineType)) {
}
} else {
// 文件大于5M,不宜展示,建议先优化处理
imageView.setImage(null);
imageView.setVisible(false);
tipLabel.setVisible(true);
tipLabel.setText("文件大于5M,请先优化处理");
}
} else {
// 提示文件不存在
imageView.setImage(null);
imageView.setVisible(false);
tipLabel.setVisible(true);
tipLabel.setText("文件不存在");
}
}
}
| cmlanche/javafx-qiniu-tinypng-client | src/com/cmlanche/bloghelper/ui/PreView.java | 1,398 | // 文件大于5M,不宜展示,建议先优化处理 | line_comment | zh-cn | package com.cmlanche.bloghelper.ui;
import com.cmlanche.bloghelper.common.Logger;
import com.cmlanche.bloghelper.model.BucketFile;
import com.cmlanche.bloghelper.utils.BucketUtils;
import com.cmlanche.bloghelper.utils.ResManager;
import com.cmlanche.bloghelper.utils.UIUtils;
import com.cmlanche.bloghelper.utils.Utils;
import com.fx.base.mvvm.CustomView;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
/**
* Created by cmlanche on 2017/12/4.
* 图片预览界面
*/
public class PreView extends CustomView {
@FXML
ImageView imageView;
@FXML
Label o_nameLabel;
@FXML
Label o_sizeLabel;
@FXML
Label n_nameLabel;
@FXML
Label n_sizeLabel;
@FXML
Button operationBtn;
@FXML
VBox detailBox;
@FXML
Label tipLabel;
@FXML
Label compressRatioLabel;
private BucketFile bucketFile;
@Override
protected void onViewCreated() {
}
/**
* 加载一个文件到预览界面
*
* @param bucketFile
*/
public void loadFile(BucketFile bucketFile) {
if (bucketFile != null) {
this.bucketFile = bucketFile;
o_nameLabel.setText(bucketFile.getName());
o_sizeLabel.setText(Utils.getSizeName(bucketFile.getSize()));
int status = BucketUtils.getBucketFileStauts(bucketFile);
detailBox.getStyleClass().clear();
detailBox.getStyleClass().add(UIUtils.getStatusBackground(status));
File optimizeFile = new File(BucketUtils.getLocalBucketfileOptimizedFilePath(bucketFile));
long size = 0;
if (optimizeFile.exists()) {
size = FileUtils.sizeOf(optimizeFile);
}
switch (status) {
case BucketUtils.NORMAL:
operationBtn.setVisible(true);
n_nameLabel.setText("-");
n_sizeLabel.setText("-");
compressRatioLabel.setText("-");
operationBtn.setText("下载");
operationBtn.setUserData("download");
break;
case BucketUtils.DOWNLOADED:
operationBtn.setVisible(true);
n_nameLabel.setText("-");
n_sizeLabel.setText("-");
compressRatioLabel.setText("-");
operationBtn.setText("优化");
operationBtn.setUserData("optimize");
break;
case BucketUtils.OPTIMIZEED:
operationBtn.setVisible(true);
n_nameLabel.setText(optimizeFile.getName());
n_sizeLabel.setText(Utils.getSizeName(size));
compressRatioLabel.setText(String.format("-%.2f%%",
(1 - (float) FileUtils.sizeOf(optimizeFile) / bucketFile.getSize()) * 100));
operationBtn.setText("上传");
operationBtn.setUserData("upload");
break;
case BucketUtils.OPTIMIZED_UPLOADED:
n_nameLabel.setText(optimizeFile.getName());
n_sizeLabel.setText(Utils.getSizeName(size));
if (UIUtils.isJpg(bucketFile.getMineType()) || UIUtils.isPng(bucketFile.getMineType())) {
operationBtn.setVisible(false);
} else {
operationBtn.setVisible(true);
}
compressRatioLabel.setText("完美,已经优化并上传了!");
operationBtn.setText("优化");
operationBtn.setUserData("optimize");
break;
}
if (ResManager.getInstance().existImage(bucketFile)) {
// 从压缩的图片中取,如果没有则进行压缩处理
File file;
if (ResManager.getInstance().existOptimizedImage(bucketFile)) {
file = new File(BucketUtils.getLocalBucketfileOptimizedFilePath(bucketFile));
} else {
file = new File(BucketUtils.getLocalBucketFilePath(bucketFile));
}
if (UIUtils.isGif(bucketFile.getMineType())) {
file = new File("cache/cmlanchecom/test.gif");
}
showImage(file, bucketFile.getMineType());
} else {
Logger.info(tag, "未下载:" + bucketFile.getName());
imageView.setImage(null);
}
}
}
/**
* 展示图像
*
* @param file
*/
private void showImage(File file, String mineType) {
if (file.exists()) {
long filesize = FileUtils.sizeOf(file);
if (filesize <= 5 * 1024 * 1024) {
if (UIUtils.isJpg(mineType) || UIUtils.isPng(mineType) || UIUtils.isGif(mineType)) {
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
Image image = new Image(fis);
tipLabel.setVisible(false);
imageView.setVisible(true);
imageView.setImage(image);
fis.close();
} catch (IOException e) {
Logger.error(tag, e.getMessage(), e);
}
} else if (UIUtils.isGif(mineType)) {
}
} else {
// 文件 <SUF>
imageView.setImage(null);
imageView.setVisible(false);
tipLabel.setVisible(true);
tipLabel.setText("文件大于5M,请先优化处理");
}
} else {
// 提示文件不存在
imageView.setImage(null);
imageView.setVisible(false);
tipLabel.setVisible(true);
tipLabel.setText("文件不存在");
}
}
}
| false | 1,177 | 13 | 1,398 | 15 | 1,489 | 13 | 1,398 | 15 | 1,782 | 27 | false | false | false | false | false | true |
66447_2 | pipeline {
agent {
label 'jnlp-slave'
}
parameters {
string(
description: '项目',
name: 'PROJECT',
defaultValue: "ms"
)
choice(
description: '你需要选择哪个模块进行构建 ?',
name: 'SERVICE',
choices: ['flask-admin']
)
string (
name: 'URL',
defaultValue: 'https://gitee.com/cmlfxz/flask-admin.git',
description: 'git url'
)
string(
description: '副本数',
name: 'REPLICAS',
defaultValue: "1"
)
}
environment {
TAG = sh( returnStdout: true, script: 'git rev-parse --short HEAD')
ENV = 'dev'
CLI = "/usr/bin/kubectl --kubeconfig /root/.kube/config"
HARBOR_REGISTRY = 'myhub.mydocker.com'
HARBOR_EMAIL = '915613275@qq.com'
// docker账号密码的保存在jenkins的Cred ID
DOCKER_HUB_ID = 'dev-dockerHub'
}
// 必须包含此步骤
stages {
stage('display var') {
steps {
echo "Runing ${env.BUILD_ID}"
echo "BRANCH ${params.BRANCH}"
echo "tag: $TAG replicas: ${params.REPLICAS} ${ENV}"
}
}
stage('checkout') {
steps {
script {
// revision = params.BRANCH
revision = 'develop'
}
checkout([
$class: 'GitSCM',
branches: [[name: "${revision}"]],
doGenerateSubmoduleConfigurations: false,
extensions: [],
submoduleCfg: [],
userRemoteConfigs: [[
credentialsId: 'gitee_account',
url: "${params.URL}" ]]
])
}
}
stage('build') {
steps {
echo "$TAG, $ENV"
withCredentials([usernamePassword(credentialsId: "$DOCKER_HUB_ID", passwordVariable: 'dockerHubPassword', usernameVariable: 'dockerHubUser')]){
sh '''
docker login -u ${dockerHubUser} -p ${dockerHubPassword} $HARBOR_REGISTRY
cd $WORKSPACE/k8s/
sh build.sh --action=build --env=$ENV --project=$PROJECT --service=$SERVICE --tag=$TAG --harbor_registry=$HARBOR_REGISTRY
'''
}
}
}
stage('deploy dev'){
steps {
withCredentials([usernamePassword(credentialsId: "$DOCKER_HUB_ID", passwordVariable: 'dockerHubPassword', usernameVariable: 'dockerHubUser')]){
configFileProvider([configFile(fileId: 'dev-k8s-config', targetLocation: '/root/.kube/config')]) {
sh '''
namespace="$PROJECT-$ENV"
$CLI create secret docker-registry harborsecret --docker-server=$HARBOR_REGISTRY --docker-username=$dockerHubUser \
--docker-password=$dockerHubPassword --docker-email=$HARBOR_EMAIL --namespace=$namespace || true
'''
}
sh '''
cd $WORKSPACE/k8s/
sh build.sh --action=deploy --env=$ENV --project=$PROJECT --service=$SERVICE --tag=$TAG --replicas=$REPLICAS --harbor_registry=$HARBOR_REGISTRY
'''
}
}
}
}
}
| cmlfxz/flask-admin | dev-jenkinsfile.java | 766 | // 必须包含此步骤 | line_comment | zh-cn | pipeline {
agent {
label 'jnlp-slave'
}
parameters {
string(
description: '项目',
name: 'PROJECT',
defaultValue: "ms"
)
choice(
description: '你需要选择哪个模块进行构建 ?',
name: 'SERVICE',
choices: ['flask-admin']
)
string (
name: 'URL',
defaultValue: 'https://gitee.com/cmlfxz/flask-admin.git',
description: 'git url'
)
string(
description: '副本数',
name: 'REPLICAS',
defaultValue: "1"
)
}
environment {
TAG = sh( returnStdout: true, script: 'git rev-parse --short HEAD')
ENV = 'dev'
CLI = "/usr/bin/kubectl --kubeconfig /root/.kube/config"
HARBOR_REGISTRY = 'myhub.mydocker.com'
HARBOR_EMAIL = '915613275@qq.com'
// docker账号密码的保存在jenkins的Cred ID
DOCKER_HUB_ID = 'dev-dockerHub'
}
// 必须 <SUF>
stages {
stage('display var') {
steps {
echo "Runing ${env.BUILD_ID}"
echo "BRANCH ${params.BRANCH}"
echo "tag: $TAG replicas: ${params.REPLICAS} ${ENV}"
}
}
stage('checkout') {
steps {
script {
// revision = params.BRANCH
revision = 'develop'
}
checkout([
$class: 'GitSCM',
branches: [[name: "${revision}"]],
doGenerateSubmoduleConfigurations: false,
extensions: [],
submoduleCfg: [],
userRemoteConfigs: [[
credentialsId: 'gitee_account',
url: "${params.URL}" ]]
])
}
}
stage('build') {
steps {
echo "$TAG, $ENV"
withCredentials([usernamePassword(credentialsId: "$DOCKER_HUB_ID", passwordVariable: 'dockerHubPassword', usernameVariable: 'dockerHubUser')]){
sh '''
docker login -u ${dockerHubUser} -p ${dockerHubPassword} $HARBOR_REGISTRY
cd $WORKSPACE/k8s/
sh build.sh --action=build --env=$ENV --project=$PROJECT --service=$SERVICE --tag=$TAG --harbor_registry=$HARBOR_REGISTRY
'''
}
}
}
stage('deploy dev'){
steps {
withCredentials([usernamePassword(credentialsId: "$DOCKER_HUB_ID", passwordVariable: 'dockerHubPassword', usernameVariable: 'dockerHubUser')]){
configFileProvider([configFile(fileId: 'dev-k8s-config', targetLocation: '/root/.kube/config')]) {
sh '''
namespace="$PROJECT-$ENV"
$CLI create secret docker-registry harborsecret --docker-server=$HARBOR_REGISTRY --docker-username=$dockerHubUser \
--docker-password=$dockerHubPassword --docker-email=$HARBOR_EMAIL --namespace=$namespace || true
'''
}
sh '''
cd $WORKSPACE/k8s/
sh build.sh --action=deploy --env=$ENV --project=$PROJECT --service=$SERVICE --tag=$TAG --replicas=$REPLICAS --harbor_registry=$HARBOR_REGISTRY
'''
}
}
}
}
}
| false | 747 | 7 | 766 | 6 | 858 | 6 | 766 | 6 | 1,019 | 17 | false | false | false | false | false | true |
40792_5 | package zhrk.missing;
import com.jfinal.core.Controller;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import zhrk.common.model.QxMissing;
import zhrk.common.model.QxUserLibrary;
import zhrk.send.SendService;
import zhrk.utils.CountUtils;
import zhrk.utils.baidu.FaceMatch;
public class MissingController extends Controller{
MissingService srv = MissingService.me;
SendService seSrv = SendService.me;
/**
* 失踪人员管理
*/
public void index(){
Page<Record> missingList = srv.paginate(getParaToInt("p", 1));
setAttr("missingList", missingList);
render("list.jsp");
}
/**
* 已找到 管理
*/
public void doneindex(){
Record user = getSessionAttr("user");
String userId = "";
String roleCode = "";
if(user != null) {
userId = user.getStr("ID");
roleCode = user.getStr("ROLECODE");
}
Page<Record> missingList = srv.donepaginate(getParaToInt("p", 1),userId,roleCode);
setAttr("missingList", missingList);
render("donelist.jsp");
}
/**
* 搜寻中 管理
*/
public void doingindex(){
Page<Record> missingList = srv.doingpaginate(getParaToInt("p", 1));
setAttr("missingList", missingList);
render("doinglist.jsp");
}
/**
* 公示信息
*/
public void publicindex(){
Page<Record> missingList = srv.doingpaginate(getParaToInt("p", 1));
setAttr("missingList", missingList);
render("publiclist.jsp");
}
/**
* 登记失踪人员表单
*/
public void form(){
Integer id = getParaToInt(0);
List<QxMissing> missingList = srv.findMissingList();
setAttr("missingList", missingList);
setAttr("missingSize", missingList.size());
if(id != null){
QxMissing missing = srv.findModelById(id);
setAttr("missing", missing);
}
render("form.jsp");
}
/**
* 登记失踪人口信息
*
* 2018年7月23日 下午5:11:53
*/
public void regiMiss() {
render("userMp.jsp");
}
/**
* 图片上传
*/
public void imageUpload() {
UploadFile uploadFile = getFile();//在磁盘上保存文件
if(uploadFile == null) {
renderJson(Ret.fail("msg", "请选择需要上传的文件。"));
}else {
String uploadPath = uploadFile.getUploadPath();//获取保存文件的文件夹
String fileName = uploadFile.getFileName();//获取保存文件的文件名
String filePath = uploadPath+"\\"+fileName;//保存文件的路径
Ret ret = srv.uploadImg(filePath,fileName,"/upload/");
renderJson(ret);
}
}
/**
* 志愿者上传图片进行对比
*
* 2018年8月7日 上午11:36:53
*/
public void tempLoad() {
UploadFile uploadFile = getFile("imageName", "\\temp\\");//在磁盘上保存文件
String uploadPath = uploadFile.getUploadPath();//获取保存文件的文件夹
String fileName = uploadFile.getFileName();//获取保存文件的文件名
String filePath = uploadPath+fileName;//保存文件的路径
Ret ret = srv.uploadImg(filePath,fileName,"/upload/temp/");
renderJson(ret);
}
/**
* 更新失踪人员信息
*/
public void upMissing(){
QxMissing missing = getBean(QxMissing.class,"missing");
Ret ret = srv.upMissing(missing);
renderJson(ret);
}
/**
* 删除失踪人员信息
*/
public void delMissing(){
Integer id = getParaToInt("id");
QxMissing missing = srv.findModelById(id);
Ret ret = srv.delMissing(missing);
renderJson(ret);
}
public void findBycardId() {
String cardId = getPara("cardId");
QxUserLibrary data = srv.findBycardId(cardId);
renderJson(data);
}
/**
* 登记失踪信息
*
* 2018年8月11日 下午5:47:02
*/
public void missSub() {
QxMissing mis = getBean(QxMissing.class,"mis");
String misdate = getPara("misdate");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");//注意格式化的表达式
try {
Date d = format.parse(misdate);
mis.setMisdate(d);
} catch (ParseException e) {
mis.setMisdate(new Date());
}
mis.setUserstate("失踪");//失踪,搜寻中,已找回
mis.setInfstate("待审核未通过");
Ret ret = srv.save(mis);
renderJson(ret);
}
public void findById() {
Integer id = getParaToInt("id");
Record data = srv.findRecordById(id);
renderJson(data);
}
/**
* 对失踪信息进行审核,审核通过,并将失踪人的状态变更为搜寻中
* 2018年7月25日 上午11:50:42
*/
public void finfs() {
Integer id = getParaToInt("misId");
String status = getPara("status");
QxMissing missing = srv.findModelById(id);
missing.setInfstate(status);
if(("审核通过").equals(status)) {
missing.setUserstate("搜寻中");
}else {
missing.setUserstate("信息作废");
}
Ret ret = srv.upMissing(missing);
renderJson(ret);
}
/**
* 删除失踪信息
* 2018年7月25日 下午5:51:00
*/
public void delMis() {
Integer id = getParaToInt("id");
Ret ret = srv.delMis(id);
renderJson(ret);
}
/**
* 失踪人口信息
* 2018年7月31日 下午4:04:31
*/
public void findMisById() {
Integer mid = getParaToInt("id");
QxMissing data = srv.findModelById(mid);
renderJson(data);
}
/**
* 分析数据,调用不同的弹出框
* 2018年8月1日 下午3:04:07
*/
public void ansMis() {
Integer id = getParaToInt("id");
boolean flag = CountUtils.getCount();
if(flag) {
renderJson(Ret.ok("msg", "成功找到").set("misId", id));
}else {
renderJson(Ret.fail("msg", "未找到,上传平台").set("misId", id));
}
}
/**
* 上传至公视平台
* 2018年8月1日 下午4:31:33
*/
public void upTopub() {
Integer misId = getParaToInt("misId");
QxMissing data = srv.findModelById(misId);
data.setInfstate("上传公视平台");
Ret ret = srv.upMissing(data);
srv.toRePer(data,"失踪人员暂时未找到,已上传至公视平台,请留意推送信息",0);//上传公视平台时候,推送信息
renderJson(ret);
}
/**
* 推送信息
*
* 2018年8月1日 下午5:32:24
*/
public void toRePer() {
Integer misId = getParaToInt("misId");
String addr = getPara("addr");
QxMissing data = srv.findModelById(misId);
data.setInfstate("信息已推送");
//data.setUserstate("已找到");
Ret ret = srv.upMissing(data);
srv.toRePer(data,"失踪人员已经找到,发现地点在" + addr,1);
renderJson(ret);
}
/**
* 对上传照片进行分析
* 2018年8月8日 上午8:45:54
*/
public void ansPhoto(){
String phoPath = getPara("phoPath");
String newPath = getPara("newPath");
Ret ret = FaceMatch.match("src/main/webapp"+phoPath, "src/main/webapp"+ newPath);
renderJson(ret);
}
/**
* 对比上的照片数据进行提交保存
*
* 2018年8月9日 下午5:24:50
*/
public void ansSub(){
String newPath = getPara("newPath");
Integer misId = getParaToInt("misId");
String addr = getPara("addr");
Integer score = getParaToInt("score");
Integer reuser = getParaToInt("reuser");
QxMissing data = srv.findModelById(misId);
if(!data.getUserstate().equals("发现失踪者")) {
data.setUserstate("发现失踪者");
srv.upMissing(data);
}
Ret ret = srv.ansSub(newPath,misId,addr,reuser,score);
renderJson(ret);
}
/**
* 根据失踪id对发现失踪者的信息显示轨迹
*
* 2018年8月11日 下午5:01:10
*/
public void route() {
Integer misId = getParaToInt("misId");
List<Record> data = seSrv.getAreaList(misId);
renderJson(data);
}
/**
* 变更失踪信息状态
*
* 2018年8月11日 下午5:32:41
*/
public void toseState() {
Integer misId = getParaToInt("misId");
QxMissing missing = srv.findModelById(misId);
missing.setUserstate("已找到");
missing.setInfstate("已找到");
Ret ret = srv.upMissing(missing);
renderJson(ret);
}
/**
* 对照片数据进行分析
*
* 2018年8月17日 上午11:12:05
*/
public void contrast() {
Integer misId = getParaToInt("misId");
String[] addrs = getPara("addrs").split(">");
String path = srv.getPicpath(misId);
List<String> paths = srv.getImgPaths();
List<Record> data = srv.contrast(paths,path,misId,addrs[0]);
renderJson(data);
}
/**
* 对视频进行分析,找出含有人物头像的视频截图
*
* 2018年9月19日 下午12:01:28
*/
public void anasView() {
String[] paths = getParaValues("path[]");
if(paths == null || paths.length == 0) {
renderJson(Ret.fail("msg", "视频未找到"));
return;
}
List<Record> list = srv.getVideo(paths);
Ret ret = srv.getImages(list);
/*List<String> data = new ArrayList<>();
if(ret.isOk()) {
Integer count = ret.getInt("msg");
data = srv.getPaths(count,data);
}*/
renderJson(ret);
}
}
| cndingwei/Intelligent-suspected-missing-persons-tracking-system | src/main/java/zhrk/missing/MissingController.java | 2,993 | /**
* 登记失踪人口信息
*
* 2018年7月23日 下午5:11:53
*/ | block_comment | zh-cn | package zhrk.missing;
import com.jfinal.core.Controller;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import zhrk.common.model.QxMissing;
import zhrk.common.model.QxUserLibrary;
import zhrk.send.SendService;
import zhrk.utils.CountUtils;
import zhrk.utils.baidu.FaceMatch;
public class MissingController extends Controller{
MissingService srv = MissingService.me;
SendService seSrv = SendService.me;
/**
* 失踪人员管理
*/
public void index(){
Page<Record> missingList = srv.paginate(getParaToInt("p", 1));
setAttr("missingList", missingList);
render("list.jsp");
}
/**
* 已找到 管理
*/
public void doneindex(){
Record user = getSessionAttr("user");
String userId = "";
String roleCode = "";
if(user != null) {
userId = user.getStr("ID");
roleCode = user.getStr("ROLECODE");
}
Page<Record> missingList = srv.donepaginate(getParaToInt("p", 1),userId,roleCode);
setAttr("missingList", missingList);
render("donelist.jsp");
}
/**
* 搜寻中 管理
*/
public void doingindex(){
Page<Record> missingList = srv.doingpaginate(getParaToInt("p", 1));
setAttr("missingList", missingList);
render("doinglist.jsp");
}
/**
* 公示信息
*/
public void publicindex(){
Page<Record> missingList = srv.doingpaginate(getParaToInt("p", 1));
setAttr("missingList", missingList);
render("publiclist.jsp");
}
/**
* 登记失踪人员表单
*/
public void form(){
Integer id = getParaToInt(0);
List<QxMissing> missingList = srv.findMissingList();
setAttr("missingList", missingList);
setAttr("missingSize", missingList.size());
if(id != null){
QxMissing missing = srv.findModelById(id);
setAttr("missing", missing);
}
render("form.jsp");
}
/**
* 登记失 <SUF>*/
public void regiMiss() {
render("userMp.jsp");
}
/**
* 图片上传
*/
public void imageUpload() {
UploadFile uploadFile = getFile();//在磁盘上保存文件
if(uploadFile == null) {
renderJson(Ret.fail("msg", "请选择需要上传的文件。"));
}else {
String uploadPath = uploadFile.getUploadPath();//获取保存文件的文件夹
String fileName = uploadFile.getFileName();//获取保存文件的文件名
String filePath = uploadPath+"\\"+fileName;//保存文件的路径
Ret ret = srv.uploadImg(filePath,fileName,"/upload/");
renderJson(ret);
}
}
/**
* 志愿者上传图片进行对比
*
* 2018年8月7日 上午11:36:53
*/
public void tempLoad() {
UploadFile uploadFile = getFile("imageName", "\\temp\\");//在磁盘上保存文件
String uploadPath = uploadFile.getUploadPath();//获取保存文件的文件夹
String fileName = uploadFile.getFileName();//获取保存文件的文件名
String filePath = uploadPath+fileName;//保存文件的路径
Ret ret = srv.uploadImg(filePath,fileName,"/upload/temp/");
renderJson(ret);
}
/**
* 更新失踪人员信息
*/
public void upMissing(){
QxMissing missing = getBean(QxMissing.class,"missing");
Ret ret = srv.upMissing(missing);
renderJson(ret);
}
/**
* 删除失踪人员信息
*/
public void delMissing(){
Integer id = getParaToInt("id");
QxMissing missing = srv.findModelById(id);
Ret ret = srv.delMissing(missing);
renderJson(ret);
}
public void findBycardId() {
String cardId = getPara("cardId");
QxUserLibrary data = srv.findBycardId(cardId);
renderJson(data);
}
/**
* 登记失踪信息
*
* 2018年8月11日 下午5:47:02
*/
public void missSub() {
QxMissing mis = getBean(QxMissing.class,"mis");
String misdate = getPara("misdate");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");//注意格式化的表达式
try {
Date d = format.parse(misdate);
mis.setMisdate(d);
} catch (ParseException e) {
mis.setMisdate(new Date());
}
mis.setUserstate("失踪");//失踪,搜寻中,已找回
mis.setInfstate("待审核未通过");
Ret ret = srv.save(mis);
renderJson(ret);
}
public void findById() {
Integer id = getParaToInt("id");
Record data = srv.findRecordById(id);
renderJson(data);
}
/**
* 对失踪信息进行审核,审核通过,并将失踪人的状态变更为搜寻中
* 2018年7月25日 上午11:50:42
*/
public void finfs() {
Integer id = getParaToInt("misId");
String status = getPara("status");
QxMissing missing = srv.findModelById(id);
missing.setInfstate(status);
if(("审核通过").equals(status)) {
missing.setUserstate("搜寻中");
}else {
missing.setUserstate("信息作废");
}
Ret ret = srv.upMissing(missing);
renderJson(ret);
}
/**
* 删除失踪信息
* 2018年7月25日 下午5:51:00
*/
public void delMis() {
Integer id = getParaToInt("id");
Ret ret = srv.delMis(id);
renderJson(ret);
}
/**
* 失踪人口信息
* 2018年7月31日 下午4:04:31
*/
public void findMisById() {
Integer mid = getParaToInt("id");
QxMissing data = srv.findModelById(mid);
renderJson(data);
}
/**
* 分析数据,调用不同的弹出框
* 2018年8月1日 下午3:04:07
*/
public void ansMis() {
Integer id = getParaToInt("id");
boolean flag = CountUtils.getCount();
if(flag) {
renderJson(Ret.ok("msg", "成功找到").set("misId", id));
}else {
renderJson(Ret.fail("msg", "未找到,上传平台").set("misId", id));
}
}
/**
* 上传至公视平台
* 2018年8月1日 下午4:31:33
*/
public void upTopub() {
Integer misId = getParaToInt("misId");
QxMissing data = srv.findModelById(misId);
data.setInfstate("上传公视平台");
Ret ret = srv.upMissing(data);
srv.toRePer(data,"失踪人员暂时未找到,已上传至公视平台,请留意推送信息",0);//上传公视平台时候,推送信息
renderJson(ret);
}
/**
* 推送信息
*
* 2018年8月1日 下午5:32:24
*/
public void toRePer() {
Integer misId = getParaToInt("misId");
String addr = getPara("addr");
QxMissing data = srv.findModelById(misId);
data.setInfstate("信息已推送");
//data.setUserstate("已找到");
Ret ret = srv.upMissing(data);
srv.toRePer(data,"失踪人员已经找到,发现地点在" + addr,1);
renderJson(ret);
}
/**
* 对上传照片进行分析
* 2018年8月8日 上午8:45:54
*/
public void ansPhoto(){
String phoPath = getPara("phoPath");
String newPath = getPara("newPath");
Ret ret = FaceMatch.match("src/main/webapp"+phoPath, "src/main/webapp"+ newPath);
renderJson(ret);
}
/**
* 对比上的照片数据进行提交保存
*
* 2018年8月9日 下午5:24:50
*/
public void ansSub(){
String newPath = getPara("newPath");
Integer misId = getParaToInt("misId");
String addr = getPara("addr");
Integer score = getParaToInt("score");
Integer reuser = getParaToInt("reuser");
QxMissing data = srv.findModelById(misId);
if(!data.getUserstate().equals("发现失踪者")) {
data.setUserstate("发现失踪者");
srv.upMissing(data);
}
Ret ret = srv.ansSub(newPath,misId,addr,reuser,score);
renderJson(ret);
}
/**
* 根据失踪id对发现失踪者的信息显示轨迹
*
* 2018年8月11日 下午5:01:10
*/
public void route() {
Integer misId = getParaToInt("misId");
List<Record> data = seSrv.getAreaList(misId);
renderJson(data);
}
/**
* 变更失踪信息状态
*
* 2018年8月11日 下午5:32:41
*/
public void toseState() {
Integer misId = getParaToInt("misId");
QxMissing missing = srv.findModelById(misId);
missing.setUserstate("已找到");
missing.setInfstate("已找到");
Ret ret = srv.upMissing(missing);
renderJson(ret);
}
/**
* 对照片数据进行分析
*
* 2018年8月17日 上午11:12:05
*/
public void contrast() {
Integer misId = getParaToInt("misId");
String[] addrs = getPara("addrs").split(">");
String path = srv.getPicpath(misId);
List<String> paths = srv.getImgPaths();
List<Record> data = srv.contrast(paths,path,misId,addrs[0]);
renderJson(data);
}
/**
* 对视频进行分析,找出含有人物头像的视频截图
*
* 2018年9月19日 下午12:01:28
*/
public void anasView() {
String[] paths = getParaValues("path[]");
if(paths == null || paths.length == 0) {
renderJson(Ret.fail("msg", "视频未找到"));
return;
}
List<Record> list = srv.getVideo(paths);
Ret ret = srv.getImages(list);
/*List<String> data = new ArrayList<>();
if(ret.isOk()) {
Integer count = ret.getInt("msg");
data = srv.getPaths(count,data);
}*/
renderJson(ret);
}
}
| false | 2,655 | 36 | 2,993 | 36 | 3,045 | 39 | 2,993 | 36 | 3,844 | 49 | false | false | false | false | false | true |
61441_1 | package com.baidu.android.voicedemo.activity;
import com.baidu.android.voicedemo.activity.setting.NluSetting;
import com.baidu.android.voicedemo.recognization.CommonRecogParams;
import com.baidu.android.voicedemo.recognization.nlu.NluRecogParams;
/**
* Created by fujiayi on 2017/6/24.
*/
public class ActivityNlu extends ActivityRecog {
{
descText = "语义解析功能是指录音被识别出文字后, 对文字进行分析,如进行分词并尽可能获取文字的意图。\n"
+ "语义解析分为在线语义和本地语义:\n"
+ "1. 在线语义由百度服务器完成。 请点“设置”按钮选择开启“在线语义”。在线语义必须选择搜索模型。\n"
+ "2. 本地语义解析,请点“设置”按钮选择“在线+离线命令词+ SLOT_DATA”,“开启本地语义解析”。大声说“打电话给赵琦”\n"
+ "3. 离线命令词语义, 请测试”离线命令词”后,断网, 请点“设置”按钮选择“离在线+离线命令词+ SLOT_DATA”,“开启本地语义解析”。大声说“打电话给赵琦”\n\n"
+ "集成指南:\n"
+ "本地语义:在开始识别ASR_START输入事件中的GRAMMER参数中设置bsg文件路径。如同时设置SLOT_DATA参数的会覆盖bsg文件中的同名词条。\n"
+ "如果开启离线命令词功能的话,本地语义文件参数可以不用输入。\n\n";
enableOffline = true; // 请确认不使用离线命令词功能后,改为false
// 改为false后需要勾选“本地语义文件”选项,同时可以勾选”扩展词条选项“
}
public ActivityNlu() {
super();
settingActivityClass = NluSetting.class;
}
@Override
protected CommonRecogParams getApiParams() {
return new NluRecogParams(this);
}
}
| cngmsy/18yearThirdRepository | yuyin/app/src/main/java/com/baidu/android/voicedemo/activity/ActivityNlu.java | 540 | // 请确认不使用离线命令词功能后,改为false | line_comment | zh-cn | package com.baidu.android.voicedemo.activity;
import com.baidu.android.voicedemo.activity.setting.NluSetting;
import com.baidu.android.voicedemo.recognization.CommonRecogParams;
import com.baidu.android.voicedemo.recognization.nlu.NluRecogParams;
/**
* Created by fujiayi on 2017/6/24.
*/
public class ActivityNlu extends ActivityRecog {
{
descText = "语义解析功能是指录音被识别出文字后, 对文字进行分析,如进行分词并尽可能获取文字的意图。\n"
+ "语义解析分为在线语义和本地语义:\n"
+ "1. 在线语义由百度服务器完成。 请点“设置”按钮选择开启“在线语义”。在线语义必须选择搜索模型。\n"
+ "2. 本地语义解析,请点“设置”按钮选择“在线+离线命令词+ SLOT_DATA”,“开启本地语义解析”。大声说“打电话给赵琦”\n"
+ "3. 离线命令词语义, 请测试”离线命令词”后,断网, 请点“设置”按钮选择“离在线+离线命令词+ SLOT_DATA”,“开启本地语义解析”。大声说“打电话给赵琦”\n\n"
+ "集成指南:\n"
+ "本地语义:在开始识别ASR_START输入事件中的GRAMMER参数中设置bsg文件路径。如同时设置SLOT_DATA参数的会覆盖bsg文件中的同名词条。\n"
+ "如果开启离线命令词功能的话,本地语义文件参数可以不用输入。\n\n";
enableOffline = true; // 请确 <SUF>
// 改为false后需要勾选“本地语义文件”选项,同时可以勾选”扩展词条选项“
}
public ActivityNlu() {
super();
settingActivityClass = NluSetting.class;
}
@Override
protected CommonRecogParams getApiParams() {
return new NluRecogParams(this);
}
}
| false | 472 | 15 | 540 | 16 | 519 | 14 | 540 | 16 | 768 | 24 | false | false | false | false | false | true |
52585_0 | package lexer;
public class Expr extends Node {
protected Token op;
protected Type type;
public Expr(Token op, Type type) {
this.op = op;
this.type = type;
}
public Token getOp() {
return op;
}
public void setOp(Token op) {
this.op = op;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public Expr gen() {
return this;
}
//规约函数
public Expr reduce() {
return this;
}
/**
* bool表达式生成跳转代码
*
* @param test bool表达式
* @param t 值为真的跳转语句标号,特殊标号0表示跳过
* @param f 值为假的跳转语句标号,特殊标号0表示跳过
*/
public void emitJumps(String test, int t, int f) {
if(t != 0 && f != 0){
emit("if " + test + " goto L" + t);
emit("goto L" + f);
}else if(t != 0) {
emit("if " + test + "goto L" + t);
}else if(f != 0) {
emit("iffalse" + test + " goto L" + f);
}
}
public void jumping(int t, int f) {
emitJumps(toString(), t, f);;
}
@Override
public String toString() {
return op.toString();
}
}
| cnlkl/Compiler | src/lexer/Expr.java | 409 | //规约函数 | line_comment | zh-cn | package lexer;
public class Expr extends Node {
protected Token op;
protected Type type;
public Expr(Token op, Type type) {
this.op = op;
this.type = type;
}
public Token getOp() {
return op;
}
public void setOp(Token op) {
this.op = op;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public Expr gen() {
return this;
}
//规约 <SUF>
public Expr reduce() {
return this;
}
/**
* bool表达式生成跳转代码
*
* @param test bool表达式
* @param t 值为真的跳转语句标号,特殊标号0表示跳过
* @param f 值为假的跳转语句标号,特殊标号0表示跳过
*/
public void emitJumps(String test, int t, int f) {
if(t != 0 && f != 0){
emit("if " + test + " goto L" + t);
emit("goto L" + f);
}else if(t != 0) {
emit("if " + test + "goto L" + t);
}else if(f != 0) {
emit("iffalse" + test + " goto L" + f);
}
}
public void jumping(int t, int f) {
emitJumps(toString(), t, f);;
}
@Override
public String toString() {
return op.toString();
}
}
| false | 356 | 4 | 409 | 4 | 444 | 4 | 409 | 4 | 528 | 9 | false | false | false | false | false | true |
59569_13 | package hadoop_kmeans;
import java.io.IOException;
import java.util.ArrayList;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.LineReader;
class Utils {
//读取中心文件的数据
public static ArrayList<ArrayList<Double>> getCentersFromHDFS(String centersPath,boolean isDirectory) throws IOException{
ArrayList<ArrayList<Double>> result = new ArrayList<ArrayList<Double>>();
Path path = new Path(centersPath);
Configuration conf = new Configuration();
FileSystem fileSystem = path.getFileSystem(conf);
if(isDirectory){
FileStatus[] listFile = fileSystem.listStatus(path);
for (int i = 0; i < listFile.length; i++) {
result.addAll(getCentersFromHDFS(listFile[i].getPath().toString(),false));
}
return result;
}
FSDataInputStream fsis = fileSystem.open(path);
LineReader lineReader = new LineReader(fsis, conf);
Text line = new Text();
while(lineReader.readLine(line) > 0){
ArrayList<Double> tempList = textToArray(line);
result.add(tempList);
}
lineReader.close();
return result;
}
//删掉文件
public static void deletePath(String pathStr) throws IOException{
Configuration conf = new Configuration();
Path path = new Path(pathStr);
FileSystem hdfs = path.getFileSystem(conf);
hdfs.delete(path ,true);
}
public static ArrayList<Double> textToArray(Text text){
ArrayList<Double> list = new ArrayList<Double>();
String[] fileds = text.toString().split(",");
for(int i=0;i<fileds.length;i++){
list.add(Double.parseDouble(fileds[i]));
}
return list;
}
public static boolean compareCenters(String centerPath,String newPath) throws IOException{
double ratio[] = {0.0,0.02278,6.65,4.49, 3.21, 5.6, 6.21, 10.76, 3.15, 0.51};
List<ArrayList<Double>> oldCenters = Utils.getCentersFromHDFS(centerPath,false);
List<ArrayList<Double>> newCenters = Utils.getCentersFromHDFS(newPath,true);
int size = oldCenters.size();
int fildSize = oldCenters.get(0).size();
double distance = 0;
for(int i=0;i<size;i++){
for(int j=1;j<fildSize-1;j++){
double t1 = oldCenters.get(i).get(j);
double t2 =newCenters.get(i).get(j);
distance += Math.pow((t1 - t2) / ratio[j], 2);
}
}
if(distance == 0.0){
//删掉新的中心文件以便最后依次归类输出
Utils.deletePath(newPath);
return true;
}else{
//先清空中心文件,将新的中心文件复制到中心文件中,再删掉中心文件
Configuration conf = new Configuration();
Path outPath = new Path(centerPath);
FileSystem fileSystem = outPath.getFileSystem(conf);
FSDataOutputStream overWrite = fileSystem.create(outPath,true);
overWrite.writeChars("");
overWrite.close();
Path inPath = new Path(newPath);
FileStatus[] listFiles = fileSystem.listStatus(inPath);
for (int i = 0; i < listFiles.length; i++) {
FSDataOutputStream out = fileSystem.create(outPath);
FSDataInputStream in = fileSystem.open(listFiles[i].getPath());
IOUtils.copyBytes(in, out, 4096, true);
}
//删掉新的中心文件以便第二次任务运行输出
Utils.deletePath(newPath);
}
return false;
}
}
public class Kmeans {
public static class Map extends Mapper<LongWritable, Text, IntWritable, Text>{
//中心集合
ArrayList<ArrayList<Double>> centers = null;
//用k个中心
int k = 6;
double ratio[] = {0.0,0.02278,6.65,4.49,3.21,5.6,6.21,10.76,3.15,0.51};
//读取中心
protected void setup(Context context) throws IOException,
InterruptedException {
centers = Utils.getCentersFromHDFS(context.getConfiguration().get("centersPath"),false);
k = centers.size();
}
/**
* 1.每次读取一条要分类的条记录与中心做对比,归类到对应的中心
* 2.以中心ID为key,中心包含的记录为value输出(例如: 1 0.2 。 1为聚类中心的ID,0.2为靠近聚类中心的某个值)
*/
protected void map(LongWritable key, Text value, Context context)
throws IOException, InterruptedException {
//读取一行数据
ArrayList<Double> fileds = Utils.textToArray(value);
int sizeOfFileds = fileds.size();
double minDistance = 99999999;
int centerIndex = 0;
//依次取出k个中心点与当前读取的记录做计算
for(int i=0;i<k;i++){
double currentDistance = 0;
for(int j=1;j<sizeOfFileds-1;j++){
double centerPoint = centers.get(i).get(j);
double filed = fileds.get(j);
currentDistance += Math.pow((centerPoint - filed) / ratio[j], 2);
}
//循环找出距离该记录最接近的中心点的ID
if(currentDistance<minDistance){
minDistance = currentDistance;
centerIndex = i;
}
}
//以中心点为Key 将记录原样输出
context.write(new IntWritable(centerIndex+1), value);
}
}
//利用reduce的归并功能以中心为Key将记录归并到一起
public static class Reduce extends Reducer<IntWritable, Text, Text, Text>{
/**
* 1.Key为聚类中心的ID value为该中心的记录集合
* 2.计数所有记录元素的平均值,求出新的中心
*/
protected void reduce(IntWritable key, Iterable<Text> value,Context context)
throws IOException, InterruptedException {
ArrayList<ArrayList<Double>> filedsList = new ArrayList<ArrayList<Double>>();
//依次读取记录集,每行为一个ArrayList<Double>
for(Iterator<Text> it =value.iterator();it.hasNext();){
ArrayList<Double> tempList = Utils.textToArray(it.next());
filedsList.add(tempList);
}
//计算新的中心
//每行的元素个数
int filedSize = filedsList.get(0).size();
double[] avg = new double[filedSize];
for(int i=1;i<filedSize-1;i++){
//求没列的平均值
double sum = 0;
int size = filedsList.size();
for(int j=0;j<size;j++){
sum += filedsList.get(j).get(i);
}
avg[i] = sum / size;
}
context.write(new Text("") , new Text(Arrays.toString(avg).replace("[", "").replace("]", "")));
}
}
@SuppressWarnings("deprecation")
public static void run(String centerPath,String dataPath,String newCenterPath,boolean runReduce) throws IOException, ClassNotFoundException, InterruptedException{
Configuration conf = new Configuration();
conf.set("centersPath", centerPath);
Job job = new Job(conf, "mykmeans");
job.setJarByClass(Kmeans.class);
job.setMapperClass(Map.class);
job.setMapOutputKeyClass(IntWritable.class);
job.setMapOutputValueClass(Text.class);
if(runReduce){
//最后一次输出不进行reduce操作
job.setReducerClass(Reduce.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
}
FileInputFormat.addInputPath(job, new Path(dataPath));
FileOutputFormat.setOutputPath(job, new Path(newCenterPath));
job.waitForCompletion(true);
}
public static void main(String[] args) throws ClassNotFoundException, IOException, InterruptedException {
String centerPath = "hdfs://localhost:9000/user/jun/oldcenters.data";
String dataPath = "hdfs://localhost:9000/user/jun/glass.data";
String newCenterPath = "hdfs://localhost:9000/user/jun/out";
int count = 0;
while(true){
run(centerPath,dataPath,newCenterPath,true);
System.out.println("Recur: " + ++count);
if(Utils.compareCenters(centerPath,newCenterPath )){
System.out.println("Nearly finish,outputing..");
run(centerPath,dataPath,newCenterPath,false);
System.out.println("Finish.");
break;
}
}
}
} | cnrpman/hadoop_Kmeans | Kmeans.java | 2,403 | //利用reduce的归并功能以中心为Key将记录归并到一起 | line_comment | zh-cn | package hadoop_kmeans;
import java.io.IOException;
import java.util.ArrayList;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.LineReader;
class Utils {
//读取中心文件的数据
public static ArrayList<ArrayList<Double>> getCentersFromHDFS(String centersPath,boolean isDirectory) throws IOException{
ArrayList<ArrayList<Double>> result = new ArrayList<ArrayList<Double>>();
Path path = new Path(centersPath);
Configuration conf = new Configuration();
FileSystem fileSystem = path.getFileSystem(conf);
if(isDirectory){
FileStatus[] listFile = fileSystem.listStatus(path);
for (int i = 0; i < listFile.length; i++) {
result.addAll(getCentersFromHDFS(listFile[i].getPath().toString(),false));
}
return result;
}
FSDataInputStream fsis = fileSystem.open(path);
LineReader lineReader = new LineReader(fsis, conf);
Text line = new Text();
while(lineReader.readLine(line) > 0){
ArrayList<Double> tempList = textToArray(line);
result.add(tempList);
}
lineReader.close();
return result;
}
//删掉文件
public static void deletePath(String pathStr) throws IOException{
Configuration conf = new Configuration();
Path path = new Path(pathStr);
FileSystem hdfs = path.getFileSystem(conf);
hdfs.delete(path ,true);
}
public static ArrayList<Double> textToArray(Text text){
ArrayList<Double> list = new ArrayList<Double>();
String[] fileds = text.toString().split(",");
for(int i=0;i<fileds.length;i++){
list.add(Double.parseDouble(fileds[i]));
}
return list;
}
public static boolean compareCenters(String centerPath,String newPath) throws IOException{
double ratio[] = {0.0,0.02278,6.65,4.49, 3.21, 5.6, 6.21, 10.76, 3.15, 0.51};
List<ArrayList<Double>> oldCenters = Utils.getCentersFromHDFS(centerPath,false);
List<ArrayList<Double>> newCenters = Utils.getCentersFromHDFS(newPath,true);
int size = oldCenters.size();
int fildSize = oldCenters.get(0).size();
double distance = 0;
for(int i=0;i<size;i++){
for(int j=1;j<fildSize-1;j++){
double t1 = oldCenters.get(i).get(j);
double t2 =newCenters.get(i).get(j);
distance += Math.pow((t1 - t2) / ratio[j], 2);
}
}
if(distance == 0.0){
//删掉新的中心文件以便最后依次归类输出
Utils.deletePath(newPath);
return true;
}else{
//先清空中心文件,将新的中心文件复制到中心文件中,再删掉中心文件
Configuration conf = new Configuration();
Path outPath = new Path(centerPath);
FileSystem fileSystem = outPath.getFileSystem(conf);
FSDataOutputStream overWrite = fileSystem.create(outPath,true);
overWrite.writeChars("");
overWrite.close();
Path inPath = new Path(newPath);
FileStatus[] listFiles = fileSystem.listStatus(inPath);
for (int i = 0; i < listFiles.length; i++) {
FSDataOutputStream out = fileSystem.create(outPath);
FSDataInputStream in = fileSystem.open(listFiles[i].getPath());
IOUtils.copyBytes(in, out, 4096, true);
}
//删掉新的中心文件以便第二次任务运行输出
Utils.deletePath(newPath);
}
return false;
}
}
public class Kmeans {
public static class Map extends Mapper<LongWritable, Text, IntWritable, Text>{
//中心集合
ArrayList<ArrayList<Double>> centers = null;
//用k个中心
int k = 6;
double ratio[] = {0.0,0.02278,6.65,4.49,3.21,5.6,6.21,10.76,3.15,0.51};
//读取中心
protected void setup(Context context) throws IOException,
InterruptedException {
centers = Utils.getCentersFromHDFS(context.getConfiguration().get("centersPath"),false);
k = centers.size();
}
/**
* 1.每次读取一条要分类的条记录与中心做对比,归类到对应的中心
* 2.以中心ID为key,中心包含的记录为value输出(例如: 1 0.2 。 1为聚类中心的ID,0.2为靠近聚类中心的某个值)
*/
protected void map(LongWritable key, Text value, Context context)
throws IOException, InterruptedException {
//读取一行数据
ArrayList<Double> fileds = Utils.textToArray(value);
int sizeOfFileds = fileds.size();
double minDistance = 99999999;
int centerIndex = 0;
//依次取出k个中心点与当前读取的记录做计算
for(int i=0;i<k;i++){
double currentDistance = 0;
for(int j=1;j<sizeOfFileds-1;j++){
double centerPoint = centers.get(i).get(j);
double filed = fileds.get(j);
currentDistance += Math.pow((centerPoint - filed) / ratio[j], 2);
}
//循环找出距离该记录最接近的中心点的ID
if(currentDistance<minDistance){
minDistance = currentDistance;
centerIndex = i;
}
}
//以中心点为Key 将记录原样输出
context.write(new IntWritable(centerIndex+1), value);
}
}
//利用 <SUF>
public static class Reduce extends Reducer<IntWritable, Text, Text, Text>{
/**
* 1.Key为聚类中心的ID value为该中心的记录集合
* 2.计数所有记录元素的平均值,求出新的中心
*/
protected void reduce(IntWritable key, Iterable<Text> value,Context context)
throws IOException, InterruptedException {
ArrayList<ArrayList<Double>> filedsList = new ArrayList<ArrayList<Double>>();
//依次读取记录集,每行为一个ArrayList<Double>
for(Iterator<Text> it =value.iterator();it.hasNext();){
ArrayList<Double> tempList = Utils.textToArray(it.next());
filedsList.add(tempList);
}
//计算新的中心
//每行的元素个数
int filedSize = filedsList.get(0).size();
double[] avg = new double[filedSize];
for(int i=1;i<filedSize-1;i++){
//求没列的平均值
double sum = 0;
int size = filedsList.size();
for(int j=0;j<size;j++){
sum += filedsList.get(j).get(i);
}
avg[i] = sum / size;
}
context.write(new Text("") , new Text(Arrays.toString(avg).replace("[", "").replace("]", "")));
}
}
@SuppressWarnings("deprecation")
public static void run(String centerPath,String dataPath,String newCenterPath,boolean runReduce) throws IOException, ClassNotFoundException, InterruptedException{
Configuration conf = new Configuration();
conf.set("centersPath", centerPath);
Job job = new Job(conf, "mykmeans");
job.setJarByClass(Kmeans.class);
job.setMapperClass(Map.class);
job.setMapOutputKeyClass(IntWritable.class);
job.setMapOutputValueClass(Text.class);
if(runReduce){
//最后一次输出不进行reduce操作
job.setReducerClass(Reduce.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
}
FileInputFormat.addInputPath(job, new Path(dataPath));
FileOutputFormat.setOutputPath(job, new Path(newCenterPath));
job.waitForCompletion(true);
}
public static void main(String[] args) throws ClassNotFoundException, IOException, InterruptedException {
String centerPath = "hdfs://localhost:9000/user/jun/oldcenters.data";
String dataPath = "hdfs://localhost:9000/user/jun/glass.data";
String newCenterPath = "hdfs://localhost:9000/user/jun/out";
int count = 0;
while(true){
run(centerPath,dataPath,newCenterPath,true);
System.out.println("Recur: " + ++count);
if(Utils.compareCenters(centerPath,newCenterPath )){
System.out.println("Nearly finish,outputing..");
run(centerPath,dataPath,newCenterPath,false);
System.out.println("Finish.");
break;
}
}
}
} | false | 2,117 | 17 | 2,403 | 17 | 2,602 | 17 | 2,403 | 17 | 2,969 | 26 | false | false | false | false | false | true |
60347_0 | package com.cnwanj.lanqiao.guosai.lanqiao7;
/**
* @Author: cnwnaj
* @Date: 2020-10-28 09:30:55
* @Description:
*
* 圆圈舞
*
* 春天温暖的阳光照耀着大地,正是草原上的小动物们最快乐的时候。
*
* 小动物们在草原上开了一个舞会,欢度这美好的时光。
*
* 舞会上最重要的一个环节就是跳圆舞曲,n只小动物手拉手围成一大圈,
*
* 随着音乐跳起来。在跳的过程中,小动物们可能会变换队形。
*
* 它们的变换方式是动物A松开自己右手,动物B松开自己的左手,
*
* 动物A和B手拉到一起,而它们对应的松开的手(如果有的话)也拉到一起。
*
* 例如,假设有10只小动物,按顺序围成一圈,动物1的右手拉着动物2的左手,
*
* 动物2的右手拉着动物3的左手,依次类推,最后动物10的右手拉着动物1的左手。
*
* 如果通过动物2和8变换队形,则动物2的右手拉着动物8的左手,
*
* 而对应的动物3的左手拉着动物7的右手,这样形成了1-2-8-9-10和3-4-5-6-7两个圈。
*
* 如果此时通过动物2和6变换队形,则将形成1-2-6-7-3-4-5-8-9-10一个大圈。
*
* 注意,如果此时通过动物1和2变换队形,那么队形不会改变,
*
* 因为动物1的右手和动物2的左手松开后又拉到一起了。
*
* 在跳舞的过程中,每个动物i都有一个欢乐值Hi和一个感动值Fi。
*
*
* 如果两个动物在一个圈中,欢乐值会彼此影响,产生欢乐能量。
*
* 如果两个动物i, j(i≠j)在同一个大小为t的圈中,
*
* 而动物i在动物j右手的第p个位置(动物j右手的第1个位置就是动物j右手所拉着的动物,
*
* 而第2个位置就是右手第1个位置的动物右手拉着的动物,依次类推),
*
* 则产生的欢乐能量为(t-p)*Hj*Fi。在跳舞的过程中,动物们的欢乐值和感动值有可能发生变化。
*
* 圆舞曲开始的时候,所有的动物按编号顺序围成一个圈,动物n右手的第i个位置正好是动物i。
*
* 现在已知小动物们变换队形的过程和欢乐值、感动值变化的过程,求每次变换后所有动物所产生的欢迎能量之和。
*
* 【输入格式】
*
* 输入的第一行包含一个整数n,表示动物的数量。
*
* 接下来n行,每行两个用空格分隔的整数Hi, Fi,按编号顺序给出每只动物的欢乐值和感动值。
*
* 接下来一行包含一个整数m,表示队形、欢乐值、感动值的变化次数。
*
* 接下来m行,每行三个用空格分隔的整数k, p, q,当k=1时,
*
* 表示小动物们通过动物p和动物q变换了队形,当k=2时,表示动物p的欢乐值变为q,当k=3时,表示动物p的感动值变为了q。
*
* 【输出格式】
*
* 输出m行,每行一个整数,表示每次变化后所有动物产生的能量之和。
*
* 答案可能很大,你需要计算答案除以1000000007的余数。
*
* 【样例输入】
*
* 10
* 1 1
* 1 1
* 1 1
* 1 1
* 1 1
* 1 1
* 1 1
* 1 1
* 1 1
* 1 1
* 9
* 1 2 8
* 1 2 6
* 2 8 10
* 3 5 10
* 1 1 2
* 1 2 1
* 2 5 5
* 1 4 8
* 1 4 5
*
* 【样例输出】
* 100
* 450
* 855
* 1341
* 1341
* 811
* 923
* 338
* 923
*
* 【数据规模与约定】
* 对于20%的数据,2<=n,m<=100。
* 对于30%的数据,2<=n,m<=1000。
* 另有20%的数据,只有k=1的操作且Hi,Fi均为1。
* 另有20%的数据,只有k=1或2的操作且Fi均为1。
* 对于100%的数据,2<=n,m<=100000,0<=Hi,Fi<=10^9,1<=k<=3,k=1时1<=p,q<=n且p≠q,k=2或3时1<=p<=n且0<=q<=10^9。
*
* 资源约定:
* 峰值内存消耗 < 256M
* CPU消耗 < 5000ms
*
* 请严格按要求输出,不要画蛇添足地打印类似:“请您输入...” 的多余内容。
*
* 所有代码放在同一个源文件中,调试通过后,拷贝提交该源码。
* 注意:不要使用package语句。不要使用jdk1.7及以上版本的特性。
* 注意:主类的名字必须是:Main,否则按无效代码处理。
*
*/
public class Main6_圆圈舞 {
}
| cnwanj/lanqiao | src/com/cnwanj/lanqiao/guosai/lanqiao7/Main6_圆圈舞.java | 1,641 | /**
* @Author: cnwnaj
* @Date: 2020-10-28 09:30:55
* @Description:
*
* 圆圈舞
*
* 春天温暖的阳光照耀着大地,正是草原上的小动物们最快乐的时候。
*
* 小动物们在草原上开了一个舞会,欢度这美好的时光。
*
* 舞会上最重要的一个环节就是跳圆舞曲,n只小动物手拉手围成一大圈,
*
* 随着音乐跳起来。在跳的过程中,小动物们可能会变换队形。
*
* 它们的变换方式是动物A松开自己右手,动物B松开自己的左手,
*
* 动物A和B手拉到一起,而它们对应的松开的手(如果有的话)也拉到一起。
*
* 例如,假设有10只小动物,按顺序围成一圈,动物1的右手拉着动物2的左手,
*
* 动物2的右手拉着动物3的左手,依次类推,最后动物10的右手拉着动物1的左手。
*
* 如果通过动物2和8变换队形,则动物2的右手拉着动物8的左手,
*
* 而对应的动物3的左手拉着动物7的右手,这样形成了1-2-8-9-10和3-4-5-6-7两个圈。
*
* 如果此时通过动物2和6变换队形,则将形成1-2-6-7-3-4-5-8-9-10一个大圈。
*
* 注意,如果此时通过动物1和2变换队形,那么队形不会改变,
*
* 因为动物1的右手和动物2的左手松开后又拉到一起了。
*
* 在跳舞的过程中,每个动物i都有一个欢乐值Hi和一个感动值Fi。
*
*
* 如果两个动物在一个圈中,欢乐值会彼此影响,产生欢乐能量。
*
* 如果两个动物i, j(i≠j)在同一个大小为t的圈中,
*
* 而动物i在动物j右手的第p个位置(动物j右手的第1个位置就是动物j右手所拉着的动物,
*
* 而第2个位置就是右手第1个位置的动物右手拉着的动物,依次类推),
*
* 则产生的欢乐能量为(t-p)*Hj*Fi。在跳舞的过程中,动物们的欢乐值和感动值有可能发生变化。
*
* 圆舞曲开始的时候,所有的动物按编号顺序围成一个圈,动物n右手的第i个位置正好是动物i。
*
* 现在已知小动物们变换队形的过程和欢乐值、感动值变化的过程,求每次变换后所有动物所产生的欢迎能量之和。
*
* 【输入格式】
*
* 输入的第一行包含一个整数n,表示动物的数量。
*
* 接下来n行,每行两个用空格分隔的整数Hi, Fi,按编号顺序给出每只动物的欢乐值和感动值。
*
* 接下来一行包含一个整数m,表示队形、欢乐值、感动值的变化次数。
*
* 接下来m行,每行三个用空格分隔的整数k, p, q,当k=1时,
*
* 表示小动物们通过动物p和动物q变换了队形,当k=2时,表示动物p的欢乐值变为q,当k=3时,表示动物p的感动值变为了q。
*
* 【输出格式】
*
* 输出m行,每行一个整数,表示每次变化后所有动物产生的能量之和。
*
* 答案可能很大,你需要计算答案除以1000000007的余数。
*
* 【样例输入】
*
* 10
* 1 1
* 1 1
* 1 1
* 1 1
* 1 1
* 1 1
* 1 1
* 1 1
* 1 1
* 1 1
* 9
* 1 2 8
* 1 2 6
* 2 8 10
* 3 5 10
* 1 1 2
* 1 2 1
* 2 5 5
* 1 4 8
* 1 4 5
*
* 【样例输出】
* 100
* 450
* 855
* 1341
* 1341
* 811
* 923
* 338
* 923
*
* 【数据规模与约定】
* 对于20%的数据,2<=n,m<=100。
* 对于30%的数据,2<=n,m<=1000。
* 另有20%的数据,只有k=1的操作且Hi,Fi均为1。
* 另有20%的数据,只有k=1或2的操作且Fi均为1。
* 对于100%的数据,2<=n,m<=100000,0<=Hi,Fi<=10^9,1<=k<=3,k=1时1<=p,q<=n且p≠q,k=2或3时1<=p<=n且0<=q<=10^9。
*
* 资源约定:
* 峰值内存消耗 < 256M
* CPU消耗 < 5000ms
*
* 请严格按要求输出,不要画蛇添足地打印类似:“请您输入...” 的多余内容。
*
* 所有代码放在同一个源文件中,调试通过后,拷贝提交该源码。
* 注意:不要使用package语句。不要使用jdk1.7及以上版本的特性。
* 注意:主类的名字必须是:Main,否则按无效代码处理。
*
*/ | block_comment | zh-cn | package com.cnwanj.lanqiao.guosai.lanqiao7;
/**
* @Au <SUF>*/
public class Main6_圆圈舞 {
}
| false | 1,362 | 1,334 | 1,641 | 1,604 | 1,412 | 1,380 | 1,641 | 1,604 | 2,052 | 2,013 | true | true | true | true | true | false |
63213_1 | /**
*
*/
package org.cocolian.nlp.pos.chmm;
/**
* 用于索引TermNature的节点树的节点
*
* @author lixf
*
*/
public interface CharNode {
enum State {
// 0.代表这个字/词不在词典中, 不再继续;
NOT_WORD(0),
// 1. 不成词,但是可以继续。比如 中流砥(柱),走到 过 的时候,还没成词,继续好了。
PART_OF_WORD(1),
// 2.是个词但是还可以继续
WORD_AND_PART(2),
// 3.停止已经是个词了
END_OF_WORD(3),
// 4. 英语
ENGLISH(4),
// 5. 数字
NUMBER(5);
private int state;
State(int state) {
this.state = state;
}
public static State valueOf(int value) {
for (State state : State.values()) {
if (state.state == value)
return state;
}
throw new IllegalArgumentException("Unknown state :" + value);
}
public boolean isChinese() {
return state < 4;
}
@Override
public String toString() {
return String.valueOf(this.state);
}
};
/**
* 这个节点对应的字符;
*
* @return
*/
public char getChar();
/**
* 从跟到当前节点的状态;
*
* @return
*/
public State getState();
/**
* 当前节点的TermNatures;
*
* @return
*/
public TermNatures getTermNatures();
/**
* 获取子节点;
*
* @param ch
* @return
*/
public CharNode get(char ch);
}
| cocolian/cocolian-nlp | src/main/java/org/cocolian/nlp/pos/chmm/CharNode.java | 461 | // 0.代表这个字/词不在词典中, 不再继续; | line_comment | zh-cn | /**
*
*/
package org.cocolian.nlp.pos.chmm;
/**
* 用于索引TermNature的节点树的节点
*
* @author lixf
*
*/
public interface CharNode {
enum State {
// 0. <SUF>
NOT_WORD(0),
// 1. 不成词,但是可以继续。比如 中流砥(柱),走到 过 的时候,还没成词,继续好了。
PART_OF_WORD(1),
// 2.是个词但是还可以继续
WORD_AND_PART(2),
// 3.停止已经是个词了
END_OF_WORD(3),
// 4. 英语
ENGLISH(4),
// 5. 数字
NUMBER(5);
private int state;
State(int state) {
this.state = state;
}
public static State valueOf(int value) {
for (State state : State.values()) {
if (state.state == value)
return state;
}
throw new IllegalArgumentException("Unknown state :" + value);
}
public boolean isChinese() {
return state < 4;
}
@Override
public String toString() {
return String.valueOf(this.state);
}
};
/**
* 这个节点对应的字符;
*
* @return
*/
public char getChar();
/**
* 从跟到当前节点的状态;
*
* @return
*/
public State getState();
/**
* 当前节点的TermNatures;
*
* @return
*/
public TermNatures getTermNatures();
/**
* 获取子节点;
*
* @param ch
* @return
*/
public CharNode get(char ch);
}
| false | 412 | 18 | 461 | 19 | 466 | 18 | 461 | 19 | 628 | 31 | false | false | false | false | false | true |
30400_0 | package com.example.answer.util;
public class ConstantData {
public static final String answerId[]={"1","2","3","4","5"};
public static final String answerName[]={"您的年龄是?","您的工作是?","下列属于腾讯开发的游戏?","网络游戏一定需要付费","患者肢体损伤制动后,短期内就可能引起关节的挛缩和变形,因此,在卧床期间,就要认真考虑预防关节挛缩的发生,下列方法中较理想的一组方法是( )"};
public static final String answerType[]={"0","0","1","2","1"};//0单选 1多选 2判断
public static final String answerOptionA[]={"18岁以下","学生","梦幻西游","对","AA"};
public static final String answerOptionB[]={"18岁至25岁","公务单位","英雄联盟","错","BB"};
public static final String answerOptionC[]={"25岁至35岁","工薪一族","诛仙","","BC"};
public static final String answerOptionD[]={"35岁至45岁","自己当老板","逆战","","CC"};
public static final String answerOptionE[]={"45岁以上","其他","劲舞团","","DD"};
public static final String answerAnalysis[]={"暂无解答","自己当老板","此题太简单了","简单","解析无"};
public static final String answerScore[]={"2","2","1","2","1"};
public static final String answerCorrect[]={"A","D","BD","B","AD"};
}
| code-hunter/Answer | src/com/example/answer/util/ConstantData.java | 414 | //0单选 1多选 2判断 | line_comment | zh-cn | package com.example.answer.util;
public class ConstantData {
public static final String answerId[]={"1","2","3","4","5"};
public static final String answerName[]={"您的年龄是?","您的工作是?","下列属于腾讯开发的游戏?","网络游戏一定需要付费","患者肢体损伤制动后,短期内就可能引起关节的挛缩和变形,因此,在卧床期间,就要认真考虑预防关节挛缩的发生,下列方法中较理想的一组方法是( )"};
public static final String answerType[]={"0","0","1","2","1"};//0单 <SUF>
public static final String answerOptionA[]={"18岁以下","学生","梦幻西游","对","AA"};
public static final String answerOptionB[]={"18岁至25岁","公务单位","英雄联盟","错","BB"};
public static final String answerOptionC[]={"25岁至35岁","工薪一族","诛仙","","BC"};
public static final String answerOptionD[]={"35岁至45岁","自己当老板","逆战","","CC"};
public static final String answerOptionE[]={"45岁以上","其他","劲舞团","","DD"};
public static final String answerAnalysis[]={"暂无解答","自己当老板","此题太简单了","简单","解析无"};
public static final String answerScore[]={"2","2","1","2","1"};
public static final String answerCorrect[]={"A","D","BD","B","AD"};
}
| false | 324 | 11 | 414 | 11 | 362 | 11 | 414 | 11 | 561 | 12 | false | false | false | false | false | true |
14030_0 | package com.ysj.tinySpring.aop;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import org.aopalliance.intercept.MethodInterceptor;
/**
* 一个基于JDK的动态代理
* 只能针对实现了接口的类生成代理。于是我们就有了基本的织入功能。
* 注意:实现了InvocationHandler接口,可以通过重写invoke方法进行控制访问
*
*/
public class JdkDynamicAopProxy extends AbstractAopProxy implements InvocationHandler {
public JdkDynamicAopProxy(AdvisedSupport advised) {
super(advised);
}
/**
* 获取代理对象
*/
@Override
public Object getProxy() {
return Proxy.newProxyInstance(getClass().getClassLoader(),
advised.getTargetSource().getInterfaces(),
this);
}
/**
* 控制访问
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 从AdvisedSupport里获取方法拦截器
MethodInterceptor methodInterceptor = advised.getMethodInterceptor();
// 如果方法匹配器存在,且匹配该对象的该方法匹配成功,则调用用户提供的方法拦截器的invoke方法
if (advised.getMethodMatcher() != null
&& advised.getMethodMatcher().matches(method, advised.getTargetSource().getTarget().getClass())) {
return methodInterceptor.invoke(new ReflectiveMethodInvocation(advised.getTargetSource().getTarget(),
method, args));
} else {
// 否则的话还是调用原对象的相关方法
return method.invoke(advised.getTargetSource().getTarget(), args);
}
}
}
| code4craft/tiny-spring | src+/main/java/com/ysj/tinySpring/aop/JdkDynamicAopProxy.java | 415 | /**
* 一个基于JDK的动态代理
* 只能针对实现了接口的类生成代理。于是我们就有了基本的织入功能。
* 注意:实现了InvocationHandler接口,可以通过重写invoke方法进行控制访问
*
*/ | block_comment | zh-cn | package com.ysj.tinySpring.aop;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import org.aopalliance.intercept.MethodInterceptor;
/**
* 一个基 <SUF>*/
public class JdkDynamicAopProxy extends AbstractAopProxy implements InvocationHandler {
public JdkDynamicAopProxy(AdvisedSupport advised) {
super(advised);
}
/**
* 获取代理对象
*/
@Override
public Object getProxy() {
return Proxy.newProxyInstance(getClass().getClassLoader(),
advised.getTargetSource().getInterfaces(),
this);
}
/**
* 控制访问
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 从AdvisedSupport里获取方法拦截器
MethodInterceptor methodInterceptor = advised.getMethodInterceptor();
// 如果方法匹配器存在,且匹配该对象的该方法匹配成功,则调用用户提供的方法拦截器的invoke方法
if (advised.getMethodMatcher() != null
&& advised.getMethodMatcher().matches(method, advised.getTargetSource().getTarget().getClass())) {
return methodInterceptor.invoke(new ReflectiveMethodInvocation(advised.getTargetSource().getTarget(),
method, args));
} else {
// 否则的话还是调用原对象的相关方法
return method.invoke(advised.getTargetSource().getTarget(), args);
}
}
}
| false | 355 | 51 | 415 | 59 | 392 | 51 | 415 | 59 | 567 | 89 | false | false | false | false | false | true |
14882_2 | package us.codecraft.webmagic.pipeline;
import us.codecraft.webmagic.MultiPageModel;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.utils.Experimental;
import us.codecraft.webmagic.utils.DoubleKeyMap;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/**
* A pipeline combines the result in more than one page together.<br>
* Used for news and articles containing more than one web page. <br>
* MultiPagePipeline will store parts of object and output them when all parts are extracted.<br>
*
* @author code4crafter@gmail.com <br>
* @since 0.2.0
*/
@Experimental
public class MultiPagePipeline implements Pipeline {
private DoubleKeyMap<String, String, Boolean> pageMap = new DoubleKeyMap<String, String, Boolean>(ConcurrentHashMap.class);
private DoubleKeyMap<String, String, MultiPageModel> objectMap = new DoubleKeyMap<String, String, MultiPageModel>(ConcurrentHashMap.class);
@Override
public void process(ResultItems resultItems, Task task) {
Map<String, Object> resultItemsAll = resultItems.getAll();
Iterator<Map.Entry<String, Object>> iterator = resultItemsAll.entrySet().iterator();
while (iterator.hasNext()) {
handleObject(iterator);
}
}
private void handleObject(Iterator<Map.Entry<String, Object>> iterator) {
Map.Entry<String, Object> objectEntry = iterator.next();
Object o = objectEntry.getValue();
//需要拼凑
if (o instanceof MultiPageModel) {
MultiPageModel multiPageModel = (MultiPageModel) o;
//这次处理的部分,设置为完成
pageMap.put(multiPageModel.getPageKey(), multiPageModel.getPage(), Boolean.FALSE);
//每个key单独加锁
synchronized (pageMap.get(multiPageModel.getPageKey())) {
pageMap.put(multiPageModel.getPageKey(), multiPageModel.getPage(), Boolean.TRUE);
//其他需要拼凑的部分
if (multiPageModel.getOtherPages() != null) {
for (String otherPage : multiPageModel.getOtherPages()) {
Boolean aBoolean = pageMap.get(multiPageModel.getPageKey(), otherPage);
if (aBoolean == null) {
pageMap.put(multiPageModel.getPageKey(), otherPage, Boolean.FALSE);
}
}
}
//check if all pages are processed
Map<String, Boolean> booleanMap = pageMap.get(multiPageModel.getPageKey());
objectMap.put(multiPageModel.getPageKey(), multiPageModel.getPage(), multiPageModel);
if (booleanMap == null) {
return;
}
// /过滤,这次完成的page item中,还未拼凑完整的item,不进入下一个pipeline
for (Map.Entry<String, Boolean> stringBooleanEntry : booleanMap.entrySet()) {
if (!stringBooleanEntry.getValue()) {
iterator.remove();
return;
}
}
List<Map.Entry<String, MultiPageModel>> entryList = new ArrayList<Map.Entry<String, MultiPageModel>>();
entryList.addAll(objectMap.get(multiPageModel.getPageKey()).entrySet());
if (entryList.size() != 0) {
Collections.sort(entryList, new Comparator<Map.Entry<String, MultiPageModel>>() {
@Override
public int compare(Map.Entry<String, MultiPageModel> o1, Map.Entry<String, MultiPageModel> o2) {
try {
int i1 = Integer.parseInt(o1.getKey());
int i2 = Integer.parseInt(o2.getKey());
return i1 - i2;
} catch (NumberFormatException e) {
return o1.getKey().compareTo(o2.getKey());
}
}
});
// 合并
MultiPageModel value = entryList.get(0).getValue();
for (int i = 1; i < entryList.size(); i++) {
value = value.combine(entryList.get(i).getValue());
}
objectEntry.setValue(value);
}
}
}
}
}
| code4craft/webmagic | webmagic-extension/src/main/java/us/codecraft/webmagic/pipeline/MultiPagePipeline.java | 989 | //这次处理的部分,设置为完成 | line_comment | zh-cn | package us.codecraft.webmagic.pipeline;
import us.codecraft.webmagic.MultiPageModel;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.utils.Experimental;
import us.codecraft.webmagic.utils.DoubleKeyMap;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/**
* A pipeline combines the result in more than one page together.<br>
* Used for news and articles containing more than one web page. <br>
* MultiPagePipeline will store parts of object and output them when all parts are extracted.<br>
*
* @author code4crafter@gmail.com <br>
* @since 0.2.0
*/
@Experimental
public class MultiPagePipeline implements Pipeline {
private DoubleKeyMap<String, String, Boolean> pageMap = new DoubleKeyMap<String, String, Boolean>(ConcurrentHashMap.class);
private DoubleKeyMap<String, String, MultiPageModel> objectMap = new DoubleKeyMap<String, String, MultiPageModel>(ConcurrentHashMap.class);
@Override
public void process(ResultItems resultItems, Task task) {
Map<String, Object> resultItemsAll = resultItems.getAll();
Iterator<Map.Entry<String, Object>> iterator = resultItemsAll.entrySet().iterator();
while (iterator.hasNext()) {
handleObject(iterator);
}
}
private void handleObject(Iterator<Map.Entry<String, Object>> iterator) {
Map.Entry<String, Object> objectEntry = iterator.next();
Object o = objectEntry.getValue();
//需要拼凑
if (o instanceof MultiPageModel) {
MultiPageModel multiPageModel = (MultiPageModel) o;
//这次 <SUF>
pageMap.put(multiPageModel.getPageKey(), multiPageModel.getPage(), Boolean.FALSE);
//每个key单独加锁
synchronized (pageMap.get(multiPageModel.getPageKey())) {
pageMap.put(multiPageModel.getPageKey(), multiPageModel.getPage(), Boolean.TRUE);
//其他需要拼凑的部分
if (multiPageModel.getOtherPages() != null) {
for (String otherPage : multiPageModel.getOtherPages()) {
Boolean aBoolean = pageMap.get(multiPageModel.getPageKey(), otherPage);
if (aBoolean == null) {
pageMap.put(multiPageModel.getPageKey(), otherPage, Boolean.FALSE);
}
}
}
//check if all pages are processed
Map<String, Boolean> booleanMap = pageMap.get(multiPageModel.getPageKey());
objectMap.put(multiPageModel.getPageKey(), multiPageModel.getPage(), multiPageModel);
if (booleanMap == null) {
return;
}
// /过滤,这次完成的page item中,还未拼凑完整的item,不进入下一个pipeline
for (Map.Entry<String, Boolean> stringBooleanEntry : booleanMap.entrySet()) {
if (!stringBooleanEntry.getValue()) {
iterator.remove();
return;
}
}
List<Map.Entry<String, MultiPageModel>> entryList = new ArrayList<Map.Entry<String, MultiPageModel>>();
entryList.addAll(objectMap.get(multiPageModel.getPageKey()).entrySet());
if (entryList.size() != 0) {
Collections.sort(entryList, new Comparator<Map.Entry<String, MultiPageModel>>() {
@Override
public int compare(Map.Entry<String, MultiPageModel> o1, Map.Entry<String, MultiPageModel> o2) {
try {
int i1 = Integer.parseInt(o1.getKey());
int i2 = Integer.parseInt(o2.getKey());
return i1 - i2;
} catch (NumberFormatException e) {
return o1.getKey().compareTo(o2.getKey());
}
}
});
// 合并
MultiPageModel value = entryList.get(0).getValue();
for (int i = 1; i < entryList.size(); i++) {
value = value.combine(entryList.get(i).getValue());
}
objectEntry.setValue(value);
}
}
}
}
}
| false | 853 | 8 | 989 | 9 | 1,038 | 7 | 989 | 9 | 1,169 | 14 | false | false | false | false | false | true |
48782_8 | package com.kk.str;
/**
* KMP字符串匹配算法
*/
public class KMP {
public static int find(String str, String temp) {
return find(str.toCharArray(), temp.toCharArray());
}
public static int find(char[] str, char[] temp) {
int n = str.length;
int tempLen = temp.length;
int[] jumpTable = calJumpTable(temp);
int j = 0; //j表示当前模版串的待匹配位置
for (int i = 0; i < n; ++i) {
while (str[i] != temp[j]) { // 失配点
j = jumpTable[j]; //不停的转移,直到可以匹配或者走到0
if (j == 0) break;
}
// 调整失配点之后,向后移位逐个比较
if (str[i] == temp[j]) j++;
if (j == tempLen) return i - tempLen + 1;
}
// 未找到
return -1;
}
static int[] calJumpTable(String temp) {
return calJumpTable(temp.toCharArray());
}
/**
* 计算失配-跳转表
*/
static int[] calJumpTable(char[] temp) {
int len = temp.length;
int[] table = new int[len + 1];
table[0] = table[1] = 0; // 边界
for (int n = 1; n < len; ++n) {
int jump = table[n];
while (temp[n] != temp[jump]) {
// jump 向前追溯
jump = table[jump];
if (jump == 0) { // 为0,表示已回退到指定点
break;
}
}
// 递推
table[n + 1] = temp[n] == temp[jump] ? jump + 1 : 0;
}
return table;
}
}
| codeartx/awesome-algorithm | src/main/java/com/kk/str/KMP.java | 459 | // 为0,表示已回退到指定点 | line_comment | zh-cn | package com.kk.str;
/**
* KMP字符串匹配算法
*/
public class KMP {
public static int find(String str, String temp) {
return find(str.toCharArray(), temp.toCharArray());
}
public static int find(char[] str, char[] temp) {
int n = str.length;
int tempLen = temp.length;
int[] jumpTable = calJumpTable(temp);
int j = 0; //j表示当前模版串的待匹配位置
for (int i = 0; i < n; ++i) {
while (str[i] != temp[j]) { // 失配点
j = jumpTable[j]; //不停的转移,直到可以匹配或者走到0
if (j == 0) break;
}
// 调整失配点之后,向后移位逐个比较
if (str[i] == temp[j]) j++;
if (j == tempLen) return i - tempLen + 1;
}
// 未找到
return -1;
}
static int[] calJumpTable(String temp) {
return calJumpTable(temp.toCharArray());
}
/**
* 计算失配-跳转表
*/
static int[] calJumpTable(char[] temp) {
int len = temp.length;
int[] table = new int[len + 1];
table[0] = table[1] = 0; // 边界
for (int n = 1; n < len; ++n) {
int jump = table[n];
while (temp[n] != temp[jump]) {
// jump 向前追溯
jump = table[jump];
if (jump == 0) { // 为0 <SUF>
break;
}
}
// 递推
table[n + 1] = temp[n] == temp[jump] ? jump + 1 : 0;
}
return table;
}
}
| false | 436 | 12 | 459 | 11 | 491 | 11 | 459 | 11 | 585 | 16 | false | false | false | false | false | true |
13808_1 | package cumt.tj.learn.offer;
/**
* Created by sky on 17-8-3.
* 题目描述
* 把只包含因子2、3和5的数称作丑数(Ugly Number)。
* 例如6、8都是丑数,但14不是,因为它包含因子7。
* 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。
*
* 思路:
* 由于丑数可以看作另外一个丑数与2、3、5相乘的结果
* 使用大小为k一个数组,准备按顺序存储丑数
* 对于数组中的最大值M,要对前面的元素分别乘2、3、5,找到大于M的最小值作为下一个要存储的元素
* 而对于一个元素如果它乘以2的值已经被加入到数组中,那么下一次乘以2的时候,应该从它后面开始
* 所以我们用3个变量分别存储已经下一个应该乘2、3、5的元素索引,以节省时间
* 详见http://blog.csdn.net/w417950004/article/details/54348695
*/
public class GetUglyNumber {
public int getUglyNumber(int index) {
if(index==0) return 0;
//丑数数组
int[] uglyNumbers=new int[index];
uglyNumbers[0]=1;
//当前数组中的丑数数量
int size=1;
//存储最小的M2、M3、M5
int m2=0;int m3=0;int m5=0;
int t2=0,t3=0,t5=0;
while (size<index) {
m2=uglyNumbers[t2]*2;m3=uglyNumbers[t3]*3;m5=uglyNumbers[t5]*5;
uglyNumbers[size]=Math.min(Math.min(m2,m3),m5);
//每一个都要判断,因为有可能相等,而那个索引下次不能用了,否则会一直停在那儿,比如:2*3=6,3×2=6
if(m2==uglyNumbers[size]) {
t2++;
}
if(m3==uglyNumbers[size]){
t3++;
}
if(m5==uglyNumbers[size]){
t5++;
}
size++;
}
return uglyNumbers[index-1];
}
}
| codeboytj/data-structures-algorithms | src/main/java/cumt/tj/learn/offer/GetUglyNumber.java | 615 | //丑数数组 | line_comment | zh-cn | package cumt.tj.learn.offer;
/**
* Created by sky on 17-8-3.
* 题目描述
* 把只包含因子2、3和5的数称作丑数(Ugly Number)。
* 例如6、8都是丑数,但14不是,因为它包含因子7。
* 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。
*
* 思路:
* 由于丑数可以看作另外一个丑数与2、3、5相乘的结果
* 使用大小为k一个数组,准备按顺序存储丑数
* 对于数组中的最大值M,要对前面的元素分别乘2、3、5,找到大于M的最小值作为下一个要存储的元素
* 而对于一个元素如果它乘以2的值已经被加入到数组中,那么下一次乘以2的时候,应该从它后面开始
* 所以我们用3个变量分别存储已经下一个应该乘2、3、5的元素索引,以节省时间
* 详见http://blog.csdn.net/w417950004/article/details/54348695
*/
public class GetUglyNumber {
public int getUglyNumber(int index) {
if(index==0) return 0;
//丑数 <SUF>
int[] uglyNumbers=new int[index];
uglyNumbers[0]=1;
//当前数组中的丑数数量
int size=1;
//存储最小的M2、M3、M5
int m2=0;int m3=0;int m5=0;
int t2=0,t3=0,t5=0;
while (size<index) {
m2=uglyNumbers[t2]*2;m3=uglyNumbers[t3]*3;m5=uglyNumbers[t5]*5;
uglyNumbers[size]=Math.min(Math.min(m2,m3),m5);
//每一个都要判断,因为有可能相等,而那个索引下次不能用了,否则会一直停在那儿,比如:2*3=6,3×2=6
if(m2==uglyNumbers[size]) {
t2++;
}
if(m3==uglyNumbers[size]){
t3++;
}
if(m5==uglyNumbers[size]){
t5++;
}
size++;
}
return uglyNumbers[index-1];
}
}
| false | 547 | 4 | 615 | 5 | 592 | 4 | 615 | 5 | 808 | 7 | false | false | false | false | false | true |
33585_5 | package moe.codeest.enviews;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PixelFormat;
import android.graphics.PorterDuffXfermode;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
/**
* Created by codeest on 2016/11/15.
*
* 我还在好奇里面装的究竟是啤酒还是橙汁 0v0
*/
public class ENLoadingView extends SurfaceView {
private static final int STATE_SHOW = 0;
private static final int STATE_HIDE = 1;
private static final int DEFAULT_RIPPLE_SPEED = 2;
private static final float DEFAULT_MOVE_SPEED = 0.01f;
private Paint mPaint[], mBeerPaint[], mBubblePaint[];
private Path mPath, mBgPath;
private Thread mThread;
private boolean isItemReady[];
private float mCurrentRippleX[];
private float mFraction[];
private float mTemp = 0;
private int mCurrentState;
private float mWidth, mHeight;
private float mCenterX, mCenterY;
private SurfaceHolder surfaceHolder;
private float mBaseLength, mBgBaseLength;
public ENLoadingView(Context context) {
super(context);
init();
}
public ENLoadingView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
mPaint = new Paint[4];
mBeerPaint = new Paint[4];
mBubblePaint = new Paint[4];
mPath = new Path();
mBgPath = new Path();
isItemReady = new boolean[4];
mFraction = new float[4];
mCurrentRippleX = new float[4];
mCurrentState = STATE_HIDE;
for (int i = 0; i< 4 ; i++) {
mPaint[i] = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint[i].setStyle(Paint.Style.STROKE);
mPaint[i].setStrokeCap(Paint.Cap.ROUND);
mPaint[i].setStrokeJoin(Paint.Join.ROUND);
mPaint[i].setColor(Color.parseColor("#f0cc36"));
mPaint[i].setStrokeWidth(9);
mBeerPaint[i] = new Paint(Paint.ANTI_ALIAS_FLAG);
mBeerPaint[i].setStyle(Paint.Style.FILL);
mBeerPaint[i].setColor(Color.parseColor("#fbce0f"));
mBubblePaint[i] = new Paint(Paint.ANTI_ALIAS_FLAG);
mBubblePaint[i].setStyle(Paint.Style.FILL);
mBubblePaint[i].setColor(Color.parseColor("#f5fba1"));
}
surfaceHolder = getHolder();
setZOrderOnTop(true);
surfaceHolder.setFormat(PixelFormat.TRANSLUCENT);
surfaceHolder.addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
}
@Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
}
@Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
if (mThread != null) {
mThread.interrupt();
mThread = null;
}
}
});
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mWidth = w;
mHeight = h;
mCenterX = w / 2;
mCenterY = h / 2;
mBaseLength = w / 10;
mBgBaseLength = w / 8;
for (int i = 0; i < 4 ;i++) {
mCurrentRippleX[i] = - 2 * mBgBaseLength;
}
mPath.reset();
mPath.moveTo(0, mCenterY + 2 * mBaseLength);
mPath.lineTo(0, mCenterY);
mPath.lineTo(mBaseLength / 4, mCenterY - mBaseLength);
mPath.lineTo(mBaseLength / 4, mCenterY - 1.5f * mBaseLength);
mPath.lineTo(mBaseLength * 3 / 4, mCenterY - 1.5f * mBaseLength);
mPath.lineTo(mBaseLength * 3 / 4, mCenterY - mBaseLength);
mPath.lineTo(mBaseLength, mCenterY);
mPath.lineTo(mBaseLength, mCenterY + 2 * mBaseLength);
mPath.close();
}
private Runnable animRunnable = new Runnable() {
@Override
public void run() {
try {
while (mCurrentState == STATE_SHOW) {
Thread.sleep(5);
flush();
draw();
}
if (mCurrentState == STATE_HIDE) {
clearCanvas();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
private void flush() {
if (mTemp >= 1)
mTemp = 0;
mTemp += DEFAULT_MOVE_SPEED;
for (int i = 0;i < 4 ; i++) {
float temp = mTemp - i * 0.25f;
if (temp < 0)
temp += 1;
mFraction[i] = temp;
if (mFraction[0] > i * 0.25f && !isItemReady[i]) {
isItemReady[i] = true;
}
}
}
private void draw() {
Canvas canvas = surfaceHolder.lockCanvas();
if(canvas == null)
return;
mPaint[0].setXfermode(new PorterDuffXfermode(android.graphics.PorterDuff.Mode.CLEAR)); //使用这只画笔清屏,清屏后恢复画笔
canvas.drawPaint(mPaint[0]);
mPaint[0].setXfermode(new PorterDuffXfermode(android.graphics.PorterDuff.Mode.DST_OVER));
for (int i = 0; i < 4 ; i++) {
drawItem(canvas, mFraction[i], i);
}
surfaceHolder.unlockCanvasAndPost(canvas);
}
private void drawItem(Canvas canvas, float mFraction, int index) {
if (!isItemReady[index]) {
return;
}
canvas.save();
canvas.translate(mFraction * mWidth ,0);
float mCurrentY;
if (mFraction < 0.1) { //嗷~ 从这开始画封口器以及确定波浪线高度
mBeerPaint[index].setAlpha((int) (255 * 10 * mFraction));
mPaint[index].setAlpha((int) (255 * 10 * mFraction));
mBubblePaint[index].setAlpha((int) (255 * 10 * mFraction));
mCurrentY = mCenterY + 2.2f * mBaseLength;
canvas.drawLine(0.1f * mBaseLength ,mCenterY - 2.5f * mBaseLength, 0.9f * mBaseLength, mCenterY - 2.5f * mBaseLength, mPaint[index]);
} else if(mFraction > 0.7) {
mBeerPaint[index].setAlpha((int) (255 / 0.3f * (1 - mFraction)));
mPaint[index].setAlpha((int) (255 / 0.3f * (1 - mFraction)));
mBubblePaint[index].setAlpha((int) (255 / 0.3f * (1 - mFraction)));
mCurrentY = mCenterY - mBaseLength;
if (mFraction <= 0.75) {
canvas.drawLine(mBaseLength * 0.5f, mCenterY - 2.5f * mBaseLength,
mBaseLength * 0.5f, mCenterY - 2.5f * mBaseLength + mBaseLength / 0.05f * (mFraction - 0.7f), mPaint[index]);
canvas.drawLine(0.1f * mBaseLength ,mCenterY - 2.5f * mBaseLength + mBaseLength / 0.05f * (mFraction - 0.7f),
0.9f * mBaseLength, mCenterY - 2.5f * mBaseLength + mBaseLength / 0.05f * (mFraction - 0.7f), mPaint[index]);
} else {
if (mFraction < 0.8) {
canvas.drawLine(mBaseLength * 0.5f, mCenterY - 2.5f * mBaseLength,
mBaseLength * 0.5f, mCenterY - 1.5f * mBaseLength - mBaseLength / 0.05f * (mFraction - 0.75f), mPaint[index]);
}
canvas.drawLine(mBaseLength / 4 - 6, mCenterY - 1.5f * mBaseLength - 6,
mBaseLength * 3 / 4 + 6, mCenterY - 1.5f * mBaseLength - 6, mPaint[index]);
}
} else {
mCurrentY = mCenterY + 2.2f * mBaseLength - 3.2f * mBaseLength / 0.6f * (mFraction - 0.1f);
canvas.drawLine(0.1f * mBaseLength ,mCenterY - 2.5f * mBaseLength, 0.9f * mBaseLength, mCenterY - 2.5f * mBaseLength, mPaint[index]);
}
canvas.drawPath(mPath, mPaint[index]); //嗷~ 在这画酒瓶
mCurrentRippleX[index] += DEFAULT_RIPPLE_SPEED;
if (mCurrentRippleX[index] >= 0) {
mCurrentRippleX[index] = - 2 * mBgBaseLength;
}
mBgPath.reset();
mBgPath.moveTo(mCurrentRippleX[index], mCurrentY);
for (int i = 0; i< 9 ; i++) {
mBgPath.rQuadTo(mBgBaseLength / 2, mBgBaseLength / 8, mBgBaseLength, 0);
mBgPath.rQuadTo(mBgBaseLength / 2, - mBgBaseLength / 8, mBgBaseLength, 0);
}
mBgPath.lineTo(mWidth, mHeight);
mBgPath.lineTo(0, mHeight);
mBgPath.close();
canvas.clipPath(mPath);
canvas.save();
canvas.translate(- mBaseLength / 12, - mBaseLength / 10 - mBaseLength / 4 * (1 - mFraction));
canvas.drawPath(mBgPath, mBubblePaint[index]); //嗷~ 在这画啤酒沫
canvas.restore();
canvas.drawPath(mBgPath, mBeerPaint[index]); //嗷~ 在这画啤酒
canvas.restore();
}
public void show() {
if (mCurrentState == STATE_SHOW) {
return;
}
mCurrentState = STATE_SHOW;
mThread = new Thread(animRunnable);
mThread.start();
}
public void hide() {
if (mCurrentState == STATE_HIDE) {
return;
}
mCurrentState = STATE_HIDE;
resetData();
}
private void clearCanvas() {
Canvas canvas = surfaceHolder.lockCanvas();
if(canvas == null)
return;
mPaint[0].setXfermode(new PorterDuffXfermode(android.graphics.PorterDuff.Mode.CLEAR));
canvas.drawPaint(mPaint[0]);
mPaint[0].setXfermode(new PorterDuffXfermode(android.graphics.PorterDuff.Mode.DST_OVER));
surfaceHolder.unlockCanvasAndPost(canvas);
mThread.interrupt();
mThread = null;
}
private void resetData() {
for (int i = 0; i<4 ; i++) {
isItemReady[i] = false;
mCurrentRippleX[i] = - 2 * mBgBaseLength;
}
mTemp = 0;
}
} | codeestX/ENViews | library/src/main/java/moe/codeest/enviews/ENLoadingView.java | 2,967 | //嗷~ 在这画啤酒 | line_comment | zh-cn | package moe.codeest.enviews;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PixelFormat;
import android.graphics.PorterDuffXfermode;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
/**
* Created by codeest on 2016/11/15.
*
* 我还在好奇里面装的究竟是啤酒还是橙汁 0v0
*/
public class ENLoadingView extends SurfaceView {
private static final int STATE_SHOW = 0;
private static final int STATE_HIDE = 1;
private static final int DEFAULT_RIPPLE_SPEED = 2;
private static final float DEFAULT_MOVE_SPEED = 0.01f;
private Paint mPaint[], mBeerPaint[], mBubblePaint[];
private Path mPath, mBgPath;
private Thread mThread;
private boolean isItemReady[];
private float mCurrentRippleX[];
private float mFraction[];
private float mTemp = 0;
private int mCurrentState;
private float mWidth, mHeight;
private float mCenterX, mCenterY;
private SurfaceHolder surfaceHolder;
private float mBaseLength, mBgBaseLength;
public ENLoadingView(Context context) {
super(context);
init();
}
public ENLoadingView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
mPaint = new Paint[4];
mBeerPaint = new Paint[4];
mBubblePaint = new Paint[4];
mPath = new Path();
mBgPath = new Path();
isItemReady = new boolean[4];
mFraction = new float[4];
mCurrentRippleX = new float[4];
mCurrentState = STATE_HIDE;
for (int i = 0; i< 4 ; i++) {
mPaint[i] = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint[i].setStyle(Paint.Style.STROKE);
mPaint[i].setStrokeCap(Paint.Cap.ROUND);
mPaint[i].setStrokeJoin(Paint.Join.ROUND);
mPaint[i].setColor(Color.parseColor("#f0cc36"));
mPaint[i].setStrokeWidth(9);
mBeerPaint[i] = new Paint(Paint.ANTI_ALIAS_FLAG);
mBeerPaint[i].setStyle(Paint.Style.FILL);
mBeerPaint[i].setColor(Color.parseColor("#fbce0f"));
mBubblePaint[i] = new Paint(Paint.ANTI_ALIAS_FLAG);
mBubblePaint[i].setStyle(Paint.Style.FILL);
mBubblePaint[i].setColor(Color.parseColor("#f5fba1"));
}
surfaceHolder = getHolder();
setZOrderOnTop(true);
surfaceHolder.setFormat(PixelFormat.TRANSLUCENT);
surfaceHolder.addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
}
@Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
}
@Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
if (mThread != null) {
mThread.interrupt();
mThread = null;
}
}
});
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mWidth = w;
mHeight = h;
mCenterX = w / 2;
mCenterY = h / 2;
mBaseLength = w / 10;
mBgBaseLength = w / 8;
for (int i = 0; i < 4 ;i++) {
mCurrentRippleX[i] = - 2 * mBgBaseLength;
}
mPath.reset();
mPath.moveTo(0, mCenterY + 2 * mBaseLength);
mPath.lineTo(0, mCenterY);
mPath.lineTo(mBaseLength / 4, mCenterY - mBaseLength);
mPath.lineTo(mBaseLength / 4, mCenterY - 1.5f * mBaseLength);
mPath.lineTo(mBaseLength * 3 / 4, mCenterY - 1.5f * mBaseLength);
mPath.lineTo(mBaseLength * 3 / 4, mCenterY - mBaseLength);
mPath.lineTo(mBaseLength, mCenterY);
mPath.lineTo(mBaseLength, mCenterY + 2 * mBaseLength);
mPath.close();
}
private Runnable animRunnable = new Runnable() {
@Override
public void run() {
try {
while (mCurrentState == STATE_SHOW) {
Thread.sleep(5);
flush();
draw();
}
if (mCurrentState == STATE_HIDE) {
clearCanvas();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
private void flush() {
if (mTemp >= 1)
mTemp = 0;
mTemp += DEFAULT_MOVE_SPEED;
for (int i = 0;i < 4 ; i++) {
float temp = mTemp - i * 0.25f;
if (temp < 0)
temp += 1;
mFraction[i] = temp;
if (mFraction[0] > i * 0.25f && !isItemReady[i]) {
isItemReady[i] = true;
}
}
}
private void draw() {
Canvas canvas = surfaceHolder.lockCanvas();
if(canvas == null)
return;
mPaint[0].setXfermode(new PorterDuffXfermode(android.graphics.PorterDuff.Mode.CLEAR)); //使用这只画笔清屏,清屏后恢复画笔
canvas.drawPaint(mPaint[0]);
mPaint[0].setXfermode(new PorterDuffXfermode(android.graphics.PorterDuff.Mode.DST_OVER));
for (int i = 0; i < 4 ; i++) {
drawItem(canvas, mFraction[i], i);
}
surfaceHolder.unlockCanvasAndPost(canvas);
}
private void drawItem(Canvas canvas, float mFraction, int index) {
if (!isItemReady[index]) {
return;
}
canvas.save();
canvas.translate(mFraction * mWidth ,0);
float mCurrentY;
if (mFraction < 0.1) { //嗷~ 从这开始画封口器以及确定波浪线高度
mBeerPaint[index].setAlpha((int) (255 * 10 * mFraction));
mPaint[index].setAlpha((int) (255 * 10 * mFraction));
mBubblePaint[index].setAlpha((int) (255 * 10 * mFraction));
mCurrentY = mCenterY + 2.2f * mBaseLength;
canvas.drawLine(0.1f * mBaseLength ,mCenterY - 2.5f * mBaseLength, 0.9f * mBaseLength, mCenterY - 2.5f * mBaseLength, mPaint[index]);
} else if(mFraction > 0.7) {
mBeerPaint[index].setAlpha((int) (255 / 0.3f * (1 - mFraction)));
mPaint[index].setAlpha((int) (255 / 0.3f * (1 - mFraction)));
mBubblePaint[index].setAlpha((int) (255 / 0.3f * (1 - mFraction)));
mCurrentY = mCenterY - mBaseLength;
if (mFraction <= 0.75) {
canvas.drawLine(mBaseLength * 0.5f, mCenterY - 2.5f * mBaseLength,
mBaseLength * 0.5f, mCenterY - 2.5f * mBaseLength + mBaseLength / 0.05f * (mFraction - 0.7f), mPaint[index]);
canvas.drawLine(0.1f * mBaseLength ,mCenterY - 2.5f * mBaseLength + mBaseLength / 0.05f * (mFraction - 0.7f),
0.9f * mBaseLength, mCenterY - 2.5f * mBaseLength + mBaseLength / 0.05f * (mFraction - 0.7f), mPaint[index]);
} else {
if (mFraction < 0.8) {
canvas.drawLine(mBaseLength * 0.5f, mCenterY - 2.5f * mBaseLength,
mBaseLength * 0.5f, mCenterY - 1.5f * mBaseLength - mBaseLength / 0.05f * (mFraction - 0.75f), mPaint[index]);
}
canvas.drawLine(mBaseLength / 4 - 6, mCenterY - 1.5f * mBaseLength - 6,
mBaseLength * 3 / 4 + 6, mCenterY - 1.5f * mBaseLength - 6, mPaint[index]);
}
} else {
mCurrentY = mCenterY + 2.2f * mBaseLength - 3.2f * mBaseLength / 0.6f * (mFraction - 0.1f);
canvas.drawLine(0.1f * mBaseLength ,mCenterY - 2.5f * mBaseLength, 0.9f * mBaseLength, mCenterY - 2.5f * mBaseLength, mPaint[index]);
}
canvas.drawPath(mPath, mPaint[index]); //嗷~ 在这画酒瓶
mCurrentRippleX[index] += DEFAULT_RIPPLE_SPEED;
if (mCurrentRippleX[index] >= 0) {
mCurrentRippleX[index] = - 2 * mBgBaseLength;
}
mBgPath.reset();
mBgPath.moveTo(mCurrentRippleX[index], mCurrentY);
for (int i = 0; i< 9 ; i++) {
mBgPath.rQuadTo(mBgBaseLength / 2, mBgBaseLength / 8, mBgBaseLength, 0);
mBgPath.rQuadTo(mBgBaseLength / 2, - mBgBaseLength / 8, mBgBaseLength, 0);
}
mBgPath.lineTo(mWidth, mHeight);
mBgPath.lineTo(0, mHeight);
mBgPath.close();
canvas.clipPath(mPath);
canvas.save();
canvas.translate(- mBaseLength / 12, - mBaseLength / 10 - mBaseLength / 4 * (1 - mFraction));
canvas.drawPath(mBgPath, mBubblePaint[index]); //嗷~ 在这画啤酒沫
canvas.restore();
canvas.drawPath(mBgPath, mBeerPaint[index]); //嗷~ <SUF>
canvas.restore();
}
public void show() {
if (mCurrentState == STATE_SHOW) {
return;
}
mCurrentState = STATE_SHOW;
mThread = new Thread(animRunnable);
mThread.start();
}
public void hide() {
if (mCurrentState == STATE_HIDE) {
return;
}
mCurrentState = STATE_HIDE;
resetData();
}
private void clearCanvas() {
Canvas canvas = surfaceHolder.lockCanvas();
if(canvas == null)
return;
mPaint[0].setXfermode(new PorterDuffXfermode(android.graphics.PorterDuff.Mode.CLEAR));
canvas.drawPaint(mPaint[0]);
mPaint[0].setXfermode(new PorterDuffXfermode(android.graphics.PorterDuff.Mode.DST_OVER));
surfaceHolder.unlockCanvasAndPost(canvas);
mThread.interrupt();
mThread = null;
}
private void resetData() {
for (int i = 0; i<4 ; i++) {
isItemReady[i] = false;
mCurrentRippleX[i] = - 2 * mBgBaseLength;
}
mTemp = 0;
}
} | false | 2,706 | 7 | 2,967 | 12 | 3,076 | 7 | 2,967 | 12 | 3,465 | 15 | false | false | false | false | false | true |
5977_2 | package com.codeest.geeknews.component;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import com.codeest.geeknews.app.App;
import com.codeest.geeknews.util.LogUtil;
import com.codeest.geeknews.util.ToastUtil;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
/**
* Created by codeest on 2016/8/3.
*/
public class CrashHandler implements Thread.UncaughtExceptionHandler {
private static Thread.UncaughtExceptionHandler defaultHandler = null;
private Context context = null;
private final String TAG = CrashHandler.class.getSimpleName();
public CrashHandler(Context context) {
this.context = context;
}
/**
* 初始化,设置该CrashHandler为程序的默认处理器
*/
public static void init(CrashHandler crashHandler) {
defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(crashHandler);
}
@Override
public void uncaughtException(Thread thread, Throwable ex) {
System.out.println(ex.toString());
LogUtil.e(TAG, ex.toString());
LogUtil.e(TAG, collectCrashDeviceInfo());
LogUtil.e(TAG, getCrashInfo(ex));
// 调用系统错误机制
defaultHandler.uncaughtException(thread, ex);
ToastUtil.shortShow("抱歉,程序发生异常即将退出");
App.getInstance().exitApp();
}
/**
* 得到程序崩溃的详细信息
*/
public String getCrashInfo(Throwable ex) {
Writer result = new StringWriter();
PrintWriter printWriter = new PrintWriter(result);
ex.setStackTrace(ex.getStackTrace());
ex.printStackTrace(printWriter);
return result.toString();
}
/**
* 收集程序崩溃的设备信息
*/
public String collectCrashDeviceInfo() {
try {
PackageManager pm = context.getPackageManager();
PackageInfo pi = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES);
String versionName = pi.versionName;
String model = android.os.Build.MODEL;
String androidVersion = android.os.Build.VERSION.RELEASE;
String manufacturer = android.os.Build.MANUFACTURER;
return versionName + " " + model + " " + androidVersion + " " + manufacturer;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return null;
}
}
| codeestX/GeekNews | app/src/main/java/com/codeest/geeknews/component/CrashHandler.java | 615 | // 调用系统错误机制
| line_comment | zh-cn | package com.codeest.geeknews.component;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import com.codeest.geeknews.app.App;
import com.codeest.geeknews.util.LogUtil;
import com.codeest.geeknews.util.ToastUtil;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
/**
* Created by codeest on 2016/8/3.
*/
public class CrashHandler implements Thread.UncaughtExceptionHandler {
private static Thread.UncaughtExceptionHandler defaultHandler = null;
private Context context = null;
private final String TAG = CrashHandler.class.getSimpleName();
public CrashHandler(Context context) {
this.context = context;
}
/**
* 初始化,设置该CrashHandler为程序的默认处理器
*/
public static void init(CrashHandler crashHandler) {
defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(crashHandler);
}
@Override
public void uncaughtException(Thread thread, Throwable ex) {
System.out.println(ex.toString());
LogUtil.e(TAG, ex.toString());
LogUtil.e(TAG, collectCrashDeviceInfo());
LogUtil.e(TAG, getCrashInfo(ex));
// 调用 <SUF>
defaultHandler.uncaughtException(thread, ex);
ToastUtil.shortShow("抱歉,程序发生异常即将退出");
App.getInstance().exitApp();
}
/**
* 得到程序崩溃的详细信息
*/
public String getCrashInfo(Throwable ex) {
Writer result = new StringWriter();
PrintWriter printWriter = new PrintWriter(result);
ex.setStackTrace(ex.getStackTrace());
ex.printStackTrace(printWriter);
return result.toString();
}
/**
* 收集程序崩溃的设备信息
*/
public String collectCrashDeviceInfo() {
try {
PackageManager pm = context.getPackageManager();
PackageInfo pi = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES);
String versionName = pi.versionName;
String model = android.os.Build.MODEL;
String androidVersion = android.os.Build.VERSION.RELEASE;
String manufacturer = android.os.Build.MANUFACTURER;
return versionName + " " + model + " " + androidVersion + " " + manufacturer;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return null;
}
}
| false | 508 | 9 | 607 | 7 | 622 | 6 | 607 | 7 | 749 | 13 | false | false | false | false | false | true |
65732_7 | package javaee.basic.httpservlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name="MyHttpServlet",urlPatterns={"/httpservlet/MyHttpServlet"})
public class MyHttpServlet extends HttpServlet {
//成员变量
int i = 0;
//用于测试Servlet单例,如何实现线程安全
int ticket = 3;
//在HttpServlet中,设计者对post提交和get提交分别处理
//回忆<form action="提交给?" mothod = "post|get"/>,默认是get
//其实doGet()/doPost()最终也去调用service方法
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//super.doGet(req, resp); //一定要注释掉这句
//局部变量
int j=0;
resp.setContentType("text/html charset=utf-8");
resp.setCharacterEncoding("utf-8");
resp.getWriter().println("i am httpServlet doGet() 中文:乱码测试");
resp.getWriter().println("i与j的区别"+ "i=" + i++ +"j=" + j++);
//线程安全简单的解决方法
synchronized (this) {
if(ticket>0){
resp.getWriter().println("你买到票");
//休眠
try{
Thread.sleep(10*1000);
}catch (InterruptedException e ){
e.printStackTrace();
}
ticket--;
resp.getWriter().println("现在还有票ticket =" + ticket +"张");
}else{
resp.getWriter().println("你没有买到票");
}
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//super.doPost(req, resp); //一定要注释掉这句
resp.getWriter().println("i am httpServlet doPost() post name = " + req.getParameter("username"));
//一般开发人员习惯把doGet()和doPost()二合为一
//this.doGet(req,resp);
}
}
| codehero-cn/javaee.basic | demo_servlet/src/main/java/httpservlet/MyHttpServlet.java | 568 | //线程安全简单的解决方法 | line_comment | zh-cn | package javaee.basic.httpservlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name="MyHttpServlet",urlPatterns={"/httpservlet/MyHttpServlet"})
public class MyHttpServlet extends HttpServlet {
//成员变量
int i = 0;
//用于测试Servlet单例,如何实现线程安全
int ticket = 3;
//在HttpServlet中,设计者对post提交和get提交分别处理
//回忆<form action="提交给?" mothod = "post|get"/>,默认是get
//其实doGet()/doPost()最终也去调用service方法
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//super.doGet(req, resp); //一定要注释掉这句
//局部变量
int j=0;
resp.setContentType("text/html charset=utf-8");
resp.setCharacterEncoding("utf-8");
resp.getWriter().println("i am httpServlet doGet() 中文:乱码测试");
resp.getWriter().println("i与j的区别"+ "i=" + i++ +"j=" + j++);
//线程 <SUF>
synchronized (this) {
if(ticket>0){
resp.getWriter().println("你买到票");
//休眠
try{
Thread.sleep(10*1000);
}catch (InterruptedException e ){
e.printStackTrace();
}
ticket--;
resp.getWriter().println("现在还有票ticket =" + ticket +"张");
}else{
resp.getWriter().println("你没有买到票");
}
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//super.doPost(req, resp); //一定要注释掉这句
resp.getWriter().println("i am httpServlet doPost() post name = " + req.getParameter("username"));
//一般开发人员习惯把doGet()和doPost()二合为一
//this.doGet(req,resp);
}
}
| false | 477 | 7 | 568 | 6 | 563 | 6 | 568 | 6 | 780 | 16 | false | false | false | false | false | true |
11948_1 | package com.xiaofu.wechat.handler.interceptor;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpMessageInterceptor;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
* @author xiaofu
* @date 2024/1/18 21:40
* @des
*/
/**
* 对微信公众号消息进行预处理、过滤等操作,根据具体业务需求决定是否允许继续执行后面的路由处理方法
* <p>
* 如果要中止消息的继续处理,即表示拦截了这个消息,需要返回 false。否则,在执行完当前拦截器操作后,允许消息的继续处理,返回 true
*/
@Component
public class TextInterceptor implements WxMpMessageInterceptor {
@Override
public boolean intercept(WxMpXmlMessage wxMpXmlMessage, Map<String, Object> map, WxMpService wxMpService, WxSessionManager wxSessionManager) {
String msg = wxMpXmlMessage.getContent();
String msgType = wxMpXmlMessage.getMsgType();
if (msgType.equals("text") && msg.contains("混蛋")) {
wxMpXmlMessage.setContent("***");
return true;
}
return true;
}
}
| codenotknock/study_circle | circle-wechat/src/main/java/com/xiaofu/wechat/handler/interceptor/TextInterceptor.java | 351 | /**
* 对微信公众号消息进行预处理、过滤等操作,根据具体业务需求决定是否允许继续执行后面的路由处理方法
* <p>
* 如果要中止消息的继续处理,即表示拦截了这个消息,需要返回 false。否则,在执行完当前拦截器操作后,允许消息的继续处理,返回 true
*/ | block_comment | zh-cn | package com.xiaofu.wechat.handler.interceptor;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpMessageInterceptor;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
* @author xiaofu
* @date 2024/1/18 21:40
* @des
*/
/**
* 对微信 <SUF>*/
@Component
public class TextInterceptor implements WxMpMessageInterceptor {
@Override
public boolean intercept(WxMpXmlMessage wxMpXmlMessage, Map<String, Object> map, WxMpService wxMpService, WxSessionManager wxSessionManager) {
String msg = wxMpXmlMessage.getContent();
String msgType = wxMpXmlMessage.getMsgType();
if (msgType.equals("text") && msg.contains("混蛋")) {
wxMpXmlMessage.setContent("***");
return true;
}
return true;
}
}
| false | 301 | 73 | 351 | 83 | 341 | 75 | 351 | 83 | 479 | 164 | false | false | false | false | false | true |
18084_2 | package zzq;
import java.util.*;
/**
* 实现Set敏感词汇转换为DFA树
*/
public class DFA {
private static final DFA dfa = new DFA();
private DFA(){
}
/**
* 初始化set
* @return
*/
public Set init(){
Set<String> set = new HashSet<String>();
set.add("晚上");
set.add("晚安");
set.add("你好啊");
return set;
}
public Map dfaMap(Set<String> txtSet){
Iterator<String> iterator= txtSet.iterator();
Map map = new HashMap();
Map nowMap=null;
Map temMap=null;
while (iterator.hasNext()) {
String key=iterator.next();
temMap=map;
for (int i = 0; i < key.length(); i++) {
char k=key.charAt(i);
Object workMap=map.get(k);
if(workMap==null){
nowMap=new HashMap<>();
nowMap.put("isEnd", "0");
temMap.put(k, nowMap);
temMap=nowMap;
}else{
temMap=(Map) workMap;
}
//最后一个字
if(i==key.length()-1){
nowMap.put("isEnd", "1");
}
}
}
return map;
}
public String test(){
return dfa.dfaMap(dfa.init()).toString();
}
public static DFA getDFA(){
return dfa;
}
public static void main(String[] args) {
System.out.println(DFA.dfa.test());
}
}
| coder-enthusiast/sensitiveWordFiltering | src/main/java/zzq/DFA.java | 395 | //最后一个字 | line_comment | zh-cn | package zzq;
import java.util.*;
/**
* 实现Set敏感词汇转换为DFA树
*/
public class DFA {
private static final DFA dfa = new DFA();
private DFA(){
}
/**
* 初始化set
* @return
*/
public Set init(){
Set<String> set = new HashSet<String>();
set.add("晚上");
set.add("晚安");
set.add("你好啊");
return set;
}
public Map dfaMap(Set<String> txtSet){
Iterator<String> iterator= txtSet.iterator();
Map map = new HashMap();
Map nowMap=null;
Map temMap=null;
while (iterator.hasNext()) {
String key=iterator.next();
temMap=map;
for (int i = 0; i < key.length(); i++) {
char k=key.charAt(i);
Object workMap=map.get(k);
if(workMap==null){
nowMap=new HashMap<>();
nowMap.put("isEnd", "0");
temMap.put(k, nowMap);
temMap=nowMap;
}else{
temMap=(Map) workMap;
}
//最后 <SUF>
if(i==key.length()-1){
nowMap.put("isEnd", "1");
}
}
}
return map;
}
public String test(){
return dfa.dfaMap(dfa.init()).toString();
}
public static DFA getDFA(){
return dfa;
}
public static void main(String[] args) {
System.out.println(DFA.dfa.test());
}
}
| false | 342 | 3 | 395 | 4 | 421 | 3 | 395 | 4 | 483 | 6 | false | false | false | false | false | true |
29826_11 | package com.hql.lightning.util;
import java.nio.charset.CodingErrorAction;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.*;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import javax.net.ssl.SSLContext;
/**
* http请求类
*/
public class HttpUtil {
private static Logger logger = Logger.getLogger(HttpUtil.class);
/**
* http客户端
*/
private CloseableHttpClient httpClient;
/**
* 连接池管理器
*/
private PoolingHttpClientConnectionManager connManager;
/**
* 连接池连接数量上限
*/
private int cmMaxTotal = 200;
/**
* 每个路由的最大连接数
*/
private int cmMaxPerRoute = 20;
/**
* 设置连接池最大连接数
*
* @param val
*/
public void setCmMaxTotal(int val) {
this.cmMaxTotal = val;
}
/**
* 设置连接池每个路由的最大连接数
*
* @param val
*/
public void setCmMaxPerRoute(int val) {
this.cmMaxPerRoute = val;
}
private String CHARSET = "UTF-8";
private static HttpUtil instance = new HttpUtil();
public static HttpUtil getInstance() {
return instance;
}
/**
* 创建http客户端
*
* @throws Exception
*/
private void generateHttpClient() throws Exception {
/*KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
SSLContext sslContext = SSLContexts.custom().useTLS().
loadTrustMaterial(trustStore, new AnyTrustStrategy()).build();
LayeredConnectionSocketFactory sslSF = new
SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", sslSF)
.build();
connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
httpClient = HttpClients.custom().setConnectionManager(connManager).build();
SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).build();
connManager.setDefaultSocketConfig(socketConfig);
MessageConstraints messageConstraints = MessageConstraints.custom()
.setMaxHeaderCount(200)
.setMaxLineLength(2000)
.build();
ConnectionConfig connectionConfig = ConnectionConfig.custom()
.setMalformedInputAction(CodingErrorAction.IGNORE)
.setUnmappableInputAction(CodingErrorAction.IGNORE)
.setCharset(Consts.UTF_8)
.setMessageConstraints(messageConstraints)
.build();
connManager.setDefaultConnectionConfig(connectionConfig);
connManager.setMaxTotal(cmMaxTotal);
connManager.setDefaultMaxPerRoute(cmMaxPerRoute);*/
RequestConfig config = RequestConfig.custom().setConnectTimeout(2000).setSocketTimeout(2000).build();
httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
}
/**
* HTTP Get 获取内容
* @param url 请求的url地址 ?之前的地址
* @param params 请求的参数
* @return 页面内容
*/
public String doGet(String url,Map<String,String> params) throws Exception{
if(StringUtils.isBlank(url)){
return null;
}
if (httpClient == null) generateHttpClient();
CloseableHttpResponse response = null;
HttpEntity entity = null;
HttpGet httpGet = null;
try {
if(params != null && !params.isEmpty()){
List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
for(Map.Entry<String,String> entry : params.entrySet()){
String value = entry.getValue();
if(value != null){
pairs.add(new BasicNameValuePair(entry.getKey(),value));
}
}
url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, CHARSET));
}
httpGet = new HttpGet(url);
response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
httpGet.abort();
throw new RuntimeException("HttpClient,error status code :" + statusCode);
}
entity = response.getEntity();
String result = null;
if (entity != null){
result = EntityUtils.toString(entity, CHARSET);
}
return result;
} catch (Exception e) {
logger.error(e);
} finally {
if(entity != null) EntityUtils.consume(entity);
if (response != null) response.close();
httpGet.releaseConnection();
}
return null;
}
/**
* HTTP Post 获取内容
* @param url 请求的url地址 ?之前的地址
* @param params 请求的参数
* @return 页面内容
*/
public String doPost(String url,Map<String,String> params) throws Exception {
if(StringUtils.isBlank(url)){
return null;
}
if (httpClient == null) generateHttpClient();
CloseableHttpResponse response = null;
HttpEntity entity = null;
HttpPost httpPost = null;
try {
List<NameValuePair> pairs = null;
if(params != null && !params.isEmpty()){
pairs = new ArrayList<NameValuePair>(params.size());
for(Map.Entry<String,String> entry : params.entrySet()){
String value = entry.getValue();
if(value != null){
pairs.add(new BasicNameValuePair(entry.getKey(),value));
}
}
}
httpPost = new HttpPost(url);
if(pairs != null && pairs.size() > 0){
httpPost.setEntity(new UrlEncodedFormEntity(pairs, CHARSET));
}
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
httpPost.abort();
throw new RuntimeException("HttpClient,error status code :" + statusCode);
}
entity = response.getEntity();
String result = null;
if (entity != null){
result = EntityUtils.toString(entity, CHARSET);
}
EntityUtils.consume(entity);
return result;
} catch (Exception e) {
logger.error(e);
} finally {
if(entity != null) EntityUtils.consume(entity);
if (response != null) response.close();
httpPost.releaseConnection();
}
return null;
}
/**
* 密钥信任策略(信任所有)
*/
class AnyTrustStrategy implements TrustStrategy {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}
}
| coder-leehui/lightning4j | src/main/java/com/hql/lightning/util/HttpUtil.java | 1,882 | /**
* 密钥信任策略(信任所有)
*/ | block_comment | zh-cn | package com.hql.lightning.util;
import java.nio.charset.CodingErrorAction;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.*;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import javax.net.ssl.SSLContext;
/**
* http请求类
*/
public class HttpUtil {
private static Logger logger = Logger.getLogger(HttpUtil.class);
/**
* http客户端
*/
private CloseableHttpClient httpClient;
/**
* 连接池管理器
*/
private PoolingHttpClientConnectionManager connManager;
/**
* 连接池连接数量上限
*/
private int cmMaxTotal = 200;
/**
* 每个路由的最大连接数
*/
private int cmMaxPerRoute = 20;
/**
* 设置连接池最大连接数
*
* @param val
*/
public void setCmMaxTotal(int val) {
this.cmMaxTotal = val;
}
/**
* 设置连接池每个路由的最大连接数
*
* @param val
*/
public void setCmMaxPerRoute(int val) {
this.cmMaxPerRoute = val;
}
private String CHARSET = "UTF-8";
private static HttpUtil instance = new HttpUtil();
public static HttpUtil getInstance() {
return instance;
}
/**
* 创建http客户端
*
* @throws Exception
*/
private void generateHttpClient() throws Exception {
/*KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
SSLContext sslContext = SSLContexts.custom().useTLS().
loadTrustMaterial(trustStore, new AnyTrustStrategy()).build();
LayeredConnectionSocketFactory sslSF = new
SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", sslSF)
.build();
connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
httpClient = HttpClients.custom().setConnectionManager(connManager).build();
SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).build();
connManager.setDefaultSocketConfig(socketConfig);
MessageConstraints messageConstraints = MessageConstraints.custom()
.setMaxHeaderCount(200)
.setMaxLineLength(2000)
.build();
ConnectionConfig connectionConfig = ConnectionConfig.custom()
.setMalformedInputAction(CodingErrorAction.IGNORE)
.setUnmappableInputAction(CodingErrorAction.IGNORE)
.setCharset(Consts.UTF_8)
.setMessageConstraints(messageConstraints)
.build();
connManager.setDefaultConnectionConfig(connectionConfig);
connManager.setMaxTotal(cmMaxTotal);
connManager.setDefaultMaxPerRoute(cmMaxPerRoute);*/
RequestConfig config = RequestConfig.custom().setConnectTimeout(2000).setSocketTimeout(2000).build();
httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
}
/**
* HTTP Get 获取内容
* @param url 请求的url地址 ?之前的地址
* @param params 请求的参数
* @return 页面内容
*/
public String doGet(String url,Map<String,String> params) throws Exception{
if(StringUtils.isBlank(url)){
return null;
}
if (httpClient == null) generateHttpClient();
CloseableHttpResponse response = null;
HttpEntity entity = null;
HttpGet httpGet = null;
try {
if(params != null && !params.isEmpty()){
List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
for(Map.Entry<String,String> entry : params.entrySet()){
String value = entry.getValue();
if(value != null){
pairs.add(new BasicNameValuePair(entry.getKey(),value));
}
}
url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, CHARSET));
}
httpGet = new HttpGet(url);
response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
httpGet.abort();
throw new RuntimeException("HttpClient,error status code :" + statusCode);
}
entity = response.getEntity();
String result = null;
if (entity != null){
result = EntityUtils.toString(entity, CHARSET);
}
return result;
} catch (Exception e) {
logger.error(e);
} finally {
if(entity != null) EntityUtils.consume(entity);
if (response != null) response.close();
httpGet.releaseConnection();
}
return null;
}
/**
* HTTP Post 获取内容
* @param url 请求的url地址 ?之前的地址
* @param params 请求的参数
* @return 页面内容
*/
public String doPost(String url,Map<String,String> params) throws Exception {
if(StringUtils.isBlank(url)){
return null;
}
if (httpClient == null) generateHttpClient();
CloseableHttpResponse response = null;
HttpEntity entity = null;
HttpPost httpPost = null;
try {
List<NameValuePair> pairs = null;
if(params != null && !params.isEmpty()){
pairs = new ArrayList<NameValuePair>(params.size());
for(Map.Entry<String,String> entry : params.entrySet()){
String value = entry.getValue();
if(value != null){
pairs.add(new BasicNameValuePair(entry.getKey(),value));
}
}
}
httpPost = new HttpPost(url);
if(pairs != null && pairs.size() > 0){
httpPost.setEntity(new UrlEncodedFormEntity(pairs, CHARSET));
}
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
httpPost.abort();
throw new RuntimeException("HttpClient,error status code :" + statusCode);
}
entity = response.getEntity();
String result = null;
if (entity != null){
result = EntityUtils.toString(entity, CHARSET);
}
EntityUtils.consume(entity);
return result;
} catch (Exception e) {
logger.error(e);
} finally {
if(entity != null) EntityUtils.consume(entity);
if (response != null) response.close();
httpPost.releaseConnection();
}
return null;
}
/**
* 密钥信 <SUF>*/
class AnyTrustStrategy implements TrustStrategy {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}
}
| false | 1,645 | 14 | 1,882 | 16 | 2,046 | 15 | 1,882 | 16 | 2,323 | 26 | false | false | false | false | false | true |
63989_4 | package com.coderpig.drysisters.ui.fragment;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPropertyAnimatorListener;
import android.support.v4.view.animation.FastOutSlowInInterpolator;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Interpolator;
import com.coderpig.drysisters.R;
import com.coderpig.drysisters.data.dto.GankMeizi;
import com.coderpig.drysisters.net.APIService;
import com.coderpig.drysisters.ui.adapter.GankMZAdapter;
import com.coderpig.drysisters.utils.ResUtils;
import com.coderpig.drysisters.utils.RxSchedulers;
import com.coderpig.drysisters.utils.ToastUtils;
import java.util.ArrayList;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
/**
* 描述:Gank.io妹子Fragment
*
* @author CoderPig on 2018/02/14 09:49.
*/
public class GankMZFragment extends Fragment {
private static final String TAG = "GankMZFragment";
private SwipeRefreshLayout srl_refresh;
private FloatingActionButton fab_top;
private RecyclerView rec_mz;
private CompositeDisposable mSubscriptions;
private GankMZAdapter mAdapter;
private static final int PRELOAD_SIZE = 6;
private int mCurPage = 1;
private ArrayList<GankMeizi> mData;
private final Interpolator INTERPOLATOR = new FastOutSlowInInterpolator();
public static GankMZFragment newInstance() {
return new GankMZFragment();
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_mz_content, container, false);
srl_refresh = view.findViewById(R.id.srl_refresh);
rec_mz = view.findViewById(R.id.rec_mz);
fab_top = view.findViewById(R.id.fab_top);
srl_refresh.setOnRefreshListener(() -> {
mCurPage = 1;
fetchGankMZ(true);
});
final GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), 2);
rec_mz.setLayoutManager(layoutManager);
rec_mz.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
if (newState == RecyclerView.SCROLL_STATE_IDLE) {//加载更多
if (layoutManager.getItemCount() - recyclerView.getChildCount() <= layoutManager.findFirstVisibleItemPosition()) {
++mCurPage;
fetchGankMZ(false);
}
}
if (layoutManager.findFirstVisibleItemPosition() != 0) {
fabInAnim();
} else {
fabOutAnim();
}
}
});
fab_top.setOnClickListener(v -> {
LinearLayoutManager manager = (LinearLayoutManager) rec_mz.getLayoutManager();
//如果超过50项直接跳到开头,不然要滚好久
if(manager.findFirstVisibleItemPosition() < 50) {
rec_mz.smoothScrollToPosition(0);
} else {
rec_mz.scrollToPosition(0);
fabOutAnim();
}
});
return view;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mSubscriptions = new CompositeDisposable();
mData = new ArrayList<>();
mAdapter = new GankMZAdapter(getActivity(), mData);
rec_mz.setAdapter(mAdapter);
srl_refresh.setRefreshing(true);
fetchGankMZ(true);
}
@Override
public void onDestroy() {
super.onDestroy();
mSubscriptions.clear();
}
/* 拉取妹子数据 */
private void fetchGankMZ(boolean isRefresh) {
Disposable subscribe = APIService.getInstance().apis.fetchGankMZ(20, mCurPage)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe(subscription -> srl_refresh.setRefreshing(true))
.doFinally(() -> srl_refresh.setRefreshing(false))
.subscribe(data -> {
if(data != null && data.getResults() != null && data.getResults().size() > 0) {
ArrayList<GankMeizi> results = data.getResults();
if (isRefresh) {
mAdapter.addAll(results);
ToastUtils.shortToast(ResUtils.getString(R.string.refresh_success));
} else {
mAdapter.loadMore(results);
String msg = String.format(ResUtils.getString(R.string.load_more_num),results.size(),"妹子");
ToastUtils.shortToast(msg);
}
}
}, RxSchedulers::processRequestException);
mSubscriptions.add(subscribe);
}
/* 悬浮按钮显示动画 */
private void fabInAnim() {
if (fab_top.getVisibility() == View.GONE) {
fab_top.setVisibility(View.VISIBLE);
ViewCompat.animate(fab_top).scaleX(1.0F).scaleY(1.0F).alpha(1.0F)
.setInterpolator(INTERPOLATOR).withLayer().setListener(null).start();
}
}
/* 悬浮图标隐藏动画 */
private void fabOutAnim() {
if (fab_top.getVisibility() == View.VISIBLE) {
ViewCompat.animate(fab_top).scaleX(0.0F).scaleY(0.0F).alpha(0.0F)
.setInterpolator(INTERPOLATOR).withLayer().setListener(new ViewPropertyAnimatorListener() {
@Override
public void onAnimationStart(View view) {
}
@Override
public void onAnimationEnd(View view) {
fab_top.setVisibility(View.GONE);
}
@Override
public void onAnimationCancel(View view) {
}
}).start();
}
}
}
| coder-pig/DrySister | app/src/main/java/com/coderpig/drysisters/ui/fragment/GankMZFragment.java | 1,639 | /* 悬浮按钮显示动画 */ | block_comment | zh-cn | package com.coderpig.drysisters.ui.fragment;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPropertyAnimatorListener;
import android.support.v4.view.animation.FastOutSlowInInterpolator;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Interpolator;
import com.coderpig.drysisters.R;
import com.coderpig.drysisters.data.dto.GankMeizi;
import com.coderpig.drysisters.net.APIService;
import com.coderpig.drysisters.ui.adapter.GankMZAdapter;
import com.coderpig.drysisters.utils.ResUtils;
import com.coderpig.drysisters.utils.RxSchedulers;
import com.coderpig.drysisters.utils.ToastUtils;
import java.util.ArrayList;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
/**
* 描述:Gank.io妹子Fragment
*
* @author CoderPig on 2018/02/14 09:49.
*/
public class GankMZFragment extends Fragment {
private static final String TAG = "GankMZFragment";
private SwipeRefreshLayout srl_refresh;
private FloatingActionButton fab_top;
private RecyclerView rec_mz;
private CompositeDisposable mSubscriptions;
private GankMZAdapter mAdapter;
private static final int PRELOAD_SIZE = 6;
private int mCurPage = 1;
private ArrayList<GankMeizi> mData;
private final Interpolator INTERPOLATOR = new FastOutSlowInInterpolator();
public static GankMZFragment newInstance() {
return new GankMZFragment();
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_mz_content, container, false);
srl_refresh = view.findViewById(R.id.srl_refresh);
rec_mz = view.findViewById(R.id.rec_mz);
fab_top = view.findViewById(R.id.fab_top);
srl_refresh.setOnRefreshListener(() -> {
mCurPage = 1;
fetchGankMZ(true);
});
final GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), 2);
rec_mz.setLayoutManager(layoutManager);
rec_mz.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
if (newState == RecyclerView.SCROLL_STATE_IDLE) {//加载更多
if (layoutManager.getItemCount() - recyclerView.getChildCount() <= layoutManager.findFirstVisibleItemPosition()) {
++mCurPage;
fetchGankMZ(false);
}
}
if (layoutManager.findFirstVisibleItemPosition() != 0) {
fabInAnim();
} else {
fabOutAnim();
}
}
});
fab_top.setOnClickListener(v -> {
LinearLayoutManager manager = (LinearLayoutManager) rec_mz.getLayoutManager();
//如果超过50项直接跳到开头,不然要滚好久
if(manager.findFirstVisibleItemPosition() < 50) {
rec_mz.smoothScrollToPosition(0);
} else {
rec_mz.scrollToPosition(0);
fabOutAnim();
}
});
return view;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mSubscriptions = new CompositeDisposable();
mData = new ArrayList<>();
mAdapter = new GankMZAdapter(getActivity(), mData);
rec_mz.setAdapter(mAdapter);
srl_refresh.setRefreshing(true);
fetchGankMZ(true);
}
@Override
public void onDestroy() {
super.onDestroy();
mSubscriptions.clear();
}
/* 拉取妹子数据 */
private void fetchGankMZ(boolean isRefresh) {
Disposable subscribe = APIService.getInstance().apis.fetchGankMZ(20, mCurPage)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe(subscription -> srl_refresh.setRefreshing(true))
.doFinally(() -> srl_refresh.setRefreshing(false))
.subscribe(data -> {
if(data != null && data.getResults() != null && data.getResults().size() > 0) {
ArrayList<GankMeizi> results = data.getResults();
if (isRefresh) {
mAdapter.addAll(results);
ToastUtils.shortToast(ResUtils.getString(R.string.refresh_success));
} else {
mAdapter.loadMore(results);
String msg = String.format(ResUtils.getString(R.string.load_more_num),results.size(),"妹子");
ToastUtils.shortToast(msg);
}
}
}, RxSchedulers::processRequestException);
mSubscriptions.add(subscribe);
}
/* 悬浮按 <SUF>*/
private void fabInAnim() {
if (fab_top.getVisibility() == View.GONE) {
fab_top.setVisibility(View.VISIBLE);
ViewCompat.animate(fab_top).scaleX(1.0F).scaleY(1.0F).alpha(1.0F)
.setInterpolator(INTERPOLATOR).withLayer().setListener(null).start();
}
}
/* 悬浮图标隐藏动画 */
private void fabOutAnim() {
if (fab_top.getVisibility() == View.VISIBLE) {
ViewCompat.animate(fab_top).scaleX(0.0F).scaleY(0.0F).alpha(0.0F)
.setInterpolator(INTERPOLATOR).withLayer().setListener(new ViewPropertyAnimatorListener() {
@Override
public void onAnimationStart(View view) {
}
@Override
public void onAnimationEnd(View view) {
fab_top.setVisibility(View.GONE);
}
@Override
public void onAnimationCancel(View view) {
}
}).start();
}
}
}
| false | 1,347 | 8 | 1,639 | 9 | 1,680 | 8 | 1,639 | 9 | 2,027 | 17 | false | false | false | false | false | true |
30242_0 | import java.util.Random;
/**
* 398. 随机数索引:https://leetcode-cn.com/problems/random-pick-index/
*/
public class RandomPickIndex {
static class Solution {
int[] nums;
Random random = new Random();
public Solution(int[] nums) {
this.nums = nums;
}
public int pick(int target) {
int result = 0;
for (int i = 0, cnt = 0; i < nums.length; i++) {
if (nums[i] == target) {
cnt++;
if (random.nextInt(cnt) == 0) {
result = i;
}
}
}
return result;
}
}
public static void main(String[] args) {
Solution solution = new Solution(new int[] {1, 2, 3, 3, 3});
solution.pick(3); // 随机返回索引 2, 3 或者 4 之一。每个索引的返回概率应该相等。
solution.pick(1); // 返回 0 。因为只有 nums[0] 等于 1 。
}
}
| coder-qi/leetcode-algs | src/main/RandomPickIndex.java | 268 | /**
* 398. 随机数索引:https://leetcode-cn.com/problems/random-pick-index/
*/ | block_comment | zh-cn | import java.util.Random;
/**
* 398 <SUF>*/
public class RandomPickIndex {
static class Solution {
int[] nums;
Random random = new Random();
public Solution(int[] nums) {
this.nums = nums;
}
public int pick(int target) {
int result = 0;
for (int i = 0, cnt = 0; i < nums.length; i++) {
if (nums[i] == target) {
cnt++;
if (random.nextInt(cnt) == 0) {
result = i;
}
}
}
return result;
}
}
public static void main(String[] args) {
Solution solution = new Solution(new int[] {1, 2, 3, 3, 3});
solution.pick(3); // 随机返回索引 2, 3 或者 4 之一。每个索引的返回概率应该相等。
solution.pick(1); // 返回 0 。因为只有 nums[0] 等于 1 。
}
}
| false | 251 | 27 | 268 | 31 | 288 | 31 | 268 | 31 | 340 | 38 | false | false | false | false | false | true |
7920_3 | package com.learnjava.java8;
public class LambdaTest {
public static void main(String[] args) {
LambdaTest lambdaTest = new LambdaTest();
//类型声明
MathOperation addition = (int a, int b) -> a + b;
//不用类型声明
MathOperation subtraction = (a, b) -> a - b;
//大括号中的返回语句
MathOperation multiplication = (int a, int b) -> {return a * b;};
//没有大括号的返回语句
MathOperation division = (int a, int b) -> a / b;
int num = 1;
Converter<Integer, String> s = (param) -> System.out.println(String.valueOf(param + num));
s.convert(2);
System.out.println(addition.operation(1, 2));
}
interface MathOperation {
int operation(int a, int b);
}
interface GreetingService {
void sayMessage(String message);
}
interface Converter<T1, T2> {
void convert(int i);
}
private int operate(int a, int b, MathOperation mathOperation) {
return mathOperation.operation(a, b);
}
}
| coderbruis/JavaSourceCodeLearning | JdkLearn/src/main/java/com/learnjava/java8/LambdaTest.java | 279 | //没有大括号的返回语句 | line_comment | zh-cn | package com.learnjava.java8;
public class LambdaTest {
public static void main(String[] args) {
LambdaTest lambdaTest = new LambdaTest();
//类型声明
MathOperation addition = (int a, int b) -> a + b;
//不用类型声明
MathOperation subtraction = (a, b) -> a - b;
//大括号中的返回语句
MathOperation multiplication = (int a, int b) -> {return a * b;};
//没有 <SUF>
MathOperation division = (int a, int b) -> a / b;
int num = 1;
Converter<Integer, String> s = (param) -> System.out.println(String.valueOf(param + num));
s.convert(2);
System.out.println(addition.operation(1, 2));
}
interface MathOperation {
int operation(int a, int b);
}
interface GreetingService {
void sayMessage(String message);
}
interface Converter<T1, T2> {
void convert(int i);
}
private int operate(int a, int b, MathOperation mathOperation) {
return mathOperation.operation(a, b);
}
}
| false | 259 | 9 | 279 | 8 | 302 | 8 | 279 | 8 | 349 | 15 | false | false | false | false | false | true |
20621_10 | package z.media;
// 媒体处理
public interface IMedia {
// 播放器状态
public static final int Null = 0;
public static final int Idle = 1;
public static final int Init = 2;
public static final int Stop = Init; // init
public static final int Prepareing = 3;
public static final int Error = 4;
public static final int Prepared = 5;
public static final int Playing = 6;
public static final int Pause = 7;
public static final int Complete = 8;
public static final int BufferIn = 9; // 缓冲中暂停
public static final int BufferOut = Playing; // 缓冲中暂停恢复
public static final int Custom = 1000; // 自定义状态
// 播放器控制id
public static final int CtrlPlay = 1;
public static final int CtrlStop = 0;
public static final int CtrlPause = -1;
public static final int CtrlResume = -2;
public static final int CtrlReset = -3;
// 事件id
public static final int Evt_Change = 100; // 播放器状态变更
public static final int Evt_Prepared = 101; // 媒体准备播放
public static final int Evt_Complete = 102;
public static final int Evt_Progress = 103;
public static final int Evt_Error = 104;
public static final int Evt_Buffering = 105;
public static final int ErrStart = 1001; // 媒体开始播放出错
public static final int ErrPlaying = 1002; // 媒体播放过程出错
public int MaxRate = 1000000; // 防止浮点数问题
public static class Rate {
// 0.0f-1.0f 到百万分比
public static int toRate(float rate) {
return rate >= 1 ? MaxRate : (int)(rate * MaxRate);
}
// 从进度到百万分比
public static int toRate(long cur, long total) {
return cur < total ? (int)(cur * MaxRate / total) : MaxRate;
}
// 从百万分比到进度
public static int toProgress(long curRate, int total) {
return curRate < MaxRate ? (int)(curRate * total / MaxRate) : total;
}
}
// 监听媒体播放
public static interface ILis {
// 监听播放状态 播放/暂停/停止/错误等
public boolean onPlayStateChange(String id,int state);
// 监听进度+缓冲进度
public boolean onProgress(String id,int cur,int buffer,int total);
}
}
| coderoom1401/CodeRoom | AFast/src/z/media/IMedia.java | 710 | // 媒体开始播放出错 | line_comment | zh-cn | package z.media;
// 媒体处理
public interface IMedia {
// 播放器状态
public static final int Null = 0;
public static final int Idle = 1;
public static final int Init = 2;
public static final int Stop = Init; // init
public static final int Prepareing = 3;
public static final int Error = 4;
public static final int Prepared = 5;
public static final int Playing = 6;
public static final int Pause = 7;
public static final int Complete = 8;
public static final int BufferIn = 9; // 缓冲中暂停
public static final int BufferOut = Playing; // 缓冲中暂停恢复
public static final int Custom = 1000; // 自定义状态
// 播放器控制id
public static final int CtrlPlay = 1;
public static final int CtrlStop = 0;
public static final int CtrlPause = -1;
public static final int CtrlResume = -2;
public static final int CtrlReset = -3;
// 事件id
public static final int Evt_Change = 100; // 播放器状态变更
public static final int Evt_Prepared = 101; // 媒体准备播放
public static final int Evt_Complete = 102;
public static final int Evt_Progress = 103;
public static final int Evt_Error = 104;
public static final int Evt_Buffering = 105;
public static final int ErrStart = 1001; // 媒体 <SUF>
public static final int ErrPlaying = 1002; // 媒体播放过程出错
public int MaxRate = 1000000; // 防止浮点数问题
public static class Rate {
// 0.0f-1.0f 到百万分比
public static int toRate(float rate) {
return rate >= 1 ? MaxRate : (int)(rate * MaxRate);
}
// 从进度到百万分比
public static int toRate(long cur, long total) {
return cur < total ? (int)(cur * MaxRate / total) : MaxRate;
}
// 从百万分比到进度
public static int toProgress(long curRate, int total) {
return curRate < MaxRate ? (int)(curRate * total / MaxRate) : total;
}
}
// 监听媒体播放
public static interface ILis {
// 监听播放状态 播放/暂停/停止/错误等
public boolean onPlayStateChange(String id,int state);
// 监听进度+缓冲进度
public boolean onProgress(String id,int cur,int buffer,int total);
}
}
| false | 634 | 9 | 710 | 8 | 669 | 6 | 710 | 8 | 850 | 14 | false | false | false | false | false | true |
39966_4 | package com.coderpage.mine.app.tally.data;
import com.coderpage.mine.R;
import java.util.Arrays;
import java.util.List;
/**
* @author abner-l. 2017-03-23
*/
public class CategoryIconHelper {
public static final String IC_NAME_SETTING = "com.coderpage.mine.ic.category_setting";
/** 其他 */
public static final String IC_NAME_OTHER = "Other";
/** 餐饮 */
public static final String IC_NAME_CAN_YIN = "CanYin";
/** 交通 */
public static final String IC_NAME_JIAO_TONG = "JiaoTong";
/** 住房 */
public static final String IC_NAME_GOU_WU = "GouWu";
/** 服饰 */
public static final String IC_NAME_FU_SHI = "FuShi";
/** 日用品 */
public static final String IC_NAME_RI_YONG_PIN = "RiYongPin";
/** 娱乐 */
public static final String IC_NAME_YU_LE = "YuLe";
/** 食材 */
public static final String IC_NAME_SHI_CAI = "ShiCai";
/** 零食 */
public static final String IC_NAME_LING_SHI = "LingShi";
/** 烟酒茶 */
public static final String IC_NAME_YAN_JIU_CHA = "YanJiuCha";
/** 学习 */
public static final String IC_NAME_XUE_XI = "XueXi";
/** 医疗 */
public static final String IC_NAME_YI_LIAO = "YiLiao";
/** 住房 */
public static final String IC_NAME_ZHU_FANG = "ZhuFang";
/** 水电煤 */
public static final String IC_NAME_SHUI_DIAN_MEI = "ShuiDianMei";
/** 通讯 */
public static final String IC_NAME_TONG_XUN = "TongXun";
/** 人情来往 */
public static final String IC_NAME_REN_QING = "RenQing";
/** 薪资 */
public static final String IC_NAME_XIN_ZI = "XinZi";
/** 奖金 */
public static final String IC_NAME_JIANG_JIN = "JiangJin";
/** 借入 */
public static final String IC_NAME_JIE_RU = "JieRu";
/** 收债 */
public static final String IC_NAME_SHOU_ZHAI = "ShouZhai";
/** 利息收入 */
public static final String IC_NAME_LI_XIN_SHOU_RU = "LixiShouRu";
/** 投资回收 */
public static final String IC_NAME_TOU_ZI_HUI_SHOU = "TouZiHuiShou";
/** 意外所得 */
public static final String IC_NAME_YI_WAI_SUO_DE = "YiWaiSuoDe";
/** 投资收益 */
public static final String IC_NAME_TOU_ZI_SHOU_YI = "TouZiShouYi";
/** 卡片 */
public static final String IC_NAME_CARD = "Card";
/** 停车 */
public static final String IC_NAME_PARK = "Park";
/** 火车 */
public static final String IC_NAME_TRAIN = "Train";
/** 旅行 */
public static final String IC_NAME_TRAVEL = "Travel";
/** 趋势 */
public static final String IC_NAME_TREND = "Trend";
/** 红酒 */
public static final String IC_NAME_WINE = "Wine";
/** 所有分类图标 */
public static final List<String> ALL_ICON = Arrays.asList(
IC_NAME_OTHER,
IC_NAME_CAN_YIN,
IC_NAME_JIAO_TONG,
IC_NAME_GOU_WU,
IC_NAME_FU_SHI,
IC_NAME_RI_YONG_PIN,
IC_NAME_YU_LE,
IC_NAME_SHI_CAI,
IC_NAME_LING_SHI,
IC_NAME_YAN_JIU_CHA,
IC_NAME_XUE_XI,
IC_NAME_YI_LIAO,
IC_NAME_ZHU_FANG,
IC_NAME_SHUI_DIAN_MEI,
IC_NAME_TONG_XUN,
IC_NAME_REN_QING,
IC_NAME_XIN_ZI,
IC_NAME_JIANG_JIN,
IC_NAME_JIE_RU,
IC_NAME_SHOU_ZHAI,
IC_NAME_LI_XIN_SHOU_RU,
IC_NAME_TOU_ZI_HUI_SHOU,
IC_NAME_YI_WAI_SUO_DE,
IC_NAME_TOU_ZI_SHOU_YI,
IC_NAME_CARD,
IC_NAME_PARK,
IC_NAME_TRAIN,
IC_NAME_TRAVEL,
IC_NAME_TREND,
IC_NAME_WINE);
public static int resId(String iconName) {
if (iconName == null) {
return R.drawable.ic_category_expense_other;
}
switch (iconName) {
case IC_NAME_SETTING:
return R.drawable.ic_setting_category;
// 支出
case IC_NAME_OTHER:
return R.drawable.ic_category_expense_other;
case IC_NAME_CAN_YIN:
return R.drawable.ic_category_expense_food;
case IC_NAME_JIAO_TONG:
return R.drawable.ic_category_expense_traffic;
case IC_NAME_GOU_WU:
return R.drawable.ic_category_expense_shopping;
case IC_NAME_FU_SHI:
return R.drawable.ic_category_expense_clothes;
case IC_NAME_RI_YONG_PIN:
return R.drawable.ic_category_expense_daily_necessities;
case IC_NAME_YU_LE:
return R.drawable.ic_category_expense_entertainment;
case IC_NAME_SHI_CAI:
return R.drawable.ic_category_expense_food_ingredients;
case IC_NAME_LING_SHI:
return R.drawable.ic_category_expense_snack;
case IC_NAME_YAN_JIU_CHA:
return R.drawable.ic_category_expense_tobacco_tea;
case IC_NAME_XUE_XI:
return R.drawable.ic_category_expense_study;
case IC_NAME_YI_LIAO:
return R.drawable.ic_category_expense_medical;
case IC_NAME_ZHU_FANG:
return R.drawable.ic_category_expense_house;
case IC_NAME_SHUI_DIAN_MEI:
return R.drawable.ic_category_expense_electricity;
case IC_NAME_TONG_XUN:
return R.drawable.ic_category_expense_communication;
case IC_NAME_REN_QING:
return R.drawable.ic_category_expense_favor_pattern;
// 收入
case IC_NAME_XIN_ZI:
return R.drawable.ic_category_income_salary;
case IC_NAME_JIANG_JIN:
return R.drawable.ic_category_income_reward;
case IC_NAME_JIE_RU:
return R.drawable.ic_category_income_lend;
case IC_NAME_SHOU_ZHAI:
return R.drawable.ic_category_income_dun;
case IC_NAME_LI_XIN_SHOU_RU:
return R.drawable.ic_category_income_interest;
case IC_NAME_TOU_ZI_HUI_SHOU:
return R.drawable.ic_category_income_invest_recovery;
case IC_NAME_YI_WAI_SUO_DE:
return R.drawable.ic_category_income_unexpected;
case IC_NAME_TOU_ZI_SHOU_YI:
return R.drawable.ic_category_income_invest_profit;
case IC_NAME_CARD:
return R.drawable.ic_category_card;
case IC_NAME_PARK:
return R.drawable.ic_category_park;
case IC_NAME_TRAIN:
return R.drawable.ic_category_train;
case IC_NAME_TRAVEL:
return R.drawable.ic_category_travel;
case IC_NAME_TREND:
return R.drawable.ic_category_trend;
case IC_NAME_WINE:
return R.drawable.ic_category_wine;
default:
return R.drawable.ic_category_expense_other;
}
}
}
| coderpage/Mine | app/src/main/java/com/coderpage/mine/app/tally/data/CategoryIconHelper.java | 2,137 | /** 住房 */ | block_comment | zh-cn | package com.coderpage.mine.app.tally.data;
import com.coderpage.mine.R;
import java.util.Arrays;
import java.util.List;
/**
* @author abner-l. 2017-03-23
*/
public class CategoryIconHelper {
public static final String IC_NAME_SETTING = "com.coderpage.mine.ic.category_setting";
/** 其他 */
public static final String IC_NAME_OTHER = "Other";
/** 餐饮 */
public static final String IC_NAME_CAN_YIN = "CanYin";
/** 交通 */
public static final String IC_NAME_JIAO_TONG = "JiaoTong";
/** 住房 <SUF>*/
public static final String IC_NAME_GOU_WU = "GouWu";
/** 服饰 */
public static final String IC_NAME_FU_SHI = "FuShi";
/** 日用品 */
public static final String IC_NAME_RI_YONG_PIN = "RiYongPin";
/** 娱乐 */
public static final String IC_NAME_YU_LE = "YuLe";
/** 食材 */
public static final String IC_NAME_SHI_CAI = "ShiCai";
/** 零食 */
public static final String IC_NAME_LING_SHI = "LingShi";
/** 烟酒茶 */
public static final String IC_NAME_YAN_JIU_CHA = "YanJiuCha";
/** 学习 */
public static final String IC_NAME_XUE_XI = "XueXi";
/** 医疗 */
public static final String IC_NAME_YI_LIAO = "YiLiao";
/** 住房 */
public static final String IC_NAME_ZHU_FANG = "ZhuFang";
/** 水电煤 */
public static final String IC_NAME_SHUI_DIAN_MEI = "ShuiDianMei";
/** 通讯 */
public static final String IC_NAME_TONG_XUN = "TongXun";
/** 人情来往 */
public static final String IC_NAME_REN_QING = "RenQing";
/** 薪资 */
public static final String IC_NAME_XIN_ZI = "XinZi";
/** 奖金 */
public static final String IC_NAME_JIANG_JIN = "JiangJin";
/** 借入 */
public static final String IC_NAME_JIE_RU = "JieRu";
/** 收债 */
public static final String IC_NAME_SHOU_ZHAI = "ShouZhai";
/** 利息收入 */
public static final String IC_NAME_LI_XIN_SHOU_RU = "LixiShouRu";
/** 投资回收 */
public static final String IC_NAME_TOU_ZI_HUI_SHOU = "TouZiHuiShou";
/** 意外所得 */
public static final String IC_NAME_YI_WAI_SUO_DE = "YiWaiSuoDe";
/** 投资收益 */
public static final String IC_NAME_TOU_ZI_SHOU_YI = "TouZiShouYi";
/** 卡片 */
public static final String IC_NAME_CARD = "Card";
/** 停车 */
public static final String IC_NAME_PARK = "Park";
/** 火车 */
public static final String IC_NAME_TRAIN = "Train";
/** 旅行 */
public static final String IC_NAME_TRAVEL = "Travel";
/** 趋势 */
public static final String IC_NAME_TREND = "Trend";
/** 红酒 */
public static final String IC_NAME_WINE = "Wine";
/** 所有分类图标 */
public static final List<String> ALL_ICON = Arrays.asList(
IC_NAME_OTHER,
IC_NAME_CAN_YIN,
IC_NAME_JIAO_TONG,
IC_NAME_GOU_WU,
IC_NAME_FU_SHI,
IC_NAME_RI_YONG_PIN,
IC_NAME_YU_LE,
IC_NAME_SHI_CAI,
IC_NAME_LING_SHI,
IC_NAME_YAN_JIU_CHA,
IC_NAME_XUE_XI,
IC_NAME_YI_LIAO,
IC_NAME_ZHU_FANG,
IC_NAME_SHUI_DIAN_MEI,
IC_NAME_TONG_XUN,
IC_NAME_REN_QING,
IC_NAME_XIN_ZI,
IC_NAME_JIANG_JIN,
IC_NAME_JIE_RU,
IC_NAME_SHOU_ZHAI,
IC_NAME_LI_XIN_SHOU_RU,
IC_NAME_TOU_ZI_HUI_SHOU,
IC_NAME_YI_WAI_SUO_DE,
IC_NAME_TOU_ZI_SHOU_YI,
IC_NAME_CARD,
IC_NAME_PARK,
IC_NAME_TRAIN,
IC_NAME_TRAVEL,
IC_NAME_TREND,
IC_NAME_WINE);
public static int resId(String iconName) {
if (iconName == null) {
return R.drawable.ic_category_expense_other;
}
switch (iconName) {
case IC_NAME_SETTING:
return R.drawable.ic_setting_category;
// 支出
case IC_NAME_OTHER:
return R.drawable.ic_category_expense_other;
case IC_NAME_CAN_YIN:
return R.drawable.ic_category_expense_food;
case IC_NAME_JIAO_TONG:
return R.drawable.ic_category_expense_traffic;
case IC_NAME_GOU_WU:
return R.drawable.ic_category_expense_shopping;
case IC_NAME_FU_SHI:
return R.drawable.ic_category_expense_clothes;
case IC_NAME_RI_YONG_PIN:
return R.drawable.ic_category_expense_daily_necessities;
case IC_NAME_YU_LE:
return R.drawable.ic_category_expense_entertainment;
case IC_NAME_SHI_CAI:
return R.drawable.ic_category_expense_food_ingredients;
case IC_NAME_LING_SHI:
return R.drawable.ic_category_expense_snack;
case IC_NAME_YAN_JIU_CHA:
return R.drawable.ic_category_expense_tobacco_tea;
case IC_NAME_XUE_XI:
return R.drawable.ic_category_expense_study;
case IC_NAME_YI_LIAO:
return R.drawable.ic_category_expense_medical;
case IC_NAME_ZHU_FANG:
return R.drawable.ic_category_expense_house;
case IC_NAME_SHUI_DIAN_MEI:
return R.drawable.ic_category_expense_electricity;
case IC_NAME_TONG_XUN:
return R.drawable.ic_category_expense_communication;
case IC_NAME_REN_QING:
return R.drawable.ic_category_expense_favor_pattern;
// 收入
case IC_NAME_XIN_ZI:
return R.drawable.ic_category_income_salary;
case IC_NAME_JIANG_JIN:
return R.drawable.ic_category_income_reward;
case IC_NAME_JIE_RU:
return R.drawable.ic_category_income_lend;
case IC_NAME_SHOU_ZHAI:
return R.drawable.ic_category_income_dun;
case IC_NAME_LI_XIN_SHOU_RU:
return R.drawable.ic_category_income_interest;
case IC_NAME_TOU_ZI_HUI_SHOU:
return R.drawable.ic_category_income_invest_recovery;
case IC_NAME_YI_WAI_SUO_DE:
return R.drawable.ic_category_income_unexpected;
case IC_NAME_TOU_ZI_SHOU_YI:
return R.drawable.ic_category_income_invest_profit;
case IC_NAME_CARD:
return R.drawable.ic_category_card;
case IC_NAME_PARK:
return R.drawable.ic_category_park;
case IC_NAME_TRAIN:
return R.drawable.ic_category_train;
case IC_NAME_TRAVEL:
return R.drawable.ic_category_travel;
case IC_NAME_TREND:
return R.drawable.ic_category_trend;
case IC_NAME_WINE:
return R.drawable.ic_category_wine;
default:
return R.drawable.ic_category_expense_other;
}
}
}
| false | 1,745 | 4 | 2,137 | 5 | 2,174 | 4 | 2,137 | 5 | 2,524 | 7 | false | false | false | false | false | true |
11998_1 | package com.ruoxu.pattern.facade;
/**
* 外观模式(门面模式)
* 使用频率高,常用在SDK中。
*
* 定义:要求一个子系统的外部与其内部通信必须通过一个统一的对象进行。提供一个高层次的接口,使得子系统更易于使用。
* 总结:外观模式就是统一接口的封装,将子系统的逻辑,交互隐藏起来,为用户提供一个高层次的接口,使得系统更加易用,同时也对外隐藏了具体的实现,减少了用户的使用成本。
* 缺点:外观模式没有遵循开闭原则,当业务出现变更时,可能需要直接修改外观类。
*
* 使用场景:
* 1.为一个复杂子系统提供一个简单接口。
* 2.当你需要构建一个层次结构的子系统时,Facade模式定义子系统中每层的入口点,如果子系统之间是相互依赖的,可以让它们仅通过Facade接口进行通信,从而简化它们之间的依赖关系。
*/
public class Demo {
public static void main(String[] args) {
MobilePhone samsung = new MobilePhone();
// 打电话
samsung.dial();
samsung.hangUp();
// 拍照
samsung.takePicture();
samsung.closeCamera();
// 视频通话
samsung.videoChat();
samsung.closeCamera();
}
}
| coding-dream/Design_Pattern | src/com/ruoxu/pattern/facade/Demo.java | 363 | // 打电话
| line_comment | zh-cn | package com.ruoxu.pattern.facade;
/**
* 外观模式(门面模式)
* 使用频率高,常用在SDK中。
*
* 定义:要求一个子系统的外部与其内部通信必须通过一个统一的对象进行。提供一个高层次的接口,使得子系统更易于使用。
* 总结:外观模式就是统一接口的封装,将子系统的逻辑,交互隐藏起来,为用户提供一个高层次的接口,使得系统更加易用,同时也对外隐藏了具体的实现,减少了用户的使用成本。
* 缺点:外观模式没有遵循开闭原则,当业务出现变更时,可能需要直接修改外观类。
*
* 使用场景:
* 1.为一个复杂子系统提供一个简单接口。
* 2.当你需要构建一个层次结构的子系统时,Facade模式定义子系统中每层的入口点,如果子系统之间是相互依赖的,可以让它们仅通过Facade接口进行通信,从而简化它们之间的依赖关系。
*/
public class Demo {
public static void main(String[] args) {
MobilePhone samsung = new MobilePhone();
// 打电 <SUF>
samsung.dial();
samsung.hangUp();
// 拍照
samsung.takePicture();
samsung.closeCamera();
// 视频通话
samsung.videoChat();
samsung.closeCamera();
}
}
| false | 298 | 5 | 359 | 6 | 317 | 4 | 360 | 6 | 554 | 6 | false | false | false | false | false | true |
26191_5 |
package com.wenjun.oa.tool;
import com.wenjun.oa.bean.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
@Component
public class Installer {
@Resource
private SessionFactory sessionFactory;
/**
* 执行安装
*/
@Transactional
public void install() {
Session session = sessionFactory.getCurrentSession();
// ==============================================================
// 保存超级管理员用户
User user = new User();
user.setLoginName("admin");
user.setName("超级管理员");
user.setPassword(DigestUtils.md5Hex("admin"));
session.save(user); // 保存
// ==============================================================
// 保存权限数据
Privilege menu, menu1, menu2, menu3, menu4, menu5;
// --------------------
menu = new Privilege("系统管理", null, null);
menu1 = new Privilege("岗位管理", "/role_list", menu);
menu2 = new Privilege("部门管理", "/department_list", menu);
menu3 = new Privilege("用户管理", "/user_list", menu);
session.save(menu);
session.save(menu1);
session.save(menu2);
session.save(menu3);
session.save(new Privilege("岗位列表", "/role_list", menu1));
session.save(new Privilege("岗位删除", "/role_delete", menu1));
session.save(new Privilege("岗位添加", "/role_add", menu1));
session.save(new Privilege("岗位修改", "/role_edit", menu1));
session.save(new Privilege("部门列表", "/department_list", menu2));
session.save(new Privilege("部门删除", "/department_delete", menu2));
session.save(new Privilege("部门添加", "/department_add", menu2));
session.save(new Privilege("部门修改", "/department_edit", menu2));
session.save(new Privilege("用户列表", "/user_list", menu3));
session.save(new Privilege("用户删除", "/user_delete", menu3));
session.save(new Privilege("用户添加", "/user_add", menu3));
session.save(new Privilege("用户修改", "/user_edit", menu3));
session.save(new Privilege("初始化密码", "/user_initPassword", menu3));
// --------------------
menu = new Privilege("审批管理", null, null);
menu1 = new Privilege("起草申请", "/flow_applyTypeListUI", menu);
menu2 = new Privilege("待我审批", "/flow_myMessageList", menu);
menu3 = new Privilege("我的申请查询", "/flow_leaveList", menu);
session.save(menu);
session.save(menu1);
session.save(menu2);
session.save(menu3);
// ====================添加测试数据
Notice notice = new Notice();
notice.setContent("各部门:\n" +
" 依国务院办公厅通知,2017年清明节放假时间为4月2日至4月4日共3天,\n" +
"4月1号(星期六)正常上班。\n" +
" 为保障假后工作的正常运行,请各位同事离开工作岗位的同时检查好各项设备的运行情况,并关闭所有的电子设备,包括电脑,电视,空调,饮水机等。节假出行注意安全。\n" +
" 特此通知!\u200B\n" +
" 文珺信息科技有限公司\n" +
" 2017年5月15日");
notice.setCreateTime(new Date());
session.save(notice);
// ---------------------
Department department1 = new Department();
department1.setName("市场部");
department1.setDescription("前端销售,后端销售,商务组");
Department department2 = new Department();
department2.setName("研发部");
department2.setDescription("研发部,GO组,PHP组,UI组");
Department department3 = new Department();
department3.setName("行政部");
department3.setDescription("日常后勤,人事");
Department department4 = new Department();
department4.setName("财务部");
department4.setDescription("掌管经济大权");
Department department5 = new Department();
department5.setName("运营部");
department5.setDescription("微信运营组,PC运营组");
session.save(department1);
session.save(department2);
session.save(department3);
session.save(department4);
session.save(department5);
// ---------------------
Role role1 = new Role();
role1.setName("经理");
role1.setDescription("管理公司日常事务");
Role role2 = new Role();
role2.setName("员工");
role2.setDescription("公司员工");
session.save(role1);
session.save(role2);
List<Role> roleList = new ArrayList<Role>();
roleList.add(role2);
//测试用户
for(int i=0;i<100;i++){
User u = new User();
u.setLoginName("wangli"+i);
u.setName("王立"+i);
u.setPassword(DigestUtils.md5Hex("1234"));
u.setCreateTime(new Date());
u.setRoles(new HashSet<Role>(roleList));
session.save(u); // 保存
}
}
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
Installer installer = (Installer) ac.getBean("installer");
installer.install();
}
}
| coding-dream/OA | src/main/java/com/wenjun/oa/tool/Installer.java | 1,575 | // 保存权限数据
| line_comment | zh-cn |
package com.wenjun.oa.tool;
import com.wenjun.oa.bean.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
@Component
public class Installer {
@Resource
private SessionFactory sessionFactory;
/**
* 执行安装
*/
@Transactional
public void install() {
Session session = sessionFactory.getCurrentSession();
// ==============================================================
// 保存超级管理员用户
User user = new User();
user.setLoginName("admin");
user.setName("超级管理员");
user.setPassword(DigestUtils.md5Hex("admin"));
session.save(user); // 保存
// ==============================================================
// 保存 <SUF>
Privilege menu, menu1, menu2, menu3, menu4, menu5;
// --------------------
menu = new Privilege("系统管理", null, null);
menu1 = new Privilege("岗位管理", "/role_list", menu);
menu2 = new Privilege("部门管理", "/department_list", menu);
menu3 = new Privilege("用户管理", "/user_list", menu);
session.save(menu);
session.save(menu1);
session.save(menu2);
session.save(menu3);
session.save(new Privilege("岗位列表", "/role_list", menu1));
session.save(new Privilege("岗位删除", "/role_delete", menu1));
session.save(new Privilege("岗位添加", "/role_add", menu1));
session.save(new Privilege("岗位修改", "/role_edit", menu1));
session.save(new Privilege("部门列表", "/department_list", menu2));
session.save(new Privilege("部门删除", "/department_delete", menu2));
session.save(new Privilege("部门添加", "/department_add", menu2));
session.save(new Privilege("部门修改", "/department_edit", menu2));
session.save(new Privilege("用户列表", "/user_list", menu3));
session.save(new Privilege("用户删除", "/user_delete", menu3));
session.save(new Privilege("用户添加", "/user_add", menu3));
session.save(new Privilege("用户修改", "/user_edit", menu3));
session.save(new Privilege("初始化密码", "/user_initPassword", menu3));
// --------------------
menu = new Privilege("审批管理", null, null);
menu1 = new Privilege("起草申请", "/flow_applyTypeListUI", menu);
menu2 = new Privilege("待我审批", "/flow_myMessageList", menu);
menu3 = new Privilege("我的申请查询", "/flow_leaveList", menu);
session.save(menu);
session.save(menu1);
session.save(menu2);
session.save(menu3);
// ====================添加测试数据
Notice notice = new Notice();
notice.setContent("各部门:\n" +
" 依国务院办公厅通知,2017年清明节放假时间为4月2日至4月4日共3天,\n" +
"4月1号(星期六)正常上班。\n" +
" 为保障假后工作的正常运行,请各位同事离开工作岗位的同时检查好各项设备的运行情况,并关闭所有的电子设备,包括电脑,电视,空调,饮水机等。节假出行注意安全。\n" +
" 特此通知!\u200B\n" +
" 文珺信息科技有限公司\n" +
" 2017年5月15日");
notice.setCreateTime(new Date());
session.save(notice);
// ---------------------
Department department1 = new Department();
department1.setName("市场部");
department1.setDescription("前端销售,后端销售,商务组");
Department department2 = new Department();
department2.setName("研发部");
department2.setDescription("研发部,GO组,PHP组,UI组");
Department department3 = new Department();
department3.setName("行政部");
department3.setDescription("日常后勤,人事");
Department department4 = new Department();
department4.setName("财务部");
department4.setDescription("掌管经济大权");
Department department5 = new Department();
department5.setName("运营部");
department5.setDescription("微信运营组,PC运营组");
session.save(department1);
session.save(department2);
session.save(department3);
session.save(department4);
session.save(department5);
// ---------------------
Role role1 = new Role();
role1.setName("经理");
role1.setDescription("管理公司日常事务");
Role role2 = new Role();
role2.setName("员工");
role2.setDescription("公司员工");
session.save(role1);
session.save(role2);
List<Role> roleList = new ArrayList<Role>();
roleList.add(role2);
//测试用户
for(int i=0;i<100;i++){
User u = new User();
u.setLoginName("wangli"+i);
u.setName("王立"+i);
u.setPassword(DigestUtils.md5Hex("1234"));
u.setCreateTime(new Date());
u.setRoles(new HashSet<Role>(roleList));
session.save(u); // 保存
}
}
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
Installer installer = (Installer) ac.getBean("installer");
installer.install();
}
}
| false | 1,262 | 6 | 1,560 | 6 | 1,488 | 5 | 1,560 | 6 | 2,024 | 11 | false | false | false | false | false | true |
8851_8 | /*
* Licensed to Neo4j under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Neo4j licenses this file to you 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.yanqun.demo;
import org.neo4j.graphdb.*;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import org.neo4j.io.fs.FileUtils;
import java.io.File;
import java.io.IOException;
public class EmbeddedNeo4j
{
//数据库 目录
//D:\dev\neo4j\db\\
private static final File databaseDirectory = new File( "D:\\dev\\neo4j\\db\\neo4jDatabases\\database-9768f3fc-3b4a-436f-b31f-749e47ec2376\\installation-3.5.14\\data\\databases" );
public String greeting;
// tag::vars[]
GraphDatabaseService graphDb;
Node firstNode;
Node secondNode;
Relationship relationship;
// end::vars[]
// tag::createReltype[]
private enum RelTypes implements RelationshipType
{
//节点之间的关系 (认识,熟悉,喜欢)
KNOWS
}
// end::createReltype[]
public static void main( final String[] args ) throws IOException
{
EmbeddedNeo4j hello = new EmbeddedNeo4j();
hello.createDb();
hello.removeData();
hello.shutDown();
}
void createDb() throws IOException
{
//删除库
FileUtils.deleteRecursively( databaseDirectory );
// tag::startDb[]
//创建新库
graphDb = new GraphDatabaseFactory().newEmbeddedDatabase( databaseDirectory );
registerShutdownHook( graphDb );//jvm回调钩子
// end::startDb[]
// tag::transaction[]
try ( Transaction tx = graphDb.beginTx() )//jdk7
{
// Database operations go here
// end::transaction[]
// tag::addData[]
firstNode = graphDb.createNode();
firstNode.setProperty( "message", "Hello, " );
secondNode = graphDb.createNode();
secondNode.setProperty( "message", "World!" );
relationship = firstNode.createRelationshipTo( secondNode, RelTypes.KNOWS );
relationship.setProperty( "message", "brave Neo4j " );
// end::addData[]
// tag::readData[]
System.out.print( firstNode.getProperty( "message" ) );
System.out.print( relationship.getProperty( "message" ) );
System.out.print( secondNode.getProperty( "message" ) );
// end::readData[]
greeting = ( (String) firstNode.getProperty( "message" ) )
+ ( (String) relationship.getProperty( "message" ) )
+ ( (String) secondNode.getProperty( "message" ) );
// tag::transaction[]
tx.success();
}
// end::transaction[]
}
void removeData()
{
try ( Transaction tx = graphDb.beginTx() )
{
// tag::removingData[]
// let's remove the data
firstNode.getSingleRelationship( RelTypes.KNOWS, Direction.OUTGOING ).delete();
firstNode.delete();
secondNode.delete();
// end::removingData[]
tx.success();
}
}
void shutDown()
{
System.out.println();
System.out.println( "Shutting down database ..." );
// tag::shutdownServer[]
graphDb.shutdown();
// end::shutdownServer[]
}
// tag::shutdownHook[]
private static void registerShutdownHook( final GraphDatabaseService graphDb )
{
// Registers a shutdown hook for the Neo4j instance so that it
// shuts down nicely when the VM exits (even if you "Ctrl-C" the
// running application).
//通过回调钩子实现:当JVM关闭时,自动关闭neo4j关闭
Runtime.getRuntime().addShutdownHook( new Thread()
{
@Override
public void run()
{
graphDb.shutdown();
}
} );
}
// end::shutdownHook[]
}
| coding-technology/JavaCore | sources/microservice/project_neo4j/src/main/java/com/yanqun/demo/EmbeddedNeo4j.java | 1,093 | //删除库 | line_comment | zh-cn | /*
* Licensed to Neo4j under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Neo4j licenses this file to you 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.yanqun.demo;
import org.neo4j.graphdb.*;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import org.neo4j.io.fs.FileUtils;
import java.io.File;
import java.io.IOException;
public class EmbeddedNeo4j
{
//数据库 目录
//D:\dev\neo4j\db\\
private static final File databaseDirectory = new File( "D:\\dev\\neo4j\\db\\neo4jDatabases\\database-9768f3fc-3b4a-436f-b31f-749e47ec2376\\installation-3.5.14\\data\\databases" );
public String greeting;
// tag::vars[]
GraphDatabaseService graphDb;
Node firstNode;
Node secondNode;
Relationship relationship;
// end::vars[]
// tag::createReltype[]
private enum RelTypes implements RelationshipType
{
//节点之间的关系 (认识,熟悉,喜欢)
KNOWS
}
// end::createReltype[]
public static void main( final String[] args ) throws IOException
{
EmbeddedNeo4j hello = new EmbeddedNeo4j();
hello.createDb();
hello.removeData();
hello.shutDown();
}
void createDb() throws IOException
{
//删除 <SUF>
FileUtils.deleteRecursively( databaseDirectory );
// tag::startDb[]
//创建新库
graphDb = new GraphDatabaseFactory().newEmbeddedDatabase( databaseDirectory );
registerShutdownHook( graphDb );//jvm回调钩子
// end::startDb[]
// tag::transaction[]
try ( Transaction tx = graphDb.beginTx() )//jdk7
{
// Database operations go here
// end::transaction[]
// tag::addData[]
firstNode = graphDb.createNode();
firstNode.setProperty( "message", "Hello, " );
secondNode = graphDb.createNode();
secondNode.setProperty( "message", "World!" );
relationship = firstNode.createRelationshipTo( secondNode, RelTypes.KNOWS );
relationship.setProperty( "message", "brave Neo4j " );
// end::addData[]
// tag::readData[]
System.out.print( firstNode.getProperty( "message" ) );
System.out.print( relationship.getProperty( "message" ) );
System.out.print( secondNode.getProperty( "message" ) );
// end::readData[]
greeting = ( (String) firstNode.getProperty( "message" ) )
+ ( (String) relationship.getProperty( "message" ) )
+ ( (String) secondNode.getProperty( "message" ) );
// tag::transaction[]
tx.success();
}
// end::transaction[]
}
void removeData()
{
try ( Transaction tx = graphDb.beginTx() )
{
// tag::removingData[]
// let's remove the data
firstNode.getSingleRelationship( RelTypes.KNOWS, Direction.OUTGOING ).delete();
firstNode.delete();
secondNode.delete();
// end::removingData[]
tx.success();
}
}
void shutDown()
{
System.out.println();
System.out.println( "Shutting down database ..." );
// tag::shutdownServer[]
graphDb.shutdown();
// end::shutdownServer[]
}
// tag::shutdownHook[]
private static void registerShutdownHook( final GraphDatabaseService graphDb )
{
// Registers a shutdown hook for the Neo4j instance so that it
// shuts down nicely when the VM exits (even if you "Ctrl-C" the
// running application).
//通过回调钩子实现:当JVM关闭时,自动关闭neo4j关闭
Runtime.getRuntime().addShutdownHook( new Thread()
{
@Override
public void run()
{
graphDb.shutdown();
}
} );
}
// end::shutdownHook[]
}
| false | 1,036 | 3 | 1,093 | 3 | 1,172 | 3 | 1,093 | 3 | 1,351 | 4 | false | false | false | false | false | true |
48395_3 | /**
*
*/
package fastdfs.client.exchange;
import io.netty.buffer.ByteBuf;
import java.util.concurrent.CompletableFuture;
/**
* 接收处理
*
* @author liulongbiao
*/
public interface Replier<T> {
/**
* @param in
* @param promise
*/
void reply(ByteBuf in, CompletableFuture<T> promise);
/**
* 响应解码器
*
* @author liulongbiao
*/
interface Decoder<T> {
/**
* 期待的长度值,小于 0 时不验证
*
* @return
*/
default long expectLength() {
return -1;
}
/**
* 解码响应
*
* @param buf
* @return
*/
T decode(ByteBuf buf);
}
/**
* 空响应解码器
*
* @author liulongbiao
*/
enum NOPDecoder implements Decoder<Void> {
INSTANCE;
@Override
public long expectLength() {
return 0;
}
@Override
public Void decode(ByteBuf buf) {
return null;
}
}
}
| coding4m/fastdfs-client | src/main/java/fastdfs/client/exchange/Replier.java | 271 | /**
* 期待的长度值,小于 0 时不验证
*
* @return
*/ | block_comment | zh-cn | /**
*
*/
package fastdfs.client.exchange;
import io.netty.buffer.ByteBuf;
import java.util.concurrent.CompletableFuture;
/**
* 接收处理
*
* @author liulongbiao
*/
public interface Replier<T> {
/**
* @param in
* @param promise
*/
void reply(ByteBuf in, CompletableFuture<T> promise);
/**
* 响应解码器
*
* @author liulongbiao
*/
interface Decoder<T> {
/**
* 期待的 <SUF>*/
default long expectLength() {
return -1;
}
/**
* 解码响应
*
* @param buf
* @return
*/
T decode(ByteBuf buf);
}
/**
* 空响应解码器
*
* @author liulongbiao
*/
enum NOPDecoder implements Decoder<Void> {
INSTANCE;
@Override
public long expectLength() {
return 0;
}
@Override
public Void decode(ByteBuf buf) {
return null;
}
}
}
| false | 255 | 25 | 271 | 25 | 301 | 27 | 271 | 25 | 360 | 38 | false | false | false | false | false | true |
58488_1 | package com.duwei.designpattern.chain.chain1;
import java.util.ArrayList;
import java.util.List;
public class Client {
public static void main(String[] args) {
//1.构建责任链
List<Ratify> ratifies = new ArrayList<>();
ratifies.add(new Leader());
ratifies.add(new Manager());
ratifies.add(new Header());
//构建请求对象
Request request = new Request.Builder().setDays(7).setName("aaa").setReason("生病").build();
//组装处理
RealChain realChain = new RealChain(ratifies, request, 0);
realChain.proceed(request);
}
}
| codingWang/JavaStudy | src/com/duwei/designpattern/chain/chain1/Client.java | 163 | //构建请求对象 | line_comment | zh-cn | package com.duwei.designpattern.chain.chain1;
import java.util.ArrayList;
import java.util.List;
public class Client {
public static void main(String[] args) {
//1.构建责任链
List<Ratify> ratifies = new ArrayList<>();
ratifies.add(new Leader());
ratifies.add(new Manager());
ratifies.add(new Header());
//构建 <SUF>
Request request = new Request.Builder().setDays(7).setName("aaa").setReason("生病").build();
//组装处理
RealChain realChain = new RealChain(ratifies, request, 0);
realChain.proceed(request);
}
}
| false | 139 | 4 | 163 | 4 | 175 | 4 | 163 | 4 | 194 | 7 | false | false | false | false | false | true |
64066_14 | package cn.codingxiaxw.dao.cache;
import cn.codingxiaxw.entity.Seckill;
import cn.codingxiaxw.utils.JedisUtils;
import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.runtime.RuntimeSchema;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import java.util.UUID;
import java.util.function.Function;
/**
* Created by codingBoy on 17/2/17.
*/
public class RedisDao {
private final JedisPool jedisPool;
public RedisDao(String ip, int port) {
jedisPool = new JedisPool(ip, port);
}
private RuntimeSchema<Seckill> schema = RuntimeSchema.createFrom(Seckill.class);
public Seckill getSeckill(long seckillId) {
return getSeckill(seckillId, null);
}
/**
* 从redis获取信息
*
* @param seckillId id
* @return 如果不存在,则返回null
*/
public Seckill getSeckill(long seckillId, Jedis jedis) {
boolean hasJedis = jedis != null;
//redis操作逻辑
try {
if (!hasJedis) {
jedis = jedisPool.getResource();
}
try {
String key = getSeckillRedisKey(seckillId);
//并没有实现哪部序列化操作
//采用自定义序列化
//protostuff: pojo.
byte[] bytes = jedis.get(key.getBytes());
//缓存重获取到
if (bytes != null) {
Seckill seckill = schema.newMessage();
ProtostuffIOUtil.mergeFrom(bytes, seckill, schema);
//seckill被反序列化
return seckill;
}
} finally {
if (!hasJedis) {
jedis.close();
}
}
} catch (Exception e) {
}
return null;
}
/**
* 从缓存获取,如果没有,则从数据库获取
* 会用到分布式锁
*
* @param seckillId id
* @param getDataFromDb 从数据库获取的方法
* @return 返回商品信息
*/
public Seckill getOrPutSeckill(long seckillId, Function<Long, Seckill> getDataFromDb) {
String lockKey = "seckill:locks:getSeckill:" + seckillId;
String lockRequestId = UUID.randomUUID().toString();
Jedis jedis = jedisPool.getResource();
try {
// 循环直到获取到数据
while (true) {
Seckill seckill = getSeckill(seckillId, jedis);
if (seckill != null) {
return seckill;
}
// 尝试获取锁。
// 锁过期时间是防止程序突然崩溃来不及解锁,而造成其他线程不能获取锁的问题。过期时间是业务容忍最长时间。
boolean getLock = JedisUtils.tryGetDistributedLock(jedis, lockKey, lockRequestId, 1000);
if (getLock) {
// 获取到锁,从数据库拿数据, 然后存redis
seckill = getDataFromDb.apply(seckillId);
putSeckill(seckill, jedis);
return seckill;
}
// 获取不到锁,睡一下,等会再出发。sleep的时间需要斟酌,主要看业务处理速度
try {
Thread.sleep(100);
} catch (InterruptedException ignored) {
}
}
} catch (Exception ignored) {
} finally {
// 无论如何,最后要去解锁
JedisUtils.releaseDistributedLock(jedis, lockKey, lockRequestId);
jedis.close();
}
return null;
}
/**
* 根据id获取redis的key
*
* @param seckillId 商品id
* @return redis的key
*/
private String getSeckillRedisKey(long seckillId) {
return "seckill:" + seckillId;
}
public String putSeckill(Seckill seckill) {
return putSeckill(seckill, null);
}
public String putSeckill(Seckill seckill, Jedis jedis) {
boolean hasJedis = jedis != null;
try {
if (!hasJedis) {
jedis = jedisPool.getResource();
}
try {
String key = getSeckillRedisKey(seckill.getSeckillId());
byte[] bytes = ProtostuffIOUtil.toByteArray(seckill, schema,
LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));
//超时缓存,1小时
int timeout = 60 * 60;
String result = jedis.setex(key.getBytes(), timeout, bytes);
return result;
} finally {
if (!hasJedis) {
jedis.close();
}
}
} catch (Exception e) {
}
return null;
}
}
| codingXiaxw/seckill | src/main/java/cn/codingxiaxw/dao/cache/RedisDao.java | 1,229 | // 无论如何,最后要去解锁 | line_comment | zh-cn | package cn.codingxiaxw.dao.cache;
import cn.codingxiaxw.entity.Seckill;
import cn.codingxiaxw.utils.JedisUtils;
import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.runtime.RuntimeSchema;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import java.util.UUID;
import java.util.function.Function;
/**
* Created by codingBoy on 17/2/17.
*/
public class RedisDao {
private final JedisPool jedisPool;
public RedisDao(String ip, int port) {
jedisPool = new JedisPool(ip, port);
}
private RuntimeSchema<Seckill> schema = RuntimeSchema.createFrom(Seckill.class);
public Seckill getSeckill(long seckillId) {
return getSeckill(seckillId, null);
}
/**
* 从redis获取信息
*
* @param seckillId id
* @return 如果不存在,则返回null
*/
public Seckill getSeckill(long seckillId, Jedis jedis) {
boolean hasJedis = jedis != null;
//redis操作逻辑
try {
if (!hasJedis) {
jedis = jedisPool.getResource();
}
try {
String key = getSeckillRedisKey(seckillId);
//并没有实现哪部序列化操作
//采用自定义序列化
//protostuff: pojo.
byte[] bytes = jedis.get(key.getBytes());
//缓存重获取到
if (bytes != null) {
Seckill seckill = schema.newMessage();
ProtostuffIOUtil.mergeFrom(bytes, seckill, schema);
//seckill被反序列化
return seckill;
}
} finally {
if (!hasJedis) {
jedis.close();
}
}
} catch (Exception e) {
}
return null;
}
/**
* 从缓存获取,如果没有,则从数据库获取
* 会用到分布式锁
*
* @param seckillId id
* @param getDataFromDb 从数据库获取的方法
* @return 返回商品信息
*/
public Seckill getOrPutSeckill(long seckillId, Function<Long, Seckill> getDataFromDb) {
String lockKey = "seckill:locks:getSeckill:" + seckillId;
String lockRequestId = UUID.randomUUID().toString();
Jedis jedis = jedisPool.getResource();
try {
// 循环直到获取到数据
while (true) {
Seckill seckill = getSeckill(seckillId, jedis);
if (seckill != null) {
return seckill;
}
// 尝试获取锁。
// 锁过期时间是防止程序突然崩溃来不及解锁,而造成其他线程不能获取锁的问题。过期时间是业务容忍最长时间。
boolean getLock = JedisUtils.tryGetDistributedLock(jedis, lockKey, lockRequestId, 1000);
if (getLock) {
// 获取到锁,从数据库拿数据, 然后存redis
seckill = getDataFromDb.apply(seckillId);
putSeckill(seckill, jedis);
return seckill;
}
// 获取不到锁,睡一下,等会再出发。sleep的时间需要斟酌,主要看业务处理速度
try {
Thread.sleep(100);
} catch (InterruptedException ignored) {
}
}
} catch (Exception ignored) {
} finally {
// 无论 <SUF>
JedisUtils.releaseDistributedLock(jedis, lockKey, lockRequestId);
jedis.close();
}
return null;
}
/**
* 根据id获取redis的key
*
* @param seckillId 商品id
* @return redis的key
*/
private String getSeckillRedisKey(long seckillId) {
return "seckill:" + seckillId;
}
public String putSeckill(Seckill seckill) {
return putSeckill(seckill, null);
}
public String putSeckill(Seckill seckill, Jedis jedis) {
boolean hasJedis = jedis != null;
try {
if (!hasJedis) {
jedis = jedisPool.getResource();
}
try {
String key = getSeckillRedisKey(seckill.getSeckillId());
byte[] bytes = ProtostuffIOUtil.toByteArray(seckill, schema,
LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));
//超时缓存,1小时
int timeout = 60 * 60;
String result = jedis.setex(key.getBytes(), timeout, bytes);
return result;
} finally {
if (!hasJedis) {
jedis.close();
}
}
} catch (Exception e) {
}
return null;
}
}
| false | 1,082 | 7 | 1,229 | 11 | 1,224 | 8 | 1,229 | 11 | 1,581 | 17 | false | false | false | false | false | true |
25432_51 | package controller;
import com.sun.org.apache.xpath.internal.operations.Mod;
import controller.validation.ValidGroup1;
import exception.CustomException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import po.Items;
import po.ItemsCustom;
import po.ItemsQueryVo;
import service.ItemsService;
import javax.annotation.Resource;
import javax.jws.WebParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* Created by codingBoy on 16/11/15.
*/
@Controller
//定义url的根路径,访问时根路径+方法名的url
@RequestMapping("/items")
public class ItemsController {
//注入service
@Autowired
private ItemsService itemsService;
//单独将商品类型的方法提取出来,将方法返回值填充到request域,在页面提示
@ModelAttribute("itemsType")
public Map<String,String> getItemsType() throws Exception{
HashMap<String,String> itemsType=new HashMap<>();
itemsType.put("001","data type");
itemsType.put("002","clothes");
return itemsType;
}
@RequestMapping("/queryItems")
@RequiresPermissions("item:query")
public ModelAndView queryItems() throws Exception {
//调用servie来查询商品列表
List<ItemsCustom> itemsList=itemsService.findItemsList(null);
ModelAndView modelAndView=new ModelAndView();
modelAndView.addObject("itemsList",itemsList);
//指定逻辑视图名itemsList.jsp
modelAndView.setViewName("itemsList");
return modelAndView;
}
//批量修改商品查询
@RequestMapping("/editItemsList")
public ModelAndView editItemsList() throws Exception {
//调用servie来查询商品列表
List<ItemsCustom> itemsList=itemsService.findItemsList(null);
ModelAndView modelAndView=new ModelAndView();
modelAndView.addObject("itemsList",itemsList);
//指定逻辑视图名itemsList.jsp
modelAndView.setViewName("editItemsList");
return modelAndView;
}
//批量修改商品的提交
@RequestMapping("/editItemsListSubmit")
public String editItemsListSubmit(ItemsQueryVo itemsQueryVo) throws Exception{
return "success";
}
//商品修改页面提示
//使用method = RequestMethod.GET来限制使用get方法
// @RequestMapping(value = "/editItems",method = RequestMethod.GET)
// public ModelAndView editItems() throws Exception
// {
// ModelAndView modelAndView=new ModelAndView();
//
// //调用service查询商品的信息
// ItemsCustom itemsCustom=itemsService.findItemsById(1);
// //将模型数据传到jsp
// modelAndView.addObject("item",itemsCustom);
// //指定逻辑视图名
// modelAndView.setViewName("editItem");
//
// return modelAndView;
// }
//方法返回字符串,字符串就是逻辑视图名,Model作用时将数据填充到request域,在页面显示
@RequestMapping(value = "/editItems",method = RequestMethod.GET)
@RequiresPermissions("item:update")//执行此方法需要item:update权限
public String editItems(Model model, Integer id) throws Exception
{
//将id传到页面
model.addAttribute("id",id);
//调用service查询商品的信息
ItemsCustom itemsCustom=itemsService.findItemsById(id);
model.addAttribute("itemsCustom",itemsCustom);
return "editItem";
}
//更具商品id查看商品信息rest接口
//@requestMapping中指定restful方式的url中的参数,参数需要用{}包起来
//@PathVariable将url中的参数和形参进行绑定
@RequestMapping("/viewItems/{id}")
public @ResponseBody ItemsCustom viewItems(@PathVariable("id") Integer id) throws Exception
{
//调用service查询商品的信息
ItemsCustom itemsCustom=itemsService.findItemsById(id);
return itemsCustom;
}
// @RequestMapping(value = "/editItems",method = RequestMethod.GET)
// public void editItems(HttpServletRequest request, HttpServletResponse response,
//// @RequestParam(value = "item_id",required = false,defaultValue = "1")
// Integer id) throws Exception
// {
//
// //调用service查询商品的信息
// ItemsCustom itemsCustom=itemsService.findItemsById(id);
//
// request.setAttribute("item",itemsCustom);
//
// //zhuyi如果使用request转向页面,这里需要指定页面的完整路径
// request.getRequestDispatcher("/WEB-INF/jsp/editItem.jsp").forward(request,response);
// }
//商品提交页面
//itemsQueryVo是包装类型的pojo
//在@Validated中定义使用ValidGroup1组下边的校验
@RequestMapping("/editItemSubmit")
@RequiresPermissions("item:update")//执行此方法需要item:update权限
public String editItemSubmit(Model model,Integer id,
@Validated(value = {ValidGroup1.class}) @ModelAttribute(value = "itemsCustom") ItemsCustom itemsCustom,
BindingResult bindingResult,
//上传图片
MultipartFile pictureFile
) throws Exception
{
//输出校验错误信息
//如果参数绑定时出错
if (bindingResult.hasErrors())
{
//获取错误
List<ObjectError> errors=bindingResult.getAllErrors();
model.addAttribute("errors",errors);
for (ObjectError error:errors)
{
//输出错误信息
System.out.println(error.getDefaultMessage());
}
//如果校验错误,仍然回到商品修改页面
return "editItem";
}
//进行数据回显
model.addAttribute("id",id);
// model.addAttribute("item",itemsCustom);
//进行图片的上传
if (pictureFile!=null&&pictureFile.getOriginalFilename()!=null&&pictureFile.getOriginalFilename().length()>0)
{
//图片上传成功后,将图片的地址写到数据库
String filePath="/Users/codingBoy/Pictures/";
String originalFilename=pictureFile.getOriginalFilename();
String newFileName= UUID.randomUUID()+originalFilename.substring(originalFilename.lastIndexOf("."));
//新文件
File file=new File(filePath+newFileName);
//将内存中的文件写入磁盘
pictureFile.transferTo(file);
//图片上传成功
itemsCustom.setPic(newFileName);
}
itemsService.updateItems(id,itemsCustom);
//请求转发
// return "forward:queryItems.action";
// return "editItem";
//重定向
return "redirect:queryItems.action";
}
//
// //自定义属性编辑器
// @InitBinder
// public void initBinder(WebDataBinder binder) throws Exception{
//
// //Date.class必须是与controller方法形参pojo属性一致的date类型,这里是java.util.Date
// binder.registerCustomEditor(Date.class,new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH-mm-ss"),true));
//
// }
//删除商品
@RequestMapping("/deleteItems")
public String deleteItems(Integer[] delete_id) throws Exception
{
//调用serive方法删除商品
return "success";
}
}
| codingXiaxw/shiro | src/controller/ItemsController.java | 1,826 | //进行图片的上传 | line_comment | zh-cn | package controller;
import com.sun.org.apache.xpath.internal.operations.Mod;
import controller.validation.ValidGroup1;
import exception.CustomException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import po.Items;
import po.ItemsCustom;
import po.ItemsQueryVo;
import service.ItemsService;
import javax.annotation.Resource;
import javax.jws.WebParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* Created by codingBoy on 16/11/15.
*/
@Controller
//定义url的根路径,访问时根路径+方法名的url
@RequestMapping("/items")
public class ItemsController {
//注入service
@Autowired
private ItemsService itemsService;
//单独将商品类型的方法提取出来,将方法返回值填充到request域,在页面提示
@ModelAttribute("itemsType")
public Map<String,String> getItemsType() throws Exception{
HashMap<String,String> itemsType=new HashMap<>();
itemsType.put("001","data type");
itemsType.put("002","clothes");
return itemsType;
}
@RequestMapping("/queryItems")
@RequiresPermissions("item:query")
public ModelAndView queryItems() throws Exception {
//调用servie来查询商品列表
List<ItemsCustom> itemsList=itemsService.findItemsList(null);
ModelAndView modelAndView=new ModelAndView();
modelAndView.addObject("itemsList",itemsList);
//指定逻辑视图名itemsList.jsp
modelAndView.setViewName("itemsList");
return modelAndView;
}
//批量修改商品查询
@RequestMapping("/editItemsList")
public ModelAndView editItemsList() throws Exception {
//调用servie来查询商品列表
List<ItemsCustom> itemsList=itemsService.findItemsList(null);
ModelAndView modelAndView=new ModelAndView();
modelAndView.addObject("itemsList",itemsList);
//指定逻辑视图名itemsList.jsp
modelAndView.setViewName("editItemsList");
return modelAndView;
}
//批量修改商品的提交
@RequestMapping("/editItemsListSubmit")
public String editItemsListSubmit(ItemsQueryVo itemsQueryVo) throws Exception{
return "success";
}
//商品修改页面提示
//使用method = RequestMethod.GET来限制使用get方法
// @RequestMapping(value = "/editItems",method = RequestMethod.GET)
// public ModelAndView editItems() throws Exception
// {
// ModelAndView modelAndView=new ModelAndView();
//
// //调用service查询商品的信息
// ItemsCustom itemsCustom=itemsService.findItemsById(1);
// //将模型数据传到jsp
// modelAndView.addObject("item",itemsCustom);
// //指定逻辑视图名
// modelAndView.setViewName("editItem");
//
// return modelAndView;
// }
//方法返回字符串,字符串就是逻辑视图名,Model作用时将数据填充到request域,在页面显示
@RequestMapping(value = "/editItems",method = RequestMethod.GET)
@RequiresPermissions("item:update")//执行此方法需要item:update权限
public String editItems(Model model, Integer id) throws Exception
{
//将id传到页面
model.addAttribute("id",id);
//调用service查询商品的信息
ItemsCustom itemsCustom=itemsService.findItemsById(id);
model.addAttribute("itemsCustom",itemsCustom);
return "editItem";
}
//更具商品id查看商品信息rest接口
//@requestMapping中指定restful方式的url中的参数,参数需要用{}包起来
//@PathVariable将url中的参数和形参进行绑定
@RequestMapping("/viewItems/{id}")
public @ResponseBody ItemsCustom viewItems(@PathVariable("id") Integer id) throws Exception
{
//调用service查询商品的信息
ItemsCustom itemsCustom=itemsService.findItemsById(id);
return itemsCustom;
}
// @RequestMapping(value = "/editItems",method = RequestMethod.GET)
// public void editItems(HttpServletRequest request, HttpServletResponse response,
//// @RequestParam(value = "item_id",required = false,defaultValue = "1")
// Integer id) throws Exception
// {
//
// //调用service查询商品的信息
// ItemsCustom itemsCustom=itemsService.findItemsById(id);
//
// request.setAttribute("item",itemsCustom);
//
// //zhuyi如果使用request转向页面,这里需要指定页面的完整路径
// request.getRequestDispatcher("/WEB-INF/jsp/editItem.jsp").forward(request,response);
// }
//商品提交页面
//itemsQueryVo是包装类型的pojo
//在@Validated中定义使用ValidGroup1组下边的校验
@RequestMapping("/editItemSubmit")
@RequiresPermissions("item:update")//执行此方法需要item:update权限
public String editItemSubmit(Model model,Integer id,
@Validated(value = {ValidGroup1.class}) @ModelAttribute(value = "itemsCustom") ItemsCustom itemsCustom,
BindingResult bindingResult,
//上传图片
MultipartFile pictureFile
) throws Exception
{
//输出校验错误信息
//如果参数绑定时出错
if (bindingResult.hasErrors())
{
//获取错误
List<ObjectError> errors=bindingResult.getAllErrors();
model.addAttribute("errors",errors);
for (ObjectError error:errors)
{
//输出错误信息
System.out.println(error.getDefaultMessage());
}
//如果校验错误,仍然回到商品修改页面
return "editItem";
}
//进行数据回显
model.addAttribute("id",id);
// model.addAttribute("item",itemsCustom);
//进行 <SUF>
if (pictureFile!=null&&pictureFile.getOriginalFilename()!=null&&pictureFile.getOriginalFilename().length()>0)
{
//图片上传成功后,将图片的地址写到数据库
String filePath="/Users/codingBoy/Pictures/";
String originalFilename=pictureFile.getOriginalFilename();
String newFileName= UUID.randomUUID()+originalFilename.substring(originalFilename.lastIndexOf("."));
//新文件
File file=new File(filePath+newFileName);
//将内存中的文件写入磁盘
pictureFile.transferTo(file);
//图片上传成功
itemsCustom.setPic(newFileName);
}
itemsService.updateItems(id,itemsCustom);
//请求转发
// return "forward:queryItems.action";
// return "editItem";
//重定向
return "redirect:queryItems.action";
}
//
// //自定义属性编辑器
// @InitBinder
// public void initBinder(WebDataBinder binder) throws Exception{
//
// //Date.class必须是与controller方法形参pojo属性一致的date类型,这里是java.util.Date
// binder.registerCustomEditor(Date.class,new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH-mm-ss"),true));
//
// }
//删除商品
@RequestMapping("/deleteItems")
public String deleteItems(Integer[] delete_id) throws Exception
{
//调用serive方法删除商品
return "success";
}
}
| false | 1,608 | 5 | 1,826 | 5 | 1,900 | 5 | 1,826 | 5 | 2,404 | 8 | false | false | false | false | false | true |
57367_13 | package controller.interceptor;
import org.springframework.beans.support.PagedListHolder;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Created by codingBoy on 16/11/18.
*/
public class LoginInterceptor implements HandlerInterceptor
{
//在执行handler之前来执行的
//用于用户认证校验、用户权限校验
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String url=request.getRequestURI();
//判断是否是公开地址
//世纪开发中需要将公开地址配置在配置文件中
if (url.indexOf("login.action")>=0)
{
//如果是公开地址则放行
return true;
}
//判断用户身份在session中是否存在
HttpSession session=request.getSession();
String usercode= (String) session.getAttribute("usercode");
//如果用户身份在session中存在则放行
if (usercode!=null)
{
return true;
}
//执行到这里就拦截,跳转到登陆页面,用户进行登陆
request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response);
return false;
}
//在执行handerl但是返回modelandview之前来执行
//如果需要向页面提供一些公用的数据或配置一些视图信息,使用此方法实现从modelAndView入手
@Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
System.out.println("HandlerInterceptor1....postHandle");
}
//执行handler之后执行此方法
//做系统统一异常处理,进行方法执行性能监控,在prehandler中设置一个时间点,在afterCompletion设置一个时间点,两个时间点的差就是执行时长
//实现系统统一日志记录
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
Exception ex) throws Exception {
System.out.println("HandlerInterceptor1....afterCompletion");
}
}
| codingXiaxw/ssm2 | src/controller/interceptor/LoginInterceptor.java | 509 | //实现系统统一日志记录 | line_comment | zh-cn | package controller.interceptor;
import org.springframework.beans.support.PagedListHolder;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Created by codingBoy on 16/11/18.
*/
public class LoginInterceptor implements HandlerInterceptor
{
//在执行handler之前来执行的
//用于用户认证校验、用户权限校验
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String url=request.getRequestURI();
//判断是否是公开地址
//世纪开发中需要将公开地址配置在配置文件中
if (url.indexOf("login.action")>=0)
{
//如果是公开地址则放行
return true;
}
//判断用户身份在session中是否存在
HttpSession session=request.getSession();
String usercode= (String) session.getAttribute("usercode");
//如果用户身份在session中存在则放行
if (usercode!=null)
{
return true;
}
//执行到这里就拦截,跳转到登陆页面,用户进行登陆
request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response);
return false;
}
//在执行handerl但是返回modelandview之前来执行
//如果需要向页面提供一些公用的数据或配置一些视图信息,使用此方法实现从modelAndView入手
@Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
System.out.println("HandlerInterceptor1....postHandle");
}
//执行handler之后执行此方法
//做系统统一异常处理,进行方法执行性能监控,在prehandler中设置一个时间点,在afterCompletion设置一个时间点,两个时间点的差就是执行时长
//实现 <SUF>
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
Exception ex) throws Exception {
System.out.println("HandlerInterceptor1....afterCompletion");
}
}
| false | 454 | 7 | 509 | 6 | 533 | 7 | 509 | 6 | 732 | 11 | false | false | false | false | false | true |
14634_2 | package com.codingapi.txlcn.tc.jdbc.sql;
import com.codingapi.txlcn.p6spy.common.StatementInformation;
import java.sql.SQLException;
/**
* @author lorne
* @date 2020/7/3
* SQL幂等性分析接口,适配各种数据库做差异性适配
*/
public interface SqlAnalyse {
/**
* 数据库类型
* @return
*/
String sqlType();
/**
* SQL幂等性分析
* 幂等性机制主要是确保在执行补偿的时候重新提交的数据保持与事务执行时的数据一致,因此为了确保数据的一致性,目前的方案是记录实际影响的数据操作,然后在补偿的时候直接提交这些实际数据。
* insert 语句分析
* insert 获取落库后的数据信息
* 实现思路
* 若sql中有主键值,则直接记录下id,然后再查询影响后的数据
* 若sql中没有主键,则通过主键策略来查询ID,然后再查询影响后的实际数据。
* update 语句分析
* update 获取落库后的数据信息
* 实现思路
* 执行完成修改操作以后,按照相同条件下执行查询获取到影响后的实际数据。
* delete 语句分析
* delete 获取要真实删除的数据信息
* 实现思路
* 再执行delete之前先查询实际删除数据的id,然后再执行删除操作
* @param sql SQL数据
* @param statementInformation 执行返回数据
* @return 满足幂等性的SQL
*/
String analyse(String sql,StatementInformation statementInformation) throws SQLException;
/**
* SQL 分析判断检查
* 仅当CUD操作才需要做幂等性检查
* @param sql 执行的SQL
* @return
*/
boolean preAnalyse(String sql);
}
| codingapi/tx-lcn | txlcn-tc/src/main/java/com/codingapi/txlcn/tc/jdbc/sql/SqlAnalyse.java | 438 | /**
* SQL幂等性分析
* 幂等性机制主要是确保在执行补偿的时候重新提交的数据保持与事务执行时的数据一致,因此为了确保数据的一致性,目前的方案是记录实际影响的数据操作,然后在补偿的时候直接提交这些实际数据。
* insert 语句分析
* insert 获取落库后的数据信息
* 实现思路
* 若sql中有主键值,则直接记录下id,然后再查询影响后的数据
* 若sql中没有主键,则通过主键策略来查询ID,然后再查询影响后的实际数据。
* update 语句分析
* update 获取落库后的数据信息
* 实现思路
* 执行完成修改操作以后,按照相同条件下执行查询获取到影响后的实际数据。
* delete 语句分析
* delete 获取要真实删除的数据信息
* 实现思路
* 再执行delete之前先查询实际删除数据的id,然后再执行删除操作
* @param sql SQL数据
* @param statementInformation 执行返回数据
* @return 满足幂等性的SQL
*/ | block_comment | zh-cn | package com.codingapi.txlcn.tc.jdbc.sql;
import com.codingapi.txlcn.p6spy.common.StatementInformation;
import java.sql.SQLException;
/**
* @author lorne
* @date 2020/7/3
* SQL幂等性分析接口,适配各种数据库做差异性适配
*/
public interface SqlAnalyse {
/**
* 数据库类型
* @return
*/
String sqlType();
/**
* SQL <SUF>*/
String analyse(String sql,StatementInformation statementInformation) throws SQLException;
/**
* SQL 分析判断检查
* 仅当CUD操作才需要做幂等性检查
* @param sql 执行的SQL
* @return
*/
boolean preAnalyse(String sql);
}
| false | 417 | 252 | 438 | 252 | 428 | 243 | 438 | 252 | 726 | 472 | false | false | false | false | false | true |
53701_10 | import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
//https://stackoverflow.com/questions/3639198/how-to-read-pgm-images-in-java
public class ReadPgm {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String filePath = "fireHouse2.pgm";
FileInputStream fileInputStream = new FileInputStream(filePath);
Scanner scan = new Scanner(fileInputStream);
// Discard the magic number
scan.nextLine();
// Discard the comment line
scan.nextLine();
// Read pic width, height and max value
int picWidth = scan.nextInt();
int picHeight = scan.nextInt();
// int maxvalue = scan.nextInt();
fileInputStream.close();
// Now parse the file as binary data
fileInputStream = new FileInputStream(filePath);
DataInputStream dis = new DataInputStream(fileInputStream);
// look for 4 lines (i.e.: the header) and discard them
int numnewlines = 4;
while (numnewlines > 0) {
char c;
do {
c = (char) (dis.readUnsignedByte());
System.out.println(c);
} while (c != '\n');
numnewlines--;
}
// read the image data and find the exactly map
int[][] data2D = new int[picHeight][picWidth];
int leftEdge = -1;
int rightEdge = -1;
int topEdge = -1;
int botEdge = -1;
int mapBGColor = 205; // 地圖的背景色
int[] humanPosition = { picWidth / 2 , picHeight / 2 }; // 人所在的位置
int[] start = new int[] { humanPosition[0], humanPosition[1] }; // 起點
// 尋找地圖的上下左右邊界
for (int row = 0; row < picHeight; row++) {
for (int col = 0; col < picWidth; col++) {
// 讀取pgm檔的內容
data2D[row][col] = dis.readUnsignedByte();
if (data2D[row][col] != mapBGColor) {
if (leftEdge <= 0 || col < leftEdge)
leftEdge = col;
if (rightEdge <= 0 || col > rightEdge)
rightEdge = col;
if (topEdge <= 0 || row < topEdge)
topEdge = row;
if (botEdge <= 0 || row > topEdge)
botEdge = row;
}
}
}
System.out.println("leftEdge: " + leftEdge);
System.out.println("rightEdge: " + rightEdge);
System.out.println("topEdge: " + topEdge);
System.out.println("botEdge: " + botEdge);
BufferedImage image = new BufferedImage(picHeight, picWidth, BufferedImage.TYPE_INT_RGB);
for (int row = topEdge; row <= botEdge; row++) {
for (int col = leftEdge; col < rightEdge; col++) {
// 將圖片的每一點轉為RGB儲存在image裡
int a = data2D[row][col];
Color newColor = new Color(a, a, a);
image.setRGB(col, row, newColor.getRGB());
// System.out.print(data2D[row][col] + " ");
}
// System.out.println();
}
// 標記人在哪以及出口位置(從原點出發,x+ 方向往右,y+ 方向往下)
// 一般二維矩陣row代表y軸,col代表x軸,所以在setRGB2的參數中需替換過來(如84行)
int startColor = new Color(255, 0, 0).getRGB(); //紅色
int endColor = new Color(0, 255, 0).getRGB(); //綠色
int[] door1 = new int[] { start[0] - 28, start[1] - 127 };
int[] door2 = new int[] { start[0] + 93, start[1] - 126 };
int[] door3 = new int[] { start[0] + 208, start[1] - 42 };
int pointSize = 3;
for (int i = -pointSize; i <= pointSize; i++) {
for (int j = -pointSize; j <= pointSize; j++) {
if ((Math.pow(i, 2) + Math.pow(j, 2) <= Math.pow(pointSize, 2))) {
image.setRGB(humanPosition[1] + j, humanPosition[0] + i, startColor);
image.setRGB(door1[0] + j, door1[1] + i, endColor);
image.setRGB(door2[0] + j, door2[1] + i, endColor);
image.setRGB(door3[0] + j, door3[1] + i, endColor);
}
}
}
// 在地圖上畫線
// for (int i = 900; i <= 1000; i++) {
// int rgb = new Color(255, 0, 0).getRGB();
// image.setRGB(i,1000, rgb);
// }
JFrame frame = new JFrame();
ImageIcon icon = new ImageIcon(image);
int height = icon.getIconHeight();
int width = icon.getIconWidth();
JLabel label = new JLabel(icon);
label.setLocation(0, 0);
label.setSize(height, width);
frame.setSize(height, width);
frame.add(label);
frame.setVisible(true);
}
}
| codingx-2019-team4/ShortestPath | TestPgm/src/ReadPgm.java | 1,588 | // 人所在的位置
| line_comment | zh-cn | import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
//https://stackoverflow.com/questions/3639198/how-to-read-pgm-images-in-java
public class ReadPgm {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String filePath = "fireHouse2.pgm";
FileInputStream fileInputStream = new FileInputStream(filePath);
Scanner scan = new Scanner(fileInputStream);
// Discard the magic number
scan.nextLine();
// Discard the comment line
scan.nextLine();
// Read pic width, height and max value
int picWidth = scan.nextInt();
int picHeight = scan.nextInt();
// int maxvalue = scan.nextInt();
fileInputStream.close();
// Now parse the file as binary data
fileInputStream = new FileInputStream(filePath);
DataInputStream dis = new DataInputStream(fileInputStream);
// look for 4 lines (i.e.: the header) and discard them
int numnewlines = 4;
while (numnewlines > 0) {
char c;
do {
c = (char) (dis.readUnsignedByte());
System.out.println(c);
} while (c != '\n');
numnewlines--;
}
// read the image data and find the exactly map
int[][] data2D = new int[picHeight][picWidth];
int leftEdge = -1;
int rightEdge = -1;
int topEdge = -1;
int botEdge = -1;
int mapBGColor = 205; // 地圖的背景色
int[] humanPosition = { picWidth / 2 , picHeight / 2 }; // 人所 <SUF>
int[] start = new int[] { humanPosition[0], humanPosition[1] }; // 起點
// 尋找地圖的上下左右邊界
for (int row = 0; row < picHeight; row++) {
for (int col = 0; col < picWidth; col++) {
// 讀取pgm檔的內容
data2D[row][col] = dis.readUnsignedByte();
if (data2D[row][col] != mapBGColor) {
if (leftEdge <= 0 || col < leftEdge)
leftEdge = col;
if (rightEdge <= 0 || col > rightEdge)
rightEdge = col;
if (topEdge <= 0 || row < topEdge)
topEdge = row;
if (botEdge <= 0 || row > topEdge)
botEdge = row;
}
}
}
System.out.println("leftEdge: " + leftEdge);
System.out.println("rightEdge: " + rightEdge);
System.out.println("topEdge: " + topEdge);
System.out.println("botEdge: " + botEdge);
BufferedImage image = new BufferedImage(picHeight, picWidth, BufferedImage.TYPE_INT_RGB);
for (int row = topEdge; row <= botEdge; row++) {
for (int col = leftEdge; col < rightEdge; col++) {
// 將圖片的每一點轉為RGB儲存在image裡
int a = data2D[row][col];
Color newColor = new Color(a, a, a);
image.setRGB(col, row, newColor.getRGB());
// System.out.print(data2D[row][col] + " ");
}
// System.out.println();
}
// 標記人在哪以及出口位置(從原點出發,x+ 方向往右,y+ 方向往下)
// 一般二維矩陣row代表y軸,col代表x軸,所以在setRGB2的參數中需替換過來(如84行)
int startColor = new Color(255, 0, 0).getRGB(); //紅色
int endColor = new Color(0, 255, 0).getRGB(); //綠色
int[] door1 = new int[] { start[0] - 28, start[1] - 127 };
int[] door2 = new int[] { start[0] + 93, start[1] - 126 };
int[] door3 = new int[] { start[0] + 208, start[1] - 42 };
int pointSize = 3;
for (int i = -pointSize; i <= pointSize; i++) {
for (int j = -pointSize; j <= pointSize; j++) {
if ((Math.pow(i, 2) + Math.pow(j, 2) <= Math.pow(pointSize, 2))) {
image.setRGB(humanPosition[1] + j, humanPosition[0] + i, startColor);
image.setRGB(door1[0] + j, door1[1] + i, endColor);
image.setRGB(door2[0] + j, door2[1] + i, endColor);
image.setRGB(door3[0] + j, door3[1] + i, endColor);
}
}
}
// 在地圖上畫線
// for (int i = 900; i <= 1000; i++) {
// int rgb = new Color(255, 0, 0).getRGB();
// image.setRGB(i,1000, rgb);
// }
JFrame frame = new JFrame();
ImageIcon icon = new ImageIcon(image);
int height = icon.getIconHeight();
int width = icon.getIconWidth();
JLabel label = new JLabel(icon);
label.setLocation(0, 0);
label.setSize(height, width);
frame.setSize(height, width);
frame.add(label);
frame.setVisible(true);
}
}
| false | 1,344 | 6 | 1,567 | 7 | 1,494 | 5 | 1,567 | 7 | 1,849 | 9 | false | false | false | false | false | true |
63695_3 | package com.home.spider5566;
import com.home.spring.JDBCHelper;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.JdbcTemplate;
import java.io.IOException;
/**
* Created by hadoop on 16-11-23.
*/
public class Ren42 {
String[] q9={"0","www.job5156.com/","www.01hr.com/","www.carjob.com.cn/","www.buildhr.com/","www.goodjob.cn/","www.ncss.org.cn/","www.1010jz.com/","www.528.com.cn/","www.jobeast.com/","www.tjrc.com.cn/","job.aweb.com.cn/","www.hgjob.com/","www.fesco.com.cn/","www.cphr.com.cn/","www.hr.com.cn/","www.doctorjob.com.cn/","www.lqjob88.com/","www.36.cn/","www.jobcn.com/","www.qzrc.com/","hr.heiguang.com/","www.nchr.com.cn/","www.jobhb.com/","www.nmgrc.com/","www.hbsc.cn/","www.baicai.com/","www.dajie.com/","www.myjob.com/","www.zjrc.com/","www.tianjihr.com/","www.jxrcw.com/","www.hnrcsc.com/","www.91student.com/","bbs.hrsalon.org/","www.triphr.com/","www.xmrc.com.cn/","www.rencaijob.com/","www.healthr.com/","www.job168.com/","www.siphrd.com/","www.wzrc.net/","www.hiall.com.cn/","www.yjbys.com/","www.pcbjob.com/","www.jobui.com/","www.djob.com/","www.xajob.com/","www.baidajob.com/","www.epjob88.com/","www.jiaoshi.com.cn/","it.800hr.com/","www.goodjobs.cn/","www.lqjob88.com/","www.yingjiesheng.com/","www.gxrc.com/","www.hrm.cn/","www.sjrc.com.cn/","www.kshr.com.cn/","www.healthr.com/","www.hxrc.com/","www.hzrc.com/","www.800hr.com/","www.chinahrd.net/","www.chinahr.com/","hr.bjx.com.cn/","www.buildjob.net/","www.chinajob.gov.cn/","jobs.12333sh.gov.cn/","www.21wecan.com/","www.gdrc.com/","www.cfw.cn/","www.szhr.com.cn/","www.tianjihr.com/","www.labournet.com.cn/","www.cjol.com/","www.51job.com/","job.zhulong.com/","www.tourjob.net/","www.01job.cn/","www.nbrc.com.cn/","www.veryeast.cn/","www.zhaojiao.net/","www.qlrc.com/","www.138job.com/","www.bosshr.com/","www.huibo.com/","www.njrsrc.com/","www.gaoxiaojob.com/","www.bankhr.com/","www.51rencai.com/","www.hr33.com/","www.hxrc.com/","www.goodjob.cn/"};
String f7="http://www.5566.org/indexe.htm";
JdbcTemplate jdbcTemplate = null;
public Ren42() {
try {
jdbcTemplate = JDBCHelper.createMysqlTemplate("mysql1", "jdbc:mysql://192.168.21.27/urlclassifier?useUnicode=true&characterEncoding=utf8", "root", "root", 5, 30);
jdbcTemplate.execute("create table if not EXISTS tb_5566new("
+ "id int(11) not null auto_increment PRIMARY KEY ,"
+ "tag1 varchar(20)," +
"tag2 varchar(20) default null," +
"url varchar(255)," +
"name varchar(50)," +
"title LONGTEXT," +
"text LONGTEXT," +
" UNIQUE INDEX `url` (`url`)" +
") ENGINE=MyISAM DEFAULT CHARSET=utf8;");
System.out.println("成功创建数据表tb_parser2");
} catch (Exception e) {
jdbcTemplate = null;
System.out.println("mysql未开启或JDBCHelper.createMysqlTemplate中的参数不正确!");
e.printStackTrace();
}
}
public void inserTable(String tag1, String tag2, String url, String name) {
try {
if (jdbcTemplate != null) {
int updates = jdbcTemplate.update("INSERT INTO tb_5566new" +
"(tag1, tag2, url, name) VALUE (?, ?,?, ?)",
tag1, tag2, url, name
);
if (updates == 1) {
System.out.println("mysql插入成功");
}
}
} catch (DuplicateKeyException e) {
System.out.println("该url:" + url + "已经存在数据库里面");
}
}
public int string2Unicode(String string) {
StringBuffer unicode = new StringBuffer();
for (int i = 0; i < string.length(); i++) {
// 取出每一个字符
char c = string.charAt(i);
// 转换为unicode
unicode.append(Integer.toUnsignedLong(c));
}
return Integer.parseInt(unicode.toString());
}
public String o5(int t5){
String url;
String z7="=''+document.location;";
String y5="7755.5566";
String i8=""+"www.5566.net";
String j7="=''+document.domain;";
String o9="8822.5566";
String u4=""+"http://www.5566.net/ren1-4.htm";
int f0=i8.lastIndexOf('.');
int i1=0+string2Unicode(String.valueOf(z7.charAt(6)));
int w1=0+Integer.parseInt(String.valueOf(o9.charAt(3)));
int q7=0+Integer.parseInt(String.valueOf(i8.charAt(f0-3)));
int t2=0+string2Unicode(String.valueOf(j7.charAt(5)));
int p8=0+Integer.parseInt(String.valueOf(i8.charAt(f0-1)));
int a2=0+Integer.parseInt(String.valueOf(o9.charAt(1)));
String y9="ren1";
if(u4.indexOf("5566")==-1||u4.indexOf("ren1")==-1){
url = "http://www.5566.org/indexe.htm";
}
else{
url = "http://"+q9[(t5-q7-a2-w1-t2-i1-87)/p8];
}
return url;
}
public String t3(int y6){
String url = "";
String g2="=''+location.href;";
String e8="=''+location.hostname;";
String j5=""+"www.5566.net";
String p6=""+"http://www.5566.net/ren1-4.htm";
String i7="9966.5566";
String y5="2288.5566";
int e0=j5.lastIndexOf('.');
int y0=0+string2Unicode(String.valueOf(g2.charAt(6)));
int f5=0+string2Unicode(String.valueOf(e8.charAt(5)));
int d9=0+Integer.parseInt(String.valueOf(j5.charAt(e0-3)));
int h6=0+Integer.parseInt(String.valueOf(i7.charAt(1)));
int m3=0+Integer.parseInt(String.valueOf(j5.charAt(e0-1)));
int e3=0+Integer.parseInt(String.valueOf(i7.charAt(3)));
String a8="ren1";
if(p6.indexOf("5566")>=0&&p6.indexOf("ren1")>=0){
url = "http://"+q9[(y6-d9-m3-e3-f5-y0-64)/h6];
}
return url;
}
public String n5(int w6){
String url = "";
String h4="=''+document.URL;";
String c4="=''+location.host;";
String q6="5577.5566";
String h9=""+"www.5566.net";
String j1="6699.5566";
String t6=""+"http://www.5566.net/ren1-4.htm";
int u5=h9.lastIndexOf('.');
int q1=0+string2Unicode(String.valueOf(h4.charAt(6)));
int i2=0+string2Unicode(String.valueOf(c4.charAt(5)));
int c5=0+Integer.parseInt(String.valueOf(h9.charAt(u5-1)));
int b4=0+Integer.parseInt(String.valueOf(h9.charAt(u5-3)));
int d7=0+Integer.parseInt(String.valueOf(q6.charAt(3)));
int n2=0+Integer.parseInt(String.valueOf(q6.charAt(0)));
String l8="ren1";
if(h9=="5566.net"||h9=="www.5566.net"||h9=="5566.org"||h9=="1.5566.org"||h9=="2.5566.org"||h9=="3.5566.org"||h9=="4.5566.org"||h9=="5.5566.org"||h9=="www.5566.org"){
url = "http://"+q9[(w6-c5-n2-d7-i2-q1-72)/b4];
}
return url;
}
public void getUrlAndText(Elements urls, String tag1, String tag2) {
String tmpUrl = "";
String tmpName = "";
String onclick = "";
for (Element href : urls) {
try {
onclick = href.attr("onclick");
tmpName = href.text();
if (onclick.substring(0, 2).equalsIgnoreCase("o5")) {
tmpUrl = o5(Integer.parseInt(String.valueOf(onclick.substring(3, onclick.indexOf(")")))));
}
if (onclick.substring(0, 2).equalsIgnoreCase("t3")) {
tmpUrl = t3(Integer.parseInt(String.valueOf(onclick.substring(3, onclick.indexOf(")")))));
}
if (onclick.substring(0, 2).equalsIgnoreCase("n5")) {
tmpUrl = n5(Integer.parseInt(String.valueOf(onclick.substring(3, onclick.indexOf(")")))));
}
} catch (Exception e) {
tmpUrl = href.attr("href");
tmpName = href.text();
}
if (tmpUrl.length() > 2) {
// System.out.println(tmpUrl + "---------" + tmpName);
inserTable(tag1, tag2, tmpUrl, tmpName);
}
}
}
public void getRenUels(String url){
Document doc=null;
try {
doc = Jsoup.connect(url).get();
} catch (IOException e) {
e.printStackTrace();
}
Elements p = doc.getElementsByTag("tr");
String tag1 = "教育";
String tag2 ="人才/求职/招聘";
// System.out.println(p.get(52));
//20,37, 52
int[] numbers = {20,37, 52};
for(int i =0;i < numbers.length;i++){
Elements urls = p.get(numbers[i]).getElementsByTag("a");
getUrlAndText(urls, tag1, tag2);
}
}
public static void main(String[] args) {
Ren42 ren42 = new Ren42();
ren42.getRenUels("http://www.5566.net/ren1-4.htm");
}
}
| colajun/urlclassifier | src/main/java/com/home/spider5566/Ren42.java | 3,161 | // 取出每一个字符 | line_comment | zh-cn | package com.home.spider5566;
import com.home.spring.JDBCHelper;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.JdbcTemplate;
import java.io.IOException;
/**
* Created by hadoop on 16-11-23.
*/
public class Ren42 {
String[] q9={"0","www.job5156.com/","www.01hr.com/","www.carjob.com.cn/","www.buildhr.com/","www.goodjob.cn/","www.ncss.org.cn/","www.1010jz.com/","www.528.com.cn/","www.jobeast.com/","www.tjrc.com.cn/","job.aweb.com.cn/","www.hgjob.com/","www.fesco.com.cn/","www.cphr.com.cn/","www.hr.com.cn/","www.doctorjob.com.cn/","www.lqjob88.com/","www.36.cn/","www.jobcn.com/","www.qzrc.com/","hr.heiguang.com/","www.nchr.com.cn/","www.jobhb.com/","www.nmgrc.com/","www.hbsc.cn/","www.baicai.com/","www.dajie.com/","www.myjob.com/","www.zjrc.com/","www.tianjihr.com/","www.jxrcw.com/","www.hnrcsc.com/","www.91student.com/","bbs.hrsalon.org/","www.triphr.com/","www.xmrc.com.cn/","www.rencaijob.com/","www.healthr.com/","www.job168.com/","www.siphrd.com/","www.wzrc.net/","www.hiall.com.cn/","www.yjbys.com/","www.pcbjob.com/","www.jobui.com/","www.djob.com/","www.xajob.com/","www.baidajob.com/","www.epjob88.com/","www.jiaoshi.com.cn/","it.800hr.com/","www.goodjobs.cn/","www.lqjob88.com/","www.yingjiesheng.com/","www.gxrc.com/","www.hrm.cn/","www.sjrc.com.cn/","www.kshr.com.cn/","www.healthr.com/","www.hxrc.com/","www.hzrc.com/","www.800hr.com/","www.chinahrd.net/","www.chinahr.com/","hr.bjx.com.cn/","www.buildjob.net/","www.chinajob.gov.cn/","jobs.12333sh.gov.cn/","www.21wecan.com/","www.gdrc.com/","www.cfw.cn/","www.szhr.com.cn/","www.tianjihr.com/","www.labournet.com.cn/","www.cjol.com/","www.51job.com/","job.zhulong.com/","www.tourjob.net/","www.01job.cn/","www.nbrc.com.cn/","www.veryeast.cn/","www.zhaojiao.net/","www.qlrc.com/","www.138job.com/","www.bosshr.com/","www.huibo.com/","www.njrsrc.com/","www.gaoxiaojob.com/","www.bankhr.com/","www.51rencai.com/","www.hr33.com/","www.hxrc.com/","www.goodjob.cn/"};
String f7="http://www.5566.org/indexe.htm";
JdbcTemplate jdbcTemplate = null;
public Ren42() {
try {
jdbcTemplate = JDBCHelper.createMysqlTemplate("mysql1", "jdbc:mysql://192.168.21.27/urlclassifier?useUnicode=true&characterEncoding=utf8", "root", "root", 5, 30);
jdbcTemplate.execute("create table if not EXISTS tb_5566new("
+ "id int(11) not null auto_increment PRIMARY KEY ,"
+ "tag1 varchar(20)," +
"tag2 varchar(20) default null," +
"url varchar(255)," +
"name varchar(50)," +
"title LONGTEXT," +
"text LONGTEXT," +
" UNIQUE INDEX `url` (`url`)" +
") ENGINE=MyISAM DEFAULT CHARSET=utf8;");
System.out.println("成功创建数据表tb_parser2");
} catch (Exception e) {
jdbcTemplate = null;
System.out.println("mysql未开启或JDBCHelper.createMysqlTemplate中的参数不正确!");
e.printStackTrace();
}
}
public void inserTable(String tag1, String tag2, String url, String name) {
try {
if (jdbcTemplate != null) {
int updates = jdbcTemplate.update("INSERT INTO tb_5566new" +
"(tag1, tag2, url, name) VALUE (?, ?,?, ?)",
tag1, tag2, url, name
);
if (updates == 1) {
System.out.println("mysql插入成功");
}
}
} catch (DuplicateKeyException e) {
System.out.println("该url:" + url + "已经存在数据库里面");
}
}
public int string2Unicode(String string) {
StringBuffer unicode = new StringBuffer();
for (int i = 0; i < string.length(); i++) {
// 取出 <SUF>
char c = string.charAt(i);
// 转换为unicode
unicode.append(Integer.toUnsignedLong(c));
}
return Integer.parseInt(unicode.toString());
}
public String o5(int t5){
String url;
String z7="=''+document.location;";
String y5="7755.5566";
String i8=""+"www.5566.net";
String j7="=''+document.domain;";
String o9="8822.5566";
String u4=""+"http://www.5566.net/ren1-4.htm";
int f0=i8.lastIndexOf('.');
int i1=0+string2Unicode(String.valueOf(z7.charAt(6)));
int w1=0+Integer.parseInt(String.valueOf(o9.charAt(3)));
int q7=0+Integer.parseInt(String.valueOf(i8.charAt(f0-3)));
int t2=0+string2Unicode(String.valueOf(j7.charAt(5)));
int p8=0+Integer.parseInt(String.valueOf(i8.charAt(f0-1)));
int a2=0+Integer.parseInt(String.valueOf(o9.charAt(1)));
String y9="ren1";
if(u4.indexOf("5566")==-1||u4.indexOf("ren1")==-1){
url = "http://www.5566.org/indexe.htm";
}
else{
url = "http://"+q9[(t5-q7-a2-w1-t2-i1-87)/p8];
}
return url;
}
public String t3(int y6){
String url = "";
String g2="=''+location.href;";
String e8="=''+location.hostname;";
String j5=""+"www.5566.net";
String p6=""+"http://www.5566.net/ren1-4.htm";
String i7="9966.5566";
String y5="2288.5566";
int e0=j5.lastIndexOf('.');
int y0=0+string2Unicode(String.valueOf(g2.charAt(6)));
int f5=0+string2Unicode(String.valueOf(e8.charAt(5)));
int d9=0+Integer.parseInt(String.valueOf(j5.charAt(e0-3)));
int h6=0+Integer.parseInt(String.valueOf(i7.charAt(1)));
int m3=0+Integer.parseInt(String.valueOf(j5.charAt(e0-1)));
int e3=0+Integer.parseInt(String.valueOf(i7.charAt(3)));
String a8="ren1";
if(p6.indexOf("5566")>=0&&p6.indexOf("ren1")>=0){
url = "http://"+q9[(y6-d9-m3-e3-f5-y0-64)/h6];
}
return url;
}
public String n5(int w6){
String url = "";
String h4="=''+document.URL;";
String c4="=''+location.host;";
String q6="5577.5566";
String h9=""+"www.5566.net";
String j1="6699.5566";
String t6=""+"http://www.5566.net/ren1-4.htm";
int u5=h9.lastIndexOf('.');
int q1=0+string2Unicode(String.valueOf(h4.charAt(6)));
int i2=0+string2Unicode(String.valueOf(c4.charAt(5)));
int c5=0+Integer.parseInt(String.valueOf(h9.charAt(u5-1)));
int b4=0+Integer.parseInt(String.valueOf(h9.charAt(u5-3)));
int d7=0+Integer.parseInt(String.valueOf(q6.charAt(3)));
int n2=0+Integer.parseInt(String.valueOf(q6.charAt(0)));
String l8="ren1";
if(h9=="5566.net"||h9=="www.5566.net"||h9=="5566.org"||h9=="1.5566.org"||h9=="2.5566.org"||h9=="3.5566.org"||h9=="4.5566.org"||h9=="5.5566.org"||h9=="www.5566.org"){
url = "http://"+q9[(w6-c5-n2-d7-i2-q1-72)/b4];
}
return url;
}
public void getUrlAndText(Elements urls, String tag1, String tag2) {
String tmpUrl = "";
String tmpName = "";
String onclick = "";
for (Element href : urls) {
try {
onclick = href.attr("onclick");
tmpName = href.text();
if (onclick.substring(0, 2).equalsIgnoreCase("o5")) {
tmpUrl = o5(Integer.parseInt(String.valueOf(onclick.substring(3, onclick.indexOf(")")))));
}
if (onclick.substring(0, 2).equalsIgnoreCase("t3")) {
tmpUrl = t3(Integer.parseInt(String.valueOf(onclick.substring(3, onclick.indexOf(")")))));
}
if (onclick.substring(0, 2).equalsIgnoreCase("n5")) {
tmpUrl = n5(Integer.parseInt(String.valueOf(onclick.substring(3, onclick.indexOf(")")))));
}
} catch (Exception e) {
tmpUrl = href.attr("href");
tmpName = href.text();
}
if (tmpUrl.length() > 2) {
// System.out.println(tmpUrl + "---------" + tmpName);
inserTable(tag1, tag2, tmpUrl, tmpName);
}
}
}
public void getRenUels(String url){
Document doc=null;
try {
doc = Jsoup.connect(url).get();
} catch (IOException e) {
e.printStackTrace();
}
Elements p = doc.getElementsByTag("tr");
String tag1 = "教育";
String tag2 ="人才/求职/招聘";
// System.out.println(p.get(52));
//20,37, 52
int[] numbers = {20,37, 52};
for(int i =0;i < numbers.length;i++){
Elements urls = p.get(numbers[i]).getElementsByTag("a");
getUrlAndText(urls, tag1, tag2);
}
}
public static void main(String[] args) {
Ren42 ren42 = new Ren42();
ren42.getRenUels("http://www.5566.net/ren1-4.htm");
}
}
| false | 2,704 | 6 | 3,161 | 7 | 3,276 | 5 | 3,161 | 7 | 3,548 | 9 | false | false | false | false | false | true |
41457_5 | package com.evin.util;
/**
* Created by amayababy
* 2016-05-04
* 上午4:26
*/
public class AmayaConstants {
public static final String PREFIX_HTTP = "http://";
public static final String PREFIX_FILE = "file://";
public static final String PREFIX_DRAWABLE = "drawable://";
public static String AMAYA_DIR_CACHE ;
public static final String Kilometer = "\u516c\u91cc";// "公里";
public static final String Meter = "\u7c73";// "米";
public static final String ByFoot = "\u6b65\u884c";// "步行";
public static final String To = "\u53bb\u5f80";// "去往";
public static final String Station = "\u8f66\u7ad9";// "车站";
public static final String TargetPlace = "\u76ee\u7684\u5730";// "目的地";
public static final String StartPlace = "\u51fa\u53d1\u5730";// "出发地";
public static final String About = "\u5927\u7ea6";// "大约";
public static final String Direction = "\u65b9\u5411";// "方向";
public static final String GetOn = "\u4e0a\u8f66";// "上车";
public static final String GetOff = "\u4e0b\u8f66";// "下车";
public static final String Zhan = "\u7ad9";// "站";
public static final String cross = "\u4ea4\u53c9\u8def\u53e3"; // 交叉路口
public static final String type = "\u7c7b\u522b"; // 类别
public static final String address = "\u5730\u5740"; // 地址
public static final String PrevStep = "\u4e0a\u4e00\u6b65";
public static final String NextStep = "\u4e0b\u4e00\u6b65";
public static final String Gong = "\u516c\u4ea4";
public static final String ByBus = "\u4e58\u8f66";
public static final String Arrive = "\u5230\u8FBE";// 到达
public static final int CODE_EMPTY_TOKEN = 900;
}
| colarking/EvinHistroy | app/src/main/java/com/evin/util/AmayaConstants.java | 620 | // "车站"; | line_comment | zh-cn | package com.evin.util;
/**
* Created by amayababy
* 2016-05-04
* 上午4:26
*/
public class AmayaConstants {
public static final String PREFIX_HTTP = "http://";
public static final String PREFIX_FILE = "file://";
public static final String PREFIX_DRAWABLE = "drawable://";
public static String AMAYA_DIR_CACHE ;
public static final String Kilometer = "\u516c\u91cc";// "公里";
public static final String Meter = "\u7c73";// "米";
public static final String ByFoot = "\u6b65\u884c";// "步行";
public static final String To = "\u53bb\u5f80";// "去往";
public static final String Station = "\u8f66\u7ad9";// "车 <SUF>
public static final String TargetPlace = "\u76ee\u7684\u5730";// "目的地";
public static final String StartPlace = "\u51fa\u53d1\u5730";// "出发地";
public static final String About = "\u5927\u7ea6";// "大约";
public static final String Direction = "\u65b9\u5411";// "方向";
public static final String GetOn = "\u4e0a\u8f66";// "上车";
public static final String GetOff = "\u4e0b\u8f66";// "下车";
public static final String Zhan = "\u7ad9";// "站";
public static final String cross = "\u4ea4\u53c9\u8def\u53e3"; // 交叉路口
public static final String type = "\u7c7b\u522b"; // 类别
public static final String address = "\u5730\u5740"; // 地址
public static final String PrevStep = "\u4e0a\u4e00\u6b65";
public static final String NextStep = "\u4e0b\u4e00\u6b65";
public static final String Gong = "\u516c\u4ea4";
public static final String ByBus = "\u4e58\u8f66";
public static final String Arrive = "\u5230\u8FBE";// 到达
public static final int CODE_EMPTY_TOKEN = 900;
}
| false | 561 | 4 | 620 | 5 | 614 | 4 | 620 | 5 | 691 | 7 | false | false | false | false | false | true |
14425_1 | package org.colorcoding.ibas.bobas.common;
import javax.xml.bind.annotation.XmlType;
import org.colorcoding.ibas.bobas.MyConfiguration;
import org.colorcoding.ibas.bobas.mapping.Value;
/**
* 条件之间关系
*/
@XmlType(name = "ConditionRelationship", namespace = MyConfiguration.NAMESPACE_BOBAS_COMMON)
public enum ConditionRelationship {
/**
* 没关系
*/
@Value("N")
NONE,
/**
* 且
*/
@Value("A")
AND,
/**
* 或
*/
@Value("O")
OR;
public static ConditionRelationship valueOf(int value) {
return values()[value];
}
public static ConditionRelationship valueOf(String value, boolean ignoreCase) {
if (ignoreCase) {
for (Object item : ConditionRelationship.class.getEnumConstants()) {
if (item.toString().equalsIgnoreCase(value)) {
return (ConditionRelationship) item;
}
}
}
return ConditionRelationship.valueOf(value);
}
}
| color-coding/ibas-framework | bobas.businessobjectscommon/src/main/java/org/colorcoding/ibas/bobas/common/ConditionRelationship.java | 273 | /**
* 没关系
*/ | block_comment | zh-cn | package org.colorcoding.ibas.bobas.common;
import javax.xml.bind.annotation.XmlType;
import org.colorcoding.ibas.bobas.MyConfiguration;
import org.colorcoding.ibas.bobas.mapping.Value;
/**
* 条件之间关系
*/
@XmlType(name = "ConditionRelationship", namespace = MyConfiguration.NAMESPACE_BOBAS_COMMON)
public enum ConditionRelationship {
/**
* 没关系 <SUF>*/
@Value("N")
NONE,
/**
* 且
*/
@Value("A")
AND,
/**
* 或
*/
@Value("O")
OR;
public static ConditionRelationship valueOf(int value) {
return values()[value];
}
public static ConditionRelationship valueOf(String value, boolean ignoreCase) {
if (ignoreCase) {
for (Object item : ConditionRelationship.class.getEnumConstants()) {
if (item.toString().equalsIgnoreCase(value)) {
return (ConditionRelationship) item;
}
}
}
return ConditionRelationship.valueOf(value);
}
}
| false | 220 | 10 | 273 | 9 | 271 | 9 | 273 | 9 | 341 | 11 | false | false | false | false | false | true |
40298_2 | /**
* 模仿天猫整站ssm 教程 为how2j.cn 版权所有
* 本教程仅用于学习使用,切勿用于非法用途,由此引起一切后果与本站无关
* 供购买者学习,请勿私自传播,否则自行承担相关法律责任
*/
package com.key.msmall.util;
public class Page {
private int start; //开始页数
private int count; //每页显示个数
private int total; //总个数
private String param; //参数
private static final int defaultCount = 5; //默认每页显示5条
public int getStart() {
return start;
}
public void setStart(int start) {
this.start = start;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public Page (){
count = defaultCount;
}
public Page(int start, int count) {
super();
this.start = start;
this.count = count;
}
public boolean isHasPreviouse(){
if(start==0)
return false;
return true;
}
public boolean isHasNext(){
if(start==getLast())
return false;
return true;
}
public int getTotalPage(){
int totalPage;
// 假设总数是50,是能够被5整除的,那么就有10页
if (0 == total % count)
totalPage = total /count;
// 假设总数是51,不能够被5整除的,那么就有11页
else
totalPage = total / count + 1;
if(0==totalPage)
totalPage = 1;
return totalPage;
}
public int getLast(){
int last;
// 假设总数是50,是能够被5整除的,那么最后一页的开始就是45
if (0 == total % count)
last = total - count;
// 假设总数是51,不能够被5整除的,那么最后一页的开始就是50
else
last = total - total % count;
last = last<0?0:last;
return last;
}
@Override
public String toString() {
return "Page [start=" + start + ", count=" + count + ", total=" + total + ", getStart()=" + getStart()
+ ", getCount()=" + getCount() + ", isHasPreviouse()=" + isHasPreviouse() + ", isHasNext()="
+ isHasNext() + ", getTotalPage()=" + getTotalPage() + ", getLast()=" + getLast() + "]";
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public String getParam() {
return param;
}
public void setParam(String param) {
this.param = param;
}
}
/**
* 模仿天猫整站ssm 教程 为how2j.cn 版权所有
* 本教程仅用于学习使用,切勿用于非法用途,由此引起一切后果与本站无关
* 供购买者学习,请勿私自传播,否则自行承担相关法律责任
*/
| comsir/MSMall | src/main/java/com/key/msmall/util/Page.java | 792 | //每页显示个数 | line_comment | zh-cn | /**
* 模仿天猫整站ssm 教程 为how2j.cn 版权所有
* 本教程仅用于学习使用,切勿用于非法用途,由此引起一切后果与本站无关
* 供购买者学习,请勿私自传播,否则自行承担相关法律责任
*/
package com.key.msmall.util;
public class Page {
private int start; //开始页数
private int count; //每页 <SUF>
private int total; //总个数
private String param; //参数
private static final int defaultCount = 5; //默认每页显示5条
public int getStart() {
return start;
}
public void setStart(int start) {
this.start = start;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public Page (){
count = defaultCount;
}
public Page(int start, int count) {
super();
this.start = start;
this.count = count;
}
public boolean isHasPreviouse(){
if(start==0)
return false;
return true;
}
public boolean isHasNext(){
if(start==getLast())
return false;
return true;
}
public int getTotalPage(){
int totalPage;
// 假设总数是50,是能够被5整除的,那么就有10页
if (0 == total % count)
totalPage = total /count;
// 假设总数是51,不能够被5整除的,那么就有11页
else
totalPage = total / count + 1;
if(0==totalPage)
totalPage = 1;
return totalPage;
}
public int getLast(){
int last;
// 假设总数是50,是能够被5整除的,那么最后一页的开始就是45
if (0 == total % count)
last = total - count;
// 假设总数是51,不能够被5整除的,那么最后一页的开始就是50
else
last = total - total % count;
last = last<0?0:last;
return last;
}
@Override
public String toString() {
return "Page [start=" + start + ", count=" + count + ", total=" + total + ", getStart()=" + getStart()
+ ", getCount()=" + getCount() + ", isHasPreviouse()=" + isHasPreviouse() + ", isHasNext()="
+ isHasNext() + ", getTotalPage()=" + getTotalPage() + ", getLast()=" + getLast() + "]";
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public String getParam() {
return param;
}
public void setParam(String param) {
this.param = param;
}
}
/**
* 模仿天猫整站ssm 教程 为how2j.cn 版权所有
* 本教程仅用于学习使用,切勿用于非法用途,由此引起一切后果与本站无关
* 供购买者学习,请勿私自传播,否则自行承担相关法律责任
*/
| false | 730 | 6 | 792 | 5 | 796 | 5 | 792 | 5 | 1,038 | 7 | false | false | false | false | false | true |
33529_10 | import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 公平公正公开的抽奖
* Created by liuzhongzheng on 2017/1/29.
*/
public class Lottery4Chicken {
private static String BIG_AWARD_TEMPLATE = "恭喜 %s 在54哥特约赞助的集资活动中抽中特等奖!";
private static String FIRST_AWARD_TEMPLATE = "恭喜 %s 在54哥特约赞助的集资活动中抽中一等奖!";
private static String SECOND_AWARD_TEMPLATE = "恭喜 %s 在54哥特约赞助的集资活动中抽中二等奖!";
private static String THIRD_AWARD_TEMPLATE = "恭喜 %s 在54哥特约赞助的集资活动中抽中三等奖!";
/**
* 鸽子们(这不是鸡吗?)
*/
private static class Chicken extends LotteryService.LotteryRate {
/**
* 概率模型的构造函数
* @param rate 概率
* @param nick 昵称
*/
Chicken(double rate, Object nick) {
super(rate, nick);
}
String getNick() {
return this.getTarget().toString();
}
}
/**
* 初始化数据
* @return 鸽子们和他们的概率列表
*/
private static List<LotteryService.LotteryRate> initData() {
List<LotteryService.LotteryRate> chickens = new ArrayList<>();
int amount = 17;
while (amount > 0) {
chickens.add(new Chicken(1, amount + "号"));
amount--;
}
return chickens;
}
/**
* 欢呼吧,鸽子们!抽中会自动把你剔除!
* @param chickens 可以参加抽奖的鸽子们
* @return 一只鸽子
*/
private static Chicken lottery4Chicken(List<LotteryService.LotteryRate> chickens) {
Chicken chicken = (Chicken)LotteryService.lottery(chickens);
// 避免重复抽到
chickens.remove(chicken);
return chicken;
}
/**
* 一千万次模拟抽奖
*/
private static void check(long seed) {
LotteryService.setSeed(seed);
// statistics
Map<String, Integer> count = new HashMap<String, Integer>();
double num = 10000000;
for (int i = 0; i < num; i++) {
Chicken chicken = lottery4Chicken(initData());
Integer value = count.get(chicken.getNick());
count.put(chicken.getNick(), value == null ? 1 : value + 1);
}
System.out.println("1千万次模拟抽奖检验结果:");
for (Map.Entry<String, Integer> entry : count.entrySet()) {
System.out.println(entry.getKey() + ", 抽中总数:" + entry.getValue() + ", 概率:" + entry.getValue() / num);
}
}
// 飞吧,鸽子们
public static void main(String[] args) {
// 设置种子
LotteryService.setSeed(20170103L);
// 鸽子们的数据
List<LotteryService.LotteryRate> chickens = initData();
System.out.println(String.format(BIG_AWARD_TEMPLATE, lottery4Chicken(chickens).getNick()));
System.out.println(String.format(FIRST_AWARD_TEMPLATE, lottery4Chicken(chickens).getNick()));
System.out.println(String.format(SECOND_AWARD_TEMPLATE, lottery4Chicken(chickens).getNick()));
System.out.println(String.format(THIRD_AWARD_TEMPLATE, lottery4Chicken(chickens).getNick()));
}
}
| conanliu/lottery4chicken | src/Lottery4Chicken.java | 974 | // 鸽子们的数据 | line_comment | zh-cn | import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 公平公正公开的抽奖
* Created by liuzhongzheng on 2017/1/29.
*/
public class Lottery4Chicken {
private static String BIG_AWARD_TEMPLATE = "恭喜 %s 在54哥特约赞助的集资活动中抽中特等奖!";
private static String FIRST_AWARD_TEMPLATE = "恭喜 %s 在54哥特约赞助的集资活动中抽中一等奖!";
private static String SECOND_AWARD_TEMPLATE = "恭喜 %s 在54哥特约赞助的集资活动中抽中二等奖!";
private static String THIRD_AWARD_TEMPLATE = "恭喜 %s 在54哥特约赞助的集资活动中抽中三等奖!";
/**
* 鸽子们(这不是鸡吗?)
*/
private static class Chicken extends LotteryService.LotteryRate {
/**
* 概率模型的构造函数
* @param rate 概率
* @param nick 昵称
*/
Chicken(double rate, Object nick) {
super(rate, nick);
}
String getNick() {
return this.getTarget().toString();
}
}
/**
* 初始化数据
* @return 鸽子们和他们的概率列表
*/
private static List<LotteryService.LotteryRate> initData() {
List<LotteryService.LotteryRate> chickens = new ArrayList<>();
int amount = 17;
while (amount > 0) {
chickens.add(new Chicken(1, amount + "号"));
amount--;
}
return chickens;
}
/**
* 欢呼吧,鸽子们!抽中会自动把你剔除!
* @param chickens 可以参加抽奖的鸽子们
* @return 一只鸽子
*/
private static Chicken lottery4Chicken(List<LotteryService.LotteryRate> chickens) {
Chicken chicken = (Chicken)LotteryService.lottery(chickens);
// 避免重复抽到
chickens.remove(chicken);
return chicken;
}
/**
* 一千万次模拟抽奖
*/
private static void check(long seed) {
LotteryService.setSeed(seed);
// statistics
Map<String, Integer> count = new HashMap<String, Integer>();
double num = 10000000;
for (int i = 0; i < num; i++) {
Chicken chicken = lottery4Chicken(initData());
Integer value = count.get(chicken.getNick());
count.put(chicken.getNick(), value == null ? 1 : value + 1);
}
System.out.println("1千万次模拟抽奖检验结果:");
for (Map.Entry<String, Integer> entry : count.entrySet()) {
System.out.println(entry.getKey() + ", 抽中总数:" + entry.getValue() + ", 概率:" + entry.getValue() / num);
}
}
// 飞吧,鸽子们
public static void main(String[] args) {
// 设置种子
LotteryService.setSeed(20170103L);
// 鸽子 <SUF>
List<LotteryService.LotteryRate> chickens = initData();
System.out.println(String.format(BIG_AWARD_TEMPLATE, lottery4Chicken(chickens).getNick()));
System.out.println(String.format(FIRST_AWARD_TEMPLATE, lottery4Chicken(chickens).getNick()));
System.out.println(String.format(SECOND_AWARD_TEMPLATE, lottery4Chicken(chickens).getNick()));
System.out.println(String.format(THIRD_AWARD_TEMPLATE, lottery4Chicken(chickens).getNick()));
}
}
| false | 813 | 7 | 974 | 7 | 939 | 6 | 974 | 7 | 1,282 | 10 | false | false | false | false | false | true |
62846_3 | package com.coo.m.vote;
import java.util.ArrayList;
import java.util.List;
import com.coo.s.cloud.model.Account;
import com.coo.s.cloud.model.Feedback;
import com.coo.s.vote.model.Channel;
import com.coo.s.vote.model.Topic;
import com.coo.s.vote.model.TopicLeg;
import com.kingstar.ngbf.ms.util.model.CommonItem;
import com.kingstar.ngbf.ms.util.model.CommonOption;
/**
* 提供测试数据,供界面调试用
*
* @author boqing.shen
*
*/
public class Mock {
public static List<Channel> CHANNNELS = new ArrayList<Channel>();
static {
CHANNNELS.add(new Channel("yinyue", "音乐"));
CHANNNELS.add(new Channel("tiyu", "体育"));
CHANNNELS.add(new Channel("worldcup_2014", "2014世界杯"));
CHANNNELS.add(new Channel("keji", "科技"));
CHANNNELS.add(new Channel("xinwen", "新闻"));
CHANNNELS.add(new Channel("guoji", "国际"));
CHANNNELS.add(new Channel("minsheng", "民生"));
CHANNNELS.add(new Channel("youxi", "游戏"));
}
/**
* 模拟产生Profile的属性条目对象,用于集中展现
*/
public static List<CommonItem> getProfileItems() {
// TODO 向服务端获得个人信息
List<CommonItem> items = new ArrayList<CommonItem>();
items.add(new CommonItem("profile.uuid", "UUID", "uuid.value"));
items.add(new CommonItem("profile.mobile", "手机号", "13917081673"));
items.add(new CommonItem("profile.nickname", "昵称", "zhangsan")
.uiType(CommonItem.UIT_TEXT));
List<CommonOption> genders = new ArrayList<CommonOption>();
genders.add(new CommonOption("男", "男"));
genders.add(new CommonOption("女", "女"));
genders.add(new CommonOption("未知", "未知"));
CommonItem ci04 = new CommonItem("profile.gender", "性别", "未知")
.uiType(CommonItem.UIT_LIST).options(genders);
items.add(ci04);
items.add(new CommonItem("profile.address", "住址", "")
.uiType(CommonItem.UIT_TEXT));
return items;
}
/**
* 获得模拟账号
*/
public static Account getAccount() {
Account account = new Account();
account.setMobile("13917081673");
account.setPassword("111111");
account.set_id("541155452170e0df13091431");
// account.setType(Account.TYPE_ADMIN);
account.setType(Account.TYPE_COMMON);
return account;
}
public static List<Account> accounts() {
List<Account> list = new ArrayList<Account>();
for (int i = 0; i < 10; i++) {
Account item = new Account();
item.setMobile("139-00000-" + i);
list.add(item);
}
return list;
}
public static List<Feedback> feedbacks() {
List<Feedback> list = new ArrayList<Feedback>();
for (int i = 0; i < 10; i++) {
Feedback item = new Feedback();
item.setNote("issue-" + i);
item.setApp_version("1.0.0");
list.add(item);
}
return list;
}
public static List<Topic> topicshots(String code) {
List<Topic> list = new ArrayList<Topic>();
for (int i = 0; i < 30; i++) {
Topic item = new Topic();
item.setTitle(code + "-Topic Title-" + i);
item.setVote(i);
item.set_tsi(System.currentTimeMillis());
// item.set_id(System.currentTimeMillis() + "-ID");
item.set_id("topic-" + i + "-ID");
TopicLeg tl1 = new TopicLeg("0", "是");
tl1.setVote(i + 1);
item.add(tl1);
TopicLeg tl2 = new TopicLeg("1", "不是");
tl2.setVote(i + 2);
item.add(tl2);
if (i % 3 == 0) {
TopicLeg tl3 = new TopicLeg("2", "LEG3");
tl3.setVote(i + 3);
item.add(tl3);
TopicLeg tl4 = new TopicLeg("3", "LEG4");
tl4.setVote(i + 4);
item.add(tl4);
// 设置投过票了....
item.setVoted(true);
}
// 设置所有者...
item.setOwner("13917081673");
list.add(item);
}
return list;
}
}
| coo-coo/mvote | coo-m-vote/src/com/coo/m/vote/Mock.java | 1,361 | /**
* 获得模拟账号
*/ | block_comment | zh-cn | package com.coo.m.vote;
import java.util.ArrayList;
import java.util.List;
import com.coo.s.cloud.model.Account;
import com.coo.s.cloud.model.Feedback;
import com.coo.s.vote.model.Channel;
import com.coo.s.vote.model.Topic;
import com.coo.s.vote.model.TopicLeg;
import com.kingstar.ngbf.ms.util.model.CommonItem;
import com.kingstar.ngbf.ms.util.model.CommonOption;
/**
* 提供测试数据,供界面调试用
*
* @author boqing.shen
*
*/
public class Mock {
public static List<Channel> CHANNNELS = new ArrayList<Channel>();
static {
CHANNNELS.add(new Channel("yinyue", "音乐"));
CHANNNELS.add(new Channel("tiyu", "体育"));
CHANNNELS.add(new Channel("worldcup_2014", "2014世界杯"));
CHANNNELS.add(new Channel("keji", "科技"));
CHANNNELS.add(new Channel("xinwen", "新闻"));
CHANNNELS.add(new Channel("guoji", "国际"));
CHANNNELS.add(new Channel("minsheng", "民生"));
CHANNNELS.add(new Channel("youxi", "游戏"));
}
/**
* 模拟产生Profile的属性条目对象,用于集中展现
*/
public static List<CommonItem> getProfileItems() {
// TODO 向服务端获得个人信息
List<CommonItem> items = new ArrayList<CommonItem>();
items.add(new CommonItem("profile.uuid", "UUID", "uuid.value"));
items.add(new CommonItem("profile.mobile", "手机号", "13917081673"));
items.add(new CommonItem("profile.nickname", "昵称", "zhangsan")
.uiType(CommonItem.UIT_TEXT));
List<CommonOption> genders = new ArrayList<CommonOption>();
genders.add(new CommonOption("男", "男"));
genders.add(new CommonOption("女", "女"));
genders.add(new CommonOption("未知", "未知"));
CommonItem ci04 = new CommonItem("profile.gender", "性别", "未知")
.uiType(CommonItem.UIT_LIST).options(genders);
items.add(ci04);
items.add(new CommonItem("profile.address", "住址", "")
.uiType(CommonItem.UIT_TEXT));
return items;
}
/**
* 获得模 <SUF>*/
public static Account getAccount() {
Account account = new Account();
account.setMobile("13917081673");
account.setPassword("111111");
account.set_id("541155452170e0df13091431");
// account.setType(Account.TYPE_ADMIN);
account.setType(Account.TYPE_COMMON);
return account;
}
public static List<Account> accounts() {
List<Account> list = new ArrayList<Account>();
for (int i = 0; i < 10; i++) {
Account item = new Account();
item.setMobile("139-00000-" + i);
list.add(item);
}
return list;
}
public static List<Feedback> feedbacks() {
List<Feedback> list = new ArrayList<Feedback>();
for (int i = 0; i < 10; i++) {
Feedback item = new Feedback();
item.setNote("issue-" + i);
item.setApp_version("1.0.0");
list.add(item);
}
return list;
}
public static List<Topic> topicshots(String code) {
List<Topic> list = new ArrayList<Topic>();
for (int i = 0; i < 30; i++) {
Topic item = new Topic();
item.setTitle(code + "-Topic Title-" + i);
item.setVote(i);
item.set_tsi(System.currentTimeMillis());
// item.set_id(System.currentTimeMillis() + "-ID");
item.set_id("topic-" + i + "-ID");
TopicLeg tl1 = new TopicLeg("0", "是");
tl1.setVote(i + 1);
item.add(tl1);
TopicLeg tl2 = new TopicLeg("1", "不是");
tl2.setVote(i + 2);
item.add(tl2);
if (i % 3 == 0) {
TopicLeg tl3 = new TopicLeg("2", "LEG3");
tl3.setVote(i + 3);
item.add(tl3);
TopicLeg tl4 = new TopicLeg("3", "LEG4");
tl4.setVote(i + 4);
item.add(tl4);
// 设置投过票了....
item.setVoted(true);
}
// 设置所有者...
item.setOwner("13917081673");
list.add(item);
}
return list;
}
}
| false | 1,100 | 11 | 1,353 | 10 | 1,310 | 10 | 1,353 | 10 | 1,614 | 18 | false | false | false | false | false | true |
18980_2 | package LibraryManagementSystem;
import java.util.Arrays;
import java.util.Scanner;
public class Book {
int[] bookId={1,2,3};
String[] bookName = {"jvm调优指南","java编程思想","C与指针"} ;
String[] bookAuthor= {"周志明","陈大王","王小二"};
int[] inventory ={20,1,3};
Scanner scanner = new Scanner(System.in);
public void control_1(){
System.out.println("1 "+"管理图书");
System.out.println("2 "+"搜索图书");
System.out.println("0 "+"退出");
System.out.println("===============================");
System.out.println("请输入编号操作(注意输完回车)");
} //运行界面控制台
public void refer() { //查询管理图书库
for(int i=0;i<bookId.length;i++){
System.out.print(bookId[i]+" ");
System.out.print(bookName[i]+" ");
System.out.print(bookAuthor[i]+" ");
System.out.println(inventory[i]);
}
System.out.println("0--返回"+'\t'+"1--新增图书"+'\t'+"2--删除图书");
System.out.println("===============================");
System.out.println("请输入编号操作(注意输完回车)");
} //查询管理图书库
public void add(){ //增加方法
int bookId = scanner.nextInt();
System.out.println("管理图书/新增图书");
System.out.println("请输入图书名(注意输完回车)");
String bookName = scanner.nextLine();
System.out.println("请输入图书作者(注意输完回车)");
String bookAuthor = scanner.nextLine();
System.out.println("请输入图书库存(注意输完回车)");
int inventory = scanner.nextInt();
System.out.println("确认添加N/Y(注意输完回车)");
String str = scanner.nextLine();
if(str=="Y"){
this.bookName = Arrays.copyOf(this.bookName, this.bookName.length + 1);
this.bookName[this.bookName.length] = bookName;
this.bookAuthor = Arrays.copyOf(this.bookAuthor, this.bookAuthor.length + 1);
this.bookAuthor[this.bookAuthor.length] = bookAuthor;
this.inventory = Arrays.copyOf(this.inventory, this.inventory.length + 1);
this.inventory[this.inventory.length] = inventory;
} else if (str=="N"){
control_1();
} else {
System.out.println("错误输入");
control_1();
}
} //添加图书
public void search(){
System.out.println("请输入书名:");
String bookName = scanner.nextLine();
for(int i=0;i<this.bookName.length;i++){
if(this.bookName[i]==bookName){
System.out.println("0-----返回");
System.out.println("1-----退出");
System.out.println("请输入图书名(注意输完回车)"+'\n');
System.out.println("搜索结果:");
System.out.println("书名:"+'\t'+this.bookName[i]);
System.out.println("作者:"+'\t'+this.bookAuthor[i]);
System.out.println("库存:"+'\t'+this.inventory[i]);
}
}
} //输入图书名检索
public void delete(int index){ //删除方法
int i;
String bN;
String bA;
int in;
if(index>=0 && index<bookId.length){
i=bookId[bookId.length-1]; //交换数组下标位置
bookId[bookId.length-1]=bookId[index-1];
bookId[index-1]=i;
bookId = Arrays.copyOf(bookId, bookId.length - 1);
bN=bookName[bookName.length-1]; //交换数组下标位置
bookName[bookName.length-1]=bookName[index-1];
bookName[index-1]=bN;
bookName = Arrays.copyOf(bookName, bookName.length - 1);
bA=bookAuthor[bookAuthor.length-1]; //交换数组下标位置
bookAuthor[bookAuthor.length-1]=bookAuthor[index-1];
bookName[index-1]=bA;
bookAuthor = Arrays.copyOf(bookAuthor, bookAuthor.length - 1);
in=inventory[inventory.length-1]; //交换数组下标位置
inventory[inventory.length-1]=inventory[index-1];
inventory[index-1]=in;
inventory = Arrays.copyOf(inventory, inventory.length - 1);
} else {
System.out.println("输入错误下标");
}
bookId = Arrays.copyOf(bookId,bookId.length-1);
bookName = Arrays.copyOf(bookName,bookName.length-1);
bookAuthor = Arrays.copyOf(bookAuthor,bookAuthor.length-1);
} //删除图书
}
| core-1/Java | Book.java | 1,226 | //查询管理图书库 | line_comment | zh-cn | package LibraryManagementSystem;
import java.util.Arrays;
import java.util.Scanner;
public class Book {
int[] bookId={1,2,3};
String[] bookName = {"jvm调优指南","java编程思想","C与指针"} ;
String[] bookAuthor= {"周志明","陈大王","王小二"};
int[] inventory ={20,1,3};
Scanner scanner = new Scanner(System.in);
public void control_1(){
System.out.println("1 "+"管理图书");
System.out.println("2 "+"搜索图书");
System.out.println("0 "+"退出");
System.out.println("===============================");
System.out.println("请输入编号操作(注意输完回车)");
} //运行界面控制台
public void refer() { //查询管理图书库
for(int i=0;i<bookId.length;i++){
System.out.print(bookId[i]+" ");
System.out.print(bookName[i]+" ");
System.out.print(bookAuthor[i]+" ");
System.out.println(inventory[i]);
}
System.out.println("0--返回"+'\t'+"1--新增图书"+'\t'+"2--删除图书");
System.out.println("===============================");
System.out.println("请输入编号操作(注意输完回车)");
} //查询 <SUF>
public void add(){ //增加方法
int bookId = scanner.nextInt();
System.out.println("管理图书/新增图书");
System.out.println("请输入图书名(注意输完回车)");
String bookName = scanner.nextLine();
System.out.println("请输入图书作者(注意输完回车)");
String bookAuthor = scanner.nextLine();
System.out.println("请输入图书库存(注意输完回车)");
int inventory = scanner.nextInt();
System.out.println("确认添加N/Y(注意输完回车)");
String str = scanner.nextLine();
if(str=="Y"){
this.bookName = Arrays.copyOf(this.bookName, this.bookName.length + 1);
this.bookName[this.bookName.length] = bookName;
this.bookAuthor = Arrays.copyOf(this.bookAuthor, this.bookAuthor.length + 1);
this.bookAuthor[this.bookAuthor.length] = bookAuthor;
this.inventory = Arrays.copyOf(this.inventory, this.inventory.length + 1);
this.inventory[this.inventory.length] = inventory;
} else if (str=="N"){
control_1();
} else {
System.out.println("错误输入");
control_1();
}
} //添加图书
public void search(){
System.out.println("请输入书名:");
String bookName = scanner.nextLine();
for(int i=0;i<this.bookName.length;i++){
if(this.bookName[i]==bookName){
System.out.println("0-----返回");
System.out.println("1-----退出");
System.out.println("请输入图书名(注意输完回车)"+'\n');
System.out.println("搜索结果:");
System.out.println("书名:"+'\t'+this.bookName[i]);
System.out.println("作者:"+'\t'+this.bookAuthor[i]);
System.out.println("库存:"+'\t'+this.inventory[i]);
}
}
} //输入图书名检索
public void delete(int index){ //删除方法
int i;
String bN;
String bA;
int in;
if(index>=0 && index<bookId.length){
i=bookId[bookId.length-1]; //交换数组下标位置
bookId[bookId.length-1]=bookId[index-1];
bookId[index-1]=i;
bookId = Arrays.copyOf(bookId, bookId.length - 1);
bN=bookName[bookName.length-1]; //交换数组下标位置
bookName[bookName.length-1]=bookName[index-1];
bookName[index-1]=bN;
bookName = Arrays.copyOf(bookName, bookName.length - 1);
bA=bookAuthor[bookAuthor.length-1]; //交换数组下标位置
bookAuthor[bookAuthor.length-1]=bookAuthor[index-1];
bookName[index-1]=bA;
bookAuthor = Arrays.copyOf(bookAuthor, bookAuthor.length - 1);
in=inventory[inventory.length-1]; //交换数组下标位置
inventory[inventory.length-1]=inventory[index-1];
inventory[index-1]=in;
inventory = Arrays.copyOf(inventory, inventory.length - 1);
} else {
System.out.println("输入错误下标");
}
bookId = Arrays.copyOf(bookId,bookId.length-1);
bookName = Arrays.copyOf(bookName,bookName.length-1);
bookAuthor = Arrays.copyOf(bookAuthor,bookAuthor.length-1);
} //删除图书
}
| false | 1,033 | 5 | 1,226 | 6 | 1,261 | 5 | 1,226 | 6 | 1,514 | 10 | false | false | false | false | false | true |
36315_0 | package io.xjar.filter;
import io.xjar.XEntryFilter;
import java.util.Collection;
/**
* ALL逻辑混合过滤器,即所有过滤器都满足的时候才满足,只要有一个过滤器不满足就立刻返回不满足,如果没有过滤器的时候则认为所有过滤器都满足。
*
* @author Payne 646742615@qq.com
* 2018/12/4 15:26
*/
public class XAllEntryFilter<E> extends XMixEntryFilter<E> implements XEntryFilter<E> {
public XAllEntryFilter() {
super(null);
}
public XAllEntryFilter(Collection<? extends XEntryFilter<? extends E>> filters) {
super(filters);
}
@Override
public XAllEntryFilter<E> mix(XEntryFilter<? extends E> filter) {
add(filter);
return this;
}
@Override
public boolean filtrate(E entry) {
XEntryFilter[] filters = this.filters.toArray(new XEntryFilter[0]);
for (XEntryFilter filter : filters) {
if (!filter.filtrate(entry)) {
return false;
}
}
return true;
}
}
| core-lib/xjar | src/main/java/io/xjar/filter/XAllEntryFilter.java | 297 | /**
* ALL逻辑混合过滤器,即所有过滤器都满足的时候才满足,只要有一个过滤器不满足就立刻返回不满足,如果没有过滤器的时候则认为所有过滤器都满足。
*
* @author Payne 646742615@qq.com
* 2018/12/4 15:26
*/ | block_comment | zh-cn | package io.xjar.filter;
import io.xjar.XEntryFilter;
import java.util.Collection;
/**
* ALL <SUF>*/
public class XAllEntryFilter<E> extends XMixEntryFilter<E> implements XEntryFilter<E> {
public XAllEntryFilter() {
super(null);
}
public XAllEntryFilter(Collection<? extends XEntryFilter<? extends E>> filters) {
super(filters);
}
@Override
public XAllEntryFilter<E> mix(XEntryFilter<? extends E> filter) {
add(filter);
return this;
}
@Override
public boolean filtrate(E entry) {
XEntryFilter[] filters = this.filters.toArray(new XEntryFilter[0]);
for (XEntryFilter filter : filters) {
if (!filter.filtrate(entry)) {
return false;
}
}
return true;
}
}
| false | 258 | 79 | 297 | 89 | 302 | 79 | 297 | 89 | 377 | 142 | false | false | false | false | false | true |
38234_15 | package com.action;
import com.common.GameContext;
import com.common.ServiceCollection;
import com.core.GameMessage;
import com.message.TeamProto.C_AgreeInvite;
import com.message.TeamProto.C_ApplyJoinTeam;
import com.message.TeamProto.C_ApplyJoinTeamDeal;
import com.message.TeamProto.C_ChangeCaptain;
import com.message.TeamProto.C_ChangeTarget;
import com.message.TeamProto.C_Follow;
import com.message.TeamProto.C_GetInviteList;
import com.message.TeamProto.C_GetTeamList;
import com.message.TeamProto.C_Invite;
import com.message.TeamProto.C_KickTeamPlayer;
import com.message.TeamProto.C_PlayerAutoMatch;
import com.message.TeamProto.C_TeamAutoMatch;
import com.service.ITeamService;
/**
* 组队接口
* @author ken
* @date 2017-3-2
*/
public class TeamAction {
private ServiceCollection serviceCollection = GameContext.getInstance().getServiceCollection();
/**
* 组队大厅
*/
public void getTeamList(GameMessage gameMessage) throws Exception{
ITeamService teamService = serviceCollection.getTeamService();
long playerId = gameMessage.getConnection().getPlayerId();
C_GetTeamList param = C_GetTeamList.parseFrom(gameMessage.getData());
int activityId = param.getActivityId();
teamService.getTeamList(playerId, activityId);
}
/**
* 创建队伍
*/
public void createTeam(GameMessage gameMessage) throws Exception {
ITeamService teamService = serviceCollection.getTeamService();
long playerId = gameMessage.getConnection().getPlayerId();
teamService.createTeam(playerId);
}
/**
* 选择活动目标
*/
public void changeTarget(GameMessage gameMessage) throws Exception {
ITeamService teamService = serviceCollection.getTeamService();
long playerId = gameMessage.getConnection().getPlayerId();
C_ChangeTarget param = C_ChangeTarget.parseFrom(gameMessage.getData());
int activityId = param.getActivityId();
int minLevel = param.getMinLevel();
teamService.changeTarget(playerId, activityId, minLevel);
}
/**
* 获取社交邀请列表
*/
public void getInviteList(GameMessage gameMessage) throws Exception {
ITeamService teamService = serviceCollection.getTeamService();
long playerId = gameMessage.getConnection().getPlayerId();
C_GetInviteList param = C_GetInviteList.parseFrom(gameMessage.getData());
int type = param.getType();
int start = param.getStart();
int offset = param.getOffset();
teamService.getInviteList(playerId, type, start, offset);
}
/**
* 邀请
*/
public void invite(GameMessage gameMessage) throws Exception {
ITeamService teamService = serviceCollection.getTeamService();
long playerId = gameMessage.getConnection().getPlayerId();
C_Invite param = C_Invite.parseFrom(gameMessage.getData());
long inviterId = param.getInviterId();
teamService.invite(playerId, inviterId);
}
/**
* 同意邀请
*/
public void agreeInvite(GameMessage gameMessage) throws Exception {
ITeamService teamService = serviceCollection.getTeamService();
long playerId = gameMessage.getConnection().getPlayerId();
C_AgreeInvite param = C_AgreeInvite.parseFrom(gameMessage.getData());
int teamId = param.getTeamId();
teamService.agreeInvite(playerId, teamId);
}
/**
* 退出队伍
*/
public void quitTeam(GameMessage gameMessage) throws Exception {
ITeamService teamService = serviceCollection.getTeamService();
long playerId = gameMessage.getConnection().getPlayerId();
teamService.quitTeam(playerId);
}
/**
* 踢队员
*/
public void kickTeamPlayer(GameMessage gameMessage) throws Exception {
ITeamService teamService = serviceCollection.getTeamService();
long playerId = gameMessage.getConnection().getPlayerId();
C_KickTeamPlayer param = C_KickTeamPlayer.parseFrom(gameMessage.getData());
teamService.kickTeamPlayer(playerId, param.getPlayerId());
}
/**
*
* 转让队长
*/
public void changeCaptain(GameMessage gameMessage) throws Exception {
ITeamService teamService = serviceCollection.getTeamService();
long playerId = gameMessage.getConnection().getPlayerId();
C_ChangeCaptain param = C_ChangeCaptain.parseFrom(gameMessage.getData());
teamService.changeCaptain(playerId, param.getPlayerId());
}
/**
* 申请加入队伍
*/
public void applyJoinTeam(GameMessage gameMessage) throws Exception {
ITeamService teamService = serviceCollection.getTeamService();
long playerId = gameMessage.getConnection().getPlayerId();
C_ApplyJoinTeam param = C_ApplyJoinTeam.parseFrom(gameMessage.getData());
int teamId = param.getTeamId();
teamService.applyJoinTeam(playerId, teamId);
}
/**
* 获取申请加入队伍消息
*/
public void getTeamApplyList(GameMessage gameMessage) throws Exception {
ITeamService teamService = serviceCollection.getTeamService();
long playerId = gameMessage.getConnection().getPlayerId();
teamService.getTeamApplyList(playerId);
}
/**
* 加入队伍信息处理
*/
public void applyJoinTeamDeal(GameMessage gameMessage) throws Exception {
ITeamService teamService = serviceCollection.getTeamService();
long playerId = gameMessage.getConnection().getPlayerId();
C_ApplyJoinTeamDeal param = C_ApplyJoinTeamDeal.parseFrom(gameMessage.getData());
long applyPlayerId = param.getApplyPlayerId();
int state = param.getState();
teamService.applyJoinTeamDeal(playerId, applyPlayerId, state);
}
/**
* 玩家自动匹配队伍
*/
public void playerAutoMatch(GameMessage gameMessage) throws Exception {
ITeamService teamService = serviceCollection.getTeamService();
long playerId = gameMessage.getConnection().getPlayerId();
C_PlayerAutoMatch param = C_PlayerAutoMatch.parseFrom(gameMessage.getData());
int activityId = param.getActivityId();
teamService.playerAutoMatch(playerId, activityId);
}
/**
* 队伍自动匹配玩家
*/
public void teamAutoMatch(GameMessage gameMessage) throws Exception {
ITeamService teamService = serviceCollection.getTeamService();
long playerId = gameMessage.getConnection().getPlayerId();
C_TeamAutoMatch param = C_TeamAutoMatch.parseFrom(gameMessage.getData());
teamService.teamAutoMatch(playerId, param.getState());
}
/**
* 跟随
*/
public void follow(GameMessage gameMessage) throws Exception {
ITeamService teamService = serviceCollection.getTeamService();
long playerId = gameMessage.getConnection().getPlayerId();
C_Follow param = C_Follow.parseFrom(gameMessage.getData());
teamService.follow(playerId, param.getState());
}
/**
* 清空队伍申请列表
*/
public void clearTeamApplyList(GameMessage gameMessage) throws Exception {
ITeamService teamService = serviceCollection.getTeamService();
long playerId = gameMessage.getConnection().getPlayerId();
teamService.clearTeamApplyList(playerId);
}
/**
* 自动同意加入申请
*/
public void autoAgreeApply(GameMessage gameMessage) throws Exception {
ITeamService teamService = serviceCollection.getTeamService();
long playerId = gameMessage.getConnection().getPlayerId();
teamService.autoAgreeApply(playerId);
}
/**
* 获取队长位置信息
*/
public void getCaptainPostion(GameMessage gameMessage) throws Exception {
ITeamService teamService = serviceCollection.getTeamService();
long playerId = gameMessage.getConnection().getPlayerId();
teamService.getCaptainPostion(playerId);
}
}
| corefan/xunhai | server/XHGameServer/src/com/action/TeamAction.java | 2,049 | /**
* 跟随
*/ | block_comment | zh-cn | package com.action;
import com.common.GameContext;
import com.common.ServiceCollection;
import com.core.GameMessage;
import com.message.TeamProto.C_AgreeInvite;
import com.message.TeamProto.C_ApplyJoinTeam;
import com.message.TeamProto.C_ApplyJoinTeamDeal;
import com.message.TeamProto.C_ChangeCaptain;
import com.message.TeamProto.C_ChangeTarget;
import com.message.TeamProto.C_Follow;
import com.message.TeamProto.C_GetInviteList;
import com.message.TeamProto.C_GetTeamList;
import com.message.TeamProto.C_Invite;
import com.message.TeamProto.C_KickTeamPlayer;
import com.message.TeamProto.C_PlayerAutoMatch;
import com.message.TeamProto.C_TeamAutoMatch;
import com.service.ITeamService;
/**
* 组队接口
* @author ken
* @date 2017-3-2
*/
public class TeamAction {
private ServiceCollection serviceCollection = GameContext.getInstance().getServiceCollection();
/**
* 组队大厅
*/
public void getTeamList(GameMessage gameMessage) throws Exception{
ITeamService teamService = serviceCollection.getTeamService();
long playerId = gameMessage.getConnection().getPlayerId();
C_GetTeamList param = C_GetTeamList.parseFrom(gameMessage.getData());
int activityId = param.getActivityId();
teamService.getTeamList(playerId, activityId);
}
/**
* 创建队伍
*/
public void createTeam(GameMessage gameMessage) throws Exception {
ITeamService teamService = serviceCollection.getTeamService();
long playerId = gameMessage.getConnection().getPlayerId();
teamService.createTeam(playerId);
}
/**
* 选择活动目标
*/
public void changeTarget(GameMessage gameMessage) throws Exception {
ITeamService teamService = serviceCollection.getTeamService();
long playerId = gameMessage.getConnection().getPlayerId();
C_ChangeTarget param = C_ChangeTarget.parseFrom(gameMessage.getData());
int activityId = param.getActivityId();
int minLevel = param.getMinLevel();
teamService.changeTarget(playerId, activityId, minLevel);
}
/**
* 获取社交邀请列表
*/
public void getInviteList(GameMessage gameMessage) throws Exception {
ITeamService teamService = serviceCollection.getTeamService();
long playerId = gameMessage.getConnection().getPlayerId();
C_GetInviteList param = C_GetInviteList.parseFrom(gameMessage.getData());
int type = param.getType();
int start = param.getStart();
int offset = param.getOffset();
teamService.getInviteList(playerId, type, start, offset);
}
/**
* 邀请
*/
public void invite(GameMessage gameMessage) throws Exception {
ITeamService teamService = serviceCollection.getTeamService();
long playerId = gameMessage.getConnection().getPlayerId();
C_Invite param = C_Invite.parseFrom(gameMessage.getData());
long inviterId = param.getInviterId();
teamService.invite(playerId, inviterId);
}
/**
* 同意邀请
*/
public void agreeInvite(GameMessage gameMessage) throws Exception {
ITeamService teamService = serviceCollection.getTeamService();
long playerId = gameMessage.getConnection().getPlayerId();
C_AgreeInvite param = C_AgreeInvite.parseFrom(gameMessage.getData());
int teamId = param.getTeamId();
teamService.agreeInvite(playerId, teamId);
}
/**
* 退出队伍
*/
public void quitTeam(GameMessage gameMessage) throws Exception {
ITeamService teamService = serviceCollection.getTeamService();
long playerId = gameMessage.getConnection().getPlayerId();
teamService.quitTeam(playerId);
}
/**
* 踢队员
*/
public void kickTeamPlayer(GameMessage gameMessage) throws Exception {
ITeamService teamService = serviceCollection.getTeamService();
long playerId = gameMessage.getConnection().getPlayerId();
C_KickTeamPlayer param = C_KickTeamPlayer.parseFrom(gameMessage.getData());
teamService.kickTeamPlayer(playerId, param.getPlayerId());
}
/**
*
* 转让队长
*/
public void changeCaptain(GameMessage gameMessage) throws Exception {
ITeamService teamService = serviceCollection.getTeamService();
long playerId = gameMessage.getConnection().getPlayerId();
C_ChangeCaptain param = C_ChangeCaptain.parseFrom(gameMessage.getData());
teamService.changeCaptain(playerId, param.getPlayerId());
}
/**
* 申请加入队伍
*/
public void applyJoinTeam(GameMessage gameMessage) throws Exception {
ITeamService teamService = serviceCollection.getTeamService();
long playerId = gameMessage.getConnection().getPlayerId();
C_ApplyJoinTeam param = C_ApplyJoinTeam.parseFrom(gameMessage.getData());
int teamId = param.getTeamId();
teamService.applyJoinTeam(playerId, teamId);
}
/**
* 获取申请加入队伍消息
*/
public void getTeamApplyList(GameMessage gameMessage) throws Exception {
ITeamService teamService = serviceCollection.getTeamService();
long playerId = gameMessage.getConnection().getPlayerId();
teamService.getTeamApplyList(playerId);
}
/**
* 加入队伍信息处理
*/
public void applyJoinTeamDeal(GameMessage gameMessage) throws Exception {
ITeamService teamService = serviceCollection.getTeamService();
long playerId = gameMessage.getConnection().getPlayerId();
C_ApplyJoinTeamDeal param = C_ApplyJoinTeamDeal.parseFrom(gameMessage.getData());
long applyPlayerId = param.getApplyPlayerId();
int state = param.getState();
teamService.applyJoinTeamDeal(playerId, applyPlayerId, state);
}
/**
* 玩家自动匹配队伍
*/
public void playerAutoMatch(GameMessage gameMessage) throws Exception {
ITeamService teamService = serviceCollection.getTeamService();
long playerId = gameMessage.getConnection().getPlayerId();
C_PlayerAutoMatch param = C_PlayerAutoMatch.parseFrom(gameMessage.getData());
int activityId = param.getActivityId();
teamService.playerAutoMatch(playerId, activityId);
}
/**
* 队伍自动匹配玩家
*/
public void teamAutoMatch(GameMessage gameMessage) throws Exception {
ITeamService teamService = serviceCollection.getTeamService();
long playerId = gameMessage.getConnection().getPlayerId();
C_TeamAutoMatch param = C_TeamAutoMatch.parseFrom(gameMessage.getData());
teamService.teamAutoMatch(playerId, param.getState());
}
/**
* 跟随
<SUF>*/
public void follow(GameMessage gameMessage) throws Exception {
ITeamService teamService = serviceCollection.getTeamService();
long playerId = gameMessage.getConnection().getPlayerId();
C_Follow param = C_Follow.parseFrom(gameMessage.getData());
teamService.follow(playerId, param.getState());
}
/**
* 清空队伍申请列表
*/
public void clearTeamApplyList(GameMessage gameMessage) throws Exception {
ITeamService teamService = serviceCollection.getTeamService();
long playerId = gameMessage.getConnection().getPlayerId();
teamService.clearTeamApplyList(playerId);
}
/**
* 自动同意加入申请
*/
public void autoAgreeApply(GameMessage gameMessage) throws Exception {
ITeamService teamService = serviceCollection.getTeamService();
long playerId = gameMessage.getConnection().getPlayerId();
teamService.autoAgreeApply(playerId);
}
/**
* 获取队长位置信息
*/
public void getCaptainPostion(GameMessage gameMessage) throws Exception {
ITeamService teamService = serviceCollection.getTeamService();
long playerId = gameMessage.getConnection().getPlayerId();
teamService.getCaptainPostion(playerId);
}
}
| false | 1,719 | 10 | 2,049 | 8 | 2,064 | 9 | 2,049 | 8 | 2,541 | 14 | false | false | false | false | false | true |
36320_0 | public class Solution {
public List<List<String>> solveNQueens(int n) {
//装n皇后的数组
int[] nums=new int[n];
//答案
List<List<String>> ans=new ArrayList<List<String>>();
int i=0;
while (true) {
//所有可能已经尝试完毕,退出游戏
if (i<0) {
return ans;
}
//成功尝试出一种答案, 装载答案
if (i==n) {
List<String> list=new ArrayList<String>();
for (int j = 0; j < nums.length; j++) {
StringBuffer sb=new StringBuffer();
for (int k = 0; k < n; k++) {
if (k!=nums[j]) {
sb.append(".");
}else {
sb.append("Q");
}
}
list.add(sb.toString());
}
ans.add(list);
//回退
i--;
while (nums[i]==n) {
nums[i]=0;
i--;
}
nums[i]++;
}else {
if (nums[i]==n) {
//回退
while (i>=0&&nums[i]==n) {
nums[i]=0;
i--;
}
if (i>=0) {
nums[i]++;
}
}else {
if (f(nums,i,nums[i])) {
i++;
}else {
nums[i]++;
}
}
}
}
// return ans;
}
public boolean f(int[] nums,int x,int val){
for (int i = 0; i < x; i++) {
int t=x-i;
if (val==nums[i]||val==nums[i]+t||val==nums[i]-t) {
return false;
}
}
return true;
}
} | corpsepiges/leetcode | java/051. N-Queens.java | 441 | //装n皇后的数组 | line_comment | zh-cn | public class Solution {
public List<List<String>> solveNQueens(int n) {
//装n <SUF>
int[] nums=new int[n];
//答案
List<List<String>> ans=new ArrayList<List<String>>();
int i=0;
while (true) {
//所有可能已经尝试完毕,退出游戏
if (i<0) {
return ans;
}
//成功尝试出一种答案, 装载答案
if (i==n) {
List<String> list=new ArrayList<String>();
for (int j = 0; j < nums.length; j++) {
StringBuffer sb=new StringBuffer();
for (int k = 0; k < n; k++) {
if (k!=nums[j]) {
sb.append(".");
}else {
sb.append("Q");
}
}
list.add(sb.toString());
}
ans.add(list);
//回退
i--;
while (nums[i]==n) {
nums[i]=0;
i--;
}
nums[i]++;
}else {
if (nums[i]==n) {
//回退
while (i>=0&&nums[i]==n) {
nums[i]=0;
i--;
}
if (i>=0) {
nums[i]++;
}
}else {
if (f(nums,i,nums[i])) {
i++;
}else {
nums[i]++;
}
}
}
}
// return ans;
}
public boolean f(int[] nums,int x,int val){
for (int i = 0; i < x; i++) {
int t=x-i;
if (val==nums[i]||val==nums[i]+t||val==nums[i]-t) {
return false;
}
}
return true;
}
} | false | 399 | 6 | 441 | 7 | 497 | 6 | 441 | 7 | 597 | 8 | false | false | false | false | false | true |
21830_2 | package lock.waitandnotify;
import basic.method.InterruptDemo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @Classname WaitAndNotifyDemo01
* @Description TODO
* @Date 2021/6/21 13:51
* @Create by Lee
*/
/**
* 线程测试
* 将原来的sleep改为wait和notify的情况
* 多个线程等待的情况
* 使用notify唤醒换成可能造成虚假唤醒情况
* 所以不该采用notify而是采用notifyAll();
* 不过还有有问题,不该唤醒的其他线程造成了虚假唤醒,应该唤醒条件位置写循环判断是否唤醒
*/
public class WaitAndNotifyDemo03 {
static final Object room = new Object();
static boolean condition = false;
static boolean conditionTwo = false;
static Logger log = LoggerFactory.getLogger(InterruptDemo.class);
public static void main(String[] args) {
new Thread(()->{
synchronized (room){
log.debug("有条件嘛:"+condition);
if (!condition){
log.debug("没有条件,开始休息");
//改变原来的代码
try {
// 他会释放锁后面的五个线程会直接执行,因为这里释放了room这个对象的锁
room.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
log.debug("休息完成");
}
log.debug("有条件嘛:[{}]",condition);
if (condition){
log.debug("{} do it.",Thread.currentThread().getName());
}
}
},"第一个线程").start();
new Thread(() -> {
synchronized (room){
log.debug("有条件嘛:"+conditionTwo);
if (!conditionTwo){
log.debug("没有条件,开始休息");
//改变原来的代码
try {
// 他会释放锁后面的五个线程会直接执行,因为这里释放了room这个对象的锁
room.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
log.debug("休息完成");
}
log.debug("有条件嘛:[{}]",conditionTwo);
if (conditionTwo){
log.debug("{} do it.",Thread.currentThread().getName());
}
}
},"第二个线程").start();
for (int i = 0;i < 5;i++){
new Thread(()->{
synchronized (room){
log.debug("{}开始干活",Thread.currentThread().getName());
}
},"其他人").start();
}
sleep(1);
new Thread(()->{
// 改变内容
synchronized (room){
conditionTwo = true;
log.debug("条件开始有了");
//这里改用all就可以回复想要的那个了
// 不过还有有问题
room.notifyAll();
// room.notify();
}
}).start();
}
public static void sleep(int second){
try {
Thread.sleep(second*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| coward-lee/integration | juc/src/main/java/lock/waitandnotify/WaitAndNotifyDemo03.java | 804 | //改变原来的代码 | line_comment | zh-cn | package lock.waitandnotify;
import basic.method.InterruptDemo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @Classname WaitAndNotifyDemo01
* @Description TODO
* @Date 2021/6/21 13:51
* @Create by Lee
*/
/**
* 线程测试
* 将原来的sleep改为wait和notify的情况
* 多个线程等待的情况
* 使用notify唤醒换成可能造成虚假唤醒情况
* 所以不该采用notify而是采用notifyAll();
* 不过还有有问题,不该唤醒的其他线程造成了虚假唤醒,应该唤醒条件位置写循环判断是否唤醒
*/
public class WaitAndNotifyDemo03 {
static final Object room = new Object();
static boolean condition = false;
static boolean conditionTwo = false;
static Logger log = LoggerFactory.getLogger(InterruptDemo.class);
public static void main(String[] args) {
new Thread(()->{
synchronized (room){
log.debug("有条件嘛:"+condition);
if (!condition){
log.debug("没有条件,开始休息");
//改变 <SUF>
try {
// 他会释放锁后面的五个线程会直接执行,因为这里释放了room这个对象的锁
room.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
log.debug("休息完成");
}
log.debug("有条件嘛:[{}]",condition);
if (condition){
log.debug("{} do it.",Thread.currentThread().getName());
}
}
},"第一个线程").start();
new Thread(() -> {
synchronized (room){
log.debug("有条件嘛:"+conditionTwo);
if (!conditionTwo){
log.debug("没有条件,开始休息");
//改变原来的代码
try {
// 他会释放锁后面的五个线程会直接执行,因为这里释放了room这个对象的锁
room.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
log.debug("休息完成");
}
log.debug("有条件嘛:[{}]",conditionTwo);
if (conditionTwo){
log.debug("{} do it.",Thread.currentThread().getName());
}
}
},"第二个线程").start();
for (int i = 0;i < 5;i++){
new Thread(()->{
synchronized (room){
log.debug("{}开始干活",Thread.currentThread().getName());
}
},"其他人").start();
}
sleep(1);
new Thread(()->{
// 改变内容
synchronized (room){
conditionTwo = true;
log.debug("条件开始有了");
//这里改用all就可以回复想要的那个了
// 不过还有有问题
room.notifyAll();
// room.notify();
}
}).start();
}
public static void sleep(int second){
try {
Thread.sleep(second*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| false | 662 | 4 | 804 | 5 | 749 | 4 | 804 | 5 | 1,177 | 8 | false | false | false | false | false | true |
29862_0 | /**
* 门面模式,又叫外观模式
*
* 要求一个子系统的外部与其内部的通信必须通过一个统一的
* 对象进行,门面模式提供一个高层次的接口,使得子系统
* 更易于使用
*
* 这个很简单,也就不敲代码了
*
* public class Facade{
*
* private A a = new A();
* private B b = new B();
* private C c = new C();
*
* public void func1(){}
*
* public void func2(){}
* }
*
* ——这里A,B,C三个类被看做是一个子系统,func1,func2提供的功能
* 必须这三者配合完成,如果由外部直接访问这三个,就比较麻烦且不好扩展,
* 所以这里Facade进行了统一的封装
* ——所以说这是一个很自然的模式,基本上你自己就会想到这样去封装起来
*
*
* 门面模式的缺点在于:
* 1、Facade这个类不能出问题,因为对其的任何修改都是对代码的直接修改,
* 需要谨慎设计
*
* 扩展:
* 1、一个子系统多个门面,这一般是根据业务逻辑划分的
* 例子:
* 邮政系统:
* ——对于寄信者来说,你就提供收信人和邮件内容,至于由多少个对象来给你把
* 这封信送到,这是送信子系统的事,不用你管
* ——对于收信者来说,你就去邮局报自己的名字就行了,或者查看自己的邮箱,至于
* 是谁给你怎么送来的,你也不用关心
*
* 用处:
* ——一个组员水平较差,就对他写的代码封装一个门面,让他烂在自己的代码里,
* 对外部模块没有影响
*/
package com.cowthan.pattern1.facade; | cowthan/JavaAyo | src/com/cowthan/pattern1/facade/package-info.java | 504 | /**
* 门面模式,又叫外观模式
*
* 要求一个子系统的外部与其内部的通信必须通过一个统一的
* 对象进行,门面模式提供一个高层次的接口,使得子系统
* 更易于使用
*
* 这个很简单,也就不敲代码了
*
* public class Facade{
*
* private A a = new A();
* private B b = new B();
* private C c = new C();
*
* public void func1(){}
*
* public void func2(){}
* }
*
* ——这里A,B,C三个类被看做是一个子系统,func1,func2提供的功能
* 必须这三者配合完成,如果由外部直接访问这三个,就比较麻烦且不好扩展,
* 所以这里Facade进行了统一的封装
* ——所以说这是一个很自然的模式,基本上你自己就会想到这样去封装起来
*
*
* 门面模式的缺点在于:
* 1、Facade这个类不能出问题,因为对其的任何修改都是对代码的直接修改,
* 需要谨慎设计
*
* 扩展:
* 1、一个子系统多个门面,这一般是根据业务逻辑划分的
* 例子:
* 邮政系统:
* ——对于寄信者来说,你就提供收信人和邮件内容,至于由多少个对象来给你把
* 这封信送到,这是送信子系统的事,不用你管
* ——对于收信者来说,你就去邮局报自己的名字就行了,或者查看自己的邮箱,至于
* 是谁给你怎么送来的,你也不用关心
*
* 用处:
* ——一个组员水平较差,就对他写的代码封装一个门面,让他烂在自己的代码里,
* 对外部模块没有影响
*/ | block_comment | zh-cn | /**
* 门面模 <SUF>*/
package com.cowthan.pattern1.facade; | false | 448 | 438 | 504 | 492 | 450 | 438 | 504 | 492 | 723 | 710 | true | true | true | true | true | false |
40821_1 | /**
* Copyright 2008 - 2011
*
* 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.
*
* @project loonframework
* @author chenpeng
* @email:ceponline@yahoo.com.cn
* @version 0.1
*/
package loon.srpg.view;
import loon.LTexture;
import loon.canvas.Canvas;
import loon.canvas.Image;
import loon.canvas.LColor;
import loon.canvas.LGradation;
import loon.font.LFont;
import loon.font.Font.Style;
import loon.opengl.GLEx;
import loon.srpg.SRPGType;
import loon.srpg.ability.SRPGAbilityFactory;
import loon.srpg.ability.SRPGDamageData;
import loon.srpg.actor.SRPGActor;
import loon.srpg.actor.SRPGActors;
import loon.srpg.actor.SRPGStatus;
import loon.srpg.field.SRPGField;
// 默认的角色伤害预期试图
public class SRPGDamageExpectView extends SRPGDrawView {
private SRPGDamageData dd;
private SRPGAbilityFactory ab;
private SRPGActor attacker;
private SRPGActor defender;
private final static LColor attackColor = new LColor(255, 220, 220),
recoveryColornew = new LColor(220, 220, 255);
private final static LFont deffont = LFont.getFont("Dialog", Style.PLAIN, 12);
private static LTexture cache;
public SRPGDamageExpectView(SRPGAbilityFactory ability, SRPGField field,
SRPGActors actors, int atk, int def) {
this(ability, field, actors, atk, def, 330, 100);
}
public SRPGDamageExpectView(SRPGAbilityFactory ability, SRPGField field,
SRPGActors actors, int atk, int def, int w, int h) {
setExist(true);
setLock(false);
super.width = w;
super.height = h;
this.attacker = actors.find(atk);
if (def != -1) {
this.defender = actors.find(def);
this.dd = ability.getDamageExpect(field, actors, atk, def);
} else {
this.defender = null;
this.dd = new SRPGDamageData();
this.dd.setGenre(ability.getGenre());
}
this.ab = ability;
}
private void drawLazy(Canvas g) {
float offsetY = -15;
g.setFont(deffont);
LGradation.create(LColor.blue, LColor.black, super.width,
super.height).drawHeight(g, 0, 0);
SRPGStatus status = attacker.getActorStatus();
g.setColor(LColor.black);
g.fillRect(5 + 0, 2 + 0, 80, 3);
if (status.max_hp > 0 && status.hp > 0) {
int i = (status.hp * 80) / status.max_hp;
g.setColor(96, 128, 255);
g.fillRect(5 + 0, 2 + 0, i, 3);
}
g.setColor(LColor.white);
g.drawText("ATTACK", 5 + 0, 15 + offsetY);
g.drawText(status.name, 5 + 0, 75 + offsetY);
g.drawText(String.valueOf(status.hp) + " / "
+ String.valueOf(status.max_hp), 5 + 0, 90 + offsetY);
g.setColor(LColor.white);
g.drawText("DEFENCE", 115 + 0, 15 + offsetY);
if (defender != null) {
SRPGStatus status1 = defender.getActorStatus();
g.setColor(LColor.black);
g.fillRect(115 + 0, 2 + 0, 80, 3);
if (status1.max_hp > 0 && status1.hp > 0) {
int hp = (status1.hp * 80) / status1.max_hp;
g.setColor(96, 128, 255);
g.fillRect(115 + 0, 2 + 0, hp, 3);
}
g.setColor(LColor.white);
g.drawText(status1.name, 115 + 0, 75 + offsetY);
g.drawText(String.valueOf(status1.hp) + " / "
+ String.valueOf(status1.max_hp), 115 + 0, 90 + offsetY);
} else {
g.drawText("- Nothing -", 115 + 0, 75 + offsetY);
}
LColor color = LColor.white;
String s = "";
// 判定使用的技能类型
switch (dd.getGenre()) {
// 普通攻击
case SRPGType.GENRE_ATTACK:
// 魔法伤害
case SRPGType.GENRE_MPDAMAGE:
// 全局伤害
case SRPGType.GENRE_ALLDAMAGE:
s = "ATTACK";
color = attackColor;
break;
// 普通恢复
case SRPGType.GENRE_RECOVERY:
// 魔法恢复
case SRPGType.GENRE_MPRECOVERY:
// 全局恢复
case SRPGType.GENRE_ALLRECOVERY:
s = "RECOVERY";
color = recoveryColornew;
break;
// 辅助技能
case SRPGType.GENRE_HELPER:
// 治疗
case SRPGType.GENRE_CURE:
s = "HELPER";
break;
// 不可用的空技能
case -1:
s = "---";
break;
}
g.drawText("Ability", 230 + 0, 15 + offsetY);
g.drawText(ab.getAbilityName(), 230 + 0, 35 + offsetY);
g.drawText(s, 230 + 0, 60 + 0);
g.drawText("STR", 230 + 0, 75 + offsetY);
g.drawText("HIT", 230 + 0, 90 + offsetY);
String s1 = dd.getHitrateExpectString();
String s2 = dd.getDamageExpectString() + dd.getHelperString();
if (defender == null) {
s1 = "---";
s2 = "---";
}
g.drawText(s1, 260 + 0, 90 + offsetY);
g.setColor(color);
g.drawText(s2, 260 + 0, 75 + offsetY);
}
@Override
public void draw(GLEx gl) {
if (!exist) {
return;
}
if (cache == null) {
Image image = Image.createImage(super.width, super.height);
Canvas g = image.getCanvas();
drawLazy(g);
cache = image.texture();
if (image != null) {
image.close();
image = null;
}
return;
}
gl.resetColor();
gl.draw(cache, super.left, super.top);
gl.draw(attacker.getImage(), 10 + super.left, 20 + super.top);
if (defender != null) {
gl.draw(defender.getImage(), 120 + super.left,
20 + super.top);
}
}
@Override
public boolean isExist() {
boolean exist = super.isExist();
if (!exist) {
if (cache != null) {
cache.close();
cache = null;
}
}
return exist;
}
}
| cping/LGame | Java/Loon-Neo/srpg/loon/srpg/view/SRPGDamageExpectView.java | 2,224 | // 默认的角色伤害预期试图 | line_comment | zh-cn | /**
* Copyright 2008 - 2011
*
* 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.
*
* @project loonframework
* @author chenpeng
* @email:ceponline@yahoo.com.cn
* @version 0.1
*/
package loon.srpg.view;
import loon.LTexture;
import loon.canvas.Canvas;
import loon.canvas.Image;
import loon.canvas.LColor;
import loon.canvas.LGradation;
import loon.font.LFont;
import loon.font.Font.Style;
import loon.opengl.GLEx;
import loon.srpg.SRPGType;
import loon.srpg.ability.SRPGAbilityFactory;
import loon.srpg.ability.SRPGDamageData;
import loon.srpg.actor.SRPGActor;
import loon.srpg.actor.SRPGActors;
import loon.srpg.actor.SRPGStatus;
import loon.srpg.field.SRPGField;
// 默认 <SUF>
public class SRPGDamageExpectView extends SRPGDrawView {
private SRPGDamageData dd;
private SRPGAbilityFactory ab;
private SRPGActor attacker;
private SRPGActor defender;
private final static LColor attackColor = new LColor(255, 220, 220),
recoveryColornew = new LColor(220, 220, 255);
private final static LFont deffont = LFont.getFont("Dialog", Style.PLAIN, 12);
private static LTexture cache;
public SRPGDamageExpectView(SRPGAbilityFactory ability, SRPGField field,
SRPGActors actors, int atk, int def) {
this(ability, field, actors, atk, def, 330, 100);
}
public SRPGDamageExpectView(SRPGAbilityFactory ability, SRPGField field,
SRPGActors actors, int atk, int def, int w, int h) {
setExist(true);
setLock(false);
super.width = w;
super.height = h;
this.attacker = actors.find(atk);
if (def != -1) {
this.defender = actors.find(def);
this.dd = ability.getDamageExpect(field, actors, atk, def);
} else {
this.defender = null;
this.dd = new SRPGDamageData();
this.dd.setGenre(ability.getGenre());
}
this.ab = ability;
}
private void drawLazy(Canvas g) {
float offsetY = -15;
g.setFont(deffont);
LGradation.create(LColor.blue, LColor.black, super.width,
super.height).drawHeight(g, 0, 0);
SRPGStatus status = attacker.getActorStatus();
g.setColor(LColor.black);
g.fillRect(5 + 0, 2 + 0, 80, 3);
if (status.max_hp > 0 && status.hp > 0) {
int i = (status.hp * 80) / status.max_hp;
g.setColor(96, 128, 255);
g.fillRect(5 + 0, 2 + 0, i, 3);
}
g.setColor(LColor.white);
g.drawText("ATTACK", 5 + 0, 15 + offsetY);
g.drawText(status.name, 5 + 0, 75 + offsetY);
g.drawText(String.valueOf(status.hp) + " / "
+ String.valueOf(status.max_hp), 5 + 0, 90 + offsetY);
g.setColor(LColor.white);
g.drawText("DEFENCE", 115 + 0, 15 + offsetY);
if (defender != null) {
SRPGStatus status1 = defender.getActorStatus();
g.setColor(LColor.black);
g.fillRect(115 + 0, 2 + 0, 80, 3);
if (status1.max_hp > 0 && status1.hp > 0) {
int hp = (status1.hp * 80) / status1.max_hp;
g.setColor(96, 128, 255);
g.fillRect(115 + 0, 2 + 0, hp, 3);
}
g.setColor(LColor.white);
g.drawText(status1.name, 115 + 0, 75 + offsetY);
g.drawText(String.valueOf(status1.hp) + " / "
+ String.valueOf(status1.max_hp), 115 + 0, 90 + offsetY);
} else {
g.drawText("- Nothing -", 115 + 0, 75 + offsetY);
}
LColor color = LColor.white;
String s = "";
// 判定使用的技能类型
switch (dd.getGenre()) {
// 普通攻击
case SRPGType.GENRE_ATTACK:
// 魔法伤害
case SRPGType.GENRE_MPDAMAGE:
// 全局伤害
case SRPGType.GENRE_ALLDAMAGE:
s = "ATTACK";
color = attackColor;
break;
// 普通恢复
case SRPGType.GENRE_RECOVERY:
// 魔法恢复
case SRPGType.GENRE_MPRECOVERY:
// 全局恢复
case SRPGType.GENRE_ALLRECOVERY:
s = "RECOVERY";
color = recoveryColornew;
break;
// 辅助技能
case SRPGType.GENRE_HELPER:
// 治疗
case SRPGType.GENRE_CURE:
s = "HELPER";
break;
// 不可用的空技能
case -1:
s = "---";
break;
}
g.drawText("Ability", 230 + 0, 15 + offsetY);
g.drawText(ab.getAbilityName(), 230 + 0, 35 + offsetY);
g.drawText(s, 230 + 0, 60 + 0);
g.drawText("STR", 230 + 0, 75 + offsetY);
g.drawText("HIT", 230 + 0, 90 + offsetY);
String s1 = dd.getHitrateExpectString();
String s2 = dd.getDamageExpectString() + dd.getHelperString();
if (defender == null) {
s1 = "---";
s2 = "---";
}
g.drawText(s1, 260 + 0, 90 + offsetY);
g.setColor(color);
g.drawText(s2, 260 + 0, 75 + offsetY);
}
@Override
public void draw(GLEx gl) {
if (!exist) {
return;
}
if (cache == null) {
Image image = Image.createImage(super.width, super.height);
Canvas g = image.getCanvas();
drawLazy(g);
cache = image.texture();
if (image != null) {
image.close();
image = null;
}
return;
}
gl.resetColor();
gl.draw(cache, super.left, super.top);
gl.draw(attacker.getImage(), 10 + super.left, 20 + super.top);
if (defender != null) {
gl.draw(defender.getImage(), 120 + super.left,
20 + super.top);
}
}
@Override
public boolean isExist() {
boolean exist = super.isExist();
if (!exist) {
if (cache != null) {
cache.close();
cache = null;
}
}
return exist;
}
}
| false | 1,839 | 6 | 2,224 | 11 | 2,113 | 6 | 2,224 | 11 | 2,563 | 19 | false | false | false | false | false | true |
63392_5 | package com.cp.suishouji.adapter;
import java.util.ArrayList;
import java.util.HashMap;
import com.cp.suishouji.R;
import com.cp.suishouji.dao.AccountInfo;
import com.cp.suishouji.utils.MyUtil;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class AccountAdapter extends AbstractAdapter{
private Context context;
private ArrayList<AccountInfo> infoList;//排序后再传进来,parent后面跟着child
private HashMap<Integer, String> nameMap;
private int[] colors = new int[]{R.color.color1,R.color.color2,R.color.color3,R.color.color4,R.color.color5,
R.color.color6,R.color.color7,R.color.color8,R.color.color9,R.color.color10,
R.color.color11,R.color.color12,R.color.color13};
public AccountAdapter(Context context, ArrayList<AccountInfo> infoList) {
super();
this.context = context;
this.infoList = infoList;
//现金,银行卡,公交卡,饭卡,支付宝,信用卡,应付款项,应收款项,公司报销
// nameMap.put(-2, value)
}
@Override
public int getCount() {
return infoList.size();
}
@Override
public int getItemViewType(int position) {
long parentAccountGroupPOID = getItem(position).parentAccountGroupPOID;
if(parentAccountGroupPOID == 1){
return 0;//parent
}else{
return 1;//child
}
}
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public AccountInfo getItem(int position) {
return infoList.get(position);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View layout;
AccountInfo info = getItem(position);
if(getItemViewType(position)==0){
//一级分类
layout = LayoutInflater.from(context).inflate(R.layout.item_account_parent, null);
TextView tv_name = (TextView) layout.findViewById(R.id.tv_name);
TextView tv_money = (TextView) layout.findViewById(R.id.tv_money);
tv_name.setText(info.name);
if(info.type==0){
tv_money.setText(MyUtil.doubleFormate(info.balance));
}else if(info.type==1){
tv_money.setText(MyUtil.doubleFormate(info.amountOfLiability));
}else if(info.type ==2){
tv_money.setText(MyUtil.doubleFormate(info.amountOfCredit));
}
}else{
layout = LayoutInflater.from(context).inflate(R.layout.item_account_child, null);
TextView tv_name = (TextView) layout.findViewById(R.id.tv_name);
TextView tv_money = (TextView) layout.findViewById(R.id.tv_money);
TextView tv_rmb = (TextView) layout.findViewById(R.id.tv_rmb);
tv_name.setText(info.name);
if(info.type==0){
tv_money.setText(MyUtil.doubleFormate(info.balance));
}else if(info.type==1){
tv_money.setText(MyUtil.doubleFormate(info.amountOfLiability));
}else if(info.type ==2){
tv_money.setText(MyUtil.doubleFormate(info.amountOfCredit));
}
// tv_money.setText(MyUtil.doubleFormate(info.balance));
if(info.secgroupname!=null){
tv_rmb.setText("人民币|"+info.secgroupname);
}
}
TextView leftline = (TextView) layout.findViewById(R.id.leftline);
leftline.setBackgroundColor(context.getResources().getColor(colors[position%13]));
return layout;
}
}
| cpoopc/suishouji | src/com/cp/suishouji/adapter/AccountAdapter.java | 1,077 | //一级分类
| line_comment | zh-cn | package com.cp.suishouji.adapter;
import java.util.ArrayList;
import java.util.HashMap;
import com.cp.suishouji.R;
import com.cp.suishouji.dao.AccountInfo;
import com.cp.suishouji.utils.MyUtil;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class AccountAdapter extends AbstractAdapter{
private Context context;
private ArrayList<AccountInfo> infoList;//排序后再传进来,parent后面跟着child
private HashMap<Integer, String> nameMap;
private int[] colors = new int[]{R.color.color1,R.color.color2,R.color.color3,R.color.color4,R.color.color5,
R.color.color6,R.color.color7,R.color.color8,R.color.color9,R.color.color10,
R.color.color11,R.color.color12,R.color.color13};
public AccountAdapter(Context context, ArrayList<AccountInfo> infoList) {
super();
this.context = context;
this.infoList = infoList;
//现金,银行卡,公交卡,饭卡,支付宝,信用卡,应付款项,应收款项,公司报销
// nameMap.put(-2, value)
}
@Override
public int getCount() {
return infoList.size();
}
@Override
public int getItemViewType(int position) {
long parentAccountGroupPOID = getItem(position).parentAccountGroupPOID;
if(parentAccountGroupPOID == 1){
return 0;//parent
}else{
return 1;//child
}
}
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public AccountInfo getItem(int position) {
return infoList.get(position);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View layout;
AccountInfo info = getItem(position);
if(getItemViewType(position)==0){
//一级 <SUF>
layout = LayoutInflater.from(context).inflate(R.layout.item_account_parent, null);
TextView tv_name = (TextView) layout.findViewById(R.id.tv_name);
TextView tv_money = (TextView) layout.findViewById(R.id.tv_money);
tv_name.setText(info.name);
if(info.type==0){
tv_money.setText(MyUtil.doubleFormate(info.balance));
}else if(info.type==1){
tv_money.setText(MyUtil.doubleFormate(info.amountOfLiability));
}else if(info.type ==2){
tv_money.setText(MyUtil.doubleFormate(info.amountOfCredit));
}
}else{
layout = LayoutInflater.from(context).inflate(R.layout.item_account_child, null);
TextView tv_name = (TextView) layout.findViewById(R.id.tv_name);
TextView tv_money = (TextView) layout.findViewById(R.id.tv_money);
TextView tv_rmb = (TextView) layout.findViewById(R.id.tv_rmb);
tv_name.setText(info.name);
if(info.type==0){
tv_money.setText(MyUtil.doubleFormate(info.balance));
}else if(info.type==1){
tv_money.setText(MyUtil.doubleFormate(info.amountOfLiability));
}else if(info.type ==2){
tv_money.setText(MyUtil.doubleFormate(info.amountOfCredit));
}
// tv_money.setText(MyUtil.doubleFormate(info.balance));
if(info.secgroupname!=null){
tv_rmb.setText("人民币|"+info.secgroupname);
}
}
TextView leftline = (TextView) layout.findViewById(R.id.leftline);
leftline.setBackgroundColor(context.getResources().getColor(colors[position%13]));
return layout;
}
}
| false | 762 | 4 | 1,068 | 5 | 1,042 | 4 | 1,068 | 5 | 1,228 | 8 | false | false | false | false | false | true |
46701_9 | package com.njxz.exam.util;
/*
* 将难易程度做成可配置(但是只能配置一次)
* 常量类
* */
public class Constants {
//difficulty_level难度系数取值
public static Double DIFFICULTY_LEVEL_VERYEASY=(double) 0.1;
public static Double DIFFICULTY_LEVEL_EASY=(double) 0.3;
public static Double DIFFICULTY_LEVEL_MEDIUM=(double) 0.5;
public static Double DIFFICULTY_LEVEL_HARD=(double) 0.7;
public static Double DIFFICULTY_LEVEL_VERYHARD=(double) 0.9;
public static double KP_COVERAGE_RATE = 0;//知识点覆盖率 占 适应度 比率
public static double DIFFICULTY_RATE = 1;//难度系数 占 适应度比率
//期望适应度
public static double EXPAND_ADATPER=0.95;
//最大迭代次数
public static int RUN_Count=500;
//上传图片存放位置
public static String PHOTO_DIRECTORY_NAME="upload";
//word模板存放位置
public static String WORD_TEMPLETE_DIRECTORY_NAME="wordTemplete";
public static String CHINESE_1="一";
//得到1-20之间的中文数字
public static String numGetChinese(int i) {
if(i<=0||i>20) {
return "";
}
switch (i) {
case 1:
return "一";
case 2:
return "二";
case 3:
return "三";
case 4:
return "四";
case 5:
return "五";
case 6:
return "六";
case 7:
return "七";
case 8:
return "八";
case 9:
return "九";
case 10:
return "十";
case 11:
return "十一";
case 12:
return "十二";
case 13:
return "十三";
case 14:
return "十四";
case 15:
return "十五";
case 16:
return "十六";
case 17:
return "十七";
case 18:
return "十八";
case 19:
return "十九";
case 20:
return "二十";
default:
return "";
}
}
//得到困难度的中文
public static String getDiffLevelStrCN(Double level) {
String levelCN="";
if((level-DIFFICULTY_LEVEL_VERYEASY)<0.0001&&(level-DIFFICULTY_LEVEL_VERYEASY)>-0.0001) {
levelCN="很容易";
}
if((level-DIFFICULTY_LEVEL_EASY)<0.0001&&(level-DIFFICULTY_LEVEL_EASY)>-0.0001) {
levelCN="容易";
}
if((level-DIFFICULTY_LEVEL_MEDIUM)<0.0001&&(level-DIFFICULTY_LEVEL_MEDIUM)>-0.0001) {
levelCN="中等";
}
if((level-DIFFICULTY_LEVEL_HARD)<0.0001&&(level-DIFFICULTY_LEVEL_HARD)>-0.0001) {
levelCN="困难";
}
if((level-DIFFICULTY_LEVEL_VERYHARD)<0.0001&&(level-DIFFICULTY_LEVEL_VERYHARD)>-0.0001) {
levelCN="很困难";
}
return levelCN;
}
public static String getDiffLevelStrEN(Double level) {
String levelEN="";
if((level-DIFFICULTY_LEVEL_VERYEASY)<0.0001&&(level-DIFFICULTY_LEVEL_VERYEASY)>-0.0001) {
levelEN="veryEasy";
}
if((level-DIFFICULTY_LEVEL_EASY)<0.0001&&(level-DIFFICULTY_LEVEL_EASY)>-0.0001) {
levelEN="easy";
}
if((level-DIFFICULTY_LEVEL_MEDIUM)<0.0001&&(level-DIFFICULTY_LEVEL_MEDIUM)>-0.0001) {
levelEN="medium";
}
if((level-DIFFICULTY_LEVEL_HARD)<0.0001&&(level-DIFFICULTY_LEVEL_HARD)>-0.0001) {
levelEN="hard";
}
if((level-DIFFICULTY_LEVEL_VERYHARD)<0.0001&&(level-DIFFICULTY_LEVEL_VERYHARD)>-0.0001) {
levelEN="veryHard";
}
return levelEN;
}
}
| cppcpp/exam-system | src/main/java/com/njxz/exam/util/Constants.java | 1,276 | //得到困难度的中文
| line_comment | zh-cn | package com.njxz.exam.util;
/*
* 将难易程度做成可配置(但是只能配置一次)
* 常量类
* */
public class Constants {
//difficulty_level难度系数取值
public static Double DIFFICULTY_LEVEL_VERYEASY=(double) 0.1;
public static Double DIFFICULTY_LEVEL_EASY=(double) 0.3;
public static Double DIFFICULTY_LEVEL_MEDIUM=(double) 0.5;
public static Double DIFFICULTY_LEVEL_HARD=(double) 0.7;
public static Double DIFFICULTY_LEVEL_VERYHARD=(double) 0.9;
public static double KP_COVERAGE_RATE = 0;//知识点覆盖率 占 适应度 比率
public static double DIFFICULTY_RATE = 1;//难度系数 占 适应度比率
//期望适应度
public static double EXPAND_ADATPER=0.95;
//最大迭代次数
public static int RUN_Count=500;
//上传图片存放位置
public static String PHOTO_DIRECTORY_NAME="upload";
//word模板存放位置
public static String WORD_TEMPLETE_DIRECTORY_NAME="wordTemplete";
public static String CHINESE_1="一";
//得到1-20之间的中文数字
public static String numGetChinese(int i) {
if(i<=0||i>20) {
return "";
}
switch (i) {
case 1:
return "一";
case 2:
return "二";
case 3:
return "三";
case 4:
return "四";
case 5:
return "五";
case 6:
return "六";
case 7:
return "七";
case 8:
return "八";
case 9:
return "九";
case 10:
return "十";
case 11:
return "十一";
case 12:
return "十二";
case 13:
return "十三";
case 14:
return "十四";
case 15:
return "十五";
case 16:
return "十六";
case 17:
return "十七";
case 18:
return "十八";
case 19:
return "十九";
case 20:
return "二十";
default:
return "";
}
}
//得到 <SUF>
public static String getDiffLevelStrCN(Double level) {
String levelCN="";
if((level-DIFFICULTY_LEVEL_VERYEASY)<0.0001&&(level-DIFFICULTY_LEVEL_VERYEASY)>-0.0001) {
levelCN="很容易";
}
if((level-DIFFICULTY_LEVEL_EASY)<0.0001&&(level-DIFFICULTY_LEVEL_EASY)>-0.0001) {
levelCN="容易";
}
if((level-DIFFICULTY_LEVEL_MEDIUM)<0.0001&&(level-DIFFICULTY_LEVEL_MEDIUM)>-0.0001) {
levelCN="中等";
}
if((level-DIFFICULTY_LEVEL_HARD)<0.0001&&(level-DIFFICULTY_LEVEL_HARD)>-0.0001) {
levelCN="困难";
}
if((level-DIFFICULTY_LEVEL_VERYHARD)<0.0001&&(level-DIFFICULTY_LEVEL_VERYHARD)>-0.0001) {
levelCN="很困难";
}
return levelCN;
}
public static String getDiffLevelStrEN(Double level) {
String levelEN="";
if((level-DIFFICULTY_LEVEL_VERYEASY)<0.0001&&(level-DIFFICULTY_LEVEL_VERYEASY)>-0.0001) {
levelEN="veryEasy";
}
if((level-DIFFICULTY_LEVEL_EASY)<0.0001&&(level-DIFFICULTY_LEVEL_EASY)>-0.0001) {
levelEN="easy";
}
if((level-DIFFICULTY_LEVEL_MEDIUM)<0.0001&&(level-DIFFICULTY_LEVEL_MEDIUM)>-0.0001) {
levelEN="medium";
}
if((level-DIFFICULTY_LEVEL_HARD)<0.0001&&(level-DIFFICULTY_LEVEL_HARD)>-0.0001) {
levelEN="hard";
}
if((level-DIFFICULTY_LEVEL_VERYHARD)<0.0001&&(level-DIFFICULTY_LEVEL_VERYHARD)>-0.0001) {
levelEN="veryHard";
}
return levelEN;
}
}
| false | 1,089 | 7 | 1,272 | 9 | 1,227 | 6 | 1,272 | 9 | 1,654 | 14 | false | false | false | false | false | true |
37478_2 | import java.awt.*;
import java.awt.event.*;
public class MovingBall {
public static void main(String[] args) {
FFrame f = new FFrame();
f.setSize(500, 500);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
f.show();
}
}
class FFrame extends Frame implements Runnable {
Thread th;
Ball myBall1;
Ball myBall2;
private boolean enable = true;
private int counter = 0;
FFrame() {
th = new Thread(this);
th.start();
}
public void run() {
myBall1 = new Ball();
myBall1.setPosition(200, 150);
myBall1.setR(10);
myBall1.setColor(Color.RED);
myBall2 = new Ball();
myBall2.setPosition(50, 250);
myBall2.setR(20);
myBall2.setColor(Color.GREEN);
while (enable) {
try {
th.sleep(100);
counter++;
if (counter >= 200) enable = false;
} catch (InterruptedException e) {
}
myBall1.move();
myBall2.move();
repaint(); // paint()メソッドが呼び出される
}
}
public void paint(Graphics g) {
myBall1.draw(g);
myBall2.draw(g);
}
// Ball というインナークラスを作る
class Ball {
int x;
int y;
int r; // 半径
Color c = Color.RED;
int xDir = 1; // 1:+方向 -1: -方向
int yDir = 1;
void setColor(Color c) {
this.c = c;
}
void move() {
if ((xDir == 1) && (x >= 300)) {
xDir = -1;
}
if ((xDir == -1) && (x <= 100)) {
xDir = 1;
}
if (xDir == 1) {
x = x + 10;
} else {
x = x - 10;
}
if ((yDir == 1) && (y >= 300)) {
yDir = -1;
}
if ((yDir == -1) && (y <= 100)) {
yDir = 1;
}
if (yDir == 1) {
y = y + 10;
} else {
y = y - 10;
}
}
void setPosition(int x, int y) {
this.x = x;
this.y = y;
}
void setR(int r) {
this.r = r;
}
void draw(Graphics g) {
g.setColor(c);
g.fillOval(x, y, 2 * r, 2 * r); // rは半径なので2倍にする
}
}//innner class Ball end
}
| cpslab/internet_programming | src/MovingBall.java | 749 | // 半径
| line_comment | zh-cn | import java.awt.*;
import java.awt.event.*;
public class MovingBall {
public static void main(String[] args) {
FFrame f = new FFrame();
f.setSize(500, 500);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
f.show();
}
}
class FFrame extends Frame implements Runnable {
Thread th;
Ball myBall1;
Ball myBall2;
private boolean enable = true;
private int counter = 0;
FFrame() {
th = new Thread(this);
th.start();
}
public void run() {
myBall1 = new Ball();
myBall1.setPosition(200, 150);
myBall1.setR(10);
myBall1.setColor(Color.RED);
myBall2 = new Ball();
myBall2.setPosition(50, 250);
myBall2.setR(20);
myBall2.setColor(Color.GREEN);
while (enable) {
try {
th.sleep(100);
counter++;
if (counter >= 200) enable = false;
} catch (InterruptedException e) {
}
myBall1.move();
myBall2.move();
repaint(); // paint()メソッドが呼び出される
}
}
public void paint(Graphics g) {
myBall1.draw(g);
myBall2.draw(g);
}
// Ball というインナークラスを作る
class Ball {
int x;
int y;
int r; // 半径 <SUF>
Color c = Color.RED;
int xDir = 1; // 1:+方向 -1: -方向
int yDir = 1;
void setColor(Color c) {
this.c = c;
}
void move() {
if ((xDir == 1) && (x >= 300)) {
xDir = -1;
}
if ((xDir == -1) && (x <= 100)) {
xDir = 1;
}
if (xDir == 1) {
x = x + 10;
} else {
x = x - 10;
}
if ((yDir == 1) && (y >= 300)) {
yDir = -1;
}
if ((yDir == -1) && (y <= 100)) {
yDir = 1;
}
if (yDir == 1) {
y = y + 10;
} else {
y = y - 10;
}
}
void setPosition(int x, int y) {
this.x = x;
this.y = y;
}
void setR(int r) {
this.r = r;
}
void draw(Graphics g) {
g.setColor(c);
g.fillOval(x, y, 2 * r, 2 * r); // rは半径なので2倍にする
}
}//innner class Ball end
}
| false | 688 | 5 | 743 | 5 | 818 | 4 | 743 | 5 | 925 | 9 | false | false | false | false | false | true |
29905_7 | package com.cq.valuegenerator;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import com.cq.common.CodeUtils;
import com.cq.file.FileUtils;
import com.github.javafaker.Faker;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.PsiParameterList;
import com.intellij.psi.PsiType;
import com.intellij.psi.util.PsiUtil;
import static com.intellij.openapi.actionSystem.CommonDataKeys.PSI_ELEMENT;
/**
* 系统环境变量
*
* @author 有尘
* @date 2021/9/29
*/
public class ValueContext {
public static ValueContext INSTANCE = new ValueContext();
public static boolean isJsonFileSource = false;
Faker faker = new Faker();
/**
* 事件
*/
public static AnActionEvent event;
/**
* 目标java类
*/
public static PsiClass psiClass;
/**
* java文件
*/
public static PsiFile psiFile;
/**
* 测试文件路径
*/
public static String filePath;
/**
* 测试文件名称
*/
public static String fileName;
/**
* 测试文件路径
*/
public static Path path;
public static PsiClass getPsiClass() {
return psiClass;
}
public static PsiFile getPsiFile() {
return psiFile;
}
public static String getFilePath() {
return filePath;
}
public static String getFileName() {
return fileName;
}
public static Path getPath() {
return path;
}
public static void setEvent(AnActionEvent e) {
event = e;
psiClass = PsiUtil.getTopLevelClass(event.getData(PSI_ELEMENT));
psiFile = event.getData(CommonDataKeys.PSI_FILE);
filePath = FileUtils.getUnitFilePath(psiFile);
fileName = FileUtils.genJavaFileName(psiClass);
path = Paths.get(filePath, fileName);
}
public static AnActionEvent getEvent() {
return event;
}
public static void setIsJsonFileSource(boolean v) {
isJsonFileSource = v;
}
public static boolean isJsonFileSource() {
return isJsonFileSource;
}
public static ValueContext getContext() {
return INSTANCE;
}
private final Map<String, PsiClass> cachedCLass = Collections.synchronizedMap(new HashMap<>());
private final Map<String, PsiMethod> cachedMethod = Collections.synchronizedMap(new HashMap<>());
public Faker getFaker() {
return faker;
}
public void loadClass(PsiClass psiClass) {
Arrays.stream(psiClass.getAllFields())
.filter(a -> !CodeUtils.isPrimitiveType(a.getType()))
.forEach(field -> {
String fieldTypeName = field.getType().getCanonicalText();
PsiClass psiClass1 = PsiUtil.resolveClassInClassTypeOnly(field.getType());
if (psiClass1 != null) {
cachedCLass.put(fieldTypeName, psiClass1);
PsiMethod[] methods = psiClass1.getAllMethods();
for (PsiMethod a : methods) {
if (!a.getModifierList().hasModifierProperty("private")) {
// 参数列表
PsiParameterList parameterList = a.getParameterList();
String name = fieldTypeName + a.getName() + parameterList.getParametersCount();
String shortName = field.getType().getPresentableText() + a.getName() + parameterList
.getParametersCount();
System.out.println("cache method: " + name);
cachedMethod.put(name, a);
cachedMethod.put(shortName, a);
for (int i = 0; i < parameterList.getParametersCount(); i++) {
PsiType fieldArgType = parameterList.getParameter(i).getType();
PsiClass fieldArgClass = PsiUtil.resolveClassInClassTypeOnly(fieldArgType);
cachedCLass.put(fieldArgType.getCanonicalText(), fieldArgClass);
}
}
}
}
}
);
}
public PsiClass getClass(String typeName) {
return cachedCLass.get(typeName);
}
public PsiMethod getMethod(String className, String methodName, int argSize) {
return getMethod(className + methodName + argSize);
}
public PsiMethod getMethod(String methodKey) {
return cachedMethod.get(methodKey);
}
public void clear() {
cachedCLass.clear();
cachedMethod.clear();
}
}
| cq1228/junit5TestCodeHelper | ValueContext.java | 1,109 | // 参数列表 | line_comment | zh-cn | package com.cq.valuegenerator;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import com.cq.common.CodeUtils;
import com.cq.file.FileUtils;
import com.github.javafaker.Faker;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.PsiParameterList;
import com.intellij.psi.PsiType;
import com.intellij.psi.util.PsiUtil;
import static com.intellij.openapi.actionSystem.CommonDataKeys.PSI_ELEMENT;
/**
* 系统环境变量
*
* @author 有尘
* @date 2021/9/29
*/
public class ValueContext {
public static ValueContext INSTANCE = new ValueContext();
public static boolean isJsonFileSource = false;
Faker faker = new Faker();
/**
* 事件
*/
public static AnActionEvent event;
/**
* 目标java类
*/
public static PsiClass psiClass;
/**
* java文件
*/
public static PsiFile psiFile;
/**
* 测试文件路径
*/
public static String filePath;
/**
* 测试文件名称
*/
public static String fileName;
/**
* 测试文件路径
*/
public static Path path;
public static PsiClass getPsiClass() {
return psiClass;
}
public static PsiFile getPsiFile() {
return psiFile;
}
public static String getFilePath() {
return filePath;
}
public static String getFileName() {
return fileName;
}
public static Path getPath() {
return path;
}
public static void setEvent(AnActionEvent e) {
event = e;
psiClass = PsiUtil.getTopLevelClass(event.getData(PSI_ELEMENT));
psiFile = event.getData(CommonDataKeys.PSI_FILE);
filePath = FileUtils.getUnitFilePath(psiFile);
fileName = FileUtils.genJavaFileName(psiClass);
path = Paths.get(filePath, fileName);
}
public static AnActionEvent getEvent() {
return event;
}
public static void setIsJsonFileSource(boolean v) {
isJsonFileSource = v;
}
public static boolean isJsonFileSource() {
return isJsonFileSource;
}
public static ValueContext getContext() {
return INSTANCE;
}
private final Map<String, PsiClass> cachedCLass = Collections.synchronizedMap(new HashMap<>());
private final Map<String, PsiMethod> cachedMethod = Collections.synchronizedMap(new HashMap<>());
public Faker getFaker() {
return faker;
}
public void loadClass(PsiClass psiClass) {
Arrays.stream(psiClass.getAllFields())
.filter(a -> !CodeUtils.isPrimitiveType(a.getType()))
.forEach(field -> {
String fieldTypeName = field.getType().getCanonicalText();
PsiClass psiClass1 = PsiUtil.resolveClassInClassTypeOnly(field.getType());
if (psiClass1 != null) {
cachedCLass.put(fieldTypeName, psiClass1);
PsiMethod[] methods = psiClass1.getAllMethods();
for (PsiMethod a : methods) {
if (!a.getModifierList().hasModifierProperty("private")) {
// 参数 <SUF>
PsiParameterList parameterList = a.getParameterList();
String name = fieldTypeName + a.getName() + parameterList.getParametersCount();
String shortName = field.getType().getPresentableText() + a.getName() + parameterList
.getParametersCount();
System.out.println("cache method: " + name);
cachedMethod.put(name, a);
cachedMethod.put(shortName, a);
for (int i = 0; i < parameterList.getParametersCount(); i++) {
PsiType fieldArgType = parameterList.getParameter(i).getType();
PsiClass fieldArgClass = PsiUtil.resolveClassInClassTypeOnly(fieldArgType);
cachedCLass.put(fieldArgType.getCanonicalText(), fieldArgClass);
}
}
}
}
}
);
}
public PsiClass getClass(String typeName) {
return cachedCLass.get(typeName);
}
public PsiMethod getMethod(String className, String methodName, int argSize) {
return getMethod(className + methodName + argSize);
}
public PsiMethod getMethod(String methodKey) {
return cachedMethod.get(methodKey);
}
public void clear() {
cachedCLass.clear();
cachedMethod.clear();
}
}
| false | 993 | 3 | 1,109 | 3 | 1,208 | 3 | 1,109 | 3 | 1,401 | 6 | false | false | false | false | false | true |
35004_0 | package com.charlie.ev3;
/**
* EV3红外传感器的模式。
*/
public enum IRMode {
/**
* 接近。
*/
PROXIMITY,
/**
* 寻找。
*/
SEEK,
/**
* EV3遥控器控制。
*/
REMOTE,
REMOTE_A,
SA_LT,
/**
* 校准。
*/
CALIBRATE
}
| cqjjjzr/LEGO-MINDSTORMS-EV3-Android-API | legoev3/src/main/java/com/charlie/ev3/IRMode.java | 108 | /**
* EV3红外传感器的模式。
*/ | block_comment | zh-cn | package com.charlie.ev3;
/**
* EV3 <SUF>*/
public enum IRMode {
/**
* 接近。
*/
PROXIMITY,
/**
* 寻找。
*/
SEEK,
/**
* EV3遥控器控制。
*/
REMOTE,
REMOTE_A,
SA_LT,
/**
* 校准。
*/
CALIBRATE
}
| false | 92 | 10 | 108 | 15 | 115 | 14 | 108 | 15 | 146 | 19 | false | false | false | false | false | true |
25670_1 | package real;
import java.util.Arrays;
import java.util.Scanner;
/**
* @ClassName 座位安排
* @Description 假设班主任需要为N名学生安排座位,现在有M张桌子,每张桌子可以供一名学生单独使用,也可以供两名学生共同使用,共用一张桌子的两名学生便称为同桌。班主任为所有学生评估出淘气值,第i名学生的淘气值为Ai,如果同桌两人淘气值之和过高,便容易产生矛盾。那么班主任该如何安排座位,使得淘气值之和最大的两名同桌,其淘气值之和尽可能小? 输入 第一行包含两个整数N和M,1≤M<N≤105且N≤M×2。 第二行包含N个整数A1到AN,0≤Ai≤109。 (数字间均以空格隔开) 输出 输出淘气值之和最大的两名同桌,其淘气值之和可能的最小值。 样例输入 5 3 4 1 8 2 6 样例输出 7 Hint 安排第1名与第4名学生共用一张桌子,两人淘气值之和为6;第2名与第5名学生共用一张桌子,两人淘气值之和为7;第3名学生单独用一张桌子。
* @Author cqutwangyu
* @DateTime 2019/3/7 19:26
* @GitHub https://github.com/cqutwangyu
*/
public class 座位安排 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//人数
int N = sc.nextInt();
//桌子
int M = sc.nextInt();
int count = 0;
int[] arr = new int[N];
while (count < N) {
arr[count] = sc.nextInt();
count++;
}
//从小到大排序
Arrays.sort(arr);
//单人坐
while (M * 2 > N) {
N--;
M--;
}
//取淘气值最低的和非单人座淘气值最高的之和
System.out.println(arr[0] + arr[N - 1]);
sc.close();
}
}
| cqutwangyu/Java-Algorithm-Notes | src/real/座位安排.java | 612 | //从小到大排序 | line_comment | zh-cn | package real;
import java.util.Arrays;
import java.util.Scanner;
/**
* @ClassName 座位安排
* @Description 假设班主任需要为N名学生安排座位,现在有M张桌子,每张桌子可以供一名学生单独使用,也可以供两名学生共同使用,共用一张桌子的两名学生便称为同桌。班主任为所有学生评估出淘气值,第i名学生的淘气值为Ai,如果同桌两人淘气值之和过高,便容易产生矛盾。那么班主任该如何安排座位,使得淘气值之和最大的两名同桌,其淘气值之和尽可能小? 输入 第一行包含两个整数N和M,1≤M<N≤105且N≤M×2。 第二行包含N个整数A1到AN,0≤Ai≤109。 (数字间均以空格隔开) 输出 输出淘气值之和最大的两名同桌,其淘气值之和可能的最小值。 样例输入 5 3 4 1 8 2 6 样例输出 7 Hint 安排第1名与第4名学生共用一张桌子,两人淘气值之和为6;第2名与第5名学生共用一张桌子,两人淘气值之和为7;第3名学生单独用一张桌子。
* @Author cqutwangyu
* @DateTime 2019/3/7 19:26
* @GitHub https://github.com/cqutwangyu
*/
public class 座位安排 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//人数
int N = sc.nextInt();
//桌子
int M = sc.nextInt();
int count = 0;
int[] arr = new int[N];
while (count < N) {
arr[count] = sc.nextInt();
count++;
}
//从小 <SUF>
Arrays.sort(arr);
//单人坐
while (M * 2 > N) {
N--;
M--;
}
//取淘气值最低的和非单人座淘气值最高的之和
System.out.println(arr[0] + arr[N - 1]);
sc.close();
}
}
| false | 508 | 5 | 612 | 6 | 548 | 4 | 612 | 6 | 793 | 9 | false | false | false | false | false | true |
20865_7 | package com.chengzw.util;
import io.jsonwebtoken.*;
import java.security.Key;
import java.util.Date;
import java.util.Map;
/**
* JWT基础工具类
* @author 程治玮
* @since 2021/5/3 10:43 上午
*/
public class JwtUtils {
/**
* jwt解密,需要密钥和token,如果解密失败,说明token无效
* @param jsonWebToken
* @param signingKey
* @return
*/
public static Claims parseJWT(String jsonWebToken, Key signingKey) {
try {
Claims claims = Jwts.parser()
.setSigningKey(signingKey)
.parseClaimsJws(jsonWebToken)
.getBody();
return claims;
} catch (JwtException ex) {
return null;
}
}
/**
* 创建token
* jwt = 头部(至少指定算法) + 身体(JWT编码的所有声明) + 签名(将标题和正文的组合通过标题中指定的算法计算得出)
* jws:JWT可以加密签名成为jws
* @param map 主题,也差不多是个人的一些信息,为了好的移植,采用了map放个人信息,而没有采用JSON
* @param audience 发送谁
* @param issuer 个人签名
* @param jwtId 相当于jwt的主键,不能重复
* @param TTLMillis Token过期时间
* @param signingKey 生成签名密钥
* @return
*/
public static String createJWT(Map map, String audience, String issuer, String jwtId, long TTLMillis, Key signingKey,SignatureAlgorithm signatureAlgorithm) {
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
//添加构成JWT的参数
JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT")
.setIssuedAt(now)
.setSubject(map.toString())
.setIssuer(issuer)
.setId(jwtId)
.setAudience(audience)
.signWith(signingKey, signatureAlgorithm); //设置签名使用的签名算法和签名使用的秘钥
//添加Token过期时间
if (TTLMillis >= 0) {
// 过期时间
long expMillis = nowMillis + TTLMillis;
// 现在是什么时间
Date exp = new Date(expMillis);
// 系统时间之前的token都是不可以被承认的
builder.setExpiration(exp).setNotBefore(now);
}
//生成JWS(加密后的JWT)
return builder.compact();
}
} | cr7258/jwt-lab | src/main/java/com/chengzw/util/JwtUtils.java | 607 | // 现在是什么时间 | line_comment | zh-cn | package com.chengzw.util;
import io.jsonwebtoken.*;
import java.security.Key;
import java.util.Date;
import java.util.Map;
/**
* JWT基础工具类
* @author 程治玮
* @since 2021/5/3 10:43 上午
*/
public class JwtUtils {
/**
* jwt解密,需要密钥和token,如果解密失败,说明token无效
* @param jsonWebToken
* @param signingKey
* @return
*/
public static Claims parseJWT(String jsonWebToken, Key signingKey) {
try {
Claims claims = Jwts.parser()
.setSigningKey(signingKey)
.parseClaimsJws(jsonWebToken)
.getBody();
return claims;
} catch (JwtException ex) {
return null;
}
}
/**
* 创建token
* jwt = 头部(至少指定算法) + 身体(JWT编码的所有声明) + 签名(将标题和正文的组合通过标题中指定的算法计算得出)
* jws:JWT可以加密签名成为jws
* @param map 主题,也差不多是个人的一些信息,为了好的移植,采用了map放个人信息,而没有采用JSON
* @param audience 发送谁
* @param issuer 个人签名
* @param jwtId 相当于jwt的主键,不能重复
* @param TTLMillis Token过期时间
* @param signingKey 生成签名密钥
* @return
*/
public static String createJWT(Map map, String audience, String issuer, String jwtId, long TTLMillis, Key signingKey,SignatureAlgorithm signatureAlgorithm) {
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
//添加构成JWT的参数
JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT")
.setIssuedAt(now)
.setSubject(map.toString())
.setIssuer(issuer)
.setId(jwtId)
.setAudience(audience)
.signWith(signingKey, signatureAlgorithm); //设置签名使用的签名算法和签名使用的秘钥
//添加Token过期时间
if (TTLMillis >= 0) {
// 过期时间
long expMillis = nowMillis + TTLMillis;
// 现在 <SUF>
Date exp = new Date(expMillis);
// 系统时间之前的token都是不可以被承认的
builder.setExpiration(exp).setNotBefore(now);
}
//生成JWS(加密后的JWT)
return builder.compact();
}
} | false | 588 | 7 | 607 | 6 | 615 | 5 | 607 | 6 | 844 | 11 | false | false | false | false | false | true |
31080_1 | /*
*
影厅类:
属性: 编号 排数 列数.
行为: 显示座位表、占座.
*/
public class yingTing {
private int num; // 影厅编号
private int row;
private int column;
private dianYing dy;
public void showInfoSeat(){
System.out.println("该厅为影院的"+num+"号厅。");
dy.showInfo();
}
public yingTing(int num, int row, int column,dianYing dy) {
super();
this.num = num;
this.row = row;
this.column = column;
this.dy = dy;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public int getRow() {
return row;
}
public void setRow(int row) {
this.row = row;
}
public int getColumn() {
return column;
}
public void setColumn(int column) {
this.column = column;
}
}
| cratd/FilmDemo | yingTing.java | 300 | // 影厅编号
| line_comment | zh-cn | /*
*
影厅类:
属性: 编号 排数 列数.
行为: 显示座位表、占座.
*/
public class yingTing {
private int num; // 影厅 <SUF>
private int row;
private int column;
private dianYing dy;
public void showInfoSeat(){
System.out.println("该厅为影院的"+num+"号厅。");
dy.showInfo();
}
public yingTing(int num, int row, int column,dianYing dy) {
super();
this.num = num;
this.row = row;
this.column = column;
this.dy = dy;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public int getRow() {
return row;
}
public void setRow(int row) {
this.row = row;
}
public int getColumn() {
return column;
}
public void setColumn(int column) {
this.column = column;
}
}
| false | 248 | 6 | 298 | 7 | 298 | 5 | 298 | 7 | 345 | 9 | false | false | false | false | false | true |