file_id
stringlengths 5
9
| content
stringlengths 86
32.8k
| repo
stringlengths 9
63
| path
stringlengths 7
161
| token_length
int64 31
8.14k
| original_comment
stringlengths 5
4.92k
| comment_type
stringclasses 2
values | detected_lang
stringclasses 1
value | masked_comment
stringlengths 87
32.8k
| excluded
bool 2
classes |
---|---|---|---|---|---|---|---|---|---|
60968_9 | package com.qgmodel.qggame.entity;
import android.util.Log;
public class MyCardSystem {
private static final String TAG = "MyCard";
private String[] originalCards = new String[]{"说数字", "说为什么", "说英文", "说成语", "说脏话", "说不要", "说好的", "说我没有", "说对不起", "说女朋友",
"说男朋友", "说谢谢", "说考试", "说年龄", "说钱", "说别动", "说明星名", "说歌曲名", "说我不说", "说怕", "说凭什么",
"说没有", "说方言", "说好难", "说该谁了", "说轮到你了", "说不会", "说人名", "说再见", "说回家", "称赞别人", "夸自己", "手托腮",
"回头看", "大叫", "回忆", "向上看", "叫人名", "摸头发", "拒绝别人", "点头", "摸鼻子", "表示同意", "大笑", "回答问题", "提问",
"打赌", "摇头", "怀疑别人", "摸嘴唇", "使眼色", "摸耳垂", "聊工作", "伸舌头","聊家人","聊猫","聊星座","说可爱","说真的","陷害别人",
"唱歌", "讨论玩法", "说听不清", "说没事", "安慰别人", "说不怕", "捂嘴","说电影名字","说刚才"};
private String[] cards = new String[originalCards.length];
private String[] resultCards;
//记录下标的数组
private int[] primes = {2,3,5,7,11,13,17,19};
private int[] indexes = new int[originalCards.length];
private int[] mark = new int[originalCards.length];
private int count = 0;
private int userNum = 4;
private int userCard = 10;
private int distributeCount = 0;
private int reset = 0;
public MyCardSystem(int userNum, int userCard){
this.userNum = userNum;
this.userCard = userCard;
reset =(int) Math.floor((double) originalCards.length/userCard);
Log.d(TAG, "=== reset--> "+reset);
}
private void shuffle(){
count++;
if (count == 1){
for(int i = 0; i< indexes.length; i++) {
indexes[i] = i;
}
}
//对坐标数组用洗牌算法
for (int i = originalCards.length-1; i >0; i--) {
int j = rand(0, i);
indexes[i] = indexes[i] + indexes[j];
indexes[j] = indexes[i] - indexes[j];
indexes[i] = indexes[i] - indexes[j];
}
for (int i = 0;i<cards.length;i++){
cards[i] = originalCards[indexes[i]];
}
}
private int rand(int start,int end){
int ret = (int)(Math.random()*(end - start)+start);
return ret;
}
public String[] getResultCards() {
//外部每次获取前重新分配
distribute();
return resultCards;
}
public void distribute(){
//每次分配都要先洗牌
shuffle();
distributeCount++;
if (distributeCount % reset ==0){
clearMark();
}
resultCards = new String[userNum*userCard];
//selected表示已算好的卡牌的数量
int selected = 0;
//userSign作为不同玩家的标志,均为质数,用于判断某牌是不是被该玩家抽中过
int userSign = primes[0];
int j = 1;
for (int i = 0;selected < userNum*userCard;i++){
if (mark[indexes[i % cards.length]]!=0&&mark[indexes[i % cards.length]] % userSign == 0){
//该牌已被该玩家抽到过
}else{
if (mark[indexes[i % cards.length]]==0){
//该牌没被任何玩家抽到过
mark[indexes[i % cards.length]]+=userSign;
}else if (mark[indexes[i % cards.length]] % userSign != 0){
//该牌没被 当前玩家 抽到过
mark[indexes[i % cards.length]]*=userSign;
}
resultCards[selected] = cards[i%cards.length];
selected++;
if (selected%userCard == 0 && j<userNum){
//如果当前玩家已分配好牌,为下一个玩家分配
userSign = primes[j++];
}
}
// Log.d(TAG, "=== i--> "+i);
}
// for (int i = 0;i<resultCards.length;i++)
// {
// Log.d(TAG, "=== resultCards--> "+resultCards[i]);
// }
// Log.d(TAG, "=== ************************************");
}
private void clearMark(){
for (int i = 0;i<mark.length;i++){
mark[i] = 0;
}
}
public int getUserNum() {
return userNum;
}
public void setUserNum(int userNum) {
this.userNum = userNum;
}
public int getUserCard() {
return userCard;
}
public void setUserCard(int userCard) {
this.userCard = userCard;
}
}
| AgoraIO-Community/RTE-2021-Innovation-Challenge | Application-Challenge/【瓜瓜队】狼人杀/langrensha/app/src/main/java/com/qgmodel/qggame/entity/MyCardSystem.java | 1,385 | //如果当前玩家已分配好牌,为下一个玩家分配 | line_comment | zh-cn | package com.qgmodel.qggame.entity;
import android.util.Log;
public class MyCardSystem {
private static final String TAG = "MyCard";
private String[] originalCards = new String[]{"说数字", "说为什么", "说英文", "说成语", "说脏话", "说不要", "说好的", "说我没有", "说对不起", "说女朋友",
"说男朋友", "说谢谢", "说考试", "说年龄", "说钱", "说别动", "说明星名", "说歌曲名", "说我不说", "说怕", "说凭什么",
"说没有", "说方言", "说好难", "说该谁了", "说轮到你了", "说不会", "说人名", "说再见", "说回家", "称赞别人", "夸自己", "手托腮",
"回头看", "大叫", "回忆", "向上看", "叫人名", "摸头发", "拒绝别人", "点头", "摸鼻子", "表示同意", "大笑", "回答问题", "提问",
"打赌", "摇头", "怀疑别人", "摸嘴唇", "使眼色", "摸耳垂", "聊工作", "伸舌头","聊家人","聊猫","聊星座","说可爱","说真的","陷害别人",
"唱歌", "讨论玩法", "说听不清", "说没事", "安慰别人", "说不怕", "捂嘴","说电影名字","说刚才"};
private String[] cards = new String[originalCards.length];
private String[] resultCards;
//记录下标的数组
private int[] primes = {2,3,5,7,11,13,17,19};
private int[] indexes = new int[originalCards.length];
private int[] mark = new int[originalCards.length];
private int count = 0;
private int userNum = 4;
private int userCard = 10;
private int distributeCount = 0;
private int reset = 0;
public MyCardSystem(int userNum, int userCard){
this.userNum = userNum;
this.userCard = userCard;
reset =(int) Math.floor((double) originalCards.length/userCard);
Log.d(TAG, "=== reset--> "+reset);
}
private void shuffle(){
count++;
if (count == 1){
for(int i = 0; i< indexes.length; i++) {
indexes[i] = i;
}
}
//对坐标数组用洗牌算法
for (int i = originalCards.length-1; i >0; i--) {
int j = rand(0, i);
indexes[i] = indexes[i] + indexes[j];
indexes[j] = indexes[i] - indexes[j];
indexes[i] = indexes[i] - indexes[j];
}
for (int i = 0;i<cards.length;i++){
cards[i] = originalCards[indexes[i]];
}
}
private int rand(int start,int end){
int ret = (int)(Math.random()*(end - start)+start);
return ret;
}
public String[] getResultCards() {
//外部每次获取前重新分配
distribute();
return resultCards;
}
public void distribute(){
//每次分配都要先洗牌
shuffle();
distributeCount++;
if (distributeCount % reset ==0){
clearMark();
}
resultCards = new String[userNum*userCard];
//selected表示已算好的卡牌的数量
int selected = 0;
//userSign作为不同玩家的标志,均为质数,用于判断某牌是不是被该玩家抽中过
int userSign = primes[0];
int j = 1;
for (int i = 0;selected < userNum*userCard;i++){
if (mark[indexes[i % cards.length]]!=0&&mark[indexes[i % cards.length]] % userSign == 0){
//该牌已被该玩家抽到过
}else{
if (mark[indexes[i % cards.length]]==0){
//该牌没被任何玩家抽到过
mark[indexes[i % cards.length]]+=userSign;
}else if (mark[indexes[i % cards.length]] % userSign != 0){
//该牌没被 当前玩家 抽到过
mark[indexes[i % cards.length]]*=userSign;
}
resultCards[selected] = cards[i%cards.length];
selected++;
if (selected%userCard == 0 && j<userNum){
//如果 <SUF>
userSign = primes[j++];
}
}
// Log.d(TAG, "=== i--> "+i);
}
// for (int i = 0;i<resultCards.length;i++)
// {
// Log.d(TAG, "=== resultCards--> "+resultCards[i]);
// }
// Log.d(TAG, "=== ************************************");
}
private void clearMark(){
for (int i = 0;i<mark.length;i++){
mark[i] = 0;
}
}
public int getUserNum() {
return userNum;
}
public void setUserNum(int userNum) {
this.userNum = userNum;
}
public int getUserCard() {
return userCard;
}
public void setUserCard(int userCard) {
this.userCard = userCard;
}
}
| false |
41478_11 | package com.xiaoyang.poweroperation.app.utils;
public class ChString {
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";// 到达
}
| AgoraIO-Community/RTE-Innovation-Challenge-2020 | SDKChallengeProject/powerOperation/app/src/main/java/com/xiaoyang/poweroperation/app/utils/ChString.java | 544 | // "站"; | line_comment | zh-cn | package com.xiaoyang.poweroperation.app.utils;
public class ChString {
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";// "站 <SUF>
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";// 到达
}
| true |
35826_7 | package io.agora.falcondemo.utils;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.text.TextUtils;
import com.agora.baselibrary.utils.SPUtil;
import java.nio.charset.StandardCharsets;
public class AppStorageUtil {
////////////////////////////////////////////////////////////////////////
//////////////////////// Constant Definition ///////////////////////////
////////////////////////////////////////////////////////////////////////
//
// 应用存储参数键值
//
public static final String KEY_ACCOUNT = "KEY_ACCOUNT";
public static final String KEY_PASSWORD = "KEY_PASSWORD";
public static final String KEY_TOKEN = "KEY_TOKEN";
public static final String KEY_IDENTITYID = "KEY_IDENTITYID";
public static final String KEY_ENDPOINT = "KEY_ENDPOINT";
public static final String KEY_POOLTOKEN = "KEY_POOLTOKEN";
public static final String KEY_IDENTIFIER = "KEY_IDENTIFIER";
public static final String KEY_IDENTIFIERPOOLID = "KEY_IDENTIFIERPOOLID";
public static final String KEY_REGION = "KEY_REGION";
//////////////////////////////////////////////////////////////////
////////////////////// Public Methods ///////////////////////////
//////////////////////////////////////////////////////////////////
private static SharedPreferences sharedPreferences;
private volatile static AppStorageUtil instance;
public static AppStorageUtil init(Context context) {
if (instance == null) {
synchronized (AppStorageUtil.class) {
if (instance == null) {
instance = new AppStorageUtil(context);
}
}
}
return instance;
}
private AppStorageUtil(Context context) {
sharedPreferences = context.getSharedPreferences("IoTDemo", Context.MODE_PRIVATE);
}
public static void keepShared(String key, String value) {
Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
public static void keepShared(String key, Integer value) {
Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.commit();
}
public static void keepShared(String key, long value) {
Editor editor = sharedPreferences.edit();
editor.putLong(key, value);
editor.commit();
}
public static void keepShared(String key, int value) {
Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.commit();
}
public static void keepShared(String key, boolean value) {
Editor editor = sharedPreferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
public static String queryValue(String key, String defvalue) {
String value = sharedPreferences.getString(key, defvalue);
// if ("".equals(value)) {
// return "";
// }
return value;
}
public static String queryValue(String key) {
String value = sharedPreferences.getString(key, "");
if ("".equals(value)) {
return "";
}
return value;
}
public static Integer queryIntValue(String key) {
int value = sharedPreferences.getInt(key, 0);
return value;
}
public static Integer queryIntValue(String key, int defalut) {
int value = sharedPreferences.getInt(key, defalut);
return value;
}
public static boolean queryBooleanValue(String key) {
return sharedPreferences.getBoolean(key, false);
}
public static long queryLongValue(String key) {
return sharedPreferences.getLong(key, 0);
}
public static boolean deleteAllValue() {
return sharedPreferences.edit().clear().commit();
}
public static void deleteValue(String key) {
sharedPreferences.edit().remove(key).commit();
}
public static void safePutString(Context ctx, String key, String value) {
if (TextUtils.isEmpty(value)) {
SPUtil.Companion.getInstance(ctx).putString(key, value);
return;
}
String encryptValue = encryptString(value);
SPUtil.Companion.getInstance(ctx).putString(key, encryptValue);
}
public static String safeGetString(Context ctx,String key, String defValue) {
String encryptValue = SPUtil.Companion.getInstance(ctx).getString(key, defValue);
if (encryptValue == null) {
return null;
}
if (encryptValue.isEmpty()) {
return "";
}
String value = decryptString(encryptValue);
return value;
}
/**
* @biref 字符串加密
*/
public static String encryptString(String value) {
if (TextUtils.isEmpty(value)) {
return "";
}
// 转换成 Utf-8 字节流
byte[] utf8 = value.getBytes(StandardCharsets.UTF_8);
byte[] encryptData = enDeCrypt(utf8);
// 每个字节转换成 xxx, 数字
String encrypted = bytesToString(encryptData);
return encrypted;
}
/**
* @biref 字符串解密
*/
public static String decryptString(String value) {
if (TextUtils.isEmpty(value)) {
return "";
}
// 每个字节转换成utf8字节流
byte[] utf8 = stringToBytes(value);
byte[] decrypted = enDeCrypt(utf8);
// 文本字节由utf8字节流创建
String text = new String(decrypted, StandardCharsets.UTF_8);
return text;
}
/**
* @biref 将字节流数据转换成16进制
* @param data 字节流数据
* @return 返回转换后的文本
*/
public static String bytesToString(byte[] data) {
if (data == null) {
return "";
}
String text = "";
for (int j = 0; j < data.length; j++) {
String dataHex = String.format("%03d,", data[j]);
text += dataHex;
}
return text;
}
/**
* @biref 将字符串转换成字节流
* @param text 字符串
* @return 返回转换后的文本
*/
public static byte[] stringToBytes(final String text) {
if (text == null) {
return null;
}
String[] elemArray = text.split(",");
if (elemArray == null || elemArray.length <= 0) {
return null;
}
byte[] data = new byte[elemArray.length];
for (int i = 0; i < elemArray.length; i++) {
data[i] = Byte.valueOf(elemArray[i]);
}
return data;
}
public static byte[] enDeCrypt(byte[] inData) {
if (inData == null) {
return null;
}
int [] key = new int[] { 0x05, 0xEF, 0x4F, 0x28, 0x61, 0x46, 0x43, 0x6C, 0x73, 0x23, 0x22, 0x43, 0x7E, 0x7D, 0x96, 0xB4};
int keyLen = key.length;
int dataSize = inData.length;
byte[] outData = new byte[dataSize];
int i, j = 0;
for (i = 0; i < dataSize; i++) {
outData[i] = (byte)(inData[i] ^ key[j]);
j = (j + 1) % keyLen;
}
return outData;
}
// public static void UnitTest() {
// String orgText = "ABCDefgh012346+-*%_@!#$%^&()华叔[好人]<>";
// String encryptText = AppStorageUtil.encryptString(orgText);
// String decryptText = AppStorageUtil.decryptString(encryptText);
//
// if (orgText.compareToIgnoreCase(decryptText) != 0) {
// Log.d("UT", "encrypt error");
// } else {
// Log.d("UT", "encrypt OK");
// }
// }
}
| AgoraIO-Community/ag-iot-android-app | app/src/main/java/io/agora/falcondemo/utils/AppStorageUtil.java | 1,837 | // 每个字节转换成 xxx, 数字 | line_comment | zh-cn | package io.agora.falcondemo.utils;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.text.TextUtils;
import com.agora.baselibrary.utils.SPUtil;
import java.nio.charset.StandardCharsets;
public class AppStorageUtil {
////////////////////////////////////////////////////////////////////////
//////////////////////// Constant Definition ///////////////////////////
////////////////////////////////////////////////////////////////////////
//
// 应用存储参数键值
//
public static final String KEY_ACCOUNT = "KEY_ACCOUNT";
public static final String KEY_PASSWORD = "KEY_PASSWORD";
public static final String KEY_TOKEN = "KEY_TOKEN";
public static final String KEY_IDENTITYID = "KEY_IDENTITYID";
public static final String KEY_ENDPOINT = "KEY_ENDPOINT";
public static final String KEY_POOLTOKEN = "KEY_POOLTOKEN";
public static final String KEY_IDENTIFIER = "KEY_IDENTIFIER";
public static final String KEY_IDENTIFIERPOOLID = "KEY_IDENTIFIERPOOLID";
public static final String KEY_REGION = "KEY_REGION";
//////////////////////////////////////////////////////////////////
////////////////////// Public Methods ///////////////////////////
//////////////////////////////////////////////////////////////////
private static SharedPreferences sharedPreferences;
private volatile static AppStorageUtil instance;
public static AppStorageUtil init(Context context) {
if (instance == null) {
synchronized (AppStorageUtil.class) {
if (instance == null) {
instance = new AppStorageUtil(context);
}
}
}
return instance;
}
private AppStorageUtil(Context context) {
sharedPreferences = context.getSharedPreferences("IoTDemo", Context.MODE_PRIVATE);
}
public static void keepShared(String key, String value) {
Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
public static void keepShared(String key, Integer value) {
Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.commit();
}
public static void keepShared(String key, long value) {
Editor editor = sharedPreferences.edit();
editor.putLong(key, value);
editor.commit();
}
public static void keepShared(String key, int value) {
Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.commit();
}
public static void keepShared(String key, boolean value) {
Editor editor = sharedPreferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
public static String queryValue(String key, String defvalue) {
String value = sharedPreferences.getString(key, defvalue);
// if ("".equals(value)) {
// return "";
// }
return value;
}
public static String queryValue(String key) {
String value = sharedPreferences.getString(key, "");
if ("".equals(value)) {
return "";
}
return value;
}
public static Integer queryIntValue(String key) {
int value = sharedPreferences.getInt(key, 0);
return value;
}
public static Integer queryIntValue(String key, int defalut) {
int value = sharedPreferences.getInt(key, defalut);
return value;
}
public static boolean queryBooleanValue(String key) {
return sharedPreferences.getBoolean(key, false);
}
public static long queryLongValue(String key) {
return sharedPreferences.getLong(key, 0);
}
public static boolean deleteAllValue() {
return sharedPreferences.edit().clear().commit();
}
public static void deleteValue(String key) {
sharedPreferences.edit().remove(key).commit();
}
public static void safePutString(Context ctx, String key, String value) {
if (TextUtils.isEmpty(value)) {
SPUtil.Companion.getInstance(ctx).putString(key, value);
return;
}
String encryptValue = encryptString(value);
SPUtil.Companion.getInstance(ctx).putString(key, encryptValue);
}
public static String safeGetString(Context ctx,String key, String defValue) {
String encryptValue = SPUtil.Companion.getInstance(ctx).getString(key, defValue);
if (encryptValue == null) {
return null;
}
if (encryptValue.isEmpty()) {
return "";
}
String value = decryptString(encryptValue);
return value;
}
/**
* @biref 字符串加密
*/
public static String encryptString(String value) {
if (TextUtils.isEmpty(value)) {
return "";
}
// 转换成 Utf-8 字节流
byte[] utf8 = value.getBytes(StandardCharsets.UTF_8);
byte[] encryptData = enDeCrypt(utf8);
// 每个 <SUF>
String encrypted = bytesToString(encryptData);
return encrypted;
}
/**
* @biref 字符串解密
*/
public static String decryptString(String value) {
if (TextUtils.isEmpty(value)) {
return "";
}
// 每个字节转换成utf8字节流
byte[] utf8 = stringToBytes(value);
byte[] decrypted = enDeCrypt(utf8);
// 文本字节由utf8字节流创建
String text = new String(decrypted, StandardCharsets.UTF_8);
return text;
}
/**
* @biref 将字节流数据转换成16进制
* @param data 字节流数据
* @return 返回转换后的文本
*/
public static String bytesToString(byte[] data) {
if (data == null) {
return "";
}
String text = "";
for (int j = 0; j < data.length; j++) {
String dataHex = String.format("%03d,", data[j]);
text += dataHex;
}
return text;
}
/**
* @biref 将字符串转换成字节流
* @param text 字符串
* @return 返回转换后的文本
*/
public static byte[] stringToBytes(final String text) {
if (text == null) {
return null;
}
String[] elemArray = text.split(",");
if (elemArray == null || elemArray.length <= 0) {
return null;
}
byte[] data = new byte[elemArray.length];
for (int i = 0; i < elemArray.length; i++) {
data[i] = Byte.valueOf(elemArray[i]);
}
return data;
}
public static byte[] enDeCrypt(byte[] inData) {
if (inData == null) {
return null;
}
int [] key = new int[] { 0x05, 0xEF, 0x4F, 0x28, 0x61, 0x46, 0x43, 0x6C, 0x73, 0x23, 0x22, 0x43, 0x7E, 0x7D, 0x96, 0xB4};
int keyLen = key.length;
int dataSize = inData.length;
byte[] outData = new byte[dataSize];
int i, j = 0;
for (i = 0; i < dataSize; i++) {
outData[i] = (byte)(inData[i] ^ key[j]);
j = (j + 1) % keyLen;
}
return outData;
}
// public static void UnitTest() {
// String orgText = "ABCDefgh012346+-*%_@!#$%^&()华叔[好人]<>";
// String encryptText = AppStorageUtil.encryptString(orgText);
// String decryptText = AppStorageUtil.decryptString(encryptText);
//
// if (orgText.compareToIgnoreCase(decryptText) != 0) {
// Log.d("UT", "encrypt error");
// } else {
// Log.d("UT", "encrypt OK");
// }
// }
}
| false |
46260_0 | package io.agora.highqualityaudio.utils;
import io.agora.rtc.Constants;
import io.agora.rtc.RtcEngine;
public class SoundEffectUtil {
public static ExampleVoiceConversion currentConversion = ExampleVoiceConversion.ORIGINAL;
public static ExampleVoiceEffect currentEffect = ExampleVoiceEffect.ORIGINAL;
public static ExampleVoiceBeautifier currentBeautifier = ExampleVoiceBeautifier.ORIGINAL;
// 音效
public static enum ExampleVoiceEffect {
// 原生
ORIGINAL(Constants.AUDIO_EFFECT_OFF),
// 男孩
BOY(Constants.VOICE_CHANGER_EFFECT_BOY),
// 爷爷
OLD_MAN(Constants.VOICE_CHANGER_EFFECT_OLDMAN),
// 女孩
GIRL(Constants.VOICE_CHANGER_EFFECT_GIRL),
// 大叔
UNCLE(Constants.VOICE_CHANGER_EFFECT_UNCLE),
// 少女
SISTER(Constants.VOICE_CHANGER_EFFECT_SISTER),
// 猪八戒
PIG_KING(Constants.VOICE_CHANGER_EFFECT_PIGKING),
// 绿巨人
HULK(Constants.VOICE_CHANGER_EFFECT_HULK),
// KTV
KTV(Constants.ROOM_ACOUSTICS_KTV),
// 演唱会
CONCERT(Constants.ROOM_ACOUSTICS_VOCAL_CONCERT),
// 录音棚
STUDIO(Constants.ROOM_ACOUSTICS_STUDIO),
// 留声机
PHONOGRAPH(Constants.ROOM_ACOUSTICS_PHONOGRAPH),
// 空旷
SPACIAL(Constants.ROOM_ACOUSTICS_SPACIAL),
// 空灵
ETHEREAL(Constants.ROOM_ACOUSTICS_ETHEREAL),
// 流行
POPULAR(Constants.STYLE_TRANSFORMATION_POPULAR),
// R&B
RNB(Constants.STYLE_TRANSFORMATION_RNB);
int value;
private ExampleVoiceEffect(int value) {
this.value = value;
}
}
// 美声
public static enum ExampleVoiceBeautifier {
// 原声
ORIGINAL(Constants.VOICE_BEAUTIFIER_OFF),
// 磁性
MAGNETIC(Constants.CHAT_BEAUTIFIER_MAGNETIC),
// 清新
FRESH(Constants.CHAT_BEAUTIFIER_FRESH),
// 活力
VITALITY(Constants.CHAT_BEAUTIFIER_VITALITY),
// 浑厚
VIGOROUS(Constants.TIMBRE_TRANSFORMATION_VIGOROUS),
// 低沉
DEEP(Constants.TIMBRE_TRANSFORMATION_DEEP),
// 圆润
MELLOW(Constants.TIMBRE_TRANSFORMATION_MELLOW),
// 假音
FALSETTO(Constants.TIMBRE_TRANSFORMATION_FALSETTO),
// 饱满
FULL(Constants.TIMBRE_TRANSFORMATION_FULL),
// 清澈
CLEAR(Constants.TIMBRE_TRANSFORMATION_CLEAR),
// 高亢
RESOUNDING(Constants.TIMBRE_TRANSFORMATION_RESOUNDING),
// 嘹亮
RINGING(Constants.TIMBRE_TRANSFORMATION_RINGING);
int value;
private ExampleVoiceBeautifier(int value) {
this.value = value;
}
}
// 变声
public static enum ExampleVoiceConversion {
// 原声
ORIGINAL(Constants.VOICE_CONVERSION_OFF),
// 低沉
BASS(Constants.VOICE_CHANGER_BASS),
// 中性
NEUTRAL(Constants.VOICE_CHANGER_NEUTRAL),
// 稳重
SOLID(Constants.VOICE_CHANGER_SOLID),
// 甜美
SWEET(Constants.VOICE_CHANGER_SWEET);
int value;
private ExampleVoiceConversion(int value) {
this.value = value;
}
}
/**
* 音效
*
* <p>
* 设置 SDK 预设的人声音效。
* 自从 v3.2.0
* 调用该方法可以为本地发流用户设置 SDK 预设的人声音效,且不会改变原声的性别特征。设置音效后,频道 内所有用户都能听到该效果。
* <p>
* 根据不同的场景,你可以为用户设置不同的音效,各音效的适用场景可参考《设置人声效果》。
* <p>
* 为获取更好的人声效果,Agora 推荐你在调用该方法前将 setAudioProfile 的 scenario 设为 AUDIO_SCENARIO_GAME_STREAMING(3)。
*/
public static void changeVoiceEffect(RtcEngine engine, ExampleVoiceEffect effect) {
engine.setAudioEffectPreset(effect.value);
}
/**
* 设置 SDK 预设的美声效果。
* <p>
* 自从
* v3.2.0
* 调用该方法可以为本地发流用户设置 SDK 预设的人声美化效果。
* 设置美声效果后,频道内所有用户都能听到该效果。根据不同的场景,你可以为用户设置不同的美声效果,各美声效果的适用场景可参考《设置人声效果》。
* <p>
* 为获取更好的人声效果
* Agora 推荐你在调用该方法前将 setAudioProfile 的 scenario 设为 AUDIO_SCENARIO_GAME_STREAMING(3)
* 并将 profile 设为 AUDIO_PROFILE_MUSIC_HIGH_QUALITY(4) 或 AUDIO_PROFILE_MUSIC_HIGH_QUALITY_STEREO(5)。
*/
public static void changeVoiceBeautifier(RtcEngine engine, ExampleVoiceBeautifier beautifier) {
engine.setVoiceBeautifierPreset(beautifier.value);
}
/**
*
* 设置 SDK 预设的变声效果。
*
* 自从
* v3.3.1
* 调用该方法可以为本地发流用户设置 SDK 预设的变声效果。
* 设置变声效果后,频道内所有用户都能听到该效果。
* 根据不同的场景,你可以为用户设置不同的变声效果,各变声效果的适用场景可参考《设置人声效果》。
*
* 为获取更好的人声效果,Agora 推荐你在调用该方法前将 setAudioProfile 的 scenario 设为 AUDIO_SCENARIO_GAME_STREAMING(3)
* 并将 profile 设为 AUDIO_PROFILE_MUSIC_HIGH_QUALITY(4) 或 AUDIO_PROFILE_MUSIC_HIGH_QUALITY_STEREO(5)。
*/
public static void changeVoiceConversion(RtcEngine engine, ExampleVoiceConversion conversion) {
engine.setVoiceConversionPreset(conversion.value);
}
}
| AgoraIO-Usecase/High-Quality-Audio | High-Quaility-Audio/High-Quality-Audio-Android/app/src/main/java/io/agora/highqualityaudio/utils/SoundEffectUtil.java | 1,635 | // 猪八戒 | line_comment | zh-cn | package io.agora.highqualityaudio.utils;
import io.agora.rtc.Constants;
import io.agora.rtc.RtcEngine;
public class SoundEffectUtil {
public static ExampleVoiceConversion currentConversion = ExampleVoiceConversion.ORIGINAL;
public static ExampleVoiceEffect currentEffect = ExampleVoiceEffect.ORIGINAL;
public static ExampleVoiceBeautifier currentBeautifier = ExampleVoiceBeautifier.ORIGINAL;
// 音效
public static enum ExampleVoiceEffect {
// 原生
ORIGINAL(Constants.AUDIO_EFFECT_OFF),
// 男孩
BOY(Constants.VOICE_CHANGER_EFFECT_BOY),
// 爷爷
OLD_MAN(Constants.VOICE_CHANGER_EFFECT_OLDMAN),
// 女孩
GIRL(Constants.VOICE_CHANGER_EFFECT_GIRL),
// 大叔
UNCLE(Constants.VOICE_CHANGER_EFFECT_UNCLE),
// 少女
SISTER(Constants.VOICE_CHANGER_EFFECT_SISTER),
// 猪八 <SUF>
PIG_KING(Constants.VOICE_CHANGER_EFFECT_PIGKING),
// 绿巨人
HULK(Constants.VOICE_CHANGER_EFFECT_HULK),
// KTV
KTV(Constants.ROOM_ACOUSTICS_KTV),
// 演唱会
CONCERT(Constants.ROOM_ACOUSTICS_VOCAL_CONCERT),
// 录音棚
STUDIO(Constants.ROOM_ACOUSTICS_STUDIO),
// 留声机
PHONOGRAPH(Constants.ROOM_ACOUSTICS_PHONOGRAPH),
// 空旷
SPACIAL(Constants.ROOM_ACOUSTICS_SPACIAL),
// 空灵
ETHEREAL(Constants.ROOM_ACOUSTICS_ETHEREAL),
// 流行
POPULAR(Constants.STYLE_TRANSFORMATION_POPULAR),
// R&B
RNB(Constants.STYLE_TRANSFORMATION_RNB);
int value;
private ExampleVoiceEffect(int value) {
this.value = value;
}
}
// 美声
public static enum ExampleVoiceBeautifier {
// 原声
ORIGINAL(Constants.VOICE_BEAUTIFIER_OFF),
// 磁性
MAGNETIC(Constants.CHAT_BEAUTIFIER_MAGNETIC),
// 清新
FRESH(Constants.CHAT_BEAUTIFIER_FRESH),
// 活力
VITALITY(Constants.CHAT_BEAUTIFIER_VITALITY),
// 浑厚
VIGOROUS(Constants.TIMBRE_TRANSFORMATION_VIGOROUS),
// 低沉
DEEP(Constants.TIMBRE_TRANSFORMATION_DEEP),
// 圆润
MELLOW(Constants.TIMBRE_TRANSFORMATION_MELLOW),
// 假音
FALSETTO(Constants.TIMBRE_TRANSFORMATION_FALSETTO),
// 饱满
FULL(Constants.TIMBRE_TRANSFORMATION_FULL),
// 清澈
CLEAR(Constants.TIMBRE_TRANSFORMATION_CLEAR),
// 高亢
RESOUNDING(Constants.TIMBRE_TRANSFORMATION_RESOUNDING),
// 嘹亮
RINGING(Constants.TIMBRE_TRANSFORMATION_RINGING);
int value;
private ExampleVoiceBeautifier(int value) {
this.value = value;
}
}
// 变声
public static enum ExampleVoiceConversion {
// 原声
ORIGINAL(Constants.VOICE_CONVERSION_OFF),
// 低沉
BASS(Constants.VOICE_CHANGER_BASS),
// 中性
NEUTRAL(Constants.VOICE_CHANGER_NEUTRAL),
// 稳重
SOLID(Constants.VOICE_CHANGER_SOLID),
// 甜美
SWEET(Constants.VOICE_CHANGER_SWEET);
int value;
private ExampleVoiceConversion(int value) {
this.value = value;
}
}
/**
* 音效
*
* <p>
* 设置 SDK 预设的人声音效。
* 自从 v3.2.0
* 调用该方法可以为本地发流用户设置 SDK 预设的人声音效,且不会改变原声的性别特征。设置音效后,频道 内所有用户都能听到该效果。
* <p>
* 根据不同的场景,你可以为用户设置不同的音效,各音效的适用场景可参考《设置人声效果》。
* <p>
* 为获取更好的人声效果,Agora 推荐你在调用该方法前将 setAudioProfile 的 scenario 设为 AUDIO_SCENARIO_GAME_STREAMING(3)。
*/
public static void changeVoiceEffect(RtcEngine engine, ExampleVoiceEffect effect) {
engine.setAudioEffectPreset(effect.value);
}
/**
* 设置 SDK 预设的美声效果。
* <p>
* 自从
* v3.2.0
* 调用该方法可以为本地发流用户设置 SDK 预设的人声美化效果。
* 设置美声效果后,频道内所有用户都能听到该效果。根据不同的场景,你可以为用户设置不同的美声效果,各美声效果的适用场景可参考《设置人声效果》。
* <p>
* 为获取更好的人声效果
* Agora 推荐你在调用该方法前将 setAudioProfile 的 scenario 设为 AUDIO_SCENARIO_GAME_STREAMING(3)
* 并将 profile 设为 AUDIO_PROFILE_MUSIC_HIGH_QUALITY(4) 或 AUDIO_PROFILE_MUSIC_HIGH_QUALITY_STEREO(5)。
*/
public static void changeVoiceBeautifier(RtcEngine engine, ExampleVoiceBeautifier beautifier) {
engine.setVoiceBeautifierPreset(beautifier.value);
}
/**
*
* 设置 SDK 预设的变声效果。
*
* 自从
* v3.3.1
* 调用该方法可以为本地发流用户设置 SDK 预设的变声效果。
* 设置变声效果后,频道内所有用户都能听到该效果。
* 根据不同的场景,你可以为用户设置不同的变声效果,各变声效果的适用场景可参考《设置人声效果》。
*
* 为获取更好的人声效果,Agora 推荐你在调用该方法前将 setAudioProfile 的 scenario 设为 AUDIO_SCENARIO_GAME_STREAMING(3)
* 并将 profile 设为 AUDIO_PROFILE_MUSIC_HIGH_QUALITY(4) 或 AUDIO_PROFILE_MUSIC_HIGH_QUALITY_STEREO(5)。
*/
public static void changeVoiceConversion(RtcEngine engine, ExampleVoiceConversion conversion) {
engine.setVoiceConversionPreset(conversion.value);
}
}
| true |
58327_0 | package io.agora.metalive.manager.editface.constant;
import android.content.Context;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import io.agora.metalive.manager.EditFaceManager;
import io.agora.metalive.manager.editface.entity.BundleRes;
import io.agora.metalive.manager.editface.entity.SpecialBundleRes;
public class JsonUtils {
/**
* 解析的是普通类型的配置文件
*/
public static final int TYPE_NORMAL = 1;
/**
* 解析的是配饰类型的配置文件
*/
public static final int TYPE_DECORATION = 2;
private List<BundleRes> jsonList = new ArrayList<>();
private List<SpecialBundleRes> jsonDecorationList = new ArrayList<>();
private Context context;
public JsonUtils() {
this.context = EditFaceManager.getInstance().getContext();
}
public void readJson(String path) {
readJson(path, TYPE_NORMAL, 0);
}
/**
* 解析传递进来的json文件
*
* @param path json文件路径
* @param type 解析的类型(1:正常类型 2:配饰类型)
* @param bundleType 配饰类型中的类型(配饰-手、配饰-脚、配饰-脖子、配饰-头、配饰-耳朵)
*/
public void readJson(String path, int type, int bundleType) {
if (type == TYPE_NORMAL) {
jsonList.clear();
} else {
jsonDecorationList.clear();
}
try {
InputStream inputStream = context.getAssets().open(path);
byte[] data = new byte[inputStream.available()];
inputStream.read(data);
inputStream.close();
String jsonStr = new String(data);
JSONObject jsonObject = new JSONObject(jsonStr);
JSONArray jsonArray = (JSONArray) (jsonObject.opt(jsonObject.keys().next()));
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
resolveConfigJson(jsonObject1, type, bundleType);
}
} catch (IOException e) {
e.printStackTrace();
Log.e("IOException", e.getMessage());
} catch (JSONException e) {
e.printStackTrace();
Log.e("JSONException", e.getMessage());
}
}
private void resolveConfigJson(JSONObject jsonObject, int type, int bundleType) {
int gender = 0;
String bundle = "";
int resId = 0;
Integer[] label = new Integer[]{};
boolean isSupport = true;
int bodyLevel = 0;
try {
if (jsonObject.has("bundle")) {
bundle = jsonObject.getString("bundle");
}
if (jsonObject.has("icon")) {
resId = context.getResources().getIdentifier(jsonObject.getString("icon"), "drawable", context.getPackageName());
}
if (jsonObject.has("gender")) {
gender = jsonObject.getInt("gender");
}
if (jsonObject.has("label")) {
JSONArray labelJA = jsonObject.getJSONArray("label");
if (labelJA != null && labelJA.length() > 0) {
label = new Integer[labelJA.length()];
}
for (int i = 0; i < labelJA.length(); i++) {
label[i] = labelJA.getInt(i);
}
}
if (jsonObject.has("body_match_level")) {
bodyLevel = jsonObject.getInt("body_match_level");
}
if (jsonObject.has("body_level")) {
bodyLevel = jsonObject.getInt("body_level");
}
} catch (JSONException e) {
e.printStackTrace();
}
if (type == TYPE_NORMAL) {
jsonList.add(new BundleRes(gender, bundle, resId, label, isSupport, bodyLevel));
} else {
jsonDecorationList.add(new SpecialBundleRes(resId, bundleType, bundle));
}
}
public List<BundleRes> getBundleResList() {
return jsonList;
}
/**
* 获取配饰配置文件解析出来的数据
*
* @return
*/
public List<SpecialBundleRes> getDecorationBundleResList() {
return jsonDecorationList;
}
//读取捏脸点位个数及对应的名称
public String[] readFacePupJson(String path) {
List<String> facePupList = new ArrayList<>();
try {
InputStream inputStream = context.getAssets().open(path);
byte[] data = new byte[inputStream.available()];
inputStream.read(data);
inputStream.close();
String jsonStr = new String(data);
JSONObject jsonObject = new JSONObject(jsonStr);
Iterator iterator = jsonObject.keys();
while (iterator.hasNext()) {
String key = iterator.next().toString();
facePupList.add(key);
}
} catch (IOException e) {
e.printStackTrace();
Log.e("IOException", e.getMessage());
} catch (JSONException e) {
e.printStackTrace();
Log.e("JSONException", e.getMessage());
}
String[] facePup = new String[facePupList.size()];
facePupList.toArray(facePup);
return facePup;
}
}
| AgoraIO-Usecase/MetaLive | Android/app/src/main/java/io/agora/metalive/manager/editface/constant/JsonUtils.java | 1,272 | /**
* 解析的是普通类型的配置文件
*/ | block_comment | zh-cn | package io.agora.metalive.manager.editface.constant;
import android.content.Context;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import io.agora.metalive.manager.EditFaceManager;
import io.agora.metalive.manager.editface.entity.BundleRes;
import io.agora.metalive.manager.editface.entity.SpecialBundleRes;
public class JsonUtils {
/**
* 解析的 <SUF>*/
public static final int TYPE_NORMAL = 1;
/**
* 解析的是配饰类型的配置文件
*/
public static final int TYPE_DECORATION = 2;
private List<BundleRes> jsonList = new ArrayList<>();
private List<SpecialBundleRes> jsonDecorationList = new ArrayList<>();
private Context context;
public JsonUtils() {
this.context = EditFaceManager.getInstance().getContext();
}
public void readJson(String path) {
readJson(path, TYPE_NORMAL, 0);
}
/**
* 解析传递进来的json文件
*
* @param path json文件路径
* @param type 解析的类型(1:正常类型 2:配饰类型)
* @param bundleType 配饰类型中的类型(配饰-手、配饰-脚、配饰-脖子、配饰-头、配饰-耳朵)
*/
public void readJson(String path, int type, int bundleType) {
if (type == TYPE_NORMAL) {
jsonList.clear();
} else {
jsonDecorationList.clear();
}
try {
InputStream inputStream = context.getAssets().open(path);
byte[] data = new byte[inputStream.available()];
inputStream.read(data);
inputStream.close();
String jsonStr = new String(data);
JSONObject jsonObject = new JSONObject(jsonStr);
JSONArray jsonArray = (JSONArray) (jsonObject.opt(jsonObject.keys().next()));
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
resolveConfigJson(jsonObject1, type, bundleType);
}
} catch (IOException e) {
e.printStackTrace();
Log.e("IOException", e.getMessage());
} catch (JSONException e) {
e.printStackTrace();
Log.e("JSONException", e.getMessage());
}
}
private void resolveConfigJson(JSONObject jsonObject, int type, int bundleType) {
int gender = 0;
String bundle = "";
int resId = 0;
Integer[] label = new Integer[]{};
boolean isSupport = true;
int bodyLevel = 0;
try {
if (jsonObject.has("bundle")) {
bundle = jsonObject.getString("bundle");
}
if (jsonObject.has("icon")) {
resId = context.getResources().getIdentifier(jsonObject.getString("icon"), "drawable", context.getPackageName());
}
if (jsonObject.has("gender")) {
gender = jsonObject.getInt("gender");
}
if (jsonObject.has("label")) {
JSONArray labelJA = jsonObject.getJSONArray("label");
if (labelJA != null && labelJA.length() > 0) {
label = new Integer[labelJA.length()];
}
for (int i = 0; i < labelJA.length(); i++) {
label[i] = labelJA.getInt(i);
}
}
if (jsonObject.has("body_match_level")) {
bodyLevel = jsonObject.getInt("body_match_level");
}
if (jsonObject.has("body_level")) {
bodyLevel = jsonObject.getInt("body_level");
}
} catch (JSONException e) {
e.printStackTrace();
}
if (type == TYPE_NORMAL) {
jsonList.add(new BundleRes(gender, bundle, resId, label, isSupport, bodyLevel));
} else {
jsonDecorationList.add(new SpecialBundleRes(resId, bundleType, bundle));
}
}
public List<BundleRes> getBundleResList() {
return jsonList;
}
/**
* 获取配饰配置文件解析出来的数据
*
* @return
*/
public List<SpecialBundleRes> getDecorationBundleResList() {
return jsonDecorationList;
}
//读取捏脸点位个数及对应的名称
public String[] readFacePupJson(String path) {
List<String> facePupList = new ArrayList<>();
try {
InputStream inputStream = context.getAssets().open(path);
byte[] data = new byte[inputStream.available()];
inputStream.read(data);
inputStream.close();
String jsonStr = new String(data);
JSONObject jsonObject = new JSONObject(jsonStr);
Iterator iterator = jsonObject.keys();
while (iterator.hasNext()) {
String key = iterator.next().toString();
facePupList.add(key);
}
} catch (IOException e) {
e.printStackTrace();
Log.e("IOException", e.getMessage());
} catch (JSONException e) {
e.printStackTrace();
Log.e("JSONException", e.getMessage());
}
String[] facePup = new String[facePupList.size()];
facePupList.toArray(facePup);
return facePup;
}
}
| true |
50318_30 | package cdd.desk.view;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.uml.umlwork.R;
import java.util.List;
import cdd.desk.model.card.Card;
import cdd.desk.contract.deskContract;
import cdd.desk.presenter.deskPresenter;
import cdd.menu.view.MainActivity;
/**
* Main UI for the add task screen. Users can enter a task title and description.
*/
public class deskActivity extends AppCompatActivity implements deskContract.View{
private ImageButton btnShowCards;
private ImageButton btnSkip;
private ImageButton btnReSelect;
private ImageButton btnExitGame;
private PlayerHandCardsViewGroup playerCardSetLayout;
private ShowedCardsViewGroup playerShowCardsLayout;
private ShowedCardsViewGroup leftRobotShowCardsLayout;
private ShowedCardsViewGroup middleRobotShowCardsLayout;
private ShowedCardsViewGroup rightRobotShowCardsLayout;
private TextView leftRobotRemainTextView;
private TextView middleRobotRemainTextView;
private TextView rightRobotRemainTextView;
private TextView timer0TextView;
private TextView timer1TextView;
private TextView timer2TextView;
private TextView timer3TextView;
private Context context;
private String useName;
//由于不知道怎么在ui层判断轮次 所以只能写4个timer了
private CountDownTimer timer0 = new CountDownTimer(10000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
timer0TextView.setText((millisUntilFinished / 1000) + "秒");
}
@Override
public void onFinish() {
timer0TextView.setText("");
if(mPresenter.isFirstHand(0)) {
playerCardSetLayout.reSelect();
playerCardSetLayout.selectFirstCard();
showCards();
}
else
mPresenter.playerPass();
}
};
private CountDownTimer timer1 = new CountDownTimer(10000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
timer1TextView.setText((millisUntilFinished / 1000) + "秒");
}
@Override
public void onFinish() {
timer1TextView.setText("");
}
};
private CountDownTimer timer2 = new CountDownTimer(10000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
timer2TextView.setText((millisUntilFinished / 1000) + "秒");
}
@Override
public void onFinish() {
timer2TextView.setText("");
}
};
private CountDownTimer timer3 = new CountDownTimer(10000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
timer3TextView.setText((millisUntilFinished / 1000) + "秒");
}
@Override
public void onFinish() {
timer3TextView.setText("");
}
};
private deskContract.Presenter mPresenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_desk);
Intent intent=getIntent();
Bundle bundle=intent.getExtras();
useName =bundle.getString("useName");
context = this;
//绑定控件
btnShowCards = findViewById(R.id.show_cards);
btnSkip = findViewById(R.id.skip);
btnReSelect = findViewById(R.id.reselect);
btnExitGame = findViewById(R.id.exit_game_btn);
btnExitGame.setScaleType(ImageView.ScaleType.CENTER_INSIDE);//ImageView.ScaleType.FIT_CENTER
playerCardSetLayout = findViewById(R.id.player_cardset_field);
playerShowCardsLayout = findViewById(R.id.player_showcards_field);
leftRobotShowCardsLayout = findViewById(R.id.robot1_cardset_field);
middleRobotShowCardsLayout = findViewById(R.id.robot2_cardset_field);
rightRobotShowCardsLayout = findViewById(R.id.robot3_cardset_field);
leftRobotRemainTextView = findViewById(R.id.robot_remain1);
middleRobotRemainTextView = findViewById(R.id.robot_remain2);
rightRobotRemainTextView = findViewById(R.id.robot_remain3);
timer0TextView = findViewById(R.id.timer0);
timer1TextView = findViewById(R.id.timer1);
timer2TextView = findViewById(R.id.timer2);
timer3TextView = findViewById(R.id.timer3);
//image resourses
btnShowCards.setImageDrawable(getDrawable(R.drawable.sendcard));
btnSkip.setImageDrawable(getDrawable(R.drawable.dontsend));
btnReSelect.setImageDrawable(getDrawable(R.drawable.again));
btnExitGame.setImageDrawable(getDrawable(R.drawable.fanhui));
//设置button监听事件
btnExitGame.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
btnExitGame.setImageDrawable(getDrawable(R.drawable.fanhuipush));
btnExitGame.setScaleType(ImageView.ScaleType.CENTER_INSIDE);//ImageView.ScaleType.FIT_CENTER
popEscapeDialog();
break;
case MotionEvent.ACTION_UP:
btnExitGame.setImageDrawable(getDrawable(R.drawable.fanhui));
btnExitGame.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
break;
}
return true;
}
});
btnShowCards.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
btnShowCards.setImageDrawable(getDrawable(R.drawable.sendcardpush));
btnShowCards.setScaleType(ImageView.ScaleType.CENTER_INSIDE);//ImageView.ScaleType.FIT_CENTER
showCards();
break;
case MotionEvent.ACTION_UP:
btnShowCards.setImageDrawable(getDrawable(R.drawable.sendcard));
btnShowCards.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
break;
}
return true;
}
});
btnSkip.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
btnSkip.setImageDrawable(getDrawable(R.drawable.dontsentpush));
btnSkip.setScaleType(ImageView.ScaleType.CENTER_INSIDE);//ImageView.ScaleType.FIT_CENTER
mPresenter.playerPass();
playerCardSetLayout.reSelect();
break;
case MotionEvent.ACTION_UP:
btnSkip.setImageDrawable(getDrawable(R.drawable.dontsend));
btnSkip.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
break;
}
return true;
}
});
btnReSelect.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
btnReSelect.setImageDrawable(getDrawable(R.drawable.againpush));
btnReSelect.setScaleType(ImageView.ScaleType.CENTER_INSIDE);//ImageView.ScaleType.FIT_CENTER
playerCardSetLayout.reSelect();
break;
case MotionEvent.ACTION_UP:
btnReSelect.setImageDrawable(getDrawable(R.drawable.again));
btnReSelect.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
break;
}
return true;
}
});
//设置presenter
mPresenter = new deskPresenter(this,useName);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
popEscapeDialog();
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public void setPresenter(@NonNull deskContract.Presenter presenter) {
mPresenter = presenter;
}
@Override
protected void onResume() {
super.onResume();
mPresenter.start();
}
//打印玩家的手牌
@Override
public void displayPlayerHandCards(List<Card> playerCards) {
playerCardSetLayout.displayCards(playerCards);
}
//打印玩家出的牌
@Override
public void displayPlayerCards(List<Card> playerCards) {
playerShowCardsLayout.displayCards(playerCards);
timer0.cancel();
//System.out.print("这个时候应该显示 出的牌");
}
@Override
public void displayRobotCards(List<Card> robotCards,int robot) {
switch (robot)
{
case 1:
leftRobotShowCardsLayout.displayCards(robotCards);
timer1.cancel();
break;
case 2:
middleRobotShowCardsLayout.displayCards(robotCards);
timer2.cancel();
break;
case 3:
rightRobotShowCardsLayout.displayCards(robotCards);
timer3.cancel();
break;
default:
throw new IllegalArgumentException("收到了不存在的机器人");
}
}
@Override
public void displayIrregularity(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
@Override
public void showCards() {
List<Integer> arr;
arr = playerCardSetLayout.getSelected();
if(arr.isEmpty()) {
displayIrregularity("请选择要出的牌");
return ;
}
mPresenter.playerShowCards(arr);
System.out.print("选中的牌的index:");
for(Integer i:arr) {
System.out.print( i );
}
System.out.println();
}
public void setRobotHandCard(List<Card> robotCards,int robot)
{
//注意:setText如果参数是int类型会被当成resourcesID使用
switch (robot)
{
case 1:
leftRobotRemainTextView.setText("剩余:"+ robotCards.size());
break;
case 2:
middleRobotRemainTextView.setText("剩余:"+ robotCards.size());
break;
case 3:
rightRobotRemainTextView.setText("剩余:"+ robotCards.size());
break;
default:
throw new IllegalArgumentException("收到了不存在的机器人");
}
}
public void displayPass(int role)
{
switch (role)
{
case 0:
timer0.cancel();
playerShowCardsLayout.displayPass();
case 1:
timer1.cancel();
leftRobotShowCardsLayout.displayPass();
break;
case 2:
timer2.cancel();
middleRobotShowCardsLayout.displayPass();
break;
case 3:
timer3.cancel();
rightRobotShowCardsLayout.displayPass();
break;
default:
}
}
public void popResultDialog(int winner,int score)
{
android.support.v7.app.AlertDialog.Builder builder = new AlertDialog.Builder(context);
View view = View.inflate(context, R.layout.game_end_dialog_view, null); // 布局文件,自定义
TextView winner_tv = view.findViewById(R.id.winner_tv);
TextView player_score_tv = view.findViewById(R.id.player_score_tv);
switch (winner)
{
case 0:
winner_tv.setText("赢家:玩家");
break;
case 1:
winner_tv.setText("赢家:机器人1");
break;
case 2:
winner_tv.setText("赢家:机器人2");
break;
case 3:
winner_tv.setText("赢家:机器人3");
break;
default:
}
player_score_tv.setText("玩家得分:"+score);
builder.setTitle("游戏结果");
builder.setIcon(R.mipmap.ic_launcher);//设置对话框icon
AlertDialog dialog = builder.create();
dialog.setView(view);
dialog.setButton(DialogInterface.BUTTON_POSITIVE,"再来一把", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
onResume();
dialog.dismiss();//关闭对话框
}
});
dialog.setButton(DialogInterface.BUTTON_NEUTRAL,"不了不了", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(deskActivity.this , MainActivity.class);
Bundle bundle=new Bundle(); //创建并实例化一个Bundle对象
bundle.putCharSequence("useName", useName); //保存用户名
intent.putExtras(bundle); //将Bundle对象添加到Intent对象中
startActivity(intent);
dialog.dismiss();//关闭对话框
}
});
dialog.setCancelable(false);
dialog.show();
}
public void popEscapeDialog()
{
android.support.v7.app.AlertDialog.Builder builder = new AlertDialog.Builder(context);
View view = View.inflate(context, R.layout.escape_dialog_view, null); // 布局文件,自定义
builder.setTitle("逃跑");
builder.setIcon(R.mipmap.ic_launcher);//设置对话框icon
AlertDialog dialog = builder.create();
dialog.setView(view);
dialog.setButton(DialogInterface.BUTTON_POSITIVE,"继续游戏", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();//关闭对话框
}
});
dialog.setButton(DialogInterface.BUTTON_NEUTRAL,"逃跑", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mPresenter.escape();
Intent intent = new Intent(deskActivity.this , MainActivity.class);
Bundle bundle=new Bundle();
bundle.putCharSequence("useName",useName);
intent.putExtras(bundle);
startActivity(intent);
dialog.dismiss();//关闭对话框
}
});
dialog.show();
}
public void startTimer(int role)
{
switch (role)
{
case 0:
timer0.start();
break;
case 1:
timer1.start();
break;
case 2:
timer2.start();
break;
case 3:
timer3.start();
break;
default:
}
}
/*
*函数名:removeShowedCards
* 功能:清除玩家或机器人出牌区的牌
* 参数:0.玩家 1.左边机器人 2.中间机器人 3.右边机器人
* */
public void removeShowedCards(int select)
{
switch (select)
{
case 0:
playerShowCardsLayout.removeAllViews();
break;
case 1:
leftRobotShowCardsLayout.removeAllViews();
break;
case 2:
middleRobotShowCardsLayout.removeAllViews();
break;
case 3:
rightRobotShowCardsLayout.removeAllViews();
default:
}
}
}
| AhaLims/UML-work | UMLwork/app/src/main/java/cdd/desk/view/deskActivity.java | 3,691 | /*
*函数名:removeShowedCards
* 功能:清除玩家或机器人出牌区的牌
* 参数:0.玩家 1.左边机器人 2.中间机器人 3.右边机器人
* */ | block_comment | zh-cn | package cdd.desk.view;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.uml.umlwork.R;
import java.util.List;
import cdd.desk.model.card.Card;
import cdd.desk.contract.deskContract;
import cdd.desk.presenter.deskPresenter;
import cdd.menu.view.MainActivity;
/**
* Main UI for the add task screen. Users can enter a task title and description.
*/
public class deskActivity extends AppCompatActivity implements deskContract.View{
private ImageButton btnShowCards;
private ImageButton btnSkip;
private ImageButton btnReSelect;
private ImageButton btnExitGame;
private PlayerHandCardsViewGroup playerCardSetLayout;
private ShowedCardsViewGroup playerShowCardsLayout;
private ShowedCardsViewGroup leftRobotShowCardsLayout;
private ShowedCardsViewGroup middleRobotShowCardsLayout;
private ShowedCardsViewGroup rightRobotShowCardsLayout;
private TextView leftRobotRemainTextView;
private TextView middleRobotRemainTextView;
private TextView rightRobotRemainTextView;
private TextView timer0TextView;
private TextView timer1TextView;
private TextView timer2TextView;
private TextView timer3TextView;
private Context context;
private String useName;
//由于不知道怎么在ui层判断轮次 所以只能写4个timer了
private CountDownTimer timer0 = new CountDownTimer(10000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
timer0TextView.setText((millisUntilFinished / 1000) + "秒");
}
@Override
public void onFinish() {
timer0TextView.setText("");
if(mPresenter.isFirstHand(0)) {
playerCardSetLayout.reSelect();
playerCardSetLayout.selectFirstCard();
showCards();
}
else
mPresenter.playerPass();
}
};
private CountDownTimer timer1 = new CountDownTimer(10000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
timer1TextView.setText((millisUntilFinished / 1000) + "秒");
}
@Override
public void onFinish() {
timer1TextView.setText("");
}
};
private CountDownTimer timer2 = new CountDownTimer(10000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
timer2TextView.setText((millisUntilFinished / 1000) + "秒");
}
@Override
public void onFinish() {
timer2TextView.setText("");
}
};
private CountDownTimer timer3 = new CountDownTimer(10000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
timer3TextView.setText((millisUntilFinished / 1000) + "秒");
}
@Override
public void onFinish() {
timer3TextView.setText("");
}
};
private deskContract.Presenter mPresenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_desk);
Intent intent=getIntent();
Bundle bundle=intent.getExtras();
useName =bundle.getString("useName");
context = this;
//绑定控件
btnShowCards = findViewById(R.id.show_cards);
btnSkip = findViewById(R.id.skip);
btnReSelect = findViewById(R.id.reselect);
btnExitGame = findViewById(R.id.exit_game_btn);
btnExitGame.setScaleType(ImageView.ScaleType.CENTER_INSIDE);//ImageView.ScaleType.FIT_CENTER
playerCardSetLayout = findViewById(R.id.player_cardset_field);
playerShowCardsLayout = findViewById(R.id.player_showcards_field);
leftRobotShowCardsLayout = findViewById(R.id.robot1_cardset_field);
middleRobotShowCardsLayout = findViewById(R.id.robot2_cardset_field);
rightRobotShowCardsLayout = findViewById(R.id.robot3_cardset_field);
leftRobotRemainTextView = findViewById(R.id.robot_remain1);
middleRobotRemainTextView = findViewById(R.id.robot_remain2);
rightRobotRemainTextView = findViewById(R.id.robot_remain3);
timer0TextView = findViewById(R.id.timer0);
timer1TextView = findViewById(R.id.timer1);
timer2TextView = findViewById(R.id.timer2);
timer3TextView = findViewById(R.id.timer3);
//image resourses
btnShowCards.setImageDrawable(getDrawable(R.drawable.sendcard));
btnSkip.setImageDrawable(getDrawable(R.drawable.dontsend));
btnReSelect.setImageDrawable(getDrawable(R.drawable.again));
btnExitGame.setImageDrawable(getDrawable(R.drawable.fanhui));
//设置button监听事件
btnExitGame.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
btnExitGame.setImageDrawable(getDrawable(R.drawable.fanhuipush));
btnExitGame.setScaleType(ImageView.ScaleType.CENTER_INSIDE);//ImageView.ScaleType.FIT_CENTER
popEscapeDialog();
break;
case MotionEvent.ACTION_UP:
btnExitGame.setImageDrawable(getDrawable(R.drawable.fanhui));
btnExitGame.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
break;
}
return true;
}
});
btnShowCards.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
btnShowCards.setImageDrawable(getDrawable(R.drawable.sendcardpush));
btnShowCards.setScaleType(ImageView.ScaleType.CENTER_INSIDE);//ImageView.ScaleType.FIT_CENTER
showCards();
break;
case MotionEvent.ACTION_UP:
btnShowCards.setImageDrawable(getDrawable(R.drawable.sendcard));
btnShowCards.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
break;
}
return true;
}
});
btnSkip.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
btnSkip.setImageDrawable(getDrawable(R.drawable.dontsentpush));
btnSkip.setScaleType(ImageView.ScaleType.CENTER_INSIDE);//ImageView.ScaleType.FIT_CENTER
mPresenter.playerPass();
playerCardSetLayout.reSelect();
break;
case MotionEvent.ACTION_UP:
btnSkip.setImageDrawable(getDrawable(R.drawable.dontsend));
btnSkip.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
break;
}
return true;
}
});
btnReSelect.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
btnReSelect.setImageDrawable(getDrawable(R.drawable.againpush));
btnReSelect.setScaleType(ImageView.ScaleType.CENTER_INSIDE);//ImageView.ScaleType.FIT_CENTER
playerCardSetLayout.reSelect();
break;
case MotionEvent.ACTION_UP:
btnReSelect.setImageDrawable(getDrawable(R.drawable.again));
btnReSelect.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
break;
}
return true;
}
});
//设置presenter
mPresenter = new deskPresenter(this,useName);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
popEscapeDialog();
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public void setPresenter(@NonNull deskContract.Presenter presenter) {
mPresenter = presenter;
}
@Override
protected void onResume() {
super.onResume();
mPresenter.start();
}
//打印玩家的手牌
@Override
public void displayPlayerHandCards(List<Card> playerCards) {
playerCardSetLayout.displayCards(playerCards);
}
//打印玩家出的牌
@Override
public void displayPlayerCards(List<Card> playerCards) {
playerShowCardsLayout.displayCards(playerCards);
timer0.cancel();
//System.out.print("这个时候应该显示 出的牌");
}
@Override
public void displayRobotCards(List<Card> robotCards,int robot) {
switch (robot)
{
case 1:
leftRobotShowCardsLayout.displayCards(robotCards);
timer1.cancel();
break;
case 2:
middleRobotShowCardsLayout.displayCards(robotCards);
timer2.cancel();
break;
case 3:
rightRobotShowCardsLayout.displayCards(robotCards);
timer3.cancel();
break;
default:
throw new IllegalArgumentException("收到了不存在的机器人");
}
}
@Override
public void displayIrregularity(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
@Override
public void showCards() {
List<Integer> arr;
arr = playerCardSetLayout.getSelected();
if(arr.isEmpty()) {
displayIrregularity("请选择要出的牌");
return ;
}
mPresenter.playerShowCards(arr);
System.out.print("选中的牌的index:");
for(Integer i:arr) {
System.out.print( i );
}
System.out.println();
}
public void setRobotHandCard(List<Card> robotCards,int robot)
{
//注意:setText如果参数是int类型会被当成resourcesID使用
switch (robot)
{
case 1:
leftRobotRemainTextView.setText("剩余:"+ robotCards.size());
break;
case 2:
middleRobotRemainTextView.setText("剩余:"+ robotCards.size());
break;
case 3:
rightRobotRemainTextView.setText("剩余:"+ robotCards.size());
break;
default:
throw new IllegalArgumentException("收到了不存在的机器人");
}
}
public void displayPass(int role)
{
switch (role)
{
case 0:
timer0.cancel();
playerShowCardsLayout.displayPass();
case 1:
timer1.cancel();
leftRobotShowCardsLayout.displayPass();
break;
case 2:
timer2.cancel();
middleRobotShowCardsLayout.displayPass();
break;
case 3:
timer3.cancel();
rightRobotShowCardsLayout.displayPass();
break;
default:
}
}
public void popResultDialog(int winner,int score)
{
android.support.v7.app.AlertDialog.Builder builder = new AlertDialog.Builder(context);
View view = View.inflate(context, R.layout.game_end_dialog_view, null); // 布局文件,自定义
TextView winner_tv = view.findViewById(R.id.winner_tv);
TextView player_score_tv = view.findViewById(R.id.player_score_tv);
switch (winner)
{
case 0:
winner_tv.setText("赢家:玩家");
break;
case 1:
winner_tv.setText("赢家:机器人1");
break;
case 2:
winner_tv.setText("赢家:机器人2");
break;
case 3:
winner_tv.setText("赢家:机器人3");
break;
default:
}
player_score_tv.setText("玩家得分:"+score);
builder.setTitle("游戏结果");
builder.setIcon(R.mipmap.ic_launcher);//设置对话框icon
AlertDialog dialog = builder.create();
dialog.setView(view);
dialog.setButton(DialogInterface.BUTTON_POSITIVE,"再来一把", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
onResume();
dialog.dismiss();//关闭对话框
}
});
dialog.setButton(DialogInterface.BUTTON_NEUTRAL,"不了不了", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(deskActivity.this , MainActivity.class);
Bundle bundle=new Bundle(); //创建并实例化一个Bundle对象
bundle.putCharSequence("useName", useName); //保存用户名
intent.putExtras(bundle); //将Bundle对象添加到Intent对象中
startActivity(intent);
dialog.dismiss();//关闭对话框
}
});
dialog.setCancelable(false);
dialog.show();
}
public void popEscapeDialog()
{
android.support.v7.app.AlertDialog.Builder builder = new AlertDialog.Builder(context);
View view = View.inflate(context, R.layout.escape_dialog_view, null); // 布局文件,自定义
builder.setTitle("逃跑");
builder.setIcon(R.mipmap.ic_launcher);//设置对话框icon
AlertDialog dialog = builder.create();
dialog.setView(view);
dialog.setButton(DialogInterface.BUTTON_POSITIVE,"继续游戏", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();//关闭对话框
}
});
dialog.setButton(DialogInterface.BUTTON_NEUTRAL,"逃跑", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mPresenter.escape();
Intent intent = new Intent(deskActivity.this , MainActivity.class);
Bundle bundle=new Bundle();
bundle.putCharSequence("useName",useName);
intent.putExtras(bundle);
startActivity(intent);
dialog.dismiss();//关闭对话框
}
});
dialog.show();
}
public void startTimer(int role)
{
switch (role)
{
case 0:
timer0.start();
break;
case 1:
timer1.start();
break;
case 2:
timer2.start();
break;
case 3:
timer3.start();
break;
default:
}
}
/*
*函数名 <SUF>*/
public void removeShowedCards(int select)
{
switch (select)
{
case 0:
playerShowCardsLayout.removeAllViews();
break;
case 1:
leftRobotShowCardsLayout.removeAllViews();
break;
case 2:
middleRobotShowCardsLayout.removeAllViews();
break;
case 3:
rightRobotShowCardsLayout.removeAllViews();
default:
}
}
}
| true |
65495_1 | package com.ahogek.lotterydrawdemo;
import com.ahogek.lotterydrawdemo.entity.LotteryData;
import com.ahogek.lotterydrawdemo.repository.LotteryDataRepository;
import com.ahogek.lotterydrawdemo.service.LotteryDataService;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
@EnableTransactionManagement
@SpringBootApplication
public class LotteryDrawDemoApplication {
private static final Logger LOG = LoggerFactory.getLogger(LotteryDrawDemoApplication.class);
private final Random random = new Random();
public static void main(String[] args) {
SpringApplication.run(LotteryDrawDemoApplication.class, args);
}
private static void checkNewInputDrawNumber(LotteryDataRepository lotteryDateRepository, List<List<String>> inputNewDrawNumber) {
if (inputNewDrawNumber != null && !inputNewDrawNumber.isEmpty()) {
// 遍历 inputNewDrawNumber 集合
inputNewDrawNumber.forEach(itemNumbers -> {
// 遍历每一项,其中第一项为日期,先判断数据库有无该日期的数据,如果没有才执行操作
LocalDate date = LocalDate.parse(itemNumbers.getFirst(),
DateTimeFormatter.ofPattern("yyyy-MM-dd"));
if (lotteryDateRepository.countByLotteryDrawTime(date) == 0) {
List<LotteryData> insertList = new ArrayList<>();
for (int i = 1; i < itemNumbers.size(); i++) {
LotteryData lotteryDrawNumber = new LotteryData();
lotteryDrawNumber.setLotteryDrawNumber(itemNumbers.get(i));
lotteryDrawNumber.setLotteryDrawTime(date);
lotteryDrawNumber.setLotteryDrawNumberType(i - 1);
insertList.add(lotteryDrawNumber);
}
if (!insertList.isEmpty())
lotteryDateRepository.saveAll(insertList);
}
});
}
}
public static void groupAllData(List<List<String>> allData, List<LotteryData> all) {
for (int i = 0; i < 7; i++) {
int type = i;
allData.add(all.stream().filter(item -> type == item.getLotteryDrawNumberType())
.map(LotteryData::getLotteryDrawNumber).toList());
}
}
private static long getCount(LocalDate lastDate, LocalDate now) {
long count = 0;
LocalDate nextLotteryDate = lastDate.plusDays(1);
while (nextLotteryDate.isBefore(now) || (nextLotteryDate.isEqual(now) && LocalDateTime.now().getHour() >= 22)) {
if (nextLotteryDate.getDayOfWeek() == DayOfWeek.SATURDAY) {
nextLotteryDate = nextLotteryDate.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
count++;
} else if (nextLotteryDate.getDayOfWeek() == DayOfWeek.MONDAY) {
nextLotteryDate = nextLotteryDate.with(TemporalAdjusters.next(DayOfWeek.WEDNESDAY));
count++;
} else if (nextLotteryDate.getDayOfWeek() == DayOfWeek.WEDNESDAY) {
nextLotteryDate = nextLotteryDate.with(TemporalAdjusters.next(DayOfWeek.SATURDAY));
count++;
} else {
nextLotteryDate = nextLotteryDate.plusDays(1);
}
}
return count;
}
@Bean
public CommandLineRunner getRandomLotteryNumber(LotteryDataService service, LotteryRequestManager request, LotteryDataRepository lotteryDateRepository) {
return args -> {
List<LotteryData> all = service.findAll();
if (all.isEmpty())
request.setData();
// 获取数据库中最新的一期数据的时间
LocalDate lastDate = lotteryDateRepository.findTopByOrderByLotteryDrawTimeDesc().getLotteryDrawTime();
// 根据但前时间判断 lastDate 是否是最新一期,彩票每周一 三 六开奖
LocalDate now = LocalDate.now();
if (ChronoUnit.DAYS.between(lastDate, now) >= 2) {
// 判断 lastDate 直到今天为止少了多少次开奖
long count = getCount(lastDate, now);
if (count > 0) {
// 根据 count 查询彩票网数据
JSONObject response = request.getNextPage(Math.toIntExact(count));
List<List<String>> inputNewDrawNumber = new ArrayList<>();
JSONArray list = response.getJSONObject("value").getJSONArray("list");
for (int i = 0; i < list.size(); i++) {
JSONObject data = list.getJSONObject(i);
String[] drawNumbers = data.getString("lotteryDrawResult").split(" ");
List<String> item = new ArrayList<>();
item.add(LocalDate.ofInstant(data.getDate("lotteryDrawTime").toInstant(),
ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
item.addAll(Arrays.asList(drawNumbers).subList(0, 7));
inputNewDrawNumber.add(item);
}
inputNewDrawNumber = inputNewDrawNumber.reversed();
checkNewInputDrawNumber(lotteryDateRepository, inputNewDrawNumber);
}
}
List<String> result = new ArrayList<>((int) (7 / 0.75f + 1));
// 前区五个球
Set<String> front = new HashSet<>();
// 后区两个球
Set<String> back = new HashSet<>();
List<List<String>> allDataGroup = new ArrayList<>();
groupAllData(allDataGroup, all);
for (int i = 0; i < 7; i++) {
// 随机一个列表里的String
drawNumbers(i, allDataGroup, front, back);
}
// 分别排序前后组
front.stream().sorted().forEach(result::add);
back.stream().sorted().forEach(result::add);
LOG.info("随机摇奖号码为:{},祝你好运!", result);
};
}
public void drawNumbers(int i, List<List<String>> allDataGroup, Set<String> front, Set<String> back) {
if (i < 5) {
do {
int index = this.random.nextInt(allDataGroup.get(i).size());
front.add(allDataGroup.get(i).get(index));
} while (front.size() != i + 1);
} else {
do {
int index = this.random.nextInt(allDataGroup.get(i).size());
back.add(allDataGroup.get(i).get(index));
} while (back.size() != i - 5 + 1);
}
}
}
| AhogeK/lottery-draw-demo | src/main/java/com/ahogek/lotterydrawdemo/LotteryDrawDemoApplication.java | 1,733 | // 遍历每一项,其中第一项为日期,先判断数据库有无该日期的数据,如果没有才执行操作 | line_comment | zh-cn | package com.ahogek.lotterydrawdemo;
import com.ahogek.lotterydrawdemo.entity.LotteryData;
import com.ahogek.lotterydrawdemo.repository.LotteryDataRepository;
import com.ahogek.lotterydrawdemo.service.LotteryDataService;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
@EnableTransactionManagement
@SpringBootApplication
public class LotteryDrawDemoApplication {
private static final Logger LOG = LoggerFactory.getLogger(LotteryDrawDemoApplication.class);
private final Random random = new Random();
public static void main(String[] args) {
SpringApplication.run(LotteryDrawDemoApplication.class, args);
}
private static void checkNewInputDrawNumber(LotteryDataRepository lotteryDateRepository, List<List<String>> inputNewDrawNumber) {
if (inputNewDrawNumber != null && !inputNewDrawNumber.isEmpty()) {
// 遍历 inputNewDrawNumber 集合
inputNewDrawNumber.forEach(itemNumbers -> {
// 遍历 <SUF>
LocalDate date = LocalDate.parse(itemNumbers.getFirst(),
DateTimeFormatter.ofPattern("yyyy-MM-dd"));
if (lotteryDateRepository.countByLotteryDrawTime(date) == 0) {
List<LotteryData> insertList = new ArrayList<>();
for (int i = 1; i < itemNumbers.size(); i++) {
LotteryData lotteryDrawNumber = new LotteryData();
lotteryDrawNumber.setLotteryDrawNumber(itemNumbers.get(i));
lotteryDrawNumber.setLotteryDrawTime(date);
lotteryDrawNumber.setLotteryDrawNumberType(i - 1);
insertList.add(lotteryDrawNumber);
}
if (!insertList.isEmpty())
lotteryDateRepository.saveAll(insertList);
}
});
}
}
public static void groupAllData(List<List<String>> allData, List<LotteryData> all) {
for (int i = 0; i < 7; i++) {
int type = i;
allData.add(all.stream().filter(item -> type == item.getLotteryDrawNumberType())
.map(LotteryData::getLotteryDrawNumber).toList());
}
}
private static long getCount(LocalDate lastDate, LocalDate now) {
long count = 0;
LocalDate nextLotteryDate = lastDate.plusDays(1);
while (nextLotteryDate.isBefore(now) || (nextLotteryDate.isEqual(now) && LocalDateTime.now().getHour() >= 22)) {
if (nextLotteryDate.getDayOfWeek() == DayOfWeek.SATURDAY) {
nextLotteryDate = nextLotteryDate.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
count++;
} else if (nextLotteryDate.getDayOfWeek() == DayOfWeek.MONDAY) {
nextLotteryDate = nextLotteryDate.with(TemporalAdjusters.next(DayOfWeek.WEDNESDAY));
count++;
} else if (nextLotteryDate.getDayOfWeek() == DayOfWeek.WEDNESDAY) {
nextLotteryDate = nextLotteryDate.with(TemporalAdjusters.next(DayOfWeek.SATURDAY));
count++;
} else {
nextLotteryDate = nextLotteryDate.plusDays(1);
}
}
return count;
}
@Bean
public CommandLineRunner getRandomLotteryNumber(LotteryDataService service, LotteryRequestManager request, LotteryDataRepository lotteryDateRepository) {
return args -> {
List<LotteryData> all = service.findAll();
if (all.isEmpty())
request.setData();
// 获取数据库中最新的一期数据的时间
LocalDate lastDate = lotteryDateRepository.findTopByOrderByLotteryDrawTimeDesc().getLotteryDrawTime();
// 根据但前时间判断 lastDate 是否是最新一期,彩票每周一 三 六开奖
LocalDate now = LocalDate.now();
if (ChronoUnit.DAYS.between(lastDate, now) >= 2) {
// 判断 lastDate 直到今天为止少了多少次开奖
long count = getCount(lastDate, now);
if (count > 0) {
// 根据 count 查询彩票网数据
JSONObject response = request.getNextPage(Math.toIntExact(count));
List<List<String>> inputNewDrawNumber = new ArrayList<>();
JSONArray list = response.getJSONObject("value").getJSONArray("list");
for (int i = 0; i < list.size(); i++) {
JSONObject data = list.getJSONObject(i);
String[] drawNumbers = data.getString("lotteryDrawResult").split(" ");
List<String> item = new ArrayList<>();
item.add(LocalDate.ofInstant(data.getDate("lotteryDrawTime").toInstant(),
ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
item.addAll(Arrays.asList(drawNumbers).subList(0, 7));
inputNewDrawNumber.add(item);
}
inputNewDrawNumber = inputNewDrawNumber.reversed();
checkNewInputDrawNumber(lotteryDateRepository, inputNewDrawNumber);
}
}
List<String> result = new ArrayList<>((int) (7 / 0.75f + 1));
// 前区五个球
Set<String> front = new HashSet<>();
// 后区两个球
Set<String> back = new HashSet<>();
List<List<String>> allDataGroup = new ArrayList<>();
groupAllData(allDataGroup, all);
for (int i = 0; i < 7; i++) {
// 随机一个列表里的String
drawNumbers(i, allDataGroup, front, back);
}
// 分别排序前后组
front.stream().sorted().forEach(result::add);
back.stream().sorted().forEach(result::add);
LOG.info("随机摇奖号码为:{},祝你好运!", result);
};
}
public void drawNumbers(int i, List<List<String>> allDataGroup, Set<String> front, Set<String> back) {
if (i < 5) {
do {
int index = this.random.nextInt(allDataGroup.get(i).size());
front.add(allDataGroup.get(i).get(index));
} while (front.size() != i + 1);
} else {
do {
int index = this.random.nextInt(allDataGroup.get(i).size());
back.add(allDataGroup.get(i).get(index));
} while (back.size() != i - 5 + 1);
}
}
}
| false |
38818_22 | package cn.ltwc.cft.data;
import android.Manifest;
import java.io.File;
import cn.ltwc.cft.MyApplication;
import cn.ltwc.cft.utils.FileUtils;
/**
* TODO:本应用的常量类
*
* @author huangshang 2015-11-10 下午2:22:42
* @Modified_By:
*/
public class Constant {
public static long exitTime = 2000;// 程序退出时间
public static boolean DEBUG = true;
public static final String SHARE_DEFAULT_IMAGE = "http://imengu.cn/Ahuangshang/img/shareImg.png";
public static final String DEFAULT_HOST_NAME = "http://imengu.cn/";
// 农历部分假日
public final static String[] lunarHoliday = new String[]{"0101 春节",
"0115 元宵节", "0202 龙抬头", "0504 皇上生辰", "0505 端午", "0707 乞巧节", "0715 中元节",
"0815 中秋节", "0909 重阳节", "1120 皇后生辰", "1208 腊八", "1224 小年", "1230 除夕"};
// 公历部分节假日
public final static String[] solarHoliday = new String[]{"0101 元旦",
"0214 情人节", "0308 妇女节", "0312 植树节", "0401 愚人节", "0501 劳动节",
"0504 青年节", "0512 护士节", "0601 儿童节", "0701 建党节", "0701 香港回归", "0801 建军节",
"0903 抗战胜利", "0910 教师节", "0918 九一八", "0928 孔子诞辰", "1001 国庆节",
"1006 老人节", "1024 联合国日", "1213 国家公祭", "1220 澳门回归", "1225 圣诞",};
// 所有的节日和二十四节气
public final static String[] holiday = new String[]{"春节", "元宵节", "龙抬头", "皇上生辰",
"端午", "乞巧节", "中元节", "中秋节", "重阳节", "腊八", "小年", "除夕", "元旦", "情人节",
"妇女节", "植树节", "愚人节", "劳动节", "青年节", "护士节", "儿童节", "建党节、香港回归纪念日",
"建军节", "抗战胜利纪念日", "教师节", "九一八事变", "孔子诞辰", "国庆节", "老人", "联合国日",
"南京大屠杀国家公祭日", "澳门回归纪念日", "圣诞", "大寒", "雨水", "春分", "谷雨", "小满", "夏至",
"大暑", "处暑", "秋分", "霜降", "小雪", "冬至", "小寒", "立春", "惊蛰", "清明", "立夏",
"芒种", "小暑", "立秋", "白露", "寒露", "立冬", "大雪"};
// 所有放假的节日
public final static String[] FANGJIAHOLIDAY = new String[]{"春节", "皇上生辰", "皇后生辰",
"端午", "中秋节", "除夕", "元旦", "妇女节", "劳动节", "儿童节", "国庆节", "清明"};
public final static String[] YUEEN = new String[]{"Jan.", "Feb.", "Mar.",
"Apr.", "May.", "Jun.", "Jul.", "Aug.", "Sept.", "Oct.", "Nov.",
"Dec."};
public static final String NOTE_BEAN = "noteBean";
public static final String FLAG = "flag";
public static final String RILIINFO = "riliInfo";
public static final String APPPACKAGENAME = "cn.ltwc.cft";
public static final String WEBURL = "webUrl";
public static final String WEBTITLE = "webTitle";
public static final String IMGURL_LIST = "imgList";
public static final String POSITION = "position";
public static final String SHARE_TYPE_TEXT = "text/plain";
public static final String SHARE_TYPE_IMG = "image/*";
public static final String SHARE_TYPE_AUDIO = "audio/*";
public static final String SHARE_TYPE_WEB = "image/text";
public static final String TYPE = "type";
public static final String SHARE_MESSAGE = "share_msg";
public static final String SHARE_IMG = "share_img";
public static final int LOADING_VIEW_DELAYED = 1000;
public static final String LOT_URL = "http://3g.iletou.com/";
public static final String GET_XIAO_MI_LAYOUT = "http://adv.sec.miui.com/info/";//获取小米的布局
public static final String GET_XIAO_MI_LAYOUT2 = "https://wtradv.market.xiaomi.com/v1/";//获取小米的布局
public static final String GET_WEATHER = "http://www.sojson.com/open/api/weather/json.shtml/";//获取天气
public static final String URL_HISTORY_TODAY_JUHE = "http://v.juhe.cn/todayOnhistory/";// 历史上的今天聚合数据接口地址
public static final String URL_GET_GIRL_IMG = "http://image.baidu.com/search/";//获取美女图片的地址
public static final String URL_GET_JOKE = "http://xiaobaxiaoba.com/";//获取笑话的接口
public static final int VIEW_PAGER_OFF_SCREEN_PAGE_LIMIT = 3;//viewPager缓存页数
public static final int PAGE_SIZE = 20;//数据加载页数
public static final File directory = FileUtils.getCacheDirectory(MyApplication.getInstance(), "DownLoad");
public static final String ACCESS_LOCATION_EXTRA_COMMANDS = Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS;//定位的权限
public static final String ACCESS_FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;//定位的权限
public static final String ACCESS_COARSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;//定位的权限
public static final String JS_NAME = "jsName";//加载的js文件名
public static final String OPTIONS = "options";//传递的参数
public static final String SHARE_URL = "shareUrl";//分享的URL。
public static final String SHARE_IMAGE_PATH = "shareImagePath";//分享链接的图片
public static final int START_ACTIVITY_FINISH = 0x9999;
public static final int LOCATION_SUCCESS = 0x9998;
public static final String CAN_GO_BACK = "canGoBack";
public static final String BAR_SHOW = "barShow";
public static final String TITLE = "title";
public static final String CONTENT = "content";
public static final String IMG_URL = "imgUrl";
public static final String TABS = "tabs";
public static final String MSG = "msg";
public static final String IMAGE_PATH = "imgPath";
public static final String AD_IMG_URL = "adUrl";
public static final String AD_SCHEME_URL = "adSchemeUrl";
public static final String SHARE_DEC = "shareDec";
}
| Ahuangshang/weex-android-calander | Calander/app/src/main/java/cn/ltwc/cft/data/Constant.java | 1,984 | //分享的URL。 | line_comment | zh-cn | package cn.ltwc.cft.data;
import android.Manifest;
import java.io.File;
import cn.ltwc.cft.MyApplication;
import cn.ltwc.cft.utils.FileUtils;
/**
* TODO:本应用的常量类
*
* @author huangshang 2015-11-10 下午2:22:42
* @Modified_By:
*/
public class Constant {
public static long exitTime = 2000;// 程序退出时间
public static boolean DEBUG = true;
public static final String SHARE_DEFAULT_IMAGE = "http://imengu.cn/Ahuangshang/img/shareImg.png";
public static final String DEFAULT_HOST_NAME = "http://imengu.cn/";
// 农历部分假日
public final static String[] lunarHoliday = new String[]{"0101 春节",
"0115 元宵节", "0202 龙抬头", "0504 皇上生辰", "0505 端午", "0707 乞巧节", "0715 中元节",
"0815 中秋节", "0909 重阳节", "1120 皇后生辰", "1208 腊八", "1224 小年", "1230 除夕"};
// 公历部分节假日
public final static String[] solarHoliday = new String[]{"0101 元旦",
"0214 情人节", "0308 妇女节", "0312 植树节", "0401 愚人节", "0501 劳动节",
"0504 青年节", "0512 护士节", "0601 儿童节", "0701 建党节", "0701 香港回归", "0801 建军节",
"0903 抗战胜利", "0910 教师节", "0918 九一八", "0928 孔子诞辰", "1001 国庆节",
"1006 老人节", "1024 联合国日", "1213 国家公祭", "1220 澳门回归", "1225 圣诞",};
// 所有的节日和二十四节气
public final static String[] holiday = new String[]{"春节", "元宵节", "龙抬头", "皇上生辰",
"端午", "乞巧节", "中元节", "中秋节", "重阳节", "腊八", "小年", "除夕", "元旦", "情人节",
"妇女节", "植树节", "愚人节", "劳动节", "青年节", "护士节", "儿童节", "建党节、香港回归纪念日",
"建军节", "抗战胜利纪念日", "教师节", "九一八事变", "孔子诞辰", "国庆节", "老人", "联合国日",
"南京大屠杀国家公祭日", "澳门回归纪念日", "圣诞", "大寒", "雨水", "春分", "谷雨", "小满", "夏至",
"大暑", "处暑", "秋分", "霜降", "小雪", "冬至", "小寒", "立春", "惊蛰", "清明", "立夏",
"芒种", "小暑", "立秋", "白露", "寒露", "立冬", "大雪"};
// 所有放假的节日
public final static String[] FANGJIAHOLIDAY = new String[]{"春节", "皇上生辰", "皇后生辰",
"端午", "中秋节", "除夕", "元旦", "妇女节", "劳动节", "儿童节", "国庆节", "清明"};
public final static String[] YUEEN = new String[]{"Jan.", "Feb.", "Mar.",
"Apr.", "May.", "Jun.", "Jul.", "Aug.", "Sept.", "Oct.", "Nov.",
"Dec."};
public static final String NOTE_BEAN = "noteBean";
public static final String FLAG = "flag";
public static final String RILIINFO = "riliInfo";
public static final String APPPACKAGENAME = "cn.ltwc.cft";
public static final String WEBURL = "webUrl";
public static final String WEBTITLE = "webTitle";
public static final String IMGURL_LIST = "imgList";
public static final String POSITION = "position";
public static final String SHARE_TYPE_TEXT = "text/plain";
public static final String SHARE_TYPE_IMG = "image/*";
public static final String SHARE_TYPE_AUDIO = "audio/*";
public static final String SHARE_TYPE_WEB = "image/text";
public static final String TYPE = "type";
public static final String SHARE_MESSAGE = "share_msg";
public static final String SHARE_IMG = "share_img";
public static final int LOADING_VIEW_DELAYED = 1000;
public static final String LOT_URL = "http://3g.iletou.com/";
public static final String GET_XIAO_MI_LAYOUT = "http://adv.sec.miui.com/info/";//获取小米的布局
public static final String GET_XIAO_MI_LAYOUT2 = "https://wtradv.market.xiaomi.com/v1/";//获取小米的布局
public static final String GET_WEATHER = "http://www.sojson.com/open/api/weather/json.shtml/";//获取天气
public static final String URL_HISTORY_TODAY_JUHE = "http://v.juhe.cn/todayOnhistory/";// 历史上的今天聚合数据接口地址
public static final String URL_GET_GIRL_IMG = "http://image.baidu.com/search/";//获取美女图片的地址
public static final String URL_GET_JOKE = "http://xiaobaxiaoba.com/";//获取笑话的接口
public static final int VIEW_PAGER_OFF_SCREEN_PAGE_LIMIT = 3;//viewPager缓存页数
public static final int PAGE_SIZE = 20;//数据加载页数
public static final File directory = FileUtils.getCacheDirectory(MyApplication.getInstance(), "DownLoad");
public static final String ACCESS_LOCATION_EXTRA_COMMANDS = Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS;//定位的权限
public static final String ACCESS_FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;//定位的权限
public static final String ACCESS_COARSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;//定位的权限
public static final String JS_NAME = "jsName";//加载的js文件名
public static final String OPTIONS = "options";//传递的参数
public static final String SHARE_URL = "shareUrl";//分享 <SUF>
public static final String SHARE_IMAGE_PATH = "shareImagePath";//分享链接的图片
public static final int START_ACTIVITY_FINISH = 0x9999;
public static final int LOCATION_SUCCESS = 0x9998;
public static final String CAN_GO_BACK = "canGoBack";
public static final String BAR_SHOW = "barShow";
public static final String TITLE = "title";
public static final String CONTENT = "content";
public static final String IMG_URL = "imgUrl";
public static final String TABS = "tabs";
public static final String MSG = "msg";
public static final String IMAGE_PATH = "imgPath";
public static final String AD_IMG_URL = "adUrl";
public static final String AD_SCHEME_URL = "adSchemeUrl";
public static final String SHARE_DEC = "shareDec";
}
| true |
55261_13 | package cn.aijiang.aop;
import org.aspectj.lang.annotation.*;
/**
* 定义一个切点
*
* 对于演出这个整体业务来说,观众在现实上表现得很重要(观众多,恰到钱就越多嘛)
* 但在业务代码里,我们只关心演出业务,观众应作为切面来看待
*/
@Aspect
public class Audience {
// /**
// * 表演开始前的表现一
// */
// @Before("execution(* cn.aijiang.aop.Performance.perform(..))")
// public void silenceCellPhones() {
// System.out.println("手机静音了嗷。");
// }
//
// /**
// * 表演开始前的表现二
// */
// @Before("execution(* cn.aijiang.aop.Performance.perform(..))")
// public void takeSeats() {
// System.out.println("谈话停止了嗷。");
// }
//
// /**
// * 表演精彩时的表现
// */
// @AfterReturning("execution(* cn.aijiang.aop.Performance.perform(..))")
// public void applause() {
// System.out.println("喔喔喔喔!精彩极了啊!");
// }
//
// /**
// * 表演失败之后的表现
// */
// @AfterThrowing("execution(* cn.aijiang.aop.Performance.perform(..))")
// public void demandRefund() {
// System.out.println("这表演真是太下饭,建议退钱!");
// }
/**
* 定义命名的切点
*/
@Pointcut("execution(* cn.aijiang.aop.Performance.perform(..))")
public void performance() {
}
/**
* 表演开始前的表现一
*/
@Before("performance()")
public void silenceCellPhones() {
System.out.println("手机静音了嗷。");
}
/**
* 表演开始前的表现二
*/
@Before("performance()")
public void takeSeats() {
System.out.println("谈话停止了嗷。");
}
/**
* 表演精彩时的表现
*/
@AfterReturning("performance()")
public void applause() {
System.out.println("喔喔喔喔!精彩极了啊!");
}
/**
* 表演失败之后的表现
*/
@AfterThrowing("performance()")
public void demandRefund() {
System.out.println("这表演真是太下饭,建议退钱!");
}
}
| AijiangyoubuAicu/JavaInterview | Spring/src/main/java/cn/aijiang/aop/Audience.java | 684 | // * 表演失败之后的表现 | line_comment | zh-cn | package cn.aijiang.aop;
import org.aspectj.lang.annotation.*;
/**
* 定义一个切点
*
* 对于演出这个整体业务来说,观众在现实上表现得很重要(观众多,恰到钱就越多嘛)
* 但在业务代码里,我们只关心演出业务,观众应作为切面来看待
*/
@Aspect
public class Audience {
// /**
// * 表演开始前的表现一
// */
// @Before("execution(* cn.aijiang.aop.Performance.perform(..))")
// public void silenceCellPhones() {
// System.out.println("手机静音了嗷。");
// }
//
// /**
// * 表演开始前的表现二
// */
// @Before("execution(* cn.aijiang.aop.Performance.perform(..))")
// public void takeSeats() {
// System.out.println("谈话停止了嗷。");
// }
//
// /**
// * 表演精彩时的表现
// */
// @AfterReturning("execution(* cn.aijiang.aop.Performance.perform(..))")
// public void applause() {
// System.out.println("喔喔喔喔!精彩极了啊!");
// }
//
// /**
// * 表演 <SUF>
// */
// @AfterThrowing("execution(* cn.aijiang.aop.Performance.perform(..))")
// public void demandRefund() {
// System.out.println("这表演真是太下饭,建议退钱!");
// }
/**
* 定义命名的切点
*/
@Pointcut("execution(* cn.aijiang.aop.Performance.perform(..))")
public void performance() {
}
/**
* 表演开始前的表现一
*/
@Before("performance()")
public void silenceCellPhones() {
System.out.println("手机静音了嗷。");
}
/**
* 表演开始前的表现二
*/
@Before("performance()")
public void takeSeats() {
System.out.println("谈话停止了嗷。");
}
/**
* 表演精彩时的表现
*/
@AfterReturning("performance()")
public void applause() {
System.out.println("喔喔喔喔!精彩极了啊!");
}
/**
* 表演失败之后的表现
*/
@AfterThrowing("performance()")
public void demandRefund() {
System.out.println("这表演真是太下饭,建议退钱!");
}
}
| false |
14466_17 | package com.github.airsaid.accountbook.util;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.github.airsaid.accountbook.mvp.main.MainActivity;
import com.github.airsaid.accountbook.R;
import com.github.airsaid.accountbook.base.BaseApplication;
import com.github.airsaid.accountbook.mvp.login.LoginActivity;
/**
* Created by zhouyou on 2016/6/27.
* Class desc: ui 操作相关封装
*/
public class UiUtils {
/**
* 获取上下文
*/
public static Context getContext() {
return BaseApplication.getContext();
}
/**
* 获取资源操作类
*/
public static Resources getResources() {
return getContext().getResources();
}
/**
* 获取字符串资源
*
* @param id 资源id
* @return 字符串
*/
public static String getString(int id) {
return getResources().getString(id);
}
/**
* 获取字符串数组资源
*
* @param id 资源id
* @return 字符串数组
*/
public static String[] getStringArray(int id) {
return getResources().getStringArray(id);
}
/**
* 获取颜色资源
*/
public static int getColor(int id) {
return ContextCompat.getColor(getContext(), id);
}
/**
* 获取颜色资源
*
* @param id 资源id
* @param theme 样式
* @return
*/
public static int getColor(int id, Resources.Theme theme) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return getResources().getColor(id, theme);
}
return getResources().getColor(id);
}
/**
* 获取drawable资源
*
* @param id 资源id
* @return
*/
public static Drawable getDrawable(int id) {
return ContextCompat.getDrawable(getContext(), id);
}
/**
* 通过图片名称获取图片资源 id
* @param imageName 图片名称
* @return 图片资源 id
*/
public static int getImageResIdByName(String imageName){
return getResources().getIdentifier(imageName, "mipmap"
, AppUtils.getPackageName());
}
/**
* 加载布局(使用View方式)
*
* @param resource 布局资源id
* @return View
*/
public static View inflate(int resource) {
return View.inflate(getContext(), resource, null);
}
/**
* 检查输入的内容是否为空
*/
public static boolean checkEmpty(EditText editText) {
if(TextUtils.isEmpty(editText.getText().toString())){
ToastUtils.show(UiUtils.getContext(), UiUtils.getString(R.string.hint_empty));
return true;
}
return false;
}
/**
* 设置透明状态栏
* @param activity
*/
public static void setStatusBar(Activity activity) {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
// 对于4.4以上5.0以下版本,设置透明状态栏
Window window = activity.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
// 5.0及以上版本,设置透明状态栏
Window window = activity.getWindow();
// 清理4.4Flag
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
// 添加标志位
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
// 设置为透明
window.setStatusBarColor(0);
}
}
/**
* 进入首页
*/
public static void enterHomePage(Context context){
ActivityManager.getInstance().popAllActivity();
Intent intent = new Intent(context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(intent);
if(context instanceof Activity){
((Activity)context).finish();
}
}
/**
* 进入登录页
* @param context 上下文
*/
public static void enterLoginPage(Context context){
enterLoginPage(context, false);
}
/**
* 进入登录页
* @param context 上下文
* @param isFinish 是否关闭当前 Activity
*/
public static void enterLoginPage(Context context, boolean isFinish){
ActivityManager.getInstance().popAllActivity();
Intent intent = new Intent(context, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
if(!(context instanceof Activity)){
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
context.startActivity(intent);
if(isFinish && context instanceof Activity){
((Activity)context).finish();
}
}
public static ColorStateList getColorList(int resId) {
return ContextCompat.getColorStateList(UiUtils.getContext(), resId);
}
public static void setCompoundDrawables(TextView textView, Drawable left, Drawable top, Drawable right, Drawable bottom){
textView.setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom);
}
/**
* 获取列表为空时显示的 Empty View
* @return 默认 Empty View
*/
public static View getEmptyView(Context context, RecyclerView recyclerView){
return getEmptyView(context, recyclerView, null, -1);
}
/**
* 获取列表为空时显示的 Empty View
* @param emptyText 提示文字
* @return Empty View
*/
public static View getEmptyView(Context context, RecyclerView recyclerView, String emptyText){
return getEmptyView(context, recyclerView, emptyText, -1);
}
/**
* 获取列表为空时显示的 Empty View
* @param emptyText 提示文字
* @param emptyImgId 图片
* @return Empty View
*/
public static View getEmptyView(Context context, RecyclerView recyclerView, String emptyText, int emptyImgId){
View emptyView = LayoutInflater.from(context).inflate(R.layout.view_empty, (ViewGroup) recyclerView.getParent(), false);
if(emptyText != null){
((TextView)emptyView.findViewById(R.id.txt_empty)).setText(emptyText);
}
if(emptyImgId != -1){
((ImageView)emptyView.findViewById(R.id.img_empty)).setImageResource(emptyImgId);
}
return emptyView;
}
/**
* 通过场景名获取场景资源图片 id
* @param scene 场景名称
* @return 场景资源图片 id
*/
public static int getSceneImageResIdByName(String scene){
switch (scene){
case "日常":
return R.mipmap.book_scene1;
case "校园":
return R.mipmap.book_scene2;
case "生意":
return R.mipmap.book_scene3;
case "家庭":
return R.mipmap.book_scene4;
case "旅行":
return R.mipmap.book_scene5;
case "装修":
return R.mipmap.book_scene6;
case "结婚":
return R.mipmap.book_scene7;
default:
return R.mipmap.book_scene1;
}
}
/** 显示不带 null 的字符 */
public static String show(String text){
return text != null ? text : "";
}
/**
* 根据自定义属性获取对应颜色值.
* @param context 上下文
* @param attrs 自定义属性
* @param defColor 默认颜色
* @return 颜色
*/
public static int getColor(Context context, int attrs, int defColor){
int[] customAttrs = {attrs};
TypedArray a = context.obtainStyledAttributes(customAttrs);
int color = a.getColor(0, defColor);
a.recycle();
return color;
}
/**
* 根据自定义属性获取对应资源 id.
* @param context 上下文
* @param attrs 自定义属性
* @param defId 默认 id
* @return 资源 id
*/
public static int getResourceId(Context context, int attrs, int defId){
int[] customAttrs = {attrs};
TypedArray a = context.obtainStyledAttributes(customAttrs);
int id = a.getResourceId(0, defId);
a.recycle();
return id;
}
}
| Airsaid/AccountBook | app/src/main/java/com/github/airsaid/accountbook/util/UiUtils.java | 2,172 | /**
* 进入首页
*/ | block_comment | zh-cn | package com.github.airsaid.accountbook.util;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.github.airsaid.accountbook.mvp.main.MainActivity;
import com.github.airsaid.accountbook.R;
import com.github.airsaid.accountbook.base.BaseApplication;
import com.github.airsaid.accountbook.mvp.login.LoginActivity;
/**
* Created by zhouyou on 2016/6/27.
* Class desc: ui 操作相关封装
*/
public class UiUtils {
/**
* 获取上下文
*/
public static Context getContext() {
return BaseApplication.getContext();
}
/**
* 获取资源操作类
*/
public static Resources getResources() {
return getContext().getResources();
}
/**
* 获取字符串资源
*
* @param id 资源id
* @return 字符串
*/
public static String getString(int id) {
return getResources().getString(id);
}
/**
* 获取字符串数组资源
*
* @param id 资源id
* @return 字符串数组
*/
public static String[] getStringArray(int id) {
return getResources().getStringArray(id);
}
/**
* 获取颜色资源
*/
public static int getColor(int id) {
return ContextCompat.getColor(getContext(), id);
}
/**
* 获取颜色资源
*
* @param id 资源id
* @param theme 样式
* @return
*/
public static int getColor(int id, Resources.Theme theme) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return getResources().getColor(id, theme);
}
return getResources().getColor(id);
}
/**
* 获取drawable资源
*
* @param id 资源id
* @return
*/
public static Drawable getDrawable(int id) {
return ContextCompat.getDrawable(getContext(), id);
}
/**
* 通过图片名称获取图片资源 id
* @param imageName 图片名称
* @return 图片资源 id
*/
public static int getImageResIdByName(String imageName){
return getResources().getIdentifier(imageName, "mipmap"
, AppUtils.getPackageName());
}
/**
* 加载布局(使用View方式)
*
* @param resource 布局资源id
* @return View
*/
public static View inflate(int resource) {
return View.inflate(getContext(), resource, null);
}
/**
* 检查输入的内容是否为空
*/
public static boolean checkEmpty(EditText editText) {
if(TextUtils.isEmpty(editText.getText().toString())){
ToastUtils.show(UiUtils.getContext(), UiUtils.getString(R.string.hint_empty));
return true;
}
return false;
}
/**
* 设置透明状态栏
* @param activity
*/
public static void setStatusBar(Activity activity) {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
// 对于4.4以上5.0以下版本,设置透明状态栏
Window window = activity.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
// 5.0及以上版本,设置透明状态栏
Window window = activity.getWindow();
// 清理4.4Flag
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
// 添加标志位
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
// 设置为透明
window.setStatusBarColor(0);
}
}
/**
* 进入首 <SUF>*/
public static void enterHomePage(Context context){
ActivityManager.getInstance().popAllActivity();
Intent intent = new Intent(context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(intent);
if(context instanceof Activity){
((Activity)context).finish();
}
}
/**
* 进入登录页
* @param context 上下文
*/
public static void enterLoginPage(Context context){
enterLoginPage(context, false);
}
/**
* 进入登录页
* @param context 上下文
* @param isFinish 是否关闭当前 Activity
*/
public static void enterLoginPage(Context context, boolean isFinish){
ActivityManager.getInstance().popAllActivity();
Intent intent = new Intent(context, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
if(!(context instanceof Activity)){
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
context.startActivity(intent);
if(isFinish && context instanceof Activity){
((Activity)context).finish();
}
}
public static ColorStateList getColorList(int resId) {
return ContextCompat.getColorStateList(UiUtils.getContext(), resId);
}
public static void setCompoundDrawables(TextView textView, Drawable left, Drawable top, Drawable right, Drawable bottom){
textView.setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom);
}
/**
* 获取列表为空时显示的 Empty View
* @return 默认 Empty View
*/
public static View getEmptyView(Context context, RecyclerView recyclerView){
return getEmptyView(context, recyclerView, null, -1);
}
/**
* 获取列表为空时显示的 Empty View
* @param emptyText 提示文字
* @return Empty View
*/
public static View getEmptyView(Context context, RecyclerView recyclerView, String emptyText){
return getEmptyView(context, recyclerView, emptyText, -1);
}
/**
* 获取列表为空时显示的 Empty View
* @param emptyText 提示文字
* @param emptyImgId 图片
* @return Empty View
*/
public static View getEmptyView(Context context, RecyclerView recyclerView, String emptyText, int emptyImgId){
View emptyView = LayoutInflater.from(context).inflate(R.layout.view_empty, (ViewGroup) recyclerView.getParent(), false);
if(emptyText != null){
((TextView)emptyView.findViewById(R.id.txt_empty)).setText(emptyText);
}
if(emptyImgId != -1){
((ImageView)emptyView.findViewById(R.id.img_empty)).setImageResource(emptyImgId);
}
return emptyView;
}
/**
* 通过场景名获取场景资源图片 id
* @param scene 场景名称
* @return 场景资源图片 id
*/
public static int getSceneImageResIdByName(String scene){
switch (scene){
case "日常":
return R.mipmap.book_scene1;
case "校园":
return R.mipmap.book_scene2;
case "生意":
return R.mipmap.book_scene3;
case "家庭":
return R.mipmap.book_scene4;
case "旅行":
return R.mipmap.book_scene5;
case "装修":
return R.mipmap.book_scene6;
case "结婚":
return R.mipmap.book_scene7;
default:
return R.mipmap.book_scene1;
}
}
/** 显示不带 null 的字符 */
public static String show(String text){
return text != null ? text : "";
}
/**
* 根据自定义属性获取对应颜色值.
* @param context 上下文
* @param attrs 自定义属性
* @param defColor 默认颜色
* @return 颜色
*/
public static int getColor(Context context, int attrs, int defColor){
int[] customAttrs = {attrs};
TypedArray a = context.obtainStyledAttributes(customAttrs);
int color = a.getColor(0, defColor);
a.recycle();
return color;
}
/**
* 根据自定义属性获取对应资源 id.
* @param context 上下文
* @param attrs 自定义属性
* @param defId 默认 id
* @return 资源 id
*/
public static int getResourceId(Context context, int attrs, int defId){
int[] customAttrs = {attrs};
TypedArray a = context.obtainStyledAttributes(customAttrs);
int id = a.getResourceId(0, defId);
a.recycle();
return id;
}
}
| false |
40960_18 |
package com.gastudio.leafloading;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import com.gastudio.leafloading.R;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
public class LeafLoadingView extends View {
private static final String TAG = "LeafLoadingView";
// 淡白色
private static final int WHITE_COLOR = 0xfffde399;
// 橙色
private static final int ORANGE_COLOR = 0xffffa800;
// 中等振幅大小
private static final int MIDDLE_AMPLITUDE = 13;
// 不同类型之间的振幅差距
private static final int AMPLITUDE_DISPARITY = 5;
// 总进度
private static final int TOTAL_PROGRESS = 100;
// 叶子飘动一个周期所花的时间
private static final long LEAF_FLOAT_TIME = 3000;
// 叶子旋转一周需要的时间
private static final long LEAF_ROTATE_TIME = 2000;
// 用于控制绘制的进度条距离左/上/下的距离
private static final int LEFT_MARGIN = 9;
// 用于控制绘制的进度条距离右的距离
private static final int RIGHT_MARGIN = 25;
private int mLeftMargin, mRightMargin;
// 中等振幅大小
private int mMiddleAmplitude = MIDDLE_AMPLITUDE;
// 振幅差
private int mAmplitudeDisparity = AMPLITUDE_DISPARITY;
// 叶子飘动一个周期所花的时间
private long mLeafFloatTime = LEAF_FLOAT_TIME;
// 叶子旋转一周需要的时间
private long mLeafRotateTime = LEAF_ROTATE_TIME;
private Resources mResources;
private Bitmap mLeafBitmap;
private int mLeafWidth, mLeafHeight;
private Bitmap mOuterBitmap;
private Rect mOuterSrcRect, mOuterDestRect;
private int mOuterWidth, mOuterHeight;
private int mTotalWidth, mTotalHeight;
private Paint mBitmapPaint, mWhitePaint, mOrangePaint;
private RectF mWhiteRectF, mOrangeRectF, mArcRectF;
// 当前进度
private int mProgress;
// 所绘制的进度条部分的宽度
private int mProgressWidth;
// 当前所在的绘制的进度条的位置
private int mCurrentProgressPosition;
// 弧形的半径
private int mArcRadius;
// arc的右上角的x坐标,也是矩形x坐标的起始点
private int mArcRightLocation;
// 用于产生叶子信息
private LeafFactory mLeafFactory;
// 产生出的叶子信息
private List<Leaf> mLeafInfos;
// 用于控制随机增加的时间不抱团
private int mAddTime;
public LeafLoadingView(Context context, AttributeSet attrs) {
super(context, attrs);
mResources = getResources();
mLeftMargin = UiUtils.dipToPx(context, LEFT_MARGIN);
mRightMargin = UiUtils.dipToPx(context, RIGHT_MARGIN);
mLeafFloatTime = LEAF_FLOAT_TIME;
mLeafRotateTime = LEAF_ROTATE_TIME;
initBitmap();
initPaint();
mLeafFactory = new LeafFactory();
mLeafInfos = mLeafFactory.generateLeafs();
}
private void initPaint() {
mBitmapPaint = new Paint();
mBitmapPaint.setAntiAlias(true);
mBitmapPaint.setDither(true);
mBitmapPaint.setFilterBitmap(true);
mWhitePaint = new Paint();
mWhitePaint.setAntiAlias(true);
mWhitePaint.setColor(WHITE_COLOR);
mOrangePaint = new Paint();
mOrangePaint.setAntiAlias(true);
mOrangePaint.setColor(ORANGE_COLOR);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 绘制进度条和叶子
// 之所以把叶子放在进度条里绘制,主要是层级原因
drawProgressAndLeafs(canvas);
// drawLeafs(canvas);
canvas.drawBitmap(mOuterBitmap, mOuterSrcRect, mOuterDestRect, mBitmapPaint);
postInvalidate();
}
private void drawProgressAndLeafs(Canvas canvas) {
if (mProgress >= TOTAL_PROGRESS) {
mProgress = 0;
}
// mProgressWidth为进度条的宽度,根据当前进度算出进度条的位置
mCurrentProgressPosition = mProgressWidth * mProgress / TOTAL_PROGRESS;
// 即当前位置在图中所示1范围内
if (mCurrentProgressPosition < mArcRadius) {
Log.i(TAG, "mProgress = " + mProgress + "---mCurrentProgressPosition = "
+ mCurrentProgressPosition
+ "--mArcProgressWidth" + mArcRadius);
// 1.绘制白色ARC,绘制orange ARC
// 2.绘制白色矩形
// 1.绘制白色ARC
canvas.drawArc(mArcRectF, 90, 180, false, mWhitePaint);
// 2.绘制白色矩形
mWhiteRectF.left = mArcRightLocation;
canvas.drawRect(mWhiteRectF, mWhitePaint);
// 绘制叶子
drawLeafs(canvas);
// 3.绘制棕色 ARC
// 单边角度
int angle = (int) Math.toDegrees(Math.acos((mArcRadius - mCurrentProgressPosition)
/ (float) mArcRadius));
// 起始的位置
int startAngle = 180 - angle;
// 扫过的角度
int sweepAngle = 2 * angle;
Log.i(TAG, "startAngle = " + startAngle);
canvas.drawArc(mArcRectF, startAngle, sweepAngle, false, mOrangePaint);
} else {
Log.i(TAG, "mProgress = " + mProgress + "---transfer-----mCurrentProgressPosition = "
+ mCurrentProgressPosition
+ "--mArcProgressWidth" + mArcRadius);
// 1.绘制white RECT
// 2.绘制Orange ARC
// 3.绘制orange RECT
// 这个层级进行绘制能让叶子感觉是融入棕色进度条中
// 1.绘制white RECT
mWhiteRectF.left = mCurrentProgressPosition;
canvas.drawRect(mWhiteRectF, mWhitePaint);
// 绘制叶子
drawLeafs(canvas);
// 2.绘制Orange ARC
canvas.drawArc(mArcRectF, 90, 180, false, mOrangePaint);
// 3.绘制orange RECT
mOrangeRectF.left = mArcRightLocation;
mOrangeRectF.right = mCurrentProgressPosition;
canvas.drawRect(mOrangeRectF, mOrangePaint);
}
}
/**
* 绘制叶子
*
* @param canvas
*/
private void drawLeafs(Canvas canvas) {
mLeafRotateTime = mLeafRotateTime <= 0 ? LEAF_ROTATE_TIME : mLeafRotateTime;
long currentTime = System.currentTimeMillis();
for (int i = 0; i < mLeafInfos.size(); i++) {
Leaf leaf = mLeafInfos.get(i);
if (currentTime > leaf.startTime && leaf.startTime != 0) {
// 绘制叶子--根据叶子的类型和当前时间得出叶子的(x,y)
getLeafLocation(leaf, currentTime);
// 根据时间计算旋转角度
canvas.save();
// 通过Matrix控制叶子旋转
Matrix matrix = new Matrix();
float transX = mLeftMargin + leaf.x;
float transY = mLeftMargin + leaf.y;
Log.i(TAG, "left.x = " + leaf.x + "--leaf.y=" + leaf.y);
matrix.postTranslate(transX, transY);
// 通过时间关联旋转角度,则可以直接通过修改LEAF_ROTATE_TIME调节叶子旋转快慢
float rotateFraction = ((currentTime - leaf.startTime) % mLeafRotateTime)
/ (float) mLeafRotateTime;
int angle = (int) (rotateFraction * 360);
// 根据叶子旋转方向确定叶子旋转角度
int rotate = leaf.rotateDirection == 0 ? angle + leaf.rotateAngle : -angle
+ leaf.rotateAngle;
matrix.postRotate(rotate, transX
+ mLeafWidth / 2, transY + mLeafHeight / 2);
canvas.drawBitmap(mLeafBitmap, matrix, mBitmapPaint);
canvas.restore();
} else {
continue;
}
}
}
private void getLeafLocation(Leaf leaf, long currentTime) {
long intervalTime = currentTime - leaf.startTime;
mLeafFloatTime = mLeafFloatTime <= 0 ? LEAF_FLOAT_TIME : mLeafFloatTime;
if (intervalTime < 0) {
return;
} else if (intervalTime > mLeafFloatTime) {
leaf.startTime = System.currentTimeMillis()
+ new Random().nextInt((int) mLeafFloatTime);
}
float fraction = (float) intervalTime / mLeafFloatTime;
leaf.x = (int) (mProgressWidth - mProgressWidth * fraction);
leaf.y = getLocationY(leaf);
}
// 通过叶子信息获取当前叶子的Y值
private int getLocationY(Leaf leaf) {
// y = A(wx+Q)+h
float w = (float) ((float) 2 * Math.PI / mProgressWidth);
float a = mMiddleAmplitude;
switch (leaf.type) {
case LITTLE:
// 小振幅 = 中等振幅 - 振幅差
a = mMiddleAmplitude - mAmplitudeDisparity;
break;
case MIDDLE:
a = mMiddleAmplitude;
break;
case BIG:
// 小振幅 = 中等振幅 + 振幅差
a = mMiddleAmplitude + mAmplitudeDisparity;
break;
default:
break;
}
Log.i(TAG, "---a = " + a + "---w = " + w + "--leaf.x = " + leaf.x);
return (int) (a * Math.sin(w * leaf.x)) + mArcRadius * 2 / 3;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
private void initBitmap() {
mLeafBitmap = ((BitmapDrawable) mResources.getDrawable(R.drawable.leaf)).getBitmap();
mLeafWidth = mLeafBitmap.getWidth();
mLeafHeight = mLeafBitmap.getHeight();
mOuterBitmap = ((BitmapDrawable) mResources.getDrawable(R.drawable.leaf_kuang)).getBitmap();
mOuterWidth = mOuterBitmap.getWidth();
mOuterHeight = mOuterBitmap.getHeight();
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mTotalWidth = w;
mTotalHeight = h;
mProgressWidth = mTotalWidth - mLeftMargin - mRightMargin;
mArcRadius = (mTotalHeight - 2 * mLeftMargin) / 2;
mOuterSrcRect = new Rect(0, 0, mOuterWidth, mOuterHeight);
mOuterDestRect = new Rect(0, 0, mTotalWidth, mTotalHeight);
mWhiteRectF = new RectF(mLeftMargin + mCurrentProgressPosition, mLeftMargin, mTotalWidth
- mRightMargin,
mTotalHeight - mLeftMargin);
mOrangeRectF = new RectF(mLeftMargin + mArcRadius, mLeftMargin,
mCurrentProgressPosition
, mTotalHeight - mLeftMargin);
mArcRectF = new RectF(mLeftMargin, mLeftMargin, mLeftMargin + 2 * mArcRadius,
mTotalHeight - mLeftMargin);
mArcRightLocation = mLeftMargin + mArcRadius;
}
private enum StartType {
LITTLE, MIDDLE, BIG
}
/**
* 叶子对象,用来记录叶子主要数据
*
* @author Ajian_Studio
*/
private class Leaf {
// 在绘制部分的位置
float x, y;
// 控制叶子飘动的幅度
StartType type;
// 旋转角度
int rotateAngle;
// 旋转方向--0代表顺时针,1代表逆时针
int rotateDirection;
// 起始时间(ms)
long startTime;
}
private class LeafFactory {
private static final int MAX_LEAFS = 8;
Random random = new Random();
// 生成一个叶子信息
public Leaf generateLeaf() {
Leaf leaf = new Leaf();
int randomType = random.nextInt(3);
// 随时类型- 随机振幅
StartType type = StartType.MIDDLE;
switch (randomType) {
case 0:
break;
case 1:
type = StartType.LITTLE;
break;
case 2:
type = StartType.BIG;
break;
default:
break;
}
leaf.type = type;
// 随机起始的旋转角度
leaf.rotateAngle = random.nextInt(360);
// 随机旋转方向(顺时针或逆时针)
leaf.rotateDirection = random.nextInt(2);
// 为了产生交错的感觉,让开始的时间有一定的随机性
mLeafFloatTime = mLeafFloatTime <= 0 ? LEAF_FLOAT_TIME : mLeafFloatTime;
mAddTime += random.nextInt((int) (mLeafFloatTime * 2));
leaf.startTime = System.currentTimeMillis() + mAddTime;
return leaf;
}
// 根据最大叶子数产生叶子信息
public List<Leaf> generateLeafs() {
return generateLeafs(MAX_LEAFS);
}
// 根据传入的叶子数量产生叶子信息
public List<Leaf> generateLeafs(int leafSize) {
List<Leaf> leafs = new LinkedList<Leaf>();
for (int i = 0; i < leafSize; i++) {
leafs.add(generateLeaf());
}
return leafs;
}
}
/**
* 设置中等振幅
*
* @param amplitude
*/
public void setMiddleAmplitude(int amplitude) {
this.mMiddleAmplitude = amplitude;
}
/**
* 设置振幅差
*
* @param disparity
*/
public void setMplitudeDisparity(int disparity) {
this.mAmplitudeDisparity = disparity;
}
/**
* 获取中等振幅
*
* @param amplitude
*/
public int getMiddleAmplitude() {
return mMiddleAmplitude;
}
/**
* 获取振幅差
*
* @param disparity
*/
public int getMplitudeDisparity() {
return mAmplitudeDisparity;
}
/**
* 设置进度
*
* @param progress
*/
public void setProgress(int progress) {
this.mProgress = progress;
postInvalidate();
}
/**
* 设置叶子飘完一个周期所花的时间
*
* @param time
*/
public void setLeafFloatTime(long time) {
this.mLeafFloatTime = time;
}
/**
* 设置叶子旋转一周所花的时间
*
* @param time
*/
public void setLeafRotateTime(long time) {
this.mLeafRotateTime = time;
}
/**
* 获取叶子飘完一个周期所花的时间
*/
public long getLeafFloatTime() {
mLeafFloatTime = mLeafFloatTime == 0 ? LEAF_FLOAT_TIME : mLeafFloatTime;
return mLeafFloatTime;
}
/**
* 获取叶子旋转一周所花的时间
*/
public long getLeafRotateTime() {
mLeafRotateTime = mLeafRotateTime == 0 ? LEAF_ROTATE_TIME : mLeafRotateTime;
return mLeafRotateTime;
}
}
| Ajian-studio/GALeafLoading | app/src/main/java/com/gastudio/leafloading/LeafLoadingView.java | 3,996 | // 产生出的叶子信息 | line_comment | zh-cn |
package com.gastudio.leafloading;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import com.gastudio.leafloading.R;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
public class LeafLoadingView extends View {
private static final String TAG = "LeafLoadingView";
// 淡白色
private static final int WHITE_COLOR = 0xfffde399;
// 橙色
private static final int ORANGE_COLOR = 0xffffa800;
// 中等振幅大小
private static final int MIDDLE_AMPLITUDE = 13;
// 不同类型之间的振幅差距
private static final int AMPLITUDE_DISPARITY = 5;
// 总进度
private static final int TOTAL_PROGRESS = 100;
// 叶子飘动一个周期所花的时间
private static final long LEAF_FLOAT_TIME = 3000;
// 叶子旋转一周需要的时间
private static final long LEAF_ROTATE_TIME = 2000;
// 用于控制绘制的进度条距离左/上/下的距离
private static final int LEFT_MARGIN = 9;
// 用于控制绘制的进度条距离右的距离
private static final int RIGHT_MARGIN = 25;
private int mLeftMargin, mRightMargin;
// 中等振幅大小
private int mMiddleAmplitude = MIDDLE_AMPLITUDE;
// 振幅差
private int mAmplitudeDisparity = AMPLITUDE_DISPARITY;
// 叶子飘动一个周期所花的时间
private long mLeafFloatTime = LEAF_FLOAT_TIME;
// 叶子旋转一周需要的时间
private long mLeafRotateTime = LEAF_ROTATE_TIME;
private Resources mResources;
private Bitmap mLeafBitmap;
private int mLeafWidth, mLeafHeight;
private Bitmap mOuterBitmap;
private Rect mOuterSrcRect, mOuterDestRect;
private int mOuterWidth, mOuterHeight;
private int mTotalWidth, mTotalHeight;
private Paint mBitmapPaint, mWhitePaint, mOrangePaint;
private RectF mWhiteRectF, mOrangeRectF, mArcRectF;
// 当前进度
private int mProgress;
// 所绘制的进度条部分的宽度
private int mProgressWidth;
// 当前所在的绘制的进度条的位置
private int mCurrentProgressPosition;
// 弧形的半径
private int mArcRadius;
// arc的右上角的x坐标,也是矩形x坐标的起始点
private int mArcRightLocation;
// 用于产生叶子信息
private LeafFactory mLeafFactory;
// 产生 <SUF>
private List<Leaf> mLeafInfos;
// 用于控制随机增加的时间不抱团
private int mAddTime;
public LeafLoadingView(Context context, AttributeSet attrs) {
super(context, attrs);
mResources = getResources();
mLeftMargin = UiUtils.dipToPx(context, LEFT_MARGIN);
mRightMargin = UiUtils.dipToPx(context, RIGHT_MARGIN);
mLeafFloatTime = LEAF_FLOAT_TIME;
mLeafRotateTime = LEAF_ROTATE_TIME;
initBitmap();
initPaint();
mLeafFactory = new LeafFactory();
mLeafInfos = mLeafFactory.generateLeafs();
}
private void initPaint() {
mBitmapPaint = new Paint();
mBitmapPaint.setAntiAlias(true);
mBitmapPaint.setDither(true);
mBitmapPaint.setFilterBitmap(true);
mWhitePaint = new Paint();
mWhitePaint.setAntiAlias(true);
mWhitePaint.setColor(WHITE_COLOR);
mOrangePaint = new Paint();
mOrangePaint.setAntiAlias(true);
mOrangePaint.setColor(ORANGE_COLOR);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 绘制进度条和叶子
// 之所以把叶子放在进度条里绘制,主要是层级原因
drawProgressAndLeafs(canvas);
// drawLeafs(canvas);
canvas.drawBitmap(mOuterBitmap, mOuterSrcRect, mOuterDestRect, mBitmapPaint);
postInvalidate();
}
private void drawProgressAndLeafs(Canvas canvas) {
if (mProgress >= TOTAL_PROGRESS) {
mProgress = 0;
}
// mProgressWidth为进度条的宽度,根据当前进度算出进度条的位置
mCurrentProgressPosition = mProgressWidth * mProgress / TOTAL_PROGRESS;
// 即当前位置在图中所示1范围内
if (mCurrentProgressPosition < mArcRadius) {
Log.i(TAG, "mProgress = " + mProgress + "---mCurrentProgressPosition = "
+ mCurrentProgressPosition
+ "--mArcProgressWidth" + mArcRadius);
// 1.绘制白色ARC,绘制orange ARC
// 2.绘制白色矩形
// 1.绘制白色ARC
canvas.drawArc(mArcRectF, 90, 180, false, mWhitePaint);
// 2.绘制白色矩形
mWhiteRectF.left = mArcRightLocation;
canvas.drawRect(mWhiteRectF, mWhitePaint);
// 绘制叶子
drawLeafs(canvas);
// 3.绘制棕色 ARC
// 单边角度
int angle = (int) Math.toDegrees(Math.acos((mArcRadius - mCurrentProgressPosition)
/ (float) mArcRadius));
// 起始的位置
int startAngle = 180 - angle;
// 扫过的角度
int sweepAngle = 2 * angle;
Log.i(TAG, "startAngle = " + startAngle);
canvas.drawArc(mArcRectF, startAngle, sweepAngle, false, mOrangePaint);
} else {
Log.i(TAG, "mProgress = " + mProgress + "---transfer-----mCurrentProgressPosition = "
+ mCurrentProgressPosition
+ "--mArcProgressWidth" + mArcRadius);
// 1.绘制white RECT
// 2.绘制Orange ARC
// 3.绘制orange RECT
// 这个层级进行绘制能让叶子感觉是融入棕色进度条中
// 1.绘制white RECT
mWhiteRectF.left = mCurrentProgressPosition;
canvas.drawRect(mWhiteRectF, mWhitePaint);
// 绘制叶子
drawLeafs(canvas);
// 2.绘制Orange ARC
canvas.drawArc(mArcRectF, 90, 180, false, mOrangePaint);
// 3.绘制orange RECT
mOrangeRectF.left = mArcRightLocation;
mOrangeRectF.right = mCurrentProgressPosition;
canvas.drawRect(mOrangeRectF, mOrangePaint);
}
}
/**
* 绘制叶子
*
* @param canvas
*/
private void drawLeafs(Canvas canvas) {
mLeafRotateTime = mLeafRotateTime <= 0 ? LEAF_ROTATE_TIME : mLeafRotateTime;
long currentTime = System.currentTimeMillis();
for (int i = 0; i < mLeafInfos.size(); i++) {
Leaf leaf = mLeafInfos.get(i);
if (currentTime > leaf.startTime && leaf.startTime != 0) {
// 绘制叶子--根据叶子的类型和当前时间得出叶子的(x,y)
getLeafLocation(leaf, currentTime);
// 根据时间计算旋转角度
canvas.save();
// 通过Matrix控制叶子旋转
Matrix matrix = new Matrix();
float transX = mLeftMargin + leaf.x;
float transY = mLeftMargin + leaf.y;
Log.i(TAG, "left.x = " + leaf.x + "--leaf.y=" + leaf.y);
matrix.postTranslate(transX, transY);
// 通过时间关联旋转角度,则可以直接通过修改LEAF_ROTATE_TIME调节叶子旋转快慢
float rotateFraction = ((currentTime - leaf.startTime) % mLeafRotateTime)
/ (float) mLeafRotateTime;
int angle = (int) (rotateFraction * 360);
// 根据叶子旋转方向确定叶子旋转角度
int rotate = leaf.rotateDirection == 0 ? angle + leaf.rotateAngle : -angle
+ leaf.rotateAngle;
matrix.postRotate(rotate, transX
+ mLeafWidth / 2, transY + mLeafHeight / 2);
canvas.drawBitmap(mLeafBitmap, matrix, mBitmapPaint);
canvas.restore();
} else {
continue;
}
}
}
private void getLeafLocation(Leaf leaf, long currentTime) {
long intervalTime = currentTime - leaf.startTime;
mLeafFloatTime = mLeafFloatTime <= 0 ? LEAF_FLOAT_TIME : mLeafFloatTime;
if (intervalTime < 0) {
return;
} else if (intervalTime > mLeafFloatTime) {
leaf.startTime = System.currentTimeMillis()
+ new Random().nextInt((int) mLeafFloatTime);
}
float fraction = (float) intervalTime / mLeafFloatTime;
leaf.x = (int) (mProgressWidth - mProgressWidth * fraction);
leaf.y = getLocationY(leaf);
}
// 通过叶子信息获取当前叶子的Y值
private int getLocationY(Leaf leaf) {
// y = A(wx+Q)+h
float w = (float) ((float) 2 * Math.PI / mProgressWidth);
float a = mMiddleAmplitude;
switch (leaf.type) {
case LITTLE:
// 小振幅 = 中等振幅 - 振幅差
a = mMiddleAmplitude - mAmplitudeDisparity;
break;
case MIDDLE:
a = mMiddleAmplitude;
break;
case BIG:
// 小振幅 = 中等振幅 + 振幅差
a = mMiddleAmplitude + mAmplitudeDisparity;
break;
default:
break;
}
Log.i(TAG, "---a = " + a + "---w = " + w + "--leaf.x = " + leaf.x);
return (int) (a * Math.sin(w * leaf.x)) + mArcRadius * 2 / 3;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
private void initBitmap() {
mLeafBitmap = ((BitmapDrawable) mResources.getDrawable(R.drawable.leaf)).getBitmap();
mLeafWidth = mLeafBitmap.getWidth();
mLeafHeight = mLeafBitmap.getHeight();
mOuterBitmap = ((BitmapDrawable) mResources.getDrawable(R.drawable.leaf_kuang)).getBitmap();
mOuterWidth = mOuterBitmap.getWidth();
mOuterHeight = mOuterBitmap.getHeight();
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mTotalWidth = w;
mTotalHeight = h;
mProgressWidth = mTotalWidth - mLeftMargin - mRightMargin;
mArcRadius = (mTotalHeight - 2 * mLeftMargin) / 2;
mOuterSrcRect = new Rect(0, 0, mOuterWidth, mOuterHeight);
mOuterDestRect = new Rect(0, 0, mTotalWidth, mTotalHeight);
mWhiteRectF = new RectF(mLeftMargin + mCurrentProgressPosition, mLeftMargin, mTotalWidth
- mRightMargin,
mTotalHeight - mLeftMargin);
mOrangeRectF = new RectF(mLeftMargin + mArcRadius, mLeftMargin,
mCurrentProgressPosition
, mTotalHeight - mLeftMargin);
mArcRectF = new RectF(mLeftMargin, mLeftMargin, mLeftMargin + 2 * mArcRadius,
mTotalHeight - mLeftMargin);
mArcRightLocation = mLeftMargin + mArcRadius;
}
private enum StartType {
LITTLE, MIDDLE, BIG
}
/**
* 叶子对象,用来记录叶子主要数据
*
* @author Ajian_Studio
*/
private class Leaf {
// 在绘制部分的位置
float x, y;
// 控制叶子飘动的幅度
StartType type;
// 旋转角度
int rotateAngle;
// 旋转方向--0代表顺时针,1代表逆时针
int rotateDirection;
// 起始时间(ms)
long startTime;
}
private class LeafFactory {
private static final int MAX_LEAFS = 8;
Random random = new Random();
// 生成一个叶子信息
public Leaf generateLeaf() {
Leaf leaf = new Leaf();
int randomType = random.nextInt(3);
// 随时类型- 随机振幅
StartType type = StartType.MIDDLE;
switch (randomType) {
case 0:
break;
case 1:
type = StartType.LITTLE;
break;
case 2:
type = StartType.BIG;
break;
default:
break;
}
leaf.type = type;
// 随机起始的旋转角度
leaf.rotateAngle = random.nextInt(360);
// 随机旋转方向(顺时针或逆时针)
leaf.rotateDirection = random.nextInt(2);
// 为了产生交错的感觉,让开始的时间有一定的随机性
mLeafFloatTime = mLeafFloatTime <= 0 ? LEAF_FLOAT_TIME : mLeafFloatTime;
mAddTime += random.nextInt((int) (mLeafFloatTime * 2));
leaf.startTime = System.currentTimeMillis() + mAddTime;
return leaf;
}
// 根据最大叶子数产生叶子信息
public List<Leaf> generateLeafs() {
return generateLeafs(MAX_LEAFS);
}
// 根据传入的叶子数量产生叶子信息
public List<Leaf> generateLeafs(int leafSize) {
List<Leaf> leafs = new LinkedList<Leaf>();
for (int i = 0; i < leafSize; i++) {
leafs.add(generateLeaf());
}
return leafs;
}
}
/**
* 设置中等振幅
*
* @param amplitude
*/
public void setMiddleAmplitude(int amplitude) {
this.mMiddleAmplitude = amplitude;
}
/**
* 设置振幅差
*
* @param disparity
*/
public void setMplitudeDisparity(int disparity) {
this.mAmplitudeDisparity = disparity;
}
/**
* 获取中等振幅
*
* @param amplitude
*/
public int getMiddleAmplitude() {
return mMiddleAmplitude;
}
/**
* 获取振幅差
*
* @param disparity
*/
public int getMplitudeDisparity() {
return mAmplitudeDisparity;
}
/**
* 设置进度
*
* @param progress
*/
public void setProgress(int progress) {
this.mProgress = progress;
postInvalidate();
}
/**
* 设置叶子飘完一个周期所花的时间
*
* @param time
*/
public void setLeafFloatTime(long time) {
this.mLeafFloatTime = time;
}
/**
* 设置叶子旋转一周所花的时间
*
* @param time
*/
public void setLeafRotateTime(long time) {
this.mLeafRotateTime = time;
}
/**
* 获取叶子飘完一个周期所花的时间
*/
public long getLeafFloatTime() {
mLeafFloatTime = mLeafFloatTime == 0 ? LEAF_FLOAT_TIME : mLeafFloatTime;
return mLeafFloatTime;
}
/**
* 获取叶子旋转一周所花的时间
*/
public long getLeafRotateTime() {
mLeafRotateTime = mLeafRotateTime == 0 ? LEAF_ROTATE_TIME : mLeafRotateTime;
return mLeafRotateTime;
}
}
| false |
36827_6 | package com.huawei;
import java.util.Collection;
import java.util.HashMap;
public class Road implements Comparable<Road> {
private int roadId;
private int length;
private int oriLength;
private int speed;
private int channel;
private Cross from;
private int fromId;
private Cross to;
private int toId;
private int isDuplex;
private Car[][] fromTo;
private Car[][] toFrom;
public int fromToLoad=0;//道路负载
public int toFromLoad=0;
public int planFromToLoad=0;//道路负载
public int planToFromLoad=0;
public int fromToLength=0;
public int toFromLength=0;
Road(int roadId , int length , int speed , int channel , int fromId , int toId , int isDuplex){
this.setRoadId(roadId);
this.setLength(length);
this.setSpeed(speed);
this.setChannel(channel);
this.setFromId(fromId);
this.setToId(toId);
this.setIsDuplex(isDuplex);
this.setFromTo();
this.setToFrom();
}
public void setLoadFator(double factor,boolean dir){
if(dir)
this.fromToLength*=factor;
else
this.toFromLength*=factor;
}
public int getFromToLoad(){
return fromToLoad;
}
public int getToFromLoad(){
return toFromLoad;
}
public int getLoadByNextCross(Cross nextCross){
if(nextCross==to)
return fromToLoad;
else
return toFromLoad;
}
public void addLoad(Car[][] roadInfo){
if(roadInfo==fromTo)
fromToLoad++;
else
toFromLoad++;
}
public void minLoad(Car[][] roadInfo){
if(roadInfo==fromTo)
fromToLoad--;
else
toFromLoad--;
}
public void addPlanLoad(Cross lastCross){
if(lastCross==from)
planFromToLoad++;
else
planToFromLoad++;
}
public void minPlanLoad(Cross lastCross){
if(lastCross==from)
planFromToLoad--;
else
planToFromLoad--;
}
public Car[][] getIntoFromCross(Cross currentCross){
if(currentCross==to)
return fromTo;
else {
// if(this.isDuplex==0)
// System.out.println("出发车辆道路错误,不存在该方向道路。");
return toFrom;
}
}
public Car[][] getOutFromCross(Cross currentCross){
if(currentCross==from)
return fromTo;
else {
// if(this.isDuplex==0)
// System.out.println("出发车辆道路错误,不存在该方向道路。");
return toFrom;
}
}
public Cross getNextCross(Cross currentCross){
if(currentCross==this.from)
return to;
else
return from;
}
public Cross getCrossByNextRoad(Road nextRoad){
if(this.to==nextRoad.from||this.to==nextRoad.to)
return to;
else
return from;
}
public void updateFromAndTo(HashMap<Integer,Cross> crosses){
setFrom(crosses.get(this.fromId));
setTo((crosses.get(this.toId)));
}
public int getRoadId() {
return roadId;
}
public void setRoadId(int roadId) {
this.roadId = roadId;
}
public int getLength() {
return length;
}
public int getLoadLength(Cross currentCross){
if(currentCross==from)
return fromToLength;
else
return toFromLength;
}
public void setLength(int length) {
this.length = length;
this.oriLength=length;
this.fromToLength=length;
this.toFromLength=length;
}
public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public int getChannel() {
return channel;
}
public void setChannel(int channel) {
this.channel = channel;
}
public int getFromId() {
return fromId;
}
public void setFromId(int fromId) {
this.fromId = fromId;
}
public int getToId() {
return toId;
}
public void setToId(int toId) {
this.toId = toId;
}
public int getIsDuplex() {
return isDuplex;
}
public void setIsDuplex(int isDuplex) {
this.isDuplex = isDuplex;
}
public void setFrom(Cross from) {
this.from = from;
}
public Cross getFrom(){
return this.from;
}
public void setTo(Cross to) {
this.to = to;
}
public Cross getTo(){
return this.to;
}
public Car[][] getFromTo() {
return fromTo;
}
public void setFromTo() {
this.fromTo = new Car[this.channel][this.length];
}
public Car[][] getToFrom() {
return toFrom;
}
public void setToFrom() {
if(this.isDuplex==1)
this.toFrom=new Car[this.channel][this.length];
else
this.toFrom=null;
}
//输出道路负载,n:道路负载最高为n米内一辆车
public void printLoad(double n){
System.out.println("道路:"+roadId+" 负载要求:"+length*channel/n + "当前道路(正)负载:"+fromToLoad + "当前道路(反)负载:"+toFromLoad);
}
//通过当前路口获取道路负载
public int getLoadByCurrentCross(Cross currentCross){
if(currentCross==from)
return fromToLoad;
else
return toFromLoad;
}
/*打印车道上车辆信息*/
public void printRoad(Cross currentCross){
if(currentCross==from && isDuplex==1){//第一种情况
System.out.println(" fromTo: 道路:"+roadId);
for(int j=0;j<channel;j++){/*打印fromTo*/
for(int i=length-1;i>=0;i--){
if(fromTo[j][i]==null){
System.out.print("00000<--");
}
else{
if(fromTo[j][i].getPriority())
System.out.print("*");
else
System.out.print("~");
System.out.print(fromTo[j][i].getCarId()+"<--");
}
}
System.out.println(" ("+j+") 路口:"+currentCross.getCrossId());
}
System.out.println(" toFrom:");
for(int j=0;j<channel;j++){/*打印toFrom*/
for(int i=0;i<length;i++){
if(toFrom[j][i]==null){
System.out.print("00000-->");
}
else{
if(toFrom[j][i].getPriority())
System.out.print("*");
else
System.out.print("~");
System.out.print(toFrom[j][i].getCarId()+"-->");
}
}
System.out.println(" ("+j+") 路口:"+currentCross.getCrossId());
}
}
else if(currentCross==from && isDuplex==0){/*打印toFrom*/
System.out.println(" fromTo: 道路:"+roadId);
for(int j=0;j<channel;j++){/*打印fromTo*/
for(int i=length-1;i>=0;i--){
if(fromTo[j][i]==null){
System.out.print("000000<--");
}
else{
if(fromTo[j][i].getPriority())
System.out.print("*");
else
System.out.print("~");
System.out.print(fromTo[j][i].getCarId()+"<--");
}
}
System.out.println(" ("+j+") 路口:"+currentCross.getCrossId());
}
}
if(currentCross==to && isDuplex==1){//第二种情况
System.out.println(" toFrom: 道路:"+roadId);
for(int j=0;j<channel;j++){/*打印toFrom*/
for(int i=length-1;i>=0;i--){
if(toFrom[j][i]==null){
System.out.print("000000<--");
}
else{
if(toFrom[j][i].getPriority())
System.out.print("*");
else
System.out.print("~");
System.out.print(toFrom[j][i].getCarId()+"<--");
}
}
System.out.println(" ("+j+") 路口:"+currentCross.getCrossId());
}
System.out.println(" fromTo:");
for(int j=0;j<channel;j++){/*打印fromTo*/
for(int i=0;i<length;i++){
if(fromTo[j][i]==null){
System.out.print("000000-->");
}
else{
if(fromTo[j][i].getPriority())
System.out.print("*");
else
System.out.print("~");
System.out.print(fromTo[j][i].getCarId()+"-->");
}
}
System.out.println(" ("+j+") 路口:"+currentCross.getCrossId());
}
}
else if(currentCross==to && isDuplex==0){/*打印toFrom*/
System.out.println(" fromTo: 道路:"+roadId);
for(int j=0;j<channel;j++){/*打印fromTo*/
for(int i=0;i<length;i++){
if(fromTo[j][i]==null){
System.out.print("000000-->");
}
else{
if(fromTo[j][i].getPriority())
System.out.print("*");
else
System.out.print("~");
System.out.print(fromTo[j][i].getCarId()+"-->");
}
}
System.out.println(" ("+j+") 路口:"+currentCross.getCrossId());
}
}
}
@Override
public int compareTo(Road o) {
if(this.roadId<o.getRoadId())
return -1;
else if(this.roadId>o.getRoadId())
return 1;
else
return 0;
}
}
| Aka-me/Huawei-CodeCraft2019 | Road.java | 2,910 | //输出道路负载,n:道路负载最高为n米内一辆车
| line_comment | zh-cn | package com.huawei;
import java.util.Collection;
import java.util.HashMap;
public class Road implements Comparable<Road> {
private int roadId;
private int length;
private int oriLength;
private int speed;
private int channel;
private Cross from;
private int fromId;
private Cross to;
private int toId;
private int isDuplex;
private Car[][] fromTo;
private Car[][] toFrom;
public int fromToLoad=0;//道路负载
public int toFromLoad=0;
public int planFromToLoad=0;//道路负载
public int planToFromLoad=0;
public int fromToLength=0;
public int toFromLength=0;
Road(int roadId , int length , int speed , int channel , int fromId , int toId , int isDuplex){
this.setRoadId(roadId);
this.setLength(length);
this.setSpeed(speed);
this.setChannel(channel);
this.setFromId(fromId);
this.setToId(toId);
this.setIsDuplex(isDuplex);
this.setFromTo();
this.setToFrom();
}
public void setLoadFator(double factor,boolean dir){
if(dir)
this.fromToLength*=factor;
else
this.toFromLength*=factor;
}
public int getFromToLoad(){
return fromToLoad;
}
public int getToFromLoad(){
return toFromLoad;
}
public int getLoadByNextCross(Cross nextCross){
if(nextCross==to)
return fromToLoad;
else
return toFromLoad;
}
public void addLoad(Car[][] roadInfo){
if(roadInfo==fromTo)
fromToLoad++;
else
toFromLoad++;
}
public void minLoad(Car[][] roadInfo){
if(roadInfo==fromTo)
fromToLoad--;
else
toFromLoad--;
}
public void addPlanLoad(Cross lastCross){
if(lastCross==from)
planFromToLoad++;
else
planToFromLoad++;
}
public void minPlanLoad(Cross lastCross){
if(lastCross==from)
planFromToLoad--;
else
planToFromLoad--;
}
public Car[][] getIntoFromCross(Cross currentCross){
if(currentCross==to)
return fromTo;
else {
// if(this.isDuplex==0)
// System.out.println("出发车辆道路错误,不存在该方向道路。");
return toFrom;
}
}
public Car[][] getOutFromCross(Cross currentCross){
if(currentCross==from)
return fromTo;
else {
// if(this.isDuplex==0)
// System.out.println("出发车辆道路错误,不存在该方向道路。");
return toFrom;
}
}
public Cross getNextCross(Cross currentCross){
if(currentCross==this.from)
return to;
else
return from;
}
public Cross getCrossByNextRoad(Road nextRoad){
if(this.to==nextRoad.from||this.to==nextRoad.to)
return to;
else
return from;
}
public void updateFromAndTo(HashMap<Integer,Cross> crosses){
setFrom(crosses.get(this.fromId));
setTo((crosses.get(this.toId)));
}
public int getRoadId() {
return roadId;
}
public void setRoadId(int roadId) {
this.roadId = roadId;
}
public int getLength() {
return length;
}
public int getLoadLength(Cross currentCross){
if(currentCross==from)
return fromToLength;
else
return toFromLength;
}
public void setLength(int length) {
this.length = length;
this.oriLength=length;
this.fromToLength=length;
this.toFromLength=length;
}
public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public int getChannel() {
return channel;
}
public void setChannel(int channel) {
this.channel = channel;
}
public int getFromId() {
return fromId;
}
public void setFromId(int fromId) {
this.fromId = fromId;
}
public int getToId() {
return toId;
}
public void setToId(int toId) {
this.toId = toId;
}
public int getIsDuplex() {
return isDuplex;
}
public void setIsDuplex(int isDuplex) {
this.isDuplex = isDuplex;
}
public void setFrom(Cross from) {
this.from = from;
}
public Cross getFrom(){
return this.from;
}
public void setTo(Cross to) {
this.to = to;
}
public Cross getTo(){
return this.to;
}
public Car[][] getFromTo() {
return fromTo;
}
public void setFromTo() {
this.fromTo = new Car[this.channel][this.length];
}
public Car[][] getToFrom() {
return toFrom;
}
public void setToFrom() {
if(this.isDuplex==1)
this.toFrom=new Car[this.channel][this.length];
else
this.toFrom=null;
}
//输出 <SUF>
public void printLoad(double n){
System.out.println("道路:"+roadId+" 负载要求:"+length*channel/n + "当前道路(正)负载:"+fromToLoad + "当前道路(反)负载:"+toFromLoad);
}
//通过当前路口获取道路负载
public int getLoadByCurrentCross(Cross currentCross){
if(currentCross==from)
return fromToLoad;
else
return toFromLoad;
}
/*打印车道上车辆信息*/
public void printRoad(Cross currentCross){
if(currentCross==from && isDuplex==1){//第一种情况
System.out.println(" fromTo: 道路:"+roadId);
for(int j=0;j<channel;j++){/*打印fromTo*/
for(int i=length-1;i>=0;i--){
if(fromTo[j][i]==null){
System.out.print("00000<--");
}
else{
if(fromTo[j][i].getPriority())
System.out.print("*");
else
System.out.print("~");
System.out.print(fromTo[j][i].getCarId()+"<--");
}
}
System.out.println(" ("+j+") 路口:"+currentCross.getCrossId());
}
System.out.println(" toFrom:");
for(int j=0;j<channel;j++){/*打印toFrom*/
for(int i=0;i<length;i++){
if(toFrom[j][i]==null){
System.out.print("00000-->");
}
else{
if(toFrom[j][i].getPriority())
System.out.print("*");
else
System.out.print("~");
System.out.print(toFrom[j][i].getCarId()+"-->");
}
}
System.out.println(" ("+j+") 路口:"+currentCross.getCrossId());
}
}
else if(currentCross==from && isDuplex==0){/*打印toFrom*/
System.out.println(" fromTo: 道路:"+roadId);
for(int j=0;j<channel;j++){/*打印fromTo*/
for(int i=length-1;i>=0;i--){
if(fromTo[j][i]==null){
System.out.print("000000<--");
}
else{
if(fromTo[j][i].getPriority())
System.out.print("*");
else
System.out.print("~");
System.out.print(fromTo[j][i].getCarId()+"<--");
}
}
System.out.println(" ("+j+") 路口:"+currentCross.getCrossId());
}
}
if(currentCross==to && isDuplex==1){//第二种情况
System.out.println(" toFrom: 道路:"+roadId);
for(int j=0;j<channel;j++){/*打印toFrom*/
for(int i=length-1;i>=0;i--){
if(toFrom[j][i]==null){
System.out.print("000000<--");
}
else{
if(toFrom[j][i].getPriority())
System.out.print("*");
else
System.out.print("~");
System.out.print(toFrom[j][i].getCarId()+"<--");
}
}
System.out.println(" ("+j+") 路口:"+currentCross.getCrossId());
}
System.out.println(" fromTo:");
for(int j=0;j<channel;j++){/*打印fromTo*/
for(int i=0;i<length;i++){
if(fromTo[j][i]==null){
System.out.print("000000-->");
}
else{
if(fromTo[j][i].getPriority())
System.out.print("*");
else
System.out.print("~");
System.out.print(fromTo[j][i].getCarId()+"-->");
}
}
System.out.println(" ("+j+") 路口:"+currentCross.getCrossId());
}
}
else if(currentCross==to && isDuplex==0){/*打印toFrom*/
System.out.println(" fromTo: 道路:"+roadId);
for(int j=0;j<channel;j++){/*打印fromTo*/
for(int i=0;i<length;i++){
if(fromTo[j][i]==null){
System.out.print("000000-->");
}
else{
if(fromTo[j][i].getPriority())
System.out.print("*");
else
System.out.print("~");
System.out.print(fromTo[j][i].getCarId()+"-->");
}
}
System.out.println(" ("+j+") 路口:"+currentCross.getCrossId());
}
}
}
@Override
public int compareTo(Road o) {
if(this.roadId<o.getRoadId())
return -1;
else if(this.roadId>o.getRoadId())
return 1;
else
return 0;
}
}
| false |
56685_25 | package pers.ruchuby.learning.basic;
import java.util.Random;
import java.util.Scanner;
public class BasicGrammar {
public static void variable() {
//变量类型
// 整数类型
double a = 6.66; //默认用double 8个字节
float aa = 6.6f; //float要加f或F 4个字节
int b = 6;
byte e = 127; // -128~127
// String为引用数据类型
String c;
c = "来日等不过方长";
char d = 65; //字符 A
//空字符 中间用空格
System.out.println(' ');
//布尔类型
boolean flag = true;
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
}
public static void typeConversion() {
// 自动类型转换
byte a = 10;
int b = a; //自动从小范围转换为大范围 内存中在左侧补充0
float c = b; // int to float(double也可以)
System.out.println(c);
double d = a + b + 2.3; //表达式 自动提升
// byte char 等类型在运算时都会转化为int
// 基本与C#一致
}
public static void operator() {
// + - * / %取余
//注意int相除的时候还是int
System.out.println(3 / 2);
System.out.println(3 * 1.0 / 2); //这样才能得到double
// 能计算就按原类型计算,否则按字符串合并
System.out.println(10 + 'a'); // 107
System.out.println('a' + "你好" + 10); // a你好10
// ++ -- 前后自增 自减
// += -= *= /= %=
//如a+=b 等同于 a = (a的类型) a+b 包含了强制类型转换
// 关系运算符 == != >= <=等等
//位运算符 位运算符判断时左右都会运算
System.out.println(true | false); // 或
System.out.println(false & true);// 与
System.out.println(!true); //非
System.out.println(true ^ true); //异或 两者不等则为true
// 逻辑运算符 ! && ||
//三元运算符
System.out.println(1 > 2 ? "1>2为真" : "1>2为假");
/*
运算符优先级 与c++有细微的差别
1. ()之类括号最高
2. ! ++ --
2. 加减乘除之类的
3. 左右移运算
4. 逻辑判断
4. 逻辑位运算
5. 逻辑运算(&& ||)
6. += -=之类
*/
}
public static void userInput() {
Scanner sc = new Scanner(System.in);
System.out.println("请输入数字");
int a = sc.nextInt();
System.out.println(a);
System.out.println("请输入字符串");
String s = sc.next();
System.out.println(s);
}
public static void processControl() {
int a = 10;
int b = 20;
// if else
if (a > b) {
System.out.println(a);
} else {
System.out.println(b);
}
// switch
switch (a) {
case 10:
System.out.println("a=10");
break;
default:
System.out.println("默认");
}
//for
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
//while
int i = 0;
while (true) {
System.out.println(i);
i++;
if (i > 3) break;
}
// do while 基本差不多
//死循环写法
// while (true)
// for (; ; )
// do{}while (true)
//随机数
Random r = new Random();
System.out.println(r.nextInt(100)); // 0-99
System.out.println(r.nextInt(100) + 10); // 10-109
}
public static void arr() {
//静态数组 就和c++差不多
// int[3] a = new int[]{1,2,3};
int[] a = {1, 2, 3, 4}; //简化写法(动态初始化)
// 整数类型的默认值为0 String 的为 null
int[] b = new int[10]; //但此时不能 {1,2,3,4}来赋值 (静态初始化)
//冒泡排序
int arr[] = {13, 51, 12, 48, 36};
//循环长度-1轮
for (int i = 0; i < arr.length - 1; i++) {
//没轮判断 长度-轮序号(从0开始)-1
for (int j = 0; j < arr.length - i - 1; j++) {
if (arr[i] < arr[j]) {
int tmp = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = tmp;
}
}
}
for (int i = 0; i < arr.length; i++) {
System.out.println(i);
}
}
}
| AkiChase/Java-Learning | src/pers/ruchuby/learning/basic/BasicGrammar.java | 1,356 | //位运算符 位运算符判断时左右都会运算 | line_comment | zh-cn | package pers.ruchuby.learning.basic;
import java.util.Random;
import java.util.Scanner;
public class BasicGrammar {
public static void variable() {
//变量类型
// 整数类型
double a = 6.66; //默认用double 8个字节
float aa = 6.6f; //float要加f或F 4个字节
int b = 6;
byte e = 127; // -128~127
// String为引用数据类型
String c;
c = "来日等不过方长";
char d = 65; //字符 A
//空字符 中间用空格
System.out.println(' ');
//布尔类型
boolean flag = true;
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
}
public static void typeConversion() {
// 自动类型转换
byte a = 10;
int b = a; //自动从小范围转换为大范围 内存中在左侧补充0
float c = b; // int to float(double也可以)
System.out.println(c);
double d = a + b + 2.3; //表达式 自动提升
// byte char 等类型在运算时都会转化为int
// 基本与C#一致
}
public static void operator() {
// + - * / %取余
//注意int相除的时候还是int
System.out.println(3 / 2);
System.out.println(3 * 1.0 / 2); //这样才能得到double
// 能计算就按原类型计算,否则按字符串合并
System.out.println(10 + 'a'); // 107
System.out.println('a' + "你好" + 10); // a你好10
// ++ -- 前后自增 自减
// += -= *= /= %=
//如a+=b 等同于 a = (a的类型) a+b 包含了强制类型转换
// 关系运算符 == != >= <=等等
//位运 <SUF>
System.out.println(true | false); // 或
System.out.println(false & true);// 与
System.out.println(!true); //非
System.out.println(true ^ true); //异或 两者不等则为true
// 逻辑运算符 ! && ||
//三元运算符
System.out.println(1 > 2 ? "1>2为真" : "1>2为假");
/*
运算符优先级 与c++有细微的差别
1. ()之类括号最高
2. ! ++ --
2. 加减乘除之类的
3. 左右移运算
4. 逻辑判断
4. 逻辑位运算
5. 逻辑运算(&& ||)
6. += -=之类
*/
}
public static void userInput() {
Scanner sc = new Scanner(System.in);
System.out.println("请输入数字");
int a = sc.nextInt();
System.out.println(a);
System.out.println("请输入字符串");
String s = sc.next();
System.out.println(s);
}
public static void processControl() {
int a = 10;
int b = 20;
// if else
if (a > b) {
System.out.println(a);
} else {
System.out.println(b);
}
// switch
switch (a) {
case 10:
System.out.println("a=10");
break;
default:
System.out.println("默认");
}
//for
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
//while
int i = 0;
while (true) {
System.out.println(i);
i++;
if (i > 3) break;
}
// do while 基本差不多
//死循环写法
// while (true)
// for (; ; )
// do{}while (true)
//随机数
Random r = new Random();
System.out.println(r.nextInt(100)); // 0-99
System.out.println(r.nextInt(100) + 10); // 10-109
}
public static void arr() {
//静态数组 就和c++差不多
// int[3] a = new int[]{1,2,3};
int[] a = {1, 2, 3, 4}; //简化写法(动态初始化)
// 整数类型的默认值为0 String 的为 null
int[] b = new int[10]; //但此时不能 {1,2,3,4}来赋值 (静态初始化)
//冒泡排序
int arr[] = {13, 51, 12, 48, 36};
//循环长度-1轮
for (int i = 0; i < arr.length - 1; i++) {
//没轮判断 长度-轮序号(从0开始)-1
for (int j = 0; j < arr.length - i - 1; j++) {
if (arr[i] < arr[j]) {
int tmp = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = tmp;
}
}
}
for (int i = 0; i < arr.length; i++) {
System.out.println(i);
}
}
}
| false |
59031_6 | package algorithm;
/**
* Q:快速获取n类素数 <br/>
* 埃氏筛选法 <br/>
* 欧拉筛选(线性筛)<br/>
* 注意:大数素数获取不要用埃氏筛、欧拉筛(内存溢出),特别是数范围可以不断减小的情况
*
* @author Yuri
* @since 2022/6/28 9:28
*/
public class EratosthenesAndEuler {
public static void main(String[] args) {
EratosthenesAndEuler eratosthenesAndEuler = new EratosthenesAndEuler();
eratosthenesAndEuler.eratosthenes();
int sum = 0;
for (int i = 0; i < MAX_N; i++) {
if (!vis[i]) {
System.out.print(i + " ");
sum++;
}
}
System.out.println("\nthe sum is: " + sum);
}
/**
* 埃氏筛选法 O(nloglogn)
*
* @see <a href="https://zh.m.wikipedia.org/zh/%E5%9F%83%E6%8B%89%E6%89%98%E6%96%AF%E7%89%B9%E5%B0%BC%E7%AD%9B%E6%B3%95">理论:wiki-埃拉托斯特尼筛法</a>
* @see <a href="https://blog.csdn.net/o83290102o5/article/details/79491834">证明:埃拉托斯特尼筛法详解</a>
*/
static int MAX_N = 100000;
static boolean[] vis = new boolean[MAX_N];
private void eratosthenes() {
vis[0] = vis[1] = true;
// 如果到了他的根号,还没有一个因子出现,那么后半部分也不会有因子出现了
int sqrt = (int) Math.sqrt(MAX_N);
for (int i = 2; i <= sqrt; i++) { //只需计算到sqrt(n)
if (vis[i]) continue; //合数直接跳
for (int j = i; i * j < MAX_N; j++) {
vis[i * j] = true; //标记为合数
}
}
}
/**
* 欧拉筛(埃氏筛的改进)
*
* @see <a href="https://blog.csdn.net/qq_43822715/article/details/105196474">埃式筛和欧拉筛讲解</a>
*/
static int[] p = new int[MAX_N];
public void euler() {
vis[0] = vis[1] = true;
int tot = 0;
for (int i = 2; i <= MAX_N; ++i) {
if (!vis[i]) {
p[++tot] = i; //记录素数
}
for (int j = 1; j <= tot && i * p[j] <= MAX_N; ++j) {
vis[i * p[j]] = true; //合数都可以以唯一形式被写成质数的乘积
//如果i % p[j] == 0(假设i/p[j]=k),则i = p[j]*k,∴i*p[j+1] = p[j]*k*p[j+1],而k*p[j+1]这会被跟后续更大的i所代替
//例如:i=12,12%2=0,k=6,如果不break继续循环,i*p[j] = 12*3 = 2*6*3 = 18*2,这会有重复,因为36会在后续循环i = 18中被计算
if (i % p[j] == 0) {
break;
}
}
}
}
}
| AkimotoAkiraXs/algorithm | src/main/code/algorithm/EratosthenesAndEuler.java | 1,012 | /**
* 欧拉筛(埃氏筛的改进)
*
* @see <a href="https://blog.csdn.net/qq_43822715/article/details/105196474">埃式筛和欧拉筛讲解</a>
*/ | block_comment | zh-cn | package algorithm;
/**
* Q:快速获取n类素数 <br/>
* 埃氏筛选法 <br/>
* 欧拉筛选(线性筛)<br/>
* 注意:大数素数获取不要用埃氏筛、欧拉筛(内存溢出),特别是数范围可以不断减小的情况
*
* @author Yuri
* @since 2022/6/28 9:28
*/
public class EratosthenesAndEuler {
public static void main(String[] args) {
EratosthenesAndEuler eratosthenesAndEuler = new EratosthenesAndEuler();
eratosthenesAndEuler.eratosthenes();
int sum = 0;
for (int i = 0; i < MAX_N; i++) {
if (!vis[i]) {
System.out.print(i + " ");
sum++;
}
}
System.out.println("\nthe sum is: " + sum);
}
/**
* 埃氏筛选法 O(nloglogn)
*
* @see <a href="https://zh.m.wikipedia.org/zh/%E5%9F%83%E6%8B%89%E6%89%98%E6%96%AF%E7%89%B9%E5%B0%BC%E7%AD%9B%E6%B3%95">理论:wiki-埃拉托斯特尼筛法</a>
* @see <a href="https://blog.csdn.net/o83290102o5/article/details/79491834">证明:埃拉托斯特尼筛法详解</a>
*/
static int MAX_N = 100000;
static boolean[] vis = new boolean[MAX_N];
private void eratosthenes() {
vis[0] = vis[1] = true;
// 如果到了他的根号,还没有一个因子出现,那么后半部分也不会有因子出现了
int sqrt = (int) Math.sqrt(MAX_N);
for (int i = 2; i <= sqrt; i++) { //只需计算到sqrt(n)
if (vis[i]) continue; //合数直接跳
for (int j = i; i * j < MAX_N; j++) {
vis[i * j] = true; //标记为合数
}
}
}
/**
* 欧拉筛 <SUF>*/
static int[] p = new int[MAX_N];
public void euler() {
vis[0] = vis[1] = true;
int tot = 0;
for (int i = 2; i <= MAX_N; ++i) {
if (!vis[i]) {
p[++tot] = i; //记录素数
}
for (int j = 1; j <= tot && i * p[j] <= MAX_N; ++j) {
vis[i * p[j]] = true; //合数都可以以唯一形式被写成质数的乘积
//如果i % p[j] == 0(假设i/p[j]=k),则i = p[j]*k,∴i*p[j+1] = p[j]*k*p[j+1],而k*p[j+1]这会被跟后续更大的i所代替
//例如:i=12,12%2=0,k=6,如果不break继续循环,i*p[j] = 12*3 = 2*6*3 = 18*2,这会有重复,因为36会在后续循环i = 18中被计算
if (i % p[j] == 0) {
break;
}
}
}
}
}
| true |
52564_1 | /*
修饰符
1. 外部类
权限修饰符:public和缺省
其他修饰符:final
2. 方法
权限修饰符:4种
其他修饰符:final, static, native,
3. 成员变量
权限修饰符:4种
其他修饰符:final, static
4. 代码块
权限修饰符:无
其他修饰符:static
*/
/*
final
1. 可以修饰:类、变量、方法
2. 修饰后有什么不同?
2.1. 修饰类:表示这个类不能被继承了
2.2. 修饰方法:表示这个方法不能被重写
2.3. 修饰变量:表示这个变量的值不能被修改,即我们称为的常量。常量命名应该用大写。
*/
/*
native
1. 可以修饰:方法
2. 修饰后有什么不同?
2.1. native修饰的方法没有方法体
2.2. native修饰的方法不是用Java语言实现的,而是调用了底层C/C++的代码。这些代码被编译为.dll文件,让Java来执行的。
3. 特殊
3.1. native方法该怎么调用还是怎么调用
3.2. 子类可以对它进行重写
*/
/*
static
1. 可以修饰:成员变量、方法、内部类、代码块
2. 修饰后有什么不同?
2.1. 静态方法
2.1.1. 对于其他类说可以用“类名.方法”进行调用。
2.1.2. 不允许出现this、super等对本类非静态属性、方法的使用
2.2. 静态成员变量
2.2.1. 静态成员变量值存储在方法区内
*/
public class KeyWords {
}
| AkiraKane/JavaLearning | src/KeyWords.java | 467 | /*
final
1. 可以修饰:类、变量、方法
2. 修饰后有什么不同?
2.1. 修饰类:表示这个类不能被继承了
2.2. 修饰方法:表示这个方法不能被重写
2.3. 修饰变量:表示这个变量的值不能被修改,即我们称为的常量。常量命名应该用大写。
*/ | block_comment | zh-cn | /*
修饰符
1. 外部类
权限修饰符:public和缺省
其他修饰符:final
2. 方法
权限修饰符:4种
其他修饰符:final, static, native,
3. 成员变量
权限修饰符:4种
其他修饰符:final, static
4. 代码块
权限修饰符:无
其他修饰符:static
*/
/*
fin <SUF>*/
/*
native
1. 可以修饰:方法
2. 修饰后有什么不同?
2.1. native修饰的方法没有方法体
2.2. native修饰的方法不是用Java语言实现的,而是调用了底层C/C++的代码。这些代码被编译为.dll文件,让Java来执行的。
3. 特殊
3.1. native方法该怎么调用还是怎么调用
3.2. 子类可以对它进行重写
*/
/*
static
1. 可以修饰:成员变量、方法、内部类、代码块
2. 修饰后有什么不同?
2.1. 静态方法
2.1.1. 对于其他类说可以用“类名.方法”进行调用。
2.1.2. 不允许出现this、super等对本类非静态属性、方法的使用
2.2. 静态成员变量
2.2.1. 静态成员变量值存储在方法区内
*/
public class KeyWords {
}
| true |
23402_2 | package main;
import java.util.Date;
import java.util.GregorianCalendar;
/**
* create by Intellij IDEA
* Author: Al-assad
* E-mail: yulinying_1994@outlook.com
* Github: https://github.com/Al-assad
* Date: 2017/4/11 11:57
* Description: bilibili用户信息类
*/
public class BiliUser {
private long mid; //mid
private String name; //昵称
private String sex ; //性别[“男”,“女”,“保密”]
private int level; //等级[1-5]
private String sign; //用户签名
private String faceUrl; //用户头像图片链接
private int friends; //关注数量
private int fans; //粉丝数量
private int playNum; //上传视频播放量
private String birthday; //生日(系统默认项:0000-01-01)
private String place ; //所在地点
public BiliUser(){
}
//getter and setter method
public long getMid() {
return mid;
}
public void setMid(long mid) {
this.mid = mid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public String getSign() {
return sign;
}
public void setSign(String sign) {
this.sign = sign;
}
public String getFaceUrl() {
return faceUrl;
}
public void setFaceUrl(String faceUrl) {
this.faceUrl = faceUrl;
}
public int getFriends() {
return friends;
}
public void setFriends(int friends) {
this.friends = friends;
}
public int getFans() {
return fans;
}
public void setFans(int fans) {
this.fans = fans;
}
public int getPlayNum() {
return playNum;
}
public void setPlayNum(int playNum) {
this.playNum = playNum;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
//废弃以0000-开头的birthday记录
if(birthday.equals("0000-01-01"))
birthday = null;
this.birthday = birthday;
}
public String getPlace() {
return place;
}
public void setPlace(String place) {
this.place = place;
}
//toString method
public String toString(){
return "mid="+mid+", "
+"name="+name+", "
+"level="+level+", "
+"sex="+sex+", "
+"sign="+sign+", "
+"friends="+friends+", "
+"faceUrl="+faceUrl+", "
+"fans="+fans+", "
+"playNum="+playNum+", "
+"brithday="+birthday+", "
+"place="+place;
}
}
| Al-assad/Spider-bilibiliUser-active | src/main/BiliUser.java | 780 | //性别[“男”,“女”,“保密”] | line_comment | zh-cn | package main;
import java.util.Date;
import java.util.GregorianCalendar;
/**
* create by Intellij IDEA
* Author: Al-assad
* E-mail: yulinying_1994@outlook.com
* Github: https://github.com/Al-assad
* Date: 2017/4/11 11:57
* Description: bilibili用户信息类
*/
public class BiliUser {
private long mid; //mid
private String name; //昵称
private String sex ; //性别 <SUF>
private int level; //等级[1-5]
private String sign; //用户签名
private String faceUrl; //用户头像图片链接
private int friends; //关注数量
private int fans; //粉丝数量
private int playNum; //上传视频播放量
private String birthday; //生日(系统默认项:0000-01-01)
private String place ; //所在地点
public BiliUser(){
}
//getter and setter method
public long getMid() {
return mid;
}
public void setMid(long mid) {
this.mid = mid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public String getSign() {
return sign;
}
public void setSign(String sign) {
this.sign = sign;
}
public String getFaceUrl() {
return faceUrl;
}
public void setFaceUrl(String faceUrl) {
this.faceUrl = faceUrl;
}
public int getFriends() {
return friends;
}
public void setFriends(int friends) {
this.friends = friends;
}
public int getFans() {
return fans;
}
public void setFans(int fans) {
this.fans = fans;
}
public int getPlayNum() {
return playNum;
}
public void setPlayNum(int playNum) {
this.playNum = playNum;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
//废弃以0000-开头的birthday记录
if(birthday.equals("0000-01-01"))
birthday = null;
this.birthday = birthday;
}
public String getPlace() {
return place;
}
public void setPlace(String place) {
this.place = place;
}
//toString method
public String toString(){
return "mid="+mid+", "
+"name="+name+", "
+"level="+level+", "
+"sex="+sex+", "
+"sign="+sign+", "
+"friends="+friends+", "
+"faceUrl="+faceUrl+", "
+"fans="+fans+", "
+"playNum="+playNum+", "
+"brithday="+birthday+", "
+"place="+place;
}
}
| false |
18241_25 | package com.song.homework09;
/* Maze.java */
import java.util.*;
import com.song.homework09.set.*;
/**
* The Maze class represents a maze in a rectangular grid. There is exactly
* one path between any two points.
**/
public class Maze {
// Horizontal and vertical dimensions of the maze.
protected int horiz;
protected int vert;
// Horizontal and vertical interior walls; each is true if the wall exists.
protected boolean[][] hWalls;
protected boolean[][] vWalls;
// Object for generting random numbers.
private static Random random;
// Constants used in depth-first search (which checks for cycles in the
// maze).
private static final int STARTHERE = 0;
private static final int FROMLEFT = 1;
private static final int FROMRIGHT = 2;
private static final int FROMABOVE = 3;
private static final int FROMBELOW = 4;
/**
* Maze() creates a rectangular maze having "horizontalSize" cells in the
* horizontal direction, and "verticalSize" cells in the vertical direction.
* There is a path between any two cells of the maze. A disjoint set data
* structure is used to ensure that there is only one path between any two
* cells.
**/
public Maze(int horizontalSize, int verticalSize) {
int i, j;
horiz = horizontalSize;
vert = verticalSize;
if ((horiz < 1) || (vert < 1) || ((horiz == 1) && (vert == 1))) {
return; // There are no interior walls
}
// Create all of the horizontal interior walls. Initially, every
// horizontal wall exists; they will be removed later by the maze
// generation algorithm.
if (vert > 1) {
hWalls = new boolean[horiz][vert - 1];
for (j = 0; j < vert - 1; j++) {
for (i = 0; i < horiz; i++) {
hWalls[i][j] = true; //wall 都存在,即没有edge。
}
}
}
// Create all of the vertical interior walls.
if (horiz > 1) {
vWalls = new boolean[horiz - 1][vert];
for (i = 0; i < horiz - 1; i++) {
for (j = 0; j < vert; j++) {
vWalls[i][j] = true;
}
}
}
/**
* Fill in the rest of this method. You should go through all the walls of
* the maze in random order, and remove any wall whose removal will not
* create a cycle. Use the implementation of disjoint sets provided in the
* set package to avoid creating any cycles.
*
* Note the method randInt() further below, which generates a random
* integer. randInt() generates different numbers every time the program
* is run, so that you can make lots of different mazes.
**/
DisjointSets cellSet=new DisjointSets(horiz*vert); //创建一个并查集,放入所有的cell
int NumofWalls=vert*(horiz-1)+horiz*(vert-1); //墙的总数
int[] WallArray=new int[NumofWalls];
int index=0;
if(vert>1){
for(j=0;j<vert-1;j++){
for(i=0;i<horiz;i++){
WallArray[index]=j*horiz+i; //horizontal wall分别编号、横着编:从左往右1234....
// 分隔上下两个cell
index++;
}
}
}
if(horiz>1){
for(i=0;i<horiz-1;i++){
for(j=0;j<vert;j++){
WallArray[index]=- (j*horiz+i); //vertical wall 分别编号,、横着编:从左往右1234....
// 为了和horizontal wall区分,用负数表示
// 分隔左右两个cell
index++;
}
}
}
//将WallArray里面的wall随机排布
int w=NumofWalls;
int temp;
while(w>1){
int x=randInt(w); //在0 - w-1随机取数
temp=WallArray[x];
WallArray[x]=WallArray[w-1]; //swap随机取的第x个和最后一个 注意WallArray[w-1]是最后一个数
WallArray[w-1]=temp;
w--; //下次swap随机取的第x个和倒数第二个,以此类推
}
for(int k=0;k<NumofWalls;k++){
index=WallArray[k]; //从随机排列后第一个WallArray开始取wall的信息,
// 这个wall同时表示了它上方(horiz)或左方(vert)的cell,见readme
if(index>0) { //如果是horizontal wall
int cellParent1 = cellSet.find(index); //返回这个cell的parent
int cellParent2 = cellSet.find(index + horiz); //返回这个cell下面那个cell的parent
//如果他们的parent是同一个,说明cell和cell下面(上面)那个cell在同一个set里,中间的墙得有
//如果不是同一个parent,也就是说他们之间没有通路,union后将墙设为false
if (cellParent1 != cellParent2) {
cellSet.union(cellParent1, cellParent2); //这个操作后他们的parent一样了
hWalls[index % horiz][index / horiz] = false;
//wall的横向位置:index % horiz
//wall的纵向位置:index / horiz
}
}
else { //如果是vertical wall
int cellParent3 = cellSet.find(-index); //返回这个cell的parent
int cellParent4 = cellSet.find(-index + 1); //返回这个cell右边那个cell的parent
if (cellParent3 != cellParent4){
cellSet.union(cellParent3,cellParent4);
vWalls[(-index)%horiz][(-index)/horiz] = false;
}
}
}
}
/**
* toString() returns a string representation of the maze.
**/
public String toString() {
int i, j;
String s = "";
// Print the top exterior wall.
for (i = 0; i < horiz; i++) {
s = s + "--";
}
s = s + "-\n|";
// Print the maze interior.
for (j = 0; j < vert; j++) {
// Print a row of cells and vertical walls.
for (i = 0; i < horiz - 1; i++) {
if (vWalls[i][j]) {
s = s + " |";
} else {
s = s + " ";
}
}
s = s + " |\n+";
if (j < vert - 1) {
// Print a row of horizontal walls and wall corners.
for (i = 0; i < horiz; i++) {
if (hWalls[i][j]) {
s = s + "-+";
} else {
s = s + " +";
}
}
s = s + "\n|";
}
}
// Print the bottom exterior wall. (Note that the first corner has
// already been printed.)
for (i = 0; i < horiz; i++) {
s = s + "--";
}
return s + "\n";
}
/**
* horizontalWall() determines whether the horizontal wall on the bottom
* edge of cell (x, y) exists. If the coordinates (x, y) do not correspond
* to an interior wall, true is returned.
**/
public boolean horizontalWall(int x, int y) {
if ((x < 0) || (y < 0) || (x > horiz - 1) || (y > vert - 2)) {
return true;
}
return hWalls[x][y];
}
/**
* verticalWall() determines whether the vertical wall on the right edge of
* cell (x, y) exists. If the coordinates (x, y) do not correspond to an
* interior wall, true is returned.
**/
public boolean verticalWall(int x, int y) {
if ((x < 0) || (y < 0) || (x > horiz - 2) || (y > vert - 1)) {
return true;
}
return vWalls[x][y];
}
/**
* randInt() returns a random integer from 0 to choices - 1.
**/
private static int randInt(int choices) {
if (random == null) { // Only executed first time randInt() is called
random = new Random(); // Create a "Random" object with random seed
}
int r = random.nextInt() % choices; // From | choice - 1 | to choices - 1
if (r < 0) {
r = -r; // From 0 to choices - 1
}
return r;
}
/**
* diagnose() checks the maze and prints a warning if not every cell can be
* reached from the upper left corner cell, or if there is a cycle reachable
* from the upper left cell.
*
* DO NOT CHANGE THIS METHOD. Your code is expected to work with our copy
* of this method.
**/
protected void diagnose() {
if ((horiz < 1) || (vert < 1) || ((horiz == 1) && (vert == 1))) {
return; // There are no interior walls
}
boolean mazeFine = true;
// Create an array that indicates whether each cell has been visited during
// a depth-first traversal.
boolean[][] cellVisited = new boolean[horiz][vert];
// Do a depth-first traversal.
if (depthFirstSearch(0, 0, STARTHERE, cellVisited)) {
System.out.println("Your maze has a cycle.");
mazeFine = false;
}
// Check to be sure that every cell of the maze was visited.
outerLoop:
for (int j = 0; j < vert; j++) {
for (int i = 0; i < horiz; i++) {
if (!cellVisited[i][j]) {
System.out.println("Not every cell in your maze is reachable from " +
"every other cell.");
mazeFine = false;
break outerLoop;
}
}
}
if (mazeFine) {
System.out.println("What a fine maze you've created!");
}
}
/**
* depthFirstSearch() does a depth-first traversal of the maze, marking each
* visited cell. Returns true if a cycle is found.
*
* DO NOT CHANGE THIS METHOD. Your code is expected to work with our copy
* of this method.
*/
protected boolean depthFirstSearch(int x, int y, int fromWhere,
boolean[][] cellVisited) {
boolean cycleDetected = false;
cellVisited[x][y] = true;
// Visit the cell to the right?
if ((fromWhere != FROMRIGHT) && !verticalWall(x, y)) {
if (cellVisited[x + 1][y]) {
cycleDetected = true;
} else {
cycleDetected = depthFirstSearch(x + 1, y, FROMLEFT, cellVisited) ||
cycleDetected;
}
}
// Visit the cell below?
if ((fromWhere != FROMBELOW) && !horizontalWall(x, y)) {
if (cellVisited[x][y + 1]) {
cycleDetected = true;
} else {
cycleDetected = depthFirstSearch(x, y + 1, FROMABOVE, cellVisited) ||
cycleDetected;
}
}
// Visit the cell to the left?
if ((fromWhere != FROMLEFT) && !verticalWall(x - 1, y)) {
if (cellVisited[x - 1][y]) {
cycleDetected = true;
} else {
cycleDetected = depthFirstSearch(x - 1, y, FROMRIGHT, cellVisited) ||
cycleDetected;
}
}
// Visit the cell above?
if ((fromWhere != FROMABOVE) && !horizontalWall(x, y - 1)) {
if (cellVisited[x][y - 1]) {
cycleDetected = true;
} else {
cycleDetected = depthFirstSearch(x, y - 1, FROMBELOW, cellVisited) ||
cycleDetected;
}
}
return cycleDetected;
}
/**
* main() creates a maze of dimensions specified on the 【command line】, prints
* the maze, and runs the diagnostic method to see if the maze is good.
*
* 命令行窗口输入:java Maze 30 10 ,那么 args[0]=30, args[1]=10;
*/
public static void main(String[] args) {
int x = 39;
int y = 15;
/**
* Read the input parameters.
*/
if (args.length > 0) {
try {
x = Integer.parseInt(args[0]);
}
catch (NumberFormatException e) {
System.out.println("First argument to Simulation is not an number.");
}
}
if (args.length > 1) {
try {
y = Integer.parseInt(args[1]);
}
catch (NumberFormatException e) {
System.out.println("Second argument to Simulation is not an number.");
}
}
Maze maze = new Maze(x, y);
System.out.print(maze);
maze.diagnose();
}
} | Alan-song641/UC-Berkeley-CS-61B | homework09/Maze.java | 3,268 | //下次swap随机取的第x个和倒数第二个,以此类推 | line_comment | zh-cn | package com.song.homework09;
/* Maze.java */
import java.util.*;
import com.song.homework09.set.*;
/**
* The Maze class represents a maze in a rectangular grid. There is exactly
* one path between any two points.
**/
public class Maze {
// Horizontal and vertical dimensions of the maze.
protected int horiz;
protected int vert;
// Horizontal and vertical interior walls; each is true if the wall exists.
protected boolean[][] hWalls;
protected boolean[][] vWalls;
// Object for generting random numbers.
private static Random random;
// Constants used in depth-first search (which checks for cycles in the
// maze).
private static final int STARTHERE = 0;
private static final int FROMLEFT = 1;
private static final int FROMRIGHT = 2;
private static final int FROMABOVE = 3;
private static final int FROMBELOW = 4;
/**
* Maze() creates a rectangular maze having "horizontalSize" cells in the
* horizontal direction, and "verticalSize" cells in the vertical direction.
* There is a path between any two cells of the maze. A disjoint set data
* structure is used to ensure that there is only one path between any two
* cells.
**/
public Maze(int horizontalSize, int verticalSize) {
int i, j;
horiz = horizontalSize;
vert = verticalSize;
if ((horiz < 1) || (vert < 1) || ((horiz == 1) && (vert == 1))) {
return; // There are no interior walls
}
// Create all of the horizontal interior walls. Initially, every
// horizontal wall exists; they will be removed later by the maze
// generation algorithm.
if (vert > 1) {
hWalls = new boolean[horiz][vert - 1];
for (j = 0; j < vert - 1; j++) {
for (i = 0; i < horiz; i++) {
hWalls[i][j] = true; //wall 都存在,即没有edge。
}
}
}
// Create all of the vertical interior walls.
if (horiz > 1) {
vWalls = new boolean[horiz - 1][vert];
for (i = 0; i < horiz - 1; i++) {
for (j = 0; j < vert; j++) {
vWalls[i][j] = true;
}
}
}
/**
* Fill in the rest of this method. You should go through all the walls of
* the maze in random order, and remove any wall whose removal will not
* create a cycle. Use the implementation of disjoint sets provided in the
* set package to avoid creating any cycles.
*
* Note the method randInt() further below, which generates a random
* integer. randInt() generates different numbers every time the program
* is run, so that you can make lots of different mazes.
**/
DisjointSets cellSet=new DisjointSets(horiz*vert); //创建一个并查集,放入所有的cell
int NumofWalls=vert*(horiz-1)+horiz*(vert-1); //墙的总数
int[] WallArray=new int[NumofWalls];
int index=0;
if(vert>1){
for(j=0;j<vert-1;j++){
for(i=0;i<horiz;i++){
WallArray[index]=j*horiz+i; //horizontal wall分别编号、横着编:从左往右1234....
// 分隔上下两个cell
index++;
}
}
}
if(horiz>1){
for(i=0;i<horiz-1;i++){
for(j=0;j<vert;j++){
WallArray[index]=- (j*horiz+i); //vertical wall 分别编号,、横着编:从左往右1234....
// 为了和horizontal wall区分,用负数表示
// 分隔左右两个cell
index++;
}
}
}
//将WallArray里面的wall随机排布
int w=NumofWalls;
int temp;
while(w>1){
int x=randInt(w); //在0 - w-1随机取数
temp=WallArray[x];
WallArray[x]=WallArray[w-1]; //swap随机取的第x个和最后一个 注意WallArray[w-1]是最后一个数
WallArray[w-1]=temp;
w--; //下次 <SUF>
}
for(int k=0;k<NumofWalls;k++){
index=WallArray[k]; //从随机排列后第一个WallArray开始取wall的信息,
// 这个wall同时表示了它上方(horiz)或左方(vert)的cell,见readme
if(index>0) { //如果是horizontal wall
int cellParent1 = cellSet.find(index); //返回这个cell的parent
int cellParent2 = cellSet.find(index + horiz); //返回这个cell下面那个cell的parent
//如果他们的parent是同一个,说明cell和cell下面(上面)那个cell在同一个set里,中间的墙得有
//如果不是同一个parent,也就是说他们之间没有通路,union后将墙设为false
if (cellParent1 != cellParent2) {
cellSet.union(cellParent1, cellParent2); //这个操作后他们的parent一样了
hWalls[index % horiz][index / horiz] = false;
//wall的横向位置:index % horiz
//wall的纵向位置:index / horiz
}
}
else { //如果是vertical wall
int cellParent3 = cellSet.find(-index); //返回这个cell的parent
int cellParent4 = cellSet.find(-index + 1); //返回这个cell右边那个cell的parent
if (cellParent3 != cellParent4){
cellSet.union(cellParent3,cellParent4);
vWalls[(-index)%horiz][(-index)/horiz] = false;
}
}
}
}
/**
* toString() returns a string representation of the maze.
**/
public String toString() {
int i, j;
String s = "";
// Print the top exterior wall.
for (i = 0; i < horiz; i++) {
s = s + "--";
}
s = s + "-\n|";
// Print the maze interior.
for (j = 0; j < vert; j++) {
// Print a row of cells and vertical walls.
for (i = 0; i < horiz - 1; i++) {
if (vWalls[i][j]) {
s = s + " |";
} else {
s = s + " ";
}
}
s = s + " |\n+";
if (j < vert - 1) {
// Print a row of horizontal walls and wall corners.
for (i = 0; i < horiz; i++) {
if (hWalls[i][j]) {
s = s + "-+";
} else {
s = s + " +";
}
}
s = s + "\n|";
}
}
// Print the bottom exterior wall. (Note that the first corner has
// already been printed.)
for (i = 0; i < horiz; i++) {
s = s + "--";
}
return s + "\n";
}
/**
* horizontalWall() determines whether the horizontal wall on the bottom
* edge of cell (x, y) exists. If the coordinates (x, y) do not correspond
* to an interior wall, true is returned.
**/
public boolean horizontalWall(int x, int y) {
if ((x < 0) || (y < 0) || (x > horiz - 1) || (y > vert - 2)) {
return true;
}
return hWalls[x][y];
}
/**
* verticalWall() determines whether the vertical wall on the right edge of
* cell (x, y) exists. If the coordinates (x, y) do not correspond to an
* interior wall, true is returned.
**/
public boolean verticalWall(int x, int y) {
if ((x < 0) || (y < 0) || (x > horiz - 2) || (y > vert - 1)) {
return true;
}
return vWalls[x][y];
}
/**
* randInt() returns a random integer from 0 to choices - 1.
**/
private static int randInt(int choices) {
if (random == null) { // Only executed first time randInt() is called
random = new Random(); // Create a "Random" object with random seed
}
int r = random.nextInt() % choices; // From | choice - 1 | to choices - 1
if (r < 0) {
r = -r; // From 0 to choices - 1
}
return r;
}
/**
* diagnose() checks the maze and prints a warning if not every cell can be
* reached from the upper left corner cell, or if there is a cycle reachable
* from the upper left cell.
*
* DO NOT CHANGE THIS METHOD. Your code is expected to work with our copy
* of this method.
**/
protected void diagnose() {
if ((horiz < 1) || (vert < 1) || ((horiz == 1) && (vert == 1))) {
return; // There are no interior walls
}
boolean mazeFine = true;
// Create an array that indicates whether each cell has been visited during
// a depth-first traversal.
boolean[][] cellVisited = new boolean[horiz][vert];
// Do a depth-first traversal.
if (depthFirstSearch(0, 0, STARTHERE, cellVisited)) {
System.out.println("Your maze has a cycle.");
mazeFine = false;
}
// Check to be sure that every cell of the maze was visited.
outerLoop:
for (int j = 0; j < vert; j++) {
for (int i = 0; i < horiz; i++) {
if (!cellVisited[i][j]) {
System.out.println("Not every cell in your maze is reachable from " +
"every other cell.");
mazeFine = false;
break outerLoop;
}
}
}
if (mazeFine) {
System.out.println("What a fine maze you've created!");
}
}
/**
* depthFirstSearch() does a depth-first traversal of the maze, marking each
* visited cell. Returns true if a cycle is found.
*
* DO NOT CHANGE THIS METHOD. Your code is expected to work with our copy
* of this method.
*/
protected boolean depthFirstSearch(int x, int y, int fromWhere,
boolean[][] cellVisited) {
boolean cycleDetected = false;
cellVisited[x][y] = true;
// Visit the cell to the right?
if ((fromWhere != FROMRIGHT) && !verticalWall(x, y)) {
if (cellVisited[x + 1][y]) {
cycleDetected = true;
} else {
cycleDetected = depthFirstSearch(x + 1, y, FROMLEFT, cellVisited) ||
cycleDetected;
}
}
// Visit the cell below?
if ((fromWhere != FROMBELOW) && !horizontalWall(x, y)) {
if (cellVisited[x][y + 1]) {
cycleDetected = true;
} else {
cycleDetected = depthFirstSearch(x, y + 1, FROMABOVE, cellVisited) ||
cycleDetected;
}
}
// Visit the cell to the left?
if ((fromWhere != FROMLEFT) && !verticalWall(x - 1, y)) {
if (cellVisited[x - 1][y]) {
cycleDetected = true;
} else {
cycleDetected = depthFirstSearch(x - 1, y, FROMRIGHT, cellVisited) ||
cycleDetected;
}
}
// Visit the cell above?
if ((fromWhere != FROMABOVE) && !horizontalWall(x, y - 1)) {
if (cellVisited[x][y - 1]) {
cycleDetected = true;
} else {
cycleDetected = depthFirstSearch(x, y - 1, FROMBELOW, cellVisited) ||
cycleDetected;
}
}
return cycleDetected;
}
/**
* main() creates a maze of dimensions specified on the 【command line】, prints
* the maze, and runs the diagnostic method to see if the maze is good.
*
* 命令行窗口输入:java Maze 30 10 ,那么 args[0]=30, args[1]=10;
*/
public static void main(String[] args) {
int x = 39;
int y = 15;
/**
* Read the input parameters.
*/
if (args.length > 0) {
try {
x = Integer.parseInt(args[0]);
}
catch (NumberFormatException e) {
System.out.println("First argument to Simulation is not an number.");
}
}
if (args.length > 1) {
try {
y = Integer.parseInt(args[1]);
}
catch (NumberFormatException e) {
System.out.println("Second argument to Simulation is not an number.");
}
}
Maze maze = new Maze(x, y);
System.out.print(maze);
maze.diagnose();
}
} | false |
31260_4 | package com.ruoyi.common.enums;
/**
* 商户类型枚举
*
* @author AlanLee
* @date 2022-08-12
*/
public enum MerchantKey {
/**
* 酒店
*/
JIUDIAN(1, "酒吧", "酒吧"),
/**
* 夜店
*/
YEDIAN(2, "夜店", "夜店"),
/**
* livehouse
*/
LIVE_HOUSE(3,"livehouse","Live House");
MerchantKey(Integer type, String name, String desc) {
this.type = type;
this.name = name;
this.desc = desc;
}
/**
* 商户类型
*/
private Integer type;
private String name;
/**
* 类型说明
*/
private String desc;
public int getType() {
return type;
}
public String getDesc() {
return desc;
}
public String getName() {
return name;
}
} | AlanLee-Java/bar | bar-common/src/main/java/com/ruoyi/common/enums/MerchantKey.java | 248 | /**
* 商户类型
*/ | block_comment | zh-cn | package com.ruoyi.common.enums;
/**
* 商户类型枚举
*
* @author AlanLee
* @date 2022-08-12
*/
public enum MerchantKey {
/**
* 酒店
*/
JIUDIAN(1, "酒吧", "酒吧"),
/**
* 夜店
*/
YEDIAN(2, "夜店", "夜店"),
/**
* livehouse
*/
LIVE_HOUSE(3,"livehouse","Live House");
MerchantKey(Integer type, String name, String desc) {
this.type = type;
this.name = name;
this.desc = desc;
}
/**
* 商户类 <SUF>*/
private Integer type;
private String name;
/**
* 类型说明
*/
private String desc;
public int getType() {
return type;
}
public String getDesc() {
return desc;
}
public String getName() {
return name;
}
} | false |
26033_15 |
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.io.*;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.SecureRandom;
import java.util.Base64;
/**
* 此class负责进行二维码DES加密
* 2019-8-28 Albert
*/
public class DESUtils {
private SecretKey securekey;
private String key;
private String codedKey=null;
/**
* 对字符串进行BASE64Decoder
*
* @param key
* @return
* @throws Exception
*/
private byte[] decryptBASE64(String key) {
return Base64.getDecoder().decode(key);
}
/**
* 对字节数组进行BASE64Encoder
*
* @param key
* @return
* @throws Exception
*/
private String encryptBASE64(byte[] key) {
return Base64.getEncoder().encodeToString(key);
}
/**
* 获取key
* @return
*/
public String getKey(){
try {
KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
keyGenerator.init(56);
// 生成一个Key
securekey = keyGenerator.generateKey();
// 转变为字节数组
byte[] encoded = securekey.getEncoded();
// 生成密钥字符串
String encodeString = encryptBASE64(encoded);
return encodeString;
} catch (Exception e) {
e.printStackTrace();
return "密钥生成错误.";
}
}
/**
* 加密,返回BASE64的加密字符串
* @param str,key 当key是String类型时使用
* @return
*/
public String getEncryptString(String str,String key) throws Exception {
DESKeySpec desKey = new DESKeySpec(key.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
securekey = keyFactory.generateSecret(desKey);
byte[] strBytes = str.getBytes("UTF-8");
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, securekey);
byte[] encryptStrBytes = cipher.doFinal(strBytes);
return encryptBASE64(encryptStrBytes);
}
/**
* 加密,返回BASE64的加密字符串
* @param str,key 当key是SecretKey类型时使用
* @return
*/
public String getEncryptString(String str,SecretKey key) throws Exception {
byte[] strBytes = str.getBytes("UTF-8");
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptStrBytes = cipher.doFinal(strBytes);
return encryptBASE64(encryptStrBytes);
}
/**
* 对BASE64加密字符串进行解密
* @param str
* @return
*/
public String getDecryptString(String str,String key) throws Exception {
DESKeySpec desKey = new DESKeySpec(key.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
securekey = keyFactory.generateSecret(desKey);
byte[] strBytes = decryptBASE64(str);
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, securekey);
byte[] encryptStrBytes = cipher.doFinal(strBytes);
return new String(encryptStrBytes, "UTF-8");
}
/**
* 得到DES加密后的密文,以及经过RSA加密后的DES密匙.
* @param name
* @return String[] 储存密文以及加密后的密匙.
* @throws Exception
*/
public String[] get_encryname_key_pair(String name)throws Exception{
if(codedKey==null){
String[] list = {getEncryptString(name,key),key};
return list;
}
else{
String[] list = {getEncryptString(name,key),codedKey};
return list;
}
}
/**
* main()是DESUtils的主要单元,负责加密DES密匙,生成DES密匙,并写入相应的txt文件内方便验证时提取。
*
* @param ifrsa true时使用RSA加密DES密匙 false时仅用DES加密.
* @return
*/
/**
* main() is the main unit of DESUtils, responsible for encrypting the DES key, generating the DES key, and writing to the corresponding TXT file for easy extraction when verification.
*
* @param ifrsa true use RSA to encrypt DES key false use DES encryption only.
* @ return
*/
public void main(Boolean ifrsa) {
try {
//String类型密匙文件路径
//String type key file path
File directory = new File(".");
String path = directory.getCanonicalPath();
String fileName = path+"\\Demo\\DesKey.txt";
//根据文件路径读取文件
//Read the file according to the file path
FileOutputStream fos = new FileOutputStream(fileName,true);
ObjectOutputStream oos = new ObjectOutputStream(fos);
// 生成密钥
// Generate the key
key = getKey();//用于DES加密的原密匙 The origin Key used for DES encryption
/*测试
String jiami = getEncryptString("Hello World!",key);
String jiami1 = getEncryptString("Hello World!",securekey);
System.out.println("密匙:" + key);
System.out.println("加密后:" + jiami+"以及"+jiami1);
String jiemi = getDecryptString(jiami,key);
System.out.println("解密后:" + jiemi);
System.out.println("--------------------------------------------------------------");
*/
//当用户选择YES时使用RSA加密DES密匙
if(ifrsa){
RSAUtils RSA = new RSAUtils();
codedKey=RSA.main(key);
}
oos.writeObject(key+"\r\n");
oos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} | AlberTgarY/QRcodeSecurity | Demo/src/DESUtils.java | 1,384 | //根据文件路径读取文件 | line_comment | zh-cn |
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.io.*;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.SecureRandom;
import java.util.Base64;
/**
* 此class负责进行二维码DES加密
* 2019-8-28 Albert
*/
public class DESUtils {
private SecretKey securekey;
private String key;
private String codedKey=null;
/**
* 对字符串进行BASE64Decoder
*
* @param key
* @return
* @throws Exception
*/
private byte[] decryptBASE64(String key) {
return Base64.getDecoder().decode(key);
}
/**
* 对字节数组进行BASE64Encoder
*
* @param key
* @return
* @throws Exception
*/
private String encryptBASE64(byte[] key) {
return Base64.getEncoder().encodeToString(key);
}
/**
* 获取key
* @return
*/
public String getKey(){
try {
KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
keyGenerator.init(56);
// 生成一个Key
securekey = keyGenerator.generateKey();
// 转变为字节数组
byte[] encoded = securekey.getEncoded();
// 生成密钥字符串
String encodeString = encryptBASE64(encoded);
return encodeString;
} catch (Exception e) {
e.printStackTrace();
return "密钥生成错误.";
}
}
/**
* 加密,返回BASE64的加密字符串
* @param str,key 当key是String类型时使用
* @return
*/
public String getEncryptString(String str,String key) throws Exception {
DESKeySpec desKey = new DESKeySpec(key.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
securekey = keyFactory.generateSecret(desKey);
byte[] strBytes = str.getBytes("UTF-8");
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, securekey);
byte[] encryptStrBytes = cipher.doFinal(strBytes);
return encryptBASE64(encryptStrBytes);
}
/**
* 加密,返回BASE64的加密字符串
* @param str,key 当key是SecretKey类型时使用
* @return
*/
public String getEncryptString(String str,SecretKey key) throws Exception {
byte[] strBytes = str.getBytes("UTF-8");
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptStrBytes = cipher.doFinal(strBytes);
return encryptBASE64(encryptStrBytes);
}
/**
* 对BASE64加密字符串进行解密
* @param str
* @return
*/
public String getDecryptString(String str,String key) throws Exception {
DESKeySpec desKey = new DESKeySpec(key.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
securekey = keyFactory.generateSecret(desKey);
byte[] strBytes = decryptBASE64(str);
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, securekey);
byte[] encryptStrBytes = cipher.doFinal(strBytes);
return new String(encryptStrBytes, "UTF-8");
}
/**
* 得到DES加密后的密文,以及经过RSA加密后的DES密匙.
* @param name
* @return String[] 储存密文以及加密后的密匙.
* @throws Exception
*/
public String[] get_encryname_key_pair(String name)throws Exception{
if(codedKey==null){
String[] list = {getEncryptString(name,key),key};
return list;
}
else{
String[] list = {getEncryptString(name,key),codedKey};
return list;
}
}
/**
* main()是DESUtils的主要单元,负责加密DES密匙,生成DES密匙,并写入相应的txt文件内方便验证时提取。
*
* @param ifrsa true时使用RSA加密DES密匙 false时仅用DES加密.
* @return
*/
/**
* main() is the main unit of DESUtils, responsible for encrypting the DES key, generating the DES key, and writing to the corresponding TXT file for easy extraction when verification.
*
* @param ifrsa true use RSA to encrypt DES key false use DES encryption only.
* @ return
*/
public void main(Boolean ifrsa) {
try {
//String类型密匙文件路径
//String type key file path
File directory = new File(".");
String path = directory.getCanonicalPath();
String fileName = path+"\\Demo\\DesKey.txt";
//根据 <SUF>
//Read the file according to the file path
FileOutputStream fos = new FileOutputStream(fileName,true);
ObjectOutputStream oos = new ObjectOutputStream(fos);
// 生成密钥
// Generate the key
key = getKey();//用于DES加密的原密匙 The origin Key used for DES encryption
/*测试
String jiami = getEncryptString("Hello World!",key);
String jiami1 = getEncryptString("Hello World!",securekey);
System.out.println("密匙:" + key);
System.out.println("加密后:" + jiami+"以及"+jiami1);
String jiemi = getDecryptString(jiami,key);
System.out.println("解密后:" + jiemi);
System.out.println("--------------------------------------------------------------");
*/
//当用户选择YES时使用RSA加密DES密匙
if(ifrsa){
RSAUtils RSA = new RSAUtils();
codedKey=RSA.main(key);
}
oos.writeObject(key+"\r\n");
oos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} | false |
17551_3 | import java.util.ArrayList;
import java.util.List;
/*
119. Pascal's Triangle II
Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle.
Note that the row index starts from 0.
In Pascal's triangle, each number is the sum of the two numbers directly above it.
Example:
Input: 3
Output: [1,3,3,1]
Follow up:
Could you optimize your algorithm to use only O(k) extra space?
*/
public class Generate2 {
//ArrayList 的set,get O(1); 与Array[]一样;
public List<Integer> getRow(int rowIndex) {
List<Integer> res = new ArrayList<>();
res.add(1);
for(int i=1;i<=rowIndex;i++){
// res.add(res.get(i-1)*(rowIndex+1-i)/i);
//当值为30时出错
// res.add((int)((double)(res.get(i-1)*(rowIndex+1-i))/i));
//当值为30时出错
// res.add((int)(double)(res.get(i-1))*(rowIndex+1-i)/i);
//当值为30时出错
// res.add((int)((double)(res.get(i-1)))*(rowIndex+1-i)/i);
//当值为30时出错
// double t= res.get(i-1)*(rowIndex+1-i);
// t=t/i;
// res.add((int)t);
//通过
// double t= res.get(i-1);
// t=t*(rowIndex+1-i)/i;
// res.add((int)t);
//通过;第一个double强转是不能有多余括号,要立马强转第一个值;
res.add((int)((double)res.get(i-1)*(rowIndex+1-i)/i));
}
return res;
}
//O(n2);
public List<Integer> getRow2(int rowIndex) {
List<Integer> res = new ArrayList<>();
for(int i=0;i<=rowIndex;i++){
res.add(c(rowIndex,i));
}
return res;
}
//数学公式C(4,2)=4*3/(1*2);
int c(int a,int b){
double res=1;
for(int i=1;i<=b;i++){
//res*=(a+1-i)/i; //发生了四舍入五,导致错误;
// res=res/i*(a+1-i);//防止溢出,先除后乘;为了防止进位错误,改float;
//在高位(27)时余数出错;
res=res*(a+1-i)/i;
}
return (int)res;
}
}
| Albert-W/leetcode | src/Generate2.java | 702 | //当值为30时出错 | line_comment | zh-cn | import java.util.ArrayList;
import java.util.List;
/*
119. Pascal's Triangle II
Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle.
Note that the row index starts from 0.
In Pascal's triangle, each number is the sum of the two numbers directly above it.
Example:
Input: 3
Output: [1,3,3,1]
Follow up:
Could you optimize your algorithm to use only O(k) extra space?
*/
public class Generate2 {
//ArrayList 的set,get O(1); 与Array[]一样;
public List<Integer> getRow(int rowIndex) {
List<Integer> res = new ArrayList<>();
res.add(1);
for(int i=1;i<=rowIndex;i++){
// res.add(res.get(i-1)*(rowIndex+1-i)/i);
//当值 <SUF>
// res.add((int)((double)(res.get(i-1)*(rowIndex+1-i))/i));
//当值为30时出错
// res.add((int)(double)(res.get(i-1))*(rowIndex+1-i)/i);
//当值为30时出错
// res.add((int)((double)(res.get(i-1)))*(rowIndex+1-i)/i);
//当值为30时出错
// double t= res.get(i-1)*(rowIndex+1-i);
// t=t/i;
// res.add((int)t);
//通过
// double t= res.get(i-1);
// t=t*(rowIndex+1-i)/i;
// res.add((int)t);
//通过;第一个double强转是不能有多余括号,要立马强转第一个值;
res.add((int)((double)res.get(i-1)*(rowIndex+1-i)/i));
}
return res;
}
//O(n2);
public List<Integer> getRow2(int rowIndex) {
List<Integer> res = new ArrayList<>();
for(int i=0;i<=rowIndex;i++){
res.add(c(rowIndex,i));
}
return res;
}
//数学公式C(4,2)=4*3/(1*2);
int c(int a,int b){
double res=1;
for(int i=1;i<=b;i++){
//res*=(a+1-i)/i; //发生了四舍入五,导致错误;
// res=res/i*(a+1-i);//防止溢出,先除后乘;为了防止进位错误,改float;
//在高位(27)时余数出错;
res=res*(a+1-i)/i;
}
return (int)res;
}
}
| false |
22946_45 | package TCP;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Date;
import java.sql.*;
class ServerThread extends Thread {
private Socket sk;
ServerThread(Socket sk) {
this.sk = sk;
}
// 线程运行实体
public void run() {
// 连接数据库的五大参数
String driverClass = "com.mysql.jdbc.Driver";// 加载数据库驱动
String databaseName = "BMS";// 连接到哪一个数据库
String serverIp = "127.0.0.1";// 服务器IP地址
String username = "root";// 用户名
String password = "314159";// 密码
// 拼凑成一个完整的URL地址jdbcUrl
String jdbcUrl = "jdbc:mysql://" + serverIp + ":3306/" + databaseName
+ "?useUnicode=true&characterEncoding=utf-8&useSSL=false";
BufferedReader in = null;
PrintWriter out = null;
try {
InputStreamReader isr;
isr = new InputStreamReader(sk.getInputStream());
in = new BufferedReader(isr);
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sk.getOutputStream())), true);
while (true) {
// 接收来自客户端的请求,根据不同的命令返回不同的信息
String cmd = in.readLine();
System.out.println(cmd);
switch (cmd) {
case "1":
// System.out.println("插入信息。");
out.println("命令:"); // 服务器返回提示信息
BufferedReader in1 = null;
PrintWriter out1 = null;
try {
InputStreamReader isr1;
isr1 = new InputStreamReader(sk.getInputStream());
in1 = new BufferedReader(isr1);
out1 = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sk.getOutputStream())), true);
// 获取了插入命令
// 例子:INSERT INTO access VALUES('6','2019-2-14','取款','362.09','李华','赵六');
String insertInfo = in1.readLine();
System.out.println(insertInfo);
Connection conn = null;
PreparedStatement preStmt = null;
Statement stmt = null;
try {
// 1.注册数据库的驱动
Class.forName(driverClass);
// 2.通过Connection对象获取Statement对象
conn = DriverManager.getConnection(jdbcUrl, username, password);
// 3.创建statement类对象,用来执行SQL语句
stmt = conn.createStatement();
// 执行的SQL语句
String sql = insertInfo;
preStmt = conn.prepareStatement(sql);
int i = stmt.executeUpdate(sql);// 执行,如果i>=1,成功,否则更新失败
if (i >= 1) {
out.println("插入成功!");
} else {
out.println("插入失败!");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (preStmt != null) {
try {
preStmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
preStmt = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
} catch (Exception e) {
e.printStackTrace();
}
break;
case "2":
// System.out.println("查询个人。");
// out.println("姓名:"); // 服务器返回提示信息
BufferedReader in2 = null;
PrintWriter out2 = null;
try {
InputStreamReader isr2;
isr2 = new InputStreamReader(sk.getInputStream());
in2 = new BufferedReader(isr2);
out2 = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sk.getOutputStream())), true);
String searchSql = in2.readLine();
// System.out.println(searchName);
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
Class.forName(driverClass);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
conn = DriverManager.getConnection(jdbcUrl, username, password);
String sql = searchSql;
stmt = conn.prepareStatement(sql);
rs = stmt.executeQuery();
out2.println("=============================================");
out.println("个人存取款信息列表");
out.println("编号 储户 时间 类别 存取数目 经办人");
while (rs.next()) {
int access_id = rs.getInt("access_id");
String access_name = rs.getString("access_name");
Date access_date = rs.getDate("access_date");
String access_class = rs.getString("access_class");
Float access_num = rs.getFloat("access_num");
String access_operator = rs.getString("access_operator");
out.println("" + access_id + " " + access_name + " " + access_date + " "
+ access_class + " " + access_num + " " + access_operator + " ");
}
out2.println("=============================================");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
break;
case "3":
// System.out.println("查询总表。");
BufferedReader in3 = null;
PrintWriter out3 = null;
try {
InputStreamReader isr3;
isr3 = new InputStreamReader(sk.getInputStream());
out3 = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sk.getOutputStream())), true);
Statement stmt = null;
ResultSet rs = null;
Connection conn = null;
try {
// 1.注册数据库的驱动
Class.forName(driverClass);
// 2.通过Connection对象获取Statement对象
conn = DriverManager.getConnection(jdbcUrl, username, password);
stmt = conn.createStatement();
String sql = "select * from access";
rs = stmt.executeQuery(sql);
out3.println("=============================================");
out3.println("总表:");
out3.println("编号 储户 时间 类别 存取数目 经办人");
while (rs.next()) {
int access_id = rs.getInt("access_id");
String access_name = rs.getString("access_name");
Date access_date = rs.getDate("access_date");
String access_class = rs.getString("access_class");
Float access_num = rs.getFloat("access_num");
String access_operator = rs.getString("access_operator");
out3.println("" + access_id + " " + access_name + " " + access_date + " "
+ access_class + " " + access_num + " " + access_operator + " ");
}
out3.println("=============================================");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
stmt = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
} catch (Exception e) {
e.printStackTrace();
}
break;
case "4":
// System.out.println("修改数据。");
// out.println("命令:"); // 服务器返回提示信息
BufferedReader in4 = null;
PrintWriter out4 = null;
try {
InputStreamReader isr4;
isr4 = new InputStreamReader(sk.getInputStream());
in4 = new BufferedReader(isr4);
out4 = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sk.getOutputStream())), true);
// 获取命令
// 例子:
String updatetInfo = in4.readLine();
// System.out.println(updatetInfo);
Connection conn = null;
PreparedStatement preStmt = null;
Statement stmt = null;
try {
// 1.注册数据库的驱动
Class.forName(driverClass);
// 2.通过Connection对象获取Statement对象
conn = DriverManager.getConnection(jdbcUrl, username, password);
// 3.创建statement类对象,用来执行SQL语句
stmt = conn.createStatement();
// 执行的SQL语句
String sql = updatetInfo;
preStmt = conn.prepareStatement(sql);
int i = stmt.executeUpdate(sql);// 执行,如果i>=1,成功,否则更新失败
if (i >= 1) {
out.println("修改成功!");
} else {
out.println("修改失败!");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (preStmt != null) {
try {
preStmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
preStmt = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
} catch (Exception e) {
e.printStackTrace();
}
break;
case "5":
// System.out.println("删除数据。");
// out.println("命令:"); // 服务器返回提示信息
BufferedReader in5 = null;
PrintWriter out5 = null;
try {
InputStreamReader isr5;
isr5 = new InputStreamReader(sk.getInputStream());
in5 = new BufferedReader(isr5);
out5 = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sk.getOutputStream())), true);
// 获取命令
// 例子:DELETE FROM access WHERE access_ '';
String delectInfo = in5.readLine();
// System.out.println(delectInfo);
Connection conn = null;
PreparedStatement preStmt = null;
Statement stmt = null;
try {
// 1.注册数据库的驱动
Class.forName(driverClass);
// 2.通过Connection对象获取Statement对象
conn = DriverManager.getConnection(jdbcUrl, username, password);
// 3.创建statement类对象,用来执行SQL语句
stmt = conn.createStatement();
// 执行的SQL语句
String sql = delectInfo;
preStmt = conn.prepareStatement(sql);
int i = stmt.executeUpdate(sql);// 执行,如果i>=1,成功,否则更新失败
if (i >= 1) {
out.println("删除成功!");
} else {
out.println("删除失败!");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (preStmt != null) {
try {
preStmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
preStmt = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
} catch (Exception e) {
e.printStackTrace();
}
break;
case "6":
out.println("再会!");
return;
// System.exit(0);
default:
out.println("请输入正确的指令!");
break;
}
// out.println(new Date().toString() + ":" + cmd); // 服务器返回时间和客户发送来的消息
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
if (sk != null) {
sk.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
} | AlbertMP/BDAWMS | src/TCP/ServerThread.java | 3,213 | // 执行,如果i>=1,成功,否则更新失败 | line_comment | zh-cn | package TCP;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Date;
import java.sql.*;
class ServerThread extends Thread {
private Socket sk;
ServerThread(Socket sk) {
this.sk = sk;
}
// 线程运行实体
public void run() {
// 连接数据库的五大参数
String driverClass = "com.mysql.jdbc.Driver";// 加载数据库驱动
String databaseName = "BMS";// 连接到哪一个数据库
String serverIp = "127.0.0.1";// 服务器IP地址
String username = "root";// 用户名
String password = "314159";// 密码
// 拼凑成一个完整的URL地址jdbcUrl
String jdbcUrl = "jdbc:mysql://" + serverIp + ":3306/" + databaseName
+ "?useUnicode=true&characterEncoding=utf-8&useSSL=false";
BufferedReader in = null;
PrintWriter out = null;
try {
InputStreamReader isr;
isr = new InputStreamReader(sk.getInputStream());
in = new BufferedReader(isr);
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sk.getOutputStream())), true);
while (true) {
// 接收来自客户端的请求,根据不同的命令返回不同的信息
String cmd = in.readLine();
System.out.println(cmd);
switch (cmd) {
case "1":
// System.out.println("插入信息。");
out.println("命令:"); // 服务器返回提示信息
BufferedReader in1 = null;
PrintWriter out1 = null;
try {
InputStreamReader isr1;
isr1 = new InputStreamReader(sk.getInputStream());
in1 = new BufferedReader(isr1);
out1 = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sk.getOutputStream())), true);
// 获取了插入命令
// 例子:INSERT INTO access VALUES('6','2019-2-14','取款','362.09','李华','赵六');
String insertInfo = in1.readLine();
System.out.println(insertInfo);
Connection conn = null;
PreparedStatement preStmt = null;
Statement stmt = null;
try {
// 1.注册数据库的驱动
Class.forName(driverClass);
// 2.通过Connection对象获取Statement对象
conn = DriverManager.getConnection(jdbcUrl, username, password);
// 3.创建statement类对象,用来执行SQL语句
stmt = conn.createStatement();
// 执行的SQL语句
String sql = insertInfo;
preStmt = conn.prepareStatement(sql);
int i = stmt.executeUpdate(sql);// 执行,如果i>=1,成功,否则更新失败
if (i >= 1) {
out.println("插入成功!");
} else {
out.println("插入失败!");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (preStmt != null) {
try {
preStmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
preStmt = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
} catch (Exception e) {
e.printStackTrace();
}
break;
case "2":
// System.out.println("查询个人。");
// out.println("姓名:"); // 服务器返回提示信息
BufferedReader in2 = null;
PrintWriter out2 = null;
try {
InputStreamReader isr2;
isr2 = new InputStreamReader(sk.getInputStream());
in2 = new BufferedReader(isr2);
out2 = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sk.getOutputStream())), true);
String searchSql = in2.readLine();
// System.out.println(searchName);
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
Class.forName(driverClass);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
conn = DriverManager.getConnection(jdbcUrl, username, password);
String sql = searchSql;
stmt = conn.prepareStatement(sql);
rs = stmt.executeQuery();
out2.println("=============================================");
out.println("个人存取款信息列表");
out.println("编号 储户 时间 类别 存取数目 经办人");
while (rs.next()) {
int access_id = rs.getInt("access_id");
String access_name = rs.getString("access_name");
Date access_date = rs.getDate("access_date");
String access_class = rs.getString("access_class");
Float access_num = rs.getFloat("access_num");
String access_operator = rs.getString("access_operator");
out.println("" + access_id + " " + access_name + " " + access_date + " "
+ access_class + " " + access_num + " " + access_operator + " ");
}
out2.println("=============================================");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
break;
case "3":
// System.out.println("查询总表。");
BufferedReader in3 = null;
PrintWriter out3 = null;
try {
InputStreamReader isr3;
isr3 = new InputStreamReader(sk.getInputStream());
out3 = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sk.getOutputStream())), true);
Statement stmt = null;
ResultSet rs = null;
Connection conn = null;
try {
// 1.注册数据库的驱动
Class.forName(driverClass);
// 2.通过Connection对象获取Statement对象
conn = DriverManager.getConnection(jdbcUrl, username, password);
stmt = conn.createStatement();
String sql = "select * from access";
rs = stmt.executeQuery(sql);
out3.println("=============================================");
out3.println("总表:");
out3.println("编号 储户 时间 类别 存取数目 经办人");
while (rs.next()) {
int access_id = rs.getInt("access_id");
String access_name = rs.getString("access_name");
Date access_date = rs.getDate("access_date");
String access_class = rs.getString("access_class");
Float access_num = rs.getFloat("access_num");
String access_operator = rs.getString("access_operator");
out3.println("" + access_id + " " + access_name + " " + access_date + " "
+ access_class + " " + access_num + " " + access_operator + " ");
}
out3.println("=============================================");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
stmt = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
} catch (Exception e) {
e.printStackTrace();
}
break;
case "4":
// System.out.println("修改数据。");
// out.println("命令:"); // 服务器返回提示信息
BufferedReader in4 = null;
PrintWriter out4 = null;
try {
InputStreamReader isr4;
isr4 = new InputStreamReader(sk.getInputStream());
in4 = new BufferedReader(isr4);
out4 = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sk.getOutputStream())), true);
// 获取命令
// 例子:
String updatetInfo = in4.readLine();
// System.out.println(updatetInfo);
Connection conn = null;
PreparedStatement preStmt = null;
Statement stmt = null;
try {
// 1.注册数据库的驱动
Class.forName(driverClass);
// 2.通过Connection对象获取Statement对象
conn = DriverManager.getConnection(jdbcUrl, username, password);
// 3.创建statement类对象,用来执行SQL语句
stmt = conn.createStatement();
// 执行的SQL语句
String sql = updatetInfo;
preStmt = conn.prepareStatement(sql);
int i = stmt.executeUpdate(sql);// 执行,如果i>=1,成功,否则更新失败
if (i >= 1) {
out.println("修改成功!");
} else {
out.println("修改失败!");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (preStmt != null) {
try {
preStmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
preStmt = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
} catch (Exception e) {
e.printStackTrace();
}
break;
case "5":
// System.out.println("删除数据。");
// out.println("命令:"); // 服务器返回提示信息
BufferedReader in5 = null;
PrintWriter out5 = null;
try {
InputStreamReader isr5;
isr5 = new InputStreamReader(sk.getInputStream());
in5 = new BufferedReader(isr5);
out5 = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sk.getOutputStream())), true);
// 获取命令
// 例子:DELETE FROM access WHERE access_ '';
String delectInfo = in5.readLine();
// System.out.println(delectInfo);
Connection conn = null;
PreparedStatement preStmt = null;
Statement stmt = null;
try {
// 1.注册数据库的驱动
Class.forName(driverClass);
// 2.通过Connection对象获取Statement对象
conn = DriverManager.getConnection(jdbcUrl, username, password);
// 3.创建statement类对象,用来执行SQL语句
stmt = conn.createStatement();
// 执行的SQL语句
String sql = delectInfo;
preStmt = conn.prepareStatement(sql);
int i = stmt.executeUpdate(sql);// 执行 <SUF>
if (i >= 1) {
out.println("删除成功!");
} else {
out.println("删除失败!");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (preStmt != null) {
try {
preStmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
preStmt = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
} catch (Exception e) {
e.printStackTrace();
}
break;
case "6":
out.println("再会!");
return;
// System.exit(0);
default:
out.println("请输入正确的指令!");
break;
}
// out.println(new Date().toString() + ":" + cmd); // 服务器返回时间和客户发送来的消息
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
if (sk != null) {
sk.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
} | false |
51770_57 | package algs.binary.search.tree.balance.advance;
import algs.util.Queue;
import java.util.NoSuchElementException;
import java.util.Scanner;
/**
* https://panjunwen.com/red-black-tree-deletion/#
* https://www.jianshu.com/p/48331a5a11f4
* 红黑二叉查找树完整实现
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
@SuppressWarnings("ALL")
public class RedBlackBST<Key extends Comparable<Key>, Value> {
private static final boolean RED = true;
private static final boolean BLACK = false;
private Node root; // root of the BST
// BST helper node data type
private class Node {
private Key key; // key
private Value val; // associated data
private Node left, right; // links to left and right subtrees
private boolean color; // color of parent link
private int size; // subtree count
Node(Key key, Value val, boolean color, int size) {
this.key = key;
this.val = val;
this.color = color;
this.size = size;
}
}
/**
* Initializes an empty symbol table.
*/
public RedBlackBST() {
}
/***************************************************************************
* Node helper methods.
***************************************************************************/
// is node x red; false if x is null ?
private boolean isRed(Node x) {
if (x == null) return false;
return x.color == RED;
}
// number of node in subtree rooted at x; 0 if x is null
private int size(Node x) {
if (x == null) return 0;
return x.size;
}
/**
* Returns the number of key-value pairs in this symbol table.
*
* @return the number of key-value pairs in this symbol table
*/
public int size() {
return size(root);
}
/**
* Is this symbol table empty?
*
* @return {@code true} if this symbol table is empty and {@code false} otherwise
*/
public boolean isEmpty() {
return root == null;
}
/***************************************************************************
* Standard BST search.
***************************************************************************/
/**
* Returns the value associated with the given key.
*
* @param key the key
* @return the value associated with the given key if the key is in the symbol table
* and {@code null} if the key is not in the symbol table
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public Value get(Key key) {
if (key == null) throw new IllegalArgumentException("argument to get() is null");
return get(root, key);
}
// value associated with the given key in subtree rooted at x; null if no such key
private Value get(Node x, Key key) {
while (x != null) {
int cmp = key.compareTo(x.key);
if (cmp < 0) x = x.left;
else if (cmp > 0) x = x.right;
else return x.val;
}
return null;
}
/**
* Does this symbol table contain the given key?
*
* @param key the key
* @return {@code true} if this symbol table contains {@code key} and
* {@code false} otherwise
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public boolean contains(Key key) {
return get(key) != null;
}
/***************************************************************************
* Red-black tree insertion.
***************************************************************************/
/**
* Inserts the specified key-value pair into the symbol table, overwriting the old
* value with the new value if the symbol table already contains the specified key.
* Deletes the specified key (and its associated value) from this symbol table
* if the specified value is {@code null}.
*
* @param key the key
* @param val the value
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public void put(Key key, Value val) {
if (key == null) throw new IllegalArgumentException("first argument to put() is null");
if (val == null) {
delete(key);
return;
}
root = put(root, key, val);
root.color = BLACK;
// assert check();
}
// insert the key-value pair in the subtree rooted at h
private Node put(Node h, Key key, Value val) {
if (h == null) return new Node(key, val, RED, 1);
int cmp = key.compareTo(h.key);
if (cmp < 0) h.left = put(h.left, key, val);
else if (cmp > 0) h.right = put(h.right, key, val);
else h.val = val;
// fix-up any right-leaning links
if (isRed(h.right) && !isRed(h.left)) h = rotateLeft(h);
if (isRed(h.left) && isRed(h.left.left)) h = rotateRight(h);
if (isRed(h.left) && isRed(h.right)) flipColors(h);
h.size = size(h.left) + size(h.right) + 1;
return h;
}
/***************************************************************************
* Red-black tree deletion.
***************************************************************************/
/**
* Removes the smallest key and associated value from the symbol table.
*
* @throws NoSuchElementException if the symbol table is empty
*/
public void deleteMin() {
if (isEmpty()) throw new NoSuchElementException("BST underflow");
/*
* if both children of root are black, set root to red
* 若果当前节点的两个子节点都是2-节点
* 对于根节点需要留意下,在实际红黑树操作中如果根节点的左右结点都是黑链接,
* 我们把指向根节点的链接『假装』成红色,也就是假装根节点的键在3-结点中。
*/
if (!isRed(root.left) && !isRed(root.right))
root.color = RED;
root = deleteMin(root);
//红黑树的根节点不允许是3-节点
if (!isEmpty()) root.color = BLACK;
// assert check();
}
// delete the key-value pair with the minimum key rooted at h
private Node deleteMin(Node h) {
//这里不同于普通二叉搜索树中的return h.right,因为当红黑树的左子节点为空时,右子节点必然为空
if (h.left == null)
return null;//在普通二叉搜索树的delMin方法中,这里为return h.right
//如果当前结点是2-结点,并且它的左孩子也是2-结点,需要调整(这里不要判断右孩子的原因是,红黑二叉树已经保证右孩子是2-节点)
if (!isRed(h.left) && !isRed(h.left.left))
h = moveRedLeft(h);
h.left = deleteMin(h.left);
return balance(h);
}
/**
* Removes the largest key and associated value from the symbol table.
*
* @throws NoSuchElementException if the symbol table is empty
*/
public void deleteMax() {
if (isEmpty()) throw new NoSuchElementException("BST underflow");
// if both children of root are black, set root to red
if (!isRed(root.left) && !isRed(root.right))
root.color = RED;
root = deleteMax(root);
if (!isEmpty()) root.color = BLACK;
// assert check();
}
// delete the key-value pair with the maximum key rooted at h
private Node deleteMax(Node h) {
if (isRed(h.left))
h = rotateRight(h);
if (h.right == null)
return null;
if (!isRed(h.right) && !isRed(h.right.left))
h = moveRedRight(h);
h.right = deleteMax(h.right);
return balance(h);
}
/**
* Removes the specified key and its associated value from this symbol table
* (if the key is in this symbol table).
*
* @param key the key
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public void delete(Key key) {
if (key == null) throw new IllegalArgumentException("argument to delete() is null");
if (!contains(key)) return;
// if both children of root are black, set root to red
if (!isRed(root.left) && !isRed(root.right))
root.color = RED;
root = delete(root, key);
if (!isEmpty()) root.color = BLACK;
// assert check();
}
// delete the key-value pair with the given key rooted at h
private Node delete(Node h, Key key) {
// assert get(h, key) != null;
if (key.compareTo(h.key) < 0) {
if (!isRed(h.left) && !isRed(h.left.left))
h = moveRedLeft(h);
h.left = delete(h.left, key);
} else {
if (isRed(h.left))
h = rotateRight(h);
if (key.compareTo(h.key) == 0 && (h.right == null))
return null;
if (!isRed(h.right) && !isRed(h.right.left))
h = moveRedRight(h);
if (key.compareTo(h.key) == 0) {
Node x = min(h.right);
h.key = x.key;
h.val = x.val;
// h.val = get(h.right, min(h.right).key);
// h.key = min(h.right).key;
h.right = deleteMin(h.right);
} else h.right = delete(h.right, key);
}
return balance(h);
}
/***************************************************************************
* Red-black tree helper functions.
***************************************************************************/
// make a left-leaning link lean to the right
private Node rotateRight(Node h) {
// assert (h != null) && isRed(h.left);
Node x = h.left;
h.left = x.right;
x.right = h;
x.color = x.right.color;
x.right.color = RED;
x.size = h.size;
h.size = size(h.left) + size(h.right) + 1;
return x;
}
// make a right-leaning link lean to the left
private Node rotateLeft(Node h) {
// assert (h != null) && isRed(h.right);
Node x = h.right;
h.right = x.left;
x.left = h;
x.color = x.left.color;
x.left.color = RED;
x.size = h.size;
h.size = size(h.left) + size(h.right) + 1;
return x;
}
// flip the colors of a node and its two children
private void flipColors(Node h) {
// h must have opposite color of its two children
// assert (h != null) && (h.left != null) && (h.right != null);
// assert (!isRed(h) && isRed(h.left) && isRed(h.right))
// || (isRed(h) && !isRed(h.left) && !isRed(h.right));
h.color = !h.color;
h.left.color = !h.left.color;
h.right.color = !h.right.color;
}
// Assuming that h is red and both h.left and h.left.left
// are black, make h.left or one of its children red.
private Node moveRedLeft(Node h) {
// assert (h != null);
// assert isRed(h) && !isRed(h.left) && !isRed(h.left.left);
//融合当前结点,左孩子,右孩子为新的4-结点
flipColors(h);
//如果右孩子是3-结点,这个时候需要上述的借键给左孩子
if (isRed(h.right.left)) {
h.right = rotateRight(h.right);
h = rotateLeft(h);
flipColors(h);
}
return h;
}
// Assuming that h is red and both h.right and h.right.left
// are black, make h.right or one of its children red.
private Node moveRedRight(Node h) {
// assert (h != null);
// assert isRed(h) && !isRed(h.right) && !isRed(h.right.left);
flipColors(h);
if (isRed(h.left.left)) {
h = rotateRight(h);
flipColors(h);
}
return h;
}
// restore red-black tree invariant
private Node balance(Node h) {
// assert (h != null);
//右斜红链接调整
if (isRed(h.right)) h = rotateLeft(h);
//连续的红链接调整
if (isRed(h.left) && isRed(h.left.left)) h = rotateRight(h);
//4-结点调整
if (isRed(h.left) && isRed(h.right)) flipColors(h);
h.size = size(h.left) + size(h.right) + 1;
return h;
}
/***************************************************************************
* Utility functions.
***************************************************************************/
/**
* Returns the height of the BST (for debugging).
*
* @return the height of the BST (a 1-node tree has height 0)
*/
public int height() {
return height(root);
}
private int height(Node x) {
if (x == null) return -1;
return 1 + Math.max(height(x.left), height(x.right));
}
/***************************************************************************
* Ordered symbol table methods.
***************************************************************************/
/**
* Returns the smallest key in the symbol table.
*
* @return the smallest key in the symbol table
* @throws NoSuchElementException if the symbol table is empty
*/
public Key min() {
if (isEmpty()) throw new NoSuchElementException("called min() with empty symbol table");
return min(root).key;
}
// the smallest key in subtree rooted at x; null if no such key
private Node min(Node x) {
// assert x != null;
if (x.left == null) return x;
else return min(x.left);
}
/**
* Returns the largest key in the symbol table.
*
* @return the largest key in the symbol table
* @throws NoSuchElementException if the symbol table is empty
*/
public Key max() {
if (isEmpty()) throw new NoSuchElementException("called max() with empty symbol table");
return max(root).key;
}
// the largest key in the subtree rooted at x; null if no such key
private Node max(Node x) {
// assert x != null;
if (x.right == null) return x;
else return max(x.right);
}
/**
* Returns the largest key in the symbol table less than or equal to {@code key}.
*
* @param key the key
* @return the largest key in the symbol table less than or equal to {@code key}
* @throws NoSuchElementException if there is no such key
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public Key floor(Key key) {
if (key == null) throw new IllegalArgumentException("argument to floor() is null");
if (isEmpty()) throw new NoSuchElementException("called floor() with empty symbol table");
Node x = floor(root, key);
if (x == null) return null;
else return x.key;
}
// the largest key in the subtree rooted at x less than or equal to the given key
private Node floor(Node x, Key key) {
if (x == null) return null;
int cmp = key.compareTo(x.key);
if (cmp == 0) return x;
if (cmp < 0) return floor(x.left, key);
Node t = floor(x.right, key);
if (t != null) return t;
else return x;
}
/**
* Returns the smallest key in the symbol table greater than or equal to {@code key}.
*
* @param key the key
* @return the smallest key in the symbol table greater than or equal to {@code key}
* @throws NoSuchElementException if there is no such key
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public Key ceiling(Key key) {
if (key == null) throw new IllegalArgumentException("argument to ceiling() is null");
if (isEmpty()) throw new NoSuchElementException("called ceiling() with empty symbol table");
Node x = ceiling(root, key);
if (x == null) return null;
else return x.key;
}
// the smallest key in the subtree rooted at x greater than or equal to the given key
private Node ceiling(Node x, Key key) {
if (x == null) return null;
int cmp = key.compareTo(x.key);
if (cmp == 0) return x;
if (cmp > 0) return ceiling(x.right, key);
Node t = ceiling(x.left, key);
if (t != null) return t;
else return x;
}
/**
* Return the kth smallest key in the symbol table.
*
* @param k the order statistic
* @return the {@code k}th smallest key in the symbol table
* @throws IllegalArgumentException unless {@code k} is between 0 and
* <em>n</em>–1
*/
public Key select(int k) {
if (k < 0 || k >= size()) {
throw new IllegalArgumentException("called select() with invalid argument: " + k);
}
Node x = select(root, k);
return x.key;
}
// the key of rank k in the subtree rooted at x
private Node select(Node x, int k) {
// assert x != null;
// assert k >= 0 && k < size(x);
int t = size(x.left);
if (t > k) return select(x.left, k);
else if (t < k) return select(x.right, k - t - 1);
else return x;
}
/**
* Return the number of keys in the symbol table strictly less than {@code key}.
*
* @param key the key
* @return the number of keys in the symbol table strictly less than {@code key}
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public int rank(Key key) {
if (key == null) throw new IllegalArgumentException("argument to rank() is null");
return rank(key, root);
}
// number of keys less than key in the subtree rooted at x
private int rank(Key key, Node x) {
if (x == null) return 0;
int cmp = key.compareTo(x.key);
if (cmp < 0) return rank(key, x.left);
else if (cmp > 0) return 1 + size(x.left) + rank(key, x.right);
else return size(x.left);
}
/***************************************************************************
* Range count and range search.
***************************************************************************/
/**
* Returns all keys in the symbol table as an {@code Iterable}.
* To iterate over all of the keys in the symbol table named {@code st},
* use the foreach notation: {@code for (Key key : st.keys())}.
*
* @return all keys in the symbol table as an {@code Iterable}
*/
public Iterable<Key> keys() {
if (isEmpty()) return new Queue<Key>();
return keys(min(), max());
}
/**
* Returns all keys in the symbol table in the given range,
* as an {@code Iterable}.
*
* @param lo minimum endpoint
* @param hi maximum endpoint
* @return all keys in the sybol table between {@code lo}
* (inclusive) and {@code hi} (inclusive) as an {@code Iterable}
* @throws IllegalArgumentException if either {@code lo} or {@code hi}
* is {@code null}
*/
public Iterable<Key> keys(Key lo, Key hi) {
if (lo == null) throw new IllegalArgumentException("first argument to keys() is null");
if (hi == null) throw new IllegalArgumentException("second argument to keys() is null");
Queue<Key> queue = new Queue<Key>();
// if (isEmpty() || lo.compareTo(hi) > 0) return queue;
keys(root, queue, lo, hi);
return queue;
}
// add the keys between lo and hi in the subtree rooted at x
// to the queue
private void keys(Node x, Queue<Key> queue, Key lo, Key hi) {
if (x == null) return;
int cmplo = lo.compareTo(x.key);
int cmphi = hi.compareTo(x.key);
if (cmplo < 0) keys(x.left, queue, lo, hi);
if (cmplo <= 0 && cmphi >= 0) queue.enqueue(x.key);
if (cmphi > 0) keys(x.right, queue, lo, hi);
}
/**
* Returns the number of keys in the symbol table in the given range.
*
* @param lo minimum endpoint
* @param hi maximum endpoint
* @return the number of keys in the sybol table between {@code lo}
* (inclusive) and {@code hi} (inclusive)
* @throws IllegalArgumentException if either {@code lo} or {@code hi}
* is {@code null}
*/
public int size(Key lo, Key hi) {
if (lo == null) throw new IllegalArgumentException("first argument to size() is null");
if (hi == null) throw new IllegalArgumentException("second argument to size() is null");
if (lo.compareTo(hi) > 0) return 0;
if (contains(hi)) return rank(hi) - rank(lo) + 1;
else return rank(hi) - rank(lo);
}
/***************************************************************************
* Check integrity of red-black tree data structure.
***************************************************************************/
private boolean check() {
if (!isBST()) System.out.println("Not in symmetric order");
if (!isSizeConsistent()) System.out.println("Subtree counts not consistent");
if (!isRankConsistent()) System.out.println("Ranks not consistent");
if (!is23()) System.out.println("Not a 2-3 tree");
if (!isBalanced()) System.out.println("Not balanced");
return isBST() && isSizeConsistent() && isRankConsistent() && is23() && isBalanced();
}
// does this binary tree satisfy symmetric order?
// Note: this test also ensures that data structure is a binary tree since order is strict
private boolean isBST() {
return isBST(root, null, null);
}
// is the tree rooted at x a BST with all keys strictly between min and max
// (if min or max is null, treat as empty constraint)
// Credit: Bob Dondero's elegant solution
private boolean isBST(Node x, Key min, Key max) {
if (x == null) return true;
if (min != null && x.key.compareTo(min) <= 0) return false;
if (max != null && x.key.compareTo(max) >= 0) return false;
return isBST(x.left, min, x.key) && isBST(x.right, x.key, max);
}
// are the size fields correct?
private boolean isSizeConsistent() {
return isSizeConsistent(root);
}
private boolean isSizeConsistent(Node x) {
if (x == null) return true;
if (x.size != size(x.left) + size(x.right) + 1) return false;
return isSizeConsistent(x.left) && isSizeConsistent(x.right);
}
// check that ranks are consistent
private boolean isRankConsistent() {
for (int i = 0; i < size(); i++)
if (i != rank(select(i))) return false;
for (Key key : keys())
if (key.compareTo(select(rank(key))) != 0) return false;
return true;
}
// Does the tree have no red right links, and at most one (left)
// red links in a row on any path?
private boolean is23() {
return is23(root);
}
private boolean is23(Node x) {
if (x == null) return true;
if (isRed(x.right)) return false;
if (x != root && isRed(x) && isRed(x.left))
return false;
return is23(x.left) && is23(x.right);
}
// do all paths from root to leaf have same number of black edges?
private boolean isBalanced() {
int black = 0; // number of black links on path from root to min
Node x = root;
while (x != null) {
if (!isRed(x)) black++;
x = x.left;
}
return isBalanced(root, black);
}
// does every path from the root to a leaf have the given number of black links?
private boolean isBalanced(Node x, int black) {
if (x == null) return black == 0;
if (!isRed(x)) black--;
return isBalanced(x.left, black) && isBalanced(x.right, black);
}
/**
* Unit tests the {@code RedBlackBST} data type.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
RedBlackBST<String, Integer> st = new RedBlackBST<String, Integer>();
Scanner scanner = new Scanner(System.in);
for (int i = 0; scanner.hasNext(); i++) {
String key = scanner.next();
st.put(key, i);
}
for (String s : st.keys())
System.out.println(s + " " + st.get(s));
System.out.println();
}
} | AlbertRui/Algorithm | search/src/algs/binary/search/tree/balance/advance/RedBlackBST.java | 6,181 | //融合当前结点,左孩子,右孩子为新的4-结点 | line_comment | zh-cn | package algs.binary.search.tree.balance.advance;
import algs.util.Queue;
import java.util.NoSuchElementException;
import java.util.Scanner;
/**
* https://panjunwen.com/red-black-tree-deletion/#
* https://www.jianshu.com/p/48331a5a11f4
* 红黑二叉查找树完整实现
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
@SuppressWarnings("ALL")
public class RedBlackBST<Key extends Comparable<Key>, Value> {
private static final boolean RED = true;
private static final boolean BLACK = false;
private Node root; // root of the BST
// BST helper node data type
private class Node {
private Key key; // key
private Value val; // associated data
private Node left, right; // links to left and right subtrees
private boolean color; // color of parent link
private int size; // subtree count
Node(Key key, Value val, boolean color, int size) {
this.key = key;
this.val = val;
this.color = color;
this.size = size;
}
}
/**
* Initializes an empty symbol table.
*/
public RedBlackBST() {
}
/***************************************************************************
* Node helper methods.
***************************************************************************/
// is node x red; false if x is null ?
private boolean isRed(Node x) {
if (x == null) return false;
return x.color == RED;
}
// number of node in subtree rooted at x; 0 if x is null
private int size(Node x) {
if (x == null) return 0;
return x.size;
}
/**
* Returns the number of key-value pairs in this symbol table.
*
* @return the number of key-value pairs in this symbol table
*/
public int size() {
return size(root);
}
/**
* Is this symbol table empty?
*
* @return {@code true} if this symbol table is empty and {@code false} otherwise
*/
public boolean isEmpty() {
return root == null;
}
/***************************************************************************
* Standard BST search.
***************************************************************************/
/**
* Returns the value associated with the given key.
*
* @param key the key
* @return the value associated with the given key if the key is in the symbol table
* and {@code null} if the key is not in the symbol table
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public Value get(Key key) {
if (key == null) throw new IllegalArgumentException("argument to get() is null");
return get(root, key);
}
// value associated with the given key in subtree rooted at x; null if no such key
private Value get(Node x, Key key) {
while (x != null) {
int cmp = key.compareTo(x.key);
if (cmp < 0) x = x.left;
else if (cmp > 0) x = x.right;
else return x.val;
}
return null;
}
/**
* Does this symbol table contain the given key?
*
* @param key the key
* @return {@code true} if this symbol table contains {@code key} and
* {@code false} otherwise
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public boolean contains(Key key) {
return get(key) != null;
}
/***************************************************************************
* Red-black tree insertion.
***************************************************************************/
/**
* Inserts the specified key-value pair into the symbol table, overwriting the old
* value with the new value if the symbol table already contains the specified key.
* Deletes the specified key (and its associated value) from this symbol table
* if the specified value is {@code null}.
*
* @param key the key
* @param val the value
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public void put(Key key, Value val) {
if (key == null) throw new IllegalArgumentException("first argument to put() is null");
if (val == null) {
delete(key);
return;
}
root = put(root, key, val);
root.color = BLACK;
// assert check();
}
// insert the key-value pair in the subtree rooted at h
private Node put(Node h, Key key, Value val) {
if (h == null) return new Node(key, val, RED, 1);
int cmp = key.compareTo(h.key);
if (cmp < 0) h.left = put(h.left, key, val);
else if (cmp > 0) h.right = put(h.right, key, val);
else h.val = val;
// fix-up any right-leaning links
if (isRed(h.right) && !isRed(h.left)) h = rotateLeft(h);
if (isRed(h.left) && isRed(h.left.left)) h = rotateRight(h);
if (isRed(h.left) && isRed(h.right)) flipColors(h);
h.size = size(h.left) + size(h.right) + 1;
return h;
}
/***************************************************************************
* Red-black tree deletion.
***************************************************************************/
/**
* Removes the smallest key and associated value from the symbol table.
*
* @throws NoSuchElementException if the symbol table is empty
*/
public void deleteMin() {
if (isEmpty()) throw new NoSuchElementException("BST underflow");
/*
* if both children of root are black, set root to red
* 若果当前节点的两个子节点都是2-节点
* 对于根节点需要留意下,在实际红黑树操作中如果根节点的左右结点都是黑链接,
* 我们把指向根节点的链接『假装』成红色,也就是假装根节点的键在3-结点中。
*/
if (!isRed(root.left) && !isRed(root.right))
root.color = RED;
root = deleteMin(root);
//红黑树的根节点不允许是3-节点
if (!isEmpty()) root.color = BLACK;
// assert check();
}
// delete the key-value pair with the minimum key rooted at h
private Node deleteMin(Node h) {
//这里不同于普通二叉搜索树中的return h.right,因为当红黑树的左子节点为空时,右子节点必然为空
if (h.left == null)
return null;//在普通二叉搜索树的delMin方法中,这里为return h.right
//如果当前结点是2-结点,并且它的左孩子也是2-结点,需要调整(这里不要判断右孩子的原因是,红黑二叉树已经保证右孩子是2-节点)
if (!isRed(h.left) && !isRed(h.left.left))
h = moveRedLeft(h);
h.left = deleteMin(h.left);
return balance(h);
}
/**
* Removes the largest key and associated value from the symbol table.
*
* @throws NoSuchElementException if the symbol table is empty
*/
public void deleteMax() {
if (isEmpty()) throw new NoSuchElementException("BST underflow");
// if both children of root are black, set root to red
if (!isRed(root.left) && !isRed(root.right))
root.color = RED;
root = deleteMax(root);
if (!isEmpty()) root.color = BLACK;
// assert check();
}
// delete the key-value pair with the maximum key rooted at h
private Node deleteMax(Node h) {
if (isRed(h.left))
h = rotateRight(h);
if (h.right == null)
return null;
if (!isRed(h.right) && !isRed(h.right.left))
h = moveRedRight(h);
h.right = deleteMax(h.right);
return balance(h);
}
/**
* Removes the specified key and its associated value from this symbol table
* (if the key is in this symbol table).
*
* @param key the key
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public void delete(Key key) {
if (key == null) throw new IllegalArgumentException("argument to delete() is null");
if (!contains(key)) return;
// if both children of root are black, set root to red
if (!isRed(root.left) && !isRed(root.right))
root.color = RED;
root = delete(root, key);
if (!isEmpty()) root.color = BLACK;
// assert check();
}
// delete the key-value pair with the given key rooted at h
private Node delete(Node h, Key key) {
// assert get(h, key) != null;
if (key.compareTo(h.key) < 0) {
if (!isRed(h.left) && !isRed(h.left.left))
h = moveRedLeft(h);
h.left = delete(h.left, key);
} else {
if (isRed(h.left))
h = rotateRight(h);
if (key.compareTo(h.key) == 0 && (h.right == null))
return null;
if (!isRed(h.right) && !isRed(h.right.left))
h = moveRedRight(h);
if (key.compareTo(h.key) == 0) {
Node x = min(h.right);
h.key = x.key;
h.val = x.val;
// h.val = get(h.right, min(h.right).key);
// h.key = min(h.right).key;
h.right = deleteMin(h.right);
} else h.right = delete(h.right, key);
}
return balance(h);
}
/***************************************************************************
* Red-black tree helper functions.
***************************************************************************/
// make a left-leaning link lean to the right
private Node rotateRight(Node h) {
// assert (h != null) && isRed(h.left);
Node x = h.left;
h.left = x.right;
x.right = h;
x.color = x.right.color;
x.right.color = RED;
x.size = h.size;
h.size = size(h.left) + size(h.right) + 1;
return x;
}
// make a right-leaning link lean to the left
private Node rotateLeft(Node h) {
// assert (h != null) && isRed(h.right);
Node x = h.right;
h.right = x.left;
x.left = h;
x.color = x.left.color;
x.left.color = RED;
x.size = h.size;
h.size = size(h.left) + size(h.right) + 1;
return x;
}
// flip the colors of a node and its two children
private void flipColors(Node h) {
// h must have opposite color of its two children
// assert (h != null) && (h.left != null) && (h.right != null);
// assert (!isRed(h) && isRed(h.left) && isRed(h.right))
// || (isRed(h) && !isRed(h.left) && !isRed(h.right));
h.color = !h.color;
h.left.color = !h.left.color;
h.right.color = !h.right.color;
}
// Assuming that h is red and both h.left and h.left.left
// are black, make h.left or one of its children red.
private Node moveRedLeft(Node h) {
// assert (h != null);
// assert isRed(h) && !isRed(h.left) && !isRed(h.left.left);
//融合 <SUF>
flipColors(h);
//如果右孩子是3-结点,这个时候需要上述的借键给左孩子
if (isRed(h.right.left)) {
h.right = rotateRight(h.right);
h = rotateLeft(h);
flipColors(h);
}
return h;
}
// Assuming that h is red and both h.right and h.right.left
// are black, make h.right or one of its children red.
private Node moveRedRight(Node h) {
// assert (h != null);
// assert isRed(h) && !isRed(h.right) && !isRed(h.right.left);
flipColors(h);
if (isRed(h.left.left)) {
h = rotateRight(h);
flipColors(h);
}
return h;
}
// restore red-black tree invariant
private Node balance(Node h) {
// assert (h != null);
//右斜红链接调整
if (isRed(h.right)) h = rotateLeft(h);
//连续的红链接调整
if (isRed(h.left) && isRed(h.left.left)) h = rotateRight(h);
//4-结点调整
if (isRed(h.left) && isRed(h.right)) flipColors(h);
h.size = size(h.left) + size(h.right) + 1;
return h;
}
/***************************************************************************
* Utility functions.
***************************************************************************/
/**
* Returns the height of the BST (for debugging).
*
* @return the height of the BST (a 1-node tree has height 0)
*/
public int height() {
return height(root);
}
private int height(Node x) {
if (x == null) return -1;
return 1 + Math.max(height(x.left), height(x.right));
}
/***************************************************************************
* Ordered symbol table methods.
***************************************************************************/
/**
* Returns the smallest key in the symbol table.
*
* @return the smallest key in the symbol table
* @throws NoSuchElementException if the symbol table is empty
*/
public Key min() {
if (isEmpty()) throw new NoSuchElementException("called min() with empty symbol table");
return min(root).key;
}
// the smallest key in subtree rooted at x; null if no such key
private Node min(Node x) {
// assert x != null;
if (x.left == null) return x;
else return min(x.left);
}
/**
* Returns the largest key in the symbol table.
*
* @return the largest key in the symbol table
* @throws NoSuchElementException if the symbol table is empty
*/
public Key max() {
if (isEmpty()) throw new NoSuchElementException("called max() with empty symbol table");
return max(root).key;
}
// the largest key in the subtree rooted at x; null if no such key
private Node max(Node x) {
// assert x != null;
if (x.right == null) return x;
else return max(x.right);
}
/**
* Returns the largest key in the symbol table less than or equal to {@code key}.
*
* @param key the key
* @return the largest key in the symbol table less than or equal to {@code key}
* @throws NoSuchElementException if there is no such key
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public Key floor(Key key) {
if (key == null) throw new IllegalArgumentException("argument to floor() is null");
if (isEmpty()) throw new NoSuchElementException("called floor() with empty symbol table");
Node x = floor(root, key);
if (x == null) return null;
else return x.key;
}
// the largest key in the subtree rooted at x less than or equal to the given key
private Node floor(Node x, Key key) {
if (x == null) return null;
int cmp = key.compareTo(x.key);
if (cmp == 0) return x;
if (cmp < 0) return floor(x.left, key);
Node t = floor(x.right, key);
if (t != null) return t;
else return x;
}
/**
* Returns the smallest key in the symbol table greater than or equal to {@code key}.
*
* @param key the key
* @return the smallest key in the symbol table greater than or equal to {@code key}
* @throws NoSuchElementException if there is no such key
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public Key ceiling(Key key) {
if (key == null) throw new IllegalArgumentException("argument to ceiling() is null");
if (isEmpty()) throw new NoSuchElementException("called ceiling() with empty symbol table");
Node x = ceiling(root, key);
if (x == null) return null;
else return x.key;
}
// the smallest key in the subtree rooted at x greater than or equal to the given key
private Node ceiling(Node x, Key key) {
if (x == null) return null;
int cmp = key.compareTo(x.key);
if (cmp == 0) return x;
if (cmp > 0) return ceiling(x.right, key);
Node t = ceiling(x.left, key);
if (t != null) return t;
else return x;
}
/**
* Return the kth smallest key in the symbol table.
*
* @param k the order statistic
* @return the {@code k}th smallest key in the symbol table
* @throws IllegalArgumentException unless {@code k} is between 0 and
* <em>n</em>–1
*/
public Key select(int k) {
if (k < 0 || k >= size()) {
throw new IllegalArgumentException("called select() with invalid argument: " + k);
}
Node x = select(root, k);
return x.key;
}
// the key of rank k in the subtree rooted at x
private Node select(Node x, int k) {
// assert x != null;
// assert k >= 0 && k < size(x);
int t = size(x.left);
if (t > k) return select(x.left, k);
else if (t < k) return select(x.right, k - t - 1);
else return x;
}
/**
* Return the number of keys in the symbol table strictly less than {@code key}.
*
* @param key the key
* @return the number of keys in the symbol table strictly less than {@code key}
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public int rank(Key key) {
if (key == null) throw new IllegalArgumentException("argument to rank() is null");
return rank(key, root);
}
// number of keys less than key in the subtree rooted at x
private int rank(Key key, Node x) {
if (x == null) return 0;
int cmp = key.compareTo(x.key);
if (cmp < 0) return rank(key, x.left);
else if (cmp > 0) return 1 + size(x.left) + rank(key, x.right);
else return size(x.left);
}
/***************************************************************************
* Range count and range search.
***************************************************************************/
/**
* Returns all keys in the symbol table as an {@code Iterable}.
* To iterate over all of the keys in the symbol table named {@code st},
* use the foreach notation: {@code for (Key key : st.keys())}.
*
* @return all keys in the symbol table as an {@code Iterable}
*/
public Iterable<Key> keys() {
if (isEmpty()) return new Queue<Key>();
return keys(min(), max());
}
/**
* Returns all keys in the symbol table in the given range,
* as an {@code Iterable}.
*
* @param lo minimum endpoint
* @param hi maximum endpoint
* @return all keys in the sybol table between {@code lo}
* (inclusive) and {@code hi} (inclusive) as an {@code Iterable}
* @throws IllegalArgumentException if either {@code lo} or {@code hi}
* is {@code null}
*/
public Iterable<Key> keys(Key lo, Key hi) {
if (lo == null) throw new IllegalArgumentException("first argument to keys() is null");
if (hi == null) throw new IllegalArgumentException("second argument to keys() is null");
Queue<Key> queue = new Queue<Key>();
// if (isEmpty() || lo.compareTo(hi) > 0) return queue;
keys(root, queue, lo, hi);
return queue;
}
// add the keys between lo and hi in the subtree rooted at x
// to the queue
private void keys(Node x, Queue<Key> queue, Key lo, Key hi) {
if (x == null) return;
int cmplo = lo.compareTo(x.key);
int cmphi = hi.compareTo(x.key);
if (cmplo < 0) keys(x.left, queue, lo, hi);
if (cmplo <= 0 && cmphi >= 0) queue.enqueue(x.key);
if (cmphi > 0) keys(x.right, queue, lo, hi);
}
/**
* Returns the number of keys in the symbol table in the given range.
*
* @param lo minimum endpoint
* @param hi maximum endpoint
* @return the number of keys in the sybol table between {@code lo}
* (inclusive) and {@code hi} (inclusive)
* @throws IllegalArgumentException if either {@code lo} or {@code hi}
* is {@code null}
*/
public int size(Key lo, Key hi) {
if (lo == null) throw new IllegalArgumentException("first argument to size() is null");
if (hi == null) throw new IllegalArgumentException("second argument to size() is null");
if (lo.compareTo(hi) > 0) return 0;
if (contains(hi)) return rank(hi) - rank(lo) + 1;
else return rank(hi) - rank(lo);
}
/***************************************************************************
* Check integrity of red-black tree data structure.
***************************************************************************/
private boolean check() {
if (!isBST()) System.out.println("Not in symmetric order");
if (!isSizeConsistent()) System.out.println("Subtree counts not consistent");
if (!isRankConsistent()) System.out.println("Ranks not consistent");
if (!is23()) System.out.println("Not a 2-3 tree");
if (!isBalanced()) System.out.println("Not balanced");
return isBST() && isSizeConsistent() && isRankConsistent() && is23() && isBalanced();
}
// does this binary tree satisfy symmetric order?
// Note: this test also ensures that data structure is a binary tree since order is strict
private boolean isBST() {
return isBST(root, null, null);
}
// is the tree rooted at x a BST with all keys strictly between min and max
// (if min or max is null, treat as empty constraint)
// Credit: Bob Dondero's elegant solution
private boolean isBST(Node x, Key min, Key max) {
if (x == null) return true;
if (min != null && x.key.compareTo(min) <= 0) return false;
if (max != null && x.key.compareTo(max) >= 0) return false;
return isBST(x.left, min, x.key) && isBST(x.right, x.key, max);
}
// are the size fields correct?
private boolean isSizeConsistent() {
return isSizeConsistent(root);
}
private boolean isSizeConsistent(Node x) {
if (x == null) return true;
if (x.size != size(x.left) + size(x.right) + 1) return false;
return isSizeConsistent(x.left) && isSizeConsistent(x.right);
}
// check that ranks are consistent
private boolean isRankConsistent() {
for (int i = 0; i < size(); i++)
if (i != rank(select(i))) return false;
for (Key key : keys())
if (key.compareTo(select(rank(key))) != 0) return false;
return true;
}
// Does the tree have no red right links, and at most one (left)
// red links in a row on any path?
private boolean is23() {
return is23(root);
}
private boolean is23(Node x) {
if (x == null) return true;
if (isRed(x.right)) return false;
if (x != root && isRed(x) && isRed(x.left))
return false;
return is23(x.left) && is23(x.right);
}
// do all paths from root to leaf have same number of black edges?
private boolean isBalanced() {
int black = 0; // number of black links on path from root to min
Node x = root;
while (x != null) {
if (!isRed(x)) black++;
x = x.left;
}
return isBalanced(root, black);
}
// does every path from the root to a leaf have the given number of black links?
private boolean isBalanced(Node x, int black) {
if (x == null) return black == 0;
if (!isRed(x)) black--;
return isBalanced(x.left, black) && isBalanced(x.right, black);
}
/**
* Unit tests the {@code RedBlackBST} data type.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
RedBlackBST<String, Integer> st = new RedBlackBST<String, Integer>();
Scanner scanner = new Scanner(System.in);
for (int i = 0; scanner.hasNext(); i++) {
String key = scanner.next();
st.put(key, i);
}
for (String s : st.keys())
System.out.println(s + " " + st.get(s));
System.out.println();
}
} | false |
18604_0 | package me.pattern.singleton;
/**
* 单例模式:Singleton
* 应用场合:有些对象只需要一个就够了,如古代皇帝,老婆
* 作用:保证整个应用程序中某个实例有且只有一个 类型:
* 饿汉模式,懒汉模式
* 此为饿汉模式:加载类比较慢,运行时获取对象较快,线程安全
* @author ZhangRui
* @data 2017年12月13日 下午11:33:53
*/
public class Singleton {
// 1.将构造方法私有化,不允许外界直接创建对象
private Singleton() {
}
// 3.创建类的唯一实例,使用private static 修饰
private static Singleton instance = new Singleton();
/**
* 4.提供一个用于获取实例的方法,用public static 修饰
*
* @return
*/
public static Singleton getInstance() {
return instance;
}
}
| AlbertRui/JavaStudy | design_pattern/singleton/Singleton.java | 245 | /**
* 单例模式:Singleton
* 应用场合:有些对象只需要一个就够了,如古代皇帝,老婆
* 作用:保证整个应用程序中某个实例有且只有一个 类型:
* 饿汉模式,懒汉模式
* 此为饿汉模式:加载类比较慢,运行时获取对象较快,线程安全
* @author ZhangRui
* @data 2017年12月13日 下午11:33:53
*/ | block_comment | zh-cn | package me.pattern.singleton;
/**
* 单例模 <SUF>*/
public class Singleton {
// 1.将构造方法私有化,不允许外界直接创建对象
private Singleton() {
}
// 3.创建类的唯一实例,使用private static 修饰
private static Singleton instance = new Singleton();
/**
* 4.提供一个用于获取实例的方法,用public static 修饰
*
* @return
*/
public static Singleton getInstance() {
return instance;
}
}
| true |
18041_8 | package org.sang.service;
import org.sang.bean.Position;
import org.sang.bean.Status;
import org.sang.bean.User;
import org.sang.bean.Course;
import org.sang.dao.UserDao;
import org.sang.dao.CourseDao;
import org.sang.dao.CourseParticipantsDao;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
* @author 零
*
*/
public class CourseService {
private CourseDao meetingDao = new CourseDao();
private UserDao employeeDao = new UserDao();
private List<User> emps;
private HashMap<User, Status> empssHashMap;
public List<User> getEmps() {
return emps;
}
public HashMap<User, Status> getEmpssHashMap() {
return empssHashMap;
}
private CourseParticipantsDao meetingParticipantsDao = new CourseParticipantsDao();
public void insert(Course meeting, String[] empids) {
int insert = meetingDao.insert(meeting);
meetingParticipantsDao.insert(insert, empids);
}
public List<Course> searchMeeting(String meetingname, String roomname, String reservername, String reservefromdate, String reservetodate, String meetingfromdate, String meetingtodate, int page, int count) {
return meetingDao.searchMeeting(meetingname, roomname, reservername, reservefromdate, reservetodate, meetingfromdate, meetingtodate, page, count);
}
public int getCount(String meetingname, String roomname, String reservername, String reservefromdate, String reservetodate, String meetingfromdate, String meetingtodate) {
return meetingDao.getCount(meetingname, roomname, reservername, reservefromdate, reservetodate, meetingfromdate, meetingtodate);
}
public Course getMeetingDetailsByMeetingId(int mid) {
Course meeting = meetingDao.getMeetingById(mid);
this.emps = employeeDao.getEmpByMeetingId(meeting.getMeetingid());
this.empssHashMap= employeeDao.getEmpStatusByUser(this.emps, mid);
return meeting;
}
public List<Course> getCanceledMeeting(int empid) {
return meetingDao.getCanceledMeeting(empid);
}
/**
* 获取七天会议
* @param empid
* @return
*/
public List<Course> getMeeting7Days(int empid) {
return meetingDao.getMeeting7Days(empid);
}
/**
* 预定会议
* @param empid
* @return
*/
public List<Course> getMyBookingMeeting(int empid) {
return meetingDao.getMyBookingMeeting(empid);
}
/**
* 参加
* @param mid
* @param reason
* @return
*/
public int attendMeeting(int mid, int userid) {
return employeeDao.attendMeeting(mid, userid);
}
/**
* 请假
* @param mid
* @param reason
* @return
*/
public int leaveMeeting(int mid, int userid) {
return employeeDao.leaveMeeting(mid, userid);
}
/**
* 取消会议
* @param mid
* @param reason
* @return
*/
public int cancelMeeting(int mid, String reason) {
return meetingDao.cancelMeeting(mid, reason);
}
/**
* 我的会议
* @param empid
* @return
*/
public List<Course> getMyMeeting(int empid) {
return meetingDao.getMyMeeting(empid);
}
/**
* 我的参会情况
*/
public Map<Course,Status> getMyMeetingcondition(int empid) {
return meetingDao.getMyMeetingcondition(empid);
}
/**
* 班级的参会情况
*/
public Map<Map<Course, Status>,User> getClassMeetingcondition(int depid) {
return meetingDao.getClassMeetingcondition(depid);
}
/**
* 获取位置
* @param parseInt
* @return
*/
public Position getclassroompostionBymid(int mid) {
// TODO Auto-generated method stub
return meetingDao.getclassroompostionBymid(mid);
}
}
| AldonahZero/classCheck | src/org/sang/service/CourseService.java | 1,015 | /**
* 班级的参会情况
*/ | block_comment | zh-cn | package org.sang.service;
import org.sang.bean.Position;
import org.sang.bean.Status;
import org.sang.bean.User;
import org.sang.bean.Course;
import org.sang.dao.UserDao;
import org.sang.dao.CourseDao;
import org.sang.dao.CourseParticipantsDao;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
* @author 零
*
*/
public class CourseService {
private CourseDao meetingDao = new CourseDao();
private UserDao employeeDao = new UserDao();
private List<User> emps;
private HashMap<User, Status> empssHashMap;
public List<User> getEmps() {
return emps;
}
public HashMap<User, Status> getEmpssHashMap() {
return empssHashMap;
}
private CourseParticipantsDao meetingParticipantsDao = new CourseParticipantsDao();
public void insert(Course meeting, String[] empids) {
int insert = meetingDao.insert(meeting);
meetingParticipantsDao.insert(insert, empids);
}
public List<Course> searchMeeting(String meetingname, String roomname, String reservername, String reservefromdate, String reservetodate, String meetingfromdate, String meetingtodate, int page, int count) {
return meetingDao.searchMeeting(meetingname, roomname, reservername, reservefromdate, reservetodate, meetingfromdate, meetingtodate, page, count);
}
public int getCount(String meetingname, String roomname, String reservername, String reservefromdate, String reservetodate, String meetingfromdate, String meetingtodate) {
return meetingDao.getCount(meetingname, roomname, reservername, reservefromdate, reservetodate, meetingfromdate, meetingtodate);
}
public Course getMeetingDetailsByMeetingId(int mid) {
Course meeting = meetingDao.getMeetingById(mid);
this.emps = employeeDao.getEmpByMeetingId(meeting.getMeetingid());
this.empssHashMap= employeeDao.getEmpStatusByUser(this.emps, mid);
return meeting;
}
public List<Course> getCanceledMeeting(int empid) {
return meetingDao.getCanceledMeeting(empid);
}
/**
* 获取七天会议
* @param empid
* @return
*/
public List<Course> getMeeting7Days(int empid) {
return meetingDao.getMeeting7Days(empid);
}
/**
* 预定会议
* @param empid
* @return
*/
public List<Course> getMyBookingMeeting(int empid) {
return meetingDao.getMyBookingMeeting(empid);
}
/**
* 参加
* @param mid
* @param reason
* @return
*/
public int attendMeeting(int mid, int userid) {
return employeeDao.attendMeeting(mid, userid);
}
/**
* 请假
* @param mid
* @param reason
* @return
*/
public int leaveMeeting(int mid, int userid) {
return employeeDao.leaveMeeting(mid, userid);
}
/**
* 取消会议
* @param mid
* @param reason
* @return
*/
public int cancelMeeting(int mid, String reason) {
return meetingDao.cancelMeeting(mid, reason);
}
/**
* 我的会议
* @param empid
* @return
*/
public List<Course> getMyMeeting(int empid) {
return meetingDao.getMyMeeting(empid);
}
/**
* 我的参会情况
*/
public Map<Course,Status> getMyMeetingcondition(int empid) {
return meetingDao.getMyMeetingcondition(empid);
}
/**
* 班级的 <SUF>*/
public Map<Map<Course, Status>,User> getClassMeetingcondition(int depid) {
return meetingDao.getClassMeetingcondition(depid);
}
/**
* 获取位置
* @param parseInt
* @return
*/
public Position getclassroompostionBymid(int mid) {
// TODO Auto-generated method stub
return meetingDao.getclassroompostionBymid(mid);
}
}
| false |
48384_1 | package cc.ryanc.halo.listener;
import cc.ryanc.halo.model.dto.HaloConst;
import cc.ryanc.halo.model.dto.Theme;
import cc.ryanc.halo.model.enums.BlogPropertiesEnum;
import cc.ryanc.halo.service.OptionsService;
import cc.ryanc.halo.utils.HaloUtils;
import cc.ryanc.halo.web.controller.core.BaseController;
import cn.hutool.core.util.StrUtil;
import cn.hutool.cron.CronUtil;
import freemarker.template.TemplateModelException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* <pre>
* 应用启动完成后所执行的方法
* </pre>
*
* @author : RYAN0UP
* @date : 2018/12/5
*/
@Slf4j
@Configuration
public class StartedListener implements ApplicationListener<ApplicationStartedEvent> {
@Autowired
private OptionsService optionsService;
@Autowired
private freemarker.template.Configuration configuration;
@Override
public void onApplicationEvent(ApplicationStartedEvent event) {
try {
this.loadActiveTheme();
} catch (TemplateModelException e) {
e.printStackTrace();
}
this.loadOptions();
this.loadThemes();
this.loadOwo();
//启动定时任务
CronUtil.start();
log.info("The scheduled task starts successfully!");
}
/**
* 加载主题设置
*/
private void loadActiveTheme() throws TemplateModelException {
final String themeValue = optionsService.findOneOption(BlogPropertiesEnum.THEME.getProp());
if (StrUtil.isNotEmpty(themeValue) && !StrUtil.equals(themeValue, null)) {
BaseController.THEME = themeValue;
} else {
//以防万一
BaseController.THEME = "anatole";
}
configuration.setSharedVariable("themeName", BaseController.THEME);
}
/**
* 加载设置选项
*/
private void loadOptions() {
final Map<String, String> options = optionsService.findAllOptions();
if (options != null && !options.isEmpty()) {
HaloConst.OPTIONS = options;
}
}
/**
* 加载所有主题
*/
private void loadThemes() {
HaloConst.THEMES.clear();
final List<Theme> themes = HaloUtils.getThemes();
if (null != themes) {
HaloConst.THEMES = themes;
}
}
/**
* 加载OwO表情
*/
private void loadOwo() {
final Map<String, String> map = new HashMap<>(135);
map.put("@[nico]", "<img src='/static/halo-common/OwO/paopao/nico.png' alt='nico.png' style='vertical-align: middle;'>");
map.put("@[OK]", "<img src='/static/halo-common/OwO/paopao/OK.png' alt='OK.png' style='vertical-align: middle;'>");
map.put("@[what]", "<img src='/static/halo-common/OwO/paopao/what.png' alt='what.png' style='vertical-align: middle;'>");
map.put("@[三道杠]", "<img src='/static/halo-common/OwO/paopao/三道杠.png' alt='三道杠.png' style='vertical-align: middle;'>");
map.put("@[不高兴]", "<img src='/static/halo-common/OwO/paopao/不高兴.png' alt='不高兴.png' style='vertical-align: middle;'>");
map.put("@[乖]", "<img src='/static/halo-common/OwO/paopao/乖.png' alt='乖.png' style='vertical-align: middle;'>");
map.put("@[你懂的]", "<img src='/static/halo-common/OwO/paopao/你懂的.png' alt='你懂的.png' style='vertical-align: middle;'>");
map.put("@[便便]", "<img src='/static/halo-common/OwO/paopao/便便.png' alt='便便.png' style='vertical-align: middle;'>");
map.put("@[冷]", "<img src='/static/halo-common/OwO/paopao/冷.png' alt='冷.png' style='vertical-align: middle;'>");
map.put("@[勉强]", "<img src='/static/halo-common/OwO/paopao/勉强.png' alt='勉强.png' style='vertical-align: middle;'>");
map.put("@[吃瓜]", "<img src='/static/halo-common/OwO/paopao/吃瓜.png' alt='吃瓜.png' style='vertical-align: middle;'>");
map.put("@[吃翔]", "<img src='/static/halo-common/OwO/paopao/吃翔.png' alt='吃翔.png' style='vertical-align: middle;'>");
map.put("@[吐]", "<img src='/static/halo-common/OwO/paopao/吐.png' alt='吐.png' style='vertical-align: middle;'>");
map.put("@[吐舌]", "<img src='/static/halo-common/OwO/paopao/吐舌.png' alt='吐舌.png' style='vertical-align: middle;'>");
map.put("@[呀咩爹]", "<img src='/static/halo-common/OwO/paopao/呀咩爹.png' alt='呀咩爹.png' style='vertical-align: middle;'>");
map.put("@[呵呵]", "<img src='/static/halo-common/OwO/paopao/呵呵.png' alt='呵呵.png' style='vertical-align: middle;'>");
map.put("@[呼]", "<img src='/static/halo-common/OwO/paopao/呼.png' alt='呼.png' style='vertical-align: middle;'>");
map.put("@[咦]", "<img src='/static/halo-common/OwO/paopao/咦.png' alt='咦.png' style='vertical-align: middle;'>");
map.put("@[哈哈]", "<img src='/static/halo-common/OwO/paopao/哈哈.png' alt='哈哈.png' style='vertical-align: middle;'>");
map.put("@[啊]", "<img src='/static/halo-common/OwO/paopao/啊.png' alt='啊.png' style='vertical-align: middle;'>");
map.put("@[喷]", "<img src='/static/halo-common/OwO/paopao/喷.png' alt='喷.png' style='vertical-align: middle;'>");
map.put("@[嘚瑟]", "<img src='/static/halo-common/OwO/paopao/嘚瑟.png' alt='嘚瑟.png' style='vertical-align: middle;'>");
map.put("@[大拇指]", "<img src='/static/halo-common/OwO/paopao/大拇指.png' alt='大拇指.png' style='vertical-align: middle;'>");
map.put("@[太开心]", "<img src='/static/halo-common/OwO/paopao/太开心.png' alt='太开心.png' style='vertical-align: middle;'>");
map.put("@[太阳]", "<img src='/static/halo-common/OwO/paopao/太阳.png' alt='太阳.png' style='vertical-align: middle;'>");
map.put("@[委屈]", "<img src='/static/halo-common/OwO/paopao/委屈.png' alt='委屈.png' style='vertical-align: middle;'>");
map.put("@[小乖]", "<img src='/static/halo-common/OwO/paopao/小乖.png' alt='小乖.png' style='vertical-align: middle;'>");
map.put("@[小红脸]", "<img src='/static/halo-common/OwO/paopao/小红脸.png' alt='小红脸.png' style='vertical-align: middle;'>");
map.put("@[开心]", "<img src='/static/halo-common/OwO/paopao/开心.png' alt='开心.png' style='vertical-align: middle;'>");
map.put("@[弱]", "<img src='/static/halo-common/OwO/paopao/弱.png' alt='弱.png' style='vertical-align: middle;'>");
map.put("@[彩虹]", "<img src='/static/halo-common/OwO/paopao/彩虹.png' alt='彩虹.png' style='vertical-align: middle;'>");
map.put("@[心碎]", "<img src='/static/halo-common/OwO/paopao/心碎.png' alt='心碎.png' style='vertical-align: middle;'>");
map.put("@[怒]", "<img src='/static/halo-common/OwO/paopao/怒.png' alt='怒.png' style='vertical-align: middle;'>");
map.put("@[惊哭]", "<img src='/static/halo-common/OwO/paopao/惊哭.png' alt='惊哭.png' style='vertical-align: middle;'>");
map.put("@[惊恐]", "<img src='/static/halo-common/OwO/paopao/惊恐.png' alt='惊恐.png' style='vertical-align: middle;'>");
map.put("@[惊讶]", "<img src='/static/halo-common/OwO/paopao/惊讶.png' alt='惊讶.png' style='vertical-align: middle;'>");
map.put("@[懒得理]", "<img src='/static/halo-common/OwO/paopao/懒得理.png' alt='懒得理.png' style='vertical-align: middle;'>");
map.put("@[手纸]", "<img src='/static/halo-common/OwO/paopao/手纸.png' alt='手纸.png' style='vertical-align: middle;'>");
map.put("@[挖鼻]", "<img src='/static/halo-common/OwO/paopao/挖鼻.png' alt='挖鼻.png' style='vertical-align: middle;'>");
map.put("@[捂嘴笑]", "<img src='/static/halo-common/OwO/paopao/捂嘴笑.png' alt='捂嘴笑.png' style='vertical-align: middle;'>");
map.put("@[星星月亮]", "<img src='/static/halo-common/OwO/paopao/星星月亮.png' alt='星星月亮.png' style='vertical-align: middle;'>");
map.put("@[汗]", "<img src='/static/halo-common/OwO/paopao/汗.png' alt='汗.png' style='vertical-align: middle;'>");
map.put("@[沙发]", "<img src='/static/halo-common/OwO/paopao/沙发.png' alt='沙发.png' style='vertical-align: middle;'>");
map.put("@[泪]", "<img src='/static/halo-common/OwO/paopao/泪.png' alt='泪.png' style='vertical-align: middle;'>");
map.put("@[滑稽]", "<img src='/static/halo-common/OwO/paopao/滑稽.png' alt='滑稽.png' style='vertical-align: middle;'>");
map.put("@[灯泡]", "<img src='/static/halo-common/OwO/paopao/灯泡.png' alt='灯泡.png' style='vertical-align: middle;'>");
map.put("@[爱心]", "<img src='/static/halo-common/OwO/paopao/爱心.png' alt='爱心.png' style='vertical-align: middle;'>");
map.put("@[犀利]", "<img src='/static/halo-common/OwO/paopao/犀利.png' alt='犀利.png' style='vertical-align: middle;'>");
map.put("@[狂汗]", "<img src='/static/halo-common/OwO/paopao/狂汗.png' alt='狂汗.png' style='vertical-align: middle;'>");
map.put("@[玫瑰]", "<img src='/static/halo-common/OwO/paopao/玫瑰.png' alt='玫瑰.png' style='vertical-align: middle;'>");
map.put("@[生气]", "<img src='/static/halo-common/OwO/paopao/生气.png' alt='生气.png' style='vertical-align: middle;'>");
map.put("@[疑问]", "<img src='/static/halo-common/OwO/paopao/疑问.png' alt='疑问.png' style='vertical-align: middle;'>");
map.put("@[真棒]", "<img src='/static/halo-common/OwO/paopao/真棒.png' alt='真棒.png' style='vertical-align: middle;'>");
map.put("@[睡觉]", "<img src='/static/halo-common/OwO/paopao/睡觉.png' alt='睡觉.png' style='vertical-align: middle;'>");
map.put("@[礼物]", "<img src='/static/halo-common/OwO/paopao/礼物.png' alt='礼物.png' style='vertical-align: middle;'>");
map.put("@[笑尿]", "<img src='/static/halo-common/OwO/paopao/笑尿.png' alt='笑尿.png' style='vertical-align: middle;'>");
map.put("@[笑眼]", "<img src='/static/halo-common/OwO/paopao/笑眼.png' alt='笑眼.png' style='vertical-align: middle;'>");
map.put("@[红领巾]", "<img src='/static/halo-common/OwO/paopao/红领巾.png' alt='红领巾.png' style='vertical-align: middle;'>");
map.put("@[胜利]", "<img src='/static/halo-common/OwO/paopao/胜利.png' alt='胜利.png' style='vertical-align: middle;'>");
map.put("@[花心]", "<img src='/static/halo-common/OwO/paopao/花心.png' alt='花心.png' style='vertical-align: middle;'>");
map.put("@[茶杯]", "<img src='/static/halo-common/OwO/paopao/茶杯.png' alt='茶杯.png' style='vertical-align: middle;'>");
map.put("@[药丸]", "<img src='/static/halo-common/OwO/paopao/药丸.png' alt='药丸.png' style='vertical-align: middle;'>");
map.put("@[蛋糕]", "<img src='/static/halo-common/OwO/paopao/蛋糕.png' alt='蛋糕.png' style='vertical-align: middle;'>");
map.put("@[蜡烛]", "<img src='/static/halo-common/OwO/paopao/蜡烛.png' alt='蜡烛.png' style='vertical-align: middle;'>");
map.put("@[鄙视]", "<img src='/static/halo-common/OwO/paopao/鄙视.png' alt='鄙视.png' style='vertical-align: middle;'>");
map.put("@[酷]", "<img src='/static/halo-common/OwO/paopao/酷.png' alt='酷.png' style='vertical-align: middle;'>");
map.put("@[酸爽]", "<img src='/static/halo-common/OwO/paopao/酸爽.png' alt='酸爽.png' style='vertical-align: middle;'>");
map.put("@[钱]", "<img src='/static/halo-common/OwO/paopao/钱.png' alt='钱.png' style='vertical-align: middle;'>");
map.put("@[钱币]", "<img src='/static/halo-common/OwO/paopao/钱币.png' alt='钱币.png' style='vertical-align: middle;'>");
map.put("@[阴险]", "<img src='/static/halo-common/OwO/paopao/阴险.png' alt='阴险.png' style='vertical-align: middle;'>");
map.put("@[音乐]", "<img src='/static/halo-common/OwO/paopao/音乐.png' alt='音乐.png' style='vertical-align: middle;'>");
map.put("@[香蕉]", "<img src='/static/halo-common/OwO/paopao/香蕉.png' alt='香蕉.png' style='vertical-align: middle;'>");
map.put("@[黑线]", "<img src='/static/halo-common/OwO/paopao/黑线.png' alt='黑线.png' style='vertical-align: middle;'>");
map.put("@(不出所料)", "<img src='/static/halo-common/OwO/alu/不出所料.png' alt='不出所料.png' style='vertical-align: middle;'>");
map.put("@(不说话)", "<img src='/static/halo-common/OwO/alu/不说话.png' alt='不说话.png' style='vertical-align: middle;'>");
map.put("@(不高兴)", "<img src='/static/halo-common/OwO/alu/不高兴.png' alt='不高兴.png' style='vertical-align: middle;'>");
map.put("@(中刀)", "<img src='/static/halo-common/OwO/alu/中刀.png' alt='中刀.png' style='vertical-align: middle;'>");
map.put("@(中指)", "<img src='/static/halo-common/OwO/alu/中指.png' alt='中指.png' style='vertical-align: middle;'>");
map.put("@(中枪)", "<img src='/static/halo-common/OwO/alu/中枪.png' alt='中枪.png' style='vertical-align: middle;'>");
map.put("@(亲亲)", "<img src='/static/halo-common/OwO/alu/亲亲.png' alt='亲亲.png' style='vertical-align: middle;'>");
map.put("@(便便)", "<img src='/static/halo-common/OwO/alu/便便.png' alt='便便.png' style='vertical-align: middle;'>");
map.put("@(傻笑)", "<img src='/static/halo-common/OwO/alu/傻笑.png' alt='傻笑.png' style='vertical-align: middle;'>");
map.put("@(内伤)", "<img src='/static/halo-common/OwO/alu/内伤.png' alt='内伤.png' style='vertical-align: middle;'>");
map.put("@(击掌)", "<img src='/static/halo-common/OwO/alu/击掌.png' alt='击掌.png' style='vertical-align: middle;'>");
map.put("@(口水)", "<img src='/static/halo-common/OwO/alu/口水.png' alt='口水.png' style='vertical-align: middle;'>");
map.put("@(吐)", "<img src='/static/halo-common/OwO/alu/吐.png' alt='吐.png' style='vertical-align: middle;'>");
map.put("@(吐舌)", "<img src='/static/halo-common/OwO/alu/吐舌.png' alt='吐舌.png' style='vertical-align: middle;'>");
map.put("@(吐血倒地)", "<img src='/static/halo-common/OwO/alu/吐血倒地.png' alt='吐血倒地.png' style='vertical-align: middle;'>");
map.put("@(呲牙)", "<img src='/static/halo-common/OwO/alu/呲牙.png' alt='呲牙.png' style='vertical-align: middle;'>");
map.put("@(咽气)", "<img src='/static/halo-common/OwO/alu/咽气.png' alt='咽气.png' style='vertical-align: middle;'>");
map.put("@(哭泣)", "<img src='/static/halo-common/OwO/alu/哭泣.png' alt='哭泣.png' style='vertical-align: middle;'>");
map.put("@(喜极而泣)", "<img src='/static/halo-common/OwO/alu/喜极而泣.png' alt='喜极而泣.png' style='vertical-align: middle;'>");
map.put("@(喷水)", "<img src='/static/halo-common/OwO/alu/喷水.png' alt='喷水.png' style='vertical-align: middle;'>");
map.put("@(喷血)", "<img src='/static/halo-common/OwO/alu/喷血.png' alt='喷血.png' style='vertical-align: middle;'>");
map.put("@(坐等)", "<img src='/static/halo-common/OwO/alu/坐等.png' alt='坐等.png' style='vertical-align: middle;'>");
map.put("@(大囧)", "<img src='/static/halo-common/OwO/alu/大囧.png' alt='大囧.png' style='vertical-align: middle;'>");
map.put("@(害羞)", "<img src='/static/halo-common/OwO/alu/害羞.png' alt='害羞.png' style='vertical-align: middle;'>");
map.put("@(小怒)", "<img src='/static/halo-common/OwO/alu/小怒.png' alt='小怒.png' style='vertical-align: middle;'>");
map.put("@(小眼睛)", "<img src='/static/halo-common/OwO/alu/小眼睛.png' alt='小眼睛.png' style='vertical-align: middle;'>");
map.put("@(尴尬)", "<img src='/static/halo-common/OwO/alu/尴尬.png' alt='尴尬.png' style='vertical-align: middle;'>");
map.put("@(得意)", "<img src='/static/halo-common/OwO/alu/得意.png' alt='得意.png' style='vertical-align: middle;'>");
map.put("@(惊喜)", "<img src='/static/halo-common/OwO/alu/惊喜.png' alt='惊喜.png' style='vertical-align: middle;'>");
map.put("@(想一想)", "<img src='/static/halo-common/OwO/alu/想一想.png' alt='想一想.png' style='vertical-align: middle;'>");
map.put("@(愤怒)", "<img src='/static/halo-common/OwO/alu/愤怒.png' alt='愤怒.png' style='vertical-align: middle;'>");
map.put("@(扇耳光)", "<img src='/static/halo-common/OwO/alu/扇耳光.png' alt='扇耳光.png' style='vertical-align: middle;'>");
map.put("@(投降)", "<img src='/static/halo-common/OwO/alu/投降.png' alt='投降.png' style='vertical-align: middle;'>");
map.put("@(抠鼻)", "<img src='/static/halo-common/OwO/alu/抠鼻.png' alt='抠鼻.png' style='vertical-align: middle;'>");
map.put("@(抽烟)", "<img src='/static/halo-common/OwO/alu/抽烟.png' alt='抽烟.png' style='vertical-align: middle;'>");
map.put("@(无奈)", "<img src='/static/halo-common/OwO/alu/无奈.png' alt='无奈.png' style='vertical-align: middle;'>");
map.put("@(无所谓)", "<img src='/static/halo-common/OwO/alu/无所谓.png' alt='无所谓.png' style='vertical-align: middle;'>");
map.put("@(无语)", "<img src='/static/halo-common/OwO/alu/无语.png' alt='无语.png' style='vertical-align: middle;'>");
map.put("@(暗地观察)", "<img src='/static/halo-common/OwO/alu/暗地观察.png' alt='暗地观察.png' style='vertical-align: middle;'>");
map.put("@(期待)", "<img src='/static/halo-common/OwO/alu/期待.png' alt='期待.png' style='vertical-align: middle;'>");
map.put("@(欢呼)", "<img src='/static/halo-common/OwO/alu/欢呼.png' alt='欢呼.png' style='vertical-align: middle;'>");
map.put("@(汗)", "<img src='/static/halo-common/OwO/alu/汗.png' alt='汗.png' style='vertical-align: middle;'>");
map.put("@(深思)", "<img src='/static/halo-common/OwO/alu/深思.png' alt='深思.png' style='vertical-align: middle;'>");
map.put("@(狂汗)", "<img src='/static/halo-common/OwO/alu/狂汗.png' alt='狂汗.png' style='vertical-align: middle;'>");
map.put("@(献花)", "<img src='/static/halo-common/OwO/alu/献花.png' alt='献花.png' style='vertical-align: middle;'>");
map.put("@(献黄瓜)", "<img src='/static/halo-common/OwO/alu/献黄瓜.png' alt='献黄瓜.png' style='vertical-align: middle;'>");
map.put("@(皱眉)", "<img src='/static/halo-common/OwO/alu/皱眉.png' alt='皱眉.png' style='vertical-align: middle;'>");
map.put("@(看不见)", "<img src='/static/halo-common/OwO/alu/看不见.png' alt='看不见.png' style='vertical-align: middle;'>");
map.put("@(看热闹)", "<img src='/static/halo-common/OwO/alu/看热闹.png' alt='看热闹.png' style='vertical-align: middle;'>");
map.put("@(肿包)", "<img src='/static/halo-common/OwO/alu/肿包.png' alt='肿包.png' style='vertical-align: middle;'>");
map.put("@(脸红)", "<img src='/static/halo-common/OwO/alu/脸红.png' alt='脸红.png' style='vertical-align: middle;'>");
map.put("@(蜡烛)", "<img src='/static/halo-common/OwO/alu/蜡烛.png' alt='蜡烛.png' style='vertical-align: middle;'>");
map.put("@(装大款)", "<img src='/static/halo-common/OwO/alu/装大款.png' alt='装大款.png' style='vertical-align: middle;'>");
map.put("@(观察)", "<img src='/static/halo-common/OwO/alu/观察.png' alt='观察.png' style='vertical-align: middle;'>");
map.put("@(赞一个)", "<img src='/static/halo-common/OwO/alu/赞一个.png' alt='赞一个.png' style='vertical-align: middle;'>");
map.put("@(邪恶)", "<img src='/static/halo-common/OwO/alu/邪恶.png' alt='邪恶.png' style='vertical-align: middle;'>");
map.put("@(锁眉)", "<img src='/static/halo-common/OwO/alu/锁眉.png' alt='锁眉.png' style='vertical-align: middle;'>");
map.put("@(长草)", "<img src='/static/halo-common/OwO/alu/长草.png' alt='长草.png' style='vertical-align: middle;'>");
map.put("@(阴暗)", "<img src='/static/halo-common/OwO/alu/阴暗.png' alt='阴暗.png' style='vertical-align: middle;'>");
map.put("@(高兴)", "<img src='/static/halo-common/OwO/alu/高兴.png' alt='高兴.png' style='vertical-align: middle;'>");
map.put("@(黑线)", "<img src='/static/halo-common/OwO/alu/黑线.png' alt='黑线.png' style='vertical-align: middle;'>");
map.put("@(鼓掌)", "<img src='/static/halo-common/OwO/alu/鼓掌.png' alt='鼓掌.png' style='vertical-align: middle;'>");
HaloConst.OWO = map;
}
}
| Alension/stone | src/main/java/cc/ryanc/halo/listener/StartedListener.java | 7,521 | //启动定时任务 | line_comment | zh-cn | package cc.ryanc.halo.listener;
import cc.ryanc.halo.model.dto.HaloConst;
import cc.ryanc.halo.model.dto.Theme;
import cc.ryanc.halo.model.enums.BlogPropertiesEnum;
import cc.ryanc.halo.service.OptionsService;
import cc.ryanc.halo.utils.HaloUtils;
import cc.ryanc.halo.web.controller.core.BaseController;
import cn.hutool.core.util.StrUtil;
import cn.hutool.cron.CronUtil;
import freemarker.template.TemplateModelException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* <pre>
* 应用启动完成后所执行的方法
* </pre>
*
* @author : RYAN0UP
* @date : 2018/12/5
*/
@Slf4j
@Configuration
public class StartedListener implements ApplicationListener<ApplicationStartedEvent> {
@Autowired
private OptionsService optionsService;
@Autowired
private freemarker.template.Configuration configuration;
@Override
public void onApplicationEvent(ApplicationStartedEvent event) {
try {
this.loadActiveTheme();
} catch (TemplateModelException e) {
e.printStackTrace();
}
this.loadOptions();
this.loadThemes();
this.loadOwo();
//启动 <SUF>
CronUtil.start();
log.info("The scheduled task starts successfully!");
}
/**
* 加载主题设置
*/
private void loadActiveTheme() throws TemplateModelException {
final String themeValue = optionsService.findOneOption(BlogPropertiesEnum.THEME.getProp());
if (StrUtil.isNotEmpty(themeValue) && !StrUtil.equals(themeValue, null)) {
BaseController.THEME = themeValue;
} else {
//以防万一
BaseController.THEME = "anatole";
}
configuration.setSharedVariable("themeName", BaseController.THEME);
}
/**
* 加载设置选项
*/
private void loadOptions() {
final Map<String, String> options = optionsService.findAllOptions();
if (options != null && !options.isEmpty()) {
HaloConst.OPTIONS = options;
}
}
/**
* 加载所有主题
*/
private void loadThemes() {
HaloConst.THEMES.clear();
final List<Theme> themes = HaloUtils.getThemes();
if (null != themes) {
HaloConst.THEMES = themes;
}
}
/**
* 加载OwO表情
*/
private void loadOwo() {
final Map<String, String> map = new HashMap<>(135);
map.put("@[nico]", "<img src='/static/halo-common/OwO/paopao/nico.png' alt='nico.png' style='vertical-align: middle;'>");
map.put("@[OK]", "<img src='/static/halo-common/OwO/paopao/OK.png' alt='OK.png' style='vertical-align: middle;'>");
map.put("@[what]", "<img src='/static/halo-common/OwO/paopao/what.png' alt='what.png' style='vertical-align: middle;'>");
map.put("@[三道杠]", "<img src='/static/halo-common/OwO/paopao/三道杠.png' alt='三道杠.png' style='vertical-align: middle;'>");
map.put("@[不高兴]", "<img src='/static/halo-common/OwO/paopao/不高兴.png' alt='不高兴.png' style='vertical-align: middle;'>");
map.put("@[乖]", "<img src='/static/halo-common/OwO/paopao/乖.png' alt='乖.png' style='vertical-align: middle;'>");
map.put("@[你懂的]", "<img src='/static/halo-common/OwO/paopao/你懂的.png' alt='你懂的.png' style='vertical-align: middle;'>");
map.put("@[便便]", "<img src='/static/halo-common/OwO/paopao/便便.png' alt='便便.png' style='vertical-align: middle;'>");
map.put("@[冷]", "<img src='/static/halo-common/OwO/paopao/冷.png' alt='冷.png' style='vertical-align: middle;'>");
map.put("@[勉强]", "<img src='/static/halo-common/OwO/paopao/勉强.png' alt='勉强.png' style='vertical-align: middle;'>");
map.put("@[吃瓜]", "<img src='/static/halo-common/OwO/paopao/吃瓜.png' alt='吃瓜.png' style='vertical-align: middle;'>");
map.put("@[吃翔]", "<img src='/static/halo-common/OwO/paopao/吃翔.png' alt='吃翔.png' style='vertical-align: middle;'>");
map.put("@[吐]", "<img src='/static/halo-common/OwO/paopao/吐.png' alt='吐.png' style='vertical-align: middle;'>");
map.put("@[吐舌]", "<img src='/static/halo-common/OwO/paopao/吐舌.png' alt='吐舌.png' style='vertical-align: middle;'>");
map.put("@[呀咩爹]", "<img src='/static/halo-common/OwO/paopao/呀咩爹.png' alt='呀咩爹.png' style='vertical-align: middle;'>");
map.put("@[呵呵]", "<img src='/static/halo-common/OwO/paopao/呵呵.png' alt='呵呵.png' style='vertical-align: middle;'>");
map.put("@[呼]", "<img src='/static/halo-common/OwO/paopao/呼.png' alt='呼.png' style='vertical-align: middle;'>");
map.put("@[咦]", "<img src='/static/halo-common/OwO/paopao/咦.png' alt='咦.png' style='vertical-align: middle;'>");
map.put("@[哈哈]", "<img src='/static/halo-common/OwO/paopao/哈哈.png' alt='哈哈.png' style='vertical-align: middle;'>");
map.put("@[啊]", "<img src='/static/halo-common/OwO/paopao/啊.png' alt='啊.png' style='vertical-align: middle;'>");
map.put("@[喷]", "<img src='/static/halo-common/OwO/paopao/喷.png' alt='喷.png' style='vertical-align: middle;'>");
map.put("@[嘚瑟]", "<img src='/static/halo-common/OwO/paopao/嘚瑟.png' alt='嘚瑟.png' style='vertical-align: middle;'>");
map.put("@[大拇指]", "<img src='/static/halo-common/OwO/paopao/大拇指.png' alt='大拇指.png' style='vertical-align: middle;'>");
map.put("@[太开心]", "<img src='/static/halo-common/OwO/paopao/太开心.png' alt='太开心.png' style='vertical-align: middle;'>");
map.put("@[太阳]", "<img src='/static/halo-common/OwO/paopao/太阳.png' alt='太阳.png' style='vertical-align: middle;'>");
map.put("@[委屈]", "<img src='/static/halo-common/OwO/paopao/委屈.png' alt='委屈.png' style='vertical-align: middle;'>");
map.put("@[小乖]", "<img src='/static/halo-common/OwO/paopao/小乖.png' alt='小乖.png' style='vertical-align: middle;'>");
map.put("@[小红脸]", "<img src='/static/halo-common/OwO/paopao/小红脸.png' alt='小红脸.png' style='vertical-align: middle;'>");
map.put("@[开心]", "<img src='/static/halo-common/OwO/paopao/开心.png' alt='开心.png' style='vertical-align: middle;'>");
map.put("@[弱]", "<img src='/static/halo-common/OwO/paopao/弱.png' alt='弱.png' style='vertical-align: middle;'>");
map.put("@[彩虹]", "<img src='/static/halo-common/OwO/paopao/彩虹.png' alt='彩虹.png' style='vertical-align: middle;'>");
map.put("@[心碎]", "<img src='/static/halo-common/OwO/paopao/心碎.png' alt='心碎.png' style='vertical-align: middle;'>");
map.put("@[怒]", "<img src='/static/halo-common/OwO/paopao/怒.png' alt='怒.png' style='vertical-align: middle;'>");
map.put("@[惊哭]", "<img src='/static/halo-common/OwO/paopao/惊哭.png' alt='惊哭.png' style='vertical-align: middle;'>");
map.put("@[惊恐]", "<img src='/static/halo-common/OwO/paopao/惊恐.png' alt='惊恐.png' style='vertical-align: middle;'>");
map.put("@[惊讶]", "<img src='/static/halo-common/OwO/paopao/惊讶.png' alt='惊讶.png' style='vertical-align: middle;'>");
map.put("@[懒得理]", "<img src='/static/halo-common/OwO/paopao/懒得理.png' alt='懒得理.png' style='vertical-align: middle;'>");
map.put("@[手纸]", "<img src='/static/halo-common/OwO/paopao/手纸.png' alt='手纸.png' style='vertical-align: middle;'>");
map.put("@[挖鼻]", "<img src='/static/halo-common/OwO/paopao/挖鼻.png' alt='挖鼻.png' style='vertical-align: middle;'>");
map.put("@[捂嘴笑]", "<img src='/static/halo-common/OwO/paopao/捂嘴笑.png' alt='捂嘴笑.png' style='vertical-align: middle;'>");
map.put("@[星星月亮]", "<img src='/static/halo-common/OwO/paopao/星星月亮.png' alt='星星月亮.png' style='vertical-align: middle;'>");
map.put("@[汗]", "<img src='/static/halo-common/OwO/paopao/汗.png' alt='汗.png' style='vertical-align: middle;'>");
map.put("@[沙发]", "<img src='/static/halo-common/OwO/paopao/沙发.png' alt='沙发.png' style='vertical-align: middle;'>");
map.put("@[泪]", "<img src='/static/halo-common/OwO/paopao/泪.png' alt='泪.png' style='vertical-align: middle;'>");
map.put("@[滑稽]", "<img src='/static/halo-common/OwO/paopao/滑稽.png' alt='滑稽.png' style='vertical-align: middle;'>");
map.put("@[灯泡]", "<img src='/static/halo-common/OwO/paopao/灯泡.png' alt='灯泡.png' style='vertical-align: middle;'>");
map.put("@[爱心]", "<img src='/static/halo-common/OwO/paopao/爱心.png' alt='爱心.png' style='vertical-align: middle;'>");
map.put("@[犀利]", "<img src='/static/halo-common/OwO/paopao/犀利.png' alt='犀利.png' style='vertical-align: middle;'>");
map.put("@[狂汗]", "<img src='/static/halo-common/OwO/paopao/狂汗.png' alt='狂汗.png' style='vertical-align: middle;'>");
map.put("@[玫瑰]", "<img src='/static/halo-common/OwO/paopao/玫瑰.png' alt='玫瑰.png' style='vertical-align: middle;'>");
map.put("@[生气]", "<img src='/static/halo-common/OwO/paopao/生气.png' alt='生气.png' style='vertical-align: middle;'>");
map.put("@[疑问]", "<img src='/static/halo-common/OwO/paopao/疑问.png' alt='疑问.png' style='vertical-align: middle;'>");
map.put("@[真棒]", "<img src='/static/halo-common/OwO/paopao/真棒.png' alt='真棒.png' style='vertical-align: middle;'>");
map.put("@[睡觉]", "<img src='/static/halo-common/OwO/paopao/睡觉.png' alt='睡觉.png' style='vertical-align: middle;'>");
map.put("@[礼物]", "<img src='/static/halo-common/OwO/paopao/礼物.png' alt='礼物.png' style='vertical-align: middle;'>");
map.put("@[笑尿]", "<img src='/static/halo-common/OwO/paopao/笑尿.png' alt='笑尿.png' style='vertical-align: middle;'>");
map.put("@[笑眼]", "<img src='/static/halo-common/OwO/paopao/笑眼.png' alt='笑眼.png' style='vertical-align: middle;'>");
map.put("@[红领巾]", "<img src='/static/halo-common/OwO/paopao/红领巾.png' alt='红领巾.png' style='vertical-align: middle;'>");
map.put("@[胜利]", "<img src='/static/halo-common/OwO/paopao/胜利.png' alt='胜利.png' style='vertical-align: middle;'>");
map.put("@[花心]", "<img src='/static/halo-common/OwO/paopao/花心.png' alt='花心.png' style='vertical-align: middle;'>");
map.put("@[茶杯]", "<img src='/static/halo-common/OwO/paopao/茶杯.png' alt='茶杯.png' style='vertical-align: middle;'>");
map.put("@[药丸]", "<img src='/static/halo-common/OwO/paopao/药丸.png' alt='药丸.png' style='vertical-align: middle;'>");
map.put("@[蛋糕]", "<img src='/static/halo-common/OwO/paopao/蛋糕.png' alt='蛋糕.png' style='vertical-align: middle;'>");
map.put("@[蜡烛]", "<img src='/static/halo-common/OwO/paopao/蜡烛.png' alt='蜡烛.png' style='vertical-align: middle;'>");
map.put("@[鄙视]", "<img src='/static/halo-common/OwO/paopao/鄙视.png' alt='鄙视.png' style='vertical-align: middle;'>");
map.put("@[酷]", "<img src='/static/halo-common/OwO/paopao/酷.png' alt='酷.png' style='vertical-align: middle;'>");
map.put("@[酸爽]", "<img src='/static/halo-common/OwO/paopao/酸爽.png' alt='酸爽.png' style='vertical-align: middle;'>");
map.put("@[钱]", "<img src='/static/halo-common/OwO/paopao/钱.png' alt='钱.png' style='vertical-align: middle;'>");
map.put("@[钱币]", "<img src='/static/halo-common/OwO/paopao/钱币.png' alt='钱币.png' style='vertical-align: middle;'>");
map.put("@[阴险]", "<img src='/static/halo-common/OwO/paopao/阴险.png' alt='阴险.png' style='vertical-align: middle;'>");
map.put("@[音乐]", "<img src='/static/halo-common/OwO/paopao/音乐.png' alt='音乐.png' style='vertical-align: middle;'>");
map.put("@[香蕉]", "<img src='/static/halo-common/OwO/paopao/香蕉.png' alt='香蕉.png' style='vertical-align: middle;'>");
map.put("@[黑线]", "<img src='/static/halo-common/OwO/paopao/黑线.png' alt='黑线.png' style='vertical-align: middle;'>");
map.put("@(不出所料)", "<img src='/static/halo-common/OwO/alu/不出所料.png' alt='不出所料.png' style='vertical-align: middle;'>");
map.put("@(不说话)", "<img src='/static/halo-common/OwO/alu/不说话.png' alt='不说话.png' style='vertical-align: middle;'>");
map.put("@(不高兴)", "<img src='/static/halo-common/OwO/alu/不高兴.png' alt='不高兴.png' style='vertical-align: middle;'>");
map.put("@(中刀)", "<img src='/static/halo-common/OwO/alu/中刀.png' alt='中刀.png' style='vertical-align: middle;'>");
map.put("@(中指)", "<img src='/static/halo-common/OwO/alu/中指.png' alt='中指.png' style='vertical-align: middle;'>");
map.put("@(中枪)", "<img src='/static/halo-common/OwO/alu/中枪.png' alt='中枪.png' style='vertical-align: middle;'>");
map.put("@(亲亲)", "<img src='/static/halo-common/OwO/alu/亲亲.png' alt='亲亲.png' style='vertical-align: middle;'>");
map.put("@(便便)", "<img src='/static/halo-common/OwO/alu/便便.png' alt='便便.png' style='vertical-align: middle;'>");
map.put("@(傻笑)", "<img src='/static/halo-common/OwO/alu/傻笑.png' alt='傻笑.png' style='vertical-align: middle;'>");
map.put("@(内伤)", "<img src='/static/halo-common/OwO/alu/内伤.png' alt='内伤.png' style='vertical-align: middle;'>");
map.put("@(击掌)", "<img src='/static/halo-common/OwO/alu/击掌.png' alt='击掌.png' style='vertical-align: middle;'>");
map.put("@(口水)", "<img src='/static/halo-common/OwO/alu/口水.png' alt='口水.png' style='vertical-align: middle;'>");
map.put("@(吐)", "<img src='/static/halo-common/OwO/alu/吐.png' alt='吐.png' style='vertical-align: middle;'>");
map.put("@(吐舌)", "<img src='/static/halo-common/OwO/alu/吐舌.png' alt='吐舌.png' style='vertical-align: middle;'>");
map.put("@(吐血倒地)", "<img src='/static/halo-common/OwO/alu/吐血倒地.png' alt='吐血倒地.png' style='vertical-align: middle;'>");
map.put("@(呲牙)", "<img src='/static/halo-common/OwO/alu/呲牙.png' alt='呲牙.png' style='vertical-align: middle;'>");
map.put("@(咽气)", "<img src='/static/halo-common/OwO/alu/咽气.png' alt='咽气.png' style='vertical-align: middle;'>");
map.put("@(哭泣)", "<img src='/static/halo-common/OwO/alu/哭泣.png' alt='哭泣.png' style='vertical-align: middle;'>");
map.put("@(喜极而泣)", "<img src='/static/halo-common/OwO/alu/喜极而泣.png' alt='喜极而泣.png' style='vertical-align: middle;'>");
map.put("@(喷水)", "<img src='/static/halo-common/OwO/alu/喷水.png' alt='喷水.png' style='vertical-align: middle;'>");
map.put("@(喷血)", "<img src='/static/halo-common/OwO/alu/喷血.png' alt='喷血.png' style='vertical-align: middle;'>");
map.put("@(坐等)", "<img src='/static/halo-common/OwO/alu/坐等.png' alt='坐等.png' style='vertical-align: middle;'>");
map.put("@(大囧)", "<img src='/static/halo-common/OwO/alu/大囧.png' alt='大囧.png' style='vertical-align: middle;'>");
map.put("@(害羞)", "<img src='/static/halo-common/OwO/alu/害羞.png' alt='害羞.png' style='vertical-align: middle;'>");
map.put("@(小怒)", "<img src='/static/halo-common/OwO/alu/小怒.png' alt='小怒.png' style='vertical-align: middle;'>");
map.put("@(小眼睛)", "<img src='/static/halo-common/OwO/alu/小眼睛.png' alt='小眼睛.png' style='vertical-align: middle;'>");
map.put("@(尴尬)", "<img src='/static/halo-common/OwO/alu/尴尬.png' alt='尴尬.png' style='vertical-align: middle;'>");
map.put("@(得意)", "<img src='/static/halo-common/OwO/alu/得意.png' alt='得意.png' style='vertical-align: middle;'>");
map.put("@(惊喜)", "<img src='/static/halo-common/OwO/alu/惊喜.png' alt='惊喜.png' style='vertical-align: middle;'>");
map.put("@(想一想)", "<img src='/static/halo-common/OwO/alu/想一想.png' alt='想一想.png' style='vertical-align: middle;'>");
map.put("@(愤怒)", "<img src='/static/halo-common/OwO/alu/愤怒.png' alt='愤怒.png' style='vertical-align: middle;'>");
map.put("@(扇耳光)", "<img src='/static/halo-common/OwO/alu/扇耳光.png' alt='扇耳光.png' style='vertical-align: middle;'>");
map.put("@(投降)", "<img src='/static/halo-common/OwO/alu/投降.png' alt='投降.png' style='vertical-align: middle;'>");
map.put("@(抠鼻)", "<img src='/static/halo-common/OwO/alu/抠鼻.png' alt='抠鼻.png' style='vertical-align: middle;'>");
map.put("@(抽烟)", "<img src='/static/halo-common/OwO/alu/抽烟.png' alt='抽烟.png' style='vertical-align: middle;'>");
map.put("@(无奈)", "<img src='/static/halo-common/OwO/alu/无奈.png' alt='无奈.png' style='vertical-align: middle;'>");
map.put("@(无所谓)", "<img src='/static/halo-common/OwO/alu/无所谓.png' alt='无所谓.png' style='vertical-align: middle;'>");
map.put("@(无语)", "<img src='/static/halo-common/OwO/alu/无语.png' alt='无语.png' style='vertical-align: middle;'>");
map.put("@(暗地观察)", "<img src='/static/halo-common/OwO/alu/暗地观察.png' alt='暗地观察.png' style='vertical-align: middle;'>");
map.put("@(期待)", "<img src='/static/halo-common/OwO/alu/期待.png' alt='期待.png' style='vertical-align: middle;'>");
map.put("@(欢呼)", "<img src='/static/halo-common/OwO/alu/欢呼.png' alt='欢呼.png' style='vertical-align: middle;'>");
map.put("@(汗)", "<img src='/static/halo-common/OwO/alu/汗.png' alt='汗.png' style='vertical-align: middle;'>");
map.put("@(深思)", "<img src='/static/halo-common/OwO/alu/深思.png' alt='深思.png' style='vertical-align: middle;'>");
map.put("@(狂汗)", "<img src='/static/halo-common/OwO/alu/狂汗.png' alt='狂汗.png' style='vertical-align: middle;'>");
map.put("@(献花)", "<img src='/static/halo-common/OwO/alu/献花.png' alt='献花.png' style='vertical-align: middle;'>");
map.put("@(献黄瓜)", "<img src='/static/halo-common/OwO/alu/献黄瓜.png' alt='献黄瓜.png' style='vertical-align: middle;'>");
map.put("@(皱眉)", "<img src='/static/halo-common/OwO/alu/皱眉.png' alt='皱眉.png' style='vertical-align: middle;'>");
map.put("@(看不见)", "<img src='/static/halo-common/OwO/alu/看不见.png' alt='看不见.png' style='vertical-align: middle;'>");
map.put("@(看热闹)", "<img src='/static/halo-common/OwO/alu/看热闹.png' alt='看热闹.png' style='vertical-align: middle;'>");
map.put("@(肿包)", "<img src='/static/halo-common/OwO/alu/肿包.png' alt='肿包.png' style='vertical-align: middle;'>");
map.put("@(脸红)", "<img src='/static/halo-common/OwO/alu/脸红.png' alt='脸红.png' style='vertical-align: middle;'>");
map.put("@(蜡烛)", "<img src='/static/halo-common/OwO/alu/蜡烛.png' alt='蜡烛.png' style='vertical-align: middle;'>");
map.put("@(装大款)", "<img src='/static/halo-common/OwO/alu/装大款.png' alt='装大款.png' style='vertical-align: middle;'>");
map.put("@(观察)", "<img src='/static/halo-common/OwO/alu/观察.png' alt='观察.png' style='vertical-align: middle;'>");
map.put("@(赞一个)", "<img src='/static/halo-common/OwO/alu/赞一个.png' alt='赞一个.png' style='vertical-align: middle;'>");
map.put("@(邪恶)", "<img src='/static/halo-common/OwO/alu/邪恶.png' alt='邪恶.png' style='vertical-align: middle;'>");
map.put("@(锁眉)", "<img src='/static/halo-common/OwO/alu/锁眉.png' alt='锁眉.png' style='vertical-align: middle;'>");
map.put("@(长草)", "<img src='/static/halo-common/OwO/alu/长草.png' alt='长草.png' style='vertical-align: middle;'>");
map.put("@(阴暗)", "<img src='/static/halo-common/OwO/alu/阴暗.png' alt='阴暗.png' style='vertical-align: middle;'>");
map.put("@(高兴)", "<img src='/static/halo-common/OwO/alu/高兴.png' alt='高兴.png' style='vertical-align: middle;'>");
map.put("@(黑线)", "<img src='/static/halo-common/OwO/alu/黑线.png' alt='黑线.png' style='vertical-align: middle;'>");
map.put("@(鼓掌)", "<img src='/static/halo-common/OwO/alu/鼓掌.png' alt='鼓掌.png' style='vertical-align: middle;'>");
HaloConst.OWO = map;
}
}
| false |
64453_1 | package com.hywa.mddemo.tab;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import com.hywa.mddemo.R;
public class TabActivity extends AppCompatActivity {
private TabLayout tab_layout;
private ViewPager vp;
private String titles[] = new String[]{
// "新闻",
// "杂志",
"汽车",
"招聘",
"NBA"
};
private TabFragment fragments[];
private TabViewPagerAdapter tabViewPagerAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab);
tab_layout = findViewById(R.id.tab_layout);
vp = findViewById(R.id.vp);
init();
}
private void init(){
fragments = new TabFragment[titles.length];
for (int i = 0; i < titles.length; i++) {
fragments[i] = new TabFragment();
Bundle bundle = new Bundle();
bundle.putString("title" , titles[i]);
fragments[i].setArguments(bundle);
}
tabViewPagerAdapter = new TabViewPagerAdapter(getSupportFragmentManager() , fragments);
vp.setAdapter(tabViewPagerAdapter);
tab_layout.setupWithViewPager(vp);
for (int i = 0; i < titles.length; i++) {
TabLayout.Tab tab = tab_layout.getTabAt(i);
// tab.setIcon(R.mipmap.ic_launcher);
tab.setCustomView(R.layout.item_tab);
}
}
}
| AlertColby/MD | app/src/main/java/com/hywa/mddemo/tab/TabActivity.java | 399 | // "杂志", | line_comment | zh-cn | package com.hywa.mddemo.tab;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import com.hywa.mddemo.R;
public class TabActivity extends AppCompatActivity {
private TabLayout tab_layout;
private ViewPager vp;
private String titles[] = new String[]{
// "新闻",
// "杂 <SUF>
"汽车",
"招聘",
"NBA"
};
private TabFragment fragments[];
private TabViewPagerAdapter tabViewPagerAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab);
tab_layout = findViewById(R.id.tab_layout);
vp = findViewById(R.id.vp);
init();
}
private void init(){
fragments = new TabFragment[titles.length];
for (int i = 0; i < titles.length; i++) {
fragments[i] = new TabFragment();
Bundle bundle = new Bundle();
bundle.putString("title" , titles[i]);
fragments[i].setArguments(bundle);
}
tabViewPagerAdapter = new TabViewPagerAdapter(getSupportFragmentManager() , fragments);
vp.setAdapter(tabViewPagerAdapter);
tab_layout.setupWithViewPager(vp);
for (int i = 0; i < titles.length; i++) {
TabLayout.Tab tab = tab_layout.getTabAt(i);
// tab.setIcon(R.mipmap.ic_launcher);
tab.setCustomView(R.layout.item_tab);
}
}
}
| true |
8988_5 | package ml_model_client;
import java.io.BufferedInputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.io.BufferedOutputStream;
/**
* Connect ML Model.
*/
public class SocketClient {
/**
* Result.
*/
private String result = "error";
/**
* Connect to ML Server.
* @param data data
* @return result
*/
public String connecting(String data) {
// String address = "140.116.245.146";
String address = "127.0.0.1";
int port = 1994;
Socket client = new Socket();
InetSocketAddress isa = new InetSocketAddress(address, port);
try {
client.connect(isa, 10000);
BufferedOutputStream out = new BufferedOutputStream(client
.getOutputStream());
BufferedInputStream in = new BufferedInputStream(client
.getInputStream());
// 送出字串
out.write(data.getBytes("UTF-8"));
out.flush();
// 接收字串
byte[] buffer = new byte[1024]; // a read buffer of 5KiB
int red = client.getInputStream().read(buffer);
byte[] redData = new byte[red];
System.arraycopy(buffer, 0, redData, 0, red);
result = new String(redData,"UTF-8"); // assumption that client sends data UTF-8 encoded
out.close();
client.close();
} catch (java.io.IOException e) {
System.out.println("Socket連線有問題 !");
System.out.println("IOException :" + e.toString());
}
return result;
}
/**
* Test
* @param args system default
*/
public static void main(String[] args) {
SocketClient socketClient = new SocketClient();
System.out.println(socketClient.connecting("警察 女兒 @所作所為 爸爸 @職位 警察 兄弟@ 姐妹 表現@ 姐姐 妹妹 黑鍋 警察 身 & 所作所為 爸爸"));
}
} | Alex-CHUN-YU/Recommender-System | RecommenderSystem/app/ml_model_client/SocketClient.java | 518 | // 接收字串 | line_comment | zh-cn | package ml_model_client;
import java.io.BufferedInputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.io.BufferedOutputStream;
/**
* Connect ML Model.
*/
public class SocketClient {
/**
* Result.
*/
private String result = "error";
/**
* Connect to ML Server.
* @param data data
* @return result
*/
public String connecting(String data) {
// String address = "140.116.245.146";
String address = "127.0.0.1";
int port = 1994;
Socket client = new Socket();
InetSocketAddress isa = new InetSocketAddress(address, port);
try {
client.connect(isa, 10000);
BufferedOutputStream out = new BufferedOutputStream(client
.getOutputStream());
BufferedInputStream in = new BufferedInputStream(client
.getInputStream());
// 送出字串
out.write(data.getBytes("UTF-8"));
out.flush();
// 接收 <SUF>
byte[] buffer = new byte[1024]; // a read buffer of 5KiB
int red = client.getInputStream().read(buffer);
byte[] redData = new byte[red];
System.arraycopy(buffer, 0, redData, 0, red);
result = new String(redData,"UTF-8"); // assumption that client sends data UTF-8 encoded
out.close();
client.close();
} catch (java.io.IOException e) {
System.out.println("Socket連線有問題 !");
System.out.println("IOException :" + e.toString());
}
return result;
}
/**
* Test
* @param args system default
*/
public static void main(String[] args) {
SocketClient socketClient = new SocketClient();
System.out.println(socketClient.connecting("警察 女兒 @所作所為 爸爸 @職位 警察 兄弟@ 姐妹 表現@ 姐姐 妹妹 黑鍋 警察 身 & 所作所為 爸爸"));
}
} | false |
13996_27 | package Exp5_2;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.List;
import java.util.*;
class Word2 {
String chinese;
String[] english;
public Word2(String chinese, String e1, String e2, String e3, String e4, String e5) {
this.chinese = chinese;
english = new String[5];
english[0] = e1;
english[1] = e2;
english[2] = e3;
english[3] = e4;
english[4] = e5;
}
public String getChinese() {
return chinese;
}
public void setChinese(String chinese) {
this.chinese = chinese;
}
public String[] getEnglish() {
return english;
}
public void setEnglish(String[] english) {
this.english = english;
}
}
public class MainFrame2 extends Frame implements Runnable {
private JPanel mainpan = new JPanel();
private JPanel header = new JPanel();
private boolean isAdd = false;//设置此标签防止一题答对,多次计分
private boolean isStart = false;
private int no = 0;//题号
private int mark = 0;//答对的题目数量
private JLabel labelNo = new JLabel("第" + no + "题");
private JLabel labelMark = new JLabel("总得" + mark + "分");
private JLabel labelFeedback = new JLabel("");
private JTextField userAnswer = new JTextField();
JButton submit = new JButton("提交");
private JLabel chinese;//中文
private JLabel hint;//提示
private JLabel[] english = new JLabel[5];//英文解释选项
private LinkedList<Word2> singletest = new LinkedList<Word2>();//单选的词库
private LinkedList<Word2> multitest = new LinkedList<Word2>();//测试的词库
private HashMap<String, ArrayList<String>> dictionary = new HashMap<>();//字典,用于查找答案
public MainFrame2() {
dictionary.put("Hello", new ArrayList<String>(List.of("你好")));
dictionary.put("morning", new ArrayList<String>(List.of("早上")));
dictionary.put("nike", new ArrayList<String>(List.of("知名运动品牌(耐克)")));
dictionary.put("English", new ArrayList<String>(List.of("英国人")));
dictionary.put("Japanese", new ArrayList<String>(List.of("日本人")));
dictionary.put("Chinese", new ArrayList<String>(List.of("中国人")));
dictionary.put("Germany", new ArrayList<String>(List.of("德国人")));
dictionary.put("economic", new ArrayList<String>(List.of("经济的")));
dictionary.put("ecosystem", new ArrayList<String>(List.of("生态系统")));
dictionary.put("yesterday", new ArrayList<String>(List.of("昨天")));
dictionary.put("captor", new ArrayList<String>(List.of("捕获者")));
dictionary.put("announce", new ArrayList<String>(List.of("宣布")));
dictionary.put("demand", new ArrayList<String>(List.of("需求")));
dictionary.put("abduct", new ArrayList<String>(List.of("绑架")));
dictionary.put("capital", new ArrayList<String>(List.of("首都")));
dictionary.put("orphanage", new ArrayList<String>(List.of("孤儿院")));
dictionary.put("problem", new ArrayList<String>(List.of("问题")));
dictionary.put("spokesman", new ArrayList<String>(List.of("发言人")));
dictionary.put("constellation", new ArrayList<String>(List.of("星座")));
dictionary.put("children", new ArrayList<String>(List.of("孩子们")));
dictionary.put("fear", new ArrayList<String>(List.of("害怕", "恐惧")));
dictionary.put("expel", new ArrayList<String>(List.of("把...开除", "驱逐")));
dictionary.put("component", new ArrayList<String>(List.of("成分", "部件")));
dictionary.put("algorithm", new ArrayList<String>(List.of("算法", "运算法则")));
dictionary.put("guard", new ArrayList<String>(List.of("卫兵", "警卫", "看守")));
dictionary.put("accurate", new ArrayList<String>(List.of("准确的", "精密的")));
dictionary.put("participant", new ArrayList<String>(List.of("参加者", "参与者")));
singletest.add(new Word2("Hello", "绑架", "你好", "成分", "捕获者", "部件"));
singletest.add(new Word2("morning", "中国人", "成分", "早上", "生态系统", "宣布"));
singletest.add(new Word2("nike", "绑架", "知名运动品牌(耐克)", "中国人", "生态系统", "孤儿院"));
singletest.add(new Word2("English", "英国人", "星座", "成分", "捕获者", "生态系统"));
singletest.add(new Word2("Japanese", "静谧的", "星座", "日本人", "运算法则", "部件"));
singletest.add(new Word2("Chinese", "静谧的", "德国人", "成分", "中国人", "宣布"));
singletest.add(new Word2("Germany", "运算法则", "德国人", "成分", "运算法则", "中国人"));
singletest.add(new Word2("economic", "经济的", "静谧的", "绑架", "中国人", "部件"));
singletest.add(new Word2("ecosystem", "孤儿院", "运算法则", "宣布", "宣布", "生态系统"));
singletest.add(new Word2("yesterday", "运算法则", "昨天", "静谧的", "参加者", "中国人"));
singletest.add(new Word2("captor", "捕获者", "成分", "captor", "成分", "捕获者"));
singletest.add(new Word2("announce", "孤儿院", "宣布", "绑架", "德国人", "静谧的"));
singletest.add(new Word2("demand", "生态系统", "星座", "成分", "德国人", "部件"));
singletest.add(new Word2("abduct", "星座", "孤儿院", "捕获者", "绑架", "部件"));
singletest.add(new Word2("capital", "运算法则", "绑架", "成分", "德国人", "首都"));
singletest.add(new Word2("orphanage", "绑架", "宣布", "生态系统", "孤儿院", "中国人"));
singletest.add(new Word2("problem", "星座", "德国人", "问题", "静谧的", "运算法则"));
singletest.add(new Word2("spokeman", "生态系统", "发言人", "捕获者", "成分", "捕获者"));
singletest.add(new Word2("constellation", "星座", "静谧的", "成分", "中国人", "运算法则"));
singletest.add(new Word2("children", "捕获者", "孩子们", "绑架", "宣布", "捕获者"));
multitest.add(new Word2("fear", "中国人", "害怕", "部件", "成分", "恐惧"));
multitest.add(new Word2("expel", "把...开除", "德国人", "部件", "驱逐", "孤儿院"));
multitest.add(new Word2("component", "成分", "部件", "成分", "星座", "宣布"));
multitest.add(new Word2("algorithm", "捕获者", "算法", "星座", "运算法则", "参加者"));
multitest.add(new Word2("guard", "成分", "成分", "卫兵", "警卫", "看守"));
multitest.add(new Word2("accurate", "精密的", "准确的", "静谧的", "绑架", "孤儿院"));
multitest.add(new Word2("participant", "捕获者", "参加者", "宣布", "参与者", "星座"));
//使得单词出现随机
Collections.shuffle(singletest);
Collections.shuffle(multitest);
}
public void init() {
this.setTitle("单机版中英文单词测试程序");
//添加组件
hint = new JLabel("首先进行的是《英译中》单词测试。前五题为多选题,六至十五题为多选题。");
chinese = new JLabel("欢迎使用单词测试");
this.setLayout(new BorderLayout());
this.add(mainpan, BorderLayout.CENTER);
mainpan.setLayout(new GridLayout(8, 1));
mainpan.add(hint);
mainpan.add(chinese);
mainpan.add(userAnswer);
for (int i = 0; i < english.length; i++) {
english[i] = new JLabel();
mainpan.add(english[i]);
}
header.add(submit);
header.add(labelNo);
header.add(labelFeedback);
header.add(labelMark);
this.setResizable(false);
this.add(header, BorderLayout.SOUTH);
this.setSize(500, 600);
this.setLocation(300, 300);
this.setVisible(true);
//事件添加
//关闭程序事件
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
//用户输入事件
submit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (!isAdd && isStart) {//此题没答对过并且以及开始测试,设置此标签防止一题答对,多次计分
JTextField textField = userAnswer;
String ans = textField.getText().trim();
String regex = "\\w{1,5}"; // 匹配1-5个字符
boolean isVaild = ans.matches(regex);//判断其输入是否是”ABCDE"其中之一个或者多个
if (isVaild) {
System.out.println(ans);
boolean flag = true;
for (int i = 0; i < ans.length(); i++) {
int index = ans.charAt(i) - 'A';
//找到选项代表的英文解释
String choosed = english[index].getText().substring(4);
// 去答案库中匹配是否存在该英语解释
if (dictionary.get(chinese.getText()).contains(choosed)) {
// 正确选项设置为绿色
english[index].setForeground(Color.green);
} else {
//提示答案错误,设置为红色
english[index].setForeground(Color.red);
flag = false;
}
}
// 用户输入答案与答案库答案长度不同 为少选或多选
if (ans.length() != dictionary.get(chinese.getText()).size()) {
labelFeedback.setText("回答错误,少选或多选!");
labelMark.setText("总得" + mark + "分");
} else if (flag) { // 完全正确
if (dictionary.get(chinese.getText()).size() > 1) mark += 10;
else mark += 5;
isAdd = true;
labelFeedback.setText("回答正确!");
labelMark.setText("总得" + mark + "分");
} else { // 包含错误答案
labelFeedback.setText("回答错误!");
labelMark.setText("总得" + mark + "分");
}
}
else
userAnswer.setText("");
}
}
});
}
private void giveWord() {
try {
Thread.sleep(10000);//先休眠10s
} catch (InterruptedException e) {
e.printStackTrace();
}
isAdd = false;
labelNo.setText("第" + (++no) + "题");
labelFeedback.setText("");
labelMark.setText("总得" + mark + "分");
// 判断出题题库来源
Word2 word = (no <= 5) ? multitest.getFirst() : singletest.getFirst();
chinese.setText(word.chinese);
for (int i = 0; i < ((no <= 5) ? 5 : 4); i++) {
english[i].setText((char) ('A' + i) + ". " + word.english[i]);
english[i].setForeground(Color.BLACK);
}
//开始测试
isStart = true;
singletest.removeFirst();
multitest.removeFirst();
//清空输入,使得使用者不用手动清空上一题的选项
userAnswer.setText("");
}
public void run() {
//循环15次,出15道题目
int count = 15;
while (count-- != 0) {
giveWord();
//清空输入,使得使用者不用手动清空提交的选项
userAnswer.setText("");
}
//程序结束后,答题界面清空
isStart = false;
chinese.setText("");
hint.setText("");
for (int i = 0; i < 5; i++) {
english[i].setText("");
}
}
public static void main(String[] args) {
MainFrame2 mainFrame = new MainFrame2();
new Thread(mainFrame).start();
mainFrame.init();
}
}
| Alex-Shen1121/SZU_Learning_Resource | 计算机与软件学院/Java程序设计/实验/必实验5 GUI高级应用/MainFrame2.java | 3,352 | //程序结束后,答题界面清空 | line_comment | zh-cn | package Exp5_2;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.List;
import java.util.*;
class Word2 {
String chinese;
String[] english;
public Word2(String chinese, String e1, String e2, String e3, String e4, String e5) {
this.chinese = chinese;
english = new String[5];
english[0] = e1;
english[1] = e2;
english[2] = e3;
english[3] = e4;
english[4] = e5;
}
public String getChinese() {
return chinese;
}
public void setChinese(String chinese) {
this.chinese = chinese;
}
public String[] getEnglish() {
return english;
}
public void setEnglish(String[] english) {
this.english = english;
}
}
public class MainFrame2 extends Frame implements Runnable {
private JPanel mainpan = new JPanel();
private JPanel header = new JPanel();
private boolean isAdd = false;//设置此标签防止一题答对,多次计分
private boolean isStart = false;
private int no = 0;//题号
private int mark = 0;//答对的题目数量
private JLabel labelNo = new JLabel("第" + no + "题");
private JLabel labelMark = new JLabel("总得" + mark + "分");
private JLabel labelFeedback = new JLabel("");
private JTextField userAnswer = new JTextField();
JButton submit = new JButton("提交");
private JLabel chinese;//中文
private JLabel hint;//提示
private JLabel[] english = new JLabel[5];//英文解释选项
private LinkedList<Word2> singletest = new LinkedList<Word2>();//单选的词库
private LinkedList<Word2> multitest = new LinkedList<Word2>();//测试的词库
private HashMap<String, ArrayList<String>> dictionary = new HashMap<>();//字典,用于查找答案
public MainFrame2() {
dictionary.put("Hello", new ArrayList<String>(List.of("你好")));
dictionary.put("morning", new ArrayList<String>(List.of("早上")));
dictionary.put("nike", new ArrayList<String>(List.of("知名运动品牌(耐克)")));
dictionary.put("English", new ArrayList<String>(List.of("英国人")));
dictionary.put("Japanese", new ArrayList<String>(List.of("日本人")));
dictionary.put("Chinese", new ArrayList<String>(List.of("中国人")));
dictionary.put("Germany", new ArrayList<String>(List.of("德国人")));
dictionary.put("economic", new ArrayList<String>(List.of("经济的")));
dictionary.put("ecosystem", new ArrayList<String>(List.of("生态系统")));
dictionary.put("yesterday", new ArrayList<String>(List.of("昨天")));
dictionary.put("captor", new ArrayList<String>(List.of("捕获者")));
dictionary.put("announce", new ArrayList<String>(List.of("宣布")));
dictionary.put("demand", new ArrayList<String>(List.of("需求")));
dictionary.put("abduct", new ArrayList<String>(List.of("绑架")));
dictionary.put("capital", new ArrayList<String>(List.of("首都")));
dictionary.put("orphanage", new ArrayList<String>(List.of("孤儿院")));
dictionary.put("problem", new ArrayList<String>(List.of("问题")));
dictionary.put("spokesman", new ArrayList<String>(List.of("发言人")));
dictionary.put("constellation", new ArrayList<String>(List.of("星座")));
dictionary.put("children", new ArrayList<String>(List.of("孩子们")));
dictionary.put("fear", new ArrayList<String>(List.of("害怕", "恐惧")));
dictionary.put("expel", new ArrayList<String>(List.of("把...开除", "驱逐")));
dictionary.put("component", new ArrayList<String>(List.of("成分", "部件")));
dictionary.put("algorithm", new ArrayList<String>(List.of("算法", "运算法则")));
dictionary.put("guard", new ArrayList<String>(List.of("卫兵", "警卫", "看守")));
dictionary.put("accurate", new ArrayList<String>(List.of("准确的", "精密的")));
dictionary.put("participant", new ArrayList<String>(List.of("参加者", "参与者")));
singletest.add(new Word2("Hello", "绑架", "你好", "成分", "捕获者", "部件"));
singletest.add(new Word2("morning", "中国人", "成分", "早上", "生态系统", "宣布"));
singletest.add(new Word2("nike", "绑架", "知名运动品牌(耐克)", "中国人", "生态系统", "孤儿院"));
singletest.add(new Word2("English", "英国人", "星座", "成分", "捕获者", "生态系统"));
singletest.add(new Word2("Japanese", "静谧的", "星座", "日本人", "运算法则", "部件"));
singletest.add(new Word2("Chinese", "静谧的", "德国人", "成分", "中国人", "宣布"));
singletest.add(new Word2("Germany", "运算法则", "德国人", "成分", "运算法则", "中国人"));
singletest.add(new Word2("economic", "经济的", "静谧的", "绑架", "中国人", "部件"));
singletest.add(new Word2("ecosystem", "孤儿院", "运算法则", "宣布", "宣布", "生态系统"));
singletest.add(new Word2("yesterday", "运算法则", "昨天", "静谧的", "参加者", "中国人"));
singletest.add(new Word2("captor", "捕获者", "成分", "captor", "成分", "捕获者"));
singletest.add(new Word2("announce", "孤儿院", "宣布", "绑架", "德国人", "静谧的"));
singletest.add(new Word2("demand", "生态系统", "星座", "成分", "德国人", "部件"));
singletest.add(new Word2("abduct", "星座", "孤儿院", "捕获者", "绑架", "部件"));
singletest.add(new Word2("capital", "运算法则", "绑架", "成分", "德国人", "首都"));
singletest.add(new Word2("orphanage", "绑架", "宣布", "生态系统", "孤儿院", "中国人"));
singletest.add(new Word2("problem", "星座", "德国人", "问题", "静谧的", "运算法则"));
singletest.add(new Word2("spokeman", "生态系统", "发言人", "捕获者", "成分", "捕获者"));
singletest.add(new Word2("constellation", "星座", "静谧的", "成分", "中国人", "运算法则"));
singletest.add(new Word2("children", "捕获者", "孩子们", "绑架", "宣布", "捕获者"));
multitest.add(new Word2("fear", "中国人", "害怕", "部件", "成分", "恐惧"));
multitest.add(new Word2("expel", "把...开除", "德国人", "部件", "驱逐", "孤儿院"));
multitest.add(new Word2("component", "成分", "部件", "成分", "星座", "宣布"));
multitest.add(new Word2("algorithm", "捕获者", "算法", "星座", "运算法则", "参加者"));
multitest.add(new Word2("guard", "成分", "成分", "卫兵", "警卫", "看守"));
multitest.add(new Word2("accurate", "精密的", "准确的", "静谧的", "绑架", "孤儿院"));
multitest.add(new Word2("participant", "捕获者", "参加者", "宣布", "参与者", "星座"));
//使得单词出现随机
Collections.shuffle(singletest);
Collections.shuffle(multitest);
}
public void init() {
this.setTitle("单机版中英文单词测试程序");
//添加组件
hint = new JLabel("首先进行的是《英译中》单词测试。前五题为多选题,六至十五题为多选题。");
chinese = new JLabel("欢迎使用单词测试");
this.setLayout(new BorderLayout());
this.add(mainpan, BorderLayout.CENTER);
mainpan.setLayout(new GridLayout(8, 1));
mainpan.add(hint);
mainpan.add(chinese);
mainpan.add(userAnswer);
for (int i = 0; i < english.length; i++) {
english[i] = new JLabel();
mainpan.add(english[i]);
}
header.add(submit);
header.add(labelNo);
header.add(labelFeedback);
header.add(labelMark);
this.setResizable(false);
this.add(header, BorderLayout.SOUTH);
this.setSize(500, 600);
this.setLocation(300, 300);
this.setVisible(true);
//事件添加
//关闭程序事件
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
//用户输入事件
submit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (!isAdd && isStart) {//此题没答对过并且以及开始测试,设置此标签防止一题答对,多次计分
JTextField textField = userAnswer;
String ans = textField.getText().trim();
String regex = "\\w{1,5}"; // 匹配1-5个字符
boolean isVaild = ans.matches(regex);//判断其输入是否是”ABCDE"其中之一个或者多个
if (isVaild) {
System.out.println(ans);
boolean flag = true;
for (int i = 0; i < ans.length(); i++) {
int index = ans.charAt(i) - 'A';
//找到选项代表的英文解释
String choosed = english[index].getText().substring(4);
// 去答案库中匹配是否存在该英语解释
if (dictionary.get(chinese.getText()).contains(choosed)) {
// 正确选项设置为绿色
english[index].setForeground(Color.green);
} else {
//提示答案错误,设置为红色
english[index].setForeground(Color.red);
flag = false;
}
}
// 用户输入答案与答案库答案长度不同 为少选或多选
if (ans.length() != dictionary.get(chinese.getText()).size()) {
labelFeedback.setText("回答错误,少选或多选!");
labelMark.setText("总得" + mark + "分");
} else if (flag) { // 完全正确
if (dictionary.get(chinese.getText()).size() > 1) mark += 10;
else mark += 5;
isAdd = true;
labelFeedback.setText("回答正确!");
labelMark.setText("总得" + mark + "分");
} else { // 包含错误答案
labelFeedback.setText("回答错误!");
labelMark.setText("总得" + mark + "分");
}
}
else
userAnswer.setText("");
}
}
});
}
private void giveWord() {
try {
Thread.sleep(10000);//先休眠10s
} catch (InterruptedException e) {
e.printStackTrace();
}
isAdd = false;
labelNo.setText("第" + (++no) + "题");
labelFeedback.setText("");
labelMark.setText("总得" + mark + "分");
// 判断出题题库来源
Word2 word = (no <= 5) ? multitest.getFirst() : singletest.getFirst();
chinese.setText(word.chinese);
for (int i = 0; i < ((no <= 5) ? 5 : 4); i++) {
english[i].setText((char) ('A' + i) + ". " + word.english[i]);
english[i].setForeground(Color.BLACK);
}
//开始测试
isStart = true;
singletest.removeFirst();
multitest.removeFirst();
//清空输入,使得使用者不用手动清空上一题的选项
userAnswer.setText("");
}
public void run() {
//循环15次,出15道题目
int count = 15;
while (count-- != 0) {
giveWord();
//清空输入,使得使用者不用手动清空提交的选项
userAnswer.setText("");
}
//程序 <SUF>
isStart = false;
chinese.setText("");
hint.setText("");
for (int i = 0; i < 5; i++) {
english[i].setText("");
}
}
public static void main(String[] args) {
MainFrame2 mainFrame = new MainFrame2();
new Thread(mainFrame).start();
mainFrame.init();
}
}
| false |
55269_8 | /*
* Copyright 2017 Alex_ZHOU
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alex.vmandroid.entities;
/**
* 服务器分析返回的数据
*/
public class Analysis {
/**
* 平均分贝数
*/
private int AverageDb;
/**
* 最小分贝数
*/
private int MinDb;
/**
* 最大分贝数
*/
private int MaxDb;
/**
* 记录时长
*/
private int RecordMinter;
/**
* 记录的总次数
*/
private int Times;
/**
* 0 -20 分贝 很静、几乎感觉不到
*/
private int _20Times;
/**
* 20 -40 分贝 安静、犹如轻声絮语
*/
private int _40Times;
/**
* 40 -60 分贝 一般、普通室内谈话
*/
private int _60Times;
/**
* 60 -70 分贝 吵闹、有损神经;
*/
private int _70Times;
/**
* 70 -90 分贝 很吵、神经细胞受到破坏
*/
private int _90Times;
/**
* 90 -100 分贝 吵闹加剧、听力受损
*/
private int _100Times;
/**
* 100 -120 分贝 难以忍受、呆一分钟即暂时致聋
*/
private int _120Times;
/**
* 120分贝以上 极度聋或全聋
*/
private int _120UpTimes;
private String Analysis;
public int getAverageDb() {
return AverageDb;
}
public void setAverageDb(int averageDb) {
AverageDb = averageDb;
}
public int getMinDb() {
return MinDb;
}
public void setMinDb(int minDb) {
MinDb = minDb;
}
public int getMaxDb() {
return MaxDb;
}
public void setMaxDb(int maxDb) {
MaxDb = maxDb;
}
public int getRecordMinter() {
return RecordMinter;
}
public void setRecordMinter(int recordMinter) {
RecordMinter = recordMinter;
}
public int getTimes() {
return Times;
}
public void setTimes(int times) {
Times = times;
}
public int get_20Times() {
return _20Times;
}
public void set_20Times(int _20Times) {
this._20Times = _20Times;
}
public int get_40Times() {
return _40Times;
}
public void set_40Times(int _40Times) {
this._40Times = _40Times;
}
public int get_60Times() {
return _60Times;
}
public void set_60Times(int _60Times) {
this._60Times = _60Times;
}
public int get_70Times() {
return _70Times;
}
public void set_70Times(int _70Times) {
this._70Times = _70Times;
}
public int get_90Times() {
return _90Times;
}
public void set_90Times(int _90Times) {
this._90Times = _90Times;
}
public int get_100Times() {
return _100Times;
}
public void set_100Times(int _100Times) {
this._100Times = _100Times;
}
public int get_120Times() {
return _120Times;
}
public void set_120Times(int _120Times) {
this._120Times = _120Times;
}
public int get_120UpTimes() {
return _120UpTimes;
}
public void set_120UpTimes(int _120UpTimes) {
this._120UpTimes = _120UpTimes;
}
public String getAnalysis() {
return Analysis;
}
public void setAnalysis(String analysis) {
Analysis = analysis;
}
}
| Alex-ZHOU/VMAndroid | app/src/main/java/com/alex/vmandroid/entities/Analysis.java | 1,298 | /**
* 20 -40 分贝 安静、犹如轻声絮语
*/ | block_comment | zh-cn | /*
* Copyright 2017 Alex_ZHOU
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alex.vmandroid.entities;
/**
* 服务器分析返回的数据
*/
public class Analysis {
/**
* 平均分贝数
*/
private int AverageDb;
/**
* 最小分贝数
*/
private int MinDb;
/**
* 最大分贝数
*/
private int MaxDb;
/**
* 记录时长
*/
private int RecordMinter;
/**
* 记录的总次数
*/
private int Times;
/**
* 0 -20 分贝 很静、几乎感觉不到
*/
private int _20Times;
/**
* 20 <SUF>*/
private int _40Times;
/**
* 40 -60 分贝 一般、普通室内谈话
*/
private int _60Times;
/**
* 60 -70 分贝 吵闹、有损神经;
*/
private int _70Times;
/**
* 70 -90 分贝 很吵、神经细胞受到破坏
*/
private int _90Times;
/**
* 90 -100 分贝 吵闹加剧、听力受损
*/
private int _100Times;
/**
* 100 -120 分贝 难以忍受、呆一分钟即暂时致聋
*/
private int _120Times;
/**
* 120分贝以上 极度聋或全聋
*/
private int _120UpTimes;
private String Analysis;
public int getAverageDb() {
return AverageDb;
}
public void setAverageDb(int averageDb) {
AverageDb = averageDb;
}
public int getMinDb() {
return MinDb;
}
public void setMinDb(int minDb) {
MinDb = minDb;
}
public int getMaxDb() {
return MaxDb;
}
public void setMaxDb(int maxDb) {
MaxDb = maxDb;
}
public int getRecordMinter() {
return RecordMinter;
}
public void setRecordMinter(int recordMinter) {
RecordMinter = recordMinter;
}
public int getTimes() {
return Times;
}
public void setTimes(int times) {
Times = times;
}
public int get_20Times() {
return _20Times;
}
public void set_20Times(int _20Times) {
this._20Times = _20Times;
}
public int get_40Times() {
return _40Times;
}
public void set_40Times(int _40Times) {
this._40Times = _40Times;
}
public int get_60Times() {
return _60Times;
}
public void set_60Times(int _60Times) {
this._60Times = _60Times;
}
public int get_70Times() {
return _70Times;
}
public void set_70Times(int _70Times) {
this._70Times = _70Times;
}
public int get_90Times() {
return _90Times;
}
public void set_90Times(int _90Times) {
this._90Times = _90Times;
}
public int get_100Times() {
return _100Times;
}
public void set_100Times(int _100Times) {
this._100Times = _100Times;
}
public int get_120Times() {
return _120Times;
}
public void set_120Times(int _120Times) {
this._120Times = _120Times;
}
public int get_120UpTimes() {
return _120UpTimes;
}
public void set_120UpTimes(int _120UpTimes) {
this._120UpTimes = _120UpTimes;
}
public String getAnalysis() {
return Analysis;
}
public void setAnalysis(String analysis) {
Analysis = analysis;
}
}
| true |
40303_1 | package CommonAPI;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexDemo {
public static void main(String[] args) {
/* 有如下文本: “当好中国式现代化建设的坚定行动派、实干家”,
这是习近平总书记提出的明确要求。全国两会结束不到一周,习近平总书记赴湖南考察,
并在长沙主持召开新时代推动中部地区崛起座谈会,强调“地方党委和政府要扛起主体责任,
坚决贯彻党中央决策部署,推动重点工作任务、重大改革事项落实落地”。*/
//要统计国字出现的次数
String str = "当好中国式现代化建设的坚定行动派、实干家,这是习近平总书记提出的明确要求。全国两会结束不到一周,习近平总书记赴湖南考察,并在长沙主持召开新时代推动中部地区崛起座谈会,强调“地方党委和政府要扛起主体责任,坚决贯彻党中央决策部署,推动重点工作任务、重大改革事项落实落地”。";
//Pattern 是正则表达式
//Matcher 文本匹配器,作用按照正则表达式的规则从头开始读取字符串
Pattern p = Pattern.compile("中");
Matcher m = p.matcher(str);
boolean b = m.find();
int count = 0;
String s = m.group();
System.out.println(s);
while (b) {
count++;
b = m.find();
}
System.out.println("中字出现的次数为:" + count);
//下面是正则表达式的一些基本规则
//部分匹配但是只取出来完全匹配的部分
String str1 = "Java的版本有:Java8、Java11、Java17";
String regex = "Java(?=8|11|17)";
Pattern pp = Pattern.compile(regex); //编译正则表达式
Matcher mm = pp.matcher(str1); //创建匹配器
while (mm.find()) {
System.out.println(mm.group());
}
//忽略大小写的匹配
String str2 = "Java的版本有:JAVa8、Java11、Java17";
String regex2 = "((?i)java)";
Pattern p2 = Pattern.compile(regex2);
Matcher m2 = p2.matcher(str2);
while (m2.find()) {
System.out.println(m2.group());
}
}
}
| Alex-hwang/AdvancedPart | src/CommonAPI/RegexDemo.java | 664 | //要统计国字出现的次数 | line_comment | zh-cn | package CommonAPI;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexDemo {
public static void main(String[] args) {
/* 有如下文本: “当好中国式现代化建设的坚定行动派、实干家”,
这是习近平总书记提出的明确要求。全国两会结束不到一周,习近平总书记赴湖南考察,
并在长沙主持召开新时代推动中部地区崛起座谈会,强调“地方党委和政府要扛起主体责任,
坚决贯彻党中央决策部署,推动重点工作任务、重大改革事项落实落地”。*/
//要统 <SUF>
String str = "当好中国式现代化建设的坚定行动派、实干家,这是习近平总书记提出的明确要求。全国两会结束不到一周,习近平总书记赴湖南考察,并在长沙主持召开新时代推动中部地区崛起座谈会,强调“地方党委和政府要扛起主体责任,坚决贯彻党中央决策部署,推动重点工作任务、重大改革事项落实落地”。";
//Pattern 是正则表达式
//Matcher 文本匹配器,作用按照正则表达式的规则从头开始读取字符串
Pattern p = Pattern.compile("中");
Matcher m = p.matcher(str);
boolean b = m.find();
int count = 0;
String s = m.group();
System.out.println(s);
while (b) {
count++;
b = m.find();
}
System.out.println("中字出现的次数为:" + count);
//下面是正则表达式的一些基本规则
//部分匹配但是只取出来完全匹配的部分
String str1 = "Java的版本有:Java8、Java11、Java17";
String regex = "Java(?=8|11|17)";
Pattern pp = Pattern.compile(regex); //编译正则表达式
Matcher mm = pp.matcher(str1); //创建匹配器
while (mm.find()) {
System.out.println(mm.group());
}
//忽略大小写的匹配
String str2 = "Java的版本有:JAVa8、Java11、Java17";
String regex2 = "((?i)java)";
Pattern p2 = Pattern.compile(regex2);
Matcher m2 = p2.matcher(str2);
while (m2.find()) {
System.out.println(m2.group());
}
}
}
| false |
5480_29 | package cartoland.messages;
import cartoland.utilities.Algorithm;
import cartoland.utilities.IDs;
import cartoland.utilities.RegularExpressions;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.entities.channel.concrete.Category;
import net.dv8tion.jda.api.entities.channel.middleman.MessageChannel;
import net.dv8tion.jda.api.entities.emoji.Emoji;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import java.util.Map;
import java.util.Set;
/**
* {@code BotCanTalkChannelMessage} is a listener that triggers when a user types anything in any channel that the
* bot can talk. This class is in an array in {@link cartoland.events.MessageEvent}.
*
* @since 2.0
* @author Alex Cai
*/
public class BotCanTalkChannelMessage implements IMessage
{
private final String[] replyACMention =
{
"父親,您找我有事嗎?",
"向父親請安,父親您好嗎?",
"爹,您好呀。",
"聽候您差遣。",
"父親,無論您需要什麼幫助,我都會全力以赴!", //由 brick-bk 新增
"父親,您辛苦了,工作忙碌之餘,也請您別忘了多休息保護眼睛!"//Add by Champsing
};
private final String[] replyMegaMention =
{
"臣向陛下請安",
"陛下萬福金安",
"陛下今日可好?",
"願陛下萬壽無疆,國泰民安,天下太平。", //由 brick-bk 新增
"祝陛下萬歲,萬歲,萬萬歲!", //由 brick-bk 新增
//Add by Champsing
"微臣向皇上請安",
"皇上龍體安康",
"微臣參見陛下",
"皇上威震四海、聲赫五洲"
};
private final String[] replyMention =
{
"你媽沒教你不要亂tag人嗎?",
"你媽知道你都在Discord亂tag人嗎?",
"勸你小心點,我認識這群群主。",
"tag我都小雞雞。",
"不要耍智障好不好。",
"你看看,就是有像你這種臭俗辣。",
"吃屎比較快。",
"你是怎麼樣?",
"在那叫什麼?",
"https://imgur.com/n1rEBO9", //在那叫什麼
"我知道我很帥,不用一直tag我",
"tag我該女裝負責吧。",
"沒梗的人才會整天tag機器人。",
"再吵,就把你丟到亞馬遜上面賣。",
"你除了tag機器人外沒別的事情好做嗎?",
"有病要去看醫生。",
"<:ping:" + IDs.PING_EMOJI_ID + '>',
"你凡是有tag我被我記起來的對不對?我一定到現場打你,一定打你!",
"沒關係你們再繼續亂tag沒關係,逮到一個、揍一個,一定、一定把你鼻樑打歪。",
"哪裡來的小孩子,家教差成這樣。",
"老子瘋狗的外號Maps群時期就有啦!",
"沒被打過是不是?",
"tag機器人是不好的行為,小朋友不要學。",
"上帝把智慧撒向人間的時候你撐了把傘嗎?",
"https://imgur.com/xxZVQvB", //你到別的地方去耍笨好不好
"小米格們也都別忘了Pick Me!\n在GitHub 點個星星 按個 讚。",
"如果大家喜歡這種機器人的話,別忘了點擊GitHub上面那個,大大~的星星!讓我知道。",
"你再tag我啊,再tag啊,沒被禁言過是不是?", //由 brick-bk 新增,經 Alex Cai 大幅修改
"豎子,不足與謀。"//死小孩,沒話跟你講。 Added by Champsing
};
private final String[] megumin =
{
"☆めぐみん大好き!☆",
"☆めぐみんは最高だ!☆",
"☆めぐみん俺の嫁!☆"
};
private final String[] fbi =
{
"https://tenor.com/view/f-bi-raid-swat-gif-11500735",
"https://tenor.com/view/fbi-calling-tom-gif-12699976",
"https://tenor.com/view/fbi-swat-busted-police-open-up-gif-16928811",
"https://tenor.com/view/fbi-swat-police-entry-attack-gif-16037524",
"https://imgur.com/GLElBwY", //電話在那裡
"https://imgur.com/Aax1R2U", //我要走向電話
"https://imgur.com/gPlBEMV" //我越來越接近電話了
};
private final Set<Long> canTalkCategories = Set.of(IDs.GENERAL_CATEGORY_ID, IDs.FORUM_CATEGORY_ID, IDs.VOICE_CATEGORY_ID, IDs.DANGEROUS_CATEGORY_ID);
private final Map<String, String[]> keywords =
Map.of("早安", new String[]{ "早上好中國 現在我有 Bing Chilling","早上好創聯 現在我有 Bing Chilling","道聲「早安」\n卻又讓我做了夢\n自然而然的生活方式不是很好嗎?" },
"午安", new String[]{ "午安你好,記得天下沒有白吃的午餐" }, //後面那句由 brick-bk 新增
"晚安", new String[]{ "那我也要睡啦","https://tenor.com/view/food-goodnight-gif-18740706","https://tenor.com/view/kfc-fried-chicken-kentucky-fried-chicken-fast-food-gif-26996460","https://tenor.com/view/burger-butter-cooking-gif-3340446" },
"安安", new String[]{ "安安你好幾歲住哪","安安各位大家好","https://static.wikia.nocookie.net/theamazingworldofgumball/images/1/10/Season_3_Anais.png/" });
@Override
public boolean messageCondition(MessageReceivedEvent event)
{
if (!event.isFromGuild()) //是私訊
return true; //私訊可以說話
Category category = event.getMessage().getCategory(); //嘗試從訊息獲取類別
return category != null && canTalkCategories.contains(category.getIdLong()); //只在特定類別說話
}
@Override
public void messageProcess(MessageReceivedEvent event)
{
Message message = event.getMessage(); //獲取訊息
String rawMessage = message.getContentRaw(); //獲取訊息字串
MessageChannel channel = message.getChannel();
User author = event.getAuthor();
if (message.getMentions().isMentioned(event.getJDA().getSelfUser(), Message.MentionType.USER, Message.MentionType.ROLE)) //有人tag機器人
{
long userID = author.getIdLong();
long channelID = channel.getIdLong();
//不要再想著用switch了 Java的switch不支援long
if (userID == IDs.AC_ID) //是AC
message.reply(Algorithm.randomElement(replyACMention)).mentionRepliedUser(false).queue();
else if (userID == IDs.MEGA_ID) //是米格
message.reply(Algorithm.randomElement(replyMegaMention)).mentionRepliedUser(false).queue();
else //是其他人
{
if (channelID == IDs.BOT_CHANNEL_ID || channelID == IDs.UNDERGROUND_CHANNEL_ID) //如果頻道在機器人或地下 就正常地回傳replyMention
message.reply(Algorithm.randomElement(replyMention)).mentionRepliedUser(false).queue();
else //在其他地方ping就固定加一個ping的emoji
message.addReaction(Emoji.fromCustom("ping", IDs.PING_EMOJI_ID, false)).queue();
}
}
int rawMessageLength = rawMessage.length(); //訊息的字數
switch (rawMessageLength)
{
case 0: //只有檔案或貼圖
case 1: //只打一個字
return; //沒有必要執行下面那些檢測
case 2: //用字串長度去最佳化 注意keywords的keys若出現2以外的長度 那這個條件就要修改
String[] sendStrings = keywords.get(rawMessage); //尋找完全相同的字串
if (sendStrings != null) //如果找到了
{
channel.sendMessage(Algorithm.randomElement(sendStrings)).queue();
return; //keywords內的字串 沒有一個包含了下面的內容 所以底下的可直接不執行
}
break;
case 3: //用字串長度去最佳化
if ("lol".equalsIgnoreCase(rawMessage))
{
channel.sendMessage("LOL").queue();
return; //在這之下的if們 全都不可能通過
}
if ("omg".equalsIgnoreCase(rawMessage))
{
channel.sendMessage("OMG").queue();
return; //在這之下的if們 全都不可能通過
}
if ("owo".equalsIgnoreCase(rawMessage))
{
channel.sendMessage("OwO").queue();
return; //在這之下的if們 全都不可能通過
}
if ("ouo".equalsIgnoreCase(rawMessage))
{
channel.sendMessage("OuO").queue();
return; //在這之下的if們 全都不可能通過
}
break;
case 4: //用字串長度去最佳化
if ("oeur".equalsIgnoreCase(rawMessage) || "芋圓柚子".equals(rawMessage))
{
channel.sendMessage(
"""
阿神的超神奇馬桶可以激發他的無限靈感
阿謙和阿神的關係到現在還是非常的不明
可愛的小夏狂搶麥最後生氣的都是巧克力
誰說阿晋拿下眼鏡之後傲嬌屬性就會轉移
阿晋泡麵加上狗子便當
再加一顆梅子就可以吃
全全的傳說傳了好幾年
半半要不要再進化一次呢
梅子空姐的廣播跳下飛機後再聽一次
丹丹的最強絕技就是永遠保持於狀況外
""").queue();
return;
}
if ("鬼島交通".equals(rawMessage)) //Added by Champsing
{
channel.sendMessage("https://memeprod.sgp1.digitaloceanspaces.com/user-wtf/1651071890313.jpg").queue();
return;
}
break;
}
if (rawMessage.contains("惠惠") || rawMessage.contains("めぐみん") || (rawMessageLength >= 7 && RegularExpressions.MEGUMIN_REGEX.matcher(rawMessage).matches()))
channel.sendMessage(Algorithm.randomElement(megumin)).queue();
if (rawMessage.contains("聰明"))
channel.sendMessage("https://tenor.com/view/galaxy-brain-meme-gif-25947987").queue();
if (rawMessage.contains("賺爛"))
channel.sendMessage("https://tenor.com/view/反正我很閒-賺爛了-gif-25311690").queue();
if (rawMessage.contains("蘿莉") || rawMessage.contains("羅莉"))
channel.sendMessage(Algorithm.randomElement(fbi)).queue();
if (rawMessage.contains("無情"))
channel.sendMessage("太無情了" + author.getEffectiveName() + ",你真的太無情了!").queue();
if (rawMessage.contains("閃現"))
channel.sendMessage("這什麼到底什麼閃現齁齁齁齁齁").queue();
if (rawMessage.contains("興奮"))
channel.sendMessage("https://tenor.com/view/excited-gif-8604873").queue();
if (rawMessage.contains("原神") && rawMessage.contains("啟動"))
channel.sendMessage("https://imgur.com/3LQqer3").queue();
}
} | AlexCai2019/Cartoland | src/main/java/cartoland/messages/BotCanTalkChannelMessage.java | 3,617 | //是米格 | line_comment | zh-cn | package cartoland.messages;
import cartoland.utilities.Algorithm;
import cartoland.utilities.IDs;
import cartoland.utilities.RegularExpressions;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.entities.channel.concrete.Category;
import net.dv8tion.jda.api.entities.channel.middleman.MessageChannel;
import net.dv8tion.jda.api.entities.emoji.Emoji;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import java.util.Map;
import java.util.Set;
/**
* {@code BotCanTalkChannelMessage} is a listener that triggers when a user types anything in any channel that the
* bot can talk. This class is in an array in {@link cartoland.events.MessageEvent}.
*
* @since 2.0
* @author Alex Cai
*/
public class BotCanTalkChannelMessage implements IMessage
{
private final String[] replyACMention =
{
"父親,您找我有事嗎?",
"向父親請安,父親您好嗎?",
"爹,您好呀。",
"聽候您差遣。",
"父親,無論您需要什麼幫助,我都會全力以赴!", //由 brick-bk 新增
"父親,您辛苦了,工作忙碌之餘,也請您別忘了多休息保護眼睛!"//Add by Champsing
};
private final String[] replyMegaMention =
{
"臣向陛下請安",
"陛下萬福金安",
"陛下今日可好?",
"願陛下萬壽無疆,國泰民安,天下太平。", //由 brick-bk 新增
"祝陛下萬歲,萬歲,萬萬歲!", //由 brick-bk 新增
//Add by Champsing
"微臣向皇上請安",
"皇上龍體安康",
"微臣參見陛下",
"皇上威震四海、聲赫五洲"
};
private final String[] replyMention =
{
"你媽沒教你不要亂tag人嗎?",
"你媽知道你都在Discord亂tag人嗎?",
"勸你小心點,我認識這群群主。",
"tag我都小雞雞。",
"不要耍智障好不好。",
"你看看,就是有像你這種臭俗辣。",
"吃屎比較快。",
"你是怎麼樣?",
"在那叫什麼?",
"https://imgur.com/n1rEBO9", //在那叫什麼
"我知道我很帥,不用一直tag我",
"tag我該女裝負責吧。",
"沒梗的人才會整天tag機器人。",
"再吵,就把你丟到亞馬遜上面賣。",
"你除了tag機器人外沒別的事情好做嗎?",
"有病要去看醫生。",
"<:ping:" + IDs.PING_EMOJI_ID + '>',
"你凡是有tag我被我記起來的對不對?我一定到現場打你,一定打你!",
"沒關係你們再繼續亂tag沒關係,逮到一個、揍一個,一定、一定把你鼻樑打歪。",
"哪裡來的小孩子,家教差成這樣。",
"老子瘋狗的外號Maps群時期就有啦!",
"沒被打過是不是?",
"tag機器人是不好的行為,小朋友不要學。",
"上帝把智慧撒向人間的時候你撐了把傘嗎?",
"https://imgur.com/xxZVQvB", //你到別的地方去耍笨好不好
"小米格們也都別忘了Pick Me!\n在GitHub 點個星星 按個 讚。",
"如果大家喜歡這種機器人的話,別忘了點擊GitHub上面那個,大大~的星星!讓我知道。",
"你再tag我啊,再tag啊,沒被禁言過是不是?", //由 brick-bk 新增,經 Alex Cai 大幅修改
"豎子,不足與謀。"//死小孩,沒話跟你講。 Added by Champsing
};
private final String[] megumin =
{
"☆めぐみん大好き!☆",
"☆めぐみんは最高だ!☆",
"☆めぐみん俺の嫁!☆"
};
private final String[] fbi =
{
"https://tenor.com/view/f-bi-raid-swat-gif-11500735",
"https://tenor.com/view/fbi-calling-tom-gif-12699976",
"https://tenor.com/view/fbi-swat-busted-police-open-up-gif-16928811",
"https://tenor.com/view/fbi-swat-police-entry-attack-gif-16037524",
"https://imgur.com/GLElBwY", //電話在那裡
"https://imgur.com/Aax1R2U", //我要走向電話
"https://imgur.com/gPlBEMV" //我越來越接近電話了
};
private final Set<Long> canTalkCategories = Set.of(IDs.GENERAL_CATEGORY_ID, IDs.FORUM_CATEGORY_ID, IDs.VOICE_CATEGORY_ID, IDs.DANGEROUS_CATEGORY_ID);
private final Map<String, String[]> keywords =
Map.of("早安", new String[]{ "早上好中國 現在我有 Bing Chilling","早上好創聯 現在我有 Bing Chilling","道聲「早安」\n卻又讓我做了夢\n自然而然的生活方式不是很好嗎?" },
"午安", new String[]{ "午安你好,記得天下沒有白吃的午餐" }, //後面那句由 brick-bk 新增
"晚安", new String[]{ "那我也要睡啦","https://tenor.com/view/food-goodnight-gif-18740706","https://tenor.com/view/kfc-fried-chicken-kentucky-fried-chicken-fast-food-gif-26996460","https://tenor.com/view/burger-butter-cooking-gif-3340446" },
"安安", new String[]{ "安安你好幾歲住哪","安安各位大家好","https://static.wikia.nocookie.net/theamazingworldofgumball/images/1/10/Season_3_Anais.png/" });
@Override
public boolean messageCondition(MessageReceivedEvent event)
{
if (!event.isFromGuild()) //是私訊
return true; //私訊可以說話
Category category = event.getMessage().getCategory(); //嘗試從訊息獲取類別
return category != null && canTalkCategories.contains(category.getIdLong()); //只在特定類別說話
}
@Override
public void messageProcess(MessageReceivedEvent event)
{
Message message = event.getMessage(); //獲取訊息
String rawMessage = message.getContentRaw(); //獲取訊息字串
MessageChannel channel = message.getChannel();
User author = event.getAuthor();
if (message.getMentions().isMentioned(event.getJDA().getSelfUser(), Message.MentionType.USER, Message.MentionType.ROLE)) //有人tag機器人
{
long userID = author.getIdLong();
long channelID = channel.getIdLong();
//不要再想著用switch了 Java的switch不支援long
if (userID == IDs.AC_ID) //是AC
message.reply(Algorithm.randomElement(replyACMention)).mentionRepliedUser(false).queue();
else if (userID == IDs.MEGA_ID) //是米 <SUF>
message.reply(Algorithm.randomElement(replyMegaMention)).mentionRepliedUser(false).queue();
else //是其他人
{
if (channelID == IDs.BOT_CHANNEL_ID || channelID == IDs.UNDERGROUND_CHANNEL_ID) //如果頻道在機器人或地下 就正常地回傳replyMention
message.reply(Algorithm.randomElement(replyMention)).mentionRepliedUser(false).queue();
else //在其他地方ping就固定加一個ping的emoji
message.addReaction(Emoji.fromCustom("ping", IDs.PING_EMOJI_ID, false)).queue();
}
}
int rawMessageLength = rawMessage.length(); //訊息的字數
switch (rawMessageLength)
{
case 0: //只有檔案或貼圖
case 1: //只打一個字
return; //沒有必要執行下面那些檢測
case 2: //用字串長度去最佳化 注意keywords的keys若出現2以外的長度 那這個條件就要修改
String[] sendStrings = keywords.get(rawMessage); //尋找完全相同的字串
if (sendStrings != null) //如果找到了
{
channel.sendMessage(Algorithm.randomElement(sendStrings)).queue();
return; //keywords內的字串 沒有一個包含了下面的內容 所以底下的可直接不執行
}
break;
case 3: //用字串長度去最佳化
if ("lol".equalsIgnoreCase(rawMessage))
{
channel.sendMessage("LOL").queue();
return; //在這之下的if們 全都不可能通過
}
if ("omg".equalsIgnoreCase(rawMessage))
{
channel.sendMessage("OMG").queue();
return; //在這之下的if們 全都不可能通過
}
if ("owo".equalsIgnoreCase(rawMessage))
{
channel.sendMessage("OwO").queue();
return; //在這之下的if們 全都不可能通過
}
if ("ouo".equalsIgnoreCase(rawMessage))
{
channel.sendMessage("OuO").queue();
return; //在這之下的if們 全都不可能通過
}
break;
case 4: //用字串長度去最佳化
if ("oeur".equalsIgnoreCase(rawMessage) || "芋圓柚子".equals(rawMessage))
{
channel.sendMessage(
"""
阿神的超神奇馬桶可以激發他的無限靈感
阿謙和阿神的關係到現在還是非常的不明
可愛的小夏狂搶麥最後生氣的都是巧克力
誰說阿晋拿下眼鏡之後傲嬌屬性就會轉移
阿晋泡麵加上狗子便當
再加一顆梅子就可以吃
全全的傳說傳了好幾年
半半要不要再進化一次呢
梅子空姐的廣播跳下飛機後再聽一次
丹丹的最強絕技就是永遠保持於狀況外
""").queue();
return;
}
if ("鬼島交通".equals(rawMessage)) //Added by Champsing
{
channel.sendMessage("https://memeprod.sgp1.digitaloceanspaces.com/user-wtf/1651071890313.jpg").queue();
return;
}
break;
}
if (rawMessage.contains("惠惠") || rawMessage.contains("めぐみん") || (rawMessageLength >= 7 && RegularExpressions.MEGUMIN_REGEX.matcher(rawMessage).matches()))
channel.sendMessage(Algorithm.randomElement(megumin)).queue();
if (rawMessage.contains("聰明"))
channel.sendMessage("https://tenor.com/view/galaxy-brain-meme-gif-25947987").queue();
if (rawMessage.contains("賺爛"))
channel.sendMessage("https://tenor.com/view/反正我很閒-賺爛了-gif-25311690").queue();
if (rawMessage.contains("蘿莉") || rawMessage.contains("羅莉"))
channel.sendMessage(Algorithm.randomElement(fbi)).queue();
if (rawMessage.contains("無情"))
channel.sendMessage("太無情了" + author.getEffectiveName() + ",你真的太無情了!").queue();
if (rawMessage.contains("閃現"))
channel.sendMessage("這什麼到底什麼閃現齁齁齁齁齁").queue();
if (rawMessage.contains("興奮"))
channel.sendMessage("https://tenor.com/view/excited-gif-8604873").queue();
if (rawMessage.contains("原神") && rawMessage.contains("啟動"))
channel.sendMessage("https://imgur.com/3LQqer3").queue();
}
} | true |
38876_7 | package sample;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.SplitPane;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import javax.swing.*;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ControllerLoginPatient {
@FXML
private Button btn_login;
@FXML
private Button btn_back;
@FXML
private TextField field_number;
@FXML
private TextField field_password;
public static String loginedPid; //静态字符串,用于controller之间传递参数
public String getLoginedPid(){
return loginedPid;
}
//回车键登录
public void onEnter(){
on_btn_login_clicked();
}
//病人登录
public void on_btn_login_clicked(){
Connection connection=new MySQLConnector().connection();
if(connection==null){
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setHeaderText("连接数据库失败!");
alert.showAndWait();
}
else{
if(field_number.getText().equals("")){ //编号输入为空
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setHeaderText("病人编号不可为空");
alert.showAndWait();
return;
}
try {
String sql="select * from patient where pid=?";
PreparedStatement preparedStatement=connection.prepareStatement(sql);
preparedStatement.setString(1,field_number.getText());
ResultSet rs=preparedStatement.executeQuery();
if(!(rs.next())){ //找不到编号
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setHeaderText("找不到该编号");
alert.showAndWait();
return;
}
String realPassword=rs.getString("password");
String inputPassword=field_password.getText();
if(!(realPassword.equals(inputPassword))) {//密码错误
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setHeaderText("密码错误");
alert.showAndWait();}
else{ //登录成功,更新登录日期
String pid=rs.getString("pid");
loginedPid=pid;
String currentTime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); //获取登陆时间
String sql2="update patient set last_login_datetime =? where pid=?";
preparedStatement=connection.prepareStatement(sql2);
preparedStatement.setString(1,currentTime);
preparedStatement.setString(2,pid);
preparedStatement.executeUpdate();
Stage currentStage=(Stage)btn_login.getScene().getWindow();
currentStage.close(); //关闭当前窗口
SplitPane root=FXMLLoader.load(getClass().getResource("RegisterPatient.fxml")); //转到挂号界面
Stage newStage=new Stage();
newStage.setTitle("病人挂号");
newStage.setScene(new Scene(root));
newStage.show();
preparedStatement.close();
connection.close();
}
}
catch (SQLException | IOException e){
e.printStackTrace();
}
}
}
//返回
public void on_btn_back_clicked() throws IOException {
Stage currentStage=(Stage)btn_login.getScene().getWindow();
currentStage.close(); //关闭当前窗口
SplitPane root=FXMLLoader.load(getClass().getResource("Login.fxml"));
Stage newStage=new Stage();
newStage.setTitle("登录");
newStage.setScene(new Scene(root));
newStage.show();
}
}
| AlexFanw/HUSTER-CS | Java实验/java实验二/hospital/src/sample/ControllerLoginPatient.java | 878 | //获取登陆时间 | line_comment | zh-cn | package sample;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.SplitPane;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import javax.swing.*;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ControllerLoginPatient {
@FXML
private Button btn_login;
@FXML
private Button btn_back;
@FXML
private TextField field_number;
@FXML
private TextField field_password;
public static String loginedPid; //静态字符串,用于controller之间传递参数
public String getLoginedPid(){
return loginedPid;
}
//回车键登录
public void onEnter(){
on_btn_login_clicked();
}
//病人登录
public void on_btn_login_clicked(){
Connection connection=new MySQLConnector().connection();
if(connection==null){
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setHeaderText("连接数据库失败!");
alert.showAndWait();
}
else{
if(field_number.getText().equals("")){ //编号输入为空
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setHeaderText("病人编号不可为空");
alert.showAndWait();
return;
}
try {
String sql="select * from patient where pid=?";
PreparedStatement preparedStatement=connection.prepareStatement(sql);
preparedStatement.setString(1,field_number.getText());
ResultSet rs=preparedStatement.executeQuery();
if(!(rs.next())){ //找不到编号
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setHeaderText("找不到该编号");
alert.showAndWait();
return;
}
String realPassword=rs.getString("password");
String inputPassword=field_password.getText();
if(!(realPassword.equals(inputPassword))) {//密码错误
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setHeaderText("密码错误");
alert.showAndWait();}
else{ //登录成功,更新登录日期
String pid=rs.getString("pid");
loginedPid=pid;
String currentTime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); //获取 <SUF>
String sql2="update patient set last_login_datetime =? where pid=?";
preparedStatement=connection.prepareStatement(sql2);
preparedStatement.setString(1,currentTime);
preparedStatement.setString(2,pid);
preparedStatement.executeUpdate();
Stage currentStage=(Stage)btn_login.getScene().getWindow();
currentStage.close(); //关闭当前窗口
SplitPane root=FXMLLoader.load(getClass().getResource("RegisterPatient.fxml")); //转到挂号界面
Stage newStage=new Stage();
newStage.setTitle("病人挂号");
newStage.setScene(new Scene(root));
newStage.show();
preparedStatement.close();
connection.close();
}
}
catch (SQLException | IOException e){
e.printStackTrace();
}
}
}
//返回
public void on_btn_back_clicked() throws IOException {
Stage currentStage=(Stage)btn_login.getScene().getWindow();
currentStage.close(); //关闭当前窗口
SplitPane root=FXMLLoader.load(getClass().getResource("Login.fxml"));
Stage newStage=new Stage();
newStage.setTitle("登录");
newStage.setScene(new Scene(root));
newStage.show();
}
}
| false |
21010_3 | package com.swagger.offline.model;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* @version V1.0
* @Title:
* @ClassName: User.java
* @Description:
* @Copyright 2016-2018 - Powered By 研发中心
* @author: 王延飞
* @date: 2018-01-22 16:06
*/
@ApiModel(value = "User", description = "用户信息描述")
public class User {
/**
* 学号
*/
@ApiModelProperty("证件号")
private int id;
/**
* 姓名
*/
@ApiModelProperty("姓名")
private String name;
/**
* 年龄
*/
@ApiModelProperty("年龄")
private int age;
/**
* 性别
*/
@ApiModelProperty("性别")
private String sex;
/**
* 住址
*/
@ApiModelProperty("家庭住址")
private String address;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
", address='" + address + '\'' +
'}';
}
}
| AlexFly666/SwaggerOfflineDoc | src/main/java/com/swagger/offline/model/User.java | 467 | /**
* 年龄
*/ | block_comment | zh-cn | package com.swagger.offline.model;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* @version V1.0
* @Title:
* @ClassName: User.java
* @Description:
* @Copyright 2016-2018 - Powered By 研发中心
* @author: 王延飞
* @date: 2018-01-22 16:06
*/
@ApiModel(value = "User", description = "用户信息描述")
public class User {
/**
* 学号
*/
@ApiModelProperty("证件号")
private int id;
/**
* 姓名
*/
@ApiModelProperty("姓名")
private String name;
/**
* 年龄
<SUF>*/
@ApiModelProperty("年龄")
private int age;
/**
* 性别
*/
@ApiModelProperty("性别")
private String sex;
/**
* 住址
*/
@ApiModelProperty("家庭住址")
private String address;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
", address='" + address + '\'' +
'}';
}
}
| false |
60226_8 | //创建回形矩阵
/**
* 具体思路:
* 一共三个部分,填充数字、确定方向、打印数字
* 使用switch根据方向填充数字(二维数组)
* 通过判断转弯条件实现控制方向
* 利用循环打印二维数组
*/
public class ch1_8{
static enum Direction{
Right,Down,Left,Up;
}//方向是常量,用枚举
//创建填充数字方法
public static void initialArray() {
int row=0, col=0;//第一个数字
for (int c=0; c<length*length;c++) {
snake[row][col] = value;
lastDirection = findDirection(row,col);
//根据方向,填充数字
switch (lastDirection) {
case Right:
col++;
break;
case Down:
row++;
break;
case Left:
col--;
break;
case Up:
row--;
break;
default:
System.out.println("error");
}
value++;
}
}
//创建确定下一步方向的方法
static Direction findDirection(int row, int col) {
Direction direction = lastDirection;
switch (direction) {
case Right:{ //如果向右到尽头则向下
if (col == length-1 || snake[row][col+1] !=0)
direction = direction.Down;
break;
}
case Down:{ //如果向下到尽头则向左
if (row == length-1 || snake[row+1][col] !=0)
direction = direction.Left;
break;
}
case Left:{ //如果向左到尽头则向上
if (col == 0 || snake[row][col-1] !=0)
direction = direction.Up;
break;
}
case Up:{ //如果向上到尽头则向右
if (snake[row-1][col] !=0)
direction = direction.Right;
break;
}
}
return direction; //返回方向
}
//创建print方法
static void print(int[][] arr) {
for (int i=0; i<length; i++) {
for (int j=0; j<length; j++) {
System.out.printf("%5d",arr[i][j]); //每个数字占5位
}
System.out.println(); //换行
}
}
//进行初始赋值
static int length = 12; // 确定行数
static int value = 1; // 确定第一个数字
static int[][] snake = new int [length][length]; // 创建二维数组
static Direction lastDirection = Direction.Right; // 确定初始方向:向右
//运行主程序
public static void main(String[] args) {
initialArray(); //填充数字
print(snake); //打印数字
}
}
| AlexLee522/100-examples-of-Java-interesting-programming- | ch1_8.java | 724 | //如果向下到尽头则向左 | line_comment | zh-cn | //创建回形矩阵
/**
* 具体思路:
* 一共三个部分,填充数字、确定方向、打印数字
* 使用switch根据方向填充数字(二维数组)
* 通过判断转弯条件实现控制方向
* 利用循环打印二维数组
*/
public class ch1_8{
static enum Direction{
Right,Down,Left,Up;
}//方向是常量,用枚举
//创建填充数字方法
public static void initialArray() {
int row=0, col=0;//第一个数字
for (int c=0; c<length*length;c++) {
snake[row][col] = value;
lastDirection = findDirection(row,col);
//根据方向,填充数字
switch (lastDirection) {
case Right:
col++;
break;
case Down:
row++;
break;
case Left:
col--;
break;
case Up:
row--;
break;
default:
System.out.println("error");
}
value++;
}
}
//创建确定下一步方向的方法
static Direction findDirection(int row, int col) {
Direction direction = lastDirection;
switch (direction) {
case Right:{ //如果向右到尽头则向下
if (col == length-1 || snake[row][col+1] !=0)
direction = direction.Down;
break;
}
case Down:{ //如果 <SUF>
if (row == length-1 || snake[row+1][col] !=0)
direction = direction.Left;
break;
}
case Left:{ //如果向左到尽头则向上
if (col == 0 || snake[row][col-1] !=0)
direction = direction.Up;
break;
}
case Up:{ //如果向上到尽头则向右
if (snake[row-1][col] !=0)
direction = direction.Right;
break;
}
}
return direction; //返回方向
}
//创建print方法
static void print(int[][] arr) {
for (int i=0; i<length; i++) {
for (int j=0; j<length; j++) {
System.out.printf("%5d",arr[i][j]); //每个数字占5位
}
System.out.println(); //换行
}
}
//进行初始赋值
static int length = 12; // 确定行数
static int value = 1; // 确定第一个数字
static int[][] snake = new int [length][length]; // 创建二维数组
static Direction lastDirection = Direction.Right; // 确定初始方向:向右
//运行主程序
public static void main(String[] args) {
initialArray(); //填充数字
print(snake); //打印数字
}
}
| false |
18351_11 | package common.dp;
/**
* @author luoyuntian
* @program: p40-algorithm
* @description: 背包问题
* @date 2022-02-27 14:57:21
*/
public class Knapsack {
public static int maxValue1(int [] weight,int[] value,int bagLimit){
return process1(weight,value,0,bagLimit);
}
// 递归实现
// 在0 .... n-1中0...index-1已经不能选了
// index... n-1这些货,自由选择
// 背包还剩下多少容量,rest,自由挑选是不能超过rest的
// index...n-1 在符合要求的情况下,最大价值能达多少
public static int process1(int[] weight,int[] value,int index,int rest){
// 剩余的负重是负数,说明之前的选择是错误的
if(rest < 0){
// 返回无效解
return -1;
}
// rest >=0去且无货了
if(index == weight.length){
return 0;
}
// 既有负重,又有货
// 第一种选择:当前index位置的货,没要
int p1 = process1(weight,value,index+1,rest);
// 第二种选择:当前index位置的货,要
int p2 = -1;
int next = process1(weight,value,index+1,rest-weight[index]);
if(next != -1){
p2 = value[index] + next;
}
return Math.max(p1,p2);
}
public static int maxValue2(int [] weight,int[] value,int bagLimit){
int n = weight.length;
// index:0... n
// bag:100 0...100
int[][] dp = new int[n+1][bagLimit+1];
for(int i=0;i<=n;i++){
for(int j=0;j<=bagLimit;j++){
dp[i][j] = -2;
}
}
return process2(weight,value,0,bagLimit,dp);
}
public static int process2(int[] weight,int[] value,int index,int rest,int[][] dp){
if(rest < 0){
return -1;
}
// 缓存命中,以前算过
if(dp[index][rest]!=-2){
return dp[index][rest];
}
// 缓存没命中
int ans = 0;
if(index == weight.length){
ans = 0;
}else {
// 既有负重,又有货
// 第一种选择:当前index位置的货,没要
int p1 = process2(weight,value,index+1,rest,dp);
// 第二种选择:当前index位置的货,要
int p2 = -1;
int next = process2(weight,value,index+1,rest-weight[index],dp);
if(next != -1){
p2 = value[index] + next;
}
ans = Math.max(p1,p2);
}
dp[index][rest] = ans;
return ans;
}
}
| AlexNOCoder/p40-algorithm | src/main/java/common/dp/Knapsack.java | 773 | // 第二种选择:当前index位置的货,要 | line_comment | zh-cn | package common.dp;
/**
* @author luoyuntian
* @program: p40-algorithm
* @description: 背包问题
* @date 2022-02-27 14:57:21
*/
public class Knapsack {
public static int maxValue1(int [] weight,int[] value,int bagLimit){
return process1(weight,value,0,bagLimit);
}
// 递归实现
// 在0 .... n-1中0...index-1已经不能选了
// index... n-1这些货,自由选择
// 背包还剩下多少容量,rest,自由挑选是不能超过rest的
// index...n-1 在符合要求的情况下,最大价值能达多少
public static int process1(int[] weight,int[] value,int index,int rest){
// 剩余的负重是负数,说明之前的选择是错误的
if(rest < 0){
// 返回无效解
return -1;
}
// rest >=0去且无货了
if(index == weight.length){
return 0;
}
// 既有负重,又有货
// 第一种选择:当前index位置的货,没要
int p1 = process1(weight,value,index+1,rest);
// 第二 <SUF>
int p2 = -1;
int next = process1(weight,value,index+1,rest-weight[index]);
if(next != -1){
p2 = value[index] + next;
}
return Math.max(p1,p2);
}
public static int maxValue2(int [] weight,int[] value,int bagLimit){
int n = weight.length;
// index:0... n
// bag:100 0...100
int[][] dp = new int[n+1][bagLimit+1];
for(int i=0;i<=n;i++){
for(int j=0;j<=bagLimit;j++){
dp[i][j] = -2;
}
}
return process2(weight,value,0,bagLimit,dp);
}
public static int process2(int[] weight,int[] value,int index,int rest,int[][] dp){
if(rest < 0){
return -1;
}
// 缓存命中,以前算过
if(dp[index][rest]!=-2){
return dp[index][rest];
}
// 缓存没命中
int ans = 0;
if(index == weight.length){
ans = 0;
}else {
// 既有负重,又有货
// 第一种选择:当前index位置的货,没要
int p1 = process2(weight,value,index+1,rest,dp);
// 第二种选择:当前index位置的货,要
int p2 = -1;
int next = process2(weight,value,index+1,rest-weight[index],dp);
if(next != -1){
p2 = value[index] + next;
}
ans = Math.max(p1,p2);
}
dp[index][rest] = ans;
return ans;
}
}
| false |
34774_0 | import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.host("localhost:8080")
.select()
//为当前包路径
.apis(RequestHandlerSelectors.basePackage("controller"))
.paths(PathSelectors.any())
.build();
}
//构建 api文档的详细信息函数,注意这里的注解引用的是哪个
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
//页面标题
.title("Spring Boot测试使用 Swagger2 构建RESTful API")
//版本号
.version("1.0")
//描述
.description("API 描述")
.build();
}
}
| AlexanderChiuluvB/DistrubutedSystemProject | demo/src/main/java/Swagger2.java | 299 | //为当前包路径 | line_comment | zh-cn | import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.host("localhost:8080")
.select()
//为当 <SUF>
.apis(RequestHandlerSelectors.basePackage("controller"))
.paths(PathSelectors.any())
.build();
}
//构建 api文档的详细信息函数,注意这里的注解引用的是哪个
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
//页面标题
.title("Spring Boot测试使用 Swagger2 构建RESTful API")
//版本号
.version("1.0")
//描述
.description("API 描述")
.build();
}
}
| false |
33615_0 | package com.mathxh.Facade;
/*
* 外观模式: 随着程序越来越大,类的关系错综复杂。需要使用该模式为互相关联在一起的类整理出一个高层的API接口(重点是简化API使用,KISS原则)
* 有时候,需要考虑系统内部各类的责任关系和依赖关系,以便正确顺序调用各个类。
*
*
*/
public class Main {
public static void main(String[] args) {
PageMaker.makeWelcomePage("kishi@163.com", "welcome.html");
}
}
| AlexiaChen/design-pattern | src/com/mathxh/Facade/Main.java | 149 | /*
* 外观模式: 随着程序越来越大,类的关系错综复杂。需要使用该模式为互相关联在一起的类整理出一个高层的API接口(重点是简化API使用,KISS原则)
* 有时候,需要考虑系统内部各类的责任关系和依赖关系,以便正确顺序调用各个类。
*
*
*/ | block_comment | zh-cn | package com.mathxh.Facade;
/*
* 外观模 <SUF>*/
public class Main {
public static void main(String[] args) {
PageMaker.makeWelcomePage("kishi@163.com", "welcome.html");
}
}
| true |
49100_0 | package SingleThreadExecution;
/*
* 单线程执行模式:就是说,同一时刻,只有一个线程能访问执行,其他线程都得排队等待
*
* 临界区,mutex之类的都是这样的。一般涉及到多线程共享资源的时候会用到该模式。用同步语义让线程排队
*
* Java提供了一些线程安全的集合类: synchronizedCollection ......
* 一般来说,锁的区域一般要尽可能小。所以Java中ConcurrentHashMap把锁粒度分散到各个Hash桶中,降低粒度,以提高并发访问量。HashTable
* 虽然线程安全,但是是一把实例大锁加上的,统一时刻只有一个线程访问,并发量不行
*
* Java标准定义了一些原子操作,比如char,int等基本类型的赋值和引用都是原子的,对象引用类型的复制和引用操作也是原子的。但是long,double
* 的复制和引用就不是原子的。如果要让long,double变为原子,那么请用volatile修饰。
*
* 当然,原子性和内存可见性又不是一个东西,如果一个原子字段int从0变到2,如果没有用volatile修饰,或者用synchronized同步化,那么最糟糕的情况
* 可能就是,其他线程“看不到”这个原子字段的最新的修改值。当然,可能一辈子都看不到,看你运气了。
*
* 关于可见性的问题,C++的atomic头文件中,提供了内存序(memory order)的概念,可以更细节的掌控内存可见性的强度
*/
public class Main {
public static void main(String[] args) {
System.out.println("Testing");
Gate gate = new Gate();
new UserThread(gate, "Alice", "Alaska").start();
new UserThread(gate, "Bob", "Berkeley").start();
new UserThread(gate, "Mike", "Michigan").start();
}
}
| AlexiaChen/multi-thread-design-pattern | src/SingleThreadExecution/Main.java | 489 | /*
* 单线程执行模式:就是说,同一时刻,只有一个线程能访问执行,其他线程都得排队等待
*
* 临界区,mutex之类的都是这样的。一般涉及到多线程共享资源的时候会用到该模式。用同步语义让线程排队
*
* Java提供了一些线程安全的集合类: synchronizedCollection ......
* 一般来说,锁的区域一般要尽可能小。所以Java中ConcurrentHashMap把锁粒度分散到各个Hash桶中,降低粒度,以提高并发访问量。HashTable
* 虽然线程安全,但是是一把实例大锁加上的,统一时刻只有一个线程访问,并发量不行
*
* Java标准定义了一些原子操作,比如char,int等基本类型的赋值和引用都是原子的,对象引用类型的复制和引用操作也是原子的。但是long,double
* 的复制和引用就不是原子的。如果要让long,double变为原子,那么请用volatile修饰。
*
* 当然,原子性和内存可见性又不是一个东西,如果一个原子字段int从0变到2,如果没有用volatile修饰,或者用synchronized同步化,那么最糟糕的情况
* 可能就是,其他线程“看不到”这个原子字段的最新的修改值。当然,可能一辈子都看不到,看你运气了。
*
* 关于可见性的问题,C++的atomic头文件中,提供了内存序(memory order)的概念,可以更细节的掌控内存可见性的强度
*/ | block_comment | zh-cn | package SingleThreadExecution;
/*
* 单线程 <SUF>*/
public class Main {
public static void main(String[] args) {
System.out.println("Testing");
Gate gate = new Gate();
new UserThread(gate, "Alice", "Alaska").start();
new UserThread(gate, "Bob", "Berkeley").start();
new UserThread(gate, "Mike", "Michigan").start();
}
}
| true |
16346_1 | package com.github.lock;
import java.util.concurrent.TimeUnit;
/**
* synchronized三种应用方式
* 8种锁的案例实际提现在3个地方
* 作用于实例方法
* 作用于代码块
* 作用于静态方法
*/
public class Lock8Demo {
public static void main(String[] args) {
/*
谈谈你对多线程锁的理解
8锁案例说明
1.标准访问有ab两个线程,请问先打印邮件还是短信
2.
*/
Phone phone = new Phone();
new Thread(()->{
phone.sendEmail();
}, "a").start();
try {
TimeUnit.MILLISECONDS.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(()->{
phone.sendSMS();
}, "b").start();
}
}
// 资源类
class Phone {
public static synchronized void sendEmail() {
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("...sendEmail");
}
public synchronized void sendSMS() {
System.out.println("...sendSMS");
}
}
| AlibabaP8Developer/JavaStudy | juc-demo/src/main/java/com/github/lock/Lock8Demo.java | 292 | /*
谈谈你对多线程锁的理解
8锁案例说明
1.标准访问有ab两个线程,请问先打印邮件还是短信
2.
*/ | block_comment | zh-cn | package com.github.lock;
import java.util.concurrent.TimeUnit;
/**
* synchronized三种应用方式
* 8种锁的案例实际提现在3个地方
* 作用于实例方法
* 作用于代码块
* 作用于静态方法
*/
public class Lock8Demo {
public static void main(String[] args) {
/*
谈谈你 <SUF>*/
Phone phone = new Phone();
new Thread(()->{
phone.sendEmail();
}, "a").start();
try {
TimeUnit.MILLISECONDS.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(()->{
phone.sendSMS();
}, "b").start();
}
}
// 资源类
class Phone {
public static synchronized void sendEmail() {
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("...sendEmail");
}
public synchronized void sendSMS() {
System.out.println("...sendSMS");
}
}
| true |
16014_4 | package array;
import java.util.*;
/**
* @author Fer
* date 2022/8/22
*/
public class ThreeSum {
/**
* 在给定数组中找出不重复的三个数,使得 a + b + c = 0
* 思想:暴力解法,三次循环 + 去重(会超时)
* 优化:先将数组排序,减少重复枚举的次数,对于每一重循环,相邻两次枚举的元素不能相同
* 双指针(第二重和第三重循环并列)
*/
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new LinkedList<>();
int len = nums.length;
if (len < 3) {
return res;
}
for (int i = 0; i < len-2; i++) {
for (int j = i+1; j < len-1; j++) {
for (int k = j+1; k < len; k++) {
if (nums[i] + nums[j] + nums[k] == 0) {
List<Integer> list = new LinkedList<>();
list.add(nums[i]);
list.add(nums[j]);
list.add(nums[k]);
Collections.sort(list);
if (!res.contains(list)) {
res.add(list);
}
}
}
}
}
return res;
}
public List<List<Integer>> threeSum1(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
int len = nums.length;
if (len < 3) {
return res;
}
// 排序
Arrays.sort(nums);
// 从前往后枚举第一个元素
for (int first = 0; first < len; first++) {
if (first > 0 && nums[first] == nums[first-1]) {
continue;
}
// c 从右往左遍历
int third = len-1;
int target = -nums[first];
for (int second = first+1; second < len; second++) {
if (second > first + 1 && nums[second-1] == nums[second]) {
continue;
}
// 保证 b 的指针在 c 的指针左侧
while (second < third && nums[second] + nums[third] > target) {
--third;
}
// 当两个指针相遇了,终止循环
if (second == third) {
break;
}
if (nums[second] + nums[third] == target) {
List<Integer> list = new ArrayList<>();
list.add(nums[first]);
list.add(nums[second]);
list.add(nums[third]);
res.add(list);
}
}
}
return res;
}
}
| AlivinFer/leetcode-Java | src/array/ThreeSum.java | 668 | // 保证 b 的指针在 c 的指针左侧 | line_comment | zh-cn | package array;
import java.util.*;
/**
* @author Fer
* date 2022/8/22
*/
public class ThreeSum {
/**
* 在给定数组中找出不重复的三个数,使得 a + b + c = 0
* 思想:暴力解法,三次循环 + 去重(会超时)
* 优化:先将数组排序,减少重复枚举的次数,对于每一重循环,相邻两次枚举的元素不能相同
* 双指针(第二重和第三重循环并列)
*/
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new LinkedList<>();
int len = nums.length;
if (len < 3) {
return res;
}
for (int i = 0; i < len-2; i++) {
for (int j = i+1; j < len-1; j++) {
for (int k = j+1; k < len; k++) {
if (nums[i] + nums[j] + nums[k] == 0) {
List<Integer> list = new LinkedList<>();
list.add(nums[i]);
list.add(nums[j]);
list.add(nums[k]);
Collections.sort(list);
if (!res.contains(list)) {
res.add(list);
}
}
}
}
}
return res;
}
public List<List<Integer>> threeSum1(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
int len = nums.length;
if (len < 3) {
return res;
}
// 排序
Arrays.sort(nums);
// 从前往后枚举第一个元素
for (int first = 0; first < len; first++) {
if (first > 0 && nums[first] == nums[first-1]) {
continue;
}
// c 从右往左遍历
int third = len-1;
int target = -nums[first];
for (int second = first+1; second < len; second++) {
if (second > first + 1 && nums[second-1] == nums[second]) {
continue;
}
// 保证 <SUF>
while (second < third && nums[second] + nums[third] > target) {
--third;
}
// 当两个指针相遇了,终止循环
if (second == third) {
break;
}
if (nums[second] + nums[third] == target) {
List<Integer> list = new ArrayList<>();
list.add(nums[first]);
list.add(nums[second]);
list.add(nums[third]);
res.add(list);
}
}
}
return res;
}
}
| false |
41314_0 | package org.allaymc.api.utils;
import org.allaymc.api.data.VanillaBlockId;
import org.allaymc.api.data.VanillaItemId;
import org.allaymc.api.data.VanillaItemMetaBlockStateBiMap;
/**
* Allay Project 2023/12/8
*
* @author daoge_cmd
* <br>
* 一个用于描述方块和物品字符串Id之间映射关系的工具类 <br>
* Id一直是mc中比较复杂的一部分,我们将所有相关逻辑都放到这里,方便阅读也方便后续维护 <br>
* <br>
* 所有的方块必将有一个对应的硬性方块物品,这里我们称之为“硬性方块物品”。但是并不是所有的物品都有对应的方块。 <br>
* 硬性方块物品的贴图只能是方块的渲染图。为了解决这个问题,原版还为某些方块注册了额外的方块物品,例如:蛋糕,炼药锅,草,海带,床,甘蔗(注意甘蔗比较特殊,后面讲)等等<br>
* 我们将这些额外注册的方块物品称为“实际方块物品”。<br>
* 在一个方块只有单独对应的方块物品时,“实际方块物品”就等于“硬性方块物品” <br>
* 原版方块&物品注册顺序:先注册物品,再注册方块(注册方块同时会注册方块的硬性方块物品,物品的id通常与方块相同,但有特例)。 <br>
* <br>
* 实际方块物品在物品注册阶段注册,先于方块。通常其id与对应的方块相同,例如蛋糕的实际方块物品id就是"minecraft:cake"。这时蛋糕方块还未注册<br>
* 在注册蛋糕方块的时候,同时还要注册一个蛋糕方块的硬性方块物品,但是"minecraft:cake"这个id已经被先前注册的物品占了<br>
* 原版在这种情况下就会在"cake"前加个"item."前缀,也就是"minecraft:item.cake" <br>
* 原版具有"item."前缀的物品有几十个 <br>
* <br>
* 特例:甘蔗 <br>
* 甘蔗是唯一不遵循上诉规则的物品,我们认为这是历史遗留问题 <br>
* 甘蔗的方块-硬性方块物品配对为"minecraft:reeds" <-> "minecraft:item.reeds" <br>
* 而方块-实际方块物品配对则为"minecraft:reeds" <-> "minecraft:sugar_cane" <br>
* 可以看到甘蔗的实际方块物品id并不与其方块id相同 <br>
* <br>
* 为了统一命名,减少混乱。在allay中,我们保证注册的方块物品的硬性方块物品id在没有id冲突的情况下与方块id相同 <br>
* 若你想为你的方块注册额外的方块物品,请确保其id与对应方块id一致。稍后在注册一个方块时,若allay发现已有一个与方块id相同的物品,将把其作为实际使用的方块物品(也就是方法BlockType.getItemType()的返回值)<br>
* 但是即便如此,硬性方块物品仍然会被注册。和原版相同,我们将加上前缀"item."
* <br>
* 请注意,对于原版方块物品,若其meta(特殊值)不等于0,则不同特殊值的物品还有可能映射到一个方块类型的不同的方块状态上 <br>
* 具体点说,此类物品特殊值是由对应方块状态的各个方块属性序列化后全填充二进制位得到的。我们不推荐继续使用特殊值,这里也不会细讲具体逻辑<br>
* 此类映射关系由 {@link VanillaItemMetaBlockStateBiMap} 维护<br>
*/
public final class BlockAndItemIdMapper {
// Naming conflict prefix
public static final String NAMING_CONFLICT_PATH_PREFIX = "item.";
/**
* 需要调用方保证传入的itemId是方块物品,且方块与方块物品的命名规则合法。否则不存在id为返回值的方块
*
* @param itemId 物品id
*
* @return 可能的方块id
*/
public static Identifier itemIdToPossibleBlockId(Identifier itemId) {
// 特例:甘蔗
if (itemId.equals(VanillaItemId.SUGAR_CANE.getIdentifier())) {
return VanillaBlockId.REEDS.getIdentifier();
}
var blockId = itemId.clone();
if (blockId.path().contains(NAMING_CONFLICT_PATH_PREFIX)) {
blockId = new Identifier(blockId.namespace(), blockId.path().replace(NAMING_CONFLICT_PATH_PREFIX, ""));
}
return blockId;
}
/**
* 我们无法仅凭方块id判断其是否有额外的方块物品,不过我们可以推断出其实际方块物品
*
* @param blockId 方块id
*
* @return 实际方块物品id
*/
public static Identifier blockIdToActualBlockItemId(Identifier blockId) {
// 特例:甘蔗
if (blockId.equals(VanillaBlockId.REEDS.getIdentifier())) {
return VanillaItemId.SUGAR_CANE.getIdentifier();
}
return blockId;
}
}
| AllayMC/Allay | Allay-API/src/main/java/org/allaymc/api/utils/BlockAndItemIdMapper.java | 1,399 | /**
* Allay Project 2023/12/8
*
* @author daoge_cmd
* <br>
* 一个用于描述方块和物品字符串Id之间映射关系的工具类 <br>
* Id一直是mc中比较复杂的一部分,我们将所有相关逻辑都放到这里,方便阅读也方便后续维护 <br>
* <br>
* 所有的方块必将有一个对应的硬性方块物品,这里我们称之为“硬性方块物品”。但是并不是所有的物品都有对应的方块。 <br>
* 硬性方块物品的贴图只能是方块的渲染图。为了解决这个问题,原版还为某些方块注册了额外的方块物品,例如:蛋糕,炼药锅,草,海带,床,甘蔗(注意甘蔗比较特殊,后面讲)等等<br>
* 我们将这些额外注册的方块物品称为“实际方块物品”。<br>
* 在一个方块只有单独对应的方块物品时,“实际方块物品”就等于“硬性方块物品” <br>
* 原版方块&物品注册顺序:先注册物品,再注册方块(注册方块同时会注册方块的硬性方块物品,物品的id通常与方块相同,但有特例)。 <br>
* <br>
* 实际方块物品在物品注册阶段注册,先于方块。通常其id与对应的方块相同,例如蛋糕的实际方块物品id就是"minecraft:cake"。这时蛋糕方块还未注册<br>
* 在注册蛋糕方块的时候,同时还要注册一个蛋糕方块的硬性方块物品,但是"minecraft:cake"这个id已经被先前注册的物品占了<br>
* 原版在这种情况下就会在"cake"前加个"item."前缀,也就是"minecraft:item.cake" <br>
* 原版具有"item."前缀的物品有几十个 <br>
* <br>
* 特例:甘蔗 <br>
* 甘蔗是唯一不遵循上诉规则的物品,我们认为这是历史遗留问题 <br>
* 甘蔗的方块-硬性方块物品配对为"minecraft:reeds" <-> "minecraft:item.reeds" <br>
* 而方块-实际方块物品配对则为"minecraft:reeds" <-> "minecraft:sugar_cane" <br>
* 可以看到甘蔗的实际方块物品id并不与其方块id相同 <br>
* <br>
* 为了统一命名,减少混乱。在allay中,我们保证注册的方块物品的硬性方块物品id在没有id冲突的情况下与方块id相同 <br>
* 若你想为你的方块注册额外的方块物品,请确保其id与对应方块id一致。稍后在注册一个方块时,若allay发现已有一个与方块id相同的物品,将把其作为实际使用的方块物品(也就是方法BlockType.getItemType()的返回值)<br>
* 但是即便如此,硬性方块物品仍然会被注册。和原版相同,我们将加上前缀"item."
* <br>
* 请注意,对于原版方块物品,若其meta(特殊值)不等于0,则不同特殊值的物品还有可能映射到一个方块类型的不同的方块状态上 <br>
* 具体点说,此类物品特殊值是由对应方块状态的各个方块属性序列化后全填充二进制位得到的。我们不推荐继续使用特殊值,这里也不会细讲具体逻辑<br>
* 此类映射关系由 {@link VanillaItemMetaBlockStateBiMap} 维护<br>
*/ | block_comment | zh-cn | package org.allaymc.api.utils;
import org.allaymc.api.data.VanillaBlockId;
import org.allaymc.api.data.VanillaItemId;
import org.allaymc.api.data.VanillaItemMetaBlockStateBiMap;
/**
* All <SUF>*/
public final class BlockAndItemIdMapper {
// Naming conflict prefix
public static final String NAMING_CONFLICT_PATH_PREFIX = "item.";
/**
* 需要调用方保证传入的itemId是方块物品,且方块与方块物品的命名规则合法。否则不存在id为返回值的方块
*
* @param itemId 物品id
*
* @return 可能的方块id
*/
public static Identifier itemIdToPossibleBlockId(Identifier itemId) {
// 特例:甘蔗
if (itemId.equals(VanillaItemId.SUGAR_CANE.getIdentifier())) {
return VanillaBlockId.REEDS.getIdentifier();
}
var blockId = itemId.clone();
if (blockId.path().contains(NAMING_CONFLICT_PATH_PREFIX)) {
blockId = new Identifier(blockId.namespace(), blockId.path().replace(NAMING_CONFLICT_PATH_PREFIX, ""));
}
return blockId;
}
/**
* 我们无法仅凭方块id判断其是否有额外的方块物品,不过我们可以推断出其实际方块物品
*
* @param blockId 方块id
*
* @return 实际方块物品id
*/
public static Identifier blockIdToActualBlockItemId(Identifier blockId) {
// 特例:甘蔗
if (blockId.equals(VanillaBlockId.REEDS.getIdentifier())) {
return VanillaItemId.SUGAR_CANE.getIdentifier();
}
return blockId;
}
}
| true |
31203_2 | import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.Closeable;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Hua on 2016/1/22.
*/
public class HttpMonitor {
String viewState;
String imageCode;
private CloseableHttpClient httpClient;
public HttpMonitor(String viewState, String imageCode, CloseableHttpClient httpClient) {
this.viewState = viewState;
this.imageCode = imageCode;
this.httpClient = httpClient;
}
private boolean getLoginState() throws UnsupportedEncodingException {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("__VIEWSTATE", this.viewState));
nvps.add(new BasicNameValuePair("txtUserName", "XXXXXXXXXXXXX"));//在此输入你的学号
nvps.add(new BasicNameValuePair("TextBox2","XXXXXXX"));//在此输入你的密码
nvps.add(new BasicNameValuePair("txtSecretCode", imageCode));
nvps.add(new BasicNameValuePair("RadioButtonList1", "学生"));
nvps.add(new BasicNameValuePair("Button1", "登录"));
HttpPost httpost = new HttpPost("http://jw.hzau.edu.cn/default2.aspx");
httpost.addHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
httpost.addHeader("Accept-Encoding","gzip, deflate, sdch");
httpost.addHeader("Accept-Language","zh-CN,zh;q=0.8");
httpost.addHeader("Cache-Control","max-age=0");
httpost.addHeader("Connection","keep-alive");
httpost.addHeader("Host","jw.hzau.edu.cn");
httpost.addHeader("Referer","http://jw.hzau.edu.cn/default2.aspx");
httpost.addHeader("Upgrade-Insecure-Requests","1");
httpost.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.82 Safari/537.36");
httpost.setEntity(new UrlEncodedFormEntity(nvps,"GB2312"));
CloseableHttpResponse response;
try {
response = this.httpClient.execute(httpost);
/*登陆成功后会返回302跳转*/
//System.out.println(EntityUtils.toString(response.getEntity()));
String result = response.getStatusLine().toString();
System.out.println(result);
if(result.equals("HTTP/1.1 302 Found")){
response.close();
return true;
}else{
return false;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
public void getStuName(){
}
public void getSchedule() throws IOException {
List<NameValuePair> list = new ArrayList<>();
list.add(new BasicNameValuePair("xh","XXXXXXXXXXX"));
list.add(new BasicNameValuePair("xm","华昕"));//在此填入姓名
list.add(new BasicNameValuePair("gnmkdm","N121608"));
String s = URLEncodedUtils.format(list,"GB2312");
HttpGet httpGet = new HttpGet("http://jw.hzau.edu.cn/xsjccx.aspx?"+s);
System.out.println(s);
httpGet.addHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
httpGet.addHeader("Accept-Encoding","gzip, deflate, sdch");
httpGet.addHeader("Accept-Language","zh-CN,zh;q=0.8");
httpGet.addHeader("Cache-Control","max-age=0");
httpGet.addHeader("Connection","keep-alive");
httpGet.addHeader("Host","jw.hzau.edu.cn");
httpGet.addHeader("Referer","http://jw.hzau.edu.cn/xs_main.aspx?xh=XXXXXXXXXXXXX");
httpGet.addHeader("Upgrade-Insecure-Requests","1");
httpGet.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.82 Safari/537.36");
CloseableHttpResponse response;
System.out.println("正在查询教材信息…………");
response = httpClient.execute(httpGet);
System.out.println("正在查询教材信息…………");
int staus = response.getStatusLine().getStatusCode();
if (staus == 200){
System.out.println("查询教材信息成功!");
System.out.println(EntityUtils.toString(response.getEntity()));
}
}
public void run() {
try {
//System.out.println(getLoginState());
if (getLoginState()){
System.out.println("登陆成功!!");
getSchedule();
}else {
System.out.println("验证码错误!!");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
System.out.println("查询失败");
e.printStackTrace();
}
}
public static void main(String[] args) {
//getUrl("","");
}
}
| Allenhua/HzauStudy | src/HttpMonitor.java | 1,486 | //在此输入你的密码 | line_comment | zh-cn | import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.Closeable;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Hua on 2016/1/22.
*/
public class HttpMonitor {
String viewState;
String imageCode;
private CloseableHttpClient httpClient;
public HttpMonitor(String viewState, String imageCode, CloseableHttpClient httpClient) {
this.viewState = viewState;
this.imageCode = imageCode;
this.httpClient = httpClient;
}
private boolean getLoginState() throws UnsupportedEncodingException {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("__VIEWSTATE", this.viewState));
nvps.add(new BasicNameValuePair("txtUserName", "XXXXXXXXXXXXX"));//在此输入你的学号
nvps.add(new BasicNameValuePair("TextBox2","XXXXXXX"));//在此 <SUF>
nvps.add(new BasicNameValuePair("txtSecretCode", imageCode));
nvps.add(new BasicNameValuePair("RadioButtonList1", "学生"));
nvps.add(new BasicNameValuePair("Button1", "登录"));
HttpPost httpost = new HttpPost("http://jw.hzau.edu.cn/default2.aspx");
httpost.addHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
httpost.addHeader("Accept-Encoding","gzip, deflate, sdch");
httpost.addHeader("Accept-Language","zh-CN,zh;q=0.8");
httpost.addHeader("Cache-Control","max-age=0");
httpost.addHeader("Connection","keep-alive");
httpost.addHeader("Host","jw.hzau.edu.cn");
httpost.addHeader("Referer","http://jw.hzau.edu.cn/default2.aspx");
httpost.addHeader("Upgrade-Insecure-Requests","1");
httpost.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.82 Safari/537.36");
httpost.setEntity(new UrlEncodedFormEntity(nvps,"GB2312"));
CloseableHttpResponse response;
try {
response = this.httpClient.execute(httpost);
/*登陆成功后会返回302跳转*/
//System.out.println(EntityUtils.toString(response.getEntity()));
String result = response.getStatusLine().toString();
System.out.println(result);
if(result.equals("HTTP/1.1 302 Found")){
response.close();
return true;
}else{
return false;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
public void getStuName(){
}
public void getSchedule() throws IOException {
List<NameValuePair> list = new ArrayList<>();
list.add(new BasicNameValuePair("xh","XXXXXXXXXXX"));
list.add(new BasicNameValuePair("xm","华昕"));//在此填入姓名
list.add(new BasicNameValuePair("gnmkdm","N121608"));
String s = URLEncodedUtils.format(list,"GB2312");
HttpGet httpGet = new HttpGet("http://jw.hzau.edu.cn/xsjccx.aspx?"+s);
System.out.println(s);
httpGet.addHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
httpGet.addHeader("Accept-Encoding","gzip, deflate, sdch");
httpGet.addHeader("Accept-Language","zh-CN,zh;q=0.8");
httpGet.addHeader("Cache-Control","max-age=0");
httpGet.addHeader("Connection","keep-alive");
httpGet.addHeader("Host","jw.hzau.edu.cn");
httpGet.addHeader("Referer","http://jw.hzau.edu.cn/xs_main.aspx?xh=XXXXXXXXXXXXX");
httpGet.addHeader("Upgrade-Insecure-Requests","1");
httpGet.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.82 Safari/537.36");
CloseableHttpResponse response;
System.out.println("正在查询教材信息…………");
response = httpClient.execute(httpGet);
System.out.println("正在查询教材信息…………");
int staus = response.getStatusLine().getStatusCode();
if (staus == 200){
System.out.println("查询教材信息成功!");
System.out.println(EntityUtils.toString(response.getEntity()));
}
}
public void run() {
try {
//System.out.println(getLoginState());
if (getLoginState()){
System.out.println("登陆成功!!");
getSchedule();
}else {
System.out.println("验证码错误!!");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
System.out.println("查询失败");
e.printStackTrace();
}
}
public static void main(String[] args) {
//getUrl("","");
}
}
| false |
51351_5 | /*
* Copyright (C), 2015-2017
* FileName: GetThNumber
* Author: Administrator
* Date: 2017/11/4 0004 22:18
* Description: 取出数组中第N大的元素
*/
package me.zonglun.Sort;
/**
* 〈一句话功能简述〉<br>
* 〈取出数组中第N大的元素〉
*
* @author Administrator
* @create 2017/11/4 0004
* @since 1.0.0
* @subject 取出一个数组中第N大的元素
*/
public class GetThNumber {
private GetThNumber() {}
// 对arr[l...r]部分进行partition操作
// 返回p, 使得arr[l...p-1] < arr[p] ; arr[p+1...r] > arr[p]
// partition 过程, 和快排的partition一样
// 思考: 双路快排和三路快排的思想能不能用在selection算法中? :)
private static int partition(Comparable[] arr, int l, int r){
// 随机在arr[l...r]的范围中, 选择一个数值作为标定点pivot
swap( arr, l , (int)(Math.random()*(r-l+1))+l );
Comparable v = arr[l];
int j = l; // arr[l+1...j] < v ; arr[j+1...i) > v
for( int i = l + 1 ; i <= r ; i ++ )
if( arr[i].compareTo(v) < 0 ){
j ++;
swap(arr, j, i);
}
swap(arr, l, j);
return j;
}
// 求出nums[l...r]范围里第k小的数
private static Comparable solve(Comparable[] nums, int l, int r, int k){
if( l == r )
return nums[l];
// partition之后, nums[p]的正确位置就在索引p上
int p = partition(nums, l, r);
if( k == p ) // 如果 k == p, 直接返回nums[p]
return nums[p];
else if( k < p ) // 如果 k < p, 只需要在nums[l...p-1]中找第k小元素即可
return solve( nums, l, p-1, k);
else // 如果 k > p, 则需要在nums[p+1...r]中找第k小元素
return solve( nums, p+1, r, k );
}
// 寻找nums数组中第k小的元素
public static Comparable solve(Comparable nums[], int n, int k) {
assert k >= 0 && k < n;
return solve(nums, 0, n - 1, k);
}
private static void swap(Object[] arr, int i, int j) {
Object t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
// 测试 Selection
public static void main(String[] args) {
// 生成一个大小为n, 包含0...n-1这n个元素的随机数组arr
int N = 10000;
Integer[] arr = SortTestHelper.generateOrderedArray(N);
// 验证selection算法, 对arr数组求第i小元素, 应该为i
for( int i = 0 ; i < N ; i ++ ){
System.out.println("test " + i + " complete.");
}
}
}
| Allenskoo856/AlgorithmsSolutions | src/me/zonglun/Sort/GetThNumber.java | 854 | // 思考: 双路快排和三路快排的思想能不能用在selection算法中? :) | line_comment | zh-cn | /*
* Copyright (C), 2015-2017
* FileName: GetThNumber
* Author: Administrator
* Date: 2017/11/4 0004 22:18
* Description: 取出数组中第N大的元素
*/
package me.zonglun.Sort;
/**
* 〈一句话功能简述〉<br>
* 〈取出数组中第N大的元素〉
*
* @author Administrator
* @create 2017/11/4 0004
* @since 1.0.0
* @subject 取出一个数组中第N大的元素
*/
public class GetThNumber {
private GetThNumber() {}
// 对arr[l...r]部分进行partition操作
// 返回p, 使得arr[l...p-1] < arr[p] ; arr[p+1...r] > arr[p]
// partition 过程, 和快排的partition一样
// 思考 <SUF>
private static int partition(Comparable[] arr, int l, int r){
// 随机在arr[l...r]的范围中, 选择一个数值作为标定点pivot
swap( arr, l , (int)(Math.random()*(r-l+1))+l );
Comparable v = arr[l];
int j = l; // arr[l+1...j] < v ; arr[j+1...i) > v
for( int i = l + 1 ; i <= r ; i ++ )
if( arr[i].compareTo(v) < 0 ){
j ++;
swap(arr, j, i);
}
swap(arr, l, j);
return j;
}
// 求出nums[l...r]范围里第k小的数
private static Comparable solve(Comparable[] nums, int l, int r, int k){
if( l == r )
return nums[l];
// partition之后, nums[p]的正确位置就在索引p上
int p = partition(nums, l, r);
if( k == p ) // 如果 k == p, 直接返回nums[p]
return nums[p];
else if( k < p ) // 如果 k < p, 只需要在nums[l...p-1]中找第k小元素即可
return solve( nums, l, p-1, k);
else // 如果 k > p, 则需要在nums[p+1...r]中找第k小元素
return solve( nums, p+1, r, k );
}
// 寻找nums数组中第k小的元素
public static Comparable solve(Comparable nums[], int n, int k) {
assert k >= 0 && k < n;
return solve(nums, 0, n - 1, k);
}
private static void swap(Object[] arr, int i, int j) {
Object t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
// 测试 Selection
public static void main(String[] args) {
// 生成一个大小为n, 包含0...n-1这n个元素的随机数组arr
int N = 10000;
Integer[] arr = SortTestHelper.generateOrderedArray(N);
// 验证selection算法, 对arr数组求第i小元素, 应该为i
for( int i = 0 ; i < N ; i ++ ){
System.out.println("test " + i + " complete.");
}
}
}
| true |
10326_0 | package payroll.model.dto;
// 看起来 dto 就是来做这些事情的
public class JsonResult {
/**
* 返回的状态吗,0:失败,1:成功
*/
private Integer code;
private String message;
private Object result;
public JsonResult(Integer code){
this.code=code;
}
public JsonResult(Integer code,String message){
this.code=code;
this.message=message;
}
public JsonResult(Integer code,String message,Object result){
this.code=code;
this.message=message;
this.result=result;
}
public JsonResult(Integer code, Object result) {
this.code = code;
this.result = result;
}
}
| Allianzcortex/code_collection | Spring-Example/MySpringDemo/src/main/java/com/example/demo/payroll/model/dto/JsonResult.java | 174 | // 看起来 dto 就是来做这些事情的 | line_comment | zh-cn | package payroll.model.dto;
// 看起 <SUF>
public class JsonResult {
/**
* 返回的状态吗,0:失败,1:成功
*/
private Integer code;
private String message;
private Object result;
public JsonResult(Integer code){
this.code=code;
}
public JsonResult(Integer code,String message){
this.code=code;
this.message=message;
}
public JsonResult(Integer code,String message,Object result){
this.code=code;
this.message=message;
this.result=result;
}
public JsonResult(Integer code, Object result) {
this.code = code;
this.result = result;
}
}
| true |
25700_2 | package com.allyn.lives.bean;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Administrator on 2016/6/20.
*/
public class BooksBean implements Parcelable {
/**
* list : [{"author":"郭昕","bookclass":4,"count":"1410","fcount":0,"id":1239,"img":"/book/150802/c9e6346d7eb6fa4a40d818754e0e4858.jpg","name":"心存慰藉","rcount":0,"summary":" 人生并非坦途,有快乐就有痛苦,有幸福就有悲伤。人情的冷暖,世态的炎凉,不能回避就要学会正确面对。在经历沧桑和磨砺之后,对人生我们就能多一些反思,多一些深刻的属于我们自己的体悟。漫长而又短暂的人生,一路走来,总会在心底印留下各色的记忆,关于我们曾经遭遇过的人,关于我们曾经经历过的事,关于我们曾经阅过的风情、风景,或美好,或苦痛,有些值得我们用毕生去追思、缅怀、玩味,有些则需要我们努力去抛弃、丢失、忘却\u2026\u2026","time":1438490059000},{"author":"苏菁","bookclass":4,"count":"1668","fcount":0,"id":1238,"img":"/book/150802/f8b347d5c59124e82974108f3e8ad24b.jpg","name":"你相信婚姻能拯","rcount":0,"summary":" 本书是一部纪实性心灵励志小说。主人公梦琪童年时代因寄养在外婆家,缺少父母的关爱,形成了较为孤僻的性格。这样的性格伴随着她走入了婚姻,当她濒临失去丈夫和儿子的边缘时,她幡然醒悟,开始了对婚姻的自救。正是在母亲的位置上,她深刻反省自己,拯救自己,由于完善了自己的性格,从而挽救了濒临崩溃的婚姻,重新找回了爱情的她,带着一份责任感来到了首都北京,从心理咨询开始了对整个社会命运的探索,她给别人做心理咨询、她深入北京各类素质培训机构、医院、北京家庭、各大高等院校、监狱、法院\u2026\u2026","time":1438490059000},{"author":"张世琦","bookclass":4,"count":"1511","fcount":0,"id":1237,"img":"/book/150802/34d2b35f671f2dcf536861b71811aeb8.jpg","name":"青年不可不知Ⅰ","rcount":0,"summary":" 婚姻问题并不神秘。人到了一定年龄,婚姻问题便摆在面前,逼着你不得不处理,不得不正确回答有关婚姻的各种问题。因此,对婚姻应该有正确认识,应该看到婚姻有可能给人带来巨大麻烦的危险性,必须正确处理好。上至高官巨富,下至平民百姓,对任何人来说,婚姻问题都是光明正大的,两性问题都是不可回避的。","time":1438490059000},{"author":"陈彤","bookclass":4,"count":"778","fcount":0,"id":1236,"img":"/book/150802/d6e6d98754088f3b70cfc2ce0c6c5542.jpg","name":"旧爱新欢","rcount":0,"summary":" 判断一个男人是否成功,有很多方式,最简单的一种,是看他有几个办公室;判断一个女人是否丰富,也有很多方式,最直接的一种,是看她睡过多少张床。有的女人很简单,闺床\u2014\u2014婚床,一生!有的女人很幸福,还没学会走路,就已经睡过好几张童床。有的女人一生睡过很多床,但其实只睡过一张,因为每张床和另一张没什么不同。","time":1438490059000}]
* page : 1
* size : 4
* status : true
* total : 415
* totalpage : 104
*/
private int page;
private int size;
private boolean status;
private int total;
private int totalpage;
private List<ListEntity> list;
public void setPage(int page) {
this.page = page;
}
public void setSize(int size) {
this.size = size;
}
public void setStatus(boolean status) {
this.status = status;
}
public void setTotal(int total) {
this.total = total;
}
public void setTotalpage(int totalpage) {
this.totalpage = totalpage;
}
public void setList(List<ListEntity> list) {
this.list = list;
}
public int getPage() {
return page;
}
public int getSize() {
return size;
}
public boolean getStatus() {
return status;
}
public int getTotal() {
return total;
}
public int getTotalpage() {
return totalpage;
}
public List<ListEntity> getList() {
return list;
}
public static class ListEntity {
/**
* author : 郭昕
* bookclass : 4
* count : 1410
* fcount : 0
* id : 1239
* img : /book/150802/c9e6346d7eb6fa4a40d818754e0e4858.jpg
* name : 心存慰藉
* rcount : 0
* summary : 人生并非坦途,有快乐就有痛苦,有幸福就有悲伤。人情的冷暖,世态的炎凉,不能回避就要学会正确面对。在经历沧桑和磨砺之后,对人生我们就能多一些反思,多一些深刻的属于我们自己的体悟。漫长而又短暂的人生,一路走来,总会在心底印留下各色的记忆,关于我们曾经遭遇过的人,关于我们曾经经历过的事,关于我们曾经阅过的风情、风景,或美好,或苦痛,有些值得我们用毕生去追思、缅怀、玩味,有些则需要我们努力去抛弃、丢失、忘却……
* time : 1438490059000
*/
private String author;
private int bookclass;
private String count;
private int fcount;
private int id;
private String img;
private String name;
private int rcount;
private String summary;
private long time;
public void setAuthor(String author) {
this.author = author;
}
public void setBookclass(int bookclass) {
this.bookclass = bookclass;
}
public void setCount(String count) {
this.count = count;
}
public void setFcount(int fcount) {
this.fcount = fcount;
}
public void setId(int id) {
this.id = id;
}
public void setImg(String img) {
this.img = img;
}
public void setName(String name) {
this.name = name;
}
public void setRcount(int rcount) {
this.rcount = rcount;
}
public void setSummary(String summary) {
this.summary = summary;
}
public void setTime(long time) {
this.time = time;
}
public String getAuthor() {
return author;
}
public int getBookclass() {
return bookclass;
}
public String getCount() {
return count;
}
public int getFcount() {
return fcount;
}
public int getId() {
return id;
}
public String getImg() {
return img;
}
public String getName() {
return name;
}
public int getRcount() {
return rcount;
}
public String getSummary() {
return summary;
}
public long getTime() {
return time;
}
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.page);
dest.writeInt(this.size);
dest.writeByte(status ? (byte) 1 : (byte) 0);
dest.writeInt(this.total);
dest.writeInt(this.totalpage);
dest.writeList(this.list);
}
public BooksBean() {
}
protected BooksBean(Parcel in) {
this.page = in.readInt();
this.size = in.readInt();
this.status = in.readByte() != 0;
this.total = in.readInt();
this.totalpage = in.readInt();
this.list = new ArrayList<ListEntity>();
in.readList(this.list, List.class.getClassLoader());
}
public static final Parcelable.Creator<BooksBean> CREATOR = new Parcelable.Creator<BooksBean>() {
public BooksBean createFromParcel(Parcel source) {
return new BooksBean(source);
}
public BooksBean[] newArray(int size) {
return new BooksBean[size];
}
};
}
| Allyns/Lives | app/src/main/java/com/allyn/lives/bean/BooksBean.java | 2,572 | /**
* author : 郭昕
* bookclass : 4
* count : 1410
* fcount : 0
* id : 1239
* img : /book/150802/c9e6346d7eb6fa4a40d818754e0e4858.jpg
* name : 心存慰藉
* rcount : 0
* summary : 人生并非坦途,有快乐就有痛苦,有幸福就有悲伤。人情的冷暖,世态的炎凉,不能回避就要学会正确面对。在经历沧桑和磨砺之后,对人生我们就能多一些反思,多一些深刻的属于我们自己的体悟。漫长而又短暂的人生,一路走来,总会在心底印留下各色的记忆,关于我们曾经遭遇过的人,关于我们曾经经历过的事,关于我们曾经阅过的风情、风景,或美好,或苦痛,有些值得我们用毕生去追思、缅怀、玩味,有些则需要我们努力去抛弃、丢失、忘却……
* time : 1438490059000
*/ | block_comment | zh-cn | package com.allyn.lives.bean;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Administrator on 2016/6/20.
*/
public class BooksBean implements Parcelable {
/**
* list : [{"author":"郭昕","bookclass":4,"count":"1410","fcount":0,"id":1239,"img":"/book/150802/c9e6346d7eb6fa4a40d818754e0e4858.jpg","name":"心存慰藉","rcount":0,"summary":" 人生并非坦途,有快乐就有痛苦,有幸福就有悲伤。人情的冷暖,世态的炎凉,不能回避就要学会正确面对。在经历沧桑和磨砺之后,对人生我们就能多一些反思,多一些深刻的属于我们自己的体悟。漫长而又短暂的人生,一路走来,总会在心底印留下各色的记忆,关于我们曾经遭遇过的人,关于我们曾经经历过的事,关于我们曾经阅过的风情、风景,或美好,或苦痛,有些值得我们用毕生去追思、缅怀、玩味,有些则需要我们努力去抛弃、丢失、忘却\u2026\u2026","time":1438490059000},{"author":"苏菁","bookclass":4,"count":"1668","fcount":0,"id":1238,"img":"/book/150802/f8b347d5c59124e82974108f3e8ad24b.jpg","name":"你相信婚姻能拯","rcount":0,"summary":" 本书是一部纪实性心灵励志小说。主人公梦琪童年时代因寄养在外婆家,缺少父母的关爱,形成了较为孤僻的性格。这样的性格伴随着她走入了婚姻,当她濒临失去丈夫和儿子的边缘时,她幡然醒悟,开始了对婚姻的自救。正是在母亲的位置上,她深刻反省自己,拯救自己,由于完善了自己的性格,从而挽救了濒临崩溃的婚姻,重新找回了爱情的她,带着一份责任感来到了首都北京,从心理咨询开始了对整个社会命运的探索,她给别人做心理咨询、她深入北京各类素质培训机构、医院、北京家庭、各大高等院校、监狱、法院\u2026\u2026","time":1438490059000},{"author":"张世琦","bookclass":4,"count":"1511","fcount":0,"id":1237,"img":"/book/150802/34d2b35f671f2dcf536861b71811aeb8.jpg","name":"青年不可不知Ⅰ","rcount":0,"summary":" 婚姻问题并不神秘。人到了一定年龄,婚姻问题便摆在面前,逼着你不得不处理,不得不正确回答有关婚姻的各种问题。因此,对婚姻应该有正确认识,应该看到婚姻有可能给人带来巨大麻烦的危险性,必须正确处理好。上至高官巨富,下至平民百姓,对任何人来说,婚姻问题都是光明正大的,两性问题都是不可回避的。","time":1438490059000},{"author":"陈彤","bookclass":4,"count":"778","fcount":0,"id":1236,"img":"/book/150802/d6e6d98754088f3b70cfc2ce0c6c5542.jpg","name":"旧爱新欢","rcount":0,"summary":" 判断一个男人是否成功,有很多方式,最简单的一种,是看他有几个办公室;判断一个女人是否丰富,也有很多方式,最直接的一种,是看她睡过多少张床。有的女人很简单,闺床\u2014\u2014婚床,一生!有的女人很幸福,还没学会走路,就已经睡过好几张童床。有的女人一生睡过很多床,但其实只睡过一张,因为每张床和另一张没什么不同。","time":1438490059000}]
* page : 1
* size : 4
* status : true
* total : 415
* totalpage : 104
*/
private int page;
private int size;
private boolean status;
private int total;
private int totalpage;
private List<ListEntity> list;
public void setPage(int page) {
this.page = page;
}
public void setSize(int size) {
this.size = size;
}
public void setStatus(boolean status) {
this.status = status;
}
public void setTotal(int total) {
this.total = total;
}
public void setTotalpage(int totalpage) {
this.totalpage = totalpage;
}
public void setList(List<ListEntity> list) {
this.list = list;
}
public int getPage() {
return page;
}
public int getSize() {
return size;
}
public boolean getStatus() {
return status;
}
public int getTotal() {
return total;
}
public int getTotalpage() {
return totalpage;
}
public List<ListEntity> getList() {
return list;
}
public static class ListEntity {
/**
* aut <SUF>*/
private String author;
private int bookclass;
private String count;
private int fcount;
private int id;
private String img;
private String name;
private int rcount;
private String summary;
private long time;
public void setAuthor(String author) {
this.author = author;
}
public void setBookclass(int bookclass) {
this.bookclass = bookclass;
}
public void setCount(String count) {
this.count = count;
}
public void setFcount(int fcount) {
this.fcount = fcount;
}
public void setId(int id) {
this.id = id;
}
public void setImg(String img) {
this.img = img;
}
public void setName(String name) {
this.name = name;
}
public void setRcount(int rcount) {
this.rcount = rcount;
}
public void setSummary(String summary) {
this.summary = summary;
}
public void setTime(long time) {
this.time = time;
}
public String getAuthor() {
return author;
}
public int getBookclass() {
return bookclass;
}
public String getCount() {
return count;
}
public int getFcount() {
return fcount;
}
public int getId() {
return id;
}
public String getImg() {
return img;
}
public String getName() {
return name;
}
public int getRcount() {
return rcount;
}
public String getSummary() {
return summary;
}
public long getTime() {
return time;
}
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.page);
dest.writeInt(this.size);
dest.writeByte(status ? (byte) 1 : (byte) 0);
dest.writeInt(this.total);
dest.writeInt(this.totalpage);
dest.writeList(this.list);
}
public BooksBean() {
}
protected BooksBean(Parcel in) {
this.page = in.readInt();
this.size = in.readInt();
this.status = in.readByte() != 0;
this.total = in.readInt();
this.totalpage = in.readInt();
this.list = new ArrayList<ListEntity>();
in.readList(this.list, List.class.getClassLoader());
}
public static final Parcelable.Creator<BooksBean> CREATOR = new Parcelable.Creator<BooksBean>() {
public BooksBean createFromParcel(Parcel source) {
return new BooksBean(source);
}
public BooksBean[] newArray(int size) {
return new BooksBean[size];
}
};
}
| true |
60261_15 | package greed_game;
import java.util.Random;
public class PlayerManager {
public void start(Player[] players,int playerNum,Dices dices) {
sortPlayers(players,playerNum);
boolean gameOver = false;
int playerIdx=-1;
/*全部人还没入局*/
do {
playerIdx = (playerIdx+1)%playerNum;
dices.reset();
Player curPlayer=players[playerIdx];
PlayView.nowTurnPlayer(curPlayer.getName(),(curPlayer instanceof Human),curPlayer.getTotalScore());
while(true)
{
PlayView.nowTurnDicesTotal(dices.getNumber());
PlayView.nowaskDices(curPlayer.getName());
boolean choice = players[playerIdx].makeChoice(dices);
if(choice)
{
PlayView.rollPointOut(curPlayer.getName(),dices.getPoint(),dices.getNumber());
int rollScore = countAndRemove(dices);
PlayView.rollScoreOut(rollScore);
if(!curPlayer.isEnrolled())
{
if(rollScore < 300) {
//”未入局“
PlayView.isNotEnrolledOut(curPlayer.getName());
break;
}
else {
//”入局“
PlayView.isEnrolledOut(curPlayer.getName());
curPlayer.setEnrolled();
}
}
if(rollScore == 0)
{
//“本回合得分为零,玩家回合结束”
curPlayer.clearTurnScore();
PlayView.playerTurnEndOut(curPlayer.getTurnScore());
break;
}
curPlayer.addTurnScore(rollScore);
//“玩家本回合得分为turnScore”
PlayView.scoreUntilNowOut(curPlayer.getName(),curPlayer.getTurnScore());
if(dices.getNumber() == 0)
{
//“没有剩余骰子,玩家回合结束”
PlayView.noDicesLeftOut();
//curPlayer.addTotalScore();
//curPlayer.clearTurnScore();
//"xxw玩家当前总得分为:"
break;
}
}
else
{
//"xx玩家放弃投掷,玩家回合结束"
PlayView.playerGiveupOut(curPlayer.getName());
//curPlayer.addTotalScore();
//curPlayer.clearTurnScore();
//"xxw玩家当前总得分为:"
break;
}
}
//"玩家回合结束"
curPlayer.addTotalScore(curPlayer.getTurnScore());
curPlayer.clearTurnScore();
//打印玩家信息
PlayView.playerTotalOut(curPlayer.getName(),curPlayer.getTotalScore());
if(curPlayer.getTotalScore() >= 3000)
{
//“宣布胜者,本局游戏结束”
gameOver = true;
PlayView.winnerOut(curPlayer.getName());
break;
}
// PlayView.waitingConfirm();
}while(!gameOver);
}
public int countAndRemove(Dices dices) {
int now_roll_number=dices.getNumber();
int[] rollscore=dices.getPoint();
int[] roll=new int[7];
for(int score=1;score<=6;score++) roll[score]=0;
for(int dicesid=0;dicesid<now_roll_number;dicesid++)
roll[rollscore[dicesid]]++;
int nowscore=0,decroll=0;
if (roll[1]==6) {
roll[1]-=6;
nowscore+=3000;
decroll+=6;
}
if (roll[1]>=3) {
roll[1]-=3;
nowscore+=1000;
decroll+=3;
}
for(int score=2;score<=6;score++) {
if (roll[score]>=3) {
roll[score]-=3;
nowscore+=score*100;
decroll+=3;
}
if (roll[score]>=3) {
roll[score]-=3;
nowscore+=score*100;
decroll+=3;
}
}
while (roll[1]>0) {
roll[1]--;
nowscore+=100;
decroll++;
}
while (roll[5]>0) {
roll[5]--;
nowscore+=50;
decroll++;
}
dices.removeDices(decroll);
return nowscore;
}
public void sortPlayers(Player[] players,int playerNum)
{
Random rand = new Random();
Player tmpPlayer;
for(int i=0;i<playerNum;i++) {
int now=rand.nextInt(i+1);
// Player swapPlayer=players[now];
tmpPlayer=players[now];
players[now]=players[i];
players[i]=tmpPlayer;
// System.out.println(now+":"+tmpPlayer.getName()+","+players[now].getName()+","+players[i].getName());
}
String[] name=new String[playerNum];
for(int i=0;i<playerNum;i++) {
name[i]=players[i].getName();
}
PlayView.shuffledPlayerOut(name,playerNum);
}
}
| Alnitak-Antares/Greed-Dice-Game | PlayerManager.java | 1,269 | //“宣布胜者,本局游戏结束” | line_comment | zh-cn | package greed_game;
import java.util.Random;
public class PlayerManager {
public void start(Player[] players,int playerNum,Dices dices) {
sortPlayers(players,playerNum);
boolean gameOver = false;
int playerIdx=-1;
/*全部人还没入局*/
do {
playerIdx = (playerIdx+1)%playerNum;
dices.reset();
Player curPlayer=players[playerIdx];
PlayView.nowTurnPlayer(curPlayer.getName(),(curPlayer instanceof Human),curPlayer.getTotalScore());
while(true)
{
PlayView.nowTurnDicesTotal(dices.getNumber());
PlayView.nowaskDices(curPlayer.getName());
boolean choice = players[playerIdx].makeChoice(dices);
if(choice)
{
PlayView.rollPointOut(curPlayer.getName(),dices.getPoint(),dices.getNumber());
int rollScore = countAndRemove(dices);
PlayView.rollScoreOut(rollScore);
if(!curPlayer.isEnrolled())
{
if(rollScore < 300) {
//”未入局“
PlayView.isNotEnrolledOut(curPlayer.getName());
break;
}
else {
//”入局“
PlayView.isEnrolledOut(curPlayer.getName());
curPlayer.setEnrolled();
}
}
if(rollScore == 0)
{
//“本回合得分为零,玩家回合结束”
curPlayer.clearTurnScore();
PlayView.playerTurnEndOut(curPlayer.getTurnScore());
break;
}
curPlayer.addTurnScore(rollScore);
//“玩家本回合得分为turnScore”
PlayView.scoreUntilNowOut(curPlayer.getName(),curPlayer.getTurnScore());
if(dices.getNumber() == 0)
{
//“没有剩余骰子,玩家回合结束”
PlayView.noDicesLeftOut();
//curPlayer.addTotalScore();
//curPlayer.clearTurnScore();
//"xxw玩家当前总得分为:"
break;
}
}
else
{
//"xx玩家放弃投掷,玩家回合结束"
PlayView.playerGiveupOut(curPlayer.getName());
//curPlayer.addTotalScore();
//curPlayer.clearTurnScore();
//"xxw玩家当前总得分为:"
break;
}
}
//"玩家回合结束"
curPlayer.addTotalScore(curPlayer.getTurnScore());
curPlayer.clearTurnScore();
//打印玩家信息
PlayView.playerTotalOut(curPlayer.getName(),curPlayer.getTotalScore());
if(curPlayer.getTotalScore() >= 3000)
{
//“宣 <SUF>
gameOver = true;
PlayView.winnerOut(curPlayer.getName());
break;
}
// PlayView.waitingConfirm();
}while(!gameOver);
}
public int countAndRemove(Dices dices) {
int now_roll_number=dices.getNumber();
int[] rollscore=dices.getPoint();
int[] roll=new int[7];
for(int score=1;score<=6;score++) roll[score]=0;
for(int dicesid=0;dicesid<now_roll_number;dicesid++)
roll[rollscore[dicesid]]++;
int nowscore=0,decroll=0;
if (roll[1]==6) {
roll[1]-=6;
nowscore+=3000;
decroll+=6;
}
if (roll[1]>=3) {
roll[1]-=3;
nowscore+=1000;
decroll+=3;
}
for(int score=2;score<=6;score++) {
if (roll[score]>=3) {
roll[score]-=3;
nowscore+=score*100;
decroll+=3;
}
if (roll[score]>=3) {
roll[score]-=3;
nowscore+=score*100;
decroll+=3;
}
}
while (roll[1]>0) {
roll[1]--;
nowscore+=100;
decroll++;
}
while (roll[5]>0) {
roll[5]--;
nowscore+=50;
decroll++;
}
dices.removeDices(decroll);
return nowscore;
}
public void sortPlayers(Player[] players,int playerNum)
{
Random rand = new Random();
Player tmpPlayer;
for(int i=0;i<playerNum;i++) {
int now=rand.nextInt(i+1);
// Player swapPlayer=players[now];
tmpPlayer=players[now];
players[now]=players[i];
players[i]=tmpPlayer;
// System.out.println(now+":"+tmpPlayer.getName()+","+players[now].getName()+","+players[i].getName());
}
String[] name=new String[playerNum];
for(int i=0;i<playerNum;i++) {
name[i]=players[i].getName();
}
PlayView.shuffledPlayerOut(name,playerNum);
}
}
| false |
47621_2 | package dt08;
import java.net.*;
import java.io.*;
// 建立SocketServer,监听 9001端口
// 客户端连接到SocketServer后,Server显示客户端发送过来的字符串
// 客户端发来 exit 字串,则断开连接
public class ChatServer1 {
public static void main(String[] args) throws IOException, InterruptedException {
final int port = 9001;
ServerSocket ss = new ServerSocket(port);
System.out.println("Server started @" + port);
Socket socket = ss.accept();
System.out.println("Client connected");
DataInputStream input = new DataInputStream(socket.getInputStream());
String line;
while (true) {
if ((line = input.readUTF()) != null) {
if (line.equals("exit")) {
System.out.println("Client disconnected");
break; // 退出循环
} else { // 将信息打印到屏幕上
System.out.println(line);
}
} else { // 没有输入
Thread.sleep(100);
}
}
input.close();
socket.close();
ss.close();
}
}
| AlohaWorld/Lessons4JavaSE | src/dt08/ChatServer1.java | 270 | // 客户端发来 exit 字串,则断开连接 | line_comment | zh-cn | package dt08;
import java.net.*;
import java.io.*;
// 建立SocketServer,监听 9001端口
// 客户端连接到SocketServer后,Server显示客户端发送过来的字符串
// 客户 <SUF>
public class ChatServer1 {
public static void main(String[] args) throws IOException, InterruptedException {
final int port = 9001;
ServerSocket ss = new ServerSocket(port);
System.out.println("Server started @" + port);
Socket socket = ss.accept();
System.out.println("Client connected");
DataInputStream input = new DataInputStream(socket.getInputStream());
String line;
while (true) {
if ((line = input.readUTF()) != null) {
if (line.equals("exit")) {
System.out.println("Client disconnected");
break; // 退出循环
} else { // 将信息打印到屏幕上
System.out.println(line);
}
} else { // 没有输入
Thread.sleep(100);
}
}
input.close();
socket.close();
ss.close();
}
}
| false |
28791_17 | import java.io.*;
import java.security.*;
import java.lang.reflect.*;
import javax.crypto.*;
import javax.crypto.spec.*;
public class MyClassLoader extends ClassLoader {
// 这些对象在构造函数中设置,
// 以后loadClass()方法将利用它们解密类
private SecretKey key;
private Cipher cipher;
// 设置解密所需要的对象
public MyClassLoader(SecretKey key) throws GeneralSecurityException, IOException {
this.key = key;
String algorithm = "DES";
SecureRandom sr = new SecureRandom();
System.err.println("[MyClassLoader: creating cipher]");
cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.DECRYPT_MODE, key, sr);
}
// main过程:读入密匙,创建MyClassLoader的
// 实例,它就是我们的定制ClassLoader。
// 设置好ClassLoader以后,用它装入应用实例,
// 最后,通过Java Reflection API调用应用实例的main方法
static public void main(String args[]) throws Exception {
String keyFilename = args[0];
String appName = args[1];
// 这些是传递给应用本身的参数
String realArgs[] = new String[args.length - 2];
System.arraycopy(args, 2, realArgs, 0, args.length - 2);
// 读取密匙
System.err.println("[MyClassLoader: reading key]");
byte rawKey[] = FileUtil.readFile(keyFilename);
DESKeySpec dks = new DESKeySpec(rawKey);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey key = keyFactory.generateSecret(dks);
// 创建解密的ClassLoader
MyClassLoader dr = new MyClassLoader(key);
// 创建应用主类的一个实例
// 通过ClassLoader装入它
System.err.println("[MyClassLoader: loading " + appName + "]");
Class clasz = dr.loadClass(appName);
// 最后,通过Reflection API调用应用实例的main()方法
// 获取一个对main()的引用
String proto[] = new String[1];
Class mainArgs[] = { (new String[1]).getClass() };
Method main = clasz.getMethod("main", mainArgs);
// 创建一个包含main()方法参数的数组
Object argsArray[] = { realArgs };
System.err.println("[MyClassLoader: running " + appName + ".main()]");
// 调用main()
main.invoke(null, argsArray);
}
public Class loadClass(String name, boolean resolve) throws ClassNotFoundException {
try {
// 要创建的Class对象
Class clasz = null;
// 如果类已经在系统缓冲之中,不必再次装入它
clasz = findLoadedClass(name);
if (clasz != null)
return clasz;
// 下面是定制部分
try {
// 读取经过加密的类文件
byte classData[] = FileUtil.readFile(name + ".class");
if (classData != null) {
// 解密...
byte decryptedClassData[] = cipher.doFinal(classData);
// ... 再把它转换成一个类
clasz = defineClass(name.replace('/', '.'), decryptedClassData, 0, decryptedClassData.length);
System.err.println("[MyClassLoader: decrypting class " + name + "]");
}
} catch (FileNotFoundException e) {
//e.printStackTrace();
}
// 如果上面没有成功尝试用默认的ClassLoader装入它
if (clasz == null)
clasz = findSystemClass(name);
// 如有必要,则装入相关的类
if (resolve && clasz != null)
resolveClass(clasz);
// 把类返回给调用者
return clasz;
} catch (IOException ie) {
throw new ClassNotFoundException(ie.toString());
} catch (GeneralSecurityException gse) {
throw new ClassNotFoundException(gse.toString());
}
}
}
| AloneMonkey/JarEncrypt | ClassLoader/MyClassLoader.java | 992 | // 如果类已经在系统缓冲之中,不必再次装入它
| line_comment | zh-cn | import java.io.*;
import java.security.*;
import java.lang.reflect.*;
import javax.crypto.*;
import javax.crypto.spec.*;
public class MyClassLoader extends ClassLoader {
// 这些对象在构造函数中设置,
// 以后loadClass()方法将利用它们解密类
private SecretKey key;
private Cipher cipher;
// 设置解密所需要的对象
public MyClassLoader(SecretKey key) throws GeneralSecurityException, IOException {
this.key = key;
String algorithm = "DES";
SecureRandom sr = new SecureRandom();
System.err.println("[MyClassLoader: creating cipher]");
cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.DECRYPT_MODE, key, sr);
}
// main过程:读入密匙,创建MyClassLoader的
// 实例,它就是我们的定制ClassLoader。
// 设置好ClassLoader以后,用它装入应用实例,
// 最后,通过Java Reflection API调用应用实例的main方法
static public void main(String args[]) throws Exception {
String keyFilename = args[0];
String appName = args[1];
// 这些是传递给应用本身的参数
String realArgs[] = new String[args.length - 2];
System.arraycopy(args, 2, realArgs, 0, args.length - 2);
// 读取密匙
System.err.println("[MyClassLoader: reading key]");
byte rawKey[] = FileUtil.readFile(keyFilename);
DESKeySpec dks = new DESKeySpec(rawKey);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey key = keyFactory.generateSecret(dks);
// 创建解密的ClassLoader
MyClassLoader dr = new MyClassLoader(key);
// 创建应用主类的一个实例
// 通过ClassLoader装入它
System.err.println("[MyClassLoader: loading " + appName + "]");
Class clasz = dr.loadClass(appName);
// 最后,通过Reflection API调用应用实例的main()方法
// 获取一个对main()的引用
String proto[] = new String[1];
Class mainArgs[] = { (new String[1]).getClass() };
Method main = clasz.getMethod("main", mainArgs);
// 创建一个包含main()方法参数的数组
Object argsArray[] = { realArgs };
System.err.println("[MyClassLoader: running " + appName + ".main()]");
// 调用main()
main.invoke(null, argsArray);
}
public Class loadClass(String name, boolean resolve) throws ClassNotFoundException {
try {
// 要创建的Class对象
Class clasz = null;
// 如果 <SUF>
clasz = findLoadedClass(name);
if (clasz != null)
return clasz;
// 下面是定制部分
try {
// 读取经过加密的类文件
byte classData[] = FileUtil.readFile(name + ".class");
if (classData != null) {
// 解密...
byte decryptedClassData[] = cipher.doFinal(classData);
// ... 再把它转换成一个类
clasz = defineClass(name.replace('/', '.'), decryptedClassData, 0, decryptedClassData.length);
System.err.println("[MyClassLoader: decrypting class " + name + "]");
}
} catch (FileNotFoundException e) {
//e.printStackTrace();
}
// 如果上面没有成功尝试用默认的ClassLoader装入它
if (clasz == null)
clasz = findSystemClass(name);
// 如有必要,则装入相关的类
if (resolve && clasz != null)
resolveClass(clasz);
// 把类返回给调用者
return clasz;
} catch (IOException ie) {
throw new ClassNotFoundException(ie.toString());
} catch (GeneralSecurityException gse) {
throw new ClassNotFoundException(gse.toString());
}
}
}
| false |
58182_8 | package com.demo.app.hybrid.core;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.webkit.JavascriptInterface;
import com.demo.app.mvp.app.BaseApplication;
import com.demo.app.tinker.util.SampleApplicationContext;
import com.demo.app.util.IKeySourceUtil;
import com.demo.app.util.LogUtil;
public class Cookie {
protected ExceptionJson exceptionJson = new ExceptionJson();
public String memberIDKey = "userid";
private Context context = null;
protected BaseApplication application;
// private MyAoyouControllerImp myAoyouControllerImp;
public Cookie(Context context) {
this.context = context;
if (context instanceof Activity) {
this.application = SampleApplicationContext.application;
// initMemberControl();
} else if (context instanceof Service) {
application = SampleApplicationContext.application;
} else {
// application = (BaseApplication) BaseApplication.getMContext();
}
}
private SharedPreferences getApplication() {
return context.getSharedPreferences("data", Context.MODE_PRIVATE);
}
@JavascriptInterface
public String getUserId() {
//取出userId,返回给js
SharedPreferences settings = context.getSharedPreferences(
IKeySourceUtil.LOGIN_STATUS,
Context.MODE_PRIVATE);
String userid=settings.getString("demoId", "0");
LogUtil.i("hww:demoIdNew",userid+"");
return String.valueOf(userid);
}
/**
* 功能:设置dataKey的value,将dataKey属性的json串保存到sp中
* @param dataKey 某些key值
* @param value key对应的value值
* @param timeout 超时时间
* @return
*/
@JavascriptInterface
public String setCookie(String dataKey, String value, int timeout) {
LogUtil.i("hww", "setCookie " + "dataKey:" + dataKey + " value:" + value);
try {
// if (dataKey.toLowerCase().equals(memberIDKey.toLowerCase())) {
// return exceptionJson.CustomExceptionJson("cookie key不能使用" + memberIDKey.toLowerCase());
// }
SharedPreferences sharedPreferences = getApplication();
SharedPreferences.Editor editor = sharedPreferences.edit();
CookieValue cv = new CookieValue();
cv.dataKey = dataKey;
cv.value = value;//版本文件json串
cv.timeout = timeout;//超时时间
cv.date = new Date().getTime();//日期
editor.putString(dataKey, cv.ConvertJson());//将dataKey和它的value以及超时时间等等保存到sp中 保存String类型json串
editor.commit();
return exceptionJson.NoExceptionJson();
} catch (Exception e) {
return exceptionJson.SystemExceptionJson(e.getMessage());
}
}
public String setMemberID(String dataKey, String value, int timeout) {
try {
SharedPreferences sharedPreferences = getApplication();
SharedPreferences.Editor editor = sharedPreferences.edit();
/*
* CookieValue cv = new CookieValue(); cv.dataKey = dataKey;
* cv.value = value; cv.timeout = timeout; cv.date = new
* Date().getTime();
*/
editor.putString(dataKey, value);
editor.commit();
return exceptionJson.NoExceptionJson();
} catch (Exception e) {
return exceptionJson.SystemExceptionJson(e.getMessage());
}
}
/**
* js调用getCookie方法获取某个dataKey的value值
* @param dataKey 下载版本文件的url
* @return sp中保存的cookievalue 实体中的版本文件json字符串 获取dataKey对应的value值
*/
@JavascriptInterface
public String getCookie(String dataKey) {
SharedPreferences sharedPreferences = getApplication();
String jsonStr = sharedPreferences.getString(dataKey, "");//从sp中取出dataKey对应的value值 注意是String类型json串
if (!TextUtils.isEmpty(jsonStr)) {
CookieValue cookieValue = new CookieValue();
cookieValue.ConvertObj(jsonStr);//转化为Cookievalue实体
long longDate = cookieValue.date;
Date date = new Date(longDate);
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(date);
cal.add(Calendar.SECOND, cookieValue.timeout);
if (cookieValue.timeout > 0) {
Date now = new Date();
if (cal.getTime().getTime() < now.getTime()) {//如果cal的时间(也就是sp中保存的时间)<当前的时间,移除Cookie
removeCookie(dataKey);
return "";
}
}
return cookieValue.value;//value就是版本文件的内容 json串
}else{
return "";
}
}
/**
* 从sp中删除这个dataKey
* @param dataKey
* @return
*/
@JavascriptInterface
public String removeCookie(String dataKey) {
try {
SharedPreferences sharedPreferences = getApplication();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove(dataKey);
editor.commit();
return exceptionJson.NoExceptionJson();
} catch (Exception e) {
return exceptionJson.SystemExceptionJson(e.getMessage());
}
}
public class CookieValue {
public String dataKey;
public String value;
public int timeout;
public long date;
//拼接json
public String ConvertJson() {
JSONObject json = new JSONObject();
try {
json.put("dataKey", dataKey);
json.put("value", value);
json.put("timeout", timeout);
json.put("date", date);
} catch (JSONException e) {
e.printStackTrace();
}
return json.toString();
}
//解析json
public void ConvertObj(String jsonStr) {
try {
JSONObject result = new JSONObject(jsonStr);
dataKey = result.getString("dataKey");
value = result.getString("value");
timeout = result.getInt("timeout");
date = result.getLong("date");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
| AlpacaNotSheep/hybrid | Android/core/Cookie.java | 1,570 | //超时时间 | line_comment | zh-cn | package com.demo.app.hybrid.core;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.webkit.JavascriptInterface;
import com.demo.app.mvp.app.BaseApplication;
import com.demo.app.tinker.util.SampleApplicationContext;
import com.demo.app.util.IKeySourceUtil;
import com.demo.app.util.LogUtil;
public class Cookie {
protected ExceptionJson exceptionJson = new ExceptionJson();
public String memberIDKey = "userid";
private Context context = null;
protected BaseApplication application;
// private MyAoyouControllerImp myAoyouControllerImp;
public Cookie(Context context) {
this.context = context;
if (context instanceof Activity) {
this.application = SampleApplicationContext.application;
// initMemberControl();
} else if (context instanceof Service) {
application = SampleApplicationContext.application;
} else {
// application = (BaseApplication) BaseApplication.getMContext();
}
}
private SharedPreferences getApplication() {
return context.getSharedPreferences("data", Context.MODE_PRIVATE);
}
@JavascriptInterface
public String getUserId() {
//取出userId,返回给js
SharedPreferences settings = context.getSharedPreferences(
IKeySourceUtil.LOGIN_STATUS,
Context.MODE_PRIVATE);
String userid=settings.getString("demoId", "0");
LogUtil.i("hww:demoIdNew",userid+"");
return String.valueOf(userid);
}
/**
* 功能:设置dataKey的value,将dataKey属性的json串保存到sp中
* @param dataKey 某些key值
* @param value key对应的value值
* @param timeout 超时时间
* @return
*/
@JavascriptInterface
public String setCookie(String dataKey, String value, int timeout) {
LogUtil.i("hww", "setCookie " + "dataKey:" + dataKey + " value:" + value);
try {
// if (dataKey.toLowerCase().equals(memberIDKey.toLowerCase())) {
// return exceptionJson.CustomExceptionJson("cookie key不能使用" + memberIDKey.toLowerCase());
// }
SharedPreferences sharedPreferences = getApplication();
SharedPreferences.Editor editor = sharedPreferences.edit();
CookieValue cv = new CookieValue();
cv.dataKey = dataKey;
cv.value = value;//版本文件json串
cv.timeout = timeout;//超时 <SUF>
cv.date = new Date().getTime();//日期
editor.putString(dataKey, cv.ConvertJson());//将dataKey和它的value以及超时时间等等保存到sp中 保存String类型json串
editor.commit();
return exceptionJson.NoExceptionJson();
} catch (Exception e) {
return exceptionJson.SystemExceptionJson(e.getMessage());
}
}
public String setMemberID(String dataKey, String value, int timeout) {
try {
SharedPreferences sharedPreferences = getApplication();
SharedPreferences.Editor editor = sharedPreferences.edit();
/*
* CookieValue cv = new CookieValue(); cv.dataKey = dataKey;
* cv.value = value; cv.timeout = timeout; cv.date = new
* Date().getTime();
*/
editor.putString(dataKey, value);
editor.commit();
return exceptionJson.NoExceptionJson();
} catch (Exception e) {
return exceptionJson.SystemExceptionJson(e.getMessage());
}
}
/**
* js调用getCookie方法获取某个dataKey的value值
* @param dataKey 下载版本文件的url
* @return sp中保存的cookievalue 实体中的版本文件json字符串 获取dataKey对应的value值
*/
@JavascriptInterface
public String getCookie(String dataKey) {
SharedPreferences sharedPreferences = getApplication();
String jsonStr = sharedPreferences.getString(dataKey, "");//从sp中取出dataKey对应的value值 注意是String类型json串
if (!TextUtils.isEmpty(jsonStr)) {
CookieValue cookieValue = new CookieValue();
cookieValue.ConvertObj(jsonStr);//转化为Cookievalue实体
long longDate = cookieValue.date;
Date date = new Date(longDate);
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(date);
cal.add(Calendar.SECOND, cookieValue.timeout);
if (cookieValue.timeout > 0) {
Date now = new Date();
if (cal.getTime().getTime() < now.getTime()) {//如果cal的时间(也就是sp中保存的时间)<当前的时间,移除Cookie
removeCookie(dataKey);
return "";
}
}
return cookieValue.value;//value就是版本文件的内容 json串
}else{
return "";
}
}
/**
* 从sp中删除这个dataKey
* @param dataKey
* @return
*/
@JavascriptInterface
public String removeCookie(String dataKey) {
try {
SharedPreferences sharedPreferences = getApplication();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove(dataKey);
editor.commit();
return exceptionJson.NoExceptionJson();
} catch (Exception e) {
return exceptionJson.SystemExceptionJson(e.getMessage());
}
}
public class CookieValue {
public String dataKey;
public String value;
public int timeout;
public long date;
//拼接json
public String ConvertJson() {
JSONObject json = new JSONObject();
try {
json.put("dataKey", dataKey);
json.put("value", value);
json.put("timeout", timeout);
json.put("date", date);
} catch (JSONException e) {
e.printStackTrace();
}
return json.toString();
}
//解析json
public void ConvertObj(String jsonStr) {
try {
JSONObject result = new JSONObject(jsonStr);
dataKey = result.getString("dataKey");
value = result.getString("value");
timeout = result.getInt("timeout");
date = result.getLong("date");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
| false |
46571_0 | class Member{ //员工
// 两个字段
private String memId;
private String memName;
private Dept dept;
// 构造方法
public Member(){}
public Member(String memId,String memName){
this.memId = memId;
this.memName = memName;
}
public void setDept(Dept dept){
this.dept = dept ;
}
public Dept getDept(){
return this.dept;
}
public String getMemInfo(){
return "【Member】memId="+memId+",memName="+memName;
}
}
class Dept{ //部门
private String deptId;
private String deptName;
private Member[] members;
private Role role;
// 构造方法
public Dept(){}
public Dept(String deptId,String deptName){
this.deptId = deptId;
this.deptName = deptName ;
}
public void setMember(Member[] members){
this.members = members;
}
public Member[] getMember(){
return this.members;
}
public void setRole(Role role){
this.role = role;
}
public Role getRole(){
return this.role;
}
public String getDeptInfo(){
return "【Dept】deptId="+deptId+",deptName="+deptName;
}
}
class Role{//角色
private String roleId;
private String roleName;
private Dept[] depts;
private Permission[] permissions;
public Role(){}
public Role(String roleId,String roleName){
this.roleId = roleId;
this.roleName = roleName ;
}
public void setDept(Dept[] depts){
this.depts = depts;
}
public Dept[] getDept(){
return this.depts;
}
public void setPermission(Permission[] permissions){
this.permissions = permissions;
}
public Permission[] getPermission(){
return permissions;
}
public String getRoleInfo(){
return "【Role】roleId="+roleId+",roleName="+roleName;
}
}
class Permission{//权限
private String perId;
private String perName;
private String perMark;
private Role[] roles;
public Permission (){}
public Permission (String perId,String perName,String perMark){
this.perId=perId;
this.perName = perName;
this.perMark = perMark;
}
public void setRole(Role[] roles){
this.roles = roles;
}
public Role[] getRole(){
return this.roles;
}
public String getPermissInfo(){
return "【Permission】perId="+perId+",perName="+perName+",perMark="+perMark;
}
}
public class TestThree{
public static void main(String[] args) {
//部门 和员工
Dept dept1 = new Dept("001","生产部");
Dept dept2 = new Dept("002","销售部");
Dept dept3 = new Dept("003","技术部");
Member mem1 = new Member("001","jack");
Member mem2 = new Member("002","ellen");
Member mem3 = new Member("003","eric");
Member mem4 = new Member("004","Paul");
Member mem5 = new Member("005","Jade");
dept1.setMember(new Member[]{mem1,mem4});
dept2.setMember(new Member[]{mem2,mem3});
dept3.setMember(new Member[]{mem5});
mem1.setDept(dept1);
mem2.setDept(dept2);
mem3.setDept(dept2);
mem4.setDept(dept1);
mem5.setDept(dept3);
// 部门和角色
Role role1 = new Role("1000","员工");
Role role2 = new Role("1001","经理");
role1.setDept(new Dept[]{dept1,dept3});
role2.setDept(new Dept[]{dept2});
dept1.setRole(role1);
dept2.setRole(role2);
dept3.setRole(role1);
// 角色和权限 互相塞数据
Permission per1 = new Permission("88001","广告","编辑");
Permission per2 = new Permission("88002","文件","修改");
Permission per3 = new Permission("88003","招聘","删除");
Permission per4 = new Permission("88004","招聘","编辑");
Permission per5 = new Permission("88005","广告","增加");
per1.setRole(new Role[]{role1});
per2.setRole(new Role[]{role1,role2});
per3.setRole(new Role[]{role2});
per4.setRole(new Role[]{role2});
per5.setRole(new Role[]{role1});
role1.setPermission(new Permission[]{per1,per2,per5});
role2.setPermission(new Permission[]{per3,per4});
// ==============================第一问=============================================
System.out.println("==========第一问=======");
System.out.println(mem1.getMemInfo());
System.out.println("\t|-"+mem1.getDept().getDeptInfo());
System.out.println("\t|-"+mem1.getDept().getRole().getRoleInfo());
// System.out.println(mem1.getDept().getRole().getPermission().length) ;
for(int x = 0 ; x < mem1.getDept().getRole().getPermission().length; x++){
System.out.println("\t\t|-"+mem1.getDept().getRole().getPermission()[x].getPermissInfo());
}
// ================================第二问===========================================
System.out.println("==========第二问=======");
System.out.println(role1.getRoleInfo());
// System.out.println(role2.getDept().length);
for (int x = 0; x < role1.getDept().length; x++) {
System.out.println("\t\t|-"+role1.getDept()[x].getDeptInfo());
}
// ================================第三问===========================================
System.out.println("==========第三问=======");
// System.out.println(per2.getRole().length);
for (int x = 0; x < per2.getRole().length ; x++ ) {
System.out.println(per2.getRole()[x].getRoleInfo());
for(int y = 0 ; y < per2.getRole()[x].getDept().length; y++){
System.out.println("\t"+per2.getRole()[x].getDept()[y].getDeptInfo());
for (int z = 0; z < per2.getRole()[x].getDept()[y].getMember().length ;z++ ) {
System.out.println("\t\t"+per2.getRole()[x].getDept()[y].getMember()[z].getMemInfo());
}
}
}
}
} | AlvaWymer/-02_final | TestThree.java | 1,801 | // 两个字段 | line_comment | zh-cn | class Member{ //员工
// 两个 <SUF>
private String memId;
private String memName;
private Dept dept;
// 构造方法
public Member(){}
public Member(String memId,String memName){
this.memId = memId;
this.memName = memName;
}
public void setDept(Dept dept){
this.dept = dept ;
}
public Dept getDept(){
return this.dept;
}
public String getMemInfo(){
return "【Member】memId="+memId+",memName="+memName;
}
}
class Dept{ //部门
private String deptId;
private String deptName;
private Member[] members;
private Role role;
// 构造方法
public Dept(){}
public Dept(String deptId,String deptName){
this.deptId = deptId;
this.deptName = deptName ;
}
public void setMember(Member[] members){
this.members = members;
}
public Member[] getMember(){
return this.members;
}
public void setRole(Role role){
this.role = role;
}
public Role getRole(){
return this.role;
}
public String getDeptInfo(){
return "【Dept】deptId="+deptId+",deptName="+deptName;
}
}
class Role{//角色
private String roleId;
private String roleName;
private Dept[] depts;
private Permission[] permissions;
public Role(){}
public Role(String roleId,String roleName){
this.roleId = roleId;
this.roleName = roleName ;
}
public void setDept(Dept[] depts){
this.depts = depts;
}
public Dept[] getDept(){
return this.depts;
}
public void setPermission(Permission[] permissions){
this.permissions = permissions;
}
public Permission[] getPermission(){
return permissions;
}
public String getRoleInfo(){
return "【Role】roleId="+roleId+",roleName="+roleName;
}
}
class Permission{//权限
private String perId;
private String perName;
private String perMark;
private Role[] roles;
public Permission (){}
public Permission (String perId,String perName,String perMark){
this.perId=perId;
this.perName = perName;
this.perMark = perMark;
}
public void setRole(Role[] roles){
this.roles = roles;
}
public Role[] getRole(){
return this.roles;
}
public String getPermissInfo(){
return "【Permission】perId="+perId+",perName="+perName+",perMark="+perMark;
}
}
public class TestThree{
public static void main(String[] args) {
//部门 和员工
Dept dept1 = new Dept("001","生产部");
Dept dept2 = new Dept("002","销售部");
Dept dept3 = new Dept("003","技术部");
Member mem1 = new Member("001","jack");
Member mem2 = new Member("002","ellen");
Member mem3 = new Member("003","eric");
Member mem4 = new Member("004","Paul");
Member mem5 = new Member("005","Jade");
dept1.setMember(new Member[]{mem1,mem4});
dept2.setMember(new Member[]{mem2,mem3});
dept3.setMember(new Member[]{mem5});
mem1.setDept(dept1);
mem2.setDept(dept2);
mem3.setDept(dept2);
mem4.setDept(dept1);
mem5.setDept(dept3);
// 部门和角色
Role role1 = new Role("1000","员工");
Role role2 = new Role("1001","经理");
role1.setDept(new Dept[]{dept1,dept3});
role2.setDept(new Dept[]{dept2});
dept1.setRole(role1);
dept2.setRole(role2);
dept3.setRole(role1);
// 角色和权限 互相塞数据
Permission per1 = new Permission("88001","广告","编辑");
Permission per2 = new Permission("88002","文件","修改");
Permission per3 = new Permission("88003","招聘","删除");
Permission per4 = new Permission("88004","招聘","编辑");
Permission per5 = new Permission("88005","广告","增加");
per1.setRole(new Role[]{role1});
per2.setRole(new Role[]{role1,role2});
per3.setRole(new Role[]{role2});
per4.setRole(new Role[]{role2});
per5.setRole(new Role[]{role1});
role1.setPermission(new Permission[]{per1,per2,per5});
role2.setPermission(new Permission[]{per3,per4});
// ==============================第一问=============================================
System.out.println("==========第一问=======");
System.out.println(mem1.getMemInfo());
System.out.println("\t|-"+mem1.getDept().getDeptInfo());
System.out.println("\t|-"+mem1.getDept().getRole().getRoleInfo());
// System.out.println(mem1.getDept().getRole().getPermission().length) ;
for(int x = 0 ; x < mem1.getDept().getRole().getPermission().length; x++){
System.out.println("\t\t|-"+mem1.getDept().getRole().getPermission()[x].getPermissInfo());
}
// ================================第二问===========================================
System.out.println("==========第二问=======");
System.out.println(role1.getRoleInfo());
// System.out.println(role2.getDept().length);
for (int x = 0; x < role1.getDept().length; x++) {
System.out.println("\t\t|-"+role1.getDept()[x].getDeptInfo());
}
// ================================第三问===========================================
System.out.println("==========第三问=======");
// System.out.println(per2.getRole().length);
for (int x = 0; x < per2.getRole().length ; x++ ) {
System.out.println(per2.getRole()[x].getRoleInfo());
for(int y = 0 ; y < per2.getRole()[x].getDept().length; y++){
System.out.println("\t"+per2.getRole()[x].getDept()[y].getDeptInfo());
for (int z = 0; z < per2.getRole()[x].getDept()[y].getMember().length ;z++ ) {
System.out.println("\t\t"+per2.getRole()[x].getDept()[y].getMember()[z].getMemInfo());
}
}
}
}
} | false |
52824_14 | package cn.mldn.shiro.realm;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import cn.mldn.shiro.service.IMemberService;
import cn.mldn.shiro.service.impl.MemberServiceImpl;
import cn.mldn.shiro.vo.Member;
public class MyDefaultRealm extends AuthorizingRealm {
@Override
protected AuthorizationInfo doGetAuthorizationInfo(
PrincipalCollection principals) {
System.out.println("++++++++++++++ 2、进行授权操作处理 ++++++++++++++");
// 该操作的主要目的是取得授权信息,说的直白一点就是角色和权限数据
SimpleAuthorizationInfo auth = new SimpleAuthorizationInfo() ;
// 执行到此方法的时候一定是已经进行过用户认证处理了(用户名和密码一定是正确的)
String mid = (String) principals.getPrimaryPrincipal() ; // 取得用户名
try {
// 存在了用户编号之后就意味着可以进行用户的角色或权限数据查询
IMemberService memberService = new MemberServiceImpl();
auth.setRoles(memberService.listRolesByMember(mid)); // 保存所有的角色
auth.setStringPermissions(memberService.listActionsByMember(mid)); // 保存所有的权限
} catch (Exception e) {
e.printStackTrace();
}
return auth ;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(
AuthenticationToken token) throws AuthenticationException {
System.out.println("============== 1、进行认证操作处理 ==============");
// 用户的认证信息一定要通过IMemberService获取
IMemberService memberService = new MemberServiceImpl();
String userid = token.getPrincipal().toString(); // 用户名
// 定义需要进行返回的操作数据信息项
SimpleAuthenticationInfo auth = new SimpleAuthenticationInfo(
token.getPrincipal(), token.getCredentials(), "memberRealm");
try {
// 取得用户名之后就需要通过业务层获取用户对象以确定改用户名是否可用
Member member = memberService.get(userid); // 通过用户名获取用户信息
if (member == null) { // 表示该用户信息不存在,不存在则应该抛出一个异常
throw new UnknownAccountException("搞什么搞,用户名不存在!");
}
// 用户名如果存在了,那么就需要确定密码是否正确
String password = new String((char[]) token.getCredentials());
if (!password.equals(member.getPassword())) { // 密码验证
throw new IncorrectCredentialsException("密码都记不住,去死吧!");
}
// 随后还需要考虑用户被锁定的问题
if (member.getLocked().equals(1)) { // 1表示非0,非0就是true
throw new LockedAccountException("被锁了,求解锁去吧!");
}
} catch (Exception e) {
e.printStackTrace();
}
return auth;
}
}
| AlvaWymer/Shiro-Demo | Shiro-Auth/src/main/java/cn/mldn/shiro/realm/MyDefaultRealm.java | 843 | // 随后还需要考虑用户被锁定的问题 | line_comment | zh-cn | package cn.mldn.shiro.realm;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import cn.mldn.shiro.service.IMemberService;
import cn.mldn.shiro.service.impl.MemberServiceImpl;
import cn.mldn.shiro.vo.Member;
public class MyDefaultRealm extends AuthorizingRealm {
@Override
protected AuthorizationInfo doGetAuthorizationInfo(
PrincipalCollection principals) {
System.out.println("++++++++++++++ 2、进行授权操作处理 ++++++++++++++");
// 该操作的主要目的是取得授权信息,说的直白一点就是角色和权限数据
SimpleAuthorizationInfo auth = new SimpleAuthorizationInfo() ;
// 执行到此方法的时候一定是已经进行过用户认证处理了(用户名和密码一定是正确的)
String mid = (String) principals.getPrimaryPrincipal() ; // 取得用户名
try {
// 存在了用户编号之后就意味着可以进行用户的角色或权限数据查询
IMemberService memberService = new MemberServiceImpl();
auth.setRoles(memberService.listRolesByMember(mid)); // 保存所有的角色
auth.setStringPermissions(memberService.listActionsByMember(mid)); // 保存所有的权限
} catch (Exception e) {
e.printStackTrace();
}
return auth ;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(
AuthenticationToken token) throws AuthenticationException {
System.out.println("============== 1、进行认证操作处理 ==============");
// 用户的认证信息一定要通过IMemberService获取
IMemberService memberService = new MemberServiceImpl();
String userid = token.getPrincipal().toString(); // 用户名
// 定义需要进行返回的操作数据信息项
SimpleAuthenticationInfo auth = new SimpleAuthenticationInfo(
token.getPrincipal(), token.getCredentials(), "memberRealm");
try {
// 取得用户名之后就需要通过业务层获取用户对象以确定改用户名是否可用
Member member = memberService.get(userid); // 通过用户名获取用户信息
if (member == null) { // 表示该用户信息不存在,不存在则应该抛出一个异常
throw new UnknownAccountException("搞什么搞,用户名不存在!");
}
// 用户名如果存在了,那么就需要确定密码是否正确
String password = new String((char[]) token.getCredentials());
if (!password.equals(member.getPassword())) { // 密码验证
throw new IncorrectCredentialsException("密码都记不住,去死吧!");
}
// 随后 <SUF>
if (member.getLocked().equals(1)) { // 1表示非0,非0就是true
throw new LockedAccountException("被锁了,求解锁去吧!");
}
} catch (Exception e) {
e.printStackTrace();
}
return auth;
}
}
| false |
17317_2 |
/******
* 快速排序
*
* 分治思想
*
*
* 设要排序的数组是A[0]⋯⋯A[N-1],首先任意选取一个数据(通常选用第1个数据)作为关键数据,
* 然后将所有比它小的数都放到它前面,所有比它大的数都放到它后面,
* 这个过程称为一趟快速排序。值得注意的是,快速排序不是一种稳定的排序算法,
* 也就是说,多个相同的值的相对位置也许会在算法结束时产生变动。
一趟快速排序的算法是:
1)设置两个变量i、j,排序开始的时候:i=0,j=N-1;
2)以第一个数组元素作为关键数据,赋值给key,即key=A[0];
3)从j开始向前搜索,即由后开始向前搜索(j -- ),找到第一个小于key的值A[j],A[i]与A[j]交换;
4)从i开始向后搜索,即由前开始向后搜索(i ++ ),找到第一个大于key的A[i],A[i]与A[j]交换;
5)重复第3、4、5步,直到 I=J; (3,4步是在程序中没找到时候j=j-1,i=i+1,直至找到为止。找到并交换的时候i,
j指针位置不变。另外当i=j这过程一定正好是i+或j-完成的最后令循环结束。
*
* **/
public class QuickSort {
/**
* @param args
*/
public static void main(String[] args) {
int n = 10;
int[] a = new int[n];
for(int i = 0; i < a.length; i++)
a[i] = (int)(Math.random() * 100);
disp(a);
sort(a, 0, a.length - 1);
disp(a);
System.out.println("yagnaihua "); System.out.println("yagnaihua好的话的反对 ");
}
private static void sort(int[] a, int left, int right) { //分为两部分,一个是左部分,一个是右部分
if (left >= right) return;
int i = left, j = right + 1;
while(true){
do{
i++;
}while(i <= right && a[i] < a[left]);
do{
j--;
}while(a[j] > a[left]);
if (i >= j) break;
swap(a, i, j);
}
swap(a, j, left);
sort(a, left, j - 1);
sort(a, j + 1, right);
}
private static void swap(int[] a, int i, int j) {
int tem = a[i];
a[i] = a[j];
a[j] = tem;
}
private static void disp(int[] a) {
for(int i = 0; i < a.length; i++)
System.out.printf("%d ", a[i]);
System.out.println();
}
}
| AlvaWymer/test1 | QuickSort.java | 812 | //分为两部分,一个是左部分,一个是右部分 | line_comment | zh-cn |
/******
* 快速排序
*
* 分治思想
*
*
* 设要排序的数组是A[0]⋯⋯A[N-1],首先任意选取一个数据(通常选用第1个数据)作为关键数据,
* 然后将所有比它小的数都放到它前面,所有比它大的数都放到它后面,
* 这个过程称为一趟快速排序。值得注意的是,快速排序不是一种稳定的排序算法,
* 也就是说,多个相同的值的相对位置也许会在算法结束时产生变动。
一趟快速排序的算法是:
1)设置两个变量i、j,排序开始的时候:i=0,j=N-1;
2)以第一个数组元素作为关键数据,赋值给key,即key=A[0];
3)从j开始向前搜索,即由后开始向前搜索(j -- ),找到第一个小于key的值A[j],A[i]与A[j]交换;
4)从i开始向后搜索,即由前开始向后搜索(i ++ ),找到第一个大于key的A[i],A[i]与A[j]交换;
5)重复第3、4、5步,直到 I=J; (3,4步是在程序中没找到时候j=j-1,i=i+1,直至找到为止。找到并交换的时候i,
j指针位置不变。另外当i=j这过程一定正好是i+或j-完成的最后令循环结束。
*
* **/
public class QuickSort {
/**
* @param args
*/
public static void main(String[] args) {
int n = 10;
int[] a = new int[n];
for(int i = 0; i < a.length; i++)
a[i] = (int)(Math.random() * 100);
disp(a);
sort(a, 0, a.length - 1);
disp(a);
System.out.println("yagnaihua "); System.out.println("yagnaihua好的话的反对 ");
}
private static void sort(int[] a, int left, int right) { //分为 <SUF>
if (left >= right) return;
int i = left, j = right + 1;
while(true){
do{
i++;
}while(i <= right && a[i] < a[left]);
do{
j--;
}while(a[j] > a[left]);
if (i >= j) break;
swap(a, i, j);
}
swap(a, j, left);
sort(a, left, j - 1);
sort(a, j + 1, right);
}
private static void swap(int[] a, int i, int j) {
int tem = a[i];
a[i] = a[j];
a[j] = tem;
}
private static void disp(int[] a) {
for(int i = 0; i < a.length; i++)
System.out.printf("%d ", a[i]);
System.out.println();
}
}
| false |
55801_0 | /**
*
*/
package entity;
import java.awt.Point;
import java.util.Random;
import util.GameMethod;
import config.GameConfig;
/**
* 俄罗斯方块的抽象类,成员:能否旋转,需要几个坐标(方块)组成,初始形态(竖的或横的) 方法:下落、位移、旋转
*
* @author phx
*/
public abstract class Tetriminos {
public static int MIN_X = GameConfig.getSYSTEM().getMinX();
public static int MAX_X = GameConfig.getSYSTEM().getMaxX();
protected static Random rand = new Random();
protected boolean rotatable;
protected byte shapeID;
/**
* mark rotate how many time then use to sync the
* hint picture
*/
protected int rotateFlag;
/**
* use to initialize the Tetriminos
*/
protected Point[] fallCoords;
/**
* use to make a hint shadow
*/
protected Point[] bottomCoords;
public Tetriminos( byte ID, boolean rotatable, int rotateFlag, Point[] fall) {
this.shapeID = ID;
this.rotatable = rotatable;
this.rotateFlag = rotateFlag;
this.fallCoords = fall;
}
public Tetriminos( byte ID) {
this.shapeID = ID;
}
/**
* rotate method
* @return coordinates after rotate
*/
public Point[] rotate() {
Point[] rotated = GameMethod.copyCoords(fallCoords);
// if the coords in the boundary move to left or right first
if(rotated[0].x == MIN_X) {
move(rotated, 1, 0);
}else if(rotated[0].x == MAX_X) {
move(rotated, -1, 0);
}
for (int i = 0; i < 4; i++) {
int newX = rotated[0].x + rotated[0].y - rotated[i].y;
int newY = rotated[0].y - rotated[0].x + rotated[i].x;
rotated[i] = new Point(newX, newY);
}
return rotated;
}
public boolean move(Point[] oldCoords, int newX, int newY) {
int len = oldCoords.length;
/* side effect */
for (int i = 0; i < len; i++) {
oldCoords[i].x += newX;
oldCoords[i].y += newY;
}
return true;
}
public boolean isRotatable() {
return rotatable;
}
public byte getShapeID() {
return shapeID;
}
public int getRotateFlag() {
return rotateFlag;
}
public Point[] getFallCoords() {
return fallCoords;
}
public void setFallCoords(Point[] fallCoords) {
this.fallCoords = fallCoords;
}
public Point[] getBottomCoords() {
return bottomCoords;
}
public void setBottomCoords(Point[] bottomCoords) {
this.bottomCoords = bottomCoords;
}
}
| Alwayswithme/JavaTetris | src/entity/Tetriminos.java | 793 | /**
* 俄罗斯方块的抽象类,成员:能否旋转,需要几个坐标(方块)组成,初始形态(竖的或横的) 方法:下落、位移、旋转
*
* @author phx
*/ | block_comment | zh-cn | /**
*
*/
package entity;
import java.awt.Point;
import java.util.Random;
import util.GameMethod;
import config.GameConfig;
/**
* 俄罗斯 <SUF>*/
public abstract class Tetriminos {
public static int MIN_X = GameConfig.getSYSTEM().getMinX();
public static int MAX_X = GameConfig.getSYSTEM().getMaxX();
protected static Random rand = new Random();
protected boolean rotatable;
protected byte shapeID;
/**
* mark rotate how many time then use to sync the
* hint picture
*/
protected int rotateFlag;
/**
* use to initialize the Tetriminos
*/
protected Point[] fallCoords;
/**
* use to make a hint shadow
*/
protected Point[] bottomCoords;
public Tetriminos( byte ID, boolean rotatable, int rotateFlag, Point[] fall) {
this.shapeID = ID;
this.rotatable = rotatable;
this.rotateFlag = rotateFlag;
this.fallCoords = fall;
}
public Tetriminos( byte ID) {
this.shapeID = ID;
}
/**
* rotate method
* @return coordinates after rotate
*/
public Point[] rotate() {
Point[] rotated = GameMethod.copyCoords(fallCoords);
// if the coords in the boundary move to left or right first
if(rotated[0].x == MIN_X) {
move(rotated, 1, 0);
}else if(rotated[0].x == MAX_X) {
move(rotated, -1, 0);
}
for (int i = 0; i < 4; i++) {
int newX = rotated[0].x + rotated[0].y - rotated[i].y;
int newY = rotated[0].y - rotated[0].x + rotated[i].x;
rotated[i] = new Point(newX, newY);
}
return rotated;
}
public boolean move(Point[] oldCoords, int newX, int newY) {
int len = oldCoords.length;
/* side effect */
for (int i = 0; i < len; i++) {
oldCoords[i].x += newX;
oldCoords[i].y += newY;
}
return true;
}
public boolean isRotatable() {
return rotatable;
}
public byte getShapeID() {
return shapeID;
}
public int getRotateFlag() {
return rotateFlag;
}
public Point[] getFallCoords() {
return fallCoords;
}
public void setFallCoords(Point[] fallCoords) {
this.fallCoords = fallCoords;
}
public Point[] getBottomCoords() {
return bottomCoords;
}
public void setBottomCoords(Point[] bottomCoords) {
this.bottomCoords = bottomCoords;
}
}
| false |
62045_3 | package com.order.dao;
import java.util.Set;
import com.order.entity.Message;
import com.order.entity.Orders;
import com.order.entity.User;
import com.order.entity.UserInfo;
public interface UserDao extends Dao{
/**
* 通过传入的部分用户信息来找回密码
* @param user
* @return
*/
public User getPasswd(User user);
/**
* 根据传入的用户信息来查找用户是否存在
* @param u
* @return
*/
public User userLogin(User u);
/**
* 判断用户邮箱是否激活
* @param
* @return
*/
public boolean mailActive(int id);
/**
* 通过邮箱判断用户是否存在
*/
public User userMail(String mail);
/**
* 根据传入的name判断用户名是否存在
* @param name
* @return
*/
public boolean judgeUser(String name);
/**
* 通过用户id得到Orders(订单)集合
* @param id
* @return
*/
public Set<Orders> find(int id);
/**
* 通过用户id来得到UserInfo(用户配送信息)对象
* @param id
* @return
*/
public UserInfo findUser(int id);
/**
* 通过用户id得到Message(留言)集合
* @param id
* @return
*/
public Set<Message> findMessageById(int id);
/**
* 通过用户的用户名得到用户的信息
* @param name
* @return
*/
public User findByName(String name);
/**
* 找回密码更新密码字段
* @param pass 用户输入的新密码
*/
public void updatePass(User user,String pass);
}
| AmazingT/OrderSystem | src/com/order/dao/UserDao.java | 416 | /**
* 通过邮箱判断用户是否存在
*/ | block_comment | zh-cn | package com.order.dao;
import java.util.Set;
import com.order.entity.Message;
import com.order.entity.Orders;
import com.order.entity.User;
import com.order.entity.UserInfo;
public interface UserDao extends Dao{
/**
* 通过传入的部分用户信息来找回密码
* @param user
* @return
*/
public User getPasswd(User user);
/**
* 根据传入的用户信息来查找用户是否存在
* @param u
* @return
*/
public User userLogin(User u);
/**
* 判断用户邮箱是否激活
* @param
* @return
*/
public boolean mailActive(int id);
/**
* 通过邮 <SUF>*/
public User userMail(String mail);
/**
* 根据传入的name判断用户名是否存在
* @param name
* @return
*/
public boolean judgeUser(String name);
/**
* 通过用户id得到Orders(订单)集合
* @param id
* @return
*/
public Set<Orders> find(int id);
/**
* 通过用户id来得到UserInfo(用户配送信息)对象
* @param id
* @return
*/
public UserInfo findUser(int id);
/**
* 通过用户id得到Message(留言)集合
* @param id
* @return
*/
public Set<Message> findMessageById(int id);
/**
* 通过用户的用户名得到用户的信息
* @param name
* @return
*/
public User findByName(String name);
/**
* 找回密码更新密码字段
* @param pass 用户输入的新密码
*/
public void updatePass(User user,String pass);
}
| false |
16723_87 | /*
* Copyright 2020-2023 the original author or authors.
*
* 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
*
* https://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.jun.mqttx.broker.handler;
import com.fasterxml.jackson.core.type.TypeReference;
import com.jun.mqttx.broker.BrokerHandler;
import com.jun.mqttx.config.MqttxConfig;
import com.jun.mqttx.constants.InternalMessageEnum;
import com.jun.mqttx.constants.ShareStrategy;
import com.jun.mqttx.consumer.Watcher;
import com.jun.mqttx.entity.ClientSub;
import com.jun.mqttx.entity.InternalMessage;
import com.jun.mqttx.entity.PubMsg;
import com.jun.mqttx.entity.Session;
import com.jun.mqttx.exception.AuthorizationException;
import com.jun.mqttx.service.*;
import com.jun.mqttx.utils.JsonSerializer;
import com.jun.mqttx.utils.RateLimiter;
import com.jun.mqttx.utils.Serializer;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.mqtt.*;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import reactor.core.publisher.Flux;
import reactor.core.publisher.GroupedFlux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
import java.time.Instant;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;
import static com.jun.mqttx.constants.ShareStrategy.random;
import static com.jun.mqttx.constants.ShareStrategy.round;
/**
* {@link MqttMessageType#PUBLISH} 处理器
*
* @author Jun
* @since 1.0.4
*/
@Handler(type = MqttMessageType.PUBLISH)
public class PublishHandler extends AbstractMqttTopicSecureHandler implements Watcher {
//@formatter:off
private final ISessionService sessionService;
private final IRetainMessageService retainMessageService;
private final ISubscriptionService subscriptionService;
private final IPublishMessageService publishMessageService;
private final IPubRelMessageService pubRelMessageService;
private final String brokerId;
private final boolean enableTopicSubPubSecure, enableRateLimiter, ignoreClientSelfPub;
/** 共享主题轮询策略 */
private final ShareStrategy shareStrategy;
/** 消息桥接开关 */
private final Boolean enableMessageBridge;
/** 主题限流器 */
private final Map<String, RateLimiter> rateLimiterMap = new HashMap<>();
private final Serializer serializer;
private IInternalMessagePublishService internalMessagePublishService;
/** 需要桥接消息的主题 */
private Set<String> bridgeTopics;
private KafkaTemplate<String, byte[]> kafkaTemplate;
/** 共享订阅轮询,存储轮询参数 */
private Map<String, AtomicInteger> roundMap;
//@formatter:on
public PublishHandler(IPublishMessageService publishMessageService,
IRetainMessageService retainMessageService,
ISubscriptionService subscriptionService,
IPubRelMessageService pubRelMessageService,
ISessionService sessionService,
@Nullable IInternalMessagePublishService internalMessagePublishService,
MqttxConfig config,
@Nullable KafkaTemplate<String, byte[]> kafkaTemplate,
Serializer serializer) {
super(config.getCluster().getEnable());
var shareTopic = config.getShareTopic();
var messageBridge = config.getMessageBridge();
var rateLimiter = config.getRateLimiter();
this.sessionService = sessionService;
this.serializer = serializer;
this.publishMessageService = publishMessageService;
this.retainMessageService = retainMessageService;
this.subscriptionService = subscriptionService;
this.pubRelMessageService = pubRelMessageService;
this.brokerId = config.getBrokerId();
this.enableTopicSubPubSecure = config.getEnableTopicSubPubSecure();
this.ignoreClientSelfPub = config.getIgnoreClientSelfPub();
if (!CollectionUtils.isEmpty(rateLimiter.getTopicRateLimits()) && rateLimiter.getEnable()) {
enableRateLimiter = true;
rateLimiter.getTopicRateLimits()
.forEach(
topicRateLimit -> rateLimiterMap.put(
topicRateLimit.getTopic(),
new RateLimiter(topicRateLimit.getCapacity(), topicRateLimit.getReplenishRate(), topicRateLimit.getTokenConsumedPerAcquire())
)
);
} else {
enableRateLimiter = false;
}
this.shareStrategy = shareTopic.getShareSubStrategy();
if (round == shareStrategy) {
roundMap = new ConcurrentHashMap<>();
}
this.enableMessageBridge = messageBridge.getEnable();
if (enableMessageBridge) {
this.bridgeTopics = messageBridge.getTopics();
this.kafkaTemplate = kafkaTemplate;
Assert.notEmpty(bridgeTopics, "消息桥接主题列表不能为空!!!");
}
if (isClusterMode()) {
this.internalMessagePublishService = internalMessagePublishService;
Assert.notNull(internalMessagePublishService, "internalMessagePublishService can't be null");
}
}
/**
* 根据 MQTT v3.1.1 Qos2 实现有 Method A 与 Method B,这里采用 B 方案,
* 具体参见 <b>Figure 4.3-Qos protocol flow diagram,non normative example</b>
*
* @param ctx 见 {@link ChannelHandlerContext}
* @param msg 解包后的数据
*/
@Override
public void process(ChannelHandlerContext ctx, MqttMessage msg) {
final var mpm = (MqttPublishMessage) msg;
final var mqttFixedHeader = mpm.fixedHeader();
final var mqttPublishVariableHeader = mpm.variableHeader();
final var payload = mpm.payload();
// 获取qos、topic、packetId、retain、payload
final var qos = mqttFixedHeader.qosLevel();
final var topic = mqttPublishVariableHeader.topicName();
final var packetId = mqttPublishVariableHeader.packetId();
final var retain = mqttFixedHeader.isRetain();
final var data = new byte[payload.readableBytes()];
payload.readBytes(data);
// 发布权限判定
if (enableTopicSubPubSecure && !hasAuthToPubTopic(ctx, topic)) {
throw new AuthorizationException("无对应 topic 发布权限");
}
// 消息桥接功能,便于对接各类 MQ(kafka, RocketMQ).
// 这里提供 kafka 的实现,需要对接其它 MQ 的同学可自行修改.
if (enableMessageBridge && bridgeTopics.contains(topic)) {
kafkaTemplate.send(topic, data);
}
// 限流判定, 满足如下四个条件即被限流:
// 1 限流器开启
// 2 qos = 0
// 3 该主题配置了限流器
// 4 令牌获取失败
// 被限流的消息就会被直接丢弃
if (enableRateLimiter &&
qos == MqttQoS.AT_MOST_ONCE &&
rateLimiterMap.containsKey(topic) &&
!rateLimiterMap.get(topic).acquire(Instant.now().getEpochSecond())) {
return;
}
// 组装消息
// When sending a PUBLISH Packet to a Client the Server MUST set the RETAIN flag to 1 if a message is sent as a
// result of a new subscription being made by a Client [MQTT-3.3.1-8]. It MUST set the RETAIN flag to 0 when a
// PUBLISH Packet is sent to a Client because it matches an established subscription regardless of how the flag
// was set in the message it received [MQTT-3.3.1-9].
// 当新 topic 订阅触发 retain 消息时,retain flag 才应该置 1,其它状况都是 0.
final var pubMsg = PubMsg.of(qos.value(), topic, false, data);
// 响应
switch (qos) {
case AT_MOST_ONCE -> publish(pubMsg, ctx, false)
.publishOn(Schedulers.boundedElastic())
.doOnSuccess(unused -> {
if (retain) {
handleRetainMsg(pubMsg).subscribe();
}
}).subscribe();
case AT_LEAST_ONCE -> {
publish(pubMsg, ctx, false)
.publishOn(Schedulers.boundedElastic())
.doOnSuccess(unused -> {
MqttMessage pubAck = MqttMessageFactory.newMessage(
new MqttFixedHeader(MqttMessageType.PUBACK, false, MqttQoS.AT_MOST_ONCE, false, 0),
MqttMessageIdVariableHeader.from(packetId),
null
);
ctx.writeAndFlush(pubAck);
// retain 消息处理
if (retain) {
handleRetainMsg(pubMsg).subscribe();
}
}).subscribe();
}
case EXACTLY_ONCE -> {
// 判断消息是否重复, 未重复的消息需要保存 messageId
if (isCleanSession(ctx)) {
Session session = getSession(ctx);
if (!session.isDupMsg(packetId)) {
publish(pubMsg, ctx, false)
.publishOn(Schedulers.boundedElastic())
.doOnSuccess(unused -> {
// 保存 pub
session.savePubRelInMsg(packetId);
//
var pubRec = MqttMessageFactory.newMessage(
new MqttFixedHeader(MqttMessageType.PUBREC, false, MqttQoS.AT_MOST_ONCE, false, 0),
MqttMessageIdVariableHeader.from(packetId),
null
);
ctx.writeAndFlush(pubRec);
// retain 消息处理
if (retain) {
handleRetainMsg(pubMsg).subscribe();
}
})
.subscribe();
} else {
var pubRec = MqttMessageFactory.newMessage(
new MqttFixedHeader(MqttMessageType.PUBREC, false, MqttQoS.AT_MOST_ONCE, false, 0),
MqttMessageIdVariableHeader.from(packetId),
null
);
ctx.writeAndFlush(pubRec);
// retain 消息处理
if (retain) {
handleRetainMsg(pubMsg).subscribe();
}
}
} else {
pubRelMessageService.isInMsgDup(clientId(ctx), packetId)
.flatMap(b -> {
if (b) {
return Mono.empty();
} else {
return publish(pubMsg, ctx, false)
.publishOn(Schedulers.boundedElastic())
.doOnSuccess(unused -> pubRelMessageService.saveIn(clientId(ctx), packetId).subscribe());
}
})
.publishOn(Schedulers.boundedElastic())
.doOnSuccess(unused -> {
var pubRec = MqttMessageFactory.newMessage(
new MqttFixedHeader(MqttMessageType.PUBREC, false, MqttQoS.AT_MOST_ONCE, false, 0),
MqttMessageIdVariableHeader.from(packetId),
null
);
ctx.writeAndFlush(pubRec);
// retain 消息处理
if (retain) {
handleRetainMsg(pubMsg).subscribe();
}
})
.subscribe();
}
}
}
}
/**
* 消息发布,目前看来 {@link PubMsg} 的来源有如下几种:
* <ol>
* <li>{@link MqttMessageType#PUBLISH} 消息</li>
* <li>遗嘱消息</li>
* <li>retain 消息被新订阅触发 </li>
* <li>集群消息 {@link #action(byte[])}</li>
* </ol>
*
* @param pubMsg publish message
* @param ctx {@link ChannelHandlerContext}, 该上下文应该是发送消息 client 的上下文
* @param isClusterMessage 标志消息源是集群还是客户端
*/
public Mono<Void> publish(final PubMsg pubMsg, ChannelHandlerContext ctx, boolean isClusterMessage) {
// 指定了客户端的消息
if (StringUtils.hasText(pubMsg.getAppointedClientId())) {
final String clientId = pubMsg.getAppointedClientId();
if (isClusterMessage) {
// 消息自集群而来,ctx 不能用,会 NPE
return isCleanSession(clientId)
.flatMap(cs -> publish0(ClientSub.of(clientId, pubMsg.getQoS(), pubMsg.getTopic(), cs), pubMsg,
true))
.then();
} else {
boolean cleanSession = isCleanSession(ctx);
return publish0(ClientSub.of(clientId, pubMsg.getQoS(), pubMsg.getTopic(), cleanSession), pubMsg, false)
.then();
}
}
// 获取 topic 订阅者 id 列表
final var topic = pubMsg.getTopic();
Flux<ClientSub> clientSubFlux = subscriptionService.searchSubscribeClientList(topic)
.filter(clientSub -> {
if (ignoreClientSelfPub) {
// 忽略 client 自身的订阅
return !Objects.equals(clientSub.getClientId(), clientId(ctx));
} else {
return true;
}
});
// 共享订阅
var f1 = clientSubFlux
.filter(ClientSub::isShareSub)
.groupBy(ClientSub::getShareName)
.flatMap(GroupedFlux::collectList)
.map(t -> chooseClient(t, topic))
.flatMap(clientSub -> {
var copied = pubMsg.copied();
copied.setAppointedClientId(clientSub.getClientId());
return publish0(clientSub, copied, isClusterMessage).doOnSuccess(unused -> {
// 满足如下条件,则发送消息给集群
// 1 集群模式开启
// 2 订阅的客户端连接在其它实例上
if (isClusterMode() && !ConnectHandler.CLIENT_MAP.containsKey(clientSub.getClientId())) {
internalMessagePublish(copied);
}
});
});
// 普通订阅
var f2 = clientSubFlux
.filter(ClientSub::notShareSub)
.collectList()
.flatMap(lst -> {
// 如果只有一个客户端订阅,那么消息可以指定客户端
var copied = pubMsg.copied();
if (lst.size() == 1) {
var clientSub = lst.get(0);
copied.setAppointedClientId(clientSub.getClientId());
}
// 将消息推送给集群中的 broker
if (isClusterMode() && !isClusterMessage) {
// 判断是否需要进行集群消息分发
var flag = false;
for (var clientSub : lst) {
if (!ConnectHandler.CLIENT_MAP.containsKey(clientSub.getClientId())) {
flag = true;
break;
}
}
if (flag) {
internalMessagePublish(copied);
}
}
return Flux.fromIterable(lst).flatMap(clientSub -> publish0(clientSub, copied.copied(), isClusterMessage)).then();
});
return Mono.when(f1, f2);
}
/**
* 发布消息给 clientSub
*
* @param clientSub {@link ClientSub}
* @param pubMsg 待发布消息
* @param isClusterMessage 内部消息flag,设计上由其它集群分发过来的消息
*/
private Mono<Void> publish0(ClientSub clientSub, PubMsg pubMsg, boolean isClusterMessage) {
// clientId, channel, topic
final var clientId = clientSub.getClientId();
final var isCleanSession = clientSub.isCleanSession();
final var channel = Optional.of(clientId)
.map(ConnectHandler.CLIENT_MAP::get)
.map(BrokerHandler.CHANNELS::find)
.orElse(null);
final var topic = pubMsg.getTopic();
// 计算Qos
final var pubQos = pubMsg.getQoS();
final var subQos = clientSub.getQos();
final var qos = subQos >= pubQos ? MqttQoS.valueOf(pubQos) : MqttQoS.valueOf(subQos);
// payload, retained flag
final var payload = pubMsg.getPayload();
final var retained = pubMsg.isRetain();
// 接下来的处理分四种情况
// 1. channel == null && cleanSession => 直接返回,由集群中其它的 broker 处理(pubMsg 无 messageId)
// 2. channel == null && !cleanSession => 保存 pubMsg (pubMsg 有 messageId)
// 3. channel != null && cleanSession => 将消息关联到会话,并发送 publish message 给 client(messageId 取自 session)
// 4. channel != null && !cleanSession => 将消息持久化到 redis, 并发送 publish message 给 client(messageId redis increment 指令)
// 1. channel == null && cleanSession
if (channel == null && isCleanSession) {
return Mono.empty();
}
// 2. channel == null && !cleanSession
if (channel == null) {
if ((qos == MqttQoS.EXACTLY_ONCE || qos == MqttQoS.AT_LEAST_ONCE) && !isClusterMessage) {
return sessionService.nextMessageId(clientId)
.flatMap(messageId -> {
pubMsg.setQoS(qos.value());
pubMsg.setMessageId(messageId);
return publishMessageService.save(clientId, pubMsg);
});
}
return Mono.empty();
}
// 处理 channel != null 的情况
// 计算 messageId
int messageId;
// 3. channel != null && cleanSession
if (isCleanSession) {
// cleanSession 状态下不判断消息是否为集群
// 假设消息由集群内其它 broker 分发,而 cleanSession 状态下 broker 消息走的内存,为了实现 qos1,2 我们必须将消息保存到内存
if ((qos == MqttQoS.EXACTLY_ONCE || qos == MqttQoS.AT_LEAST_ONCE)) {
messageId = nextMessageId(channel);
getSession(channel).savePubMsg(messageId, pubMsg);
} else {
// qos0
messageId = 0;
}
} else {
// 4. channel != null && !cleanSession
if (qos == MqttQoS.EXACTLY_ONCE || qos == MqttQoS.AT_LEAST_ONCE) {
return sessionService.nextMessageId(clientId)
.flatMap(e -> {
if (isClusterMessage) {
var mpm = new MqttPublishMessage(
new MqttFixedHeader(MqttMessageType.PUBLISH, false, qos, retained, 0),
new MqttPublishVariableHeader(topic, e),
Unpooled.wrappedBuffer(payload)
);
channel.writeAndFlush(mpm);
return Mono.empty();
} else {
pubMsg.setQoS(qos.value());
pubMsg.setMessageId(e);
return publishMessageService.save(clientId, pubMsg).doOnSuccess(unused -> {
var mpm = new MqttPublishMessage(
new MqttFixedHeader(MqttMessageType.PUBLISH, false, qos, retained, 0),
new MqttPublishVariableHeader(topic, e),
Unpooled.wrappedBuffer(payload)
);
channel.writeAndFlush(mpm);
});
}
})
.then();
} else {
// qos0
messageId = 0;
}
}
// 发送报文给 client
// mqttx 只有 ConnectHandler#republish(ChannelHandlerContext) 方法有必要将 dup flag 设置为 true(qos > 0), 其它应该为 false.
var mpm = new MqttPublishMessage(
new MqttFixedHeader(MqttMessageType.PUBLISH, false, qos, retained, 0),
new MqttPublishVariableHeader(topic, messageId),
Unpooled.wrappedBuffer(payload)
);
channel.writeAndFlush(mpm);
return Mono.empty();
}
/**
* 处理 retain 消息
*
* @param pubMsg retain message
*/
public Mono<Void> handleRetainMsg(PubMsg pubMsg) {
byte[] payload = pubMsg.getPayload();
String topic = pubMsg.getTopic();
// with issue https://github.com/Amazingwujun/mqttx/issues/14 And PR
// https://github.com/Amazingwujun/mqttx/pull/15
// If the Server receives a QoS 0 message with the RETAIN flag set to 1 it
// MUST discard any message previously retained for that topic. It SHOULD
// store the new QoS 0 message as the new retained message for that topic,
// but MAY choose to discard it at any time - if this happens there will be
// no retained message for that topic [MQTT-3.3.1-7].
// [MQTT-3.3.1-7] 当 broker 收到 qos 为 0 并且 RETAIN = 1 的消息 必须抛弃该主题保留
// 之前的消息(注意:是 retained 消息), 同时 broker 可以选择保留或抛弃当前的消息,MQTTX
// 的选择是保留.
// A PUBLISH Packet with a RETAIN flag set to 1 and a payload containing zero
// bytes will be processed as normal by the Server and sent to Clients with a
// subscription matching the topic name. Additionally any existing retained
// message with the same topic name MUST be removed and any future subscribers
// for the topic will not receive a retained message [MQTT-3.3.1-10].
// [MQTT-3.3.1-10] 注意 [Additionally] 内容, broker 收到 retain 消息载荷(payload)
// 为空时,broker 必须移除 topic 关联的 retained 消息.
if (ObjectUtils.isEmpty(payload)) {
return retainMessageService.remove(topic);
}
return retainMessageService.save(topic, pubMsg);
}
/**
* 集群内部消息发布
*
* @param pubMsg {@link PubMsg}
*/
private void internalMessagePublish(PubMsg pubMsg) {
var im = new InternalMessage<>(pubMsg, System.currentTimeMillis(), brokerId);
internalMessagePublishService.publish(im, InternalMessageEnum.PUB.getChannel());
}
@Override
public void action(byte[] msg) {
InternalMessage<PubMsg> im;
if (serializer instanceof JsonSerializer s) {
im = s.deserialize(msg, new TypeReference<>() {
});
} else {
//noinspection unchecked
im = serializer.deserialize(msg, InternalMessage.class);
}
PubMsg data = im.getData();
publish(data, null, true).subscribe();
}
@Override
public boolean support(String channel) {
return InternalMessageEnum.PUB.getChannel().equals(channel);
}
/**
* 共享订阅选择客户端, 支持的策略如下:
* <ol>
* <li>随机: {@link ShareStrategy#random}</li>
* <li>轮询: {@link ShareStrategy#round}</li>
* </ol>
*
* @param clientSubList 接收客户端列表
* @return 按规则选择的客户端
*/
private ClientSub chooseClient(List<ClientSub> clientSubList, String topic) {
// 集合排序
clientSubList.sort(ClientSub::compareTo);
final var size = clientSubList.size();
if (random == shareStrategy) {
int key = ThreadLocalRandom.current().nextInt(0, size);
return clientSubList.get(key % size);
} else if (round == shareStrategy) {
int i = roundMap.computeIfAbsent(topic, s -> new AtomicInteger(0)).getAndIncrement();
return clientSubList.get(i % size);
}
throw new IllegalArgumentException("不可能到达的代码, strategy:" + shareStrategy);
}
/**
* 判断 clientId 关联的会话是否是 cleanSession 会话
*
* @param clientId 客户端id
* @return true if session is cleanSession
*/
private Mono<Boolean> isCleanSession(String clientId) {
return sessionService.hasKey(clientId).map(e -> !e);
}
}
| Amazingwujun/mqttx | src/main/java/com/jun/mqttx/broker/handler/PublishHandler.java | 5,817 | // 集合排序 | line_comment | zh-cn | /*
* Copyright 2020-2023 the original author or authors.
*
* 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
*
* https://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.jun.mqttx.broker.handler;
import com.fasterxml.jackson.core.type.TypeReference;
import com.jun.mqttx.broker.BrokerHandler;
import com.jun.mqttx.config.MqttxConfig;
import com.jun.mqttx.constants.InternalMessageEnum;
import com.jun.mqttx.constants.ShareStrategy;
import com.jun.mqttx.consumer.Watcher;
import com.jun.mqttx.entity.ClientSub;
import com.jun.mqttx.entity.InternalMessage;
import com.jun.mqttx.entity.PubMsg;
import com.jun.mqttx.entity.Session;
import com.jun.mqttx.exception.AuthorizationException;
import com.jun.mqttx.service.*;
import com.jun.mqttx.utils.JsonSerializer;
import com.jun.mqttx.utils.RateLimiter;
import com.jun.mqttx.utils.Serializer;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.mqtt.*;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import reactor.core.publisher.Flux;
import reactor.core.publisher.GroupedFlux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
import java.time.Instant;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;
import static com.jun.mqttx.constants.ShareStrategy.random;
import static com.jun.mqttx.constants.ShareStrategy.round;
/**
* {@link MqttMessageType#PUBLISH} 处理器
*
* @author Jun
* @since 1.0.4
*/
@Handler(type = MqttMessageType.PUBLISH)
public class PublishHandler extends AbstractMqttTopicSecureHandler implements Watcher {
//@formatter:off
private final ISessionService sessionService;
private final IRetainMessageService retainMessageService;
private final ISubscriptionService subscriptionService;
private final IPublishMessageService publishMessageService;
private final IPubRelMessageService pubRelMessageService;
private final String brokerId;
private final boolean enableTopicSubPubSecure, enableRateLimiter, ignoreClientSelfPub;
/** 共享主题轮询策略 */
private final ShareStrategy shareStrategy;
/** 消息桥接开关 */
private final Boolean enableMessageBridge;
/** 主题限流器 */
private final Map<String, RateLimiter> rateLimiterMap = new HashMap<>();
private final Serializer serializer;
private IInternalMessagePublishService internalMessagePublishService;
/** 需要桥接消息的主题 */
private Set<String> bridgeTopics;
private KafkaTemplate<String, byte[]> kafkaTemplate;
/** 共享订阅轮询,存储轮询参数 */
private Map<String, AtomicInteger> roundMap;
//@formatter:on
public PublishHandler(IPublishMessageService publishMessageService,
IRetainMessageService retainMessageService,
ISubscriptionService subscriptionService,
IPubRelMessageService pubRelMessageService,
ISessionService sessionService,
@Nullable IInternalMessagePublishService internalMessagePublishService,
MqttxConfig config,
@Nullable KafkaTemplate<String, byte[]> kafkaTemplate,
Serializer serializer) {
super(config.getCluster().getEnable());
var shareTopic = config.getShareTopic();
var messageBridge = config.getMessageBridge();
var rateLimiter = config.getRateLimiter();
this.sessionService = sessionService;
this.serializer = serializer;
this.publishMessageService = publishMessageService;
this.retainMessageService = retainMessageService;
this.subscriptionService = subscriptionService;
this.pubRelMessageService = pubRelMessageService;
this.brokerId = config.getBrokerId();
this.enableTopicSubPubSecure = config.getEnableTopicSubPubSecure();
this.ignoreClientSelfPub = config.getIgnoreClientSelfPub();
if (!CollectionUtils.isEmpty(rateLimiter.getTopicRateLimits()) && rateLimiter.getEnable()) {
enableRateLimiter = true;
rateLimiter.getTopicRateLimits()
.forEach(
topicRateLimit -> rateLimiterMap.put(
topicRateLimit.getTopic(),
new RateLimiter(topicRateLimit.getCapacity(), topicRateLimit.getReplenishRate(), topicRateLimit.getTokenConsumedPerAcquire())
)
);
} else {
enableRateLimiter = false;
}
this.shareStrategy = shareTopic.getShareSubStrategy();
if (round == shareStrategy) {
roundMap = new ConcurrentHashMap<>();
}
this.enableMessageBridge = messageBridge.getEnable();
if (enableMessageBridge) {
this.bridgeTopics = messageBridge.getTopics();
this.kafkaTemplate = kafkaTemplate;
Assert.notEmpty(bridgeTopics, "消息桥接主题列表不能为空!!!");
}
if (isClusterMode()) {
this.internalMessagePublishService = internalMessagePublishService;
Assert.notNull(internalMessagePublishService, "internalMessagePublishService can't be null");
}
}
/**
* 根据 MQTT v3.1.1 Qos2 实现有 Method A 与 Method B,这里采用 B 方案,
* 具体参见 <b>Figure 4.3-Qos protocol flow diagram,non normative example</b>
*
* @param ctx 见 {@link ChannelHandlerContext}
* @param msg 解包后的数据
*/
@Override
public void process(ChannelHandlerContext ctx, MqttMessage msg) {
final var mpm = (MqttPublishMessage) msg;
final var mqttFixedHeader = mpm.fixedHeader();
final var mqttPublishVariableHeader = mpm.variableHeader();
final var payload = mpm.payload();
// 获取qos、topic、packetId、retain、payload
final var qos = mqttFixedHeader.qosLevel();
final var topic = mqttPublishVariableHeader.topicName();
final var packetId = mqttPublishVariableHeader.packetId();
final var retain = mqttFixedHeader.isRetain();
final var data = new byte[payload.readableBytes()];
payload.readBytes(data);
// 发布权限判定
if (enableTopicSubPubSecure && !hasAuthToPubTopic(ctx, topic)) {
throw new AuthorizationException("无对应 topic 发布权限");
}
// 消息桥接功能,便于对接各类 MQ(kafka, RocketMQ).
// 这里提供 kafka 的实现,需要对接其它 MQ 的同学可自行修改.
if (enableMessageBridge && bridgeTopics.contains(topic)) {
kafkaTemplate.send(topic, data);
}
// 限流判定, 满足如下四个条件即被限流:
// 1 限流器开启
// 2 qos = 0
// 3 该主题配置了限流器
// 4 令牌获取失败
// 被限流的消息就会被直接丢弃
if (enableRateLimiter &&
qos == MqttQoS.AT_MOST_ONCE &&
rateLimiterMap.containsKey(topic) &&
!rateLimiterMap.get(topic).acquire(Instant.now().getEpochSecond())) {
return;
}
// 组装消息
// When sending a PUBLISH Packet to a Client the Server MUST set the RETAIN flag to 1 if a message is sent as a
// result of a new subscription being made by a Client [MQTT-3.3.1-8]. It MUST set the RETAIN flag to 0 when a
// PUBLISH Packet is sent to a Client because it matches an established subscription regardless of how the flag
// was set in the message it received [MQTT-3.3.1-9].
// 当新 topic 订阅触发 retain 消息时,retain flag 才应该置 1,其它状况都是 0.
final var pubMsg = PubMsg.of(qos.value(), topic, false, data);
// 响应
switch (qos) {
case AT_MOST_ONCE -> publish(pubMsg, ctx, false)
.publishOn(Schedulers.boundedElastic())
.doOnSuccess(unused -> {
if (retain) {
handleRetainMsg(pubMsg).subscribe();
}
}).subscribe();
case AT_LEAST_ONCE -> {
publish(pubMsg, ctx, false)
.publishOn(Schedulers.boundedElastic())
.doOnSuccess(unused -> {
MqttMessage pubAck = MqttMessageFactory.newMessage(
new MqttFixedHeader(MqttMessageType.PUBACK, false, MqttQoS.AT_MOST_ONCE, false, 0),
MqttMessageIdVariableHeader.from(packetId),
null
);
ctx.writeAndFlush(pubAck);
// retain 消息处理
if (retain) {
handleRetainMsg(pubMsg).subscribe();
}
}).subscribe();
}
case EXACTLY_ONCE -> {
// 判断消息是否重复, 未重复的消息需要保存 messageId
if (isCleanSession(ctx)) {
Session session = getSession(ctx);
if (!session.isDupMsg(packetId)) {
publish(pubMsg, ctx, false)
.publishOn(Schedulers.boundedElastic())
.doOnSuccess(unused -> {
// 保存 pub
session.savePubRelInMsg(packetId);
//
var pubRec = MqttMessageFactory.newMessage(
new MqttFixedHeader(MqttMessageType.PUBREC, false, MqttQoS.AT_MOST_ONCE, false, 0),
MqttMessageIdVariableHeader.from(packetId),
null
);
ctx.writeAndFlush(pubRec);
// retain 消息处理
if (retain) {
handleRetainMsg(pubMsg).subscribe();
}
})
.subscribe();
} else {
var pubRec = MqttMessageFactory.newMessage(
new MqttFixedHeader(MqttMessageType.PUBREC, false, MqttQoS.AT_MOST_ONCE, false, 0),
MqttMessageIdVariableHeader.from(packetId),
null
);
ctx.writeAndFlush(pubRec);
// retain 消息处理
if (retain) {
handleRetainMsg(pubMsg).subscribe();
}
}
} else {
pubRelMessageService.isInMsgDup(clientId(ctx), packetId)
.flatMap(b -> {
if (b) {
return Mono.empty();
} else {
return publish(pubMsg, ctx, false)
.publishOn(Schedulers.boundedElastic())
.doOnSuccess(unused -> pubRelMessageService.saveIn(clientId(ctx), packetId).subscribe());
}
})
.publishOn(Schedulers.boundedElastic())
.doOnSuccess(unused -> {
var pubRec = MqttMessageFactory.newMessage(
new MqttFixedHeader(MqttMessageType.PUBREC, false, MqttQoS.AT_MOST_ONCE, false, 0),
MqttMessageIdVariableHeader.from(packetId),
null
);
ctx.writeAndFlush(pubRec);
// retain 消息处理
if (retain) {
handleRetainMsg(pubMsg).subscribe();
}
})
.subscribe();
}
}
}
}
/**
* 消息发布,目前看来 {@link PubMsg} 的来源有如下几种:
* <ol>
* <li>{@link MqttMessageType#PUBLISH} 消息</li>
* <li>遗嘱消息</li>
* <li>retain 消息被新订阅触发 </li>
* <li>集群消息 {@link #action(byte[])}</li>
* </ol>
*
* @param pubMsg publish message
* @param ctx {@link ChannelHandlerContext}, 该上下文应该是发送消息 client 的上下文
* @param isClusterMessage 标志消息源是集群还是客户端
*/
public Mono<Void> publish(final PubMsg pubMsg, ChannelHandlerContext ctx, boolean isClusterMessage) {
// 指定了客户端的消息
if (StringUtils.hasText(pubMsg.getAppointedClientId())) {
final String clientId = pubMsg.getAppointedClientId();
if (isClusterMessage) {
// 消息自集群而来,ctx 不能用,会 NPE
return isCleanSession(clientId)
.flatMap(cs -> publish0(ClientSub.of(clientId, pubMsg.getQoS(), pubMsg.getTopic(), cs), pubMsg,
true))
.then();
} else {
boolean cleanSession = isCleanSession(ctx);
return publish0(ClientSub.of(clientId, pubMsg.getQoS(), pubMsg.getTopic(), cleanSession), pubMsg, false)
.then();
}
}
// 获取 topic 订阅者 id 列表
final var topic = pubMsg.getTopic();
Flux<ClientSub> clientSubFlux = subscriptionService.searchSubscribeClientList(topic)
.filter(clientSub -> {
if (ignoreClientSelfPub) {
// 忽略 client 自身的订阅
return !Objects.equals(clientSub.getClientId(), clientId(ctx));
} else {
return true;
}
});
// 共享订阅
var f1 = clientSubFlux
.filter(ClientSub::isShareSub)
.groupBy(ClientSub::getShareName)
.flatMap(GroupedFlux::collectList)
.map(t -> chooseClient(t, topic))
.flatMap(clientSub -> {
var copied = pubMsg.copied();
copied.setAppointedClientId(clientSub.getClientId());
return publish0(clientSub, copied, isClusterMessage).doOnSuccess(unused -> {
// 满足如下条件,则发送消息给集群
// 1 集群模式开启
// 2 订阅的客户端连接在其它实例上
if (isClusterMode() && !ConnectHandler.CLIENT_MAP.containsKey(clientSub.getClientId())) {
internalMessagePublish(copied);
}
});
});
// 普通订阅
var f2 = clientSubFlux
.filter(ClientSub::notShareSub)
.collectList()
.flatMap(lst -> {
// 如果只有一个客户端订阅,那么消息可以指定客户端
var copied = pubMsg.copied();
if (lst.size() == 1) {
var clientSub = lst.get(0);
copied.setAppointedClientId(clientSub.getClientId());
}
// 将消息推送给集群中的 broker
if (isClusterMode() && !isClusterMessage) {
// 判断是否需要进行集群消息分发
var flag = false;
for (var clientSub : lst) {
if (!ConnectHandler.CLIENT_MAP.containsKey(clientSub.getClientId())) {
flag = true;
break;
}
}
if (flag) {
internalMessagePublish(copied);
}
}
return Flux.fromIterable(lst).flatMap(clientSub -> publish0(clientSub, copied.copied(), isClusterMessage)).then();
});
return Mono.when(f1, f2);
}
/**
* 发布消息给 clientSub
*
* @param clientSub {@link ClientSub}
* @param pubMsg 待发布消息
* @param isClusterMessage 内部消息flag,设计上由其它集群分发过来的消息
*/
private Mono<Void> publish0(ClientSub clientSub, PubMsg pubMsg, boolean isClusterMessage) {
// clientId, channel, topic
final var clientId = clientSub.getClientId();
final var isCleanSession = clientSub.isCleanSession();
final var channel = Optional.of(clientId)
.map(ConnectHandler.CLIENT_MAP::get)
.map(BrokerHandler.CHANNELS::find)
.orElse(null);
final var topic = pubMsg.getTopic();
// 计算Qos
final var pubQos = pubMsg.getQoS();
final var subQos = clientSub.getQos();
final var qos = subQos >= pubQos ? MqttQoS.valueOf(pubQos) : MqttQoS.valueOf(subQos);
// payload, retained flag
final var payload = pubMsg.getPayload();
final var retained = pubMsg.isRetain();
// 接下来的处理分四种情况
// 1. channel == null && cleanSession => 直接返回,由集群中其它的 broker 处理(pubMsg 无 messageId)
// 2. channel == null && !cleanSession => 保存 pubMsg (pubMsg 有 messageId)
// 3. channel != null && cleanSession => 将消息关联到会话,并发送 publish message 给 client(messageId 取自 session)
// 4. channel != null && !cleanSession => 将消息持久化到 redis, 并发送 publish message 给 client(messageId redis increment 指令)
// 1. channel == null && cleanSession
if (channel == null && isCleanSession) {
return Mono.empty();
}
// 2. channel == null && !cleanSession
if (channel == null) {
if ((qos == MqttQoS.EXACTLY_ONCE || qos == MqttQoS.AT_LEAST_ONCE) && !isClusterMessage) {
return sessionService.nextMessageId(clientId)
.flatMap(messageId -> {
pubMsg.setQoS(qos.value());
pubMsg.setMessageId(messageId);
return publishMessageService.save(clientId, pubMsg);
});
}
return Mono.empty();
}
// 处理 channel != null 的情况
// 计算 messageId
int messageId;
// 3. channel != null && cleanSession
if (isCleanSession) {
// cleanSession 状态下不判断消息是否为集群
// 假设消息由集群内其它 broker 分发,而 cleanSession 状态下 broker 消息走的内存,为了实现 qos1,2 我们必须将消息保存到内存
if ((qos == MqttQoS.EXACTLY_ONCE || qos == MqttQoS.AT_LEAST_ONCE)) {
messageId = nextMessageId(channel);
getSession(channel).savePubMsg(messageId, pubMsg);
} else {
// qos0
messageId = 0;
}
} else {
// 4. channel != null && !cleanSession
if (qos == MqttQoS.EXACTLY_ONCE || qos == MqttQoS.AT_LEAST_ONCE) {
return sessionService.nextMessageId(clientId)
.flatMap(e -> {
if (isClusterMessage) {
var mpm = new MqttPublishMessage(
new MqttFixedHeader(MqttMessageType.PUBLISH, false, qos, retained, 0),
new MqttPublishVariableHeader(topic, e),
Unpooled.wrappedBuffer(payload)
);
channel.writeAndFlush(mpm);
return Mono.empty();
} else {
pubMsg.setQoS(qos.value());
pubMsg.setMessageId(e);
return publishMessageService.save(clientId, pubMsg).doOnSuccess(unused -> {
var mpm = new MqttPublishMessage(
new MqttFixedHeader(MqttMessageType.PUBLISH, false, qos, retained, 0),
new MqttPublishVariableHeader(topic, e),
Unpooled.wrappedBuffer(payload)
);
channel.writeAndFlush(mpm);
});
}
})
.then();
} else {
// qos0
messageId = 0;
}
}
// 发送报文给 client
// mqttx 只有 ConnectHandler#republish(ChannelHandlerContext) 方法有必要将 dup flag 设置为 true(qos > 0), 其它应该为 false.
var mpm = new MqttPublishMessage(
new MqttFixedHeader(MqttMessageType.PUBLISH, false, qos, retained, 0),
new MqttPublishVariableHeader(topic, messageId),
Unpooled.wrappedBuffer(payload)
);
channel.writeAndFlush(mpm);
return Mono.empty();
}
/**
* 处理 retain 消息
*
* @param pubMsg retain message
*/
public Mono<Void> handleRetainMsg(PubMsg pubMsg) {
byte[] payload = pubMsg.getPayload();
String topic = pubMsg.getTopic();
// with issue https://github.com/Amazingwujun/mqttx/issues/14 And PR
// https://github.com/Amazingwujun/mqttx/pull/15
// If the Server receives a QoS 0 message with the RETAIN flag set to 1 it
// MUST discard any message previously retained for that topic. It SHOULD
// store the new QoS 0 message as the new retained message for that topic,
// but MAY choose to discard it at any time - if this happens there will be
// no retained message for that topic [MQTT-3.3.1-7].
// [MQTT-3.3.1-7] 当 broker 收到 qos 为 0 并且 RETAIN = 1 的消息 必须抛弃该主题保留
// 之前的消息(注意:是 retained 消息), 同时 broker 可以选择保留或抛弃当前的消息,MQTTX
// 的选择是保留.
// A PUBLISH Packet with a RETAIN flag set to 1 and a payload containing zero
// bytes will be processed as normal by the Server and sent to Clients with a
// subscription matching the topic name. Additionally any existing retained
// message with the same topic name MUST be removed and any future subscribers
// for the topic will not receive a retained message [MQTT-3.3.1-10].
// [MQTT-3.3.1-10] 注意 [Additionally] 内容, broker 收到 retain 消息载荷(payload)
// 为空时,broker 必须移除 topic 关联的 retained 消息.
if (ObjectUtils.isEmpty(payload)) {
return retainMessageService.remove(topic);
}
return retainMessageService.save(topic, pubMsg);
}
/**
* 集群内部消息发布
*
* @param pubMsg {@link PubMsg}
*/
private void internalMessagePublish(PubMsg pubMsg) {
var im = new InternalMessage<>(pubMsg, System.currentTimeMillis(), brokerId);
internalMessagePublishService.publish(im, InternalMessageEnum.PUB.getChannel());
}
@Override
public void action(byte[] msg) {
InternalMessage<PubMsg> im;
if (serializer instanceof JsonSerializer s) {
im = s.deserialize(msg, new TypeReference<>() {
});
} else {
//noinspection unchecked
im = serializer.deserialize(msg, InternalMessage.class);
}
PubMsg data = im.getData();
publish(data, null, true).subscribe();
}
@Override
public boolean support(String channel) {
return InternalMessageEnum.PUB.getChannel().equals(channel);
}
/**
* 共享订阅选择客户端, 支持的策略如下:
* <ol>
* <li>随机: {@link ShareStrategy#random}</li>
* <li>轮询: {@link ShareStrategy#round}</li>
* </ol>
*
* @param clientSubList 接收客户端列表
* @return 按规则选择的客户端
*/
private ClientSub chooseClient(List<ClientSub> clientSubList, String topic) {
// 集合 <SUF>
clientSubList.sort(ClientSub::compareTo);
final var size = clientSubList.size();
if (random == shareStrategy) {
int key = ThreadLocalRandom.current().nextInt(0, size);
return clientSubList.get(key % size);
} else if (round == shareStrategy) {
int i = roundMap.computeIfAbsent(topic, s -> new AtomicInteger(0)).getAndIncrement();
return clientSubList.get(i % size);
}
throw new IllegalArgumentException("不可能到达的代码, strategy:" + shareStrategy);
}
/**
* 判断 clientId 关联的会话是否是 cleanSession 会话
*
* @param clientId 客户端id
* @return true if session is cleanSession
*/
private Mono<Boolean> isCleanSession(String clientId) {
return sessionService.hasKey(clientId).map(e -> !e);
}
}
| false |
41951_21 |
//数组的引出
//
public class Array01 {
//编写一个main方法
public static void main(String[] args) {
/*
它们的体重分别是3kg,5kg,1kg,3.4kg,2kg,50kg 。
请问这六只鸡的总体重是多少?平均体重是多少?
思路分析
1. 定义六个变量 double , 求和 得到总体重
2. 平均体重 = 总体重 / 6
3. 分析传统实现的方式问题. 6->600->566
4. 引出新的技术 -> 使用数组来解决.
*/
// double hen1 = 3;
// double hen2 = 5;
// double hen3 = 1;
// double hen4 = 3.4;
// double hen5 = 2;
// double hen6 = 50;
// double totalWeight = hen1 + hen2 + hen3 + hen4 + hen5 + hen6;
// double avgWeight = totalWeight / 6;
// System.out.println("总体重=" + totalWeight
// + "平均体重=" + avgWeight);
//比如,我们可以用数组来解决上一个问题 => 体验
//
//定义一个数组
//老韩解读
//1. double[] 表示 是double类型的数组, 数组名 hens
//2. {3, 5, 1, 3.4, 2, 50} 表示数组的值/元素,依次表示数组的
// 第几个元素
//
double[] hens = {3, 5, 1, 3.4, 2, 50, 7.8, 88.8,1.1,5.6,100};
//遍历数组得到数组的所有元素的和, 使用for
//老韩解读
//1. 我们可以通过 hens[下标] 来访问数组的元素
// 下标是从 0 开始编号的比如第一个元素就是 hens[0]
// 第2个元素就是 hens[1] , 依次类推
//2. 通过for就可以循环的访问 数组的元素/值
//3. 使用一个变量 totalWeight 将各个元素累积
System.out.println("===使用数组解决===");
//老师提示: 可以通过 数组名.length 得到数组的大小/长度
//System.out.println("数组的长度=" + hens.length);
double totalWeight = 0;
for( int i = 0; i < hens.length; i++) {
//System.out.println("第" + (i+1) + "个元素的值=" + hens[i]);
totalWeight += hens[i];
}
System.out.println("总体重=" + totalWeight
+ "平均体重=" + (totalWeight / hens.length) );
}
} | Ambrogram/https---github.com-Ambrogram-INFO6205 | Array01.java | 747 | //1. 我们可以通过 hens[下标] 来访问数组的元素 | line_comment | zh-cn |
//数组的引出
//
public class Array01 {
//编写一个main方法
public static void main(String[] args) {
/*
它们的体重分别是3kg,5kg,1kg,3.4kg,2kg,50kg 。
请问这六只鸡的总体重是多少?平均体重是多少?
思路分析
1. 定义六个变量 double , 求和 得到总体重
2. 平均体重 = 总体重 / 6
3. 分析传统实现的方式问题. 6->600->566
4. 引出新的技术 -> 使用数组来解决.
*/
// double hen1 = 3;
// double hen2 = 5;
// double hen3 = 1;
// double hen4 = 3.4;
// double hen5 = 2;
// double hen6 = 50;
// double totalWeight = hen1 + hen2 + hen3 + hen4 + hen5 + hen6;
// double avgWeight = totalWeight / 6;
// System.out.println("总体重=" + totalWeight
// + "平均体重=" + avgWeight);
//比如,我们可以用数组来解决上一个问题 => 体验
//
//定义一个数组
//老韩解读
//1. double[] 表示 是double类型的数组, 数组名 hens
//2. {3, 5, 1, 3.4, 2, 50} 表示数组的值/元素,依次表示数组的
// 第几个元素
//
double[] hens = {3, 5, 1, 3.4, 2, 50, 7.8, 88.8,1.1,5.6,100};
//遍历数组得到数组的所有元素的和, 使用for
//老韩解读
//1. <SUF>
// 下标是从 0 开始编号的比如第一个元素就是 hens[0]
// 第2个元素就是 hens[1] , 依次类推
//2. 通过for就可以循环的访问 数组的元素/值
//3. 使用一个变量 totalWeight 将各个元素累积
System.out.println("===使用数组解决===");
//老师提示: 可以通过 数组名.length 得到数组的大小/长度
//System.out.println("数组的长度=" + hens.length);
double totalWeight = 0;
for( int i = 0; i < hens.length; i++) {
//System.out.println("第" + (i+1) + "个元素的值=" + hens[i]);
totalWeight += hens[i];
}
System.out.println("总体重=" + totalWeight
+ "平均体重=" + (totalWeight / hens.length) );
}
} | false |
53552_37 | package AmbroseRen.util;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.lang.reflect.Array;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.Format;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
//import oracle.net.aso.i;
/**
*
* 项目名称:AmbroseRen
* 类名称:Tools
* 类描述:
* 创建人:Administrator
* 创建时间:2018年12月3日 上午9:03:18
* @version
*/
public class Tools {
//截取指定字段字符串
public static String subString(String str, String strStart, String strEnd) {
/* 找出指定的2个字符在 该字符串里面的 位置 */
int strStartIndex = str.indexOf(strStart);
int strEndIndex = str.indexOf(strEnd);
/* index 为负数 即表示该字符串中 没有该字符 */
if (strStartIndex < 0) {
return "字符串 :---->" + str + "<---- 中不存在 " + strStart + ", 无法截取目标字符串";
}
if (strEndIndex < 0) {
return "字符串 :---->" + str + "<---- 中不存在 " + strEnd + ", 无法截取目标字符串";
}
/* 开始截取 */
String result = str.substring(strStartIndex, strEndIndex).substring(strStart.length());
return result;
}
//16进制String 转 2进制byte[]
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
try {
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
} catch (Exception e) {
//Log.d("", "Argument(s) for hexStringToByteArray(String s)"+ "was not a hex string");
}
return data;
}
//2进制byte[] 转16进制String
public static String byte2HexString(byte[] bytes) {
String hex= "";
if (bytes != null) {
for (Byte b : bytes) {
//%02x (x代表以十六进制形式输出,02代表不足两位,前面补0输出,如果超过两位,则以实际输出)
//&0xff 补位运算,防止溢出,在运算前会转成整形参与运算
hex += String.format("%02X", b.intValue() & 0xFF);
}
}
return hex;
}
//二进制字符串 转换为 byte[],每个字节以","隔开
public static byte[] binStrToByteArr(String binStr) {
String[] temp = binStr.split(",");
byte[] b = new byte[temp.length];
for (int i = 0; i < b.length; i++) {
b[i] = Long.valueOf(temp[i], 2).byteValue();
}
return b;
}
//byte[] 转换为 二进制字符串,每个字节以","隔开
public static String byteArrToBinStr(byte[] b) {
StringBuffer result = new StringBuffer();
for (int i = 0; i < b.length; i++) {
result.append(Long.toString(b[i] & 0xff, 2) + ",");
}
return result.toString().substring(0, result.length() - 1);
}
//字符串转换unicode
public static String string2Unicode(String string) {
StringBuffer unicode = new StringBuffer();
for (int i = 0; i < string.length(); i++) {
char c = string.charAt(i);
// 转换为unicode
unicode.append("\\u" + Integer.toHexString(c));
}
return unicode.toString();
}
//unicode 转字符串
public static String unicode2String(String unicode) {
StringBuffer string = new StringBuffer();
String[] hex = unicode.split("\\\\u");
for (int i = 1; i < hex.length; i++) {
// 转换出每一个代码点
int data = Integer.parseInt(hex[i], 16);
// 追加成string
string.append((char) data);
}
return string.toString();
}
//字符串 转 16进制
public static String strTo16(String s) {
String str = "";
for (int i = 0; i < s.length(); i++) {
int ch = (int) s.charAt(i);
String s4 = Integer.toHexString(ch);
str = str + s4;
}
return str;
}
//字符串转换成为16进制(无需Unicode编码)
public static String str2HexStr(String str) {
char[] chars = "0123456789ABCDEF".toCharArray();
StringBuilder sb = new StringBuilder("");
byte[] bs = str.getBytes();
int bit;
for (int i = 0; i < bs.length; i++) {
bit = (bs[i] & 0x0f0) >> 4;
sb.append(chars[bit]);
bit = bs[i] & 0x0f;
sb.append(chars[bit]);
// sb.append(' ');
}
return sb.toString().trim();
}
//16进制转换成为string类型字符串
public static String hexStringToString(String s) {
if (s == null || s.equals("")) {
return null;
}
s = s.replace(" ", "");
byte[] baKeyword = new byte[s.length() / 2];
for (int i = 0; i < baKeyword.length; i++) {
try {
baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
} catch (Exception e) {
e.printStackTrace();
}
}
try {
s = new String(baKeyword, "UTF-8");
new String();
} catch (Exception e) {
e.printStackTrace();
}
return s;
}
//16进制直接转换成为字符串(无需Unicode解码)
public static String hexStr2Str(String hexStr) {
String str = "0123456789ABCDEF";
char[] hexs = hexStr.toCharArray();
byte[] bytes = new byte[hexStr.length() / 2];
int n;
for (int i = 0; i < bytes.length; i++) {
n = str.indexOf(hexs[2 * i]) * 16;
n += str.indexOf(hexs[2 * i + 1]);
bytes[i] = (byte) (n & 0xff);
}
return new String(bytes);
}
//读取IC卡
public void readCard(){
ActiveXComponent component1=new ActiveXComponent("ATMCRWIO.SIMCard");
Dispatch disp1 = (Dispatch) component1.getObject();
Variant variant1=Dispatch.call(disp1, "ReadOperID");
System.out.println(variant1);
ActiveXComponent component2=new ActiveXComponent("ATMCRWIO.MeterCard");
Dispatch disp2 = (Dispatch) component2.getObject();
Variant variant2=Dispatch.call(disp2, "ReadCard",0);
// Variant variant2=component2.invoke("ReadCard",0);
System.out.println(variant2);
//mid(rs,3,5) 是字符串截取的意思
Variant result3 = Dispatch.call(disp2, "WriteCard", null,null,null);
System.out.println(result3);
}
//URL网址 调用,传入URL和参数,如下示例
/** String resultString = Tools.load(
"http://192.168.10.89:8080/eoffice-restful/resources/sys/oaholiday",
"floor=first&year=2017&month=9&isLeader=N");*/
public static String load(String url,String query) throws Exception{
URL restURL = new URL(url);
/*
* 此处的urlConnection对象实际上是根据URL的请求协议(此处是http)生成的URLConnection类 的子类HttpURLConnection
*/
HttpURLConnection conn = (HttpURLConnection) restURL.openConnection();
//请求方式
conn.setRequestMethod("POST");
//设置是否从httpUrlConnection读入,默认情况下是true; httpUrlConnection.setDoInput(true);
conn.setDoOutput(true);
//allowUserInteraction 如果为 true,则在允许用户交互(例如弹出一个验证对话框)的上下文中对此 URL 进行检查。
conn.setAllowUserInteraction(false);
PrintStream ps = new PrintStream(conn.getOutputStream());
ps.print(query);
ps.close();
BufferedReader bReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line,resultStr="";
while(null != (line=bReader.readLine())) {
resultStr +=line;
}
System.out.println("3412412---"+resultStr);
bReader.close();
return resultStr;
}
/**
* HMAC-SHA1 签名源码
* @param data
* @param key
* @return
*/
public static String hamcsha(byte[] data, byte[] key)
{
try {
SecretKeySpec signingKey = new SecretKeySpec(key, "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(signingKey);
return byte2hex(mac.doFinal(data));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
}
return null;
}
public static String byte2hex(byte[] b){
StringBuilder hs = new StringBuilder();
String stmp;
for (int n = 0; b!=null && n < b.length; n++) {
stmp = Integer.toHexString(b[n] & 0XFF);
if (stmp.length() == 1)
hs.append('0');
hs.append(stmp);
}
return hs.toString().toUpperCase();
}
/**
* 转int修改字符串
* @param str
* @return
*/
public static String SIS(String str){
String nextDayNum =String.valueOf(Integer.parseInt(str.substring(str.length() -1, str.length()))+1);
StringBuffer buffer = new StringBuffer(str);
String newStr =(buffer.replace(str.length()-1, str.length(), nextDayNum)).toString();
return newStr;
}
/**
* 字符串取明天时间(根据输入日期长度取格式)
* @param time
* @return
* @throws ParseException
*/
public static String STS(String begindate) throws ParseException{
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date=null;
date=sdf.parse(begindate);
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.DAY_OF_MONTH, 1);
Format f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String tomorrow =f.format(c.getTime());
return tomorrow;
}
/**
* 取下月时间
* @param begindate
* @return
* @throws ParseException
*/
public static String SMS(String begindate) throws ParseException{
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date=null;
date=sdf.parse(begindate);
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.MONTH, 1);
Format f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String nextMonth =f.format(c.getTime());
return nextMonth;
}
//范围质数数组
public static ArrayList PrimeNumber(int beginNum,int endNum){
int count=0;
ArrayList<Integer> array =new ArrayList<Integer>();
for(int a=beginNum;a<=endNum;a++){//遍历范围
boolean flag =true;//开关判断
for(int i=2;i<=Math.sqrt(a);i++){//判断质数 //条件
if(a% i ==0){
flag=false; break;
}
}
if(flag==true){//==true不用写
System.out.print(a+"\t");
array.add(a);
count++;
if(count%10==0){
System.out.println();//够10换行
}
}
}
return array;
}
/**
*
* @param a
* 被匹配的长字符串
* @param b
* 匹配的短字符串
* @return 匹配次数
*/
public int hit(String a, String b) {
if (a.length() < b.length()) {
return 0;
}
char[] a_t = a.toCharArray();
int count = 0;
for (int i = 0; i < a.length() - b.length(); i++) {
StringBuffer buffer = new StringBuffer();
for (int j = 0; j < b.length(); j++) {
buffer.append(a_t[i + j]);
}
if(buffer.toString().equals(b)){
count ++;
}
}
return count;
}
/**
* 使用取值实例:
String[] ArrayID = { "name", "value", "css" };
String[] arr0 =ArrayAdd(ArrayID, "name1", "value1", "css1");
String[] arr1 =ArrayAdd(ArrayID, "name2", "value2", "css2");
//arr0[0]为所传name数组,arr0[1]为所传value数组,arr0[2]为所传css数组
String arr0_name =arr0[0].split(",")[1];
String arr0_value =arr0[1].split(",")[1];
String arr0_css =arr0[2].split(",")[1];
*
* @param ArrayID
* @param name
* @param value
* @param css
* @return
* @throws Exception
*/
public static String[] ArrayAdd(String[] ArrayID,String name,String value,String css) throws Exception{
ArrayID[0]=ArrayID[0]+","+name;
ArrayID[1]=ArrayID[1]+","+value;
ArrayID[2]=ArrayID[2]+","+css;
return ArrayID;
}
}
| AmbroseRen/test | java/Tools.java | 3,735 | //遍历范围 | line_comment | zh-cn | package AmbroseRen.util;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.lang.reflect.Array;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.Format;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
//import oracle.net.aso.i;
/**
*
* 项目名称:AmbroseRen
* 类名称:Tools
* 类描述:
* 创建人:Administrator
* 创建时间:2018年12月3日 上午9:03:18
* @version
*/
public class Tools {
//截取指定字段字符串
public static String subString(String str, String strStart, String strEnd) {
/* 找出指定的2个字符在 该字符串里面的 位置 */
int strStartIndex = str.indexOf(strStart);
int strEndIndex = str.indexOf(strEnd);
/* index 为负数 即表示该字符串中 没有该字符 */
if (strStartIndex < 0) {
return "字符串 :---->" + str + "<---- 中不存在 " + strStart + ", 无法截取目标字符串";
}
if (strEndIndex < 0) {
return "字符串 :---->" + str + "<---- 中不存在 " + strEnd + ", 无法截取目标字符串";
}
/* 开始截取 */
String result = str.substring(strStartIndex, strEndIndex).substring(strStart.length());
return result;
}
//16进制String 转 2进制byte[]
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
try {
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
} catch (Exception e) {
//Log.d("", "Argument(s) for hexStringToByteArray(String s)"+ "was not a hex string");
}
return data;
}
//2进制byte[] 转16进制String
public static String byte2HexString(byte[] bytes) {
String hex= "";
if (bytes != null) {
for (Byte b : bytes) {
//%02x (x代表以十六进制形式输出,02代表不足两位,前面补0输出,如果超过两位,则以实际输出)
//&0xff 补位运算,防止溢出,在运算前会转成整形参与运算
hex += String.format("%02X", b.intValue() & 0xFF);
}
}
return hex;
}
//二进制字符串 转换为 byte[],每个字节以","隔开
public static byte[] binStrToByteArr(String binStr) {
String[] temp = binStr.split(",");
byte[] b = new byte[temp.length];
for (int i = 0; i < b.length; i++) {
b[i] = Long.valueOf(temp[i], 2).byteValue();
}
return b;
}
//byte[] 转换为 二进制字符串,每个字节以","隔开
public static String byteArrToBinStr(byte[] b) {
StringBuffer result = new StringBuffer();
for (int i = 0; i < b.length; i++) {
result.append(Long.toString(b[i] & 0xff, 2) + ",");
}
return result.toString().substring(0, result.length() - 1);
}
//字符串转换unicode
public static String string2Unicode(String string) {
StringBuffer unicode = new StringBuffer();
for (int i = 0; i < string.length(); i++) {
char c = string.charAt(i);
// 转换为unicode
unicode.append("\\u" + Integer.toHexString(c));
}
return unicode.toString();
}
//unicode 转字符串
public static String unicode2String(String unicode) {
StringBuffer string = new StringBuffer();
String[] hex = unicode.split("\\\\u");
for (int i = 1; i < hex.length; i++) {
// 转换出每一个代码点
int data = Integer.parseInt(hex[i], 16);
// 追加成string
string.append((char) data);
}
return string.toString();
}
//字符串 转 16进制
public static String strTo16(String s) {
String str = "";
for (int i = 0; i < s.length(); i++) {
int ch = (int) s.charAt(i);
String s4 = Integer.toHexString(ch);
str = str + s4;
}
return str;
}
//字符串转换成为16进制(无需Unicode编码)
public static String str2HexStr(String str) {
char[] chars = "0123456789ABCDEF".toCharArray();
StringBuilder sb = new StringBuilder("");
byte[] bs = str.getBytes();
int bit;
for (int i = 0; i < bs.length; i++) {
bit = (bs[i] & 0x0f0) >> 4;
sb.append(chars[bit]);
bit = bs[i] & 0x0f;
sb.append(chars[bit]);
// sb.append(' ');
}
return sb.toString().trim();
}
//16进制转换成为string类型字符串
public static String hexStringToString(String s) {
if (s == null || s.equals("")) {
return null;
}
s = s.replace(" ", "");
byte[] baKeyword = new byte[s.length() / 2];
for (int i = 0; i < baKeyword.length; i++) {
try {
baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
} catch (Exception e) {
e.printStackTrace();
}
}
try {
s = new String(baKeyword, "UTF-8");
new String();
} catch (Exception e) {
e.printStackTrace();
}
return s;
}
//16进制直接转换成为字符串(无需Unicode解码)
public static String hexStr2Str(String hexStr) {
String str = "0123456789ABCDEF";
char[] hexs = hexStr.toCharArray();
byte[] bytes = new byte[hexStr.length() / 2];
int n;
for (int i = 0; i < bytes.length; i++) {
n = str.indexOf(hexs[2 * i]) * 16;
n += str.indexOf(hexs[2 * i + 1]);
bytes[i] = (byte) (n & 0xff);
}
return new String(bytes);
}
//读取IC卡
public void readCard(){
ActiveXComponent component1=new ActiveXComponent("ATMCRWIO.SIMCard");
Dispatch disp1 = (Dispatch) component1.getObject();
Variant variant1=Dispatch.call(disp1, "ReadOperID");
System.out.println(variant1);
ActiveXComponent component2=new ActiveXComponent("ATMCRWIO.MeterCard");
Dispatch disp2 = (Dispatch) component2.getObject();
Variant variant2=Dispatch.call(disp2, "ReadCard",0);
// Variant variant2=component2.invoke("ReadCard",0);
System.out.println(variant2);
//mid(rs,3,5) 是字符串截取的意思
Variant result3 = Dispatch.call(disp2, "WriteCard", null,null,null);
System.out.println(result3);
}
//URL网址 调用,传入URL和参数,如下示例
/** String resultString = Tools.load(
"http://192.168.10.89:8080/eoffice-restful/resources/sys/oaholiday",
"floor=first&year=2017&month=9&isLeader=N");*/
public static String load(String url,String query) throws Exception{
URL restURL = new URL(url);
/*
* 此处的urlConnection对象实际上是根据URL的请求协议(此处是http)生成的URLConnection类 的子类HttpURLConnection
*/
HttpURLConnection conn = (HttpURLConnection) restURL.openConnection();
//请求方式
conn.setRequestMethod("POST");
//设置是否从httpUrlConnection读入,默认情况下是true; httpUrlConnection.setDoInput(true);
conn.setDoOutput(true);
//allowUserInteraction 如果为 true,则在允许用户交互(例如弹出一个验证对话框)的上下文中对此 URL 进行检查。
conn.setAllowUserInteraction(false);
PrintStream ps = new PrintStream(conn.getOutputStream());
ps.print(query);
ps.close();
BufferedReader bReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line,resultStr="";
while(null != (line=bReader.readLine())) {
resultStr +=line;
}
System.out.println("3412412---"+resultStr);
bReader.close();
return resultStr;
}
/**
* HMAC-SHA1 签名源码
* @param data
* @param key
* @return
*/
public static String hamcsha(byte[] data, byte[] key)
{
try {
SecretKeySpec signingKey = new SecretKeySpec(key, "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(signingKey);
return byte2hex(mac.doFinal(data));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
}
return null;
}
public static String byte2hex(byte[] b){
StringBuilder hs = new StringBuilder();
String stmp;
for (int n = 0; b!=null && n < b.length; n++) {
stmp = Integer.toHexString(b[n] & 0XFF);
if (stmp.length() == 1)
hs.append('0');
hs.append(stmp);
}
return hs.toString().toUpperCase();
}
/**
* 转int修改字符串
* @param str
* @return
*/
public static String SIS(String str){
String nextDayNum =String.valueOf(Integer.parseInt(str.substring(str.length() -1, str.length()))+1);
StringBuffer buffer = new StringBuffer(str);
String newStr =(buffer.replace(str.length()-1, str.length(), nextDayNum)).toString();
return newStr;
}
/**
* 字符串取明天时间(根据输入日期长度取格式)
* @param time
* @return
* @throws ParseException
*/
public static String STS(String begindate) throws ParseException{
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date=null;
date=sdf.parse(begindate);
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.DAY_OF_MONTH, 1);
Format f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String tomorrow =f.format(c.getTime());
return tomorrow;
}
/**
* 取下月时间
* @param begindate
* @return
* @throws ParseException
*/
public static String SMS(String begindate) throws ParseException{
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date=null;
date=sdf.parse(begindate);
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.MONTH, 1);
Format f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String nextMonth =f.format(c.getTime());
return nextMonth;
}
//范围质数数组
public static ArrayList PrimeNumber(int beginNum,int endNum){
int count=0;
ArrayList<Integer> array =new ArrayList<Integer>();
for(int a=beginNum;a<=endNum;a++){//遍历 <SUF>
boolean flag =true;//开关判断
for(int i=2;i<=Math.sqrt(a);i++){//判断质数 //条件
if(a% i ==0){
flag=false; break;
}
}
if(flag==true){//==true不用写
System.out.print(a+"\t");
array.add(a);
count++;
if(count%10==0){
System.out.println();//够10换行
}
}
}
return array;
}
/**
*
* @param a
* 被匹配的长字符串
* @param b
* 匹配的短字符串
* @return 匹配次数
*/
public int hit(String a, String b) {
if (a.length() < b.length()) {
return 0;
}
char[] a_t = a.toCharArray();
int count = 0;
for (int i = 0; i < a.length() - b.length(); i++) {
StringBuffer buffer = new StringBuffer();
for (int j = 0; j < b.length(); j++) {
buffer.append(a_t[i + j]);
}
if(buffer.toString().equals(b)){
count ++;
}
}
return count;
}
/**
* 使用取值实例:
String[] ArrayID = { "name", "value", "css" };
String[] arr0 =ArrayAdd(ArrayID, "name1", "value1", "css1");
String[] arr1 =ArrayAdd(ArrayID, "name2", "value2", "css2");
//arr0[0]为所传name数组,arr0[1]为所传value数组,arr0[2]为所传css数组
String arr0_name =arr0[0].split(",")[1];
String arr0_value =arr0[1].split(",")[1];
String arr0_css =arr0[2].split(",")[1];
*
* @param ArrayID
* @param name
* @param value
* @param css
* @return
* @throws Exception
*/
public static String[] ArrayAdd(String[] ArrayID,String name,String value,String css) throws Exception{
ArrayID[0]=ArrayID[0]+","+name;
ArrayID[1]=ArrayID[1]+","+value;
ArrayID[2]=ArrayID[2]+","+css;
return ArrayID;
}
}
| false |
26557_5 | public class DoubleNode {
DoubleNode prev = this;
DoubleNode next = this;
int data;
public DoubleNode(int data){
this.data = data;
}
//增加节点
public void after(DoubleNode node){
//原来的下一个节点
DoubleNode nextNext = next;
//把新节点作为当前节点的前一个节点
this.next = node;
//把当前节点做新节点的下一个节点
node.prev = this;
//让原来的下一个节点做新节点的下一个节点
node.next = nextNext;
//让原来的下一个节点的上一个节点做新节点
nextNext.prev = node;
}
//下一个节点
public DoubleNode next(){
return this.next;
}
public DoubleNode prev(){
return this.prev;
}
public int getData(){
return data;
}
}
| Ameesha15/DSA-ALGORITHMS | DoubleNode.java | 201 | //让原来的下一个节点的上一个节点做新节点 | line_comment | zh-cn | public class DoubleNode {
DoubleNode prev = this;
DoubleNode next = this;
int data;
public DoubleNode(int data){
this.data = data;
}
//增加节点
public void after(DoubleNode node){
//原来的下一个节点
DoubleNode nextNext = next;
//把新节点作为当前节点的前一个节点
this.next = node;
//把当前节点做新节点的下一个节点
node.prev = this;
//让原来的下一个节点做新节点的下一个节点
node.next = nextNext;
//让原 <SUF>
nextNext.prev = node;
}
//下一个节点
public DoubleNode next(){
return this.next;
}
public DoubleNode prev(){
return this.prev;
}
public int getData(){
return data;
}
}
| false |
34360_50 | package java_work0202;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class CatApp {
public static void main(String[] args) {
//今回で言えば、猫の種類はランダムに決める必要があるのでRandomインスタンス
//ユーザーからの入力を受け取るのでScannerインスタンスが必要となる
Random rand = new Random();
Scanner sc = new Scanner(System.in);
//続いて定数を定義していこう。
//今回[白,黒,茶トラ]という猫の種類は配列で扱っておくと便利そうだ。
//Catインスタンスを格納するArrayListもこのタイミングで用意しておこう。
//今回は猫を何匹でも集められる仕様なので、
//この場合は要素数が決まっている配列よりもArrayListの方が便利だ
final String[] TYPES = {"白", "黒", "茶トラ"};
ArrayList<Cat> list = new ArrayList<>();
//実行例を見ると、
//メニューの表示->選択->何かしら処理
//というのが繰り返されているのがわかる。なのでforかwhileを使うことになる。
//繰り返す回数がわかる場合はforそうでない場合はwhileを使うというのが基本だ。
//今回は何度繰り返されるかわからない、なのでwhile文を使っていこう。
System.out.println("***猫集め***");
//まずは、終了が選ばれたときの処理を記述
//このように特殊な場合にすぐにreturnして処理を抜けるというのは早期リターンと呼ばれていて、
//処理のネストが深くならない上、
//わかりやすいという特徴があるのでおすすめだ
while(true) {
System.out.print("1.集める 2.遊ぶ 3.終了>>");
int select = sc.nextInt();
if(select == 3) {
System.out.println("***結果***");
for(Cat c : list) {
System.out.println(c.showStatus());
}
System.out.println("また遊んでね。おしまい");
return;
}
//分岐の骨組みを先に書いてしまうのもよく行う手法だ。
//今回、if~elseで組んでも同じだが、
//1を選んだのか2を選んだのかがわかりやすいいように上記のif ~ else if文を使った。
if(select == 1) {
//猫の種類の配列から一つを取り出している。
//ほぼイディオムとも言ってよい処理なので問題はないだろう。
String type = TYPES[rand.nextInt(TYPES.length)];
//%sは後に指定される引数(typeと思われる)で置き換えられます。
//変数 type の値に基づいてフォーマットされたメッセージを表示する
System.out.printf("%s猫を見つけた!%n", type);
System.out.print("この猫に名前をつけてください>>");
//名前を受け取りCatインスタンスを生成し、リストに追加する
String name = sc.next();
Cat cat = new Cat(name, type);
list.add(cat);
System.out.println(cat.name + "が仲間に加わった!");
}
//ここでもまずは異常系の処理を書いていこう。
//このように最初に異常系の処理を書いて抜けるようにするとネストが浅くなる。
//ここではreturnではなくcontinueだ。
else if(select == 2) {
if(list.size() == 0) {
System.out.println("まだ遊ぶ猫がいません。。。");
continue;
}
//showStatus()の結果をフォーマットして表示します
for(int i = 0; i < list.size(); i++) {
System.out.printf("%d・・・%s%n", i, list.get(i).showStatus());
}
//リストに入っている猫をgetで取り出して、
//そのインスタンスがplayメソッドを実行することで親密度があがるのであった。
System.out.print("どの猫と遊びますか?>>");
int no = sc.nextInt();
list.get(no).play();
//sortCatのよびだし
sortCat(list);
}
}
}
//今回は親密度で並び替えを行わなくてはならない。
//なので親密度が変わったまさにこのあとにlistのソート処理をいれる。
//ただ、この下に書くと2を選んだときの記述が長くなりすぎるので、
//この部分は以下のようにメソッドにしよう。以下の処理をメインメソッドの外に書く。
//このコードは、ArrayList内のCatオブジェクトを
//intimacy(親密度)の降順にソートするための静的メソッドです。
static void sortCat(ArrayList<Cat> list) {
for(int i = 0; i < list.size()-1; i++) {
for(int j = i+1; j < list.size(); j++) {
//list.get(i).intimacy < list.get(j).intimacyがtrueであれば、
//i番目の要素のintimacyがj番目の要素のintimacyよりも小さいということです。
//この場合、要素を入れ替えます。
if(list.get(i).intimacy < list.get(j).intimacy) {
//tempを使ってi番目の要素を退避し、j番目の要素をi番目にセットし、
//最後にtempの値をj番目にセットしています。
Cat temp = list.get(i);
list.set(i, list.get(j));
list.set(i, temp);
}
}
}
}
}
class Cat {
//フィールド
String name;
private String type;
int intimacy = 0;
//コンストラクタ
//クラスのインスタンスを生成するための特別なメソッドです。
//コンストラクタはクラス名と同じ名前を持ち、戻り値の型が指定されていません。
//主な目的は、新しいオブジェクトを初期化することです。
//コンストラクタは、newキーワードを使用してオブジェクトを生成する際に呼び出されます
//今回は(名前、種類)を指定してインスタンスを生成できるようにする
public Cat(String name, String type) {
this.name = name;
this.type = type;
}
//自分自身の情報を文字列情報として表せるメソッドex.やま[茶トラ](0)
//%s:文字列、%d:整数。%f:少数、%n:改行
//String.gormat("フォーマット文字列", 仮置きした値);
public String showStatus() {
return String.format("%s[%s](%d)", this.name, this.type, this.intimacy);
}
//メソッドをどこに記述するかを考える際、重要となるのが自分のフィールド(パラメータ)を操作する部分があったら
//それはインスタンスメソッドとして作成するということ
//今回は遊ぶことによって親密度があがるのでこの部分はインスタンスメソッドとして記述していく
public void play() {
System.out.println(this.name + "と遊んだ");
System.out.println("...");
System.out.println(this.name+"の親密度がアップした!");
this.intimacy++;
}
}
| AmiOshima0130/java_work | CatApp.java | 2,102 | //%s:文字列、%d:整数。%f:少数、%n:改行 | line_comment | zh-cn | package java_work0202;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class CatApp {
public static void main(String[] args) {
//今回で言えば、猫の種類はランダムに決める必要があるのでRandomインスタンス
//ユーザーからの入力を受け取るのでScannerインスタンスが必要となる
Random rand = new Random();
Scanner sc = new Scanner(System.in);
//続いて定数を定義していこう。
//今回[白,黒,茶トラ]という猫の種類は配列で扱っておくと便利そうだ。
//Catインスタンスを格納するArrayListもこのタイミングで用意しておこう。
//今回は猫を何匹でも集められる仕様なので、
//この場合は要素数が決まっている配列よりもArrayListの方が便利だ
final String[] TYPES = {"白", "黒", "茶トラ"};
ArrayList<Cat> list = new ArrayList<>();
//実行例を見ると、
//メニューの表示->選択->何かしら処理
//というのが繰り返されているのがわかる。なのでforかwhileを使うことになる。
//繰り返す回数がわかる場合はforそうでない場合はwhileを使うというのが基本だ。
//今回は何度繰り返されるかわからない、なのでwhile文を使っていこう。
System.out.println("***猫集め***");
//まずは、終了が選ばれたときの処理を記述
//このように特殊な場合にすぐにreturnして処理を抜けるというのは早期リターンと呼ばれていて、
//処理のネストが深くならない上、
//わかりやすいという特徴があるのでおすすめだ
while(true) {
System.out.print("1.集める 2.遊ぶ 3.終了>>");
int select = sc.nextInt();
if(select == 3) {
System.out.println("***結果***");
for(Cat c : list) {
System.out.println(c.showStatus());
}
System.out.println("また遊んでね。おしまい");
return;
}
//分岐の骨組みを先に書いてしまうのもよく行う手法だ。
//今回、if~elseで組んでも同じだが、
//1を選んだのか2を選んだのかがわかりやすいいように上記のif ~ else if文を使った。
if(select == 1) {
//猫の種類の配列から一つを取り出している。
//ほぼイディオムとも言ってよい処理なので問題はないだろう。
String type = TYPES[rand.nextInt(TYPES.length)];
//%sは後に指定される引数(typeと思われる)で置き換えられます。
//変数 type の値に基づいてフォーマットされたメッセージを表示する
System.out.printf("%s猫を見つけた!%n", type);
System.out.print("この猫に名前をつけてください>>");
//名前を受け取りCatインスタンスを生成し、リストに追加する
String name = sc.next();
Cat cat = new Cat(name, type);
list.add(cat);
System.out.println(cat.name + "が仲間に加わった!");
}
//ここでもまずは異常系の処理を書いていこう。
//このように最初に異常系の処理を書いて抜けるようにするとネストが浅くなる。
//ここではreturnではなくcontinueだ。
else if(select == 2) {
if(list.size() == 0) {
System.out.println("まだ遊ぶ猫がいません。。。");
continue;
}
//showStatus()の結果をフォーマットして表示します
for(int i = 0; i < list.size(); i++) {
System.out.printf("%d・・・%s%n", i, list.get(i).showStatus());
}
//リストに入っている猫をgetで取り出して、
//そのインスタンスがplayメソッドを実行することで親密度があがるのであった。
System.out.print("どの猫と遊びますか?>>");
int no = sc.nextInt();
list.get(no).play();
//sortCatのよびだし
sortCat(list);
}
}
}
//今回は親密度で並び替えを行わなくてはならない。
//なので親密度が変わったまさにこのあとにlistのソート処理をいれる。
//ただ、この下に書くと2を選んだときの記述が長くなりすぎるので、
//この部分は以下のようにメソッドにしよう。以下の処理をメインメソッドの外に書く。
//このコードは、ArrayList内のCatオブジェクトを
//intimacy(親密度)の降順にソートするための静的メソッドです。
static void sortCat(ArrayList<Cat> list) {
for(int i = 0; i < list.size()-1; i++) {
for(int j = i+1; j < list.size(); j++) {
//list.get(i).intimacy < list.get(j).intimacyがtrueであれば、
//i番目の要素のintimacyがj番目の要素のintimacyよりも小さいということです。
//この場合、要素を入れ替えます。
if(list.get(i).intimacy < list.get(j).intimacy) {
//tempを使ってi番目の要素を退避し、j番目の要素をi番目にセットし、
//最後にtempの値をj番目にセットしています。
Cat temp = list.get(i);
list.set(i, list.get(j));
list.set(i, temp);
}
}
}
}
}
class Cat {
//フィールド
String name;
private String type;
int intimacy = 0;
//コンストラクタ
//クラスのインスタンスを生成するための特別なメソッドです。
//コンストラクタはクラス名と同じ名前を持ち、戻り値の型が指定されていません。
//主な目的は、新しいオブジェクトを初期化することです。
//コンストラクタは、newキーワードを使用してオブジェクトを生成する際に呼び出されます
//今回は(名前、種類)を指定してインスタンスを生成できるようにする
public Cat(String name, String type) {
this.name = name;
this.type = type;
}
//自分自身の情報を文字列情報として表せるメソッドex.やま[茶トラ](0)
//%s <SUF>
//String.gormat("フォーマット文字列", 仮置きした値);
public String showStatus() {
return String.format("%s[%s](%d)", this.name, this.type, this.intimacy);
}
//メソッドをどこに記述するかを考える際、重要となるのが自分のフィールド(パラメータ)を操作する部分があったら
//それはインスタンスメソッドとして作成するということ
//今回は遊ぶことによって親密度があがるのでこの部分はインスタンスメソッドとして記述していく
public void play() {
System.out.println(this.name + "と遊んだ");
System.out.println("...");
System.out.println(this.name+"の親密度がアップした!");
this.intimacy++;
}
}
| false |
27852_6 | 前言部分:
1.concurentHashmap在jdk8以前,使用的是分段锁的设计理念来完成并发控制,1.8进行了一次非常大幅度的改版,原因有下:
(1).synchronized关键字 -- 1.8对synchronized的优化已经足够好,以至于不需要用segment来增强并发
(2).类似于hashmap在1.8的增强,concurenthashmap也在出现hash冲突过多的时候采用红黑树的方式来降低query的时间
2.这里为什么分析transfer方法呢:
(1).transfer方法是concurenthashmap里最复杂的方法
(2).transfer方法在1.8的时候也进行了增强,在出现多线程问题的时候,如果让我设计,我的第一反应是锁住当前map,transfer之后再修改,那么1.8里怎么做的呢,非常非常非常牛逼,它直接把另外一个线程拉进来一起帮着做transfer,
而控制transfer的就是concurenthashmap中的新数据结构,ForwardingNode。
其实这里我还有一些地方没有彻底搞明白,也借鉴了一下网上其他人对源码的解读,综合了一下我自己的理解,重要的部分都用中文做了注释,有兴趣的可以研究一下源码以及相关概念,concurenthashmap和hashmap在1.8的改变真的是非常非常大。
/**
* Moves and/or copies the nodes in each bin to new table. See
* above for explanation.
*/
private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
int n = tab.length, stride;
if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
stride = MIN_TRANSFER_STRIDE; // subdivide range
if (nextTab == null) { // initiating
try {
//构造一个nextTable对象 它的容量是原来的两倍
Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n << 1];
nextTab = nt;
} catch (Throwable ex) { // try to cope with OOME
sizeCtl = Integer.MAX_VALUE;
return;
}
nextTable = nextTab;
//下一个表索引 + 1 在调整时
transferIndex = n;
}
int nextn = nextTab.length;
ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab); //构造一个连节点指针 用于标志位
boolean advance = true; //并发扩容的关键属性 如果等于true 说明这个节点已经处理过
boolean finishing = false; // to ensure sweep before committing nextTab
//这里是一个无限循环,直到处理结束或者(sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT条件达成 TODO <--这个条件干吗用的
for (int i = 0, bound = 0;;) {
Node<K,V> f; int fh;
//这个while循环体的作用就是在控制i,不断的i--,用来循环整个table
while (advance) {
int nextIndex, nextBound;
if (--i >= bound || finishing)
advance = false;
else if ((nextIndex = transferIndex) <= 0) {
i = -1;
advance = false;
} else if (U.compareAndSwapInt(this, TRANSFERINDEX, nextIndex,nextBound = (nextIndex > stride ? nextIndex - stride : 0))) {
bound = nextBound;
i = nextIndex - 1;
advance = false;
}
}
//nextn就是下一个table的长度,n是旧表的长度,i则是每一个元素的位置
if (i < 0 || i >= n || i + n >= nextn) {
int sc;
//如果所有的节点都已经完成复制工作 就把nextTable赋值给table 清空临时对象nextTable
if (finishing) {
nextTable = null;
table = nextTab;
sizeCtl = (n << 1) - (n >>> 1);//扩容阈值设置为原来容量的1.5倍 依然相当于现在容量的0.75倍
return;
}
if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, sc - 1)) {
//什么时候会在这里返回???
if ((sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT) {
return;
}
finishing = advance = true;
i = n; // recheck before commit
}
} else if ((f = tabAt(tab, i)) == null) {
//如果遍历到的节点为空 则放入ForwardingNode指针
advance = casTabAt(tab, i, null, fwd);
} else if ((fh = f.hash) == MOVED) {
//如果遍历到ForwardingNode节点 说明这个点已经被处理过了 直接跳过 这里是控制并发扩容的核心
advance = true; // already processed
} else {
synchronized (f) {
if (tabAt(tab, i) == f) {
Node<K,V> ln, hn;
//如果fh>=0 证明这是一个Node节点
if (fh >= 0) {
//以下的部分在完成的工作是构造两个链表
int runBit = fh & n;
Node<K,V> lastRun = f;
for (Node<K,V> p = f.next; p != null; p = p.next) {
int b = p.hash & n;
if (b != runBit) {
runBit = b;
lastRun = p;
}
}
if (runBit == 0) {
ln = lastRun;
hn = null;
} else {
hn = lastRun;
ln = null;
}
for (Node<K,V> p = f; p != lastRun; p = p.next) {
int ph = p.hash; K pk = p.key; V pv = p.val;
if ((ph & n) == 0)
ln = new Node<K,V>(ph, pk, pv, ln);
else
hn = new Node<K,V>(ph, pk, pv, hn);
}
//在nextTable的i位置上插入一个链表
setTabAt(nextTab, i, ln);
//这是在干吗没看懂- -
setTabAt(nextTab, i + n, hn);
//在table的i位置上插入forwardNode节点 表示已经处理过该节点
setTabAt(tab, i, fwd);
//设置advance为true 返回到上面的while循环中 就可以执行i--操作
advance = true;
}
//对TreeBin对象进行处理 与上面的过程类似
else if (f instanceof TreeBin) {
TreeBin<K,V> t = (TreeBin<K,V>)f;
TreeNode<K,V> lo = null, loTail = null;
TreeNode<K,V> hi = null, hiTail = null;
int lc = 0, hc = 0;
for (Node<K,V> e = t.first; e != null; e = e.next) {
int h = e.hash;
TreeNode<K,V> p = new TreeNode<K,V>
(h, e.key, e.val, null, null);
if ((h & n) == 0) {
if ((p.prev = loTail) == null)
lo = p;
else
loTail.next = p;
loTail = p;
++lc;
}
else {
if ((p.prev = hiTail) == null)
hi = p;
else
hiTail.next = p;
hiTail = p;
++hc;
}
}
//如果扩容后已经不再需要tree的结构 反向转换为链表结构
ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) :
(hc != 0) ? new TreeBin<K,V>(lo) : t;
hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) :
(lc != 0) ? new TreeBin<K,V>(hi) : t;
setTabAt(nextTab, i, ln);
setTabAt(nextTab, i + n, hn);
setTabAt(tab, i, fwd);
advance = true;
}
}
}
}
// end if
}
} | Amnesiacs/Dubbo-Code | 顺道分享java源码解析/transfer.java | 2,020 | //构造一个连节点指针 用于标志位 | line_comment | zh-cn | 前言部分:
1.concurentHashmap在jdk8以前,使用的是分段锁的设计理念来完成并发控制,1.8进行了一次非常大幅度的改版,原因有下:
(1).synchronized关键字 -- 1.8对synchronized的优化已经足够好,以至于不需要用segment来增强并发
(2).类似于hashmap在1.8的增强,concurenthashmap也在出现hash冲突过多的时候采用红黑树的方式来降低query的时间
2.这里为什么分析transfer方法呢:
(1).transfer方法是concurenthashmap里最复杂的方法
(2).transfer方法在1.8的时候也进行了增强,在出现多线程问题的时候,如果让我设计,我的第一反应是锁住当前map,transfer之后再修改,那么1.8里怎么做的呢,非常非常非常牛逼,它直接把另外一个线程拉进来一起帮着做transfer,
而控制transfer的就是concurenthashmap中的新数据结构,ForwardingNode。
其实这里我还有一些地方没有彻底搞明白,也借鉴了一下网上其他人对源码的解读,综合了一下我自己的理解,重要的部分都用中文做了注释,有兴趣的可以研究一下源码以及相关概念,concurenthashmap和hashmap在1.8的改变真的是非常非常大。
/**
* Moves and/or copies the nodes in each bin to new table. See
* above for explanation.
*/
private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
int n = tab.length, stride;
if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
stride = MIN_TRANSFER_STRIDE; // subdivide range
if (nextTab == null) { // initiating
try {
//构造一个nextTable对象 它的容量是原来的两倍
Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n << 1];
nextTab = nt;
} catch (Throwable ex) { // try to cope with OOME
sizeCtl = Integer.MAX_VALUE;
return;
}
nextTable = nextTab;
//下一个表索引 + 1 在调整时
transferIndex = n;
}
int nextn = nextTab.length;
ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab); //构造 <SUF>
boolean advance = true; //并发扩容的关键属性 如果等于true 说明这个节点已经处理过
boolean finishing = false; // to ensure sweep before committing nextTab
//这里是一个无限循环,直到处理结束或者(sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT条件达成 TODO <--这个条件干吗用的
for (int i = 0, bound = 0;;) {
Node<K,V> f; int fh;
//这个while循环体的作用就是在控制i,不断的i--,用来循环整个table
while (advance) {
int nextIndex, nextBound;
if (--i >= bound || finishing)
advance = false;
else if ((nextIndex = transferIndex) <= 0) {
i = -1;
advance = false;
} else if (U.compareAndSwapInt(this, TRANSFERINDEX, nextIndex,nextBound = (nextIndex > stride ? nextIndex - stride : 0))) {
bound = nextBound;
i = nextIndex - 1;
advance = false;
}
}
//nextn就是下一个table的长度,n是旧表的长度,i则是每一个元素的位置
if (i < 0 || i >= n || i + n >= nextn) {
int sc;
//如果所有的节点都已经完成复制工作 就把nextTable赋值给table 清空临时对象nextTable
if (finishing) {
nextTable = null;
table = nextTab;
sizeCtl = (n << 1) - (n >>> 1);//扩容阈值设置为原来容量的1.5倍 依然相当于现在容量的0.75倍
return;
}
if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, sc - 1)) {
//什么时候会在这里返回???
if ((sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT) {
return;
}
finishing = advance = true;
i = n; // recheck before commit
}
} else if ((f = tabAt(tab, i)) == null) {
//如果遍历到的节点为空 则放入ForwardingNode指针
advance = casTabAt(tab, i, null, fwd);
} else if ((fh = f.hash) == MOVED) {
//如果遍历到ForwardingNode节点 说明这个点已经被处理过了 直接跳过 这里是控制并发扩容的核心
advance = true; // already processed
} else {
synchronized (f) {
if (tabAt(tab, i) == f) {
Node<K,V> ln, hn;
//如果fh>=0 证明这是一个Node节点
if (fh >= 0) {
//以下的部分在完成的工作是构造两个链表
int runBit = fh & n;
Node<K,V> lastRun = f;
for (Node<K,V> p = f.next; p != null; p = p.next) {
int b = p.hash & n;
if (b != runBit) {
runBit = b;
lastRun = p;
}
}
if (runBit == 0) {
ln = lastRun;
hn = null;
} else {
hn = lastRun;
ln = null;
}
for (Node<K,V> p = f; p != lastRun; p = p.next) {
int ph = p.hash; K pk = p.key; V pv = p.val;
if ((ph & n) == 0)
ln = new Node<K,V>(ph, pk, pv, ln);
else
hn = new Node<K,V>(ph, pk, pv, hn);
}
//在nextTable的i位置上插入一个链表
setTabAt(nextTab, i, ln);
//这是在干吗没看懂- -
setTabAt(nextTab, i + n, hn);
//在table的i位置上插入forwardNode节点 表示已经处理过该节点
setTabAt(tab, i, fwd);
//设置advance为true 返回到上面的while循环中 就可以执行i--操作
advance = true;
}
//对TreeBin对象进行处理 与上面的过程类似
else if (f instanceof TreeBin) {
TreeBin<K,V> t = (TreeBin<K,V>)f;
TreeNode<K,V> lo = null, loTail = null;
TreeNode<K,V> hi = null, hiTail = null;
int lc = 0, hc = 0;
for (Node<K,V> e = t.first; e != null; e = e.next) {
int h = e.hash;
TreeNode<K,V> p = new TreeNode<K,V>
(h, e.key, e.val, null, null);
if ((h & n) == 0) {
if ((p.prev = loTail) == null)
lo = p;
else
loTail.next = p;
loTail = p;
++lc;
}
else {
if ((p.prev = hiTail) == null)
hi = p;
else
hiTail.next = p;
hiTail = p;
++hc;
}
}
//如果扩容后已经不再需要tree的结构 反向转换为链表结构
ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) :
(hc != 0) ? new TreeBin<K,V>(lo) : t;
hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) :
(lc != 0) ? new TreeBin<K,V>(hi) : t;
setTabAt(nextTab, i, ln);
setTabAt(nextTab, i + n, hn);
setTabAt(tab, i, fwd);
advance = true;
}
}
}
}
// end if
}
} | false |
63096_0 | package anmao.mc.ned.mob$skill.b2;
import anmao.mc.amlib.attribute.AttributeHelper;
import anmao.mc.ned.attribute.NEDAttributes;
import anmao.mc.ned.lib.EntityHelper;
import anmao.mc.ned.mob$skill.MobSkill;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.ai.attributes.AttributeModifier;
import net.minecraft.world.entity.ai.attributes.Attributes;
import net.minecraftforge.event.entity.living.LivingEvent;
import net.minecraftforge.eventbus.api.Event;
import java.util.List;
public class AloneMobSkill extends MobSkill {
//孤独
//怪物越少,攻击力,移速,减伤提升越多
public AloneMobSkill(String id) {
super(id);
}
@Override
public <T extends Event> void event(T event, CompoundTag dat) {
if (event instanceof LivingEvent.LivingTickEvent livingTickEvent){
int tick = dat.getInt("tick");
if (tick > 200){
dat.putInt("tick",0);
LivingEntity entity = livingTickEvent.getEntity();
List<? extends LivingEntity> entities = EntityHelper.getLivingEntities(entity);
double s = 1d / entities.size();
double a = 1 + s * 5;
AttributeHelper.setTempAttribute(entity, Attributes.ATTACK_DAMAGE,ATTRIBUTE_SKILL_ATTACK_DAMAGE,a, AttributeModifier.Operation.MULTIPLY_TOTAL,180);
a = 1 + s * 2;
AttributeHelper.setTempAttribute(entity, Attributes.MOVEMENT_SPEED,ATTRIBUTE_SKILL_MOVE_SPEED,a, AttributeModifier.Operation.MULTIPLY_TOTAL,180);
a = s * 50;
AttributeHelper.setTempAttribute(entity, NEDAttributes.hurtDown,ATTRIBUTE_SKILL_HURT_DOWN,a, AttributeModifier.Operation.ADDITION,180);
}else {
dat.putInt("tick",tick + 1);
}
}
}
}
| An-Mao/NekoDifficulty | src/main/java/anmao/mc/ned/mob$skill/b2/AloneMobSkill.java | 530 | //怪物越少,攻击力,移速,减伤提升越多 | line_comment | zh-cn | package anmao.mc.ned.mob$skill.b2;
import anmao.mc.amlib.attribute.AttributeHelper;
import anmao.mc.ned.attribute.NEDAttributes;
import anmao.mc.ned.lib.EntityHelper;
import anmao.mc.ned.mob$skill.MobSkill;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.ai.attributes.AttributeModifier;
import net.minecraft.world.entity.ai.attributes.Attributes;
import net.minecraftforge.event.entity.living.LivingEvent;
import net.minecraftforge.eventbus.api.Event;
import java.util.List;
public class AloneMobSkill extends MobSkill {
//孤独
//怪物 <SUF>
public AloneMobSkill(String id) {
super(id);
}
@Override
public <T extends Event> void event(T event, CompoundTag dat) {
if (event instanceof LivingEvent.LivingTickEvent livingTickEvent){
int tick = dat.getInt("tick");
if (tick > 200){
dat.putInt("tick",0);
LivingEntity entity = livingTickEvent.getEntity();
List<? extends LivingEntity> entities = EntityHelper.getLivingEntities(entity);
double s = 1d / entities.size();
double a = 1 + s * 5;
AttributeHelper.setTempAttribute(entity, Attributes.ATTACK_DAMAGE,ATTRIBUTE_SKILL_ATTACK_DAMAGE,a, AttributeModifier.Operation.MULTIPLY_TOTAL,180);
a = 1 + s * 2;
AttributeHelper.setTempAttribute(entity, Attributes.MOVEMENT_SPEED,ATTRIBUTE_SKILL_MOVE_SPEED,a, AttributeModifier.Operation.MULTIPLY_TOTAL,180);
a = s * 50;
AttributeHelper.setTempAttribute(entity, NEDAttributes.hurtDown,ATTRIBUTE_SKILL_HURT_DOWN,a, AttributeModifier.Operation.ADDITION,180);
}else {
dat.putInt("tick",tick + 1);
}
}
}
}
| false |
10486_209 | package com.cy.androidview;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.os.Handler;
import android.os.Looper;
import android.util.TypedValue;
import android.view.View;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by lenovo on 2017/12/24.
*/
public class BitmapUtils {
/**
* 选择变换
*
* @param origin 原图
* @param orientationDegree 旋转角度,可正可负
* @return 旋转后的图片
*/
public static Bitmap bitmapRotate(Bitmap origin, float orientationDegree) {
if (origin == null) {
return null;
}
int width = origin.getWidth();
int height = origin.getHeight();
Matrix matrix = new Matrix();
matrix.setRotate(orientationDegree);
// 围绕原地进行旋转
Bitmap newBM = Bitmap.createBitmap(origin, 0, 0, width, height, matrix, false);
return newBM;
}
/**
* @param source
* @param degree 比如90度,是顺时针旋转90度,-90度是逆时针旋转90度
* @param flipHorizontal 是否左右镜像
* @return
*/
public static Bitmap bitmapRotate(Bitmap source, int degree, boolean flipHorizontal) {
if (degree == 0 && !flipHorizontal) {
return source;
}
Matrix matrix = new Matrix();
matrix.postRotate(degree);
if (flipHorizontal)
matrix.postScale(-1, 1);
return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, false);
}
/**
* 从底层返回的数据拿到对应的图片的角度,有些手机hal层会对手机拍出来的照片作相应的旋转,有些手机不会(比如三星手机)
* //有些奇葩垃圾手机拍出来会被旋转,如小米奇葩垃圾手机 cc9,
* //手机屏幕正上方指向正上方,图片逆时针旋转了90度,getHardwareOrientation 得到90度,
* 手机屏幕正上方指向正左方,图片没有被旋转,getHardwareOrientation得到0度
*
* @return
*/
public static int getPicDegree(InputStream inputStream) {
int degree = 0;
try {
ExifInterface exifInterface = new ExifInterface(inputStream);
int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
degree = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
degree = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
degree = 270;
break;
}
// exifInterface.setAttribute(ExifInterface.TAG_ORIENTATION, "no");
// exifInterface.saveAttributes();
} catch (IOException e) {
e.printStackTrace();
LogUtils.log("getPicDegree", e.getMessage());
}
LogUtils.log("getPicDegree", degree);
return degree;
}
/**
* 从底层返回的数据拿到对应的图片的角度,有些手机hal层会对手机拍出来的照片作相应的旋转,有些手机不会(比如三星手机)
* //有些奇葩垃圾手机拍出来会被旋转,如小米奇葩垃圾手机 cc9,
* //手机屏幕正上方指向正上方,图片逆时针旋转了90度,getHardwareOrientation 得到90度,
* 手机屏幕正上方指向正左方,图片没有被旋转,getHardwareOrientation得到0度
*
* @return
*/
// public static int getHardwareOrientation(byte[] jpeg) {
// if (jpeg == null) {
// return 0;
// }
//
// int offset = 0;
// int length = 0;
//
// // ISO/IEC 10918-1:1993(E)
// while (offset + 3 < jpeg.length && (jpeg[offset++] & 0xFF) == 0xFF) {
// int marker = jpeg[offset] & 0xFF;
//
// // Check if the marker is a padding.
// if (marker == 0xFF) {
// continue;
// }
// offset++;
//
// // Check if the marker is SOI or TEM.
// if (marker == 0xD8 || marker == 0x01) {
// continue;
// }
// // Check if the marker is EOI or SOS.
// if (marker == 0xD9 || marker == 0xDA) {
// break;
// }
//
// // Get the length and check if it is reasonable.
// length = pack(jpeg, offset, 2, false);
// if (length < 2 || offset + length > jpeg.length) {
//// KSLog.e(TAG, "Invalid length");
// return 0;
// }
//
// // Break if the marker is EXIF in APP1.
// if (marker == 0xE1 && length >= 8 &&
// pack(jpeg, offset + 2, 4, false) == 0x45786966 &&
// pack(jpeg, offset + 6, 2, false) == 0) {
// offset += 8;
// length -= 8;
// break;
// }
//
// // Skip other markers.
// offset += length;
// length = 0;
// }
//
// // JEITA CP-3451 Exif Version 2.2
// if (length > 8) {
// // Identify the byte order.
// int tag = pack(jpeg, offset, 4, false);
// if (tag != 0x49492A00 && tag != 0x4D4D002A) {
//// KSLog.e(TAG, "Invalid byte order");
// return 0;
// }
// boolean littleEndian = (tag == 0x49492A00);
//
// // Get the offset and check if it is reasonable.
// int count = pack(jpeg, offset + 4, 4, littleEndian) + 2;
// if (count < 10 || count > length) {
//// KSLog.e(TAG, "Invalid offset");
// return 0;
// }
// offset += count;
// length -= count;
//
// // Get the count and go through all the elements.
// count = pack(jpeg, offset - 2, 2, littleEndian);
// while (count-- > 0 && length >= 12) {
// // Get the tag and check if it is orientation.
// tag = pack(jpeg, offset, 2, littleEndian);
// if (tag == 0x0112) {
// // We do not really care about type and count, do we?
// int orientation = pack(jpeg, offset + 8, 2, littleEndian);
// switch (orientation) {
// case 1:
// return 0;
// case 3:
// return 180;
// case 6:
// return 90;
// case 8:
// return 270;
// }
//// KSLog.i(TAG, "Unsupported orientation");
// return 0;
// }
// offset += 12;
// length -= 12;
// }
// }
// return 0;
// }
//
// private static int pack(byte[] bytes, int offset, int length,
// boolean littleEndian) {
// int step = 1;
// if (littleEndian) {
// offset += length - 1;
// step = -1;
// }
//
// int value = 0;
// while (length-- > 0) {
// value = (value << 8) | (bytes[offset] & 0xFF);
// offset += step;
// }
// return value;
// }
public static String getSuffix(String filePath) {
String suffix = "";
try {
suffix = filePath.substring(filePath.lastIndexOf(".") + 1, filePath.length());
} catch (Exception e) {
}
return suffix;
}
/**
* @param bitmap
* @return
*/
// public static boolean saveBitmapToFile(Bitmap bitmap, File file) {
// return saveBitmapToFile(bitmap, file, 100);
// }
/**
* @param bitmap
* @return
*/
public static boolean saveBitmapToFile(Bitmap bitmap, File file, int quality) {
try {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
if (file.getAbsolutePath().endsWith(".png")) {
//PNG不支持压缩
bitmap.compress(Bitmap.CompressFormat.PNG, quality, bos);
} else {
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, bos);
}
bos.flush();
bos.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
// public static boolean saveBitmapToPngFile(Bitmap bitmap, String path) {
// return saveBitmapToPngFile(bitmap,createFile(path));
// }
// public static boolean saveBitmapToPngFile(Bitmap bitmap, File file) {
// try {
// BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
// //写60页不会压缩,因为PNG不支持压缩
// bitmap.compress(Bitmap.CompressFormat.PNG,100,bos);
// bos.flush();
// bos.close();
// } catch (IOException e) {
// e.printStackTrace();
// return false;
// }
// return true;
// }
/**
* 根据路径 创建文件
*
* @param pathFile
* @return
* @throws Exception 用Exception 防止其他异常
*/
public static File createFile(String pathFile) {
File file = null;
try {
File fileDir = new File(pathFile.substring(0, pathFile.lastIndexOf(File.separator)));
file = new File(pathFile);
if (!fileDir.exists()) fileDir.mkdirs();
if (!file.exists()) file.createNewFile();
} catch (Exception e) {
}
return file;
}
// /**
// * 不压缩,传入压缩过的bitampa
// *
// * @param bitmap
// * @return
// */
// public static boolean saveBitmapToFile(Bitmap bitmap, String path) {
// File file = null;
// try {
// file = createFile(path);
// } catch (IOException e) {
// e.printStackTrace();
// return false;
// }
// return saveBitmapToFile(bitmap, file, 100);
// }
/**
* 压缩,
*
* @param bitmap
* @return
*/
public static boolean saveBitmapToFile(Bitmap bitmap, String path, int quality) {
return saveBitmapToFile(bitmap, createFile(path), quality);
}
public static boolean saveBitmapToFile_90(Bitmap bitmap, String path) {
return saveBitmapToFile(bitmap, createFile(path), 90);
}
/**
* 不压缩
*
* @return
*/
public static boolean saveBytesToFile(byte[] bytes, String path) {
File file = createFile(path);
if (file == null) return false;
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(bytes);
fileOutputStream.flush();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return true;
}
// /*
// * 由file转bitmap,压缩
// */
//
// public static Bitmap decodeBitmapFromStream(InputStream inputStream, long contentLength, int widthReq, int heightReq) {
//
// // First decode with inJustDecodeBounds=true to check dimensions
// BitmapFactory.Options options = new BitmapFactory.Options();
// // Calculate inSampleSize
// //不让图片文件>500kb,不一定精准
// float ratio = contentLength * 1f / 1024 / 500;
// if (ratio >= 1) {
// options.inSampleSize = (int) Math.round(ratio + 1.5);
// } else {
// options.inSampleSize = 2;
// }
// Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, options);
// if (bitmap == null) return null;
// return compressBitmap(bitmap, widthReq, heightReq);
// }
/*
* 计算采样率
*/
// public static int calculateInSampleSize(BitmapFactory.Options options,
// int reqWidth, int reqHeight) {
// // Raw height and width of image
// final int height = options.outHeight;
// final int width = options.outWidth;
// int inSampleSize = 1;
//
// if (height > reqHeight || width > reqWidth) {
//
// final int halfHeight = height / 2;
// final int halfWidth = width / 2;
// while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) {
// inSampleSize *= 2;
// }
// }
//
// return inSampleSize;
// }
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
final int width = options.outWidth;
final int height = options.outHeight;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
//使用需要的宽高的最大值来计算比率
final int suitedValue = reqHeight > reqWidth ? reqHeight : reqWidth;
final int heightRatio = Math.round((float) height / (float) suitedValue);
final int widthRatio = Math.round((float) width / (float) suitedValue);
inSampleSize = heightRatio > widthRatio ? heightRatio : widthRatio;//用最大
}
return inSampleSize;
}
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidthxreqHeight) {
return getInSampleSize(options.outWidth, options.outHeight, reqWidthxreqHeight);
}
/**
* 裁剪
*
* @param bitmap 原图
* @return 裁剪后的图像
*/
public static Bitmap cropBitmap(Bitmap bitmap, float hRatioW) {
int w = bitmap.getWidth(); // 得到图片的宽,高
int h = bitmap.getHeight();
return Bitmap.createBitmap(bitmap, 0, 0, w, (int) (w * hRatioW), null, false);
}
/**
* 按比例缩放图片
*
* @param origin 原图
* @param ratio 比例
* @return 新的bitmap
*/
public static Bitmap scaleBitmap(Bitmap origin, float ratio) {
int width = origin.getWidth();
int height = origin.getHeight();
Matrix matrix = new Matrix();
matrix.preScale(ratio, ratio);
Bitmap newBM = Bitmap.createBitmap(origin, 0, 0, width, height, matrix, false);
return newBM;
}
/*
* 质量压缩法:将图片文件压缩,压缩是耗时操作
*/
public static void compressBitmapToFile(CompressFileBean compressFileBean, CompressFileCallback compressFileCallback) {
new CompressFileThread(compressFileBean, compressFileCallback).start();
}
/**
* drawable raw目录均可以
*直接使用BitmapFactory.decodeResource btimap 会被根据屏幕密度进行压缩,真是麻雀啄了牛屁股
* @param context
* @param resId
* @return
*/
public static Bitmap decodeResourceOrigin(Context context, int resId) {
BitmapFactory.Options options = new BitmapFactory.Options();
TypedValue value = new TypedValue();
context.getResources().openRawResource(resId, value);
options.inTargetDensity = value.density;
options.inScaled = false;//不缩放
return BitmapFactory.decodeResource(context.getResources(), resId, options);
}
/**
* drawable raw目录均可以
*
* @param context
* @return
*/
public static Bitmap decodeResource(Context context, int id, int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;//如此,无法decode bitmap
BitmapFactory.decodeResource(context.getResources(), id, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;//如此,方可decode bitmap
return BitmapFactory.decodeResource(context.getResources(), id, options);
}
// public static Bitmap decodeBitmapFromRaw(Context context, @RawRes int id) {
// return BitmapFactory.decodeStream(context.getResources().openRawResource(id));
// }
/**
* drawable raw目录均可以
*
* @param context
* @return
*/
public static Bitmap decodeResource(Context context, int id, int reqWidthxreqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;//如此,无法decode bitmap
BitmapFactory.decodeResource(context.getResources(), id, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidthxreqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;//如此,方可decode bitmap
return BitmapFactory.decodeResource(context.getResources(), id, options);
}
public static Bitmap decodeByteArray(byte[] bytes, int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;//如此,无法decode bitmap
BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;//如此,方可decode bitmap
return BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
}
/*
* 由file转bitmap
*/
public static Bitmap decodeBitmapFromFilePath(String path, int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;//如此,无法decode bitmap
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;//如此,方可decode bitmap
return BitmapFactory.decodeFile(path, options);
}
/*
* 由file转bitmap,3000*3000像素的bitmap argb_8888 占用内存34.3MB
* 4000*4000像素的bitmap argb_8888 占用内存61MB
* 5000*5000像素的bitmap argb_8888 占用内存95MB
*/
public static Bitmap decodeBitmapFromFilePath3000(String path) {
// First decode with inJustDecodeBounds=true to check dimensions
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;//如此,无法decode bitmap
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, 9000000);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;//如此,方可decode bitmap
return BitmapFactory.decodeFile(path, options);
}
public static Bitmap decodeBitmapFromFilePathWxH(String path, int reqWidthxreqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;//如此,无法decode bitmap
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidthxreqHeight);
LogUtils.log("inSampleSize", options.inSampleSize);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;//如此,方可decode bitmap
return BitmapFactory.decodeFile(path, options);
}
public static int getInSampleSize(int width_pic, int height_pic, int reqWidthxreqHeight) {
//最小为1,像素不能超过3000*3000,不能低于100*100, insimplesize >1则2, >2则3
return (int) Math.max(1, Math.ceil(Math.sqrt(width_pic * height_pic * 1f / reqWidthxreqHeight)));
}
/*
* 由file转bitmap
*/
public static Bitmap decodeBitmapFromFilePath(String path, int inSampleSize) {
// First decode with inJustDecodeBounds=true to check dimensions
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;//如此,无法decode bitmap
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
options.inSampleSize = inSampleSize;
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;//如此,方可decode bitmap
return BitmapFactory.decodeFile(path, options);
}
public static int[] getBitmapWHFromFilePath(String path) {
// First decode with inJustDecodeBounds=true to check dimensions
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;//如此,无法decode bitmap
BitmapFactory.decodeFile(path, options);
return new int[]{options.outWidth, options.outHeight};
}
/**
* 通过canvas复制view的bitmap
*
* @param view
* @return
*/
public static Bitmap getBitmapFromView(View view) {
int width = view.getWidth();
int height = view.getHeight();
view.layout(0, 0, width, height);
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
/**
* Bitampa.Config_ARGB_8888,每个像素4个通道,每个通道8Bit,一个像素需要4个字节,
* 5000x5000像素的图片占用内存=5000x5000x8x4/1024/1024=762.94MB
*
* @param bitmap
* @param widthReq
* @param heightReq
* @return
*/
public static Bitmap compressBitmap(Bitmap bitmap, int widthReq, int heightReq) {
Matrix matrix = new Matrix();
float ratio_width = widthReq * 1f / bitmap.getWidth();
float ratio_height = heightReq * 1f / bitmap.getHeight();
float ratio = Math.min(ratio_width, ratio_height);
matrix.setScale(ratio, ratio);
final Bitmap bitmap_result = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
return bitmap_result;
}
private static class CompressFileThread extends Thread {
private Handler handler_deliver = new Handler(Looper.getMainLooper());
private CompressFileBean compressFileBean;
private CompressFileCallback compressFileCallback;
private int quality = 100;
public CompressFileThread(CompressFileBean compressFileBean, CompressFileCallback compressFileCallback) {
this.compressFileBean = compressFileBean;
this.quality = compressFileBean.getQuality_first();
this.compressFileCallback = compressFileCallback;
}
@Override
public void run() {
super.run();
final Bitmap bitmapOrigin = compressFileBean.getBitmapOrigin();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//quality,压缩精度尽量不要低于50,否则影响清晰度,不支持压缩PNG
bitmapOrigin.compress(Bitmap.CompressFormat.JPEG, quality, byteArrayOutputStream);
// long size=byteArrayOutputStream.size();
while (byteArrayOutputStream.toByteArray().length / 1024 > compressFileBean.getKb_max() && quality > compressFileBean.getQuality_min()) {
// LogUtils.log("compress", byteArrayOutputStream.toByteArray().length / 1024);
// 循环判断如果压缩后图片是否大于kb_max kb,大于继续压缩,
byteArrayOutputStream.reset();
quality -= 10;
bitmapOrigin.compress(Bitmap.CompressFormat.JPEG, quality, byteArrayOutputStream);
}
try {
final File fileCompressed = createFile(compressFileBean.getPathCompressed());
FileOutputStream fileOutputStream = new FileOutputStream(fileCompressed);
fileOutputStream.write(byteArrayOutputStream.toByteArray());//写入目标文件
fileOutputStream.flush();
fileOutputStream.close();
byteArrayOutputStream.close();
if (fileCompressed != null && fileCompressed.length() > 0) {
final int[] wh = getBitmapWHFromFilePath(fileCompressed.getAbsolutePath());
runOnUiThread(new Runnable() {
@Override
public void run() {
//压缩成功
compressFileCallback.onCompressFileFinished(fileCompressed, wh[0], wh[1]);
}
});
}
} catch (final Exception e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
@Override
public void run() {
//压缩失败
compressFileCallback.onCompressFileFailed("压缩图片文件失败" + e.getMessage());
}
});
}
}
private void runOnUiThread(Runnable run) {
handler_deliver.post(run);
}
}
public static class CompressFileBean {
// private String pathSource;//原图文件路径
private String pathCompressed;//压缩后的图片文件路径
private int kb_max = 1;//压缩到多少KB,不能精确,只能<=kb_max
private int quality_min = 10;//压缩精度,尽量>=50
private int quality_first = 90;
private Bitmap bitmapOrigin;
public int getQuality_first() {
return quality_first;
}
public CompressFileBean setQuality_first(int quality_first) {
this.quality_first = quality_first;
return this;
}
public String getPathCompressed() {
return pathCompressed;
}
public CompressFileBean setPathCompressed(String pathCompressed) {
this.pathCompressed = pathCompressed;
return this;
}
public int getKb_max() {
return kb_max;
}
public CompressFileBean setKb_max(int kb_max) {
this.kb_max = kb_max;
return this;
}
public int getQuality_min() {
return quality_min;
}
public CompressFileBean setQuality_min(int quality_min) {
this.quality_min = quality_min;
return this;
}
public Bitmap getBitmapOrigin() {
return bitmapOrigin;
}
public CompressFileBean setBitmapOrigin(Bitmap bitmapOrigin) {
this.bitmapOrigin = bitmapOrigin;
return this;
}
}
public static interface CompressFileCallback {
//图片压缩成功
public void onCompressFileFinished(File file, int width, int height);
//图片压缩失败
public void onCompressFileFailed(String errorMsg);
}
}
| AnJiaoDe/AndroidView | androidview/src/main/java/com/cy/androidview/BitmapUtils.java | 6,902 | //压缩失败 | line_comment | zh-cn | package com.cy.androidview;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.os.Handler;
import android.os.Looper;
import android.util.TypedValue;
import android.view.View;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by lenovo on 2017/12/24.
*/
public class BitmapUtils {
/**
* 选择变换
*
* @param origin 原图
* @param orientationDegree 旋转角度,可正可负
* @return 旋转后的图片
*/
public static Bitmap bitmapRotate(Bitmap origin, float orientationDegree) {
if (origin == null) {
return null;
}
int width = origin.getWidth();
int height = origin.getHeight();
Matrix matrix = new Matrix();
matrix.setRotate(orientationDegree);
// 围绕原地进行旋转
Bitmap newBM = Bitmap.createBitmap(origin, 0, 0, width, height, matrix, false);
return newBM;
}
/**
* @param source
* @param degree 比如90度,是顺时针旋转90度,-90度是逆时针旋转90度
* @param flipHorizontal 是否左右镜像
* @return
*/
public static Bitmap bitmapRotate(Bitmap source, int degree, boolean flipHorizontal) {
if (degree == 0 && !flipHorizontal) {
return source;
}
Matrix matrix = new Matrix();
matrix.postRotate(degree);
if (flipHorizontal)
matrix.postScale(-1, 1);
return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, false);
}
/**
* 从底层返回的数据拿到对应的图片的角度,有些手机hal层会对手机拍出来的照片作相应的旋转,有些手机不会(比如三星手机)
* //有些奇葩垃圾手机拍出来会被旋转,如小米奇葩垃圾手机 cc9,
* //手机屏幕正上方指向正上方,图片逆时针旋转了90度,getHardwareOrientation 得到90度,
* 手机屏幕正上方指向正左方,图片没有被旋转,getHardwareOrientation得到0度
*
* @return
*/
public static int getPicDegree(InputStream inputStream) {
int degree = 0;
try {
ExifInterface exifInterface = new ExifInterface(inputStream);
int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
degree = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
degree = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
degree = 270;
break;
}
// exifInterface.setAttribute(ExifInterface.TAG_ORIENTATION, "no");
// exifInterface.saveAttributes();
} catch (IOException e) {
e.printStackTrace();
LogUtils.log("getPicDegree", e.getMessage());
}
LogUtils.log("getPicDegree", degree);
return degree;
}
/**
* 从底层返回的数据拿到对应的图片的角度,有些手机hal层会对手机拍出来的照片作相应的旋转,有些手机不会(比如三星手机)
* //有些奇葩垃圾手机拍出来会被旋转,如小米奇葩垃圾手机 cc9,
* //手机屏幕正上方指向正上方,图片逆时针旋转了90度,getHardwareOrientation 得到90度,
* 手机屏幕正上方指向正左方,图片没有被旋转,getHardwareOrientation得到0度
*
* @return
*/
// public static int getHardwareOrientation(byte[] jpeg) {
// if (jpeg == null) {
// return 0;
// }
//
// int offset = 0;
// int length = 0;
//
// // ISO/IEC 10918-1:1993(E)
// while (offset + 3 < jpeg.length && (jpeg[offset++] & 0xFF) == 0xFF) {
// int marker = jpeg[offset] & 0xFF;
//
// // Check if the marker is a padding.
// if (marker == 0xFF) {
// continue;
// }
// offset++;
//
// // Check if the marker is SOI or TEM.
// if (marker == 0xD8 || marker == 0x01) {
// continue;
// }
// // Check if the marker is EOI or SOS.
// if (marker == 0xD9 || marker == 0xDA) {
// break;
// }
//
// // Get the length and check if it is reasonable.
// length = pack(jpeg, offset, 2, false);
// if (length < 2 || offset + length > jpeg.length) {
//// KSLog.e(TAG, "Invalid length");
// return 0;
// }
//
// // Break if the marker is EXIF in APP1.
// if (marker == 0xE1 && length >= 8 &&
// pack(jpeg, offset + 2, 4, false) == 0x45786966 &&
// pack(jpeg, offset + 6, 2, false) == 0) {
// offset += 8;
// length -= 8;
// break;
// }
//
// // Skip other markers.
// offset += length;
// length = 0;
// }
//
// // JEITA CP-3451 Exif Version 2.2
// if (length > 8) {
// // Identify the byte order.
// int tag = pack(jpeg, offset, 4, false);
// if (tag != 0x49492A00 && tag != 0x4D4D002A) {
//// KSLog.e(TAG, "Invalid byte order");
// return 0;
// }
// boolean littleEndian = (tag == 0x49492A00);
//
// // Get the offset and check if it is reasonable.
// int count = pack(jpeg, offset + 4, 4, littleEndian) + 2;
// if (count < 10 || count > length) {
//// KSLog.e(TAG, "Invalid offset");
// return 0;
// }
// offset += count;
// length -= count;
//
// // Get the count and go through all the elements.
// count = pack(jpeg, offset - 2, 2, littleEndian);
// while (count-- > 0 && length >= 12) {
// // Get the tag and check if it is orientation.
// tag = pack(jpeg, offset, 2, littleEndian);
// if (tag == 0x0112) {
// // We do not really care about type and count, do we?
// int orientation = pack(jpeg, offset + 8, 2, littleEndian);
// switch (orientation) {
// case 1:
// return 0;
// case 3:
// return 180;
// case 6:
// return 90;
// case 8:
// return 270;
// }
//// KSLog.i(TAG, "Unsupported orientation");
// return 0;
// }
// offset += 12;
// length -= 12;
// }
// }
// return 0;
// }
//
// private static int pack(byte[] bytes, int offset, int length,
// boolean littleEndian) {
// int step = 1;
// if (littleEndian) {
// offset += length - 1;
// step = -1;
// }
//
// int value = 0;
// while (length-- > 0) {
// value = (value << 8) | (bytes[offset] & 0xFF);
// offset += step;
// }
// return value;
// }
public static String getSuffix(String filePath) {
String suffix = "";
try {
suffix = filePath.substring(filePath.lastIndexOf(".") + 1, filePath.length());
} catch (Exception e) {
}
return suffix;
}
/**
* @param bitmap
* @return
*/
// public static boolean saveBitmapToFile(Bitmap bitmap, File file) {
// return saveBitmapToFile(bitmap, file, 100);
// }
/**
* @param bitmap
* @return
*/
public static boolean saveBitmapToFile(Bitmap bitmap, File file, int quality) {
try {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
if (file.getAbsolutePath().endsWith(".png")) {
//PNG不支持压缩
bitmap.compress(Bitmap.CompressFormat.PNG, quality, bos);
} else {
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, bos);
}
bos.flush();
bos.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
// public static boolean saveBitmapToPngFile(Bitmap bitmap, String path) {
// return saveBitmapToPngFile(bitmap,createFile(path));
// }
// public static boolean saveBitmapToPngFile(Bitmap bitmap, File file) {
// try {
// BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
// //写60页不会压缩,因为PNG不支持压缩
// bitmap.compress(Bitmap.CompressFormat.PNG,100,bos);
// bos.flush();
// bos.close();
// } catch (IOException e) {
// e.printStackTrace();
// return false;
// }
// return true;
// }
/**
* 根据路径 创建文件
*
* @param pathFile
* @return
* @throws Exception 用Exception 防止其他异常
*/
public static File createFile(String pathFile) {
File file = null;
try {
File fileDir = new File(pathFile.substring(0, pathFile.lastIndexOf(File.separator)));
file = new File(pathFile);
if (!fileDir.exists()) fileDir.mkdirs();
if (!file.exists()) file.createNewFile();
} catch (Exception e) {
}
return file;
}
// /**
// * 不压缩,传入压缩过的bitampa
// *
// * @param bitmap
// * @return
// */
// public static boolean saveBitmapToFile(Bitmap bitmap, String path) {
// File file = null;
// try {
// file = createFile(path);
// } catch (IOException e) {
// e.printStackTrace();
// return false;
// }
// return saveBitmapToFile(bitmap, file, 100);
// }
/**
* 压缩,
*
* @param bitmap
* @return
*/
public static boolean saveBitmapToFile(Bitmap bitmap, String path, int quality) {
return saveBitmapToFile(bitmap, createFile(path), quality);
}
public static boolean saveBitmapToFile_90(Bitmap bitmap, String path) {
return saveBitmapToFile(bitmap, createFile(path), 90);
}
/**
* 不压缩
*
* @return
*/
public static boolean saveBytesToFile(byte[] bytes, String path) {
File file = createFile(path);
if (file == null) return false;
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(bytes);
fileOutputStream.flush();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return true;
}
// /*
// * 由file转bitmap,压缩
// */
//
// public static Bitmap decodeBitmapFromStream(InputStream inputStream, long contentLength, int widthReq, int heightReq) {
//
// // First decode with inJustDecodeBounds=true to check dimensions
// BitmapFactory.Options options = new BitmapFactory.Options();
// // Calculate inSampleSize
// //不让图片文件>500kb,不一定精准
// float ratio = contentLength * 1f / 1024 / 500;
// if (ratio >= 1) {
// options.inSampleSize = (int) Math.round(ratio + 1.5);
// } else {
// options.inSampleSize = 2;
// }
// Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, options);
// if (bitmap == null) return null;
// return compressBitmap(bitmap, widthReq, heightReq);
// }
/*
* 计算采样率
*/
// public static int calculateInSampleSize(BitmapFactory.Options options,
// int reqWidth, int reqHeight) {
// // Raw height and width of image
// final int height = options.outHeight;
// final int width = options.outWidth;
// int inSampleSize = 1;
//
// if (height > reqHeight || width > reqWidth) {
//
// final int halfHeight = height / 2;
// final int halfWidth = width / 2;
// while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) {
// inSampleSize *= 2;
// }
// }
//
// return inSampleSize;
// }
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
final int width = options.outWidth;
final int height = options.outHeight;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
//使用需要的宽高的最大值来计算比率
final int suitedValue = reqHeight > reqWidth ? reqHeight : reqWidth;
final int heightRatio = Math.round((float) height / (float) suitedValue);
final int widthRatio = Math.round((float) width / (float) suitedValue);
inSampleSize = heightRatio > widthRatio ? heightRatio : widthRatio;//用最大
}
return inSampleSize;
}
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidthxreqHeight) {
return getInSampleSize(options.outWidth, options.outHeight, reqWidthxreqHeight);
}
/**
* 裁剪
*
* @param bitmap 原图
* @return 裁剪后的图像
*/
public static Bitmap cropBitmap(Bitmap bitmap, float hRatioW) {
int w = bitmap.getWidth(); // 得到图片的宽,高
int h = bitmap.getHeight();
return Bitmap.createBitmap(bitmap, 0, 0, w, (int) (w * hRatioW), null, false);
}
/**
* 按比例缩放图片
*
* @param origin 原图
* @param ratio 比例
* @return 新的bitmap
*/
public static Bitmap scaleBitmap(Bitmap origin, float ratio) {
int width = origin.getWidth();
int height = origin.getHeight();
Matrix matrix = new Matrix();
matrix.preScale(ratio, ratio);
Bitmap newBM = Bitmap.createBitmap(origin, 0, 0, width, height, matrix, false);
return newBM;
}
/*
* 质量压缩法:将图片文件压缩,压缩是耗时操作
*/
public static void compressBitmapToFile(CompressFileBean compressFileBean, CompressFileCallback compressFileCallback) {
new CompressFileThread(compressFileBean, compressFileCallback).start();
}
/**
* drawable raw目录均可以
*直接使用BitmapFactory.decodeResource btimap 会被根据屏幕密度进行压缩,真是麻雀啄了牛屁股
* @param context
* @param resId
* @return
*/
public static Bitmap decodeResourceOrigin(Context context, int resId) {
BitmapFactory.Options options = new BitmapFactory.Options();
TypedValue value = new TypedValue();
context.getResources().openRawResource(resId, value);
options.inTargetDensity = value.density;
options.inScaled = false;//不缩放
return BitmapFactory.decodeResource(context.getResources(), resId, options);
}
/**
* drawable raw目录均可以
*
* @param context
* @return
*/
public static Bitmap decodeResource(Context context, int id, int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;//如此,无法decode bitmap
BitmapFactory.decodeResource(context.getResources(), id, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;//如此,方可decode bitmap
return BitmapFactory.decodeResource(context.getResources(), id, options);
}
// public static Bitmap decodeBitmapFromRaw(Context context, @RawRes int id) {
// return BitmapFactory.decodeStream(context.getResources().openRawResource(id));
// }
/**
* drawable raw目录均可以
*
* @param context
* @return
*/
public static Bitmap decodeResource(Context context, int id, int reqWidthxreqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;//如此,无法decode bitmap
BitmapFactory.decodeResource(context.getResources(), id, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidthxreqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;//如此,方可decode bitmap
return BitmapFactory.decodeResource(context.getResources(), id, options);
}
public static Bitmap decodeByteArray(byte[] bytes, int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;//如此,无法decode bitmap
BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;//如此,方可decode bitmap
return BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
}
/*
* 由file转bitmap
*/
public static Bitmap decodeBitmapFromFilePath(String path, int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;//如此,无法decode bitmap
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;//如此,方可decode bitmap
return BitmapFactory.decodeFile(path, options);
}
/*
* 由file转bitmap,3000*3000像素的bitmap argb_8888 占用内存34.3MB
* 4000*4000像素的bitmap argb_8888 占用内存61MB
* 5000*5000像素的bitmap argb_8888 占用内存95MB
*/
public static Bitmap decodeBitmapFromFilePath3000(String path) {
// First decode with inJustDecodeBounds=true to check dimensions
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;//如此,无法decode bitmap
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, 9000000);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;//如此,方可decode bitmap
return BitmapFactory.decodeFile(path, options);
}
public static Bitmap decodeBitmapFromFilePathWxH(String path, int reqWidthxreqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;//如此,无法decode bitmap
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidthxreqHeight);
LogUtils.log("inSampleSize", options.inSampleSize);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;//如此,方可decode bitmap
return BitmapFactory.decodeFile(path, options);
}
public static int getInSampleSize(int width_pic, int height_pic, int reqWidthxreqHeight) {
//最小为1,像素不能超过3000*3000,不能低于100*100, insimplesize >1则2, >2则3
return (int) Math.max(1, Math.ceil(Math.sqrt(width_pic * height_pic * 1f / reqWidthxreqHeight)));
}
/*
* 由file转bitmap
*/
public static Bitmap decodeBitmapFromFilePath(String path, int inSampleSize) {
// First decode with inJustDecodeBounds=true to check dimensions
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;//如此,无法decode bitmap
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
options.inSampleSize = inSampleSize;
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;//如此,方可decode bitmap
return BitmapFactory.decodeFile(path, options);
}
public static int[] getBitmapWHFromFilePath(String path) {
// First decode with inJustDecodeBounds=true to check dimensions
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;//如此,无法decode bitmap
BitmapFactory.decodeFile(path, options);
return new int[]{options.outWidth, options.outHeight};
}
/**
* 通过canvas复制view的bitmap
*
* @param view
* @return
*/
public static Bitmap getBitmapFromView(View view) {
int width = view.getWidth();
int height = view.getHeight();
view.layout(0, 0, width, height);
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
/**
* Bitampa.Config_ARGB_8888,每个像素4个通道,每个通道8Bit,一个像素需要4个字节,
* 5000x5000像素的图片占用内存=5000x5000x8x4/1024/1024=762.94MB
*
* @param bitmap
* @param widthReq
* @param heightReq
* @return
*/
public static Bitmap compressBitmap(Bitmap bitmap, int widthReq, int heightReq) {
Matrix matrix = new Matrix();
float ratio_width = widthReq * 1f / bitmap.getWidth();
float ratio_height = heightReq * 1f / bitmap.getHeight();
float ratio = Math.min(ratio_width, ratio_height);
matrix.setScale(ratio, ratio);
final Bitmap bitmap_result = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
return bitmap_result;
}
private static class CompressFileThread extends Thread {
private Handler handler_deliver = new Handler(Looper.getMainLooper());
private CompressFileBean compressFileBean;
private CompressFileCallback compressFileCallback;
private int quality = 100;
public CompressFileThread(CompressFileBean compressFileBean, CompressFileCallback compressFileCallback) {
this.compressFileBean = compressFileBean;
this.quality = compressFileBean.getQuality_first();
this.compressFileCallback = compressFileCallback;
}
@Override
public void run() {
super.run();
final Bitmap bitmapOrigin = compressFileBean.getBitmapOrigin();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//quality,压缩精度尽量不要低于50,否则影响清晰度,不支持压缩PNG
bitmapOrigin.compress(Bitmap.CompressFormat.JPEG, quality, byteArrayOutputStream);
// long size=byteArrayOutputStream.size();
while (byteArrayOutputStream.toByteArray().length / 1024 > compressFileBean.getKb_max() && quality > compressFileBean.getQuality_min()) {
// LogUtils.log("compress", byteArrayOutputStream.toByteArray().length / 1024);
// 循环判断如果压缩后图片是否大于kb_max kb,大于继续压缩,
byteArrayOutputStream.reset();
quality -= 10;
bitmapOrigin.compress(Bitmap.CompressFormat.JPEG, quality, byteArrayOutputStream);
}
try {
final File fileCompressed = createFile(compressFileBean.getPathCompressed());
FileOutputStream fileOutputStream = new FileOutputStream(fileCompressed);
fileOutputStream.write(byteArrayOutputStream.toByteArray());//写入目标文件
fileOutputStream.flush();
fileOutputStream.close();
byteArrayOutputStream.close();
if (fileCompressed != null && fileCompressed.length() > 0) {
final int[] wh = getBitmapWHFromFilePath(fileCompressed.getAbsolutePath());
runOnUiThread(new Runnable() {
@Override
public void run() {
//压缩成功
compressFileCallback.onCompressFileFinished(fileCompressed, wh[0], wh[1]);
}
});
}
} catch (final Exception e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
@Override
public void run() {
//压缩 <SUF>
compressFileCallback.onCompressFileFailed("压缩图片文件失败" + e.getMessage());
}
});
}
}
private void runOnUiThread(Runnable run) {
handler_deliver.post(run);
}
}
public static class CompressFileBean {
// private String pathSource;//原图文件路径
private String pathCompressed;//压缩后的图片文件路径
private int kb_max = 1;//压缩到多少KB,不能精确,只能<=kb_max
private int quality_min = 10;//压缩精度,尽量>=50
private int quality_first = 90;
private Bitmap bitmapOrigin;
public int getQuality_first() {
return quality_first;
}
public CompressFileBean setQuality_first(int quality_first) {
this.quality_first = quality_first;
return this;
}
public String getPathCompressed() {
return pathCompressed;
}
public CompressFileBean setPathCompressed(String pathCompressed) {
this.pathCompressed = pathCompressed;
return this;
}
public int getKb_max() {
return kb_max;
}
public CompressFileBean setKb_max(int kb_max) {
this.kb_max = kb_max;
return this;
}
public int getQuality_min() {
return quality_min;
}
public CompressFileBean setQuality_min(int quality_min) {
this.quality_min = quality_min;
return this;
}
public Bitmap getBitmapOrigin() {
return bitmapOrigin;
}
public CompressFileBean setBitmapOrigin(Bitmap bitmapOrigin) {
this.bitmapOrigin = bitmapOrigin;
return this;
}
}
public static interface CompressFileCallback {
//图片压缩成功
public void onCompressFileFinished(File file, int width, int height);
//图片压缩失败
public void onCompressFileFailed(String errorMsg);
}
}
| false |
50986_2 | package com.cy.tablayoutsimple_;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;
import com.cy.tablayoutniubility.TabMediatorVp2;
import com.cy.tablayoutniubility.TabViewHolder;
import com.cy.tablayoutniubility.FragPageAdapterVp2;
import com.cy.tablayoutniubility.TabAdapter;
import com.cy.tablayoutniubility.TabLayoutScroll;
import java.util.ArrayList;
import java.util.List;
public class TabLayoutVP2Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab_layout_r_v);
ViewPager2 viewPager2 = findViewById(R.id.view_pager);
TabLayoutScroll tabLayoutLine = findViewById(R.id.tablayout);
// tabLayoutLine.setSpace_horizontal(dpAdapt(20)).setSpace_vertical(dpAdapt(8));
FragPageAdapterVp2<String> fragmentPageAdapter = new FragPageAdapterVp2<String>(this) {
@Override
public Fragment createFragment(String bean, int position) {
LogUtils.log("createFragmentpppppppppppp",position);
return FragmentTab2.newInstance(FragmentTab2.TAB_NAME2, getList_bean().get(position));
}
@Override
public void bindDataToTab(TabViewHolder holder, int position, String bean, boolean isSelected) {
TextView textView = holder.getView(R.id.tv);
if (isSelected) {
textView.setTextColor(0xffe45540);
textView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
} else {
textView.setTextColor(0xff444444);
textView.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
}
textView.setText(bean);
}
@Override
public int getTabLayoutID(int position, String bean) {
if (position == 0) {
return R.layout.item_tab_msg;
}
return R.layout.item_tab;
}
};
TabAdapter<String> tabAdapter = new TabMediatorVp2<String>(tabLayoutLine, viewPager2).setAdapter(fragmentPageAdapter);
List<String> list = new ArrayList<>();
list.add("关注");
list.add("推荐");
list.add("视频");
list.add("抗疫");
list.add("深圳");
list.add("热榜");
list.add("小视频");
list.add("软件");
list.add("探索");
list.add("在家上课");
list.add("手机");
list.add("动漫");
list.add("通信");
list.add("影视");
list.add("互联网");
list.add("设计");
list.add("家电");
list.add("平板");
list.add("网球");
list.add("军事");
list.add("羽毛球");
list.add("奢侈品");
list.add("美食");
list.add("瘦身");
list.add("幸福里");
list.add("棋牌");
list.add("奇闻");
list.add("艺术");
list.add("减肥");
list.add("电玩");
list.add("台球");
list.add("八卦");
list.add("酷玩");
list.add("彩票");
list.add("漫画");
fragmentPageAdapter.add(list);
tabAdapter.add(list);
}
/**
* --------------------------------------------------------------------------------
*/
public int dpAdapt(float dp) {
return dpAdapt(dp, 360);
}
public int dpAdapt(float dp, float widthDpBase) {
DisplayMetrics dm = getResources().getDisplayMetrics();
int heightPixels = dm.heightPixels;//高的像素
int widthPixels = dm.widthPixels;//宽的像素
float density = dm.density;//density=dpi/160,密度比
float heightDP = heightPixels / density;//高度的dp
float widthDP = widthPixels / density;//宽度的dp
float w = widthDP > heightDP ? heightDP : widthDP;
return (int) (dp * w / widthDpBase * density + 0.5f);
}
}
| AnJiaoDe/TabLayoutNiubility | app/src/main/java/com/cy/tablayoutsimple_/TabLayoutVP2Activity.java | 1,085 | //高的像素 | line_comment | zh-cn | package com.cy.tablayoutsimple_;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;
import com.cy.tablayoutniubility.TabMediatorVp2;
import com.cy.tablayoutniubility.TabViewHolder;
import com.cy.tablayoutniubility.FragPageAdapterVp2;
import com.cy.tablayoutniubility.TabAdapter;
import com.cy.tablayoutniubility.TabLayoutScroll;
import java.util.ArrayList;
import java.util.List;
public class TabLayoutVP2Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab_layout_r_v);
ViewPager2 viewPager2 = findViewById(R.id.view_pager);
TabLayoutScroll tabLayoutLine = findViewById(R.id.tablayout);
// tabLayoutLine.setSpace_horizontal(dpAdapt(20)).setSpace_vertical(dpAdapt(8));
FragPageAdapterVp2<String> fragmentPageAdapter = new FragPageAdapterVp2<String>(this) {
@Override
public Fragment createFragment(String bean, int position) {
LogUtils.log("createFragmentpppppppppppp",position);
return FragmentTab2.newInstance(FragmentTab2.TAB_NAME2, getList_bean().get(position));
}
@Override
public void bindDataToTab(TabViewHolder holder, int position, String bean, boolean isSelected) {
TextView textView = holder.getView(R.id.tv);
if (isSelected) {
textView.setTextColor(0xffe45540);
textView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
} else {
textView.setTextColor(0xff444444);
textView.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
}
textView.setText(bean);
}
@Override
public int getTabLayoutID(int position, String bean) {
if (position == 0) {
return R.layout.item_tab_msg;
}
return R.layout.item_tab;
}
};
TabAdapter<String> tabAdapter = new TabMediatorVp2<String>(tabLayoutLine, viewPager2).setAdapter(fragmentPageAdapter);
List<String> list = new ArrayList<>();
list.add("关注");
list.add("推荐");
list.add("视频");
list.add("抗疫");
list.add("深圳");
list.add("热榜");
list.add("小视频");
list.add("软件");
list.add("探索");
list.add("在家上课");
list.add("手机");
list.add("动漫");
list.add("通信");
list.add("影视");
list.add("互联网");
list.add("设计");
list.add("家电");
list.add("平板");
list.add("网球");
list.add("军事");
list.add("羽毛球");
list.add("奢侈品");
list.add("美食");
list.add("瘦身");
list.add("幸福里");
list.add("棋牌");
list.add("奇闻");
list.add("艺术");
list.add("减肥");
list.add("电玩");
list.add("台球");
list.add("八卦");
list.add("酷玩");
list.add("彩票");
list.add("漫画");
fragmentPageAdapter.add(list);
tabAdapter.add(list);
}
/**
* --------------------------------------------------------------------------------
*/
public int dpAdapt(float dp) {
return dpAdapt(dp, 360);
}
public int dpAdapt(float dp, float widthDpBase) {
DisplayMetrics dm = getResources().getDisplayMetrics();
int heightPixels = dm.heightPixels;//高的 <SUF>
int widthPixels = dm.widthPixels;//宽的像素
float density = dm.density;//density=dpi/160,密度比
float heightDP = heightPixels / density;//高度的dp
float widthDP = widthPixels / density;//宽度的dp
float w = widthDP > heightDP ? heightDP : widthDP;
return (int) (dp * w / widthDpBase * density + 0.5f);
}
}
| false |
64141_8 | package _2021_B2;
import java.io.*;
import java.util.*;
/*
* 有 n 台计算机,第 i 台计算机的运算能力为 vi。
有一系列的任务被指派到各个计算机上,第 i 个任务在 ai 时刻分配,指定
计算机编号为 bi ,耗时为 ci 且算力消耗为 di 。如果此任务成功分配,将立刻
开始运行,期间持续占用 bi 号计算机 di 的算力,持续 ci 秒。
对于每次任务分配,如果计算机剩余的运算能力不足则输出 −1,并取消这
次分配,否则输出分配完这个任务后这台计算机的剩余运算能力。
【输入格式】
输入的第一行包含两个整数 n, m,分别表示计算机数目和要分配的任务数。
第二行包含 n 个整数 v1, v2, · · · vn,分别表示每个计算机的运算能力。
接下来 m 行每行 4 个整数 ai, bi, ci, di,意义如上所述。数据保证 ai 严格递
增,即 ai < ai+1。
【输出格式】
输出 m 行,每行包含一个数,对应每次任务分配的结果。
【样例输入】
2 6
5 5
1 1 5 3
2 2 2 6
3 1 2 3
4 1 6 1
5 1 3 3
6 1 3 4
【样例输出】
2
-1
-1
1
-1
0
【样例说明】
时刻 1,第 1 个任务被分配到第 1 台计算机,耗时为 5 ,这个任务时刻 6
会结束,占用计算机 1 的算力 3。
时刻 2,第 2 个任务需要的算力不足,所以分配失败了。
时刻 3,第 1 个计算机仍然正在计算第 1 个任务,剩余算力不足 3,所以
失败。
时刻 4,第 1 个计算机仍然正在计算第 1 个任务,但剩余算力足够,分配
后剩余算力 1。
时刻 5,第 1 个计算机仍然正在计算第 1, 4 个任务,剩余算力不足 4,失
败。
时刻 6,第 1 个计算机仍然正在计算第 4 个任务,剩余算力足够,且恰好
用完。
【评测用例规模与约定】
对于 20% 的评测用例,n, m ≤ 200。
对于 40% 的评测用例,n, m ≤ 2000。
对于所有评测用例,1 ≤ n, m ≤ 200000,1 ≤ ai, ci, di, vi ≤ 109,1 ≤ bi ≤ n。
————————————————
版权声明:本文为CSDN博主「dem.o」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_45800978/article/details/116724283
*/
public class _09负载均衡 {
/*
* 直接模拟,用优先队列,也就是所谓的堆去存储一个个节点,这个节点存储着当前任务的结束时刻,
* 和恢复体力值,考虑到有多个计算机,应该要用优先队列数组进行存储。
再次强调Java中使用System.out.println速度过慢的问题,改用BufferedWriter,
打印的时候将输出内容转换为String类型即可。
————————————————
版权声明:本文为CSDN博主「可乐塞满冰」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/Mxeron/article/details/123021102
*/
static class node{
int reHour;
int health;
node(){};
node(int reHour, int health) {
this.reHour = reHour;
this.health = health;
}
static BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));
public static void main(String args[]) throws IOException {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int m = scan.nextInt();
// 运算能力
int[] com = new int[n + 1];
for (int i = 1; i <= n; i++) {
com[i] = scan.nextInt();
}
// 构建优先队列
Queue<node>[] pq = new PriorityQueue[n + 1];
for (int i = 0; i < n + 1; i++) {
pq[i] = new PriorityQueue<>(new Comparator<node>() {
@Override
// 按照恢复时间从小到大排序
public int compare(node o1, node o2) {
return o1.reHour - o2.reHour;
}
});
}
int a, b, c, d;
for (int i = 0; i < m; i++) {
// 第 i 个任务在 ai 时刻分配,指定计算机编号为 bi,耗时为 ci 且算力消耗为 di
// 如果此任务成功分配,将立刻开始运行,期间持续占用 bi 号计算机 di 的算力,持续 ci 秒
a = scan.nextInt();
b = scan.nextInt();
c = scan.nextInt();
d = scan.nextInt();
// 注意任务执行完,算力是可以恢复的
while (!pq[b].isEmpty()) {
node tmp = pq[b].peek();
if (tmp.reHour <= a) {
com[b] += tmp.health;
pq[b].poll();
} else {
break;
}
}
if (com[b] < d) {
log.write(-1 + "");
log.write("\n");
} else {
// 消耗计算机算力
com[b] -= d;
// 入队
pq[b].offer(new node(a + c, d));
log.write(com[b] + "");
log.write('\n');
}
}
log.flush();
}
}
}
| Anan121no/LanQiao- | src/_2021_B2/_09负载均衡.java | 1,556 | // 消耗计算机算力 | line_comment | zh-cn | package _2021_B2;
import java.io.*;
import java.util.*;
/*
* 有 n 台计算机,第 i 台计算机的运算能力为 vi。
有一系列的任务被指派到各个计算机上,第 i 个任务在 ai 时刻分配,指定
计算机编号为 bi ,耗时为 ci 且算力消耗为 di 。如果此任务成功分配,将立刻
开始运行,期间持续占用 bi 号计算机 di 的算力,持续 ci 秒。
对于每次任务分配,如果计算机剩余的运算能力不足则输出 −1,并取消这
次分配,否则输出分配完这个任务后这台计算机的剩余运算能力。
【输入格式】
输入的第一行包含两个整数 n, m,分别表示计算机数目和要分配的任务数。
第二行包含 n 个整数 v1, v2, · · · vn,分别表示每个计算机的运算能力。
接下来 m 行每行 4 个整数 ai, bi, ci, di,意义如上所述。数据保证 ai 严格递
增,即 ai < ai+1。
【输出格式】
输出 m 行,每行包含一个数,对应每次任务分配的结果。
【样例输入】
2 6
5 5
1 1 5 3
2 2 2 6
3 1 2 3
4 1 6 1
5 1 3 3
6 1 3 4
【样例输出】
2
-1
-1
1
-1
0
【样例说明】
时刻 1,第 1 个任务被分配到第 1 台计算机,耗时为 5 ,这个任务时刻 6
会结束,占用计算机 1 的算力 3。
时刻 2,第 2 个任务需要的算力不足,所以分配失败了。
时刻 3,第 1 个计算机仍然正在计算第 1 个任务,剩余算力不足 3,所以
失败。
时刻 4,第 1 个计算机仍然正在计算第 1 个任务,但剩余算力足够,分配
后剩余算力 1。
时刻 5,第 1 个计算机仍然正在计算第 1, 4 个任务,剩余算力不足 4,失
败。
时刻 6,第 1 个计算机仍然正在计算第 4 个任务,剩余算力足够,且恰好
用完。
【评测用例规模与约定】
对于 20% 的评测用例,n, m ≤ 200。
对于 40% 的评测用例,n, m ≤ 2000。
对于所有评测用例,1 ≤ n, m ≤ 200000,1 ≤ ai, ci, di, vi ≤ 109,1 ≤ bi ≤ n。
————————————————
版权声明:本文为CSDN博主「dem.o」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_45800978/article/details/116724283
*/
public class _09负载均衡 {
/*
* 直接模拟,用优先队列,也就是所谓的堆去存储一个个节点,这个节点存储着当前任务的结束时刻,
* 和恢复体力值,考虑到有多个计算机,应该要用优先队列数组进行存储。
再次强调Java中使用System.out.println速度过慢的问题,改用BufferedWriter,
打印的时候将输出内容转换为String类型即可。
————————————————
版权声明:本文为CSDN博主「可乐塞满冰」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/Mxeron/article/details/123021102
*/
static class node{
int reHour;
int health;
node(){};
node(int reHour, int health) {
this.reHour = reHour;
this.health = health;
}
static BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));
public static void main(String args[]) throws IOException {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int m = scan.nextInt();
// 运算能力
int[] com = new int[n + 1];
for (int i = 1; i <= n; i++) {
com[i] = scan.nextInt();
}
// 构建优先队列
Queue<node>[] pq = new PriorityQueue[n + 1];
for (int i = 0; i < n + 1; i++) {
pq[i] = new PriorityQueue<>(new Comparator<node>() {
@Override
// 按照恢复时间从小到大排序
public int compare(node o1, node o2) {
return o1.reHour - o2.reHour;
}
});
}
int a, b, c, d;
for (int i = 0; i < m; i++) {
// 第 i 个任务在 ai 时刻分配,指定计算机编号为 bi,耗时为 ci 且算力消耗为 di
// 如果此任务成功分配,将立刻开始运行,期间持续占用 bi 号计算机 di 的算力,持续 ci 秒
a = scan.nextInt();
b = scan.nextInt();
c = scan.nextInt();
d = scan.nextInt();
// 注意任务执行完,算力是可以恢复的
while (!pq[b].isEmpty()) {
node tmp = pq[b].peek();
if (tmp.reHour <= a) {
com[b] += tmp.health;
pq[b].poll();
} else {
break;
}
}
if (com[b] < d) {
log.write(-1 + "");
log.write("\n");
} else {
// 消耗 <SUF>
com[b] -= d;
// 入队
pq[b].offer(new node(a + c, d));
log.write(com[b] + "");
log.write('\n');
}
}
log.flush();
}
}
}
| false |
29847_6 | package io;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
public class SelectorExample {
public static void main(String[] args) throws Exception{
Selector selector = Selector.open();
ServerSocketChannel servChannel = ServerSocketChannel.open();
servChannel.configureBlocking(false);
// 建立一个server socket,到本地端口9999, backlog 1024
servChannel.socket().setReuseAddress(true);
servChannel.socket().bind(new InetSocketAddress(9999), 1024);
// selector 关心 server 上的 ACCEPT 事件
servChannel.register(selector, SelectionKey.OP_ACCEPT);
servChannel.register(selector, SelectionKey.OP_CONNECT, new SelectorExample());
boolean start = true;
while (start) {
try {
// 阻塞等待 直到有IO事件可读(系统IO事件队列不为空)
selector.select();
// 获取 事件 以及 事件所对应的 channel (client server 的连接)
Set<SelectionKey> selectedKeys = selector.selectedKeys();
Iterator<SelectionKey> it = selectedKeys.iterator();
SelectionKey key = null;
while (it.hasNext()) {
key = it.next();
it.remove();
try {
if (key.isValid()) {
// OP_ACCEPT 事件 表示有个新client 完成了三次握手。连接上了本服务器
if (key.isAcceptable()) {
// Accept the new connection
ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
SocketChannel sc = ssc.accept();
sc.configureBlocking(false);
// 将该连接的可读事件 注册到 selector, 到时候他发起请求的时候,我会收到新事件
sc.register(selector, SelectionKey.OP_READ);
}
// OP_READ 事件 说明 client 发的数据已经发到了系统缓冲区,server 可以去读了。
if (key.isReadable()) {
SocketChannel sc = (SocketChannel) key.channel();
// 分配用户台空间, 将数据从内核态 拷贝到 用户态
ByteBuffer readBuffer = ByteBuffer.allocate(4);
int readBytes = sc.read(readBuffer);
if (readBytes > 0) {
// 切换读写模式 详见下面的图, 表示自己目前可以读 [position, limit]
readBuffer.flip();
byte[] bytes = new byte[readBuffer.remaining()];
// 将buffer 数据拷贝到 bytes 数组
// 如果这里只收到一半的数据怎么办?
String body = new String(bytes, "UTF-8");
System.out.println(body);
// 将 read的数据 写回去
ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
writeBuffer.put(bytes);
writeBuffer.flip();
sc.write(writeBuffer);
} else if (readBytes < 0) {
// 对端链路关闭
key.cancel();
sc.close();
} else
;
}
}
} catch (Exception e) {
if (key != null) {
key.cancel();
if (key.channel() != null)
key.channel().close();
}
}
}
} catch (Exception e) {
throw e;
}
}
}
}
| AndiHappy/dayCode | src/main/java/io/SelectorExample.java | 853 | // 将该连接的可读事件 注册到 selector, 到时候他发起请求的时候,我会收到新事件 | line_comment | zh-cn | package io;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
public class SelectorExample {
public static void main(String[] args) throws Exception{
Selector selector = Selector.open();
ServerSocketChannel servChannel = ServerSocketChannel.open();
servChannel.configureBlocking(false);
// 建立一个server socket,到本地端口9999, backlog 1024
servChannel.socket().setReuseAddress(true);
servChannel.socket().bind(new InetSocketAddress(9999), 1024);
// selector 关心 server 上的 ACCEPT 事件
servChannel.register(selector, SelectionKey.OP_ACCEPT);
servChannel.register(selector, SelectionKey.OP_CONNECT, new SelectorExample());
boolean start = true;
while (start) {
try {
// 阻塞等待 直到有IO事件可读(系统IO事件队列不为空)
selector.select();
// 获取 事件 以及 事件所对应的 channel (client server 的连接)
Set<SelectionKey> selectedKeys = selector.selectedKeys();
Iterator<SelectionKey> it = selectedKeys.iterator();
SelectionKey key = null;
while (it.hasNext()) {
key = it.next();
it.remove();
try {
if (key.isValid()) {
// OP_ACCEPT 事件 表示有个新client 完成了三次握手。连接上了本服务器
if (key.isAcceptable()) {
// Accept the new connection
ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
SocketChannel sc = ssc.accept();
sc.configureBlocking(false);
// 将该 <SUF>
sc.register(selector, SelectionKey.OP_READ);
}
// OP_READ 事件 说明 client 发的数据已经发到了系统缓冲区,server 可以去读了。
if (key.isReadable()) {
SocketChannel sc = (SocketChannel) key.channel();
// 分配用户台空间, 将数据从内核态 拷贝到 用户态
ByteBuffer readBuffer = ByteBuffer.allocate(4);
int readBytes = sc.read(readBuffer);
if (readBytes > 0) {
// 切换读写模式 详见下面的图, 表示自己目前可以读 [position, limit]
readBuffer.flip();
byte[] bytes = new byte[readBuffer.remaining()];
// 将buffer 数据拷贝到 bytes 数组
// 如果这里只收到一半的数据怎么办?
String body = new String(bytes, "UTF-8");
System.out.println(body);
// 将 read的数据 写回去
ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
writeBuffer.put(bytes);
writeBuffer.flip();
sc.write(writeBuffer);
} else if (readBytes < 0) {
// 对端链路关闭
key.cancel();
sc.close();
} else
;
}
}
} catch (Exception e) {
if (key != null) {
key.cancel();
if (key.channel() != null)
key.channel().close();
}
}
}
} catch (Exception e) {
throw e;
}
}
}
}
| false |
54717_2 | /*
* Author: Andliage Pox
* Date: 2020-01-14
*/
package leetcode.solution;
public class Solution00122 {
public static void main(String[] args) {
int[] prices = {7, 1, 5, 3, 6, 4};
System.out.println(new Solution00122().maxProfit(prices));
}
public int maxProfit(int[] prices) {
/*
* 唯一的问题是最好的买法是什么?
* 这个问题,在金钱的诱惑下,很好看出来
* 谷买峰卖,那么问题就来到了如何找波峰波谷这边
*/
int i = 0, top, valley, profit = 0;
while (i + 1 < prices.length) {
while (i + 1 < prices.length && prices[i + 1] <= prices[i]) {
i++;
}
valley = prices[i];
while (i + 1 < prices.length && prices[i + 1] >= prices[i]) {
i++;
}
top = prices[i];
profit += top - valley;
}
return profit;
/*
* 总之,没有问题,复杂度时间O(n)空间O(1)
*/
}
}
| AndliagePox/ap | src/leetcode/solution/Solution00122.java | 325 | /*
* 总之,没有问题,复杂度时间O(n)空间O(1)
*/ | block_comment | zh-cn | /*
* Author: Andliage Pox
* Date: 2020-01-14
*/
package leetcode.solution;
public class Solution00122 {
public static void main(String[] args) {
int[] prices = {7, 1, 5, 3, 6, 4};
System.out.println(new Solution00122().maxProfit(prices));
}
public int maxProfit(int[] prices) {
/*
* 唯一的问题是最好的买法是什么?
* 这个问题,在金钱的诱惑下,很好看出来
* 谷买峰卖,那么问题就来到了如何找波峰波谷这边
*/
int i = 0, top, valley, profit = 0;
while (i + 1 < prices.length) {
while (i + 1 < prices.length && prices[i + 1] <= prices[i]) {
i++;
}
valley = prices[i];
while (i + 1 < prices.length && prices[i + 1] >= prices[i]) {
i++;
}
top = prices[i];
profit += top - valley;
}
return profit;
/*
* 总之, <SUF>*/
}
}
| true |
60187_18 | package com.andrewtse.testdemo.activity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.andrewtse.testdemo.R;
import com.andrewtse.testdemo.sound.media.MusicPlayer;
import com.andrewtse.testdemo.sound.media.NetMusicPlayer;
import com.andrewtse.testdemo.sound.widget.AlphaImageView;
import com.andrewtse.testdemo.sound.widget.ProgressView;
public class MediaPlayerActivity extends AppCompatActivity {
@BindView(R.id.id_pv_pre)
public ProgressView mProgressView;
@BindView(R.id.id_iv_ctrl)
public ImageView mIvCtrl;
@BindView(R.id.id_iv_next)
public AlphaImageView mIvNext;
@BindView(R.id.id_iv_pre_list)
public AlphaImageView mIvPreList;
@BindView(R.id.id_tv_music_name)
public TextView mTvMusicName;
@BindView(R.id.id_tv_singer)
public TextView mTvSignerName;
private MusicPlayer mLocalMusicPlayer;
private NetMusicPlayer mNetMusicPlayer;
private final String mFilePath = "/sdcard/Music/";
private final String mFileUri = "http://172.18.67.240:8080/test_music.mp3";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_media_player);
ButterKnife.bind(this);
//本地音乐播放--start
// mLocalMusicPlayer = new MusicPlayer();
//
// mLocalMusicPlayer.setOnSeekListener(per_100 -> mProgressView.setProgress(per_100));
// mLocalMusicPlayer.setOnBufferListener(per_100 -> mProgressView.setProgress2(per_100));
// mProgressView.setOnDragListener(per_100 -> mLocalMusicPlayer.seekTo(per_100));
//
// mIvCtrl.setOnClickListener(v -> {
// if (mLocalMusicPlayer.isPlaying()) {
// mLocalMusicPlayer.pause();
// mIvCtrl.setImageResource(R.drawable.icon_stop_2);//设置图标暂停
// } else {
// mLocalMusicPlayer.start(mFilePath + "向天再借五百年 - 韩磊.mp3");
// mIvCtrl.setImageResource(R.drawable.icon_start_2);//设置图标播放
// }
// });
// mTvMusicName.setText("向天再借五百年");
// mTvSignerName.setText("韩磊");
//end
//网络音乐播放--start
mNetMusicPlayer = new NetMusicPlayer(this);
mNetMusicPlayer.setOnSeekListener(per_100 -> mProgressView.setProgress(per_100));
mNetMusicPlayer.setOnBufferListener(per_100 -> mProgressView.setProgress2(per_100));
mProgressView.setOnDragListener(per_100 -> mNetMusicPlayer.seekTo(per_100));
mIvCtrl.setOnClickListener(v -> {
if (mNetMusicPlayer.isPlaying()) {
mNetMusicPlayer.pause();
mIvCtrl.setImageResource(R.drawable.icon_stop_2);//设置图标暂停
} else {
mNetMusicPlayer.start(mFileUri);
mIvCtrl.setImageResource(R.drawable.icon_start_2);//设置图标播放
}
});
mTvMusicName.setText("勇气");
mTvSignerName.setText("梁静茹");
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mLocalMusicPlayer != null) {
mLocalMusicPlayer.onDestroy();
}
if (mNetMusicPlayer != null) {
mNetMusicPlayer.onDestroy();
}
}
}
| AndrewTseZhou/AndroidDayDayUp | app/src/main/java/com/andrewtse/testdemo/activity/MediaPlayerActivity.java | 991 | //设置图标暂停 | line_comment | zh-cn | package com.andrewtse.testdemo.activity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.andrewtse.testdemo.R;
import com.andrewtse.testdemo.sound.media.MusicPlayer;
import com.andrewtse.testdemo.sound.media.NetMusicPlayer;
import com.andrewtse.testdemo.sound.widget.AlphaImageView;
import com.andrewtse.testdemo.sound.widget.ProgressView;
public class MediaPlayerActivity extends AppCompatActivity {
@BindView(R.id.id_pv_pre)
public ProgressView mProgressView;
@BindView(R.id.id_iv_ctrl)
public ImageView mIvCtrl;
@BindView(R.id.id_iv_next)
public AlphaImageView mIvNext;
@BindView(R.id.id_iv_pre_list)
public AlphaImageView mIvPreList;
@BindView(R.id.id_tv_music_name)
public TextView mTvMusicName;
@BindView(R.id.id_tv_singer)
public TextView mTvSignerName;
private MusicPlayer mLocalMusicPlayer;
private NetMusicPlayer mNetMusicPlayer;
private final String mFilePath = "/sdcard/Music/";
private final String mFileUri = "http://172.18.67.240:8080/test_music.mp3";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_media_player);
ButterKnife.bind(this);
//本地音乐播放--start
// mLocalMusicPlayer = new MusicPlayer();
//
// mLocalMusicPlayer.setOnSeekListener(per_100 -> mProgressView.setProgress(per_100));
// mLocalMusicPlayer.setOnBufferListener(per_100 -> mProgressView.setProgress2(per_100));
// mProgressView.setOnDragListener(per_100 -> mLocalMusicPlayer.seekTo(per_100));
//
// mIvCtrl.setOnClickListener(v -> {
// if (mLocalMusicPlayer.isPlaying()) {
// mLocalMusicPlayer.pause();
// mIvCtrl.setImageResource(R.drawable.icon_stop_2);//设置图标暂停
// } else {
// mLocalMusicPlayer.start(mFilePath + "向天再借五百年 - 韩磊.mp3");
// mIvCtrl.setImageResource(R.drawable.icon_start_2);//设置图标播放
// }
// });
// mTvMusicName.setText("向天再借五百年");
// mTvSignerName.setText("韩磊");
//end
//网络音乐播放--start
mNetMusicPlayer = new NetMusicPlayer(this);
mNetMusicPlayer.setOnSeekListener(per_100 -> mProgressView.setProgress(per_100));
mNetMusicPlayer.setOnBufferListener(per_100 -> mProgressView.setProgress2(per_100));
mProgressView.setOnDragListener(per_100 -> mNetMusicPlayer.seekTo(per_100));
mIvCtrl.setOnClickListener(v -> {
if (mNetMusicPlayer.isPlaying()) {
mNetMusicPlayer.pause();
mIvCtrl.setImageResource(R.drawable.icon_stop_2);//设置 <SUF>
} else {
mNetMusicPlayer.start(mFileUri);
mIvCtrl.setImageResource(R.drawable.icon_start_2);//设置图标播放
}
});
mTvMusicName.setText("勇气");
mTvSignerName.setText("梁静茹");
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mLocalMusicPlayer != null) {
mLocalMusicPlayer.onDestroy();
}
if (mNetMusicPlayer != null) {
mNetMusicPlayer.onDestroy();
}
}
}
| false |
39092_2 | package com.le.net_thread;
import com.le.utils.MLog;
import com.le.utils.UtilString;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import static android.R.attr.name;
/**
* Created by sahara on 2016/4/27.
*/
public class UploadFile {
// 定义数据分割线
private static String BOUNDARY = "------------------------7dc2fd5c0894";
// 定义最后数据分割线
private static byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
public void makeRequest(File file, final String url, MyCallBack callBack){
HttpURLConnection conn = null;
String result = "";
try {
URL url1 = new URL(url);
MLog.e("当前上传图片接口:"+url);
conn = (HttpURLConnection) url1.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
// conn.setRequestProperty("Cookie", BaseConfig.COOKIE);
BufferedOutputStream bos = new BufferedOutputStream(conn.getOutputStream());
StringBuilder sb = new StringBuilder();
sb.append("--");
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data; name=\""+name+"\";filename=\"" + file.getName() + "\"\r\n");
// 這裏不能漏掉,根據文件類型來來做處理,由於上傳的是圖片,所以這裏可以寫成image/pjpeg
String type = "";
switch (UtilString.getLast(file.getName(), ".")+"") {
case "png":
type = "Content-Type: image/png\r\n\r\n";
break;
case "jpg":
type = "Content-Type: image/jpeg\r\n\r\n";
break;
case "txt":
type = "Content-Type: text/plain\r\n\r\n";
break;
default:
type = "Content-Type: application/octet-stream\r\n\r\n";
break;
}
sb.append(type);//text/plain
//application/octet-stream
//image/png
//image/jpeg
bos.write(sb.toString().getBytes());
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
byte[] byteArray=new byte[1024];
int tmp=0;
int current = 0;
int total = bis.available();
while ((tmp = bis.read(byteArray))!=-1) {
current = current+tmp;
bos.write(byteArray, 0, tmp);
callBack.inProgress(current,total,file.getName());
}
// bos.write("\r\n".getBytes());
bos.write(end_data);
bis.close();
bos.flush();
bos.close();
// conn.connect();
//上传完成后,开始读取返回内容
if (conn.getResponseCode()>=300){
InputStream errorStream = conn.getErrorStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(errorStream, "UTF8"));
String errorStr = "";
while(true) {
String line = rd.readLine();
if(line != null) {
errorStr += line + "\n";
} else {
callBack.error(new Exception(errorStr),file.getName());
break;
}
}
return;
}
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
while ((line = br.readLine())!=null) {
result = result+line+"\n";
}
callBack.finish(result);
} catch (Exception e) {
callBack.error(e,file.getName());
}
}
}
| Android-xiaole/LeeDemo | public_jar/src/main/java/com/le/net_thread/UploadFile.java | 1,000 | // 定义最后数据分割线 | line_comment | zh-cn | package com.le.net_thread;
import com.le.utils.MLog;
import com.le.utils.UtilString;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import static android.R.attr.name;
/**
* Created by sahara on 2016/4/27.
*/
public class UploadFile {
// 定义数据分割线
private static String BOUNDARY = "------------------------7dc2fd5c0894";
// 定义 <SUF>
private static byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
public void makeRequest(File file, final String url, MyCallBack callBack){
HttpURLConnection conn = null;
String result = "";
try {
URL url1 = new URL(url);
MLog.e("当前上传图片接口:"+url);
conn = (HttpURLConnection) url1.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
// conn.setRequestProperty("Cookie", BaseConfig.COOKIE);
BufferedOutputStream bos = new BufferedOutputStream(conn.getOutputStream());
StringBuilder sb = new StringBuilder();
sb.append("--");
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data; name=\""+name+"\";filename=\"" + file.getName() + "\"\r\n");
// 這裏不能漏掉,根據文件類型來來做處理,由於上傳的是圖片,所以這裏可以寫成image/pjpeg
String type = "";
switch (UtilString.getLast(file.getName(), ".")+"") {
case "png":
type = "Content-Type: image/png\r\n\r\n";
break;
case "jpg":
type = "Content-Type: image/jpeg\r\n\r\n";
break;
case "txt":
type = "Content-Type: text/plain\r\n\r\n";
break;
default:
type = "Content-Type: application/octet-stream\r\n\r\n";
break;
}
sb.append(type);//text/plain
//application/octet-stream
//image/png
//image/jpeg
bos.write(sb.toString().getBytes());
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
byte[] byteArray=new byte[1024];
int tmp=0;
int current = 0;
int total = bis.available();
while ((tmp = bis.read(byteArray))!=-1) {
current = current+tmp;
bos.write(byteArray, 0, tmp);
callBack.inProgress(current,total,file.getName());
}
// bos.write("\r\n".getBytes());
bos.write(end_data);
bis.close();
bos.flush();
bos.close();
// conn.connect();
//上传完成后,开始读取返回内容
if (conn.getResponseCode()>=300){
InputStream errorStream = conn.getErrorStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(errorStream, "UTF8"));
String errorStr = "";
while(true) {
String line = rd.readLine();
if(line != null) {
errorStr += line + "\n";
} else {
callBack.error(new Exception(errorStr),file.getName());
break;
}
}
return;
}
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
while ((line = br.readLine())!=null) {
result = result+line+"\n";
}
callBack.finish(result);
} catch (Exception e) {
callBack.error(e,file.getName());
}
}
}
| false |
54052_2 | package com.songchao.mybilibili.model;
import com.songchao.mybilibili.R;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Author: SongCHao
* Date: 2017/9/30/10:35
* Email: 15704762346@163.com
*/
public class ImageCardUtil {
/**
* 获取具体图片类别
*/
public static List<ImageCard> getImageCardList(){
List<ImageCard> dataList = new ArrayList<>();
//获得系统当前时间
Date mDate = new Date();
SimpleDateFormat mFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
String date = mFormat.format(mDate);
final String MASHLADI = "玛莎拉蒂";
dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche01,date,R.mipmap.save,MASHLADI));
dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche02,date,R.mipmap.save,MASHLADI));
dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche03,date,R.mipmap.save,MASHLADI));
dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche04,date,R.mipmap.save,MASHLADI));
dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche05,date,R.mipmap.save,MASHLADI));
dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche01,date,R.mipmap.save,MASHLADI));
final String FANGHUA = "芳华电影";
dataList.add(new ImageCard("芳华",R.mipmap.fanghua01,date,R.mipmap.save,FANGHUA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua02,date,R.mipmap.save,FANGHUA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua03,date,R.mipmap.save,FANGHUA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua04,date,R.mipmap.save,FANGHUA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua05,date,R.mipmap.save,FANGHUA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua06,date,R.mipmap.save,FANGHUA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua07,date,R.mipmap.save,FANGHUA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua08,date,R.mipmap.save,FANGHUA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua09,date,R.mipmap.save,FANGHUA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua10,date,R.mipmap.save,FANGHUA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua11,date,R.mipmap.save,FANGHUA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua12,date,R.mipmap.save,FANGHUA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua13,date,R.mipmap.save,FANGHUA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua01,date,R.mipmap.save,FANGHUA));
final String MASHLADIDI = "贼帅的玛莎拉蒂";
dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche01,date,R.mipmap.save,MASHLADIDI));
dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche02,date,R.mipmap.save,MASHLADIDI));
dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche03,date,R.mipmap.save,MASHLADIDI));
dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche04,date,R.mipmap.save,MASHLADIDI));
dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche05,date,R.mipmap.save,MASHLADIDI));
dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche01,date,R.mipmap.save,MASHLADIDI));
final String FANGHUAHA = "芳华情怀";
dataList.add(new ImageCard("芳华",R.mipmap.fanghua01,date,R.mipmap.save,FANGHUAHA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua02,date,R.mipmap.save,FANGHUAHA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua03,date,R.mipmap.save,FANGHUAHA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua04,date,R.mipmap.save,FANGHUAHA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua05,date,R.mipmap.save,FANGHUAHA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua06,date,R.mipmap.save,FANGHUAHA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua07,date,R.mipmap.save,FANGHUAHA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua08,date,R.mipmap.save,FANGHUAHA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua09,date,R.mipmap.save,FANGHUAHA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua10,date,R.mipmap.save,FANGHUAHA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua11,date,R.mipmap.save,FANGHUAHA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua12,date,R.mipmap.save,FANGHUAHA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua13,date,R.mipmap.save,FANGHUAHA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua01,date,R.mipmap.save,FANGHUAHA));
final String MASHLADIDIDI = "我的玛莎拉蒂";
dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche01,date,R.mipmap.save,MASHLADIDIDI));
dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche02,date,R.mipmap.save,MASHLADIDIDI));
dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche03,date,R.mipmap.save,MASHLADIDIDI));
dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche04,date,R.mipmap.save,MASHLADIDIDI));
dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche05,date,R.mipmap.save,MASHLADIDIDI));
dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche01,date,R.mipmap.save,MASHLADIDIDI));
return dataList;
}
}
| AndroidBoySC/Mybilibili | app/src/main/java/com/songchao/mybilibili/model/ImageCardUtil.java | 2,194 | //获得系统当前时间 | line_comment | zh-cn | package com.songchao.mybilibili.model;
import com.songchao.mybilibili.R;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Author: SongCHao
* Date: 2017/9/30/10:35
* Email: 15704762346@163.com
*/
public class ImageCardUtil {
/**
* 获取具体图片类别
*/
public static List<ImageCard> getImageCardList(){
List<ImageCard> dataList = new ArrayList<>();
//获得 <SUF>
Date mDate = new Date();
SimpleDateFormat mFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
String date = mFormat.format(mDate);
final String MASHLADI = "玛莎拉蒂";
dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche01,date,R.mipmap.save,MASHLADI));
dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche02,date,R.mipmap.save,MASHLADI));
dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche03,date,R.mipmap.save,MASHLADI));
dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche04,date,R.mipmap.save,MASHLADI));
dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche05,date,R.mipmap.save,MASHLADI));
dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche01,date,R.mipmap.save,MASHLADI));
final String FANGHUA = "芳华电影";
dataList.add(new ImageCard("芳华",R.mipmap.fanghua01,date,R.mipmap.save,FANGHUA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua02,date,R.mipmap.save,FANGHUA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua03,date,R.mipmap.save,FANGHUA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua04,date,R.mipmap.save,FANGHUA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua05,date,R.mipmap.save,FANGHUA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua06,date,R.mipmap.save,FANGHUA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua07,date,R.mipmap.save,FANGHUA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua08,date,R.mipmap.save,FANGHUA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua09,date,R.mipmap.save,FANGHUA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua10,date,R.mipmap.save,FANGHUA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua11,date,R.mipmap.save,FANGHUA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua12,date,R.mipmap.save,FANGHUA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua13,date,R.mipmap.save,FANGHUA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua01,date,R.mipmap.save,FANGHUA));
final String MASHLADIDI = "贼帅的玛莎拉蒂";
dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche01,date,R.mipmap.save,MASHLADIDI));
dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche02,date,R.mipmap.save,MASHLADIDI));
dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche03,date,R.mipmap.save,MASHLADIDI));
dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche04,date,R.mipmap.save,MASHLADIDI));
dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche05,date,R.mipmap.save,MASHLADIDI));
dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche01,date,R.mipmap.save,MASHLADIDI));
final String FANGHUAHA = "芳华情怀";
dataList.add(new ImageCard("芳华",R.mipmap.fanghua01,date,R.mipmap.save,FANGHUAHA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua02,date,R.mipmap.save,FANGHUAHA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua03,date,R.mipmap.save,FANGHUAHA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua04,date,R.mipmap.save,FANGHUAHA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua05,date,R.mipmap.save,FANGHUAHA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua06,date,R.mipmap.save,FANGHUAHA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua07,date,R.mipmap.save,FANGHUAHA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua08,date,R.mipmap.save,FANGHUAHA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua09,date,R.mipmap.save,FANGHUAHA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua10,date,R.mipmap.save,FANGHUAHA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua11,date,R.mipmap.save,FANGHUAHA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua12,date,R.mipmap.save,FANGHUAHA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua13,date,R.mipmap.save,FANGHUAHA));
dataList.add(new ImageCard("芳华",R.mipmap.fanghua01,date,R.mipmap.save,FANGHUAHA));
final String MASHLADIDIDI = "我的玛莎拉蒂";
dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche01,date,R.mipmap.save,MASHLADIDIDI));
dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche02,date,R.mipmap.save,MASHLADIDIDI));
dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche03,date,R.mipmap.save,MASHLADIDIDI));
dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche04,date,R.mipmap.save,MASHLADIDIDI));
dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche05,date,R.mipmap.save,MASHLADIDIDI));
dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche01,date,R.mipmap.save,MASHLADIDIDI));
return dataList;
}
}
| false |
48452_11 | package com.xiaxl.demo;
import android.os.Message;
import android.util.Log;
import com.xiaxl.demo.statemachine.State;
import com.xiaxl.demo.statemachine.StateMachine;
public class PersonStateMachine extends StateMachine {
private static final String TAG = "MachineTest";
//设置状态改变标志常量
public static final int MSG_WAKEUP = 1; // 醒
public static final int MSG_TIRED = 2; // 困
public static final int MSG_HUNGRY = 3; // 饿
private static final int MSG_HALTING = 4; //停
//创建状态
private State mBoringState = new BoringState();// 默认状态
private State mWorkState = new WorkState(); // 工作
private State mEatState = new EatState(); // 吃
private State mSleepState = new SleepState(); // 睡
/**
* 构造方法
*
* @param name
*/
PersonStateMachine(String name) {
super(name);
Log.e(TAG, "PersonStateMachine");
//加入状态,初始化状态
addState(mBoringState, null);
addState(mSleepState, mBoringState);
addState(mWorkState, mBoringState);
addState(mEatState, mBoringState);
// sleep状态为初始状态
setInitialState(mSleepState);
}
/**
* @return 创建启动person 状态机
*/
public static PersonStateMachine makePerson() {
Log.e(TAG, "PersonStateMachine makePerson");
PersonStateMachine person = new PersonStateMachine("Person");
person.start();
return person;
}
@Override
protected void onHalting() {
Log.e(TAG, "PersonStateMachine halting");
synchronized (this) {
this.notifyAll();
}
}
/**
* 定义状态:无聊
*/
class BoringState extends State {
@Override
public void enter() {
Log.e(TAG, "BoringState enter Boring");
}
@Override
public void exit() {
Log.e(TAG, "BoringState exit Boring");
}
@Override
public boolean processMessage(Message msg) {
Log.e(TAG, "BoringState processMessage.....");
return true;
}
}
/**
* 定义状态:睡觉
*/
class SleepState extends State {
@Override
public void enter() {
Log.e(TAG, "SleepState enter Sleep");
}
@Override
public void exit() {
Log.e(TAG, "SleepState exit Sleep");
}
@Override
public boolean processMessage(Message msg) {
Log.e(TAG, "SleepState processMessage.....");
switch (msg.what) {
// 收到清醒信号
case MSG_WAKEUP:
Log.e(TAG, "SleepState MSG_WAKEUP");
// 进入工作状态
deferMessage(msg);
transitionTo(mWorkState);
//
//发送饿了信号...
sendMessage(obtainMessage(MSG_HUNGRY));
break;
case MSG_HALTING:
Log.e(TAG, "SleepState MSG_HALTING");
// 停止
transitionToHaltingState();
break;
default:
return false;
}
return true;
}
}
/**
* 定义状态:工作
*/
class WorkState extends State {
@Override
public void enter() {
Log.e(TAG, "WorkState enter Work");
}
@Override
public void exit() {
Log.e(TAG, "WorkState exit Work");
}
@Override
public boolean processMessage(Message msg) {
Log.e(TAG, "WorkState processMessage.....");
switch (msg.what) {
// 收到 饿了 信号
case MSG_HUNGRY:
Log.e(TAG, "WorkState MSG_HUNGRY");
// 吃饭状态
deferMessage(msg);
transitionTo(mEatState);
// 发送累了信号...
sendMessage(obtainMessage(MSG_TIRED));
break;
default:
return false;
}
return true;
}
}
/**
* 定义状态:吃
*/
class EatState extends State {
@Override
public void enter() {
Log.e(TAG, "EatState enter Eat");
}
@Override
public void exit() {
Log.e(TAG, "EatState exit Eat");
}
@Override
public boolean processMessage(Message msg) {
Log.e(TAG, "EatState processMessage.....");
switch (msg.what) {
// 收到 困了 信号
case MSG_TIRED:
Log.e(TAG, "EatState MSG_TIRED");
// 睡觉
deferMessage(msg);
transitionTo(mSleepState);
// 发出结束信号...
sendMessage(obtainMessage(MSG_HALTING));
break;
default:
return false;
}
return true;
}
}
} | AndroidHighQualityCodeStudy/Android_-StateMachine | app/src/main/java/com/xiaxl/demo/PersonStateMachine.java | 1,192 | //发送饿了信号... | line_comment | zh-cn | package com.xiaxl.demo;
import android.os.Message;
import android.util.Log;
import com.xiaxl.demo.statemachine.State;
import com.xiaxl.demo.statemachine.StateMachine;
public class PersonStateMachine extends StateMachine {
private static final String TAG = "MachineTest";
//设置状态改变标志常量
public static final int MSG_WAKEUP = 1; // 醒
public static final int MSG_TIRED = 2; // 困
public static final int MSG_HUNGRY = 3; // 饿
private static final int MSG_HALTING = 4; //停
//创建状态
private State mBoringState = new BoringState();// 默认状态
private State mWorkState = new WorkState(); // 工作
private State mEatState = new EatState(); // 吃
private State mSleepState = new SleepState(); // 睡
/**
* 构造方法
*
* @param name
*/
PersonStateMachine(String name) {
super(name);
Log.e(TAG, "PersonStateMachine");
//加入状态,初始化状态
addState(mBoringState, null);
addState(mSleepState, mBoringState);
addState(mWorkState, mBoringState);
addState(mEatState, mBoringState);
// sleep状态为初始状态
setInitialState(mSleepState);
}
/**
* @return 创建启动person 状态机
*/
public static PersonStateMachine makePerson() {
Log.e(TAG, "PersonStateMachine makePerson");
PersonStateMachine person = new PersonStateMachine("Person");
person.start();
return person;
}
@Override
protected void onHalting() {
Log.e(TAG, "PersonStateMachine halting");
synchronized (this) {
this.notifyAll();
}
}
/**
* 定义状态:无聊
*/
class BoringState extends State {
@Override
public void enter() {
Log.e(TAG, "BoringState enter Boring");
}
@Override
public void exit() {
Log.e(TAG, "BoringState exit Boring");
}
@Override
public boolean processMessage(Message msg) {
Log.e(TAG, "BoringState processMessage.....");
return true;
}
}
/**
* 定义状态:睡觉
*/
class SleepState extends State {
@Override
public void enter() {
Log.e(TAG, "SleepState enter Sleep");
}
@Override
public void exit() {
Log.e(TAG, "SleepState exit Sleep");
}
@Override
public boolean processMessage(Message msg) {
Log.e(TAG, "SleepState processMessage.....");
switch (msg.what) {
// 收到清醒信号
case MSG_WAKEUP:
Log.e(TAG, "SleepState MSG_WAKEUP");
// 进入工作状态
deferMessage(msg);
transitionTo(mWorkState);
//
//发送 <SUF>
sendMessage(obtainMessage(MSG_HUNGRY));
break;
case MSG_HALTING:
Log.e(TAG, "SleepState MSG_HALTING");
// 停止
transitionToHaltingState();
break;
default:
return false;
}
return true;
}
}
/**
* 定义状态:工作
*/
class WorkState extends State {
@Override
public void enter() {
Log.e(TAG, "WorkState enter Work");
}
@Override
public void exit() {
Log.e(TAG, "WorkState exit Work");
}
@Override
public boolean processMessage(Message msg) {
Log.e(TAG, "WorkState processMessage.....");
switch (msg.what) {
// 收到 饿了 信号
case MSG_HUNGRY:
Log.e(TAG, "WorkState MSG_HUNGRY");
// 吃饭状态
deferMessage(msg);
transitionTo(mEatState);
// 发送累了信号...
sendMessage(obtainMessage(MSG_TIRED));
break;
default:
return false;
}
return true;
}
}
/**
* 定义状态:吃
*/
class EatState extends State {
@Override
public void enter() {
Log.e(TAG, "EatState enter Eat");
}
@Override
public void exit() {
Log.e(TAG, "EatState exit Eat");
}
@Override
public boolean processMessage(Message msg) {
Log.e(TAG, "EatState processMessage.....");
switch (msg.what) {
// 收到 困了 信号
case MSG_TIRED:
Log.e(TAG, "EatState MSG_TIRED");
// 睡觉
deferMessage(msg);
transitionTo(mSleepState);
// 发出结束信号...
sendMessage(obtainMessage(MSG_HALTING));
break;
default:
return false;
}
return true;
}
}
} | false |
66471_16 | package io.github.celestialphineas.sanxing.UIStatistics;
import android.os.Build;
import android.os.Bundle;
import android.support.transition.TransitionManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.github.celestialphineas.sanxing.MyApplication;
import io.github.celestialphineas.sanxing.R;
import io.github.celestialphineas.sanxing.sxObjectManager.HabitManager;
import io.github.celestialphineas.sanxing.sxObjectManager.TaskManager;
import io.github.celestialphineas.sanxing.sxObjectManager.TimeLeftManager;
//import com.konifar.fab_transformation.FabTransformation;
public class StatisticsActivity extends AppCompatActivity {
@BindView(R.id.statistics_toolbar)
Toolbar toolbar;
@BindView(R.id.statistics_root_linear_layout)
ViewGroup rootLinearLayout;
@BindView(R.id.statistics_total_relative_layout)
ViewGroup totalRelativeLayout;
@BindView(R.id.total_grid)
ViewGroup totalGrid;
@BindView(R.id.statistics_place_holder)
ViewGroup placeHolder;
@BindView(R.id.achievement_card)
ViewGroup achievementCard;
@BindView(R.id.total_description)
AppCompatTextView totalDescriptionView;
@BindView(R.id.task_count)
AppCompatTextView taskCountView;
@BindView(R.id.habit_count)
AppCompatTextView habitCountView;
@BindView(R.id.time_left_count)
AppCompatTextView timeLeftCountView;
@BindView(R.id.achievement_list)
ListView achievementListView;
@BindString(R.string.statistics_total_description)
String currentTotalString;
@BindString(R.string.statistics_finished_description)
String finishedTotalString;
int nTasks = 0, nHabits = 0, nTimeLefts = 0;
int nFinishedTasks = 0, nFinishedHabits = 0, nFinishedTimeLefts = 0;
boolean showCurrent = true;
static final int TASK = 0, HABIT = 1, TIME_LEFT = 2;
static final int BRONZE = 0, SILVER = 1, GOLD = 2;
List<Achievement> achievements = new ArrayList<>();
//
// Achievement
class Achievement {
int type, prize;
String title, description;
Achievement(int type, int prize, String title, String description) {
this.type = type;
this.prize = prize;
this.title = title;
this.description = description;
}
int getBandColor() {
switch (type) {
case TASK:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return getBaseContext().getResources().getColor(R.color.colorTasks, null);
} else return getBaseContext().getResources().getColor(R.color.colorTasks);
case HABIT:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return getBaseContext().getResources().getColor(R.color.colorHabits, null);
} else return getBaseContext().getResources().getColor(R.color.colorHabits);
case TIME_LEFT:
default:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return getBaseContext().getResources().getColor(R.color.colorTimeLeft, null);
} else return getBaseContext().getResources().getColor(R.color.colorTimeLeft);
}
}
int getMedalBrightColor() {
switch (prize) {
case BRONZE:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return getBaseContext().getResources().getColor(R.color.bronze_bright, null);
} else return getBaseContext().getResources().getColor(R.color.bronze_bright);
case SILVER:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return getBaseContext().getResources().getColor(R.color.silver_bright, null);
} else return getBaseContext().getResources().getColor(R.color.silver_bright);
case GOLD:
default:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return getBaseContext().getResources().getColor(R.color.gold_bright, null);
} else return getBaseContext().getResources().getColor(R.color.gold_bright);
}
}
int getMedalDarkColor() {
switch (prize) {
case BRONZE:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return getBaseContext().getResources().getColor(R.color.bronze_dark, null);
} else return getBaseContext().getResources().getColor(R.color.bronze_dark);
case SILVER:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return getBaseContext().getResources().getColor(R.color.silver_dark, null);
} else return getBaseContext().getResources().getColor(R.color.silver_dark);
case GOLD:
default:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return getBaseContext().getResources().getColor(R.color.gold_dark, null);
} else return getBaseContext().getResources().getColor(R.color.gold_dark);
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_statistics);
ButterKnife.bind(this);
//backend
MyApplication myApplication = (MyApplication) getApplication();
TaskManager taskManager = myApplication.get_task_manager();
HabitManager habitManager = myApplication.get_habit_manager();
TimeLeftManager timeLeftManager = myApplication.get_time_left_manager();
//////// Toolbar ////////
// Set the toolbar as the default action bar of the window
setSupportActionBar(toolbar);
setTitle(getString(R.string.statistics_and_achievements));
// Enable the back button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
// Set the number of items
//end numbers
taskManager.resetNumbers();
habitManager.resetNumbers();
timeLeftManager.resetNumbers();
nTasks = taskManager.getNumberOfTasks();
nHabits = habitManager.getNumberOfHabits();
nTimeLefts = timeLeftManager.getNumberOfTimeLefts();
nFinishedTasks = taskManager.getNumberOfFinishedTasks();
nFinishedHabits = habitManager.getNumberOfFinishedHabits();
nFinishedTimeLefts = timeLeftManager.getNumberOfFinishedTimeLefts();
// Set up achievements
// nFinishedTimeLefts=101;
// nFinishedHabits=101;
// nFinishedTasks=101;
if (nFinishedTasks >= 100)
achievements.add(new Achievement(TASK, GOLD, "打败deadline", "完成任务数 >= 100"));
if (nFinishedHabits >= 30)
achievements.add(new Achievement(HABIT, GOLD, "坚持造就伟大", "完成习惯数 >= 30"));
if (nFinishedTimeLefts >= 30)
achievements.add(new Achievement(TIME_LEFT, GOLD, "惟愿时光清浅,将你温柔以待", "完成倒计时数 >= 30"));
if (nFinishedTasks >= 10)
achievements.add(new Achievement(TASK, SILVER, "任务达人", "完成任务数 >= 10"));
if (nFinishedHabits >= 10)
achievements.add(new Achievement(HABIT, SILVER, "自律者", "完成习惯数 >= 10"));
if (nFinishedTimeLefts >= 10)
achievements.add(new Achievement(TIME_LEFT, SILVER, "守望时光", "完成倒计时数 >= 10"));
if (nFinishedTasks >= 1 && nFinishedHabits == 0) {
achievements.add(new Achievement(TASK, BRONZE, "第一次", "完成了一个任务或习惯"));
} else if (nFinishedTasks == 0 && nFinishedHabits >= 1) {
achievements.add(new Achievement(HABIT, BRONZE, "第一次", "完成了一个任务或习惯"));
} else if (nFinishedTasks >= 1 && nFinishedHabits >= 1) {
achievements.add(new Achievement(TASK, SILVER, "第一次", "完成了一个任务和一个习惯"));
}
if (nFinishedTimeLefts >= 1) {
achievements.add(new Achievement(TIME_LEFT, SILVER, "倒计时,你怕了吗", "完成了一个倒计时"));
}
// achievements.add(new Achievement(HABIT, GOLD, "Hello", "world, blablabla"));
// achievements.add(new Achievement(TASK, BRONZE, "Task bla", "You've won a lot"));
// achievements.add(new Achievement(TIME_LEFT, SILVER, "What?", "What the heck!!!"));
//
//////// ListAdapter ////////
if (achievements == null || achievements.isEmpty()) {
placeHolder.setVisibility(View.VISIBLE);
achievementCard.setVisibility(View.GONE);
} else {
achievementListView.setAdapter(new AchievementsAdapter(this, achievements));
}
showCurrentNumbers();
}
@OnClick(R.id.toggle_summary_button)
//切换按钮
void toggleSummaryButtonOnClickBehavior() {
TransitionManager.beginDelayedTransition(rootLinearLayout);
TransitionManager.beginDelayedTransition(totalRelativeLayout);
TransitionManager.beginDelayedTransition(totalGrid);
if (!showCurrent) {
showCurrentNumbers();
showCurrent = true;
} else {
showFinishedNumbers();
showCurrent = false;
}
}
private void showCurrentNumbers() {
totalDescriptionView.setText(currentTotalString);
taskCountView.setText(Integer.toString(nTasks));
habitCountView.setText(Integer.toString(nHabits));
timeLeftCountView.setText(Integer.toString(nTimeLefts));
}
private void showFinishedNumbers() {
totalDescriptionView.setText(finishedTotalString);
taskCountView.setText(Integer.toString(nFinishedTasks));
habitCountView.setText(Integer.toString(nFinishedHabits));
timeLeftCountView.setText(Integer.toString(nFinishedTimeLefts));
}
}
| AndroidNewbies/Sanxing | app/src/main/java/io/github/celestialphineas/sanxing/UIStatistics/StatisticsActivity.java | 2,697 | //切换按钮 | line_comment | zh-cn | package io.github.celestialphineas.sanxing.UIStatistics;
import android.os.Build;
import android.os.Bundle;
import android.support.transition.TransitionManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.github.celestialphineas.sanxing.MyApplication;
import io.github.celestialphineas.sanxing.R;
import io.github.celestialphineas.sanxing.sxObjectManager.HabitManager;
import io.github.celestialphineas.sanxing.sxObjectManager.TaskManager;
import io.github.celestialphineas.sanxing.sxObjectManager.TimeLeftManager;
//import com.konifar.fab_transformation.FabTransformation;
public class StatisticsActivity extends AppCompatActivity {
@BindView(R.id.statistics_toolbar)
Toolbar toolbar;
@BindView(R.id.statistics_root_linear_layout)
ViewGroup rootLinearLayout;
@BindView(R.id.statistics_total_relative_layout)
ViewGroup totalRelativeLayout;
@BindView(R.id.total_grid)
ViewGroup totalGrid;
@BindView(R.id.statistics_place_holder)
ViewGroup placeHolder;
@BindView(R.id.achievement_card)
ViewGroup achievementCard;
@BindView(R.id.total_description)
AppCompatTextView totalDescriptionView;
@BindView(R.id.task_count)
AppCompatTextView taskCountView;
@BindView(R.id.habit_count)
AppCompatTextView habitCountView;
@BindView(R.id.time_left_count)
AppCompatTextView timeLeftCountView;
@BindView(R.id.achievement_list)
ListView achievementListView;
@BindString(R.string.statistics_total_description)
String currentTotalString;
@BindString(R.string.statistics_finished_description)
String finishedTotalString;
int nTasks = 0, nHabits = 0, nTimeLefts = 0;
int nFinishedTasks = 0, nFinishedHabits = 0, nFinishedTimeLefts = 0;
boolean showCurrent = true;
static final int TASK = 0, HABIT = 1, TIME_LEFT = 2;
static final int BRONZE = 0, SILVER = 1, GOLD = 2;
List<Achievement> achievements = new ArrayList<>();
//
// Achievement
class Achievement {
int type, prize;
String title, description;
Achievement(int type, int prize, String title, String description) {
this.type = type;
this.prize = prize;
this.title = title;
this.description = description;
}
int getBandColor() {
switch (type) {
case TASK:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return getBaseContext().getResources().getColor(R.color.colorTasks, null);
} else return getBaseContext().getResources().getColor(R.color.colorTasks);
case HABIT:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return getBaseContext().getResources().getColor(R.color.colorHabits, null);
} else return getBaseContext().getResources().getColor(R.color.colorHabits);
case TIME_LEFT:
default:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return getBaseContext().getResources().getColor(R.color.colorTimeLeft, null);
} else return getBaseContext().getResources().getColor(R.color.colorTimeLeft);
}
}
int getMedalBrightColor() {
switch (prize) {
case BRONZE:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return getBaseContext().getResources().getColor(R.color.bronze_bright, null);
} else return getBaseContext().getResources().getColor(R.color.bronze_bright);
case SILVER:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return getBaseContext().getResources().getColor(R.color.silver_bright, null);
} else return getBaseContext().getResources().getColor(R.color.silver_bright);
case GOLD:
default:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return getBaseContext().getResources().getColor(R.color.gold_bright, null);
} else return getBaseContext().getResources().getColor(R.color.gold_bright);
}
}
int getMedalDarkColor() {
switch (prize) {
case BRONZE:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return getBaseContext().getResources().getColor(R.color.bronze_dark, null);
} else return getBaseContext().getResources().getColor(R.color.bronze_dark);
case SILVER:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return getBaseContext().getResources().getColor(R.color.silver_dark, null);
} else return getBaseContext().getResources().getColor(R.color.silver_dark);
case GOLD:
default:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return getBaseContext().getResources().getColor(R.color.gold_dark, null);
} else return getBaseContext().getResources().getColor(R.color.gold_dark);
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_statistics);
ButterKnife.bind(this);
//backend
MyApplication myApplication = (MyApplication) getApplication();
TaskManager taskManager = myApplication.get_task_manager();
HabitManager habitManager = myApplication.get_habit_manager();
TimeLeftManager timeLeftManager = myApplication.get_time_left_manager();
//////// Toolbar ////////
// Set the toolbar as the default action bar of the window
setSupportActionBar(toolbar);
setTitle(getString(R.string.statistics_and_achievements));
// Enable the back button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
// Set the number of items
//end numbers
taskManager.resetNumbers();
habitManager.resetNumbers();
timeLeftManager.resetNumbers();
nTasks = taskManager.getNumberOfTasks();
nHabits = habitManager.getNumberOfHabits();
nTimeLefts = timeLeftManager.getNumberOfTimeLefts();
nFinishedTasks = taskManager.getNumberOfFinishedTasks();
nFinishedHabits = habitManager.getNumberOfFinishedHabits();
nFinishedTimeLefts = timeLeftManager.getNumberOfFinishedTimeLefts();
// Set up achievements
// nFinishedTimeLefts=101;
// nFinishedHabits=101;
// nFinishedTasks=101;
if (nFinishedTasks >= 100)
achievements.add(new Achievement(TASK, GOLD, "打败deadline", "完成任务数 >= 100"));
if (nFinishedHabits >= 30)
achievements.add(new Achievement(HABIT, GOLD, "坚持造就伟大", "完成习惯数 >= 30"));
if (nFinishedTimeLefts >= 30)
achievements.add(new Achievement(TIME_LEFT, GOLD, "惟愿时光清浅,将你温柔以待", "完成倒计时数 >= 30"));
if (nFinishedTasks >= 10)
achievements.add(new Achievement(TASK, SILVER, "任务达人", "完成任务数 >= 10"));
if (nFinishedHabits >= 10)
achievements.add(new Achievement(HABIT, SILVER, "自律者", "完成习惯数 >= 10"));
if (nFinishedTimeLefts >= 10)
achievements.add(new Achievement(TIME_LEFT, SILVER, "守望时光", "完成倒计时数 >= 10"));
if (nFinishedTasks >= 1 && nFinishedHabits == 0) {
achievements.add(new Achievement(TASK, BRONZE, "第一次", "完成了一个任务或习惯"));
} else if (nFinishedTasks == 0 && nFinishedHabits >= 1) {
achievements.add(new Achievement(HABIT, BRONZE, "第一次", "完成了一个任务或习惯"));
} else if (nFinishedTasks >= 1 && nFinishedHabits >= 1) {
achievements.add(new Achievement(TASK, SILVER, "第一次", "完成了一个任务和一个习惯"));
}
if (nFinishedTimeLefts >= 1) {
achievements.add(new Achievement(TIME_LEFT, SILVER, "倒计时,你怕了吗", "完成了一个倒计时"));
}
// achievements.add(new Achievement(HABIT, GOLD, "Hello", "world, blablabla"));
// achievements.add(new Achievement(TASK, BRONZE, "Task bla", "You've won a lot"));
// achievements.add(new Achievement(TIME_LEFT, SILVER, "What?", "What the heck!!!"));
//
//////// ListAdapter ////////
if (achievements == null || achievements.isEmpty()) {
placeHolder.setVisibility(View.VISIBLE);
achievementCard.setVisibility(View.GONE);
} else {
achievementListView.setAdapter(new AchievementsAdapter(this, achievements));
}
showCurrentNumbers();
}
@OnClick(R.id.toggle_summary_button)
//切换 <SUF>
void toggleSummaryButtonOnClickBehavior() {
TransitionManager.beginDelayedTransition(rootLinearLayout);
TransitionManager.beginDelayedTransition(totalRelativeLayout);
TransitionManager.beginDelayedTransition(totalGrid);
if (!showCurrent) {
showCurrentNumbers();
showCurrent = true;
} else {
showFinishedNumbers();
showCurrent = false;
}
}
private void showCurrentNumbers() {
totalDescriptionView.setText(currentTotalString);
taskCountView.setText(Integer.toString(nTasks));
habitCountView.setText(Integer.toString(nHabits));
timeLeftCountView.setText(Integer.toString(nTimeLefts));
}
private void showFinishedNumbers() {
totalDescriptionView.setText(finishedTotalString);
taskCountView.setText(Integer.toString(nFinishedTasks));
habitCountView.setText(Integer.toString(nFinishedHabits));
timeLeftCountView.setText(Integer.toString(nFinishedTimeLefts));
}
}
| false |
32715_6 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package translation;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* @author yoUng @description 发送http请求 @filename HttpUtil.java @time 2011-6-15
* 下午05:26:36
* @version 1.0
*/
public class Post {
public static String http(String url, Map<String, String> params) {
URL u = null;
HttpURLConnection con = null;
StringBuffer buffer = new StringBuffer();
//构建请求参数
StringBuffer sb = new StringBuffer();
if (params != null) {
for (Entry<String, String> e : params.entrySet()) {
sb.append(e.getKey());
sb.append("=");
sb.append(e.getValue());
//sb.append("&");//多个参数时需要加上
}
sb.substring(0, sb.length() - 1);
}
// System.out.println("send_url:" + url);
// System.out.println("send_data:" + sb.toString());
//尝试发送请求
try {
u = new URL(url);
con = (HttpURLConnection) u.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setDoInput(true);
con.setUseCaches(false);
con.setReadTimeout(3000);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
osw.write(sb.toString());
osw.flush();
osw.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (con != null) {
con.disconnect();
}
}
//读取返回内容
try {
if (con.getResponseCode() == 200) {
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
String temp;
while ((temp = br.readLine()) != null) {
buffer.append(temp);
buffer.append("\n");
}
} else {
buffer.append(con.getResponseCode());
}
//System.out.println(con.getResponseCode() + "");
} catch (Exception e) {
e.printStackTrace();
}
return buffer.toString();
}
/**
* 获取翻译结果
*
* @param tvalue 需要翻译的中文字符串
* @return
*/
public static String tg(String translate_site, String tvalue) {
Map<String, String> map = new HashMap<String, String>();;
map.put("origin", tvalue);
return http(translate_site, map).trim();
}
/**
* 获取翻译结果(比用JSON速度更快)
*
* @param tvalue 需要翻译的中文字符串
* @return
*/
public String tg1(String translate_site, String tvalue) {
Map<String, String> map = new HashMap<String, String>();
map.put("origin", tvalue);
String tempt = WordsTransfer.unicodeToUtf8(http(translate_site, map).trim());
tempt = tempt.substring(tempt.lastIndexOf(":") + 1, tempt.length() - 3).replaceAll("\"", "");
return tempt;
}
// public static void main(String[] args) {
// Map<String, String> map = new HashMap<String, String>();;
// map.put("q", "中国");
// System.out.println(http("http://zhangwei911.duapp.com/TranslateGet.jsp", map).trim());
// }
}
| AndroidStudioTranslate/Android-Studio-Translate-Tool | src/translation/Post.java | 949 | //尝试发送请求 | line_comment | zh-cn | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package translation;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* @author yoUng @description 发送http请求 @filename HttpUtil.java @time 2011-6-15
* 下午05:26:36
* @version 1.0
*/
public class Post {
public static String http(String url, Map<String, String> params) {
URL u = null;
HttpURLConnection con = null;
StringBuffer buffer = new StringBuffer();
//构建请求参数
StringBuffer sb = new StringBuffer();
if (params != null) {
for (Entry<String, String> e : params.entrySet()) {
sb.append(e.getKey());
sb.append("=");
sb.append(e.getValue());
//sb.append("&");//多个参数时需要加上
}
sb.substring(0, sb.length() - 1);
}
// System.out.println("send_url:" + url);
// System.out.println("send_data:" + sb.toString());
//尝试 <SUF>
try {
u = new URL(url);
con = (HttpURLConnection) u.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setDoInput(true);
con.setUseCaches(false);
con.setReadTimeout(3000);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
osw.write(sb.toString());
osw.flush();
osw.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (con != null) {
con.disconnect();
}
}
//读取返回内容
try {
if (con.getResponseCode() == 200) {
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
String temp;
while ((temp = br.readLine()) != null) {
buffer.append(temp);
buffer.append("\n");
}
} else {
buffer.append(con.getResponseCode());
}
//System.out.println(con.getResponseCode() + "");
} catch (Exception e) {
e.printStackTrace();
}
return buffer.toString();
}
/**
* 获取翻译结果
*
* @param tvalue 需要翻译的中文字符串
* @return
*/
public static String tg(String translate_site, String tvalue) {
Map<String, String> map = new HashMap<String, String>();;
map.put("origin", tvalue);
return http(translate_site, map).trim();
}
/**
* 获取翻译结果(比用JSON速度更快)
*
* @param tvalue 需要翻译的中文字符串
* @return
*/
public String tg1(String translate_site, String tvalue) {
Map<String, String> map = new HashMap<String, String>();
map.put("origin", tvalue);
String tempt = WordsTransfer.unicodeToUtf8(http(translate_site, map).trim());
tempt = tempt.substring(tempt.lastIndexOf(":") + 1, tempt.length() - 3).replaceAll("\"", "");
return tempt;
}
// public static void main(String[] args) {
// Map<String, String> map = new HashMap<String, String>();;
// map.put("q", "中国");
// System.out.println(http("http://zhangwei911.duapp.com/TranslateGet.jsp", map).trim());
// }
}
| false |
25031_0 | package zimu.common;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ZiMuCommon {
/**
* 将字符串复制到剪切板。
*/
public static void copyClipboard(String writeMe) {
Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable tText = new StringSelection(writeMe);
clip.setContents(tText, null);
}
/**
* 获取字符中的汉字部分
* @param title
* @return
*/
public static String getTitleCnStr(String title) {
if(title == null)return "";
title = title.replace(":", ":");
//title = title.replace("_", "—");
//title = title.replace("-", "ˉ");
title = title.replace("[", "【");
title = title.replace("]", "】");
title = title.replace("修正版", "");
String[] arr = title.split("\\.");
if(arr.length > 2) {
title = title.substring(0, title.lastIndexOf("."));
}
if(arr.length > 3) {
title = title.substring(0, title.lastIndexOf("."));
}
String title2 = title.replaceAll("【.*】", "");
//中文+标点组合
Pattern pattern = Pattern.compile("[\u4E00-\u9FA5"
+ "\u3002\uff1f\uff01\uff0c\u3001\uff1b\uff1a\u201c"
+ "\u201d\u2018\u2019\uff08\uff09\u300a\u300b\u3008"
+ "\u3009\u3010\u3011\u300e\u300f\u300c\u300d\ufe43"
+ "\ufe44\u3014\u3015\u2026\u2014\uff5e\ufe4f\uffe5"
+ "\u02c9]+");
Matcher matcher = pattern.matcher(title2);
String resStr = "";
if(matcher.find()) {
resStr = matcher.group(0);
}else {
matcher = pattern.matcher(title);
if(matcher.find()) {
resStr = matcher.group(0);
resStr = resStr.replaceAll("[【】]+", "");
}
}
//中文+英文+标点组合
pattern = Pattern.compile("[\\w\u4E00-\u9FA5"
+ "\u3002\uff1f\uff01\uff0c\u3001\uff1b\uff1a\u201c"
+ "\u201d\u2018\u2019\uff08\uff09\u300a\u300b\u3008"
+ "\u3009\u3010\u3011\u300e\u300f\u300c\u300d\ufe43"
+ "\ufe44\u3014\u3015\u2026\u2014\uff5e\ufe4f\uffe5"
+ "\u02c9]+");
if((resStr == null || resStr.length() == 0) && Pattern.compile("[\u4E00-\u9FA5]+").matcher(title).find()) {
matcher = pattern.matcher(title);
if(matcher.find()) {
resStr = matcher.group(0);
resStr = resStr.replaceAll("[【】]+", "");
}
}
return resStr;
}
public static void main(String[] args) {
// System.out.println("[缩小人生]Downsizing.2017.1080p.Bluray.MKV.x264.AC3修正版.ass [ASS/SSA][双语][下载次数:1709]".
// replaceAll("\\[[^]]*]\\[[^]]*]\\[下载次数.+]", ""));;
//System.out.println(getTitleCnStr("【X战警:逆转未来 导演剪辑版】X-Men.Days.of.Future.Past.THE.ROGUE.CUT.1080p.BluRay.x264-SADPANDA"));
//System.exit(0);
String[] titles = new String[] {
"test.a.b.c",
"我是中文.a.b.c",
"我是中文 a.b.c",
"我是中文a.b.c",
"我是-中文a.b.c",
"我是_中文a.b.c",
"[我是中文]a.b.c",
"【获取】我是中文a.b.c",
"[获wee取]我是中文a.b.c",
"[超人特工队(国粤台英)].The.Incredibles.2004.BluRay.720p.x264.AC3.4Audios-CMCT.完美匹配国语chsc",
"[缩小人生]Downsizing.2017.1080p.Bluray.MKV.x264.AC3修正版",
"X战警:第一战.X-Men.First.Class.2011.2160p.BluRay",
"战X警:第一战.X-Men.First.Class.2011.2160p.BluRay",
"【X战警:逆转未来 导演剪辑版】X-Men.Days.of.Future.Past.THE.ROGUE.CUT.1080p.BluRay.x264-SADPANDA"
};
//System.out.println(getTitleCnStr("[获wee取]我是中文a.b.c"));
for(int i = 0; i < titles.length; i++) {
System.out.println(getTitleCnStr(titles[i]));
}
}
}
| Andyfoo/SubTitleSearcher | src/main/java/zimu/common/ZiMuCommon.java | 1,619 | /**
* 将字符串复制到剪切板。
*/ | block_comment | zh-cn | package zimu.common;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ZiMuCommon {
/**
* 将字符 <SUF>*/
public static void copyClipboard(String writeMe) {
Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable tText = new StringSelection(writeMe);
clip.setContents(tText, null);
}
/**
* 获取字符中的汉字部分
* @param title
* @return
*/
public static String getTitleCnStr(String title) {
if(title == null)return "";
title = title.replace(":", ":");
//title = title.replace("_", "—");
//title = title.replace("-", "ˉ");
title = title.replace("[", "【");
title = title.replace("]", "】");
title = title.replace("修正版", "");
String[] arr = title.split("\\.");
if(arr.length > 2) {
title = title.substring(0, title.lastIndexOf("."));
}
if(arr.length > 3) {
title = title.substring(0, title.lastIndexOf("."));
}
String title2 = title.replaceAll("【.*】", "");
//中文+标点组合
Pattern pattern = Pattern.compile("[\u4E00-\u9FA5"
+ "\u3002\uff1f\uff01\uff0c\u3001\uff1b\uff1a\u201c"
+ "\u201d\u2018\u2019\uff08\uff09\u300a\u300b\u3008"
+ "\u3009\u3010\u3011\u300e\u300f\u300c\u300d\ufe43"
+ "\ufe44\u3014\u3015\u2026\u2014\uff5e\ufe4f\uffe5"
+ "\u02c9]+");
Matcher matcher = pattern.matcher(title2);
String resStr = "";
if(matcher.find()) {
resStr = matcher.group(0);
}else {
matcher = pattern.matcher(title);
if(matcher.find()) {
resStr = matcher.group(0);
resStr = resStr.replaceAll("[【】]+", "");
}
}
//中文+英文+标点组合
pattern = Pattern.compile("[\\w\u4E00-\u9FA5"
+ "\u3002\uff1f\uff01\uff0c\u3001\uff1b\uff1a\u201c"
+ "\u201d\u2018\u2019\uff08\uff09\u300a\u300b\u3008"
+ "\u3009\u3010\u3011\u300e\u300f\u300c\u300d\ufe43"
+ "\ufe44\u3014\u3015\u2026\u2014\uff5e\ufe4f\uffe5"
+ "\u02c9]+");
if((resStr == null || resStr.length() == 0) && Pattern.compile("[\u4E00-\u9FA5]+").matcher(title).find()) {
matcher = pattern.matcher(title);
if(matcher.find()) {
resStr = matcher.group(0);
resStr = resStr.replaceAll("[【】]+", "");
}
}
return resStr;
}
public static void main(String[] args) {
// System.out.println("[缩小人生]Downsizing.2017.1080p.Bluray.MKV.x264.AC3修正版.ass [ASS/SSA][双语][下载次数:1709]".
// replaceAll("\\[[^]]*]\\[[^]]*]\\[下载次数.+]", ""));;
//System.out.println(getTitleCnStr("【X战警:逆转未来 导演剪辑版】X-Men.Days.of.Future.Past.THE.ROGUE.CUT.1080p.BluRay.x264-SADPANDA"));
//System.exit(0);
String[] titles = new String[] {
"test.a.b.c",
"我是中文.a.b.c",
"我是中文 a.b.c",
"我是中文a.b.c",
"我是-中文a.b.c",
"我是_中文a.b.c",
"[我是中文]a.b.c",
"【获取】我是中文a.b.c",
"[获wee取]我是中文a.b.c",
"[超人特工队(国粤台英)].The.Incredibles.2004.BluRay.720p.x264.AC3.4Audios-CMCT.完美匹配国语chsc",
"[缩小人生]Downsizing.2017.1080p.Bluray.MKV.x264.AC3修正版",
"X战警:第一战.X-Men.First.Class.2011.2160p.BluRay",
"战X警:第一战.X-Men.First.Class.2011.2160p.BluRay",
"【X战警:逆转未来 导演剪辑版】X-Men.Days.of.Future.Past.THE.ROGUE.CUT.1080p.BluRay.x264-SADPANDA"
};
//System.out.println(getTitleCnStr("[获wee取]我是中文a.b.c"));
for(int i = 0; i < titles.length; i++) {
System.out.println(getTitleCnStr(titles[i]));
}
}
}
| true |
61225_1 | package com.pslib.jtool.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import cn.hutool.json.JSONArray;
/**
* @author ******
*
*
* 功能说明:请补充
*/
public class MathUtil {
// 取随机数
/*
* 生成 min-max之间的数字, 包括min,max
*
*/
public static int getRand(int min, int max) {
return (int) (min + Math.random() * (max - min + 1));
}
// 生成随机数的数组,
public static int[] getUniqueRandArray(int num, int min, int max) {
if(max - min + 1 < num) {
return null;
}
List<Integer> arr = new ArrayList<Integer>();
int n;
int[] r = new int[num];
for (int i = 0; i < num; i++) {
do {
n = MathUtil.getRand(min, max);
}while(arr.contains(n));
arr.add(n);
r[i] = n;
}
arr.clear();
return r;
}
// 生成随机数的数组,并排序
public static int[] getUniqueRandArray(int num, int min, int max, String sort) {
int[] sel = getUniqueRandArray(num, min, max);
if (sort.equals("ASC")) {
Arrays.sort(sel);
int[] sel2 = new int[sel.length];
for (int i = sel.length; i > 0; i--) {
sel2[sel.length - i] = sel[i - 1];
}
return sel;
} else {
Arrays.sort(sel);
return sel;
}
}
// 生成随机数字符串的数组,
public static String[] getUniqueStringRandArray(int num, int len, int min, int max) {
int[] sel = getUniqueRandArray(num, min, max);
String[] result = new String[sel.length];
for (int i = 0; i < sel.length; i++) {
result[i] = StringUtil.strPad(Integer.toString(sel[i]), len, "0");
}
return result;
}
// 生成随机数字符串的数组,并排序
public static String[] getUniqueStringRandArray(int num, int len, int min, int max, String sort) {
int[] sel = getUniqueRandArray(num, min, max, sort);
String[] result = new String[sel.length];
for (int i = 0; i < sel.length; i++) {
result[i] = StringUtil.strPad(Integer.toString(sel[i]), len, "0");
}
return result;
}
/**
* 排列组合 (java多个一维数组进行组合排序 笛卡尔 http://blog.csdn.net/wuyongde_0922/article/details/56511362)
*
* @param source
* "a,b,c|2,3|A,B,C"
* @return
*/
public static JSONArray getCombJSONArray(String source) {
String[] list = source.split("\\|");
JSONArray strs = new JSONArray();
for (int i = 0; i < list.length; i++) {
strs.add(Arrays.asList(list[i].split(",")));
}
return getCombJSONArray(strs);
}
/**
* 排列组合
*
* @param strs
* [["a","b","c"],["2","3"]]
* @return
*/
public static JSONArray getCombJSONArray(JSONArray strs) {
int total = 1;
for (int i = 0; i < strs.size(); i++) {
total *= strs.getJSONArray(i).size();
}
JSONArray mysesult = new JSONArray();
for (int i = 0; i < total; i++) {
mysesult.add(new JSONArray());
}
int now = 1;
// 每个元素每次循环打印个数
int itemLoopNum = 1;
// 每个元素循环的总次数
int loopPerItem = 1;
for (int i = 0; i < strs.size(); i++) {
JSONArray temp = strs.getJSONArray(i);
now = now * temp.size();
// 目标数组的索引值
int index = 0;
int currentSize = temp.size();
itemLoopNum = total / now;
loopPerItem = total / (itemLoopNum * currentSize);
int myindex = 0;
for (int j = 0; j < temp.size(); j++) {
// 每个元素循环的总次数
for (int k = 0; k < loopPerItem; k++) {
if (myindex == temp.size())
myindex = 0;
// 每个元素每次循环打印个数
for (int m = 0; m < itemLoopNum; m++) {
JSONArray rows = mysesult.getJSONArray(index);
rows.add(temp.get(myindex));
mysesult.set(index, rows);
index++;
}
myindex++;
}
}
}
return mysesult;
}
/**
* 排列组合
*
* @param source
* "a,b,c|2,3|A,B,C"
* @return
*/
public static List<List<String>> getCombList(String source) {
String[] list = source.split("\\|");
List<List<String>> strs = new ArrayList<List<String>>();
for (int i = 0; i < list.length; i++) {
strs.add(Arrays.asList(list[i].split(",")));
}
return getCombList(strs);
}
/**
* 排列组合
*
* @param strs
* [["a","b","c"],["2","3"]]
* @return
*/
public static List<List<String>> getCombList(List<List<String>> strs) {
int total = 1;
for (int i = 0; i < strs.size(); i++) {
total *= strs.get(i).size();
}
List<List<String>> mysesult = new ArrayList<List<String>>();
for (int i = 0; i < total; i++) {
mysesult.add(new ArrayList<String>());
}
int now = 1;
// 每个元素每次循环打印个数
int itemLoopNum = 1;
// 每个元素循环的总次数
int loopPerItem = 1;
for (int i = 0; i < strs.size(); i++) {
List<String> temp = strs.get(i);
now = now * temp.size();
// 目标数组的索引值
int index = 0;
int currentSize = temp.size();
itemLoopNum = total / now;
loopPerItem = total / (itemLoopNum * currentSize);
int myindex = 0;
for (int j = 0; j < temp.size(); j++) {
// 每个元素循环的总次数
for (int k = 0; k < loopPerItem; k++) {
if (myindex == temp.size())
myindex = 0;
// 每个元素每次循环打印个数
for (int m = 0; m < itemLoopNum; m++) {
List<String> rows = mysesult.get(index);
rows.add(temp.get(myindex));
mysesult.set(index, rows);
index++;
}
myindex++;
}
}
}
return mysesult;
}
public static void main(String[] args) {
System.out.println(getRand(3, 999));
System.out.println(getUniqueRandArray(3, 0, 3));
}
}
| Andyfoo/pslib-jtool | pslib-jtool-core/src/main/java/com/pslib/jtool/util/MathUtil.java | 2,029 | // 取随机数 | line_comment | zh-cn | package com.pslib.jtool.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import cn.hutool.json.JSONArray;
/**
* @author ******
*
*
* 功能说明:请补充
*/
public class MathUtil {
// 取随 <SUF>
/*
* 生成 min-max之间的数字, 包括min,max
*
*/
public static int getRand(int min, int max) {
return (int) (min + Math.random() * (max - min + 1));
}
// 生成随机数的数组,
public static int[] getUniqueRandArray(int num, int min, int max) {
if(max - min + 1 < num) {
return null;
}
List<Integer> arr = new ArrayList<Integer>();
int n;
int[] r = new int[num];
for (int i = 0; i < num; i++) {
do {
n = MathUtil.getRand(min, max);
}while(arr.contains(n));
arr.add(n);
r[i] = n;
}
arr.clear();
return r;
}
// 生成随机数的数组,并排序
public static int[] getUniqueRandArray(int num, int min, int max, String sort) {
int[] sel = getUniqueRandArray(num, min, max);
if (sort.equals("ASC")) {
Arrays.sort(sel);
int[] sel2 = new int[sel.length];
for (int i = sel.length; i > 0; i--) {
sel2[sel.length - i] = sel[i - 1];
}
return sel;
} else {
Arrays.sort(sel);
return sel;
}
}
// 生成随机数字符串的数组,
public static String[] getUniqueStringRandArray(int num, int len, int min, int max) {
int[] sel = getUniqueRandArray(num, min, max);
String[] result = new String[sel.length];
for (int i = 0; i < sel.length; i++) {
result[i] = StringUtil.strPad(Integer.toString(sel[i]), len, "0");
}
return result;
}
// 生成随机数字符串的数组,并排序
public static String[] getUniqueStringRandArray(int num, int len, int min, int max, String sort) {
int[] sel = getUniqueRandArray(num, min, max, sort);
String[] result = new String[sel.length];
for (int i = 0; i < sel.length; i++) {
result[i] = StringUtil.strPad(Integer.toString(sel[i]), len, "0");
}
return result;
}
/**
* 排列组合 (java多个一维数组进行组合排序 笛卡尔 http://blog.csdn.net/wuyongde_0922/article/details/56511362)
*
* @param source
* "a,b,c|2,3|A,B,C"
* @return
*/
public static JSONArray getCombJSONArray(String source) {
String[] list = source.split("\\|");
JSONArray strs = new JSONArray();
for (int i = 0; i < list.length; i++) {
strs.add(Arrays.asList(list[i].split(",")));
}
return getCombJSONArray(strs);
}
/**
* 排列组合
*
* @param strs
* [["a","b","c"],["2","3"]]
* @return
*/
public static JSONArray getCombJSONArray(JSONArray strs) {
int total = 1;
for (int i = 0; i < strs.size(); i++) {
total *= strs.getJSONArray(i).size();
}
JSONArray mysesult = new JSONArray();
for (int i = 0; i < total; i++) {
mysesult.add(new JSONArray());
}
int now = 1;
// 每个元素每次循环打印个数
int itemLoopNum = 1;
// 每个元素循环的总次数
int loopPerItem = 1;
for (int i = 0; i < strs.size(); i++) {
JSONArray temp = strs.getJSONArray(i);
now = now * temp.size();
// 目标数组的索引值
int index = 0;
int currentSize = temp.size();
itemLoopNum = total / now;
loopPerItem = total / (itemLoopNum * currentSize);
int myindex = 0;
for (int j = 0; j < temp.size(); j++) {
// 每个元素循环的总次数
for (int k = 0; k < loopPerItem; k++) {
if (myindex == temp.size())
myindex = 0;
// 每个元素每次循环打印个数
for (int m = 0; m < itemLoopNum; m++) {
JSONArray rows = mysesult.getJSONArray(index);
rows.add(temp.get(myindex));
mysesult.set(index, rows);
index++;
}
myindex++;
}
}
}
return mysesult;
}
/**
* 排列组合
*
* @param source
* "a,b,c|2,3|A,B,C"
* @return
*/
public static List<List<String>> getCombList(String source) {
String[] list = source.split("\\|");
List<List<String>> strs = new ArrayList<List<String>>();
for (int i = 0; i < list.length; i++) {
strs.add(Arrays.asList(list[i].split(",")));
}
return getCombList(strs);
}
/**
* 排列组合
*
* @param strs
* [["a","b","c"],["2","3"]]
* @return
*/
public static List<List<String>> getCombList(List<List<String>> strs) {
int total = 1;
for (int i = 0; i < strs.size(); i++) {
total *= strs.get(i).size();
}
List<List<String>> mysesult = new ArrayList<List<String>>();
for (int i = 0; i < total; i++) {
mysesult.add(new ArrayList<String>());
}
int now = 1;
// 每个元素每次循环打印个数
int itemLoopNum = 1;
// 每个元素循环的总次数
int loopPerItem = 1;
for (int i = 0; i < strs.size(); i++) {
List<String> temp = strs.get(i);
now = now * temp.size();
// 目标数组的索引值
int index = 0;
int currentSize = temp.size();
itemLoopNum = total / now;
loopPerItem = total / (itemLoopNum * currentSize);
int myindex = 0;
for (int j = 0; j < temp.size(); j++) {
// 每个元素循环的总次数
for (int k = 0; k < loopPerItem; k++) {
if (myindex == temp.size())
myindex = 0;
// 每个元素每次循环打印个数
for (int m = 0; m < itemLoopNum; m++) {
List<String> rows = mysesult.get(index);
rows.add(temp.get(myindex));
mysesult.set(index, rows);
index++;
}
myindex++;
}
}
}
return mysesult;
}
public static void main(String[] args) {
System.out.println(getRand(3, 999));
System.out.println(getUniqueRandArray(3, 0, 3));
}
}
| false |
57674_0 | package com.itheima.ifdemo;
import java.util.Scanner;
public class IfDemo1 {
public static void main(String[] args) {
//键盘录入女婿酒量,如果大于2斤,老丈人给出回应,反之不回应
Scanner sc = new Scanner (System.in);
System.out.println ("请输入女婿酒量:");
int wine = sc.nextInt();
if (wine > 2) {
System.out.println ("小伙子,不错呦!");
}
}
}
| Angelfishxy/JAVA21_Basic | day04/src/com/itheima/ifdemo/IfDemo1.java | 140 | //键盘录入女婿酒量,如果大于2斤,老丈人给出回应,反之不回应 | line_comment | zh-cn | package com.itheima.ifdemo;
import java.util.Scanner;
public class IfDemo1 {
public static void main(String[] args) {
//键盘 <SUF>
Scanner sc = new Scanner (System.in);
System.out.println ("请输入女婿酒量:");
int wine = sc.nextInt();
if (wine > 2) {
System.out.println ("小伙子,不错呦!");
}
}
}
| true |
24111_2 | package javaleetcode.sort;
/**
* @authorAdministrator
* @date2024/1/8 0008 10:51
* @description
*/
/**
* 时间复杂度为O(n^2)的排序算法
* TODO
* */
public class Onlogn {
public static void shellSort(int[] arr) {
// 间隔序列,在希尔排序中我们称之为增量序列
for (int gap = arr.length / 2; gap > 0; gap /= 2) {
// 分组
for (int groupStartIndex = 0; groupStartIndex < gap; groupStartIndex++) {
// 插入排序
for (int currentIndex = groupStartIndex + gap; currentIndex < arr.length; currentIndex += gap) {
// currentNumber 站起来,开始找位置
int currentNumber = arr[currentIndex];
int preIndex = currentIndex - gap;
while (preIndex >= groupStartIndex && currentNumber < arr[preIndex]) {
// 向后挪位置
arr[preIndex + gap] = arr[preIndex];
preIndex -= gap;
}
// currentNumber 找到了自己的位置,坐下
arr[preIndex + gap] = currentNumber;
}
}
}
}
}
| AngryXZC/LeetCode- | JavaLeetCode/app/src/main/java/javaleetcode/sort/Onlogn.java | 293 | // 间隔序列,在希尔排序中我们称之为增量序列 | line_comment | zh-cn | package javaleetcode.sort;
/**
* @authorAdministrator
* @date2024/1/8 0008 10:51
* @description
*/
/**
* 时间复杂度为O(n^2)的排序算法
* TODO
* */
public class Onlogn {
public static void shellSort(int[] arr) {
// 间隔 <SUF>
for (int gap = arr.length / 2; gap > 0; gap /= 2) {
// 分组
for (int groupStartIndex = 0; groupStartIndex < gap; groupStartIndex++) {
// 插入排序
for (int currentIndex = groupStartIndex + gap; currentIndex < arr.length; currentIndex += gap) {
// currentNumber 站起来,开始找位置
int currentNumber = arr[currentIndex];
int preIndex = currentIndex - gap;
while (preIndex >= groupStartIndex && currentNumber < arr[preIndex]) {
// 向后挪位置
arr[preIndex + gap] = arr[preIndex];
preIndex -= gap;
}
// currentNumber 找到了自己的位置,坐下
arr[preIndex + gap] = currentNumber;
}
}
}
}
}
| false |
17961_6 | /**
* BCPlan.java
* 订阅计划
* Created by xuanzhui on 2016/7/28.
* Copyright (c) 2016 BeeCloud. All rights reserved.
*/
package cn.beecloud.entity;
import java.util.Map;
public class BCPlan {
/**
* 订阅计划的唯一标识
*/
private String id;
/**
* 扣款单价
*/
private Integer fee;
/**
* 扣款周期,只可以是:day, week, month or year
*/
private String interval;
/**
* 计划名
*/
private String name;
/**
* ISO货币名,如'CNY'代表人民币
*/
private String currency;
/**
* 扣款周期间隔数,例如interval为month,这边设置为3,
* 那么每3个月扣款,订阅系统默认1
*/
private Integer interval_count;
/**
* 试用天数
*/
private Integer trial_days;
/**
* map类型附加信息
*/
private Map<String, Object> optional;
/**
* 计划是否生效
*/
private Boolean valid;
/**
* @return 订阅计划的唯一标识
*/
public String getId() {
return id;
}
/**
* @return 扣款单价,分为单位
*/
public Integer getFee() {
return fee;
}
/**
* @param fee 扣款单价,分为单位
*/
public void setFee(Integer fee) {
this.fee = fee;
}
/**
* @return 扣款周期:day, week, month or year.
*/
public String getInterval() {
return interval;
}
/**
* @param interval 扣款周期: 只可以是字符串 day, week, month or year.
*/
public void setInterval(String interval) {
this.interval = interval;
}
/**
* @return 计划名
*/
public String getName() {
return name;
}
/**
* @param name 计划名
*/
public void setName(String name) {
this.name = name;
}
/**
* @return ISO货币名,如'CNY'
*/
public String getCurrency() {
return currency;
}
/**
* @param currency ISO货币名,如'CNY'
*/
public void setCurrency(String currency) {
this.currency = currency;
}
/**
* @return 扣款周期间隔数
*/
public Integer getIntervalCount() {
return interval_count;
}
/**
* @param intervalCount 扣款周期间隔数,例如interval为month,这边设置为3,
* 那么每3个月扣款,订阅系统默认1
*/
public void setIntervalCount(Integer intervalCount) {
this.interval_count = intervalCount;
}
/**
* @return 试用天数
*/
public Integer getTrialDays() {
return trial_days;
}
/**
* @param trialDays 试用天数
*/
public void setTrialDays(Integer trialDays) {
this.trial_days = trialDays;
}
/**
* @return map类型附加信息
*/
public Map<String, Object> getOptional() {
return optional;
}
/**
* @param optional map类型附加信息
*/
public void setOptional(Map<String, Object> optional) {
this.optional = optional;
}
/**
* @return 计划是否生效
*/
public boolean isValid() {
return valid != null && valid;
}
}
| Anjiefan/flutter_campus_social_app | android/sdk/src/main/java/cn/beecloud/entity/BCPlan.java | 856 | /**
* 扣款周期间隔数,例如interval为month,这边设置为3,
* 那么每3个月扣款,订阅系统默认1
*/ | block_comment | zh-cn | /**
* BCPlan.java
* 订阅计划
* Created by xuanzhui on 2016/7/28.
* Copyright (c) 2016 BeeCloud. All rights reserved.
*/
package cn.beecloud.entity;
import java.util.Map;
public class BCPlan {
/**
* 订阅计划的唯一标识
*/
private String id;
/**
* 扣款单价
*/
private Integer fee;
/**
* 扣款周期,只可以是:day, week, month or year
*/
private String interval;
/**
* 计划名
*/
private String name;
/**
* ISO货币名,如'CNY'代表人民币
*/
private String currency;
/**
* 扣款周 <SUF>*/
private Integer interval_count;
/**
* 试用天数
*/
private Integer trial_days;
/**
* map类型附加信息
*/
private Map<String, Object> optional;
/**
* 计划是否生效
*/
private Boolean valid;
/**
* @return 订阅计划的唯一标识
*/
public String getId() {
return id;
}
/**
* @return 扣款单价,分为单位
*/
public Integer getFee() {
return fee;
}
/**
* @param fee 扣款单价,分为单位
*/
public void setFee(Integer fee) {
this.fee = fee;
}
/**
* @return 扣款周期:day, week, month or year.
*/
public String getInterval() {
return interval;
}
/**
* @param interval 扣款周期: 只可以是字符串 day, week, month or year.
*/
public void setInterval(String interval) {
this.interval = interval;
}
/**
* @return 计划名
*/
public String getName() {
return name;
}
/**
* @param name 计划名
*/
public void setName(String name) {
this.name = name;
}
/**
* @return ISO货币名,如'CNY'
*/
public String getCurrency() {
return currency;
}
/**
* @param currency ISO货币名,如'CNY'
*/
public void setCurrency(String currency) {
this.currency = currency;
}
/**
* @return 扣款周期间隔数
*/
public Integer getIntervalCount() {
return interval_count;
}
/**
* @param intervalCount 扣款周期间隔数,例如interval为month,这边设置为3,
* 那么每3个月扣款,订阅系统默认1
*/
public void setIntervalCount(Integer intervalCount) {
this.interval_count = intervalCount;
}
/**
* @return 试用天数
*/
public Integer getTrialDays() {
return trial_days;
}
/**
* @param trialDays 试用天数
*/
public void setTrialDays(Integer trialDays) {
this.trial_days = trialDays;
}
/**
* @return map类型附加信息
*/
public Map<String, Object> getOptional() {
return optional;
}
/**
* @param optional map类型附加信息
*/
public void setOptional(Map<String, Object> optional) {
this.optional = optional;
}
/**
* @return 计划是否生效
*/
public boolean isValid() {
return valid != null && valid;
}
}
| false |
35857_30 | import android.graphics.Bitmap;
import java.io.InputStream;
import java.util.Vector;
public class GifDecoder {
/**
* 各帧静态图对象
*/
public static class GifFrame {
public Bitmap image;//静态图Bitmap
public int delay;//图像延迟时间
public GifFrame(Bitmap im, int del) {
image = im;
delay = del;
}
}
public static final int STATUS_OK = 0;//解码成功
public static final int STATUS_FORMAT_ERROR = 1;//格式错误
public static final int STATUS_OPEN_ERROR = 2;//打开图片失败
protected int status;//解码状态
protected InputStream in;
protected int width;//完整的GIF图像宽度
protected int height;//完整的GIF图像高度
protected boolean gctFlag;//是否使用了全局颜色列表
protected int gctSize; //全局颜色列表大小
protected int loopCount = 1; // iterations; 0 = repeat forever
protected int[] gct; //全局颜色列表
protected int[] lct; //局部颜色列表
protected int[] act; //当前使用的颜色列表
protected int bgIndex; //背景颜色索引
protected int bgColor; //背景颜色
protected int lastBgColor; // previous bg color
protected int pixelAspect; //像素宽高比(Pixel Aspect Radio)
protected boolean lctFlag;//局部颜色列表标志(Local Color Table Flag)
protected boolean interlace;//交织标志(Interlace Flag)
protected int lctSize;//局部颜色列表大小(Size of Local Color Table)
protected int ix, iy, iw, ih; //当前帧图像的xy偏移量及宽高
protected int lrx, lry, lrw, lrh;
protected Bitmap image; // current frame
protected Bitmap lastImage; // previous frame
protected int frameindex = 0;
public int getFrameindex() {
return frameindex;
}
public void setFrameindex(int frameindex) {
this.frameindex = frameindex;
if (frameindex > frames.size() - 1) {
frameindex = 0;
}
}
protected byte[] block = new byte[256]; // current data block
protected int blockSize = 0; //扩展块大小
// last graphic control extension info
protected int dispose = 0;
// 0=no action; 1=leave in place; 2=restore to bg; 3=restore to prev
protected int lastDispose = 0;
protected boolean transparency = false;//是否使用透明色
protected int delay = 0;//延迟时间(毫秒)
protected int transIndex;//透明色索引
protected static final int MaxStackSize = 4096;
// max decoder pixel stack size
// LZW decoder working arrays
protected short[] prefix;
protected byte[] suffix;
protected byte[] pixelStack;
protected byte[] pixels;
protected Vector<GifFrame> frames;// 存放各帧对象的数组
protected int frameCount;//帧数
// to get its Width / Height
public int getWidth() {
return width;
}
public int getHeigh() {
return height;
}
/**
* Gets display duration for specified frame.
*
* @param n
* int index of frame
* @return delay in milliseconds
*/
public int getDelay(int n) {
delay = -1;
if ((n >= 0) && (n < frameCount)) {
delay = ((GifFrame) frames.elementAt(n)).delay;
}
return delay;
}
public int getFrameCount() {
return frameCount;
}
public Bitmap getImage() {
return getFrame(0);
}
public int getLoopCount() {
return loopCount;
}
protected void setPixels() {
int[] dest = new int[width * height];
// fill in starting image contents based on last image's dispose code
if (lastDispose > 0) {
if (lastDispose == 3) {
// use image before last
int n = frameCount - 2;
if (n > 0) {
lastImage = getFrame(n - 1);
} else {
lastImage = null;
}
}
if (lastImage != null) {
lastImage.getPixels(dest, 0, width, 0, 0, width, height);
// copy pixels
if (lastDispose == 2) {
// fill last image rect area with background color
int c = 0;
if (!transparency) {
c = lastBgColor;
}
for (int i = 0; i < lrh; i++) {
int n1 = (lry + i) * width + lrx;
int n2 = n1 + lrw;
for (int k = n1; k < n2; k++) {
dest[k] = c;
}
}
}
}
}
// copy each source line to the appropriate place in the destination
int pass = 1;
int inc = 8;
int iline = 0;
for (int i = 0; i < ih; i++) {
int line = i;
if (interlace) {
if (iline >= ih) {
pass++;
switch (pass) {
case 2:
iline = 4;
break;
case 3:
iline = 2;
inc = 4;
break;
case 4:
iline = 1;
inc = 2;
}
}
line = iline;
iline += inc;
}
line += iy;
if (line < height) {
int k = line * width;
int dx = k + ix; // start of line in dest
int dlim = dx + iw; // end of dest line
if ((k + width) < dlim) {
dlim = k + width; // past dest edge
}
int sx = i * iw; // start of line in source
while (dx < dlim) {
// map color and insert in destination
int index = ((int) pixels[sx++]) & 0xff;
int c = act[index];
if (c != 0) {
dest[dx] = c;
}
dx++;
}
}
}
image = Bitmap.createBitmap(dest, width, height, Bitmap.Config.RGB_565);
}
public Bitmap getFrame(int n) {
Bitmap im = null;
if ((n >= 0) && (n < frameCount)) {
im = ((GifFrame) frames.elementAt(n)).image;
}
return im;
}
public GifFrame[] getFrames() {
if (null != frames)
return frames.toArray(new GifFrame[0]);
return null;
}
public Bitmap nextBitmap() {
frameindex++;
if (frameindex > frames.size() - 1) {
frameindex = 0;
}
return ((GifFrame) frames.elementAt(frameindex)).image;
}
public int nextDelay() {
return ((GifFrame) frames.elementAt(frameindex)).delay;
}
/**
* 解码入口,读取GIF图片输入流
* @param is
* @return
*/
public int read(InputStream is) {
init();
if (is != null) {
in = is;
readHeader();
if (!err()) {
readContents();
if (frameCount < 0) {
status = STATUS_FORMAT_ERROR;
}
}
} else {
status = STATUS_OPEN_ERROR;
}
try {
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return status;
}
/**
* 解码图像数据
*/
protected void decodeImageData() {
int NullCode = -1;
int npix = iw * ih;
int available, clear, code_mask, code_size, end_of_information, in_code, old_code, bits, code, count, i, datum, data_size, first, top, bi, pi;
if ((pixels == null) || (pixels.length < npix)) {
pixels = new byte[npix]; // allocate new pixel array
}
if (prefix == null) {
prefix = new short[MaxStackSize];
}
if (suffix == null) {
suffix = new byte[MaxStackSize];
}
if (pixelStack == null) {
pixelStack = new byte[MaxStackSize + 1];
}
// Initialize GIF data stream decoder.
data_size = read();
clear = 1 << data_size;
end_of_information = clear + 1;
available = clear + 2;
old_code = NullCode;
code_size = data_size + 1;
code_mask = (1 << code_size) - 1;
for (code = 0; code < clear; code++) {
prefix[code] = 0;
suffix[code] = (byte) code;
}
// Decode GIF pixel stream.
datum = bits = count = first = top = pi = bi = 0;
for (i = 0; i < npix;) {
if (top == 0) {
if (bits < code_size) {
// Load bytes until there are enough bits for a code.
if (count == 0) {
// Read a new data block.
count = readBlock();
if (count <= 0) {
break;
}
bi = 0;
}
datum += (((int) block[bi]) & 0xff) << bits;
bits += 8;
bi++;
count--;
continue;
}
// Get the next code.
code = datum & code_mask;
datum >>= code_size;
bits -= code_size;
// Interpret the code
if ((code > available) || (code == end_of_information)) {
break;
}
if (code == clear) {
// Reset decoder.
code_size = data_size + 1;
code_mask = (1 << code_size) - 1;
available = clear + 2;
old_code = NullCode;
continue;
}
if (old_code == NullCode) {
pixelStack[top++] = suffix[code];
old_code = code;
first = code;
continue;
}
in_code = code;
if (code == available) {
pixelStack[top++] = (byte) first;
code = old_code;
}
while (code > clear) {
pixelStack[top++] = suffix[code];
code = prefix[code];
}
first = ((int) suffix[code]) & 0xff;
// Add a new string to the string table,
if (available >= MaxStackSize) {
break;
}
pixelStack[top++] = (byte) first;
prefix[available] = (short) old_code;
suffix[available] = (byte) first;
available++;
if (((available & code_mask) == 0)
&& (available < MaxStackSize)) {
code_size++;
code_mask += available;
}
old_code = in_code;
}
// Pop a pixel off the pixel stack.
top--;
pixels[pi++] = pixelStack[top];
i++;
}
for (i = pi; i < npix; i++) {
pixels[i] = 0; // clear missing pixels
}
}
/**
* 判断当前解码过程是否出错,若出错返回true
* @return
*/
protected boolean err() {
return status != STATUS_OK;
}
/**
* 初始化参数
*/
protected void init() {
status = STATUS_OK;
frameCount = 0;
frames = new Vector<GifFrame>();
gct = null;
lct = null;
}
/**
* 按顺序一个一个读取输入流字节,失败则设置读取失败状态码
* @return
*/
protected int read() {
int curByte = 0;
try {
curByte = in.read();
} catch (Exception e) {
status = STATUS_FORMAT_ERROR;
}
return curByte;
}
/**
* 读取扩展块(应用程序扩展块)
* @return
*/
protected int readBlock() {
blockSize = read();
int n = 0;
if (blockSize > 0) {
try {
int count = 0;
while (n < blockSize) {
count = in.read(block, n, blockSize - n);
if (count == -1) {
break;
}
n += count;
}
} catch (Exception e) {
e.printStackTrace();
}
if (n < blockSize) {
status = STATUS_FORMAT_ERROR;
}
}
return n;
}
/**
* 读取颜色列表
* @param ncolors 列表大小,即颜色数量
* @return
*/
protected int[] readColorTable(int ncolors) {
int nbytes = 3 * ncolors;//一个颜色占3个字节(r g b 各占1字节),因此占用空间为 颜色数量*3 字节
int[] tab = null;
byte[] c = new byte[nbytes];
int n = 0;
try {
n = in.read(c);
} catch (Exception e) {
e.printStackTrace();
}
if (n < nbytes) {
status = STATUS_FORMAT_ERROR;
} else {//开始解析颜色列表
tab = new int[256];//设置最大尺寸避免边界检查
int i = 0;
int j = 0;
while (i < ncolors) {
int r = ((int) c[j++]) & 0xff;
int g = ((int) c[j++]) & 0xff;
int b = ((int) c[j++]) & 0xff;
tab[i++] = 0xff000000 | (r << 16) | (g << 8) | b;
}
}
return tab;
}
/**
* 读取图像块内容
*/
protected void readContents() {
boolean done = false;
while (!(done || err())) {
int code = read();
switch (code) {
//图象标识符(Image Descriptor)开始
case 0x2C:
readImage();
break;
//扩展块开始
case 0x21: //扩展块标识,固定值0x21
code = read();
switch (code) {
case 0xf9: //图形控制扩展块标识(Graphic Control Label),固定值0xf9
readGraphicControlExt();
break;
case 0xff: //应用程序扩展块标识(Application Extension Label),固定值0xFF
readBlock();
String app = "";
for (int i = 0; i < 11; i++) {
app += (char) block[i];
}
if (app.equals("NETSCAPE2.0")) {
readNetscapeExt();
} else {
skip(); // don't care
}
break;
default: //其他扩展都选择跳过
skip();
}
break;
case 0x3b://标识GIF文件结束,固定值0x3B
done = true;
break;
case 0x00: //可能会出现的坏字节,可根据需要在此处编写坏字节分析等相关内容
break;
default:
status = STATUS_FORMAT_ERROR;
}
}
}
/**
* 读取图形控制扩展块
*/
protected void readGraphicControlExt() {
read();//按读取顺序,此处为块大小
int packed = read();//读取处置方法、用户输入标志等
dispose = (packed & 0x1c) >> 2; //从packed中解析出处置方法(Disposal Method)
if (dispose == 0) {
dispose = 1; //elect to keep old image if discretionary
}
transparency = (packed & 1) != 0;//从packed中解析出透明色标志
delay = readShort() * 10;//读取延迟时间(毫秒)
transIndex = read();//读取透明色索引
read();//按读取顺序,此处为标识块终结(Block Terminator)
}
/**
* 读取GIF 文件头、逻辑屏幕标识符、全局颜色列表
*/
protected void readHeader() {
//根据文件头判断是否GIF图片
String id = "";
for (int i = 0; i < 6; i++) {
id += (char) read();
}
if (!id.toUpperCase().startsWith("GIF")) {
status = STATUS_FORMAT_ERROR;
return;
}
//解析GIF逻辑屏幕标识符
readLSD();
//读取全局颜色列表
if (gctFlag && !err()) {
gct = readColorTable(gctSize);
bgColor = gct[bgIndex];//根据索引在全局颜色列表拿到背景颜色
}
}
/**
* 按顺序读取图像块数据:
* 图象标识符(Image Descriptor)
* 局部颜色列表(Local Color Table)(有的话)
* 基于颜色列表的图象数据(Table-Based Image Data)
*/
protected void readImage() {
/**
* 开始读取图象标识符(Image Descriptor)
*/
ix = readShort();//x方向偏移量
iy = readShort();//y方向偏移量
iw = readShort();//图像宽度
ih = readShort();//图像高度
int packed = read();
lctFlag = (packed & 0x80) != 0;//局部颜色列表标志(Local Color Table Flag)
interlace = (packed & 0x40) != 0;//交织标志(Interlace Flag)
// 3 - sort flag
// 4-5 - reserved
lctSize = 2 << (packed & 7);//局部颜色列表大小(Size of Local Color Table)
/**
* 开始读取局部颜色列表(Local Color Table)
*/
if (lctFlag) {
lct = readColorTable(lctSize);//解码局部颜色列表
act = lct;//若有局部颜色列表,则图象数据是基于局部颜色列表的
} else {
act = gct; //否则都以全局颜色列表为准
if (bgIndex == transIndex) {
bgColor = 0;
}
}
int save = 0;
if (transparency) {
save = act[transIndex];//保存透明色索引位置原来的颜色
act[transIndex] = 0;//根据索引位置设置透明颜色
}
if (act == null) {
status = STATUS_FORMAT_ERROR;//若没有颜色列表可用,则解码出错
}
if (err()) {
return;
}
/**
* 开始解码图像数据
*/
decodeImageData();
skip();
if (err()) {
return;
}
frameCount++;
image = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
setPixels(); //将像素数据转换为图像Bitmap
frames.addElement(new GifFrame(image, delay));//添加到帧图集合
// list
if (transparency) {
act[transIndex] = save;//重置回原来的颜色
}
resetFrame();
}
/**
* 读取逻辑屏幕标识符(Logical Screen Descriptor)与全局颜色列表(Global Color Table)
*/
protected void readLSD() {
//获取GIF图像宽高
width = readShort();
height = readShort();
/**
* 解析全局颜色列表(Global Color Table)的配置信息
* 配置信息占一个字节,具体各Bit存放的数据如下
* 7 6 5 4 3 2 1 0 BIT
* | m | cr | s | pixel |
*/
int packed = read();
gctFlag = (packed & 0x80) != 0;//判断是否有全局颜色列表(m,0x80在计算机内部表示为1000 0000)
gctSize = 2 << (packed & 7);//读取全局颜色列表大小(pixel)
//读取背景颜色索引和像素宽高比(Pixel Aspect Radio)
bgIndex = read();
pixelAspect = read();
}
protected void readNetscapeExt() {
do {
readBlock();
if (block[0] == 1) {
// loop count sub-block
int b1 = ((int) block[1]) & 0xff;
int b2 = ((int) block[2]) & 0xff;
loopCount = (b2 << 8) | b1;
}
} while ((blockSize > 0) && !err());
}
/**
* 读取两个字节的数据
* @return
*/
protected int readShort() {
return read() | (read() << 8);
}
protected void resetFrame() {
lastDispose = dispose;
lrx = ix;
lry = iy;
lrw = iw;
lrh = ih;
lastImage = image;
lastBgColor = bgColor;
dispose = 0;
transparency = false;
delay = 0;
lct = null;
}
/**
* Skips variable length blocks up to and including next zero length block.
*/
protected void skip() {
do {
readBlock();
} while ((blockSize > 0) && !err());
}
}
| AnliaLee/android-gif-analysis | GifDecoder.java | 4,951 | //延迟时间(毫秒) | line_comment | zh-cn | import android.graphics.Bitmap;
import java.io.InputStream;
import java.util.Vector;
public class GifDecoder {
/**
* 各帧静态图对象
*/
public static class GifFrame {
public Bitmap image;//静态图Bitmap
public int delay;//图像延迟时间
public GifFrame(Bitmap im, int del) {
image = im;
delay = del;
}
}
public static final int STATUS_OK = 0;//解码成功
public static final int STATUS_FORMAT_ERROR = 1;//格式错误
public static final int STATUS_OPEN_ERROR = 2;//打开图片失败
protected int status;//解码状态
protected InputStream in;
protected int width;//完整的GIF图像宽度
protected int height;//完整的GIF图像高度
protected boolean gctFlag;//是否使用了全局颜色列表
protected int gctSize; //全局颜色列表大小
protected int loopCount = 1; // iterations; 0 = repeat forever
protected int[] gct; //全局颜色列表
protected int[] lct; //局部颜色列表
protected int[] act; //当前使用的颜色列表
protected int bgIndex; //背景颜色索引
protected int bgColor; //背景颜色
protected int lastBgColor; // previous bg color
protected int pixelAspect; //像素宽高比(Pixel Aspect Radio)
protected boolean lctFlag;//局部颜色列表标志(Local Color Table Flag)
protected boolean interlace;//交织标志(Interlace Flag)
protected int lctSize;//局部颜色列表大小(Size of Local Color Table)
protected int ix, iy, iw, ih; //当前帧图像的xy偏移量及宽高
protected int lrx, lry, lrw, lrh;
protected Bitmap image; // current frame
protected Bitmap lastImage; // previous frame
protected int frameindex = 0;
public int getFrameindex() {
return frameindex;
}
public void setFrameindex(int frameindex) {
this.frameindex = frameindex;
if (frameindex > frames.size() - 1) {
frameindex = 0;
}
}
protected byte[] block = new byte[256]; // current data block
protected int blockSize = 0; //扩展块大小
// last graphic control extension info
protected int dispose = 0;
// 0=no action; 1=leave in place; 2=restore to bg; 3=restore to prev
protected int lastDispose = 0;
protected boolean transparency = false;//是否使用透明色
protected int delay = 0;//延迟 <SUF>
protected int transIndex;//透明色索引
protected static final int MaxStackSize = 4096;
// max decoder pixel stack size
// LZW decoder working arrays
protected short[] prefix;
protected byte[] suffix;
protected byte[] pixelStack;
protected byte[] pixels;
protected Vector<GifFrame> frames;// 存放各帧对象的数组
protected int frameCount;//帧数
// to get its Width / Height
public int getWidth() {
return width;
}
public int getHeigh() {
return height;
}
/**
* Gets display duration for specified frame.
*
* @param n
* int index of frame
* @return delay in milliseconds
*/
public int getDelay(int n) {
delay = -1;
if ((n >= 0) && (n < frameCount)) {
delay = ((GifFrame) frames.elementAt(n)).delay;
}
return delay;
}
public int getFrameCount() {
return frameCount;
}
public Bitmap getImage() {
return getFrame(0);
}
public int getLoopCount() {
return loopCount;
}
protected void setPixels() {
int[] dest = new int[width * height];
// fill in starting image contents based on last image's dispose code
if (lastDispose > 0) {
if (lastDispose == 3) {
// use image before last
int n = frameCount - 2;
if (n > 0) {
lastImage = getFrame(n - 1);
} else {
lastImage = null;
}
}
if (lastImage != null) {
lastImage.getPixels(dest, 0, width, 0, 0, width, height);
// copy pixels
if (lastDispose == 2) {
// fill last image rect area with background color
int c = 0;
if (!transparency) {
c = lastBgColor;
}
for (int i = 0; i < lrh; i++) {
int n1 = (lry + i) * width + lrx;
int n2 = n1 + lrw;
for (int k = n1; k < n2; k++) {
dest[k] = c;
}
}
}
}
}
// copy each source line to the appropriate place in the destination
int pass = 1;
int inc = 8;
int iline = 0;
for (int i = 0; i < ih; i++) {
int line = i;
if (interlace) {
if (iline >= ih) {
pass++;
switch (pass) {
case 2:
iline = 4;
break;
case 3:
iline = 2;
inc = 4;
break;
case 4:
iline = 1;
inc = 2;
}
}
line = iline;
iline += inc;
}
line += iy;
if (line < height) {
int k = line * width;
int dx = k + ix; // start of line in dest
int dlim = dx + iw; // end of dest line
if ((k + width) < dlim) {
dlim = k + width; // past dest edge
}
int sx = i * iw; // start of line in source
while (dx < dlim) {
// map color and insert in destination
int index = ((int) pixels[sx++]) & 0xff;
int c = act[index];
if (c != 0) {
dest[dx] = c;
}
dx++;
}
}
}
image = Bitmap.createBitmap(dest, width, height, Bitmap.Config.RGB_565);
}
public Bitmap getFrame(int n) {
Bitmap im = null;
if ((n >= 0) && (n < frameCount)) {
im = ((GifFrame) frames.elementAt(n)).image;
}
return im;
}
public GifFrame[] getFrames() {
if (null != frames)
return frames.toArray(new GifFrame[0]);
return null;
}
public Bitmap nextBitmap() {
frameindex++;
if (frameindex > frames.size() - 1) {
frameindex = 0;
}
return ((GifFrame) frames.elementAt(frameindex)).image;
}
public int nextDelay() {
return ((GifFrame) frames.elementAt(frameindex)).delay;
}
/**
* 解码入口,读取GIF图片输入流
* @param is
* @return
*/
public int read(InputStream is) {
init();
if (is != null) {
in = is;
readHeader();
if (!err()) {
readContents();
if (frameCount < 0) {
status = STATUS_FORMAT_ERROR;
}
}
} else {
status = STATUS_OPEN_ERROR;
}
try {
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return status;
}
/**
* 解码图像数据
*/
protected void decodeImageData() {
int NullCode = -1;
int npix = iw * ih;
int available, clear, code_mask, code_size, end_of_information, in_code, old_code, bits, code, count, i, datum, data_size, first, top, bi, pi;
if ((pixels == null) || (pixels.length < npix)) {
pixels = new byte[npix]; // allocate new pixel array
}
if (prefix == null) {
prefix = new short[MaxStackSize];
}
if (suffix == null) {
suffix = new byte[MaxStackSize];
}
if (pixelStack == null) {
pixelStack = new byte[MaxStackSize + 1];
}
// Initialize GIF data stream decoder.
data_size = read();
clear = 1 << data_size;
end_of_information = clear + 1;
available = clear + 2;
old_code = NullCode;
code_size = data_size + 1;
code_mask = (1 << code_size) - 1;
for (code = 0; code < clear; code++) {
prefix[code] = 0;
suffix[code] = (byte) code;
}
// Decode GIF pixel stream.
datum = bits = count = first = top = pi = bi = 0;
for (i = 0; i < npix;) {
if (top == 0) {
if (bits < code_size) {
// Load bytes until there are enough bits for a code.
if (count == 0) {
// Read a new data block.
count = readBlock();
if (count <= 0) {
break;
}
bi = 0;
}
datum += (((int) block[bi]) & 0xff) << bits;
bits += 8;
bi++;
count--;
continue;
}
// Get the next code.
code = datum & code_mask;
datum >>= code_size;
bits -= code_size;
// Interpret the code
if ((code > available) || (code == end_of_information)) {
break;
}
if (code == clear) {
// Reset decoder.
code_size = data_size + 1;
code_mask = (1 << code_size) - 1;
available = clear + 2;
old_code = NullCode;
continue;
}
if (old_code == NullCode) {
pixelStack[top++] = suffix[code];
old_code = code;
first = code;
continue;
}
in_code = code;
if (code == available) {
pixelStack[top++] = (byte) first;
code = old_code;
}
while (code > clear) {
pixelStack[top++] = suffix[code];
code = prefix[code];
}
first = ((int) suffix[code]) & 0xff;
// Add a new string to the string table,
if (available >= MaxStackSize) {
break;
}
pixelStack[top++] = (byte) first;
prefix[available] = (short) old_code;
suffix[available] = (byte) first;
available++;
if (((available & code_mask) == 0)
&& (available < MaxStackSize)) {
code_size++;
code_mask += available;
}
old_code = in_code;
}
// Pop a pixel off the pixel stack.
top--;
pixels[pi++] = pixelStack[top];
i++;
}
for (i = pi; i < npix; i++) {
pixels[i] = 0; // clear missing pixels
}
}
/**
* 判断当前解码过程是否出错,若出错返回true
* @return
*/
protected boolean err() {
return status != STATUS_OK;
}
/**
* 初始化参数
*/
protected void init() {
status = STATUS_OK;
frameCount = 0;
frames = new Vector<GifFrame>();
gct = null;
lct = null;
}
/**
* 按顺序一个一个读取输入流字节,失败则设置读取失败状态码
* @return
*/
protected int read() {
int curByte = 0;
try {
curByte = in.read();
} catch (Exception e) {
status = STATUS_FORMAT_ERROR;
}
return curByte;
}
/**
* 读取扩展块(应用程序扩展块)
* @return
*/
protected int readBlock() {
blockSize = read();
int n = 0;
if (blockSize > 0) {
try {
int count = 0;
while (n < blockSize) {
count = in.read(block, n, blockSize - n);
if (count == -1) {
break;
}
n += count;
}
} catch (Exception e) {
e.printStackTrace();
}
if (n < blockSize) {
status = STATUS_FORMAT_ERROR;
}
}
return n;
}
/**
* 读取颜色列表
* @param ncolors 列表大小,即颜色数量
* @return
*/
protected int[] readColorTable(int ncolors) {
int nbytes = 3 * ncolors;//一个颜色占3个字节(r g b 各占1字节),因此占用空间为 颜色数量*3 字节
int[] tab = null;
byte[] c = new byte[nbytes];
int n = 0;
try {
n = in.read(c);
} catch (Exception e) {
e.printStackTrace();
}
if (n < nbytes) {
status = STATUS_FORMAT_ERROR;
} else {//开始解析颜色列表
tab = new int[256];//设置最大尺寸避免边界检查
int i = 0;
int j = 0;
while (i < ncolors) {
int r = ((int) c[j++]) & 0xff;
int g = ((int) c[j++]) & 0xff;
int b = ((int) c[j++]) & 0xff;
tab[i++] = 0xff000000 | (r << 16) | (g << 8) | b;
}
}
return tab;
}
/**
* 读取图像块内容
*/
protected void readContents() {
boolean done = false;
while (!(done || err())) {
int code = read();
switch (code) {
//图象标识符(Image Descriptor)开始
case 0x2C:
readImage();
break;
//扩展块开始
case 0x21: //扩展块标识,固定值0x21
code = read();
switch (code) {
case 0xf9: //图形控制扩展块标识(Graphic Control Label),固定值0xf9
readGraphicControlExt();
break;
case 0xff: //应用程序扩展块标识(Application Extension Label),固定值0xFF
readBlock();
String app = "";
for (int i = 0; i < 11; i++) {
app += (char) block[i];
}
if (app.equals("NETSCAPE2.0")) {
readNetscapeExt();
} else {
skip(); // don't care
}
break;
default: //其他扩展都选择跳过
skip();
}
break;
case 0x3b://标识GIF文件结束,固定值0x3B
done = true;
break;
case 0x00: //可能会出现的坏字节,可根据需要在此处编写坏字节分析等相关内容
break;
default:
status = STATUS_FORMAT_ERROR;
}
}
}
/**
* 读取图形控制扩展块
*/
protected void readGraphicControlExt() {
read();//按读取顺序,此处为块大小
int packed = read();//读取处置方法、用户输入标志等
dispose = (packed & 0x1c) >> 2; //从packed中解析出处置方法(Disposal Method)
if (dispose == 0) {
dispose = 1; //elect to keep old image if discretionary
}
transparency = (packed & 1) != 0;//从packed中解析出透明色标志
delay = readShort() * 10;//读取延迟时间(毫秒)
transIndex = read();//读取透明色索引
read();//按读取顺序,此处为标识块终结(Block Terminator)
}
/**
* 读取GIF 文件头、逻辑屏幕标识符、全局颜色列表
*/
protected void readHeader() {
//根据文件头判断是否GIF图片
String id = "";
for (int i = 0; i < 6; i++) {
id += (char) read();
}
if (!id.toUpperCase().startsWith("GIF")) {
status = STATUS_FORMAT_ERROR;
return;
}
//解析GIF逻辑屏幕标识符
readLSD();
//读取全局颜色列表
if (gctFlag && !err()) {
gct = readColorTable(gctSize);
bgColor = gct[bgIndex];//根据索引在全局颜色列表拿到背景颜色
}
}
/**
* 按顺序读取图像块数据:
* 图象标识符(Image Descriptor)
* 局部颜色列表(Local Color Table)(有的话)
* 基于颜色列表的图象数据(Table-Based Image Data)
*/
protected void readImage() {
/**
* 开始读取图象标识符(Image Descriptor)
*/
ix = readShort();//x方向偏移量
iy = readShort();//y方向偏移量
iw = readShort();//图像宽度
ih = readShort();//图像高度
int packed = read();
lctFlag = (packed & 0x80) != 0;//局部颜色列表标志(Local Color Table Flag)
interlace = (packed & 0x40) != 0;//交织标志(Interlace Flag)
// 3 - sort flag
// 4-5 - reserved
lctSize = 2 << (packed & 7);//局部颜色列表大小(Size of Local Color Table)
/**
* 开始读取局部颜色列表(Local Color Table)
*/
if (lctFlag) {
lct = readColorTable(lctSize);//解码局部颜色列表
act = lct;//若有局部颜色列表,则图象数据是基于局部颜色列表的
} else {
act = gct; //否则都以全局颜色列表为准
if (bgIndex == transIndex) {
bgColor = 0;
}
}
int save = 0;
if (transparency) {
save = act[transIndex];//保存透明色索引位置原来的颜色
act[transIndex] = 0;//根据索引位置设置透明颜色
}
if (act == null) {
status = STATUS_FORMAT_ERROR;//若没有颜色列表可用,则解码出错
}
if (err()) {
return;
}
/**
* 开始解码图像数据
*/
decodeImageData();
skip();
if (err()) {
return;
}
frameCount++;
image = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
setPixels(); //将像素数据转换为图像Bitmap
frames.addElement(new GifFrame(image, delay));//添加到帧图集合
// list
if (transparency) {
act[transIndex] = save;//重置回原来的颜色
}
resetFrame();
}
/**
* 读取逻辑屏幕标识符(Logical Screen Descriptor)与全局颜色列表(Global Color Table)
*/
protected void readLSD() {
//获取GIF图像宽高
width = readShort();
height = readShort();
/**
* 解析全局颜色列表(Global Color Table)的配置信息
* 配置信息占一个字节,具体各Bit存放的数据如下
* 7 6 5 4 3 2 1 0 BIT
* | m | cr | s | pixel |
*/
int packed = read();
gctFlag = (packed & 0x80) != 0;//判断是否有全局颜色列表(m,0x80在计算机内部表示为1000 0000)
gctSize = 2 << (packed & 7);//读取全局颜色列表大小(pixel)
//读取背景颜色索引和像素宽高比(Pixel Aspect Radio)
bgIndex = read();
pixelAspect = read();
}
protected void readNetscapeExt() {
do {
readBlock();
if (block[0] == 1) {
// loop count sub-block
int b1 = ((int) block[1]) & 0xff;
int b2 = ((int) block[2]) & 0xff;
loopCount = (b2 << 8) | b1;
}
} while ((blockSize > 0) && !err());
}
/**
* 读取两个字节的数据
* @return
*/
protected int readShort() {
return read() | (read() << 8);
}
protected void resetFrame() {
lastDispose = dispose;
lrx = ix;
lry = iy;
lrw = iw;
lrh = ih;
lastImage = image;
lastBgColor = bgColor;
dispose = 0;
transparency = false;
delay = 0;
lct = null;
}
/**
* Skips variable length blocks up to and including next zero length block.
*/
protected void skip() {
do {
readBlock();
} while ((blockSize > 0) && !err());
}
}
| false |
55517_3 | package day19;
import java.util.Objects;
//Cloneable是一个标记接口 , 规则
public class Student implements Cloneable {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
protected Object clone() throws CloneNotSupportedException {
//去调用父类object中的clone方法
return super.clone();
}
/**
* 重写equals方法,比较两个对象的内容,一样就返回true
* 比较者 this
* 被比较者 o
*
* @param o
* @return
*/
@Override
public boolean equals(Object o) {
//1.比较两个对象的地址是否一样,一样直接true
if (this == o) return true;
//2. 判断o是null直接返回false,或者比较他们两者的类型不一样直接返回false
if (o == null || getClass() != o.getClass()) return false;
//3. o 不是null,且o一定是Student学生类型的对象的话,开始比较内容了。
Student student = (Student) o;
return age == student.age && Objects.equals(name, student.name);
}
}
| AnswerExplanationAll/IDEA_JAVA_Project_Study | src/day19/Student.java | 383 | //1.比较两个对象的地址是否一样,一样直接true | line_comment | zh-cn | package day19;
import java.util.Objects;
//Cloneable是一个标记接口 , 规则
public class Student implements Cloneable {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
protected Object clone() throws CloneNotSupportedException {
//去调用父类object中的clone方法
return super.clone();
}
/**
* 重写equals方法,比较两个对象的内容,一样就返回true
* 比较者 this
* 被比较者 o
*
* @param o
* @return
*/
@Override
public boolean equals(Object o) {
//1. <SUF>
if (this == o) return true;
//2. 判断o是null直接返回false,或者比较他们两者的类型不一样直接返回false
if (o == null || getClass() != o.getClass()) return false;
//3. o 不是null,且o一定是Student学生类型的对象的话,开始比较内容了。
Student student = (Student) o;
return age == student.age && Objects.equals(name, student.name);
}
}
| false |
46516_11 | import java.util.Arrays;
public class ClosestAntennaPair {
private double closestDistance = Double.POSITIVE_INFINITY;
private long counter = 0;
public ClosestAntennaPair(Point2D[] aPoints, Point2D[] bPoints) {
// Insert your solution here.
/**
* aPoints
*/
int an = aPoints.length;
if (an <= 0) return;
Point2D[] aPointsSortedByX = new Point2D[an];
for (int i = 0; i < an; i++)
aPointsSortedByX[i] = aPoints[i];
Arrays.sort(aPointsSortedByX, Point2D.Y_ORDER);
Arrays.sort(aPointsSortedByX, Point2D.X_ORDER);
/**
* bPoints
*/
int bn = bPoints.length;
if (bn <= 0) return;
Point2D[] bPointsSortedByX = new Point2D[bn];
for (int i = 0; i < bn; i++)
bPointsSortedByX[i] = bPoints[i];
Arrays.sort(bPointsSortedByX, Point2D.Y_ORDER);
Arrays.sort(bPointsSortedByX, Point2D.X_ORDER);
/**
* // set up the array that eventually will hold the points sorted by y-coordinate
*/
Point2D[] aPointsSortedByY = new Point2D[an];
for (int i = 0; i < an; i++)
aPointsSortedByY[i] = aPointsSortedByX[i];
Point2D[] bPointsSortedByY = new Point2D[bn];
for (int i = 0; i < bn; i++)
bPointsSortedByY[i] = bPointsSortedByX[i];
// auxiliary array
Point2D[] auxA = new Point2D[an];
Point2D[] auxB = new Point2D[bn];
closest(aPointsSortedByX, bPointsSortedByX, aPointsSortedByY, bPointsSortedByY, auxA, auxB, 0, 0, an-1, bn-1);
}
public double closest(Point2D[] aPointsSortedByX, Point2D[] bPointsSortedByX, // a/b sorted by X
Point2D[] aPointsSortedByY, Point2D[] bPointsSortedByY, // a/b sorted by y
Point2D[] auxA, Point2D[] auxB, // a/b auxiliary array
int lowA, int lowB, int highA, int highB) { // a/b's lowest/highest indices
// high/low means the indices of the array list
// please do not delete/modify the next line!
counter++;
if(highA<lowA || highB<lowB) { //悲剧结局,没点
closestDistance = Double.POSITIVE_INFINITY;
return closestDistance;
}
if(highA==lowA && highB==lowB) { //轻松结局,都一个
double distance = aPointsSortedByX[0].distanceTo(bPointsSortedByX[0]);
if(distance<closestDistance) {
closestDistance = distance;
return closestDistance;
}else {
return distance;
}
}
if(highA==lowA) { //一个A,
for(int i = lowB; i<=highB;i++) {
double distance = bPointsSortedByX[i].distanceTo(aPointsSortedByX[0]);
if(distance<closestDistance) {
closestDistance =distance;
}
}
return closestDistance;
}
if(highB==lowB) { //一个B,
for(int i = lowA; i<=highA;i++) {
double distance = aPointsSortedByX[i].distanceTo(bPointsSortedByX[lowB]);
if(distance<closestDistance) {
closestDistance =distance;
}
}
return closestDistance;
}
if(highA>lowA) { //一群A,先干A,B不止一个
int midA = lowA + (highA - lowA) / 2; // if low==high then mid==low
Point2D median = aPointsSortedByX[midA];
double delta1 = closest(aPointsSortedByX, bPointsSortedByX, aPointsSortedByY, bPointsSortedByY, auxA, auxB, lowA, lowB, midA, highB);
double delta2 = closest(aPointsSortedByX, bPointsSortedByX, aPointsSortedByY, bPointsSortedByY, auxA, auxB, midA+1, lowB, highA, highB);
double delta = Math.min(delta1, delta2);
merge(aPointsSortedByY, auxA, lowA, midA, highA);
int midB = lowB + (highB - lowB) / 2;
merge(bPointsSortedByY,auxB,lowB,midB,highB);
int m = 0;
int m2 = 0;
for (int i = lowA; i <= highA; i++) {
if (Math.abs(aPointsSortedByY[i].x() - median.x()) < delta) {
auxA[m] = aPointsSortedByY[i];
m++;
}
}//如果点的 x 在median附近小于delta的范围,则写入array aux----之后会从上到下走一编y value to check the new min
for (int i = lowB; i <= highB; i++) {
if (Math.abs(bPointsSortedByY[i].x() - median.x()) < delta) {
auxB[m2] = bPointsSortedByY[i];
m2++;
}
}//如果点的 x 在median附近小于delta的范围,则写入array aux----之后会从上到下走一编y value to check the new min
for (int i = 0; i <
m; i++) {
for (int j = 0; (j < m2); j++) {
double distance = auxA[i].distanceTo(auxB[j]);
if (distance < delta) {
delta = distance;
if (distance < closestDistance) {
closestDistance = delta;
return closestDistance;
}else {
return delta;
}
}
}
}
}
return closestDistance;
}
public double distance() {
return closestDistance;
}
public long getCounter() {
return counter;
}
// stably merge a[low .. mid] with a[mid+1 ..high] using aux[low .. high]
// precondition: a[low .. mid] and a[mid+1 .. high] are sorted subarrays, namely sorted by y coordinate
// this is the same as in ClosestPair
private static void merge(Point2D[] a, Point2D[] aux, int low, int mid, int high) {
// copy to aux[]
// note this wipes out any values that were previously in aux in the [low,high] range we're currently using
for (int k = low; k <= high; k++) {
aux[k] = a[k];
}
int i = low, j = mid + 1;
for (int k = low; k <= high; k++) {
if (i > mid) a[k] = aux[j++]; // already finished with the low list ? then dump the rest of high list
else if (j > high) a[k] = aux[i++]; // already finished with the high list ? then dump the rest of low list
else if (aux[i].compareByY(aux[j]) < 0)
a[k] = aux[i++]; // aux[i] should be in front of aux[j] ? position and increment the pointer
else a[k] = aux[j++];
}
}
}
| AntiAntonyZhao/Introduction-to-Java | A3/ClosestAntennaPair.java | 1,971 | //悲剧结局,没点 | line_comment | zh-cn | import java.util.Arrays;
public class ClosestAntennaPair {
private double closestDistance = Double.POSITIVE_INFINITY;
private long counter = 0;
public ClosestAntennaPair(Point2D[] aPoints, Point2D[] bPoints) {
// Insert your solution here.
/**
* aPoints
*/
int an = aPoints.length;
if (an <= 0) return;
Point2D[] aPointsSortedByX = new Point2D[an];
for (int i = 0; i < an; i++)
aPointsSortedByX[i] = aPoints[i];
Arrays.sort(aPointsSortedByX, Point2D.Y_ORDER);
Arrays.sort(aPointsSortedByX, Point2D.X_ORDER);
/**
* bPoints
*/
int bn = bPoints.length;
if (bn <= 0) return;
Point2D[] bPointsSortedByX = new Point2D[bn];
for (int i = 0; i < bn; i++)
bPointsSortedByX[i] = bPoints[i];
Arrays.sort(bPointsSortedByX, Point2D.Y_ORDER);
Arrays.sort(bPointsSortedByX, Point2D.X_ORDER);
/**
* // set up the array that eventually will hold the points sorted by y-coordinate
*/
Point2D[] aPointsSortedByY = new Point2D[an];
for (int i = 0; i < an; i++)
aPointsSortedByY[i] = aPointsSortedByX[i];
Point2D[] bPointsSortedByY = new Point2D[bn];
for (int i = 0; i < bn; i++)
bPointsSortedByY[i] = bPointsSortedByX[i];
// auxiliary array
Point2D[] auxA = new Point2D[an];
Point2D[] auxB = new Point2D[bn];
closest(aPointsSortedByX, bPointsSortedByX, aPointsSortedByY, bPointsSortedByY, auxA, auxB, 0, 0, an-1, bn-1);
}
public double closest(Point2D[] aPointsSortedByX, Point2D[] bPointsSortedByX, // a/b sorted by X
Point2D[] aPointsSortedByY, Point2D[] bPointsSortedByY, // a/b sorted by y
Point2D[] auxA, Point2D[] auxB, // a/b auxiliary array
int lowA, int lowB, int highA, int highB) { // a/b's lowest/highest indices
// high/low means the indices of the array list
// please do not delete/modify the next line!
counter++;
if(highA<lowA || highB<lowB) { //悲剧 <SUF>
closestDistance = Double.POSITIVE_INFINITY;
return closestDistance;
}
if(highA==lowA && highB==lowB) { //轻松结局,都一个
double distance = aPointsSortedByX[0].distanceTo(bPointsSortedByX[0]);
if(distance<closestDistance) {
closestDistance = distance;
return closestDistance;
}else {
return distance;
}
}
if(highA==lowA) { //一个A,
for(int i = lowB; i<=highB;i++) {
double distance = bPointsSortedByX[i].distanceTo(aPointsSortedByX[0]);
if(distance<closestDistance) {
closestDistance =distance;
}
}
return closestDistance;
}
if(highB==lowB) { //一个B,
for(int i = lowA; i<=highA;i++) {
double distance = aPointsSortedByX[i].distanceTo(bPointsSortedByX[lowB]);
if(distance<closestDistance) {
closestDistance =distance;
}
}
return closestDistance;
}
if(highA>lowA) { //一群A,先干A,B不止一个
int midA = lowA + (highA - lowA) / 2; // if low==high then mid==low
Point2D median = aPointsSortedByX[midA];
double delta1 = closest(aPointsSortedByX, bPointsSortedByX, aPointsSortedByY, bPointsSortedByY, auxA, auxB, lowA, lowB, midA, highB);
double delta2 = closest(aPointsSortedByX, bPointsSortedByX, aPointsSortedByY, bPointsSortedByY, auxA, auxB, midA+1, lowB, highA, highB);
double delta = Math.min(delta1, delta2);
merge(aPointsSortedByY, auxA, lowA, midA, highA);
int midB = lowB + (highB - lowB) / 2;
merge(bPointsSortedByY,auxB,lowB,midB,highB);
int m = 0;
int m2 = 0;
for (int i = lowA; i <= highA; i++) {
if (Math.abs(aPointsSortedByY[i].x() - median.x()) < delta) {
auxA[m] = aPointsSortedByY[i];
m++;
}
}//如果点的 x 在median附近小于delta的范围,则写入array aux----之后会从上到下走一编y value to check the new min
for (int i = lowB; i <= highB; i++) {
if (Math.abs(bPointsSortedByY[i].x() - median.x()) < delta) {
auxB[m2] = bPointsSortedByY[i];
m2++;
}
}//如果点的 x 在median附近小于delta的范围,则写入array aux----之后会从上到下走一编y value to check the new min
for (int i = 0; i <
m; i++) {
for (int j = 0; (j < m2); j++) {
double distance = auxA[i].distanceTo(auxB[j]);
if (distance < delta) {
delta = distance;
if (distance < closestDistance) {
closestDistance = delta;
return closestDistance;
}else {
return delta;
}
}
}
}
}
return closestDistance;
}
public double distance() {
return closestDistance;
}
public long getCounter() {
return counter;
}
// stably merge a[low .. mid] with a[mid+1 ..high] using aux[low .. high]
// precondition: a[low .. mid] and a[mid+1 .. high] are sorted subarrays, namely sorted by y coordinate
// this is the same as in ClosestPair
private static void merge(Point2D[] a, Point2D[] aux, int low, int mid, int high) {
// copy to aux[]
// note this wipes out any values that were previously in aux in the [low,high] range we're currently using
for (int k = low; k <= high; k++) {
aux[k] = a[k];
}
int i = low, j = mid + 1;
for (int k = low; k <= high; k++) {
if (i > mid) a[k] = aux[j++]; // already finished with the low list ? then dump the rest of high list
else if (j > high) a[k] = aux[i++]; // already finished with the high list ? then dump the rest of low list
else if (aux[i].compareByY(aux[j]) < 0)
a[k] = aux[i++]; // aux[i] should be in front of aux[j] ? position and increment the pointer
else a[k] = aux[j++];
}
}
}
| false |
32600_17 | package ThMod.characters;
import ThMod.ThMod;
import ThMod.cards.Cirno.Chirumiru;
import ThMod.patches.AbstractCardEnum;
import ThMod.patches.ThModClassEnum;
import basemod.abstracts.CustomPlayer;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.math.MathUtils;
import com.megacrit.cardcrawl.actions.AbstractGameAction.AttackEffect;
import com.megacrit.cardcrawl.cards.AbstractCard;
import com.megacrit.cardcrawl.cards.DamageInfo;
import com.megacrit.cardcrawl.characters.AbstractPlayer;
import com.megacrit.cardcrawl.core.CardCrawlGame;
import com.megacrit.cardcrawl.core.EnergyManager;
import com.megacrit.cardcrawl.core.Settings;
import com.megacrit.cardcrawl.core.Settings.GameLanguage;
import com.megacrit.cardcrawl.helpers.FontHelper;
import com.megacrit.cardcrawl.helpers.ImageMaster;
import com.megacrit.cardcrawl.helpers.ScreenShake;
import com.megacrit.cardcrawl.screens.CharSelectInfo;
import com.megacrit.cardcrawl.unlock.UnlockTracker;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.ArrayList;
public class Cirno extends CustomPlayer {
private static final int ENERGY_PER_TURN = 3; // how much energy you get every turn
private static final String CIRNO_SHOULDER_2 = "img/char/Cirno/shoulder2.png"; // shoulder2 / shoulder_1
private static final String CIRNO_SHOULDER_1 = "img/char/Cirno/shoulder1.png"; // shoulder1 / shoulder_2
private static final String CIRNO_CORPSE = "img/char/Cirno/fallen.png"; // dead corpse
public static final Logger logger = LogManager.getLogger(ThMod.class.getName());
//private static final float[] layerSpeeds = { 20.0F, 0.0F, -40.0F, 0.0F, 0.0F, 5.0F, 0.0F, -8.0F, 0.0F, 8.0F };
// private static final String CIRNO_SKELETON_ATLAS = "img/char/Cirno/MarisaModelv3.atlas";// Marisa_v0 / MarisaModel_v02 /MarisaModelv3
// private static final String CIRNO_SKELETON_JSON = "img/char/Cirno/MarisaModelv3.json";
private static final String CIRNO_ANIMATION = "Idle";// Sprite / Idle
private static final String[] ORB_TEXTURES = {
"img/UI/EPanel/layer5.png",
"img/UI/EPanel/layer4.png",
"img/UI/EPanel/layer3.png",
"img/UI/EPanel/layer2.png",
"img/UI/EPanel/layer1.png",
"img/UI/EPanel/layer0.png",
"img/UI/EPanel/layer5d.png",
"img/UI/EPanel/layer4d.png",
"img/UI/EPanel/layer3d.png",
"img/UI/EPanel/layer2d.png",
"img/UI/EPanel/layer1d.png"
};
private static final String ORB_VFX = "img/UI/energyBlueVFX.png";
private static final float[] LAYER_SPEED =
{-40.0F, -32.0F, 20.0F, -20.0F, 0.0F, -10.0F, -8.0F, 5.0F, -5.0F, 0.0F};
//public static final String SPRITER_ANIM_FILEPATH = "img/char/MyCharacter/marisa_test.scml"; // spriter animation scml
public Cirno(String name) {
//super(name, setClass, null, null , null ,new SpriterAnimation(SPRITER_ANIM_FILEPATH));
super(name, ThModClassEnum.CIRNO, ORB_TEXTURES, ORB_VFX, LAYER_SPEED, null, null);
//super(name, setClass, null, null, (String) null, null);
this.dialogX = (this.drawX + 0.0F * Settings.scale); // set location for text bubbles
this.dialogY = (this.drawY + 220.0F * Settings.scale); // you can just copy these values
logger.info("init Cirno");
initializeClass(
"img/char/Cirno/cirno.png",
CIRNO_SHOULDER_2, // required call to load textures and setup energy/loadout
CIRNO_SHOULDER_1,
CIRNO_CORPSE,
getLoadout(),
20.0F, -10.0F, 220.0F, 290.0F,
new EnergyManager(ENERGY_PER_TURN)
);
// loadAnimation(CIRNO_SKELETON_ATLAS, CIRNO_SKELETON_JSON, 2.0F);
// if you're using modified versions of base game animations or made animations in spine make sure to include this bit and the following lines
/*
AnimationState.TrackEntry e = this.state.setAnimation(0, CIRNO_ANIMATION, true);
e.setTime(e.getEndTime() * MathUtils.random());
this.stateData.setMix("Hit", "Idle", 0.1F);
e.setTimeScale(1.0F);
*/
logger.info("init finish");
}
public ArrayList<String> getStartingDeck() { // 初始卡组
ArrayList<String> ret = new ArrayList<>();
for (int i = 0; i < 5; i++)
ret.add("IceGrain");
for (int i = 0; i < 5; i++)
ret.add("IceBarrier");
ret.add("IcicleShot");
ret.add("ShowOff");
return ret;
}
public ArrayList<String> getStartingRelics() { // 初始遗物
ArrayList<String> ret = new ArrayList<>();
ret.add("CrystalWings");
UnlockTracker.markRelicAsSeen("CrystalWings");
return ret;
}
private static final int STARTING_HP = 69;
private static final int MAX_HP = 69;
private static final int STARTING_GOLD = 99;
private static final int HAND_SIZE = 5;
private static final int ASCENSION_MAX_HP_LOSS = 4;
public CharSelectInfo getLoadout() { // the rest of the character loadout so includes your character select screen info plus hp and starting gold
String title;
String flavor;
if (Settings.language == Settings.GameLanguage.ZHS || Settings.language == Settings.GameLanguage.ZHT) {
title = "琪露诺";
flavor = "居住在雾之湖的冰之妖精。笨蛋。";
} else {
title = "Cirno";
flavor = "Baka!";
}
return new CharSelectInfo(
title,
flavor,
STARTING_HP,
MAX_HP,
0,
STARTING_GOLD,
HAND_SIZE,
this,
getStartingRelics(),
getStartingDeck(),
false
);
}
public AbstractCard.CardColor getCardColor() {
return AbstractCardEnum.CIRNO_COLOR;
}
public AbstractCard getStartCardForEvent() {
return new Chirumiru();
}
public String getTitle(PlayerClass playerClass) {
String title;
if (Settings.language == GameLanguage.ZHS) {
title = "冰之小妖精";
} else {
title = "Little Ice Fairy";
}
return title;
}
public Color getCardTrailColor() {
return ThMod.CHILLED;
}
public int getAscensionMaxHPLoss() {
return ASCENSION_MAX_HP_LOSS;
}
public BitmapFont getEnergyNumFont() {
return FontHelper.energyNumFontBlue;
}
public void doCharSelectScreenSelectEffect() {
CardCrawlGame.sound.playA("SELECT_CIRNO", MathUtils.random(-0.1F, 0.1F));
CardCrawlGame.screenShake.shake(
ScreenShake.ShakeIntensity.MED,
ScreenShake.ShakeDur.SHORT,
false
);
}
public String getCustomModeCharacterButtonSoundKey() {
return "SELECT_CIRNO";
}
public String getLocalizedCharacterName() {
String char_name;
if ((Settings.language == Settings.GameLanguage.ZHS)
|| (Settings.language == Settings.GameLanguage.ZHT)) {
char_name = "琪露诺";
} else if (Settings.language == Settings.GameLanguage.JPN) {
char_name = "チルノ";
} else {
char_name = "Cirno";
}
return char_name;
}
public AbstractPlayer newInstance() {
return new Cirno(this.name);
}
@Override
public String getVampireText() {
return com.megacrit.cardcrawl.events.city.Vampires.DESCRIPTIONS[1];
}
public Color getCardRenderColor() {
return ThMod.CHILLED;
}
public void updateOrb(int orbCount) {
this.energyOrb.updateOrb(orbCount);
}
public TextureAtlas.AtlasRegion getOrb() {
return new TextureAtlas.AtlasRegion(ImageMaster.loadImage(ThMod.CARD_ENERGY_ORB), 0, 0, 24, 24);
}
public Color getSlashAttackColor() {
return ThMod.CHILLED;
}
public AttackEffect[] getSpireHeartSlashEffect() {
return new AttackEffect[]{
AttackEffect.SLASH_HEAVY,
AttackEffect.FIRE,
AttackEffect.SLASH_DIAGONAL,
AttackEffect.SLASH_HEAVY,
AttackEffect.FIRE,
AttackEffect.SLASH_DIAGONAL
};
}
public String getSpireHeartText() {
return com.megacrit.cardcrawl.events.beyond.SpireHeart.DESCRIPTIONS[10];
}
public void damage(DamageInfo info) {
// if ((info.owner != null) && (info.type != DamageInfo.DamageType.THORNS)
// && (info.output - this.currentBlock > 0)) {
// AnimationState.TrackEntry e = this.state.setAnimation(0, "Hit", false);
// this.state.addAnimation(0, "Idle", true, 0.0F);
// e.setTimeScale(1.0F);
// }
super.damage(info);
}
public void applyPreCombatLogic() {
super.applyPreCombatLogic();
// ThMod.typhoonCounter = 0;
// ThMod.logger.info(
// "Marisa : applyPreCombatLogic : I just reset the god damn typhoon counter ! current counter : "
// + ThMod.typhoonCounter
// );
}
}
| AntiLeaf/CirnoMod | src/main/java/ThMod/characters/Cirno.java | 2,956 | // 初始卡组 | line_comment | zh-cn | package ThMod.characters;
import ThMod.ThMod;
import ThMod.cards.Cirno.Chirumiru;
import ThMod.patches.AbstractCardEnum;
import ThMod.patches.ThModClassEnum;
import basemod.abstracts.CustomPlayer;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.math.MathUtils;
import com.megacrit.cardcrawl.actions.AbstractGameAction.AttackEffect;
import com.megacrit.cardcrawl.cards.AbstractCard;
import com.megacrit.cardcrawl.cards.DamageInfo;
import com.megacrit.cardcrawl.characters.AbstractPlayer;
import com.megacrit.cardcrawl.core.CardCrawlGame;
import com.megacrit.cardcrawl.core.EnergyManager;
import com.megacrit.cardcrawl.core.Settings;
import com.megacrit.cardcrawl.core.Settings.GameLanguage;
import com.megacrit.cardcrawl.helpers.FontHelper;
import com.megacrit.cardcrawl.helpers.ImageMaster;
import com.megacrit.cardcrawl.helpers.ScreenShake;
import com.megacrit.cardcrawl.screens.CharSelectInfo;
import com.megacrit.cardcrawl.unlock.UnlockTracker;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.ArrayList;
public class Cirno extends CustomPlayer {
private static final int ENERGY_PER_TURN = 3; // how much energy you get every turn
private static final String CIRNO_SHOULDER_2 = "img/char/Cirno/shoulder2.png"; // shoulder2 / shoulder_1
private static final String CIRNO_SHOULDER_1 = "img/char/Cirno/shoulder1.png"; // shoulder1 / shoulder_2
private static final String CIRNO_CORPSE = "img/char/Cirno/fallen.png"; // dead corpse
public static final Logger logger = LogManager.getLogger(ThMod.class.getName());
//private static final float[] layerSpeeds = { 20.0F, 0.0F, -40.0F, 0.0F, 0.0F, 5.0F, 0.0F, -8.0F, 0.0F, 8.0F };
// private static final String CIRNO_SKELETON_ATLAS = "img/char/Cirno/MarisaModelv3.atlas";// Marisa_v0 / MarisaModel_v02 /MarisaModelv3
// private static final String CIRNO_SKELETON_JSON = "img/char/Cirno/MarisaModelv3.json";
private static final String CIRNO_ANIMATION = "Idle";// Sprite / Idle
private static final String[] ORB_TEXTURES = {
"img/UI/EPanel/layer5.png",
"img/UI/EPanel/layer4.png",
"img/UI/EPanel/layer3.png",
"img/UI/EPanel/layer2.png",
"img/UI/EPanel/layer1.png",
"img/UI/EPanel/layer0.png",
"img/UI/EPanel/layer5d.png",
"img/UI/EPanel/layer4d.png",
"img/UI/EPanel/layer3d.png",
"img/UI/EPanel/layer2d.png",
"img/UI/EPanel/layer1d.png"
};
private static final String ORB_VFX = "img/UI/energyBlueVFX.png";
private static final float[] LAYER_SPEED =
{-40.0F, -32.0F, 20.0F, -20.0F, 0.0F, -10.0F, -8.0F, 5.0F, -5.0F, 0.0F};
//public static final String SPRITER_ANIM_FILEPATH = "img/char/MyCharacter/marisa_test.scml"; // spriter animation scml
public Cirno(String name) {
//super(name, setClass, null, null , null ,new SpriterAnimation(SPRITER_ANIM_FILEPATH));
super(name, ThModClassEnum.CIRNO, ORB_TEXTURES, ORB_VFX, LAYER_SPEED, null, null);
//super(name, setClass, null, null, (String) null, null);
this.dialogX = (this.drawX + 0.0F * Settings.scale); // set location for text bubbles
this.dialogY = (this.drawY + 220.0F * Settings.scale); // you can just copy these values
logger.info("init Cirno");
initializeClass(
"img/char/Cirno/cirno.png",
CIRNO_SHOULDER_2, // required call to load textures and setup energy/loadout
CIRNO_SHOULDER_1,
CIRNO_CORPSE,
getLoadout(),
20.0F, -10.0F, 220.0F, 290.0F,
new EnergyManager(ENERGY_PER_TURN)
);
// loadAnimation(CIRNO_SKELETON_ATLAS, CIRNO_SKELETON_JSON, 2.0F);
// if you're using modified versions of base game animations or made animations in spine make sure to include this bit and the following lines
/*
AnimationState.TrackEntry e = this.state.setAnimation(0, CIRNO_ANIMATION, true);
e.setTime(e.getEndTime() * MathUtils.random());
this.stateData.setMix("Hit", "Idle", 0.1F);
e.setTimeScale(1.0F);
*/
logger.info("init finish");
}
public ArrayList<String> getStartingDeck() { // 初始 <SUF>
ArrayList<String> ret = new ArrayList<>();
for (int i = 0; i < 5; i++)
ret.add("IceGrain");
for (int i = 0; i < 5; i++)
ret.add("IceBarrier");
ret.add("IcicleShot");
ret.add("ShowOff");
return ret;
}
public ArrayList<String> getStartingRelics() { // 初始遗物
ArrayList<String> ret = new ArrayList<>();
ret.add("CrystalWings");
UnlockTracker.markRelicAsSeen("CrystalWings");
return ret;
}
private static final int STARTING_HP = 69;
private static final int MAX_HP = 69;
private static final int STARTING_GOLD = 99;
private static final int HAND_SIZE = 5;
private static final int ASCENSION_MAX_HP_LOSS = 4;
public CharSelectInfo getLoadout() { // the rest of the character loadout so includes your character select screen info plus hp and starting gold
String title;
String flavor;
if (Settings.language == Settings.GameLanguage.ZHS || Settings.language == Settings.GameLanguage.ZHT) {
title = "琪露诺";
flavor = "居住在雾之湖的冰之妖精。笨蛋。";
} else {
title = "Cirno";
flavor = "Baka!";
}
return new CharSelectInfo(
title,
flavor,
STARTING_HP,
MAX_HP,
0,
STARTING_GOLD,
HAND_SIZE,
this,
getStartingRelics(),
getStartingDeck(),
false
);
}
public AbstractCard.CardColor getCardColor() {
return AbstractCardEnum.CIRNO_COLOR;
}
public AbstractCard getStartCardForEvent() {
return new Chirumiru();
}
public String getTitle(PlayerClass playerClass) {
String title;
if (Settings.language == GameLanguage.ZHS) {
title = "冰之小妖精";
} else {
title = "Little Ice Fairy";
}
return title;
}
public Color getCardTrailColor() {
return ThMod.CHILLED;
}
public int getAscensionMaxHPLoss() {
return ASCENSION_MAX_HP_LOSS;
}
public BitmapFont getEnergyNumFont() {
return FontHelper.energyNumFontBlue;
}
public void doCharSelectScreenSelectEffect() {
CardCrawlGame.sound.playA("SELECT_CIRNO", MathUtils.random(-0.1F, 0.1F));
CardCrawlGame.screenShake.shake(
ScreenShake.ShakeIntensity.MED,
ScreenShake.ShakeDur.SHORT,
false
);
}
public String getCustomModeCharacterButtonSoundKey() {
return "SELECT_CIRNO";
}
public String getLocalizedCharacterName() {
String char_name;
if ((Settings.language == Settings.GameLanguage.ZHS)
|| (Settings.language == Settings.GameLanguage.ZHT)) {
char_name = "琪露诺";
} else if (Settings.language == Settings.GameLanguage.JPN) {
char_name = "チルノ";
} else {
char_name = "Cirno";
}
return char_name;
}
public AbstractPlayer newInstance() {
return new Cirno(this.name);
}
@Override
public String getVampireText() {
return com.megacrit.cardcrawl.events.city.Vampires.DESCRIPTIONS[1];
}
public Color getCardRenderColor() {
return ThMod.CHILLED;
}
public void updateOrb(int orbCount) {
this.energyOrb.updateOrb(orbCount);
}
public TextureAtlas.AtlasRegion getOrb() {
return new TextureAtlas.AtlasRegion(ImageMaster.loadImage(ThMod.CARD_ENERGY_ORB), 0, 0, 24, 24);
}
public Color getSlashAttackColor() {
return ThMod.CHILLED;
}
public AttackEffect[] getSpireHeartSlashEffect() {
return new AttackEffect[]{
AttackEffect.SLASH_HEAVY,
AttackEffect.FIRE,
AttackEffect.SLASH_DIAGONAL,
AttackEffect.SLASH_HEAVY,
AttackEffect.FIRE,
AttackEffect.SLASH_DIAGONAL
};
}
public String getSpireHeartText() {
return com.megacrit.cardcrawl.events.beyond.SpireHeart.DESCRIPTIONS[10];
}
public void damage(DamageInfo info) {
// if ((info.owner != null) && (info.type != DamageInfo.DamageType.THORNS)
// && (info.output - this.currentBlock > 0)) {
// AnimationState.TrackEntry e = this.state.setAnimation(0, "Hit", false);
// this.state.addAnimation(0, "Idle", true, 0.0F);
// e.setTimeScale(1.0F);
// }
super.damage(info);
}
public void applyPreCombatLogic() {
super.applyPreCombatLogic();
// ThMod.typhoonCounter = 0;
// ThMod.logger.info(
// "Marisa : applyPreCombatLogic : I just reset the god damn typhoon counter ! current counter : "
// + ThMod.typhoonCounter
// );
}
}
| false |
7800_3 | package top.sharehome.springbootinittemplate.config.security;
import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import top.sharehome.springbootinittemplate.common.base.Constants;
import top.sharehome.springbootinittemplate.config.security.condition.SaCondition;
import top.sharehome.springbootinittemplate.model.vo.auth.AuthLoginVo;
import jakarta.annotation.PostConstruct;
import java.util.Collections;
import java.util.List;
/**
* SaToken鉴权配置
* 这里应该会依靠loginId对数据库进行相关查询,得到的结果放入结果集中,
* 该模板不会单独规划处一个权限或者角色数据库表样式,而是将角色内嵌于模板SQL中t_user表内,因为该模板主要针对于不同的中小系统而设计的,不同系统都有不同的权限和角色分配,
* 用与不用SaToken鉴权完全取决于系统本身业务,所以此处@Component注解打开与否完全取决于开发者;
*
* @author AntonyCheng
*/
@Configuration
@Conditional(SaCondition.class)
@Slf4j
public class AuthorizationConfiguration implements StpInterface {
/**
* 重写权限方法
*
* @param loginId 账号id
* @param loginType 账号类型
* @return 返回结果
*/
@Override
public List<String> getPermissionList(Object loginId, String loginType) {
// 根据SaToken权限配置文档:https://sa-token.cc/doc.html#/use/jur-auth
// 由于此处设计主要针对于接口权限,所以权限通常有多个,上帝权限和个别极端情况除外
// 举例:User实体中有一个add方法(),则推荐将该方法权限写为"user.add",支持通配符操作,如果想要得到User实体类中所有方法的调用权限,则写为"user.*"
// "*"表示上帝权限
return Collections.singletonList("*");
}
/**
* 重写角色方法
*
* @param loginId 账号id
* @param loginType 账号类型
* @return 返回结果
*/
@Override
public List<String> getRoleList(Object loginId, String loginType) {
// 根据SaToken权限配置文档:https://sa-token.cc/doc.html#/use/jur-auth
// 由于此处设计主要针对于用户角色,所以角色通常只有一个,个别情况除外
// "*"表示上帝角色
SaSession session = StpUtil.getSessionByLoginId(loginId);
String userRole = ((AuthLoginVo) session.get(Constants.LOGIN_USER_KEY)).getRole();
return Collections.singletonList(userRole);
}
/**
* 依赖注入日志输出
*/
@PostConstruct
private void initDi() {
log.info("############ {} Configuration DI.", this.getClass().getSimpleName().split("\\$\\$")[0]);
}
} | AntonyCheng/spring-boot-init-template | src/main/java/top/sharehome/springbootinittemplate/config/security/AuthorizationConfiguration.java | 783 | // 由于此处设计主要针对于接口权限,所以权限通常有多个,上帝权限和个别极端情况除外 | line_comment | zh-cn | package top.sharehome.springbootinittemplate.config.security;
import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import top.sharehome.springbootinittemplate.common.base.Constants;
import top.sharehome.springbootinittemplate.config.security.condition.SaCondition;
import top.sharehome.springbootinittemplate.model.vo.auth.AuthLoginVo;
import jakarta.annotation.PostConstruct;
import java.util.Collections;
import java.util.List;
/**
* SaToken鉴权配置
* 这里应该会依靠loginId对数据库进行相关查询,得到的结果放入结果集中,
* 该模板不会单独规划处一个权限或者角色数据库表样式,而是将角色内嵌于模板SQL中t_user表内,因为该模板主要针对于不同的中小系统而设计的,不同系统都有不同的权限和角色分配,
* 用与不用SaToken鉴权完全取决于系统本身业务,所以此处@Component注解打开与否完全取决于开发者;
*
* @author AntonyCheng
*/
@Configuration
@Conditional(SaCondition.class)
@Slf4j
public class AuthorizationConfiguration implements StpInterface {
/**
* 重写权限方法
*
* @param loginId 账号id
* @param loginType 账号类型
* @return 返回结果
*/
@Override
public List<String> getPermissionList(Object loginId, String loginType) {
// 根据SaToken权限配置文档:https://sa-token.cc/doc.html#/use/jur-auth
// 由于 <SUF>
// 举例:User实体中有一个add方法(),则推荐将该方法权限写为"user.add",支持通配符操作,如果想要得到User实体类中所有方法的调用权限,则写为"user.*"
// "*"表示上帝权限
return Collections.singletonList("*");
}
/**
* 重写角色方法
*
* @param loginId 账号id
* @param loginType 账号类型
* @return 返回结果
*/
@Override
public List<String> getRoleList(Object loginId, String loginType) {
// 根据SaToken权限配置文档:https://sa-token.cc/doc.html#/use/jur-auth
// 由于此处设计主要针对于用户角色,所以角色通常只有一个,个别情况除外
// "*"表示上帝角色
SaSession session = StpUtil.getSessionByLoginId(loginId);
String userRole = ((AuthLoginVo) session.get(Constants.LOGIN_USER_KEY)).getRole();
return Collections.singletonList(userRole);
}
/**
* 依赖注入日志输出
*/
@PostConstruct
private void initDi() {
log.info("############ {} Configuration DI.", this.getClass().getSimpleName().split("\\$\\$")[0]);
}
} | false |
44793_20 | package kualian.dc.deal.application.util;
import android.app.Activity;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Vibrator;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import kualian.dc.deal.application.R;
import kualian.dc.deal.application.WalletApp;
import kualian.dc.deal.application.database.CoinDao;
import kualian.dc.deal.application.wallet.CoinType;
import kualian.dc.deal.application.wallet.coins.BitcoinMain;
import kualian.dc.deal.application.wallet.coins.UbMain;
import static android.content.Context.AUDIO_SERVICE;
/**
* Created by vondear on 2016/1/24.
* RxTools的常用工具类
* <p>
* For the brave souls who getWallet this far: You are the chosen ones,
* the valiant knights of programming who toil away, without rest,
* fixing our most awful code. To you, true saviors, kings of men,
* I say this: never gonna give you up, never gonna let you down,
* never gonna run around and desert you. Never gonna make you cry,
* never gonna say goodbye. Never gonna tell a lie and hurt you.
* <p>
* 致终于来到这里的勇敢的人:
* 你是被上帝选中的人,是英勇的、不敌辛苦的、不眠不休的来修改我们这最棘手的代码的编程骑士。
* 你,我们的救世主,人中之龙,我要对你说:永远不要放弃,永远不要对自己失望,永远不要逃走,辜负了自己,
* 永远不要哭啼,永远不要说再见,永远不要说谎来伤害自己。
*/
public class WalletTool {
private static Context context;
private static long lastClickTime;
/**
* 初始化工具类
*
* @param context 上下文
*/
public static void init(Context context) {
WalletTool.context = context.getApplicationContext();
}
/**
* 在某种获取不到 Context 的情况下,即可以使用才方法获取 Context
* <p>
* 获取ApplicationContext
*
* @return ApplicationContext
*/
public static Context getContext() {
if (context != null) return context;
throw new NullPointerException("请先调用init()方法");
}
//==============================================================================================延时任务封装 end
//----------------------------------------------------------------------------------------------延时任务封装 start
/**
* 倒计时
*
* @param textView 控件
* @param waitTime 倒计时总时长
* @param interval 倒计时的间隔时间
* @param hint 倒计时完毕时显示的文字
*/
public static void countDown(final TextView textView, long waitTime, long interval, final String hint) {
textView.setEnabled(false);
android.os.CountDownTimer timer = new android.os.CountDownTimer(waitTime, interval) {
@Override
public void onTick(long millisUntilFinished) {
textView.setText("剩下 " + (millisUntilFinished / 1000) + " S");
}
@Override
public void onFinish() {
textView.setEnabled(true);
textView.setText(hint);
}
};
timer.start();
}
/**
* 手动计算出listView的高度,但是不再具有滚动效果
*
* @param listView
*/
public static void fixListViewHeight(ListView listView) {
// 如果没有设置数据适配器,则ListView没有子项,返回。
ListAdapter listAdapter = listView.getAdapter();
int totalHeight = 0;
if (listAdapter == null) {
return;
}
for (int index = 0, len = listAdapter.getCount(); index < len; index++) {
View listViewItem = listAdapter.getView(index, null, listView);
// 计算子项View 的宽高
listViewItem.measure(0, 0);
// 计算所有子项的高度
totalHeight += listViewItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
// listView.getDividerHeight()获取子项间分隔符的高度
// params.height设置ListView完全显示需要的高度
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
//---------------------------------------------MD5加密-------------------------------------------
/**
* 生成MD5加密32位字符串
*
* @param MStr :需要加密的字符串
* @return
*/
public static String Md5(String MStr) {
try {
final MessageDigest mDigest = MessageDigest.getInstance("MD5");
mDigest.update(MStr.getBytes());
return bytesToHexString(mDigest.digest());
} catch (NoSuchAlgorithmException e) {
return String.valueOf(MStr.hashCode());
}
}
// MD5内部算法---------------不能修改!
private static String bytesToHexString(byte[] bytes) {
// http://stackoverflow.com/questions/332079
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(0xFF & bytes[i]);
if (hex.length() == 1) {
sb.append('0');
}
sb.append(hex);
}
return sb.toString();
}
//============================================MD5加密============================================
/**
* 根据资源名称获取资源 id
* <p>
* 不提倡使用这个方法获取资源,比其直接获取ID效率慢
* <p>
* 例如
* getResources().getIdentifier("ic_launcher", "drawable", getPackageName());
*
* @param context
* @param name
* @param defType
* @return
*/
public static final int getResIdByName(Context context, String name, String defType) {
return context.getResources().getIdentifier("ic_launcher", "drawable", context.getPackageName());
}
public static boolean isFastClick(int millisecond) {
long curClickTime = System.currentTimeMillis();
long interval = (curClickTime - lastClickTime);
if (0 < interval && interval < millisecond) {
// 超过点击间隔后再将lastClickTime重置为当前点击时间
return true;
}
lastClickTime = curClickTime;
return false;
}
/**
* Edittext 首位小数点自动加零,最多两位小数
*
* @param editText
*/
public static void setEdTwoDecimal(EditText editText) {
setEdDecimal(editText, 3);
}
public static void setEdDecimal(EditText editText, int count) {
if (count < 1) {
count = 1;
}
editText.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_CLASS_NUMBER);
//设置字符过滤
final int finalCount = count;
editText.setFilters(new InputFilter[]{new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if (source.equals(".") && dest.toString().length() == 0) {
return "0.";
}
if (dest.toString().contains(".")) {
int index = dest.toString().indexOf(".");
int mlength = dest.toString().substring(index).length();
if (mlength == finalCount) {
return "";
}
}
return null;
}
}});
}
public static void setEditNumberPrefix(final EditText edSerialNumber, final int number) {
edSerialNumber.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
String s = edSerialNumber.getText().toString();
String temp = "";
for (int i = s.length(); i < number; i++) {
s = "0" + s;
}
for (int i = 0; i < number; i++) {
temp += "0";
}
if (s.equals(temp)) {
s = temp.substring(1) + "1";
}
edSerialNumber.setText(s);
}
}
});
}
private static final float BEEP_VOLUME = 0.50f;
private static final int VIBRATE_DURATION = 200;
private static boolean playBeep = false;
private static MediaPlayer mediaPlayer;
public static void playBeep(Activity mContext, boolean vibrate) {
playBeep = true;
AudioManager audioService = (AudioManager) mContext.getSystemService(AUDIO_SERVICE);
if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
playBeep = false;
}
if (playBeep && mediaPlayer != null) {
mediaPlayer.start();
} else {
mContext.setVolumeControlStream(AudioManager.STREAM_MUSIC);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.seekTo(0);
}
});
AssetFileDescriptor file = mContext.getResources().openRawResourceFd(R.raw.beep);
try {
mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
file.close();
mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
mediaPlayer.prepare();
} catch (IOException e) {
mediaPlayer = null;
}
}
if (vibrate) {
vibrateOnce(mContext, VIBRATE_DURATION);
}
}
private static Vibrator vibrator;
/**
* 简单震动
* @param context 调用震动的Context
* @param millisecond 震动的时间,毫秒
*/
@SuppressWarnings("static-access")
public static void vibrateOnce(Context context, int millisecond) {
vibrator = (Vibrator) context.getSystemService(context.VIBRATOR_SERVICE);
vibrator.vibrate(millisecond);
}
/**
* Resize the bitmap
*
* @param bitmap 图片引用
* @param width 宽度
* @param height 高度
* @return 缩放之后的图片引用
*/
public static Bitmap zoomBitmap(Bitmap bitmap, int width, int height) {
int w = bitmap.getWidth();
int h = bitmap.getHeight();
Matrix matrix = new Matrix();
float scaleWidth = ((float) width / w);
float scaleHeight = ((float) height / h);
matrix.postScale(scaleWidth, scaleHeight);
return Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
}
public static Handler getBackgroundHandler() {
HandlerThread thread = new HandlerThread("background");
thread.start();
Handler mBackgroundHandler = new Handler(thread.getLooper());
return mBackgroundHandler;
}
public static CoinType getDefaultCoin(){
List<CoinType> list = new CoinDao().queryAll(SpUtil.getInstance().getWalletID());
for (CoinType type: list) {
if (type.getCoinIndex()==SpUtil.getInstance().getDefaultCoinIndex()){
return type;
}
}
return new UbMain();
}
}
| AnyBitIO/anybit-Android | app/src/main/java/kualian/dc/deal/application/util/WalletTool.java | 2,852 | //设置字符过滤 | line_comment | zh-cn | package kualian.dc.deal.application.util;
import android.app.Activity;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Vibrator;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import kualian.dc.deal.application.R;
import kualian.dc.deal.application.WalletApp;
import kualian.dc.deal.application.database.CoinDao;
import kualian.dc.deal.application.wallet.CoinType;
import kualian.dc.deal.application.wallet.coins.BitcoinMain;
import kualian.dc.deal.application.wallet.coins.UbMain;
import static android.content.Context.AUDIO_SERVICE;
/**
* Created by vondear on 2016/1/24.
* RxTools的常用工具类
* <p>
* For the brave souls who getWallet this far: You are the chosen ones,
* the valiant knights of programming who toil away, without rest,
* fixing our most awful code. To you, true saviors, kings of men,
* I say this: never gonna give you up, never gonna let you down,
* never gonna run around and desert you. Never gonna make you cry,
* never gonna say goodbye. Never gonna tell a lie and hurt you.
* <p>
* 致终于来到这里的勇敢的人:
* 你是被上帝选中的人,是英勇的、不敌辛苦的、不眠不休的来修改我们这最棘手的代码的编程骑士。
* 你,我们的救世主,人中之龙,我要对你说:永远不要放弃,永远不要对自己失望,永远不要逃走,辜负了自己,
* 永远不要哭啼,永远不要说再见,永远不要说谎来伤害自己。
*/
public class WalletTool {
private static Context context;
private static long lastClickTime;
/**
* 初始化工具类
*
* @param context 上下文
*/
public static void init(Context context) {
WalletTool.context = context.getApplicationContext();
}
/**
* 在某种获取不到 Context 的情况下,即可以使用才方法获取 Context
* <p>
* 获取ApplicationContext
*
* @return ApplicationContext
*/
public static Context getContext() {
if (context != null) return context;
throw new NullPointerException("请先调用init()方法");
}
//==============================================================================================延时任务封装 end
//----------------------------------------------------------------------------------------------延时任务封装 start
/**
* 倒计时
*
* @param textView 控件
* @param waitTime 倒计时总时长
* @param interval 倒计时的间隔时间
* @param hint 倒计时完毕时显示的文字
*/
public static void countDown(final TextView textView, long waitTime, long interval, final String hint) {
textView.setEnabled(false);
android.os.CountDownTimer timer = new android.os.CountDownTimer(waitTime, interval) {
@Override
public void onTick(long millisUntilFinished) {
textView.setText("剩下 " + (millisUntilFinished / 1000) + " S");
}
@Override
public void onFinish() {
textView.setEnabled(true);
textView.setText(hint);
}
};
timer.start();
}
/**
* 手动计算出listView的高度,但是不再具有滚动效果
*
* @param listView
*/
public static void fixListViewHeight(ListView listView) {
// 如果没有设置数据适配器,则ListView没有子项,返回。
ListAdapter listAdapter = listView.getAdapter();
int totalHeight = 0;
if (listAdapter == null) {
return;
}
for (int index = 0, len = listAdapter.getCount(); index < len; index++) {
View listViewItem = listAdapter.getView(index, null, listView);
// 计算子项View 的宽高
listViewItem.measure(0, 0);
// 计算所有子项的高度
totalHeight += listViewItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
// listView.getDividerHeight()获取子项间分隔符的高度
// params.height设置ListView完全显示需要的高度
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
//---------------------------------------------MD5加密-------------------------------------------
/**
* 生成MD5加密32位字符串
*
* @param MStr :需要加密的字符串
* @return
*/
public static String Md5(String MStr) {
try {
final MessageDigest mDigest = MessageDigest.getInstance("MD5");
mDigest.update(MStr.getBytes());
return bytesToHexString(mDigest.digest());
} catch (NoSuchAlgorithmException e) {
return String.valueOf(MStr.hashCode());
}
}
// MD5内部算法---------------不能修改!
private static String bytesToHexString(byte[] bytes) {
// http://stackoverflow.com/questions/332079
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(0xFF & bytes[i]);
if (hex.length() == 1) {
sb.append('0');
}
sb.append(hex);
}
return sb.toString();
}
//============================================MD5加密============================================
/**
* 根据资源名称获取资源 id
* <p>
* 不提倡使用这个方法获取资源,比其直接获取ID效率慢
* <p>
* 例如
* getResources().getIdentifier("ic_launcher", "drawable", getPackageName());
*
* @param context
* @param name
* @param defType
* @return
*/
public static final int getResIdByName(Context context, String name, String defType) {
return context.getResources().getIdentifier("ic_launcher", "drawable", context.getPackageName());
}
public static boolean isFastClick(int millisecond) {
long curClickTime = System.currentTimeMillis();
long interval = (curClickTime - lastClickTime);
if (0 < interval && interval < millisecond) {
// 超过点击间隔后再将lastClickTime重置为当前点击时间
return true;
}
lastClickTime = curClickTime;
return false;
}
/**
* Edittext 首位小数点自动加零,最多两位小数
*
* @param editText
*/
public static void setEdTwoDecimal(EditText editText) {
setEdDecimal(editText, 3);
}
public static void setEdDecimal(EditText editText, int count) {
if (count < 1) {
count = 1;
}
editText.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_CLASS_NUMBER);
//设置 <SUF>
final int finalCount = count;
editText.setFilters(new InputFilter[]{new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if (source.equals(".") && dest.toString().length() == 0) {
return "0.";
}
if (dest.toString().contains(".")) {
int index = dest.toString().indexOf(".");
int mlength = dest.toString().substring(index).length();
if (mlength == finalCount) {
return "";
}
}
return null;
}
}});
}
public static void setEditNumberPrefix(final EditText edSerialNumber, final int number) {
edSerialNumber.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
String s = edSerialNumber.getText().toString();
String temp = "";
for (int i = s.length(); i < number; i++) {
s = "0" + s;
}
for (int i = 0; i < number; i++) {
temp += "0";
}
if (s.equals(temp)) {
s = temp.substring(1) + "1";
}
edSerialNumber.setText(s);
}
}
});
}
private static final float BEEP_VOLUME = 0.50f;
private static final int VIBRATE_DURATION = 200;
private static boolean playBeep = false;
private static MediaPlayer mediaPlayer;
public static void playBeep(Activity mContext, boolean vibrate) {
playBeep = true;
AudioManager audioService = (AudioManager) mContext.getSystemService(AUDIO_SERVICE);
if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
playBeep = false;
}
if (playBeep && mediaPlayer != null) {
mediaPlayer.start();
} else {
mContext.setVolumeControlStream(AudioManager.STREAM_MUSIC);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.seekTo(0);
}
});
AssetFileDescriptor file = mContext.getResources().openRawResourceFd(R.raw.beep);
try {
mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
file.close();
mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
mediaPlayer.prepare();
} catch (IOException e) {
mediaPlayer = null;
}
}
if (vibrate) {
vibrateOnce(mContext, VIBRATE_DURATION);
}
}
private static Vibrator vibrator;
/**
* 简单震动
* @param context 调用震动的Context
* @param millisecond 震动的时间,毫秒
*/
@SuppressWarnings("static-access")
public static void vibrateOnce(Context context, int millisecond) {
vibrator = (Vibrator) context.getSystemService(context.VIBRATOR_SERVICE);
vibrator.vibrate(millisecond);
}
/**
* Resize the bitmap
*
* @param bitmap 图片引用
* @param width 宽度
* @param height 高度
* @return 缩放之后的图片引用
*/
public static Bitmap zoomBitmap(Bitmap bitmap, int width, int height) {
int w = bitmap.getWidth();
int h = bitmap.getHeight();
Matrix matrix = new Matrix();
float scaleWidth = ((float) width / w);
float scaleHeight = ((float) height / h);
matrix.postScale(scaleWidth, scaleHeight);
return Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
}
public static Handler getBackgroundHandler() {
HandlerThread thread = new HandlerThread("background");
thread.start();
Handler mBackgroundHandler = new Handler(thread.getLooper());
return mBackgroundHandler;
}
public static CoinType getDefaultCoin(){
List<CoinType> list = new CoinDao().queryAll(SpUtil.getInstance().getWalletID());
for (CoinType type: list) {
if (type.getCoinIndex()==SpUtil.getInstance().getDefaultCoinIndex()){
return type;
}
}
return new UbMain();
}
}
| false |
17979_14 |
package com.ai.face.verify;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import com.ai.face.FaceApplication;
import com.ai.face.R;
import com.ai.face.base.view.CameraXFragment;
import com.ai.face.base.view.FaceCoverView;
import com.ai.face.faceVerify.graphic.FaceTipsOverlay;
import com.ai.face.faceVerify.verify.FaceProcessBuilder;
import com.ai.face.faceVerify.verify.FaceVerifyUtils;
import com.ai.face.faceVerify.verify.ProcessCallBack;
import com.ai.face.faceVerify.verify.VerifyStatus.*;
import com.ai.face.utils.VoicePlayer;
import com.google.android.material.snackbar.Snackbar;
import java.io.File;
/**
* 1:1 的人脸识别 + 动作活体检测 SDK 接入演示Demo 代码,用户根据自己业务情况参考
* <p>
* <p>
* 1:N & M:N 人脸检索迁移到了 https://github.com/AnyLifeZLB/FaceSearchSDK_Android
* 体积更小,反应速度更快
*/
public class Verify_11_javaActivity extends AppCompatActivity {
private ConstraintLayout rootView;
private TextView tipsTextView, scoreText;
private FaceTipsOverlay faceTipsOverlay;
private FaceCoverView faceCoverView;
private final FaceVerifyUtils faceVerifyUtils = new FaceVerifyUtils();
//RGB 镜头 1080p, 固定 30 帧,无拖影,RGB 镜头建议是宽动态
private static final float silentPassScore = 0.92f; //静默活体分数通过的阈值
private float silentScoreValue = 0f; //静默活体的分数
//字段拆分出来,照顾Free 用户
private final boolean needLiveCheck=true; //是否需要活体检测,不需要的话最终识别结果不用考虑静默活体分数
private Boolean isVerifyMatched = null; //先取一个中性的null, 真实只有true 和 false
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_verify_11);
setTitle("1:1人脸识别with 活体检测");
rootView=findViewById(R.id.rootView);
scoreText = findViewById(R.id.silent_Score);
tipsTextView = findViewById(R.id.tips_view);
faceCoverView = findViewById(R.id.face_cover);
faceTipsOverlay = findViewById(R.id.faceTips);
findViewById(R.id.back).setOnClickListener(v -> {
Verify_11_javaActivity.this.finish();
});
int cameraLensFacing = getSharedPreferences("faceVerify", Context.MODE_PRIVATE)
.getInt("cameraFlag", 0);
// 1. Camera 的初始化。第一个参数0/1 指定前后摄像头;
// 第二个参数linearZoom [0.1f,1.0f] 指定焦距,默认0.1。根据你的设备和场景选择合适的值
CameraXFragment cameraXFragment = CameraXFragment.newInstance(cameraLensFacing, 0.09f);
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_camerax, cameraXFragment).commit();
//1:1 人脸对比,摄像头和预留的人脸底片对比。(动作活体人脸检测完成后开始1:1比对)
//如果仅仅需要活体检测,可以把App logo Bitmap 当参数传入并忽略对比结果
//人脸底图要经过BaseImageDispose saveBaseImage处理,不是随便一张图能当底图!!!
String yourUniQueFaceId = getIntent().getStringExtra(FaceApplication.USER_ID_KEY);
File file = new File(FaceApplication.CACHE_BASE_FACE_DIR, yourUniQueFaceId);
Bitmap baseBitmap = BitmapFactory.decodeFile(file.getPath());
//1.初始化引擎,各种参数配置
initFaceVerify(baseBitmap);
cameraXFragment.setOnAnalyzerListener(imageProxy -> {
//防止在识别过程中关闭页面导致Crash
if (!isDestroyed() && !isFinishing() && faceVerifyUtils != null) {
//第二个参数是指圆形人脸框到屏幕边距,可加快裁剪图像和指定识别区域,设太大会裁剪点人脸区域
faceVerifyUtils.goVerify(imageProxy, faceCoverView.getMargin());
}
});
}
/**
* 初始化认证引擎
* <p>
* 活体检测的使用需要你发送邮件申请,简要描述App名称,包名和功能简介到 anylife.zlb@gmail.com
*
* @param baseBitmap 1:1 人脸识别对比的底片,如果仅仅需要活体检测,可以把App logo Bitmap 当参数传入并忽略对比结果
*/
private void initFaceVerify(Bitmap baseBitmap) {
FaceProcessBuilder faceProcessBuilder = new FaceProcessBuilder.Builder(this)
.setThreshold(0.88f) //阈值设置,范围限 [0.8 , 0.95] 识别可信度,也是识别灵敏度
.setBaseBitmap(baseBitmap) //1:1 人脸识别对比的底片,仅仅需要SDK活体检测可以忽略比对结果
.setLiveCheck(needLiveCheck) //是否需要活体检测(包含动作和静默),开通需要发送邮件,参考ReadMe
.setSilentAliveThreshold(0.88f) //静默活体阈值 [0.88,0.99]
.setMotionStepSize(1) //随机动作验证活体的步骤个数[0-2],0个没有动作活体只有静默活体
.setVerifyTimeOut(12) //活体检测支持设置超时时间 [9,16] 秒
.setGraphicOverlay(faceTipsOverlay)//正式环境请去除设置
.setProcessCallBack(new ProcessCallBack() {
//静默活体检测得分大于0.9 可以认为是真人,可结合动作活体一起使用
@Override
public void onSilentAntiSpoofing(float scoreValue) {
runOnUiThread(() -> {
scoreText.setText("静默活体可靠得分:" + scoreValue);
});
silentScoreValue = scoreValue;
playVerifyResult();
}
//onCompleted --- rename ---> onVerifyMatched
@Override
public void onVerifyMatched(boolean isMatched) {
isVerifyMatched = isMatched;
playVerifyResult();
}
@Override
public void onFailed(int i) {
//预留防护
}
//人脸识别活体检测过程中的各种提示
@Override
public void onProcessTips(int i) {
showAliveDetectTips(i);
}
//动作活体检测时间限制倒计时
@Override
public void onTimeOutStart(float time) {
faceCoverView.startCountDown(time);
}
}).create();
faceVerifyUtils.setDetectorParams(faceProcessBuilder);
}
/**
* 检测1:1 人脸识别是否通过
* 动作活体要有人配合必须,必须先动作再1:1 匹配
* 静默活体不需要人配合可以和1:1 同时进行但要注意不确定谁先返回的问题
*/
private void playVerifyResult() {
//不需要活体检测,忽略分数,下版本放到SDK 内部处理
if(!needLiveCheck){
silentScoreValue=1.0f;
}
//1:1 人脸识别对比的结果,是同一个人还是非同一个人
runOnUiThread(() -> {
if (isVerifyMatched == null || silentScoreValue == 0f) {
//必须要两个值都有才能判断
Log.d("playVerifyResult", "等待状态 D silentScoreValue=" + silentScoreValue + " isVerifyMatched=" + isVerifyMatched);
} else {
if (silentScoreValue > silentPassScore && isVerifyMatched) {
tipsTextView.setText("核验已通过,与底片为同一人! ");
VoicePlayer.getInstance().addPayList(R.raw.verify_success);
//关闭页面时间业务自己根据实际情况定
new Handler(Looper.getMainLooper()).postDelayed(Verify_11_javaActivity.this::finish, 1500);
} else {
if (!isVerifyMatched) {
tipsTextView.setText("核验不通过,与底片不符! ");
VoicePlayer.getInstance().addPayList(R.raw.verify_failed);
new AlertDialog.Builder(Verify_11_javaActivity.this)
.setMessage("1:1 人脸识别不通过,与底片不符! ")
.setCancelable(false)
.setPositiveButton("知道了", (dialogInterface, i) -> finish())
.setNegativeButton("重试", (dialog, which) -> faceVerifyUtils.retryVerify())
.show();
} else {
tipsTextView.setText("静默活体得分过低");
new AlertDialog.Builder(Verify_11_javaActivity.this)
.setMessage("静默活体得分过低! ")
.setCancelable(false)
.setPositiveButton("知道了", (dialogInterface, i) -> finish())
.show();
}
}
}
});
}
/**
* 根据业务和设计师UI交互修改你的 UI,Demo 仅供参考
* <p>
* 添加声音提示和动画提示定制也在这里根据返回码进行定制
*/
boolean isSnakeBarShow=false;
private void showAliveDetectTips(int actionCode) {
if (!isDestroyed() && !isFinishing()) {
runOnUiThread(() -> {
switch (actionCode) {
//5次相比阈值太低就判断为非同一人
case VERIFY_DETECT_TIPS_ENUM.ACTION_PROCESS:
tipsTextView.setText("人脸识别中...");
break;
case VERIFY_DETECT_TIPS_ENUM.ACTION_NO_FACE:
tipsTextView.setText("画面没有检测到人脸");
break;
case VERIFY_DETECT_TIPS_ENUM.ACTION_FAILED:
tipsTextView.setText("动作活体检测失败了");
break;
case VERIFY_DETECT_TIPS_ENUM.ACTION_OK: {
VoicePlayer.getInstance().addPayList(R.raw.face_camera);
tipsTextView.setText("请保持正对屏幕");
}
break;
case ALIVE_DETECT_TYPE_ENUM.OPEN_MOUSE: {
VoicePlayer.getInstance().addPayList(R.raw.open_mouse);
tipsTextView.setText("请张嘴");
}
break;
case ALIVE_DETECT_TYPE_ENUM.SMILE: {
tipsTextView.setText("请微笑");
VoicePlayer.getInstance().addPayList(R.raw.smile);
}
break;
case ALIVE_DETECT_TYPE_ENUM.BLINK: {
VoicePlayer.getInstance().addPayList(R.raw.blink);
tipsTextView.setText("请轻眨眼");
}
break;
case ALIVE_DETECT_TYPE_ENUM.SHAKE_HEAD: {
VoicePlayer.getInstance().addPayList(R.raw.shake_head);
tipsTextView.setText("请缓慢左右摇头");
}
break;
case ALIVE_DETECT_TYPE_ENUM.NOD_HEAD: {
VoicePlayer.getInstance().addPayList(R.raw.nod_head);
tipsTextView.setText("请缓慢上下点头");
}
break;
case VERIFY_DETECT_TIPS_ENUM.ACTION_TIME_OUT: {
new AlertDialog.Builder(this)
.setMessage("活体检测超时了")
.setCancelable(false)
.setPositiveButton("重试一次", (dialogInterface, i) -> faceVerifyUtils.retryVerify()
).show();
}
break;
case VERIFY_DETECT_TIPS_ENUM.NO_FACE_REPEATEDLY: {
tipsTextView.setText("多次切换画面或无人脸");
new AlertDialog.Builder(this)
.setMessage("多次切换画面或无人脸,停止识别。\n识别过程请保持人脸在画面中")
.setCancelable(false)
.setPositiveButton("知道了", (dialogInterface, i) -> finish())
.show();
}
break;
//请远一点,交互业务自行实现仅供参考
case VERIFY_DETECT_TIPS_ENUM.FACE_TOO_LARGE:
if(isSnakeBarShow) return;
Snackbar.make(rootView, "请离屏幕远一点!", Snackbar.LENGTH_SHORT).setCallback(new Snackbar.Callback(){
@Override
public void onShown(Snackbar sb) {
super.onShown(sb);
isSnakeBarShow=true;
}
@Override
public void onDismissed(Snackbar transientBottomBar, int event) {
super.onDismissed(transientBottomBar, event);
isSnakeBarShow=false;
}
}).show();
break;
}
});
}
}
/**
* 资源释放
*/
@Override
protected void onDestroy() {
super.onDestroy();
faceVerifyUtils.destroyProcess();
faceCoverView.destroyView();
}
/**
* 暂停识别,防止切屏识别,如果你需要退后台不能识别的话
*/
protected void onPause() {
super.onPause();
faceVerifyUtils.pauseProcess();
}
}
| AnyLifeZLB/FaceVerificationSDK | app/src/main/java/com/ai/face/verify/Verify_11_javaActivity.java | 3,323 | //第二个参数是指圆形人脸框到屏幕边距,可加快裁剪图像和指定识别区域,设太大会裁剪点人脸区域 | line_comment | zh-cn |
package com.ai.face.verify;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import com.ai.face.FaceApplication;
import com.ai.face.R;
import com.ai.face.base.view.CameraXFragment;
import com.ai.face.base.view.FaceCoverView;
import com.ai.face.faceVerify.graphic.FaceTipsOverlay;
import com.ai.face.faceVerify.verify.FaceProcessBuilder;
import com.ai.face.faceVerify.verify.FaceVerifyUtils;
import com.ai.face.faceVerify.verify.ProcessCallBack;
import com.ai.face.faceVerify.verify.VerifyStatus.*;
import com.ai.face.utils.VoicePlayer;
import com.google.android.material.snackbar.Snackbar;
import java.io.File;
/**
* 1:1 的人脸识别 + 动作活体检测 SDK 接入演示Demo 代码,用户根据自己业务情况参考
* <p>
* <p>
* 1:N & M:N 人脸检索迁移到了 https://github.com/AnyLifeZLB/FaceSearchSDK_Android
* 体积更小,反应速度更快
*/
public class Verify_11_javaActivity extends AppCompatActivity {
private ConstraintLayout rootView;
private TextView tipsTextView, scoreText;
private FaceTipsOverlay faceTipsOverlay;
private FaceCoverView faceCoverView;
private final FaceVerifyUtils faceVerifyUtils = new FaceVerifyUtils();
//RGB 镜头 1080p, 固定 30 帧,无拖影,RGB 镜头建议是宽动态
private static final float silentPassScore = 0.92f; //静默活体分数通过的阈值
private float silentScoreValue = 0f; //静默活体的分数
//字段拆分出来,照顾Free 用户
private final boolean needLiveCheck=true; //是否需要活体检测,不需要的话最终识别结果不用考虑静默活体分数
private Boolean isVerifyMatched = null; //先取一个中性的null, 真实只有true 和 false
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_verify_11);
setTitle("1:1人脸识别with 活体检测");
rootView=findViewById(R.id.rootView);
scoreText = findViewById(R.id.silent_Score);
tipsTextView = findViewById(R.id.tips_view);
faceCoverView = findViewById(R.id.face_cover);
faceTipsOverlay = findViewById(R.id.faceTips);
findViewById(R.id.back).setOnClickListener(v -> {
Verify_11_javaActivity.this.finish();
});
int cameraLensFacing = getSharedPreferences("faceVerify", Context.MODE_PRIVATE)
.getInt("cameraFlag", 0);
// 1. Camera 的初始化。第一个参数0/1 指定前后摄像头;
// 第二个参数linearZoom [0.1f,1.0f] 指定焦距,默认0.1。根据你的设备和场景选择合适的值
CameraXFragment cameraXFragment = CameraXFragment.newInstance(cameraLensFacing, 0.09f);
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_camerax, cameraXFragment).commit();
//1:1 人脸对比,摄像头和预留的人脸底片对比。(动作活体人脸检测完成后开始1:1比对)
//如果仅仅需要活体检测,可以把App logo Bitmap 当参数传入并忽略对比结果
//人脸底图要经过BaseImageDispose saveBaseImage处理,不是随便一张图能当底图!!!
String yourUniQueFaceId = getIntent().getStringExtra(FaceApplication.USER_ID_KEY);
File file = new File(FaceApplication.CACHE_BASE_FACE_DIR, yourUniQueFaceId);
Bitmap baseBitmap = BitmapFactory.decodeFile(file.getPath());
//1.初始化引擎,各种参数配置
initFaceVerify(baseBitmap);
cameraXFragment.setOnAnalyzerListener(imageProxy -> {
//防止在识别过程中关闭页面导致Crash
if (!isDestroyed() && !isFinishing() && faceVerifyUtils != null) {
//第二 <SUF>
faceVerifyUtils.goVerify(imageProxy, faceCoverView.getMargin());
}
});
}
/**
* 初始化认证引擎
* <p>
* 活体检测的使用需要你发送邮件申请,简要描述App名称,包名和功能简介到 anylife.zlb@gmail.com
*
* @param baseBitmap 1:1 人脸识别对比的底片,如果仅仅需要活体检测,可以把App logo Bitmap 当参数传入并忽略对比结果
*/
private void initFaceVerify(Bitmap baseBitmap) {
FaceProcessBuilder faceProcessBuilder = new FaceProcessBuilder.Builder(this)
.setThreshold(0.88f) //阈值设置,范围限 [0.8 , 0.95] 识别可信度,也是识别灵敏度
.setBaseBitmap(baseBitmap) //1:1 人脸识别对比的底片,仅仅需要SDK活体检测可以忽略比对结果
.setLiveCheck(needLiveCheck) //是否需要活体检测(包含动作和静默),开通需要发送邮件,参考ReadMe
.setSilentAliveThreshold(0.88f) //静默活体阈值 [0.88,0.99]
.setMotionStepSize(1) //随机动作验证活体的步骤个数[0-2],0个没有动作活体只有静默活体
.setVerifyTimeOut(12) //活体检测支持设置超时时间 [9,16] 秒
.setGraphicOverlay(faceTipsOverlay)//正式环境请去除设置
.setProcessCallBack(new ProcessCallBack() {
//静默活体检测得分大于0.9 可以认为是真人,可结合动作活体一起使用
@Override
public void onSilentAntiSpoofing(float scoreValue) {
runOnUiThread(() -> {
scoreText.setText("静默活体可靠得分:" + scoreValue);
});
silentScoreValue = scoreValue;
playVerifyResult();
}
//onCompleted --- rename ---> onVerifyMatched
@Override
public void onVerifyMatched(boolean isMatched) {
isVerifyMatched = isMatched;
playVerifyResult();
}
@Override
public void onFailed(int i) {
//预留防护
}
//人脸识别活体检测过程中的各种提示
@Override
public void onProcessTips(int i) {
showAliveDetectTips(i);
}
//动作活体检测时间限制倒计时
@Override
public void onTimeOutStart(float time) {
faceCoverView.startCountDown(time);
}
}).create();
faceVerifyUtils.setDetectorParams(faceProcessBuilder);
}
/**
* 检测1:1 人脸识别是否通过
* 动作活体要有人配合必须,必须先动作再1:1 匹配
* 静默活体不需要人配合可以和1:1 同时进行但要注意不确定谁先返回的问题
*/
private void playVerifyResult() {
//不需要活体检测,忽略分数,下版本放到SDK 内部处理
if(!needLiveCheck){
silentScoreValue=1.0f;
}
//1:1 人脸识别对比的结果,是同一个人还是非同一个人
runOnUiThread(() -> {
if (isVerifyMatched == null || silentScoreValue == 0f) {
//必须要两个值都有才能判断
Log.d("playVerifyResult", "等待状态 D silentScoreValue=" + silentScoreValue + " isVerifyMatched=" + isVerifyMatched);
} else {
if (silentScoreValue > silentPassScore && isVerifyMatched) {
tipsTextView.setText("核验已通过,与底片为同一人! ");
VoicePlayer.getInstance().addPayList(R.raw.verify_success);
//关闭页面时间业务自己根据实际情况定
new Handler(Looper.getMainLooper()).postDelayed(Verify_11_javaActivity.this::finish, 1500);
} else {
if (!isVerifyMatched) {
tipsTextView.setText("核验不通过,与底片不符! ");
VoicePlayer.getInstance().addPayList(R.raw.verify_failed);
new AlertDialog.Builder(Verify_11_javaActivity.this)
.setMessage("1:1 人脸识别不通过,与底片不符! ")
.setCancelable(false)
.setPositiveButton("知道了", (dialogInterface, i) -> finish())
.setNegativeButton("重试", (dialog, which) -> faceVerifyUtils.retryVerify())
.show();
} else {
tipsTextView.setText("静默活体得分过低");
new AlertDialog.Builder(Verify_11_javaActivity.this)
.setMessage("静默活体得分过低! ")
.setCancelable(false)
.setPositiveButton("知道了", (dialogInterface, i) -> finish())
.show();
}
}
}
});
}
/**
* 根据业务和设计师UI交互修改你的 UI,Demo 仅供参考
* <p>
* 添加声音提示和动画提示定制也在这里根据返回码进行定制
*/
boolean isSnakeBarShow=false;
private void showAliveDetectTips(int actionCode) {
if (!isDestroyed() && !isFinishing()) {
runOnUiThread(() -> {
switch (actionCode) {
//5次相比阈值太低就判断为非同一人
case VERIFY_DETECT_TIPS_ENUM.ACTION_PROCESS:
tipsTextView.setText("人脸识别中...");
break;
case VERIFY_DETECT_TIPS_ENUM.ACTION_NO_FACE:
tipsTextView.setText("画面没有检测到人脸");
break;
case VERIFY_DETECT_TIPS_ENUM.ACTION_FAILED:
tipsTextView.setText("动作活体检测失败了");
break;
case VERIFY_DETECT_TIPS_ENUM.ACTION_OK: {
VoicePlayer.getInstance().addPayList(R.raw.face_camera);
tipsTextView.setText("请保持正对屏幕");
}
break;
case ALIVE_DETECT_TYPE_ENUM.OPEN_MOUSE: {
VoicePlayer.getInstance().addPayList(R.raw.open_mouse);
tipsTextView.setText("请张嘴");
}
break;
case ALIVE_DETECT_TYPE_ENUM.SMILE: {
tipsTextView.setText("请微笑");
VoicePlayer.getInstance().addPayList(R.raw.smile);
}
break;
case ALIVE_DETECT_TYPE_ENUM.BLINK: {
VoicePlayer.getInstance().addPayList(R.raw.blink);
tipsTextView.setText("请轻眨眼");
}
break;
case ALIVE_DETECT_TYPE_ENUM.SHAKE_HEAD: {
VoicePlayer.getInstance().addPayList(R.raw.shake_head);
tipsTextView.setText("请缓慢左右摇头");
}
break;
case ALIVE_DETECT_TYPE_ENUM.NOD_HEAD: {
VoicePlayer.getInstance().addPayList(R.raw.nod_head);
tipsTextView.setText("请缓慢上下点头");
}
break;
case VERIFY_DETECT_TIPS_ENUM.ACTION_TIME_OUT: {
new AlertDialog.Builder(this)
.setMessage("活体检测超时了")
.setCancelable(false)
.setPositiveButton("重试一次", (dialogInterface, i) -> faceVerifyUtils.retryVerify()
).show();
}
break;
case VERIFY_DETECT_TIPS_ENUM.NO_FACE_REPEATEDLY: {
tipsTextView.setText("多次切换画面或无人脸");
new AlertDialog.Builder(this)
.setMessage("多次切换画面或无人脸,停止识别。\n识别过程请保持人脸在画面中")
.setCancelable(false)
.setPositiveButton("知道了", (dialogInterface, i) -> finish())
.show();
}
break;
//请远一点,交互业务自行实现仅供参考
case VERIFY_DETECT_TIPS_ENUM.FACE_TOO_LARGE:
if(isSnakeBarShow) return;
Snackbar.make(rootView, "请离屏幕远一点!", Snackbar.LENGTH_SHORT).setCallback(new Snackbar.Callback(){
@Override
public void onShown(Snackbar sb) {
super.onShown(sb);
isSnakeBarShow=true;
}
@Override
public void onDismissed(Snackbar transientBottomBar, int event) {
super.onDismissed(transientBottomBar, event);
isSnakeBarShow=false;
}
}).show();
break;
}
});
}
}
/**
* 资源释放
*/
@Override
protected void onDestroy() {
super.onDestroy();
faceVerifyUtils.destroyProcess();
faceCoverView.destroyView();
}
/**
* 暂停识别,防止切屏识别,如果你需要退后台不能识别的话
*/
protected void onPause() {
super.onPause();
faceVerifyUtils.pauseProcess();
}
}
| false |
16345_7 | package com.xjtu.bookreader.bean.book;
import android.databinding.BaseObservable;
import com.xjtu.bookreader.http.ParamNames;
import java.io.Serializable;
/**
* Created by jingbin on 2016/12/15.
*/
public class BooksBean extends BaseObservable implements Serializable {
/**
* rating : {"max":10,"numRaters":116375,"average":"7.9","min":0}
* subtitle :
* author : ["韩寒"]
* pubdate : 2010-9
* tags : [{"count":38955,"name":"韩寒","title":"韩寒"},{"count":16343,"name":"小说","title":"小说"},{"count":12037,"name":"我想和这个世界谈谈","title":"我想和这个世界谈谈"},{"count":10674,"name":"公路小说","title":"公路小说"},{"count":6392,"name":"1988","title":"1988"},{"count":5868,"name":"中国文学","title":"中国文学"},{"count":5260,"name":"中国","title":"中国"},{"count":4730,"name":"文学","title":"文学"}]
* origin_title :
* image : https://img5.doubanio.com/mpic/s4477716.jpg
* binding : 平装
* translator : []
* catalog : 曹操与刘备的一生
* pages : 215
* images : {"small":"https://img5.doubanio.com/spic/s4477716.jpg","large":"https://img5.doubanio.com/lpic/s4477716.jpg","medium":"https://img5.doubanio.com/mpic/s4477716.jpg"}
* alt : https://book.douban.com/subject/5275059/
* id : 5275059
* publisher : 国际文化出版公司
* isbn10 : 751250098X
* isbn13 : 9787512500983
* title : 1988:我想和这个世界谈谈
* url : https://api.douban.com/v2/book/5275059
* alt_title :
* author_intro : 韩寒 1982年9月23日出生。作家,赛车手。已出版作品:《三重门》、《零下一度》、《像少年啦飞驰》、《通稿2003》、《毒》、《韩寒五年文集》、《长安乱》、《就这么漂来漂去》、《一座城池》、《寒》、《光荣日》、《杂的文》或有其他。
* summary : 系列主题:《我想和这个世界谈谈》
* 目前在韩寒主编的杂志《独唱团》中首度连载,这是韩寒预谋已久的一个系列,也是国内首度实际尝试“公路小说”这一概念的第一本——《1988》。
* 所谓“公路小说”就是以路途为载体反应人生观,现实观的小说。
* 如果说一件真正的艺术品的面世具有任何重大意义的话,韩寒新书的出版将会在中国创造一个历史事件,文章开头“空气越来越差,我必须上路了。我开着一台1988年出厂的旅行车,在说不清是迷雾还是毒气的夜色里拐上了318国道。”用一部旅行车为载体,通过在路上的见闻、过去的回忆、扑朔迷离的人物关系等各种现实场景,以韩寒本人对路上所见、所闻引发自己的观点,这场真正的旅途在精神层面;如果说似乎逾越了部分法律和道德的界限,但出发点也仅仅是希望在另一侧找到信仰。韩寒是“叛逆的”,他“试图用能给世界一些新意的眼光来看世界。试图寻找令人信服的价值”。他认为这一切通过文学都可以实现,产生了要创造一种批判现有一切社会习俗的“新幻象”的念头——《1988》就此问世。
* 目前“公路小说”的系列已经开始策划,韩寒的作品首当其冲,韩寒表示将会撰写三部作品与聚石文华联合打造“公路小说”这一品牌
* price : 25.00元
*/
@ParamNames("id") // id
private String id;
@ParamNames("title") // 标题
private String title;
@ParamNames("author") // 作者
private String author;
@ParamNames("authorDescription") //作者介绍
private String authorDescription;
@ParamNames("subtitle") // 副标题
private String subtitle;
@ParamNames("subject") // 主题
private String subject;
@ParamNames("description") // 概要
private String description;
@ParamNames("publisher") //出版社
private String publisher;
@ParamNames("pubdate") // 出版时间
private String pubDate;
@ParamNames("coverImage") // 封面图片
private String coverImage;
@ParamNames("rating") // 评分
private String rating;
@ParamNames("pages") // 页数
private String pages;
@ParamNames("isbn") // 标准书号
private String isbn;
@ParamNames("payType") // 付费方式 (免费或者收费)
private int payType;
@ParamNames("price") // 价格
private String price;
}
| AotY/BookReader | app/src/main/java/com/xjtu/bookreader/bean/book/BooksBean.java | 1,503 | // 标准书号 | line_comment | zh-cn | package com.xjtu.bookreader.bean.book;
import android.databinding.BaseObservable;
import com.xjtu.bookreader.http.ParamNames;
import java.io.Serializable;
/**
* Created by jingbin on 2016/12/15.
*/
public class BooksBean extends BaseObservable implements Serializable {
/**
* rating : {"max":10,"numRaters":116375,"average":"7.9","min":0}
* subtitle :
* author : ["韩寒"]
* pubdate : 2010-9
* tags : [{"count":38955,"name":"韩寒","title":"韩寒"},{"count":16343,"name":"小说","title":"小说"},{"count":12037,"name":"我想和这个世界谈谈","title":"我想和这个世界谈谈"},{"count":10674,"name":"公路小说","title":"公路小说"},{"count":6392,"name":"1988","title":"1988"},{"count":5868,"name":"中国文学","title":"中国文学"},{"count":5260,"name":"中国","title":"中国"},{"count":4730,"name":"文学","title":"文学"}]
* origin_title :
* image : https://img5.doubanio.com/mpic/s4477716.jpg
* binding : 平装
* translator : []
* catalog : 曹操与刘备的一生
* pages : 215
* images : {"small":"https://img5.doubanio.com/spic/s4477716.jpg","large":"https://img5.doubanio.com/lpic/s4477716.jpg","medium":"https://img5.doubanio.com/mpic/s4477716.jpg"}
* alt : https://book.douban.com/subject/5275059/
* id : 5275059
* publisher : 国际文化出版公司
* isbn10 : 751250098X
* isbn13 : 9787512500983
* title : 1988:我想和这个世界谈谈
* url : https://api.douban.com/v2/book/5275059
* alt_title :
* author_intro : 韩寒 1982年9月23日出生。作家,赛车手。已出版作品:《三重门》、《零下一度》、《像少年啦飞驰》、《通稿2003》、《毒》、《韩寒五年文集》、《长安乱》、《就这么漂来漂去》、《一座城池》、《寒》、《光荣日》、《杂的文》或有其他。
* summary : 系列主题:《我想和这个世界谈谈》
* 目前在韩寒主编的杂志《独唱团》中首度连载,这是韩寒预谋已久的一个系列,也是国内首度实际尝试“公路小说”这一概念的第一本——《1988》。
* 所谓“公路小说”就是以路途为载体反应人生观,现实观的小说。
* 如果说一件真正的艺术品的面世具有任何重大意义的话,韩寒新书的出版将会在中国创造一个历史事件,文章开头“空气越来越差,我必须上路了。我开着一台1988年出厂的旅行车,在说不清是迷雾还是毒气的夜色里拐上了318国道。”用一部旅行车为载体,通过在路上的见闻、过去的回忆、扑朔迷离的人物关系等各种现实场景,以韩寒本人对路上所见、所闻引发自己的观点,这场真正的旅途在精神层面;如果说似乎逾越了部分法律和道德的界限,但出发点也仅仅是希望在另一侧找到信仰。韩寒是“叛逆的”,他“试图用能给世界一些新意的眼光来看世界。试图寻找令人信服的价值”。他认为这一切通过文学都可以实现,产生了要创造一种批判现有一切社会习俗的“新幻象”的念头——《1988》就此问世。
* 目前“公路小说”的系列已经开始策划,韩寒的作品首当其冲,韩寒表示将会撰写三部作品与聚石文华联合打造“公路小说”这一品牌
* price : 25.00元
*/
@ParamNames("id") // id
private String id;
@ParamNames("title") // 标题
private String title;
@ParamNames("author") // 作者
private String author;
@ParamNames("authorDescription") //作者介绍
private String authorDescription;
@ParamNames("subtitle") // 副标题
private String subtitle;
@ParamNames("subject") // 主题
private String subject;
@ParamNames("description") // 概要
private String description;
@ParamNames("publisher") //出版社
private String publisher;
@ParamNames("pubdate") // 出版时间
private String pubDate;
@ParamNames("coverImage") // 封面图片
private String coverImage;
@ParamNames("rating") // 评分
private String rating;
@ParamNames("pages") // 页数
private String pages;
@ParamNames("isbn") // 标准 <SUF>
private String isbn;
@ParamNames("payType") // 付费方式 (免费或者收费)
private int payType;
@ParamNames("price") // 价格
private String price;
}
| false |
27394_1 | /*
* Copyright (C) 2014 The AppCan Open Source Project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.zywx.wbpalmstar.platform.push;
import java.io.Serializable;
public class PushDataInfo implements Serializable {
private static final long serialVersionUID = 1L;
private String pushDataString;
private int contentAvailable; //静默方式;透传(静默):1,通知:0
private String appId;
private String taskId;
private String title;
private String alert;
private int badge;
private String[] remindType; //声音:sound,震动:shake,呼吸灯:breathe
private String iconUrl;
private String fontColor;
private String behavior;
private String tenantId;
public PushDataInfo() {
}
public int getContentAvailable() {
return contentAvailable;
}
public void setContentAvailable(int contentAvailable) {
this.contentAvailable = contentAvailable;
}
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAlert() {
return alert;
}
public void setAlert(String alert) {
this.alert = alert;
}
public String getPushDataString() {
return pushDataString;
}
public void setPushDataString(String pushDataString) {
this.pushDataString = pushDataString;
}
public int getBadge() {
return badge;
}
public void setBadge(int badge) {
this.badge = badge;
}
public String[] getRemindType() {
return remindType;
}
public void setRemindType(String[] remindType) {
this.remindType = remindType;
}
public String getIconUrl() {
return iconUrl;
}
public void setIconUrl(String iconUrl) {
this.iconUrl = iconUrl;
}
public String getFontColor() {
return fontColor;
}
public void setFontColor(String fontColor) {
this.fontColor = fontColor;
}
public String getBehavior() {
return behavior;
}
public void setBehavior(String behavior) {
this.behavior = behavior;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
} | AppCanOpenSource/appcan-android | Engine/src/main/java/org/zywx/wbpalmstar/platform/push/PushDataInfo.java | 779 | //静默方式;透传(静默):1,通知:0 | line_comment | zh-cn | /*
* Copyright (C) 2014 The AppCan Open Source Project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.zywx.wbpalmstar.platform.push;
import java.io.Serializable;
public class PushDataInfo implements Serializable {
private static final long serialVersionUID = 1L;
private String pushDataString;
private int contentAvailable; //静默 <SUF>
private String appId;
private String taskId;
private String title;
private String alert;
private int badge;
private String[] remindType; //声音:sound,震动:shake,呼吸灯:breathe
private String iconUrl;
private String fontColor;
private String behavior;
private String tenantId;
public PushDataInfo() {
}
public int getContentAvailable() {
return contentAvailable;
}
public void setContentAvailable(int contentAvailable) {
this.contentAvailable = contentAvailable;
}
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAlert() {
return alert;
}
public void setAlert(String alert) {
this.alert = alert;
}
public String getPushDataString() {
return pushDataString;
}
public void setPushDataString(String pushDataString) {
this.pushDataString = pushDataString;
}
public int getBadge() {
return badge;
}
public void setBadge(int badge) {
this.badge = badge;
}
public String[] getRemindType() {
return remindType;
}
public void setRemindType(String[] remindType) {
this.remindType = remindType;
}
public String getIconUrl() {
return iconUrl;
}
public void setIconUrl(String iconUrl) {
this.iconUrl = iconUrl;
}
public String getFontColor() {
return fontColor;
}
public void setFontColor(String fontColor) {
this.fontColor = fontColor;
}
public String getBehavior() {
return behavior;
}
public void setBehavior(String behavior) {
this.behavior = behavior;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
} | false |
16353_1 | package knowledge.concurrent;
import com.google.common.collect.Lists;
import java.util.List;
/**
* ThreadLocal
* <pre>
* ThreadLocal 中填充的变量属于当前线程,该变量对其他线程而言是隔离的
* ThreadLocal 对象使用 static 修饰,ThreadLocal 无法解决共享对象的更新问题(阿里编程规约)
* </pre>
* 使用场景:
* <pre>
* 1 在进行对象跨层传递的时候,使用 ThreadLocal 可以避免多次传递,打破层次间的约束
* 2 线程间数据隔离
* 3 进行事务操作,用于存储线程事务信息
* 4 数据库连接,Session 会话管理
* </pre>
* 参考:
* <pre>
* <a href="https://baijiahao.baidu.com/s?id=1653790035315010634">知道 ThreadLocal 嘛?谈谈你对它的理解?</a>
* <a href="https://blog.csdn.net/qq_33589510/article/details/105071141">说说线程封闭与 ThreadLocal 的关系</a>
* </pre>
*
* @author ljh
* @since 2020/11/6 12:55
*/
public class ThreadLocalDemo {
private static final ThreadLocal<List<String>> threadLocal = new ThreadLocal<>();
public static void main(String[] args) {
new Thread(() -> {
List<String> strList = Lists.newArrayList("1", "2", "3");
try {
threadLocal.set(strList);
threadLocal.get().forEach(name -> System.out.println(Thread.currentThread().getName() + " : " + name));
} finally {
// 阿里编程规约:
// 必须回收自定义的 ThreadLocal 变量记录的当前线程的值,尤其在线程池场景下,线程经常会被复用,
// 如果不清理自定义的 ThreadLocal 变量,可能会影响后续业务逻辑和造成内存泄露等问题。
// 尽量在代码中使用 try-finally 块进行回收
threadLocal.remove();
}
}, "Thread-A").start();
new Thread(() -> {
List<String> strList = Lists.newArrayList("a", "b", "c");
try {
threadLocal.set(strList);
threadLocal.get().forEach(name -> System.out.println(Thread.currentThread().getName() + " : " + name));
} finally {
threadLocal.remove();
}
}, "Thread-B").start();
}
}
| Apparition2018/epitome | src/main/java/knowledge/concurrent/ThreadLocalDemo.java | 643 | // 阿里编程规约: | line_comment | zh-cn | package knowledge.concurrent;
import com.google.common.collect.Lists;
import java.util.List;
/**
* ThreadLocal
* <pre>
* ThreadLocal 中填充的变量属于当前线程,该变量对其他线程而言是隔离的
* ThreadLocal 对象使用 static 修饰,ThreadLocal 无法解决共享对象的更新问题(阿里编程规约)
* </pre>
* 使用场景:
* <pre>
* 1 在进行对象跨层传递的时候,使用 ThreadLocal 可以避免多次传递,打破层次间的约束
* 2 线程间数据隔离
* 3 进行事务操作,用于存储线程事务信息
* 4 数据库连接,Session 会话管理
* </pre>
* 参考:
* <pre>
* <a href="https://baijiahao.baidu.com/s?id=1653790035315010634">知道 ThreadLocal 嘛?谈谈你对它的理解?</a>
* <a href="https://blog.csdn.net/qq_33589510/article/details/105071141">说说线程封闭与 ThreadLocal 的关系</a>
* </pre>
*
* @author ljh
* @since 2020/11/6 12:55
*/
public class ThreadLocalDemo {
private static final ThreadLocal<List<String>> threadLocal = new ThreadLocal<>();
public static void main(String[] args) {
new Thread(() -> {
List<String> strList = Lists.newArrayList("1", "2", "3");
try {
threadLocal.set(strList);
threadLocal.get().forEach(name -> System.out.println(Thread.currentThread().getName() + " : " + name));
} finally {
// 阿里 <SUF>
// 必须回收自定义的 ThreadLocal 变量记录的当前线程的值,尤其在线程池场景下,线程经常会被复用,
// 如果不清理自定义的 ThreadLocal 变量,可能会影响后续业务逻辑和造成内存泄露等问题。
// 尽量在代码中使用 try-finally 块进行回收
threadLocal.remove();
}
}, "Thread-A").start();
new Thread(() -> {
List<String> strList = Lists.newArrayList("a", "b", "c");
try {
threadLocal.set(strList);
threadLocal.get().forEach(name -> System.out.println(Thread.currentThread().getName() + " : " + name));
} finally {
threadLocal.remove();
}
}, "Thread-B").start();
}
}
| true |
23961_103 | package com.studio314.d_emo.server;
import com.alibaba.fastjson.JSONObject;
import com.studio314.d_emo.mapper.ChatsMapper;
import com.studio314.d_emo.mapper.TodoMapper;
import com.studio314.d_emo.pojo.Chats;
import com.studio314.d_emo.pojo.Todo;
import com.studio314.d_emo.server.impl.TodoServerImpl;
import com.studio314.d_emo.utils.PADAlgorithm;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
@Component
@Slf4j
@ServerEndpoint("/webSocketServer/{myUserId}")
public class ChatServer {
/**
* 与客户端的连接会话,需要通过他来给客户端发消息
*/
private Session session;
private static String pythonServer;
public static Map<String, Integer> EMOTIONS = new LinkedHashMap<>();
static {
EMOTIONS.put("高兴", 2131230905);
EMOTIONS.put("生气", 2131230916);
EMOTIONS.put("喜欢", 2131230927);
EMOTIONS.put("疲劳", 2131230929);
EMOTIONS.put("笑哭", 2131230930);
EMOTIONS.put("调皮", 2131230931);
EMOTIONS.put("焦虑", 2131230932);
EMOTIONS.put("亲亲", 2131230933);
EMOTIONS.put("安逸", 2131230934);
EMOTIONS.put("烦躁", 2131230906);
EMOTIONS.put("痛苦", 2131230907);
EMOTIONS.put("惊吓", 2131230908);
EMOTIONS.put("失落", 2131230909);
EMOTIONS.put("害怕", 2131230910);
EMOTIONS.put("轻松", 2131230911);
EMOTIONS.put("吃惊", 2131230912);
EMOTIONS.put("开心", 2131230913);
EMOTIONS.put("兴奋", 2131230914);
EMOTIONS.put("大哭", 2131230915);
EMOTIONS.put("愤恨", 2131230917);
EMOTIONS.put("愉快", 2131230918);
EMOTIONS.put("不满", 2131230919);
EMOTIONS.put("悲伤", 2131230920);
EMOTIONS.put("恐惧", 2131230921);
EMOTIONS.put("满足", 2131230922);
EMOTIONS.put("小恶魔", 2131230923);
EMOTIONS.put("羞愧", 2131230924);
EMOTIONS.put("爱", 2131230925);
EMOTIONS.put("点赞", 2131230926);
EMOTIONS.put("许愿", 2131230928);
}
@Value("${ip.python" +
"Server}") String setPythonServer(String pythonServer){
return ChatServer.pythonServer = pythonServer;
}
/**
* 是否第一次连接 ai 服务器
*/
private boolean firstConnected = true;
private Socket socket;
/**
* 当前用户ID
*/
private String userId;
/**
* concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
* 虽然@Component默认是单例模式的,但springboot还是会为每个websocket连接初始化一个bean,所以可以用一个静态set保存起来。
*/
private static CopyOnWriteArraySet<ChatServer> webSockets =new CopyOnWriteArraySet<>();
/**
*用来存在线连接用户信息
*/
private static ConcurrentHashMap<String,Session> sessionPool = new ConcurrentHashMap<String,Session>();
@Autowired ChatsMapper setChatsMapper(ChatsMapper chatsMapper){
return ChatServer.chatsMapper = chatsMapper;
}
static ChatsMapper chatsMapper;
@Autowired
TodoMapper setTodoMapper(TodoMapper todoMapper){
return ChatServer.todoMapper = todoMapper;
}
static TodoMapper todoMapper;
private static final int HEARTBEAT_INTERVAL = 1000; // 心跳间隔时间,单位:毫秒
private final Object lock = new Object(); // 用于线程同步的锁对象
private class HeartbeatThread extends Thread {
@Override
public void run() {
try {
OutputStream outputStream = socket.getOutputStream();
while (true) {
synchronized (lock) {
// 检查是否需要建立连接
if (socket == null || socket.isClosed()) {
// 创建新的Socket连接
socket = new Socket(pythonServer, 12345);
outputStream = socket.getOutputStream();
// System.out.println("建立连接");
}
// 发送心跳包数据
//将消息封装成json格式
JSONObject heartJsonObject = new JSONObject();
heartJsonObject.put("type", "heart");
heartJsonObject.put("firstConnect", firstConnected);
outputStream.write(heartJsonObject.toJSONString().getBytes());
outputStream.flush();
// log.info("心跳发送成功...");
BufferedInputStream bis1 = new BufferedInputStream(socket.getInputStream());
byte[] data = new byte[10240];
int len = bis1.read(data);
String rec = new String(data,0,len);
// log.info("rec:"+rec);
if (rec.equals("success")) {
// log.info("心跳包收到回复...");
} else {
log.info("心跳包收到回复异常,尝试重连");
// 关闭旧的Socket连接
try {
if (socket != null && !socket.isClosed()) {
socket.close();
// 创建新的Socket连接
socket = new Socket(pythonServer, 12345);
outputStream = socket.getOutputStream();
log.info("与服务器重新建立连接成功");
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
// 等待一段时间
Thread.sleep(HEARTBEAT_INTERVAL);
}
} catch (IOException e) {
e.printStackTrace();
log.info("心跳发送失败,尝试重新连接...");
// 关闭旧的Socket连接
try {
if (socket != null && !socket.isClosed()) {
socket.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* 连接成功方法
* @param session 连接会话
* @param userId 用户编号
*/
@OnOpen
public void onOpen(Session session , @PathParam("myUserId") String userId){
try {
this.session = session;
this.userId = userId;
webSockets.add(this);
sessionPool.put(userId, session);
log.info("【websocket消息】 用户:" + userId + " 加入连接...");
// 创建Socket连接
socket = new Socket(pythonServer, 12345);
// 启动心跳线程
new HeartbeatThread().start();
// log.info("【websocket消息】 用户:" + userId + " 连接服务器成功...");
} catch (Exception e) {
log.error("---------------WebSocket连接异常---------------");
}
}
/**
* 关闭连接
*/
@OnClose
public void onClose(){
try {
webSockets.remove(this);
sessionPool.remove(this.userId);
log.info("【websocket消息】 用户:"+ this.userId + " 断开连接...");
} catch (Exception e) {
log.error("---------------WebSocket断开异常---------------");
}
}
@OnMessage
public void onMessage(@PathParam("myUserId") String userId, String body){
try {
if (socket == null) {
socket = new Socket(pythonServer, 12345);
socket.setKeepAlive(true);
log.info("【websocket消息】 用户:" + userId + " 连接服务器成功...");
}
//将Body解析
JSONObject clientJsonObject = JSONObject.parseObject(body);
//获取目标用户地址
String targetUserId = clientJsonObject.getString("userId");
//获取消息内容
String clientMessage = clientJsonObject.getString("content");
log.info("【websocket消息】 用户:"+ userId + " 发送消息:"+clientMessage);
//获取heartRate
float heartRate = clientJsonObject.getFloat("heartRate");
//获取睡眠的分
float sleepScore = clientJsonObject.getFloat("sleepScore");
//获取压力值
float pressure = clientJsonObject.getFloat("pressure");
log.info("heartRate:"+heartRate + " sleepScore:"+sleepScore + " pressure:"+pressure);
// log.info("【websocket消息】 用户:"+ userId + " 发送消息:"+clientMessage);
int audioTime = clientJsonObject.getIntValue("time");
//获取消息类型
int type = clientJsonObject.getIntValue("type");
//获取上一条消息的情绪
Chats lastChat = chatsMapper.getLastChat(Integer.parseInt(userId));
String lastEmotion;
if(lastChat == null || lastChat.getEmotion() == null){
lastEmotion = "未知";
} else {
lastEmotion = lastChat.getEmotion();
int emotionID = Integer.parseInt(lastEmotion);
//将数字映射为文字,如果为-1或未找到,都是未知
if (EMOTIONS.containsValue(emotionID)) {
for (Map.Entry<String, Integer> entry : EMOTIONS.entrySet()) {
if (entry.getValue().equals(emotionID)) {
lastEmotion = entry.getKey();
break;
}
}
} else {
lastEmotion = "未知";
}
}
if (type == 0){
//将消息封装成json格式
JSONObject messageJsonObject = new JSONObject();
messageJsonObject.put("type", "text");
messageJsonObject.put("ID", Integer.parseInt(userId));
messageJsonObject.put("data", clientMessage);
messageJsonObject.put("firstConnect", firstConnected);
messageJsonObject.put("emotion", lastEmotion);
log.info(clientMessage);
// 防止心跳与消息发送冲突
synchronized (lock) {
//socket将clientMessage发送给服务器
BufferedOutputStream bos;
try {
bos = new BufferedOutputStream(socket.getOutputStream());
bos.write(messageJsonObject.toJSONString().getBytes(StandardCharsets.UTF_8));
firstConnected = false;
bos.flush();
} catch(Exception e) {
log.info("服务器已断开");
socket = new Socket(pythonServer, 12345);
bos = new BufferedOutputStream(socket.getOutputStream());
log.info("重新连接成功");
messageJsonObject.put("firstConnect", true);
bos.write(messageJsonObject.toJSONString().getBytes());
firstConnected = false;
bos.flush();
}
}
// socket.shutdownOutput();
// 读取服务器上的响应数据
BufferedInputStream bis1 = new BufferedInputStream(socket.getInputStream());
byte[] data = new byte[10240];
int len = bis1.read(data);
String rec = new String(data,0,len);
// log.info("rec:"+rec);
JSONObject recJsonObject = JSONObject.parseObject(rec);
String recData = recJsonObject.getString("data");
String emotion = recJsonObject.getString("emotion");
log.info("AI-emotion:"+emotion);
double pleasure;
double arousal;
double dominance;
// 获取pleasure
try {
emotion = emotion.replace("'", "").replace("'", "");
emotion = emotion.replace(" ", "").replace(" ", "");
pleasure = Double.parseDouble(emotion.substring(emotion.indexOf("P") + 2, emotion.indexOf("A") - 1));
arousal = Double.parseDouble(emotion.substring(emotion.indexOf("A") + 2, emotion.indexOf("D") - 1));
dominance = Double.parseDouble(emotion.substring(emotion.indexOf("D") + 2, emotion.length() - 1));
} catch (Exception e) {
e.printStackTrace();
pleasure = 0.5;
arousal = 0.5;
dominance = 0.5;
}
log.info("PAD:"+pleasure + " " + pressure + " " + heartRate + " " + sleepScore);
// 使用replace去除 [ ] 符号
emotion = emotion.replace("[", "").replace("]", "");
// 使用replace去除 ' 符号 和 ' 符号
emotion = emotion.replace("'", "").replace("'", "");
// 使用replace去除 " 符合 和 " 符号
emotion = emotion.replace("\"", "").replace("\"", "");
// //测试判断情况
// pressure = ;
// heartRate = ;
// sleepScore = ;
//计算情绪
PADAlgorithm.EmotionType PADemotionType = PADAlgorithm.getEmotionWithAI(pleasure, pressure, heartRate, sleepScore, arousal, dominance);
log.info("PAD-emotion:" + PADAlgorithm.getEmotionString(PADemotionType));
String operator = recJsonObject.getString("operator");
// log.info("operator:"+operator);
JSONObject operateJsonObject = JSONObject.parseObject(operator);
String operateType = operateJsonObject.getString("type");
log.info("operateType:"+operateType);
if (operateType.equals("todo")){
JSONObject todoJsonObject = JSONObject.parseObject(operateJsonObject.getString("data"));
String date = todoJsonObject.getString("time");
// log.info("date:"+date);
String name = todoJsonObject.getString("str");
// log.info("name:"+name);
Todo todo = new Todo();
// Timestamp timestamp = Timestamp.valueOf(date);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date parsedDate = dateFormat.parse(date);
Timestamp timestamp = new Timestamp(parsedDate.getTime());
todo.setDate(timestamp);
log.info("待办timestamp:"+timestamp);
todo.setName(name);
log.info("userId:"+userId);
todo.setUserid(Integer.parseInt(userId));
todo.setIsfinished(0);
todoMapper.insert(todo);
} else if (operateType.equals("diary")) {
}
// 使用replace去除 [ ] 符号
emotion = emotion.replace("[", "").replace("]", "");
// 使用replace去除 ' 符号 和 ' 符号
emotion = emotion.replace("'", "").replace("'", "");
// 使用replace去除 " 符合 和 " 符号
emotion = emotion.replace("\"", "").replace("\"", "");
// log.info("emotionaaaaaaa:"+emotion);
// //判断情绪是否在情绪列表中
// if (EMOTIONS.containsKey(PADemotion)) {
// emotion = EMOTIONS.get(emotion).toString();
//// log.info("转换后emotion:" + emotion);
// }else {
// emotion = "-1";
// }
emotion = String.valueOf(PADAlgorithm.getEmoji(PADemotionType));
//text为utf-8字符,解码
String recText = new String(recData.getBytes("utf-8"), "utf-8");
// log.info("【websocket消息】 用户:"+ userId + " 接收消息:"+recText);
//将获取到的消息发送给接收端
JSONObject serverJsonObject = new JSONObject();
serverJsonObject.put("type", 0);
serverJsonObject.put("message", recText);
sendMoreMessage(new String[]{targetUserId} , JSONObject.toJSONString(serverJsonObject));
// log.info("emotion:"+emotion);
// 保存文本消息
chatsMapper.insertChat(Integer.parseInt(userId), clientMessage, type, 0, emotion);
//将获取到的信息保存到数据库
chatsMapper.insertChat(Integer.parseInt(userId), recText, 0, 1, null);
} else if (type == 1) {
//将消息封装成json格式
JSONObject messageJsonObject = new JSONObject();
messageJsonObject.put("type", "img");
messageJsonObject.put("ID", Integer.parseInt(userId));
messageJsonObject.put("data", clientMessage);
messageJsonObject.put("firstConnect", firstConnected);
messageJsonObject.put("emotion", lastEmotion);
synchronized (lock){
//socket将clientMessage发送给服务器
BufferedOutputStream bos;
try {
bos = new BufferedOutputStream(socket.getOutputStream());
bos.write(messageJsonObject.toJSONString().getBytes());
firstConnected = false;
bos.flush();
} catch(Exception e) {
System.out.println("服务器已断开");
socket = new Socket(pythonServer, 12345);
bos = new BufferedOutputStream(socket.getOutputStream());
System.out.println("重新连接成功");
messageJsonObject.put("firstConnect", true);
bos.write(messageJsonObject.toJSONString().getBytes());
firstConnected = false;
bos.flush();
}
}
// socket.shutdownOutput();
// 读取服务器上的响应数据
BufferedInputStream bis1 = new BufferedInputStream(socket.getInputStream());
byte[] data = new byte[10240];
int len = bis1.read(data);
String rec = new String(data,0,len);
JSONObject recJsonObject = JSONObject.parseObject(rec);
String recData = recJsonObject.getString("data");
String emotion = recJsonObject.getString("emotion");
double pleasure;
double arousal;
double dominance;
// 获取pleasure
try {
emotion = emotion.replace("'", "").replace("'", "");
emotion = emotion.replace(" ", "").replace(" ", "");
pleasure = Double.parseDouble(emotion.substring(emotion.indexOf("P") + 2, emotion.indexOf("A") - 1));
arousal = Double.parseDouble(emotion.substring(emotion.indexOf("A") + 2, emotion.indexOf("D") - 1));
dominance = Double.parseDouble(emotion.substring(emotion.indexOf("D") + 2, emotion.length() - 1));
} catch (Exception e) {
e.printStackTrace();
pleasure = 0.5;
arousal = 0.5;
dominance = 0.5;
}
log.info("PAD:"+pleasure + " " + pressure + " " + heartRate + " " + sleepScore);
//计算情绪
PADAlgorithm.EmotionType PADemotionType = PADAlgorithm.getEmotionWithAI(pleasure, pressure, heartRate, sleepScore, arousal, dominance);
log.info("PAD-emotion:" + PADAlgorithm.getEmotionString(PADemotionType));
// 使用replace去除 [ ] 符号
emotion = emotion.replace("[", "").replace("]", "");
// 使用replace去除 ' 符号 和 ' 符号
emotion = emotion.replace("'", "").replace("'", "");
// 使用replace去除 " 符合 和 " 符号
emotion = emotion.replace("\"", "").replace("\"", "");
//text为utf-8字符,解码
String recText = new String(recData.getBytes("utf-8"), "utf-8");
// log.info("【websocket消息】 用户:"+ userId + " 接收消息:"+recText);
// //判断情绪是否在情绪列表中
// if (EMOTIONS.containsKey(PADemotion)) {
// emotion = EMOTIONS.get(emotion).toString();
//// log.info("转换后emotion:" + emotion);
// }else {
// emotion = "-1";
// }
emotion = String.valueOf(PADAlgorithm.getEmoji(PADemotionType));
//将获取到的消息发送给接收端
JSONObject serverJsonObject = new JSONObject();
serverJsonObject.put("type", 0);
serverJsonObject.put("message", recText);
sendMoreMessage(new String[]{targetUserId} , JSONObject.toJSONString(serverJsonObject));
// 保存图片消息
chatsMapper.insertChat(Integer.parseInt(userId), clientMessage, type, 0, emotion);
//将获取到的信息保存到数据库
chatsMapper.insertChat(Integer.parseInt(userId), recText, 0, 1, null);
} else if (type == 2) {
// 分别为每个属性创建String变量
String appid = "8635128650";
String token = "0M1WqciqDTrWwOWo9L8voBAMTuTFYozO";
String cluster = "volc_auc_common";
String uid = "388808087185088";
String format = "ogg";
String audioUrl = clientMessage;
// String audioUrl = "https://d-emo.obs.cn-north-4.myhuaweicloud.com/chat/audio/ea31da9e-b997-4b73-886e-fd778f7d17a8.ogg";
String bearerToken ="Bearer; "+token;
// 构建JSON字符串
String jsonBody = "{\n" +
" \"app\": {\n" +
" \"appid\": \"" + appid + "\",\n" +
" \"token\": \"" + token + "\",\n" +
" \"cluster\": \"" + cluster + "\"\n" +
" },\n" +
" \"user\": {\n" +
" \"uid\": \"" + uid + "\"\n" +
" },\n" +
" \"audio\": {\n" +
" \"format\": \"" + format + "\",\n" +
" \"url\": \"" + audioUrl + "\"\n" +
" }\n" +
"}";
// 创建HttpClient实例
HttpClient httpClient = HttpClient.newBuilder().build();
// 创建POST请求
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://openspeech.bytedance.com/api/v1/auc/submit")) // 设置请求的URL
.header("Content-Type", "application/json") // 设置请求头
.header("Authorization", bearerToken) // 设置请求头
.POST(HttpRequest.BodyPublishers.ofString(jsonBody)) // 设置请求体为JSON数据
.build();
// 发送请求并获取响应
try {
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
// 输出响应结果
System.out.println("Response Code: " + response.statusCode());
System.out.println("Response Body: " + response.body());
//下面解析返回的json数据
// 将 JSON 字符串解析为 JSON 对象
JsonObject jsonObject = new Gson().fromJson(response.body(), JsonObject.class);
// 从 JSON 对象中获取 resp 对象
JsonObject respObject = jsonObject.getAsJsonObject("resp");
// 从 resp 对象中获取属性值
String code = respObject.get("code").getAsString(); // 获取 code 属性的值
String message = respObject.get("message").getAsString(); // 获取 message 属性的值
String id = respObject.get("id").getAsString(); // 获取 id 属性的值
// 输出属性值
System.out.println("code: " + code);
System.out.println("message: " + message);
System.out.println("id: " + id);
String queryJsonBody = "{\n" +
" \"appid\": \"" + appid + "\",\n" +
" \"token\": \"" + token + "\",\n" +
" \"cluster\": \"" + cluster + "\",\n" +
" \"id\": \"" + id + "\"\n" +
" }";
System.out.println("queryJsonBody: " + queryJsonBody);
// 创建POST请求
HttpRequest queryRequest = HttpRequest.newBuilder()
.uri(URI.create("https://openspeech.bytedance.com/api/v1/auc/query")) // 设置请求的URL
.header("Content-Type", "application/json") // 设置请求头
.header("Authorization", bearerToken) // 设置请求头
.POST(HttpRequest.BodyPublishers.ofString(queryJsonBody)) // 设置请求体为JSON数据
.build();
// 发送请求并获取响应
HttpResponse<String> queryResponse = httpClient.send(queryRequest, HttpResponse.BodyHandlers.ofString());
//解析返回的json数据 从 JSON 对象中获取 resp 对象
JsonObject queryJsonObject = new Gson().fromJson(queryResponse.body(), JsonObject.class);
JsonObject queryRespObject = queryJsonObject.getAsJsonObject("resp");
String text = queryRespObject.get("text").getAsString(); // 获取 text 属性的值
//如果返回的text为空,说明还没有识别出来,可以继续查询
while (text.equals("")) {
Thread.sleep(1000);
queryResponse = httpClient.send(queryRequest, HttpResponse.BodyHandlers.ofString());
queryJsonObject = new Gson().fromJson(queryResponse.body(), JsonObject.class);
queryRespObject = queryJsonObject.getAsJsonObject("resp");
text = queryRespObject.get("text").getAsString(); // 获取 text 属性的值
}
System.out.println("text: " + text);
clientMessage = text;
clientMessage = new String(clientMessage.getBytes("utf-8"), "utf-8");
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
//将消息封装成json格式
JSONObject messageJsonObject = new JSONObject();
messageJsonObject.put("type", "text");
messageJsonObject.put("ID", Integer.parseInt(userId));
messageJsonObject.put("data", clientMessage);
messageJsonObject.put("firstConnect", firstConnected);
messageJsonObject.put("emotion", lastEmotion);
// 防止心跳与消息发送冲突
synchronized (lock){
//socket将clientMessage发送给服务器
BufferedOutputStream bos;
try {
bos = new BufferedOutputStream(socket.getOutputStream());
bos.write(messageJsonObject.toJSONString().getBytes());
firstConnected = false;
bos.flush();
} catch(Exception e) {
System.out.println("服务器已断开");
socket = new Socket(pythonServer, 12345);
bos = new BufferedOutputStream(socket.getOutputStream());
System.out.println("重新连接成功");
messageJsonObject.put("firstConnect", true);
bos.write(messageJsonObject.toJSONString().getBytes());
firstConnected = false;
bos.flush();
}
}
// 读取服务器上的响应数据
BufferedInputStream bis1 = new BufferedInputStream(socket.getInputStream());
byte[] data = new byte[10240];
int len = bis1.read(data);
String rec = new String(data,0,len);
// log.info("rec:"+rec);
JSONObject recJsonObject = JSONObject.parseObject(rec);
String recData = recJsonObject.getString("data");
String emotion = recJsonObject.getString("emotion");
double pleasure;
double arousal;
double dominance;
// 获取pleasure
try {
emotion = emotion.replace("'", "").replace("'", "");
emotion = emotion.replace(" ", "").replace(" ", "");
pleasure = Double.parseDouble(emotion.substring(emotion.indexOf("P") + 2, emotion.indexOf("A") - 1));
arousal = Double.parseDouble(emotion.substring(emotion.indexOf("A") + 2, emotion.indexOf("D") - 1));
dominance = Double.parseDouble(emotion.substring(emotion.indexOf("D") + 2, emotion.length() - 1));
} catch (Exception e) {
e.printStackTrace();
pleasure = 0.5;
arousal = 0.5;
dominance = 0.5;
}
log.info("PAD:"+pleasure + " " + pressure + " " + heartRate + " " + sleepScore);
//计算情绪
PADAlgorithm.EmotionType PADemotionType = PADAlgorithm.getEmotionWithAI(pleasure, pressure, heartRate, sleepScore, arousal, dominance);
log.info("PAD-emotion:" + PADAlgorithm.getEmotionString(PADemotionType));
// 使用replace去除 [ ] 符号
emotion = emotion.replace("[", "").replace("]", "");
// 使用replace去除 ' 符号 和 ' 符号
emotion = emotion.replace("'", "").replace("'", "");
// 使用replace去除 " 符合 和 " 符号
emotion = emotion.replace("\"", "").replace("\"", "");
String operator = recJsonObject.getString("operator");
// log.info("operator:"+operator);
JSONObject operateJsonObject = JSONObject.parseObject(operator);
String operateType = operateJsonObject.getString("type");
if (operateType.equals("todo")){
JSONObject todoJsonObject = JSONObject.parseObject(operateJsonObject.getString("data"));
String date = todoJsonObject.getString("time");
// log.info("date:"+date);
String name = todoJsonObject.getString("str");
// log.info("name:"+name);
Todo todo = new Todo();
// Timestamp timestamp = Timestamp.valueOf(date);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date parsedDate = dateFormat.parse(date);
Timestamp timestamp = new Timestamp(parsedDate.getTime());
todo.setDate(timestamp);
todo.setName(name);
todo.setUserid(Integer.parseInt(userId));
todo.setIsfinished(0);
todoMapper.insert(todo);
}
// //判断情绪是否在情绪列表中
// if (EMOTIONS.containsKey(PADemotion)) {
// emotion = EMOTIONS.get(emotion).toString();
//// log.info("转换后emotion:" + emotion);
// }else {
// emotion = "-1";
// }
emotion = String.valueOf(PADAlgorithm.getEmoji(PADemotionType));
//text为utf-8字符,解码
String recText = new String(recData.getBytes("utf-8"), "utf-8");
// log.info("【websocket消息】 用户:"+ userId + " 接收消息:"+recText);
//将获取到的消息发送给接收端
JSONObject serverJsonObject = new JSONObject();
serverJsonObject.put("type", 0);
serverJsonObject.put("message", recText);
sendMoreMessage(new String[]{targ | AppleGrey/D-emo-server | src/main/java/com/studio314/d_emo/server/ChatServer.java | 8,005 | // 从 resp 对象中获取属性值 | line_comment | zh-cn | package com.studio314.d_emo.server;
import com.alibaba.fastjson.JSONObject;
import com.studio314.d_emo.mapper.ChatsMapper;
import com.studio314.d_emo.mapper.TodoMapper;
import com.studio314.d_emo.pojo.Chats;
import com.studio314.d_emo.pojo.Todo;
import com.studio314.d_emo.server.impl.TodoServerImpl;
import com.studio314.d_emo.utils.PADAlgorithm;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
@Component
@Slf4j
@ServerEndpoint("/webSocketServer/{myUserId}")
public class ChatServer {
/**
* 与客户端的连接会话,需要通过他来给客户端发消息
*/
private Session session;
private static String pythonServer;
public static Map<String, Integer> EMOTIONS = new LinkedHashMap<>();
static {
EMOTIONS.put("高兴", 2131230905);
EMOTIONS.put("生气", 2131230916);
EMOTIONS.put("喜欢", 2131230927);
EMOTIONS.put("疲劳", 2131230929);
EMOTIONS.put("笑哭", 2131230930);
EMOTIONS.put("调皮", 2131230931);
EMOTIONS.put("焦虑", 2131230932);
EMOTIONS.put("亲亲", 2131230933);
EMOTIONS.put("安逸", 2131230934);
EMOTIONS.put("烦躁", 2131230906);
EMOTIONS.put("痛苦", 2131230907);
EMOTIONS.put("惊吓", 2131230908);
EMOTIONS.put("失落", 2131230909);
EMOTIONS.put("害怕", 2131230910);
EMOTIONS.put("轻松", 2131230911);
EMOTIONS.put("吃惊", 2131230912);
EMOTIONS.put("开心", 2131230913);
EMOTIONS.put("兴奋", 2131230914);
EMOTIONS.put("大哭", 2131230915);
EMOTIONS.put("愤恨", 2131230917);
EMOTIONS.put("愉快", 2131230918);
EMOTIONS.put("不满", 2131230919);
EMOTIONS.put("悲伤", 2131230920);
EMOTIONS.put("恐惧", 2131230921);
EMOTIONS.put("满足", 2131230922);
EMOTIONS.put("小恶魔", 2131230923);
EMOTIONS.put("羞愧", 2131230924);
EMOTIONS.put("爱", 2131230925);
EMOTIONS.put("点赞", 2131230926);
EMOTIONS.put("许愿", 2131230928);
}
@Value("${ip.python" +
"Server}") String setPythonServer(String pythonServer){
return ChatServer.pythonServer = pythonServer;
}
/**
* 是否第一次连接 ai 服务器
*/
private boolean firstConnected = true;
private Socket socket;
/**
* 当前用户ID
*/
private String userId;
/**
* concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
* 虽然@Component默认是单例模式的,但springboot还是会为每个websocket连接初始化一个bean,所以可以用一个静态set保存起来。
*/
private static CopyOnWriteArraySet<ChatServer> webSockets =new CopyOnWriteArraySet<>();
/**
*用来存在线连接用户信息
*/
private static ConcurrentHashMap<String,Session> sessionPool = new ConcurrentHashMap<String,Session>();
@Autowired ChatsMapper setChatsMapper(ChatsMapper chatsMapper){
return ChatServer.chatsMapper = chatsMapper;
}
static ChatsMapper chatsMapper;
@Autowired
TodoMapper setTodoMapper(TodoMapper todoMapper){
return ChatServer.todoMapper = todoMapper;
}
static TodoMapper todoMapper;
private static final int HEARTBEAT_INTERVAL = 1000; // 心跳间隔时间,单位:毫秒
private final Object lock = new Object(); // 用于线程同步的锁对象
private class HeartbeatThread extends Thread {
@Override
public void run() {
try {
OutputStream outputStream = socket.getOutputStream();
while (true) {
synchronized (lock) {
// 检查是否需要建立连接
if (socket == null || socket.isClosed()) {
// 创建新的Socket连接
socket = new Socket(pythonServer, 12345);
outputStream = socket.getOutputStream();
// System.out.println("建立连接");
}
// 发送心跳包数据
//将消息封装成json格式
JSONObject heartJsonObject = new JSONObject();
heartJsonObject.put("type", "heart");
heartJsonObject.put("firstConnect", firstConnected);
outputStream.write(heartJsonObject.toJSONString().getBytes());
outputStream.flush();
// log.info("心跳发送成功...");
BufferedInputStream bis1 = new BufferedInputStream(socket.getInputStream());
byte[] data = new byte[10240];
int len = bis1.read(data);
String rec = new String(data,0,len);
// log.info("rec:"+rec);
if (rec.equals("success")) {
// log.info("心跳包收到回复...");
} else {
log.info("心跳包收到回复异常,尝试重连");
// 关闭旧的Socket连接
try {
if (socket != null && !socket.isClosed()) {
socket.close();
// 创建新的Socket连接
socket = new Socket(pythonServer, 12345);
outputStream = socket.getOutputStream();
log.info("与服务器重新建立连接成功");
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
// 等待一段时间
Thread.sleep(HEARTBEAT_INTERVAL);
}
} catch (IOException e) {
e.printStackTrace();
log.info("心跳发送失败,尝试重新连接...");
// 关闭旧的Socket连接
try {
if (socket != null && !socket.isClosed()) {
socket.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* 连接成功方法
* @param session 连接会话
* @param userId 用户编号
*/
@OnOpen
public void onOpen(Session session , @PathParam("myUserId") String userId){
try {
this.session = session;
this.userId = userId;
webSockets.add(this);
sessionPool.put(userId, session);
log.info("【websocket消息】 用户:" + userId + " 加入连接...");
// 创建Socket连接
socket = new Socket(pythonServer, 12345);
// 启动心跳线程
new HeartbeatThread().start();
// log.info("【websocket消息】 用户:" + userId + " 连接服务器成功...");
} catch (Exception e) {
log.error("---------------WebSocket连接异常---------------");
}
}
/**
* 关闭连接
*/
@OnClose
public void onClose(){
try {
webSockets.remove(this);
sessionPool.remove(this.userId);
log.info("【websocket消息】 用户:"+ this.userId + " 断开连接...");
} catch (Exception e) {
log.error("---------------WebSocket断开异常---------------");
}
}
@OnMessage
public void onMessage(@PathParam("myUserId") String userId, String body){
try {
if (socket == null) {
socket = new Socket(pythonServer, 12345);
socket.setKeepAlive(true);
log.info("【websocket消息】 用户:" + userId + " 连接服务器成功...");
}
//将Body解析
JSONObject clientJsonObject = JSONObject.parseObject(body);
//获取目标用户地址
String targetUserId = clientJsonObject.getString("userId");
//获取消息内容
String clientMessage = clientJsonObject.getString("content");
log.info("【websocket消息】 用户:"+ userId + " 发送消息:"+clientMessage);
//获取heartRate
float heartRate = clientJsonObject.getFloat("heartRate");
//获取睡眠的分
float sleepScore = clientJsonObject.getFloat("sleepScore");
//获取压力值
float pressure = clientJsonObject.getFloat("pressure");
log.info("heartRate:"+heartRate + " sleepScore:"+sleepScore + " pressure:"+pressure);
// log.info("【websocket消息】 用户:"+ userId + " 发送消息:"+clientMessage);
int audioTime = clientJsonObject.getIntValue("time");
//获取消息类型
int type = clientJsonObject.getIntValue("type");
//获取上一条消息的情绪
Chats lastChat = chatsMapper.getLastChat(Integer.parseInt(userId));
String lastEmotion;
if(lastChat == null || lastChat.getEmotion() == null){
lastEmotion = "未知";
} else {
lastEmotion = lastChat.getEmotion();
int emotionID = Integer.parseInt(lastEmotion);
//将数字映射为文字,如果为-1或未找到,都是未知
if (EMOTIONS.containsValue(emotionID)) {
for (Map.Entry<String, Integer> entry : EMOTIONS.entrySet()) {
if (entry.getValue().equals(emotionID)) {
lastEmotion = entry.getKey();
break;
}
}
} else {
lastEmotion = "未知";
}
}
if (type == 0){
//将消息封装成json格式
JSONObject messageJsonObject = new JSONObject();
messageJsonObject.put("type", "text");
messageJsonObject.put("ID", Integer.parseInt(userId));
messageJsonObject.put("data", clientMessage);
messageJsonObject.put("firstConnect", firstConnected);
messageJsonObject.put("emotion", lastEmotion);
log.info(clientMessage);
// 防止心跳与消息发送冲突
synchronized (lock) {
//socket将clientMessage发送给服务器
BufferedOutputStream bos;
try {
bos = new BufferedOutputStream(socket.getOutputStream());
bos.write(messageJsonObject.toJSONString().getBytes(StandardCharsets.UTF_8));
firstConnected = false;
bos.flush();
} catch(Exception e) {
log.info("服务器已断开");
socket = new Socket(pythonServer, 12345);
bos = new BufferedOutputStream(socket.getOutputStream());
log.info("重新连接成功");
messageJsonObject.put("firstConnect", true);
bos.write(messageJsonObject.toJSONString().getBytes());
firstConnected = false;
bos.flush();
}
}
// socket.shutdownOutput();
// 读取服务器上的响应数据
BufferedInputStream bis1 = new BufferedInputStream(socket.getInputStream());
byte[] data = new byte[10240];
int len = bis1.read(data);
String rec = new String(data,0,len);
// log.info("rec:"+rec);
JSONObject recJsonObject = JSONObject.parseObject(rec);
String recData = recJsonObject.getString("data");
String emotion = recJsonObject.getString("emotion");
log.info("AI-emotion:"+emotion);
double pleasure;
double arousal;
double dominance;
// 获取pleasure
try {
emotion = emotion.replace("'", "").replace("'", "");
emotion = emotion.replace(" ", "").replace(" ", "");
pleasure = Double.parseDouble(emotion.substring(emotion.indexOf("P") + 2, emotion.indexOf("A") - 1));
arousal = Double.parseDouble(emotion.substring(emotion.indexOf("A") + 2, emotion.indexOf("D") - 1));
dominance = Double.parseDouble(emotion.substring(emotion.indexOf("D") + 2, emotion.length() - 1));
} catch (Exception e) {
e.printStackTrace();
pleasure = 0.5;
arousal = 0.5;
dominance = 0.5;
}
log.info("PAD:"+pleasure + " " + pressure + " " + heartRate + " " + sleepScore);
// 使用replace去除 [ ] 符号
emotion = emotion.replace("[", "").replace("]", "");
// 使用replace去除 ' 符号 和 ' 符号
emotion = emotion.replace("'", "").replace("'", "");
// 使用replace去除 " 符合 和 " 符号
emotion = emotion.replace("\"", "").replace("\"", "");
// //测试判断情况
// pressure = ;
// heartRate = ;
// sleepScore = ;
//计算情绪
PADAlgorithm.EmotionType PADemotionType = PADAlgorithm.getEmotionWithAI(pleasure, pressure, heartRate, sleepScore, arousal, dominance);
log.info("PAD-emotion:" + PADAlgorithm.getEmotionString(PADemotionType));
String operator = recJsonObject.getString("operator");
// log.info("operator:"+operator);
JSONObject operateJsonObject = JSONObject.parseObject(operator);
String operateType = operateJsonObject.getString("type");
log.info("operateType:"+operateType);
if (operateType.equals("todo")){
JSONObject todoJsonObject = JSONObject.parseObject(operateJsonObject.getString("data"));
String date = todoJsonObject.getString("time");
// log.info("date:"+date);
String name = todoJsonObject.getString("str");
// log.info("name:"+name);
Todo todo = new Todo();
// Timestamp timestamp = Timestamp.valueOf(date);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date parsedDate = dateFormat.parse(date);
Timestamp timestamp = new Timestamp(parsedDate.getTime());
todo.setDate(timestamp);
log.info("待办timestamp:"+timestamp);
todo.setName(name);
log.info("userId:"+userId);
todo.setUserid(Integer.parseInt(userId));
todo.setIsfinished(0);
todoMapper.insert(todo);
} else if (operateType.equals("diary")) {
}
// 使用replace去除 [ ] 符号
emotion = emotion.replace("[", "").replace("]", "");
// 使用replace去除 ' 符号 和 ' 符号
emotion = emotion.replace("'", "").replace("'", "");
// 使用replace去除 " 符合 和 " 符号
emotion = emotion.replace("\"", "").replace("\"", "");
// log.info("emotionaaaaaaa:"+emotion);
// //判断情绪是否在情绪列表中
// if (EMOTIONS.containsKey(PADemotion)) {
// emotion = EMOTIONS.get(emotion).toString();
//// log.info("转换后emotion:" + emotion);
// }else {
// emotion = "-1";
// }
emotion = String.valueOf(PADAlgorithm.getEmoji(PADemotionType));
//text为utf-8字符,解码
String recText = new String(recData.getBytes("utf-8"), "utf-8");
// log.info("【websocket消息】 用户:"+ userId + " 接收消息:"+recText);
//将获取到的消息发送给接收端
JSONObject serverJsonObject = new JSONObject();
serverJsonObject.put("type", 0);
serverJsonObject.put("message", recText);
sendMoreMessage(new String[]{targetUserId} , JSONObject.toJSONString(serverJsonObject));
// log.info("emotion:"+emotion);
// 保存文本消息
chatsMapper.insertChat(Integer.parseInt(userId), clientMessage, type, 0, emotion);
//将获取到的信息保存到数据库
chatsMapper.insertChat(Integer.parseInt(userId), recText, 0, 1, null);
} else if (type == 1) {
//将消息封装成json格式
JSONObject messageJsonObject = new JSONObject();
messageJsonObject.put("type", "img");
messageJsonObject.put("ID", Integer.parseInt(userId));
messageJsonObject.put("data", clientMessage);
messageJsonObject.put("firstConnect", firstConnected);
messageJsonObject.put("emotion", lastEmotion);
synchronized (lock){
//socket将clientMessage发送给服务器
BufferedOutputStream bos;
try {
bos = new BufferedOutputStream(socket.getOutputStream());
bos.write(messageJsonObject.toJSONString().getBytes());
firstConnected = false;
bos.flush();
} catch(Exception e) {
System.out.println("服务器已断开");
socket = new Socket(pythonServer, 12345);
bos = new BufferedOutputStream(socket.getOutputStream());
System.out.println("重新连接成功");
messageJsonObject.put("firstConnect", true);
bos.write(messageJsonObject.toJSONString().getBytes());
firstConnected = false;
bos.flush();
}
}
// socket.shutdownOutput();
// 读取服务器上的响应数据
BufferedInputStream bis1 = new BufferedInputStream(socket.getInputStream());
byte[] data = new byte[10240];
int len = bis1.read(data);
String rec = new String(data,0,len);
JSONObject recJsonObject = JSONObject.parseObject(rec);
String recData = recJsonObject.getString("data");
String emotion = recJsonObject.getString("emotion");
double pleasure;
double arousal;
double dominance;
// 获取pleasure
try {
emotion = emotion.replace("'", "").replace("'", "");
emotion = emotion.replace(" ", "").replace(" ", "");
pleasure = Double.parseDouble(emotion.substring(emotion.indexOf("P") + 2, emotion.indexOf("A") - 1));
arousal = Double.parseDouble(emotion.substring(emotion.indexOf("A") + 2, emotion.indexOf("D") - 1));
dominance = Double.parseDouble(emotion.substring(emotion.indexOf("D") + 2, emotion.length() - 1));
} catch (Exception e) {
e.printStackTrace();
pleasure = 0.5;
arousal = 0.5;
dominance = 0.5;
}
log.info("PAD:"+pleasure + " " + pressure + " " + heartRate + " " + sleepScore);
//计算情绪
PADAlgorithm.EmotionType PADemotionType = PADAlgorithm.getEmotionWithAI(pleasure, pressure, heartRate, sleepScore, arousal, dominance);
log.info("PAD-emotion:" + PADAlgorithm.getEmotionString(PADemotionType));
// 使用replace去除 [ ] 符号
emotion = emotion.replace("[", "").replace("]", "");
// 使用replace去除 ' 符号 和 ' 符号
emotion = emotion.replace("'", "").replace("'", "");
// 使用replace去除 " 符合 和 " 符号
emotion = emotion.replace("\"", "").replace("\"", "");
//text为utf-8字符,解码
String recText = new String(recData.getBytes("utf-8"), "utf-8");
// log.info("【websocket消息】 用户:"+ userId + " 接收消息:"+recText);
// //判断情绪是否在情绪列表中
// if (EMOTIONS.containsKey(PADemotion)) {
// emotion = EMOTIONS.get(emotion).toString();
//// log.info("转换后emotion:" + emotion);
// }else {
// emotion = "-1";
// }
emotion = String.valueOf(PADAlgorithm.getEmoji(PADemotionType));
//将获取到的消息发送给接收端
JSONObject serverJsonObject = new JSONObject();
serverJsonObject.put("type", 0);
serverJsonObject.put("message", recText);
sendMoreMessage(new String[]{targetUserId} , JSONObject.toJSONString(serverJsonObject));
// 保存图片消息
chatsMapper.insertChat(Integer.parseInt(userId), clientMessage, type, 0, emotion);
//将获取到的信息保存到数据库
chatsMapper.insertChat(Integer.parseInt(userId), recText, 0, 1, null);
} else if (type == 2) {
// 分别为每个属性创建String变量
String appid = "8635128650";
String token = "0M1WqciqDTrWwOWo9L8voBAMTuTFYozO";
String cluster = "volc_auc_common";
String uid = "388808087185088";
String format = "ogg";
String audioUrl = clientMessage;
// String audioUrl = "https://d-emo.obs.cn-north-4.myhuaweicloud.com/chat/audio/ea31da9e-b997-4b73-886e-fd778f7d17a8.ogg";
String bearerToken ="Bearer; "+token;
// 构建JSON字符串
String jsonBody = "{\n" +
" \"app\": {\n" +
" \"appid\": \"" + appid + "\",\n" +
" \"token\": \"" + token + "\",\n" +
" \"cluster\": \"" + cluster + "\"\n" +
" },\n" +
" \"user\": {\n" +
" \"uid\": \"" + uid + "\"\n" +
" },\n" +
" \"audio\": {\n" +
" \"format\": \"" + format + "\",\n" +
" \"url\": \"" + audioUrl + "\"\n" +
" }\n" +
"}";
// 创建HttpClient实例
HttpClient httpClient = HttpClient.newBuilder().build();
// 创建POST请求
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://openspeech.bytedance.com/api/v1/auc/submit")) // 设置请求的URL
.header("Content-Type", "application/json") // 设置请求头
.header("Authorization", bearerToken) // 设置请求头
.POST(HttpRequest.BodyPublishers.ofString(jsonBody)) // 设置请求体为JSON数据
.build();
// 发送请求并获取响应
try {
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
// 输出响应结果
System.out.println("Response Code: " + response.statusCode());
System.out.println("Response Body: " + response.body());
//下面解析返回的json数据
// 将 JSON 字符串解析为 JSON 对象
JsonObject jsonObject = new Gson().fromJson(response.body(), JsonObject.class);
// 从 JSON 对象中获取 resp 对象
JsonObject respObject = jsonObject.getAsJsonObject("resp");
// 从 <SUF>
String code = respObject.get("code").getAsString(); // 获取 code 属性的值
String message = respObject.get("message").getAsString(); // 获取 message 属性的值
String id = respObject.get("id").getAsString(); // 获取 id 属性的值
// 输出属性值
System.out.println("code: " + code);
System.out.println("message: " + message);
System.out.println("id: " + id);
String queryJsonBody = "{\n" +
" \"appid\": \"" + appid + "\",\n" +
" \"token\": \"" + token + "\",\n" +
" \"cluster\": \"" + cluster + "\",\n" +
" \"id\": \"" + id + "\"\n" +
" }";
System.out.println("queryJsonBody: " + queryJsonBody);
// 创建POST请求
HttpRequest queryRequest = HttpRequest.newBuilder()
.uri(URI.create("https://openspeech.bytedance.com/api/v1/auc/query")) // 设置请求的URL
.header("Content-Type", "application/json") // 设置请求头
.header("Authorization", bearerToken) // 设置请求头
.POST(HttpRequest.BodyPublishers.ofString(queryJsonBody)) // 设置请求体为JSON数据
.build();
// 发送请求并获取响应
HttpResponse<String> queryResponse = httpClient.send(queryRequest, HttpResponse.BodyHandlers.ofString());
//解析返回的json数据 从 JSON 对象中获取 resp 对象
JsonObject queryJsonObject = new Gson().fromJson(queryResponse.body(), JsonObject.class);
JsonObject queryRespObject = queryJsonObject.getAsJsonObject("resp");
String text = queryRespObject.get("text").getAsString(); // 获取 text 属性的值
//如果返回的text为空,说明还没有识别出来,可以继续查询
while (text.equals("")) {
Thread.sleep(1000);
queryResponse = httpClient.send(queryRequest, HttpResponse.BodyHandlers.ofString());
queryJsonObject = new Gson().fromJson(queryResponse.body(), JsonObject.class);
queryRespObject = queryJsonObject.getAsJsonObject("resp");
text = queryRespObject.get("text").getAsString(); // 获取 text 属性的值
}
System.out.println("text: " + text);
clientMessage = text;
clientMessage = new String(clientMessage.getBytes("utf-8"), "utf-8");
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
//将消息封装成json格式
JSONObject messageJsonObject = new JSONObject();
messageJsonObject.put("type", "text");
messageJsonObject.put("ID", Integer.parseInt(userId));
messageJsonObject.put("data", clientMessage);
messageJsonObject.put("firstConnect", firstConnected);
messageJsonObject.put("emotion", lastEmotion);
// 防止心跳与消息发送冲突
synchronized (lock){
//socket将clientMessage发送给服务器
BufferedOutputStream bos;
try {
bos = new BufferedOutputStream(socket.getOutputStream());
bos.write(messageJsonObject.toJSONString().getBytes());
firstConnected = false;
bos.flush();
} catch(Exception e) {
System.out.println("服务器已断开");
socket = new Socket(pythonServer, 12345);
bos = new BufferedOutputStream(socket.getOutputStream());
System.out.println("重新连接成功");
messageJsonObject.put("firstConnect", true);
bos.write(messageJsonObject.toJSONString().getBytes());
firstConnected = false;
bos.flush();
}
}
// 读取服务器上的响应数据
BufferedInputStream bis1 = new BufferedInputStream(socket.getInputStream());
byte[] data = new byte[10240];
int len = bis1.read(data);
String rec = new String(data,0,len);
// log.info("rec:"+rec);
JSONObject recJsonObject = JSONObject.parseObject(rec);
String recData = recJsonObject.getString("data");
String emotion = recJsonObject.getString("emotion");
double pleasure;
double arousal;
double dominance;
// 获取pleasure
try {
emotion = emotion.replace("'", "").replace("'", "");
emotion = emotion.replace(" ", "").replace(" ", "");
pleasure = Double.parseDouble(emotion.substring(emotion.indexOf("P") + 2, emotion.indexOf("A") - 1));
arousal = Double.parseDouble(emotion.substring(emotion.indexOf("A") + 2, emotion.indexOf("D") - 1));
dominance = Double.parseDouble(emotion.substring(emotion.indexOf("D") + 2, emotion.length() - 1));
} catch (Exception e) {
e.printStackTrace();
pleasure = 0.5;
arousal = 0.5;
dominance = 0.5;
}
log.info("PAD:"+pleasure + " " + pressure + " " + heartRate + " " + sleepScore);
//计算情绪
PADAlgorithm.EmotionType PADemotionType = PADAlgorithm.getEmotionWithAI(pleasure, pressure, heartRate, sleepScore, arousal, dominance);
log.info("PAD-emotion:" + PADAlgorithm.getEmotionString(PADemotionType));
// 使用replace去除 [ ] 符号
emotion = emotion.replace("[", "").replace("]", "");
// 使用replace去除 ' 符号 和 ' 符号
emotion = emotion.replace("'", "").replace("'", "");
// 使用replace去除 " 符合 和 " 符号
emotion = emotion.replace("\"", "").replace("\"", "");
String operator = recJsonObject.getString("operator");
// log.info("operator:"+operator);
JSONObject operateJsonObject = JSONObject.parseObject(operator);
String operateType = operateJsonObject.getString("type");
if (operateType.equals("todo")){
JSONObject todoJsonObject = JSONObject.parseObject(operateJsonObject.getString("data"));
String date = todoJsonObject.getString("time");
// log.info("date:"+date);
String name = todoJsonObject.getString("str");
// log.info("name:"+name);
Todo todo = new Todo();
// Timestamp timestamp = Timestamp.valueOf(date);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date parsedDate = dateFormat.parse(date);
Timestamp timestamp = new Timestamp(parsedDate.getTime());
todo.setDate(timestamp);
todo.setName(name);
todo.setUserid(Integer.parseInt(userId));
todo.setIsfinished(0);
todoMapper.insert(todo);
}
// //判断情绪是否在情绪列表中
// if (EMOTIONS.containsKey(PADemotion)) {
// emotion = EMOTIONS.get(emotion).toString();
//// log.info("转换后emotion:" + emotion);
// }else {
// emotion = "-1";
// }
emotion = String.valueOf(PADAlgorithm.getEmoji(PADemotionType));
//text为utf-8字符,解码
String recText = new String(recData.getBytes("utf-8"), "utf-8");
// log.info("【websocket消息】 用户:"+ userId + " 接收消息:"+recText);
//将获取到的消息发送给接收端
JSONObject serverJsonObject = new JSONObject();
serverJsonObject.put("type", 0);
serverJsonObject.put("message", recText);
sendMoreMessage(new String[]{targetUserI | false |
26558_9 | package com.testm;
import java.net.URISyntaxException;
import org.fusesource.mqtt.client.BlockingConnection;
import org.fusesource.mqtt.client.Future;
import org.fusesource.mqtt.client.FutureConnection;
import org.fusesource.mqtt.client.MQTT;
import org.fusesource.mqtt.client.Message;
import org.fusesource.mqtt.client.QoS;
import org.fusesource.mqtt.client.Topic;
public class MClient {
//private final static String CLIENT_ID = "publishService";
public static Topic[] topics = {
new Topic("/beacons", QoS.AT_MOST_ONCE)}; //AT_LEAST_ONCE
public static void main(String[] args) {
//创建MQTT对象
MQTT mqtt = new MQTT();
try {
//设置mqtt broker的ip和端口
mqtt.setHost("tcp://192.168.1.123:1883");
// 原来的值:876543210,用于设置客户端会话的ID。在setCleanSession(false);被调用时,MQTT服务器利用该ID获得相应的会话。此ID应少于23个字符,默认根据本机地址、端口和时间自动生成
mqtt.setClientId("beacons");
//连接前清空会话信息, 若设为false,MQTT服务器将持久化客户端会话的主体订阅和ACK位置,默认为true
mqtt.setCleanSession(true);
//设置重新连接的次数
mqtt.setReconnectAttemptsMax(6);
//设置重连的间隔时间
mqtt.setReconnectDelay(2000);
//设置心跳时间
mqtt.setKeepAlive((short)30); // 低耗网络,但是又需要及时获取数据,心跳30s
//设置缓冲的大小
mqtt.setSendBufferSize(2*1024*1024); //发送最大缓冲为2M
//获取mqtt的连接对象BlockingConnection
// final FutureConnection connection= mqtt.futureConnection();
BlockingConnection connection = mqtt.blockingConnection();
connection.connect();
if(connection.isConnected()){
System.out.println("连接成功");
}else{
System.out.println("连接失败");
}
while(true){
Thread.sleep(2000);
byte[] qoses = connection.subscribe(topics);
Message message = connection.receive();
System.out.println("getTopic:"+message.getTopic());
byte[] payload = message.getPayload();
message.ack();
System.out.println("MQTTFutureClient.Receive Message "+ "Topic Title :"+message.getTopic()+" context :"+String.valueOf(message.getPayloadBuffer()));
}
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}finally{
}
}
}
| AprilBrother/mqtt-client-examples | java/MqttClient.java | 723 | //设置心跳时间
| line_comment | zh-cn | package com.testm;
import java.net.URISyntaxException;
import org.fusesource.mqtt.client.BlockingConnection;
import org.fusesource.mqtt.client.Future;
import org.fusesource.mqtt.client.FutureConnection;
import org.fusesource.mqtt.client.MQTT;
import org.fusesource.mqtt.client.Message;
import org.fusesource.mqtt.client.QoS;
import org.fusesource.mqtt.client.Topic;
public class MClient {
//private final static String CLIENT_ID = "publishService";
public static Topic[] topics = {
new Topic("/beacons", QoS.AT_MOST_ONCE)}; //AT_LEAST_ONCE
public static void main(String[] args) {
//创建MQTT对象
MQTT mqtt = new MQTT();
try {
//设置mqtt broker的ip和端口
mqtt.setHost("tcp://192.168.1.123:1883");
// 原来的值:876543210,用于设置客户端会话的ID。在setCleanSession(false);被调用时,MQTT服务器利用该ID获得相应的会话。此ID应少于23个字符,默认根据本机地址、端口和时间自动生成
mqtt.setClientId("beacons");
//连接前清空会话信息, 若设为false,MQTT服务器将持久化客户端会话的主体订阅和ACK位置,默认为true
mqtt.setCleanSession(true);
//设置重新连接的次数
mqtt.setReconnectAttemptsMax(6);
//设置重连的间隔时间
mqtt.setReconnectDelay(2000);
//设置 <SUF>
mqtt.setKeepAlive((short)30); // 低耗网络,但是又需要及时获取数据,心跳30s
//设置缓冲的大小
mqtt.setSendBufferSize(2*1024*1024); //发送最大缓冲为2M
//获取mqtt的连接对象BlockingConnection
// final FutureConnection connection= mqtt.futureConnection();
BlockingConnection connection = mqtt.blockingConnection();
connection.connect();
if(connection.isConnected()){
System.out.println("连接成功");
}else{
System.out.println("连接失败");
}
while(true){
Thread.sleep(2000);
byte[] qoses = connection.subscribe(topics);
Message message = connection.receive();
System.out.println("getTopic:"+message.getTopic());
byte[] payload = message.getPayload();
message.ack();
System.out.println("MQTTFutureClient.Receive Message "+ "Topic Title :"+message.getTopic()+" context :"+String.valueOf(message.getPayloadBuffer()));
}
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}finally{
}
}
}
| false |
25139_2 | package cn.Launcher;
import javax.swing.*;
import java.awt.event.*;
public class adsad extends JDialog {
private JPanel contentPane;
private JButton buttonOK;
private JButton buttonCancel;
public adsad() {
setContentPane(contentPane);
setModal(true);
getRootPane().setDefaultButton(buttonOK);
buttonOK.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
onOK();
}
});
buttonCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
onCancel();
}
});
// 点击 X 时调用 onCancel()
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
onCancel();
}
});
// 遇到 ESCAPE 时调用 onCancel()
contentPane.registerKeyboardAction(new ActionListener() {
public void actionPerformed(ActionEvent e) {
onCancel();
}
}, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
}
private void onOK() {
// 在此处添加您的代码
dispose();
}
private void onCancel() {
// 必要时在此处添加您的代码
dispose();
}
public static void main(String[] args) {
adsad dialog = new adsad();
dialog.pack();
dialog.setVisible(true);
System.exit(0);
}
}
| Araykal/Open-BokerLite-Launcher | cn/Launcher/adsad.java | 347 | // 在此处添加您的代码
| line_comment | zh-cn | package cn.Launcher;
import javax.swing.*;
import java.awt.event.*;
public class adsad extends JDialog {
private JPanel contentPane;
private JButton buttonOK;
private JButton buttonCancel;
public adsad() {
setContentPane(contentPane);
setModal(true);
getRootPane().setDefaultButton(buttonOK);
buttonOK.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
onOK();
}
});
buttonCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
onCancel();
}
});
// 点击 X 时调用 onCancel()
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
onCancel();
}
});
// 遇到 ESCAPE 时调用 onCancel()
contentPane.registerKeyboardAction(new ActionListener() {
public void actionPerformed(ActionEvent e) {
onCancel();
}
}, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
}
private void onOK() {
// 在此 <SUF>
dispose();
}
private void onCancel() {
// 必要时在此处添加您的代码
dispose();
}
public static void main(String[] args) {
adsad dialog = new adsad();
dialog.pack();
dialog.setVisible(true);
System.exit(0);
}
}
| true |
56221_0 | package priv.linsu.game.life.simulator.model.domain.text;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class ConditionEqual {
//岁数
private Integer age;
//体质
private Integer constitution;
//智力
private Integer intelligence;
//运气
private Integer luck;
//容貌
private Integer appearance;
//财富
private Integer wealth;
//权力
private Integer power;
//时间节点
private Integer currentId;
private String status;
private String talent;
}
| ArcherLinsu/life-simulator | server/src/main/java/priv/linsu/game/life/simulator/model/domain/text/ConditionEqual.java | 192 | //时间节点 | line_comment | zh-cn | package priv.linsu.game.life.simulator.model.domain.text;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class ConditionEqual {
//岁数
private Integer age;
//体质
private Integer constitution;
//智力
private Integer intelligence;
//运气
private Integer luck;
//容貌
private Integer appearance;
//财富
private Integer wealth;
//权力
private Integer power;
//时间 <SUF>
private Integer currentId;
private String status;
private String talent;
}
| false |
50405_7 | package com.ydj.zhuaqu.ali1688;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
* @author : Ares.yi
* @createTime : 2014-11-10 上午11:13:42
* @version : 1.0
* @description :
*
*/
public class IndustryCache {
private static Map<String,String> newMap = new HashMap<String, String>();
private static Map<String,List<Industry>> temp = new HashMap<String,List<Industry>>();
private static List<Industry> oneList = new ArrayList<Industry>();
static{
addNewMapData();
addUserIndustryCache();
}
/**
* 根据code获取行业名称
* @param code
* @return
*/
public static String getName(String code){
try {
return newMap.get(code);
} catch (Exception e) {
return "未知分类";
}
}
private static void addNewMapData(){
newMap.put("01" ,"服装纺织|面料");
newMap.put("02" ,"鞋靴|箱包|配饰");
newMap.put("03" ,"橡塑|化工|钢材|石油|煤炭");
newMap.put("04" ,"汽车|汽车配件");
newMap.put("05" ,"农产品|食品");
newMap.put("06" ,"美妆日化");
newMap.put("07" ,"母婴用品|童装|玩具");
newMap.put("08" ,"家纺家饰|家装建材");
newMap.put("09" ,"电子|电气|电工|仪表");
newMap.put("10" ,"安防|照明");
newMap.put("11" ,"机械|五金|轴承");
newMap.put("12" ,"医药卫生");
newMap.put("13" ,"百货|工艺品");
newMap.put("14" ,"包装|印刷|办公用品");
newMap.put("15" ,"物流运输");
newMap.put("16" ,"金融|教育|会计|法律|人力资源|广告");
newMap.put("17" ,"IT通讯|家电数码");
newMap.put("18" ,"餐饮旅游服务");
newMap.put("19" ,"房地产");
newMap.put("20" ,"公共事业");
newMap.put("21" ,"微商直销");
newMap.put("0101" ,"服装服饰");
newMap.put("0201" ,"纺织面料");
/**
* 2016.2.25 去掉行业 '皮革面料' 合并到'纺织面料'
*/
//newMap.put("0301" ,"皮革面料");
newMap.put("9901" ,"其它");
newMap.put("0102" ,"鞋靴");
newMap.put("0202" ,"箱包");
newMap.put("0302" ,"眼镜");
newMap.put("0402" ,"帽子|围巾|手套");
newMap.put("9902" ,"其它");
newMap.put("0103" ,"橡胶塑料");
newMap.put("0203" ,"化工原材料");
newMap.put("0303" ,"矿业|煤炭");
newMap.put("0403" ,"玻璃|陶瓷|混凝土");
newMap.put("0503" ,"石油|天然气能源");
newMap.put("0603" ,"再生能源");
// 将人的行业二级“钢材丨矿业丨煤炭” 拆分为“钢材|钢铁”和“矿业|煤炭”
newMap.put("0703" ,"钢材|钢铁");
newMap.put("0803" ,"木材|林业");
newMap.put("9903" ,"其它");
newMap.put("0104" ,"汽车整车销售|制造");
newMap.put("0204" ,"汽车配件");
/**
* 2016.2.25 去掉行业'汽车用品' 合并到'汽车配件'
*/
//newMap.put("0304" ,"汽车用品");
newMap.put("0404" ,"船舶配件");
newMap.put("0504" ,"摩托车配件");
newMap.put("0604" ,"非机动车配件");
newMap.put("0704" ,"汽车维修|汽车养护");
newMap.put("9904" ,"其它");
newMap.put("0105" ,"农产品");
newMap.put("0205" ,"食品饮料");
newMap.put("0605" ,"海鲜水产品");
newMap.put("0305" ,"酒业");
newMap.put("0405" ,"烟草");
newMap.put("0505" ,"化肥|饲料");
newMap.put("9905" ,"其它");
newMap.put("0106" ,"美容护肤");
newMap.put("0206" ,"美发造型");
newMap.put("0406" ,"美甲");
newMap.put("0306" ,"家化|家清纸品");
newMap.put("9906" ,"其它");
newMap.put("0107" ,"母婴用品");
newMap.put("0207" ,"玩具");
newMap.put("0307" ,"童装");
newMap.put("9907" ,"其它");
newMap.put("0108" ,"家饰");
newMap.put("0208" ,"家具灯具");
newMap.put("0308" ,"床上用品|毛巾");
newMap.put("0408" ,"装修建材");
newMap.put("0508" ,"装饰装修服务");
newMap.put("9908" ,"其它");
newMap.put("0109" ,"电工器材");
newMap.put("0209" ,"高、低压电器");
newMap.put("0309" ,"仪器仪表");
newMap.put("0409" ,"电气工控");
newMap.put("0509" ,"半导体|集成电路");
newMap.put("9909" ,"其它");
newMap.put("0110" ,"照明器材");
newMap.put("0210" ,"LED");
newMap.put("0310" ,"监控器材");
newMap.put("0410" ,"个人防护");
newMap.put("0510" ,"消防|防盗");
newMap.put("0610" ,"其它");
newMap.put("0111" ,"机械主机|配件");
newMap.put("0211" ,"五金工具");
newMap.put("0311" ,"轴承");
newMap.put("9911" ,"其它");
newMap.put("0112" ,"医药保健");
newMap.put("0212" ,"医疗设备");
newMap.put("0312" ,"宠物兽医");
newMap.put("0412" ,"医院医疗");
newMap.put("0512" ,"生物信息工程");
newMap.put("9912" ,"其它");
newMap.put("0113" ,"日用百货");
newMap.put("0213" ,"工艺品");
newMap.put("0313" ,"珠宝首饰");
newMap.put("0413" ,"钟表");
newMap.put("0513" ,"礼品");
newMap.put("0613" ,"体育用品");
newMap.put("9913" ,"其它");
newMap.put("0114" ,"包装");
newMap.put("0214" ,"印刷");
newMap.put("0314" ,"标签");
newMap.put("0414" ,"造纸与木材");
newMap.put("0514" ,"办公用品");
newMap.put("9914" ,"其它");
newMap.put("0115" ,"陆运");
newMap.put("0215" ,"海上运输");
newMap.put("0315" ,"航空运输");
newMap.put("0415" ,"快递");
newMap.put("0515" ,"货运代理");
newMap.put("9915" ,"其它");
newMap.put("0116" ,"金融投资");
newMap.put("0216" ,"教育培训");
newMap.put("0316" ,"商务服务");
newMap.put("0416" ,"广电传媒");
newMap.put("0516" ,"法律服务");
newMap.put("0616" ,"会计审计");
newMap.put("0716" ,"人力资源");
newMap.put("0916" ,"会务服务");
newMap.put("1016" ,"广告营销");
newMap.put("1116" ,"营销咨询|管理咨询");
/**
* 增加 行业 保险 理财
*/
newMap.put("1216" ,"保险");
newMap.put("1316" ,"理财");
newMap.put("9916" ,"其它");
newMap.put("0117" ,"计算机产品");
newMap.put("0217" ,"网络设备");
newMap.put("0317" ,"数码产品");
newMap.put("0417" ,"家用电器");
newMap.put("0517" ,"通讯产品");
newMap.put("0617" ,"互联网|电子商务");
newMap.put("9917" ,"其它");
newMap.put("0118" ,"餐饮娱乐");
newMap.put("0218" ,"度假旅游");
newMap.put("9918" ,"其它");
newMap.put("0119" ,"房地产开发");
/**
* 房地产销售 改成 房地产中介
*/
newMap.put("0219" ,"房地产中介");
newMap.put("0319" ,"物业管理");
newMap.put("9919" ,"其它");
newMap.put("0120" ,"政府机构");
newMap.put("0220" ,"行业协会");
newMap.put("0320" ,"军事机构");
newMap.put("0420" ,"水利工程");
newMap.put("0520" ,"电力工程");
newMap.put("0620" ,"环保绿化");
newMap.put("9920" ,"其它");
// newMap.put("0121" ,"再生能源");
// newMap.put("0221" ,"体育用品");
// newMap.put("0321" ,"环保绿化");
newMap.put("0421" ,"直销");
newMap.put("0521" ,"微商");
newMap.put("9921" ,"其它");
}
private static void addUserIndustryCache(){
for (Map.Entry<String, String> e : newMap.entrySet()) {
String code = e.getKey();
Industry one = new Industry( code, e.getValue());
if (code.length() == 2) {
oneList.add(one);
}else {
String s = code.substring(2);
List<Industry> l = new ArrayList<Industry>();
if(temp.containsKey(s)){
l = temp.get(s);
}
l.add(one);
temp.put(s, l);
}
}
}
public static List<Industry> getSecondIndustry(String oneCode){
return temp.get(oneCode);
}
public static List<Industry> getOneIndustry(){
return oneList;
}
public static void main(String[] args) {
}
}
| Aresyi/simpleSpider | src/main/java/com/ydj/zhuaqu/ali1688/IndustryCache.java | 3,607 | /**
* 增加 行业 保险 理财
*/ | block_comment | zh-cn | package com.ydj.zhuaqu.ali1688;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
* @author : Ares.yi
* @createTime : 2014-11-10 上午11:13:42
* @version : 1.0
* @description :
*
*/
public class IndustryCache {
private static Map<String,String> newMap = new HashMap<String, String>();
private static Map<String,List<Industry>> temp = new HashMap<String,List<Industry>>();
private static List<Industry> oneList = new ArrayList<Industry>();
static{
addNewMapData();
addUserIndustryCache();
}
/**
* 根据code获取行业名称
* @param code
* @return
*/
public static String getName(String code){
try {
return newMap.get(code);
} catch (Exception e) {
return "未知分类";
}
}
private static void addNewMapData(){
newMap.put("01" ,"服装纺织|面料");
newMap.put("02" ,"鞋靴|箱包|配饰");
newMap.put("03" ,"橡塑|化工|钢材|石油|煤炭");
newMap.put("04" ,"汽车|汽车配件");
newMap.put("05" ,"农产品|食品");
newMap.put("06" ,"美妆日化");
newMap.put("07" ,"母婴用品|童装|玩具");
newMap.put("08" ,"家纺家饰|家装建材");
newMap.put("09" ,"电子|电气|电工|仪表");
newMap.put("10" ,"安防|照明");
newMap.put("11" ,"机械|五金|轴承");
newMap.put("12" ,"医药卫生");
newMap.put("13" ,"百货|工艺品");
newMap.put("14" ,"包装|印刷|办公用品");
newMap.put("15" ,"物流运输");
newMap.put("16" ,"金融|教育|会计|法律|人力资源|广告");
newMap.put("17" ,"IT通讯|家电数码");
newMap.put("18" ,"餐饮旅游服务");
newMap.put("19" ,"房地产");
newMap.put("20" ,"公共事业");
newMap.put("21" ,"微商直销");
newMap.put("0101" ,"服装服饰");
newMap.put("0201" ,"纺织面料");
/**
* 2016.2.25 去掉行业 '皮革面料' 合并到'纺织面料'
*/
//newMap.put("0301" ,"皮革面料");
newMap.put("9901" ,"其它");
newMap.put("0102" ,"鞋靴");
newMap.put("0202" ,"箱包");
newMap.put("0302" ,"眼镜");
newMap.put("0402" ,"帽子|围巾|手套");
newMap.put("9902" ,"其它");
newMap.put("0103" ,"橡胶塑料");
newMap.put("0203" ,"化工原材料");
newMap.put("0303" ,"矿业|煤炭");
newMap.put("0403" ,"玻璃|陶瓷|混凝土");
newMap.put("0503" ,"石油|天然气能源");
newMap.put("0603" ,"再生能源");
// 将人的行业二级“钢材丨矿业丨煤炭” 拆分为“钢材|钢铁”和“矿业|煤炭”
newMap.put("0703" ,"钢材|钢铁");
newMap.put("0803" ,"木材|林业");
newMap.put("9903" ,"其它");
newMap.put("0104" ,"汽车整车销售|制造");
newMap.put("0204" ,"汽车配件");
/**
* 2016.2.25 去掉行业'汽车用品' 合并到'汽车配件'
*/
//newMap.put("0304" ,"汽车用品");
newMap.put("0404" ,"船舶配件");
newMap.put("0504" ,"摩托车配件");
newMap.put("0604" ,"非机动车配件");
newMap.put("0704" ,"汽车维修|汽车养护");
newMap.put("9904" ,"其它");
newMap.put("0105" ,"农产品");
newMap.put("0205" ,"食品饮料");
newMap.put("0605" ,"海鲜水产品");
newMap.put("0305" ,"酒业");
newMap.put("0405" ,"烟草");
newMap.put("0505" ,"化肥|饲料");
newMap.put("9905" ,"其它");
newMap.put("0106" ,"美容护肤");
newMap.put("0206" ,"美发造型");
newMap.put("0406" ,"美甲");
newMap.put("0306" ,"家化|家清纸品");
newMap.put("9906" ,"其它");
newMap.put("0107" ,"母婴用品");
newMap.put("0207" ,"玩具");
newMap.put("0307" ,"童装");
newMap.put("9907" ,"其它");
newMap.put("0108" ,"家饰");
newMap.put("0208" ,"家具灯具");
newMap.put("0308" ,"床上用品|毛巾");
newMap.put("0408" ,"装修建材");
newMap.put("0508" ,"装饰装修服务");
newMap.put("9908" ,"其它");
newMap.put("0109" ,"电工器材");
newMap.put("0209" ,"高、低压电器");
newMap.put("0309" ,"仪器仪表");
newMap.put("0409" ,"电气工控");
newMap.put("0509" ,"半导体|集成电路");
newMap.put("9909" ,"其它");
newMap.put("0110" ,"照明器材");
newMap.put("0210" ,"LED");
newMap.put("0310" ,"监控器材");
newMap.put("0410" ,"个人防护");
newMap.put("0510" ,"消防|防盗");
newMap.put("0610" ,"其它");
newMap.put("0111" ,"机械主机|配件");
newMap.put("0211" ,"五金工具");
newMap.put("0311" ,"轴承");
newMap.put("9911" ,"其它");
newMap.put("0112" ,"医药保健");
newMap.put("0212" ,"医疗设备");
newMap.put("0312" ,"宠物兽医");
newMap.put("0412" ,"医院医疗");
newMap.put("0512" ,"生物信息工程");
newMap.put("9912" ,"其它");
newMap.put("0113" ,"日用百货");
newMap.put("0213" ,"工艺品");
newMap.put("0313" ,"珠宝首饰");
newMap.put("0413" ,"钟表");
newMap.put("0513" ,"礼品");
newMap.put("0613" ,"体育用品");
newMap.put("9913" ,"其它");
newMap.put("0114" ,"包装");
newMap.put("0214" ,"印刷");
newMap.put("0314" ,"标签");
newMap.put("0414" ,"造纸与木材");
newMap.put("0514" ,"办公用品");
newMap.put("9914" ,"其它");
newMap.put("0115" ,"陆运");
newMap.put("0215" ,"海上运输");
newMap.put("0315" ,"航空运输");
newMap.put("0415" ,"快递");
newMap.put("0515" ,"货运代理");
newMap.put("9915" ,"其它");
newMap.put("0116" ,"金融投资");
newMap.put("0216" ,"教育培训");
newMap.put("0316" ,"商务服务");
newMap.put("0416" ,"广电传媒");
newMap.put("0516" ,"法律服务");
newMap.put("0616" ,"会计审计");
newMap.put("0716" ,"人力资源");
newMap.put("0916" ,"会务服务");
newMap.put("1016" ,"广告营销");
newMap.put("1116" ,"营销咨询|管理咨询");
/**
* 增加 <SUF>*/
newMap.put("1216" ,"保险");
newMap.put("1316" ,"理财");
newMap.put("9916" ,"其它");
newMap.put("0117" ,"计算机产品");
newMap.put("0217" ,"网络设备");
newMap.put("0317" ,"数码产品");
newMap.put("0417" ,"家用电器");
newMap.put("0517" ,"通讯产品");
newMap.put("0617" ,"互联网|电子商务");
newMap.put("9917" ,"其它");
newMap.put("0118" ,"餐饮娱乐");
newMap.put("0218" ,"度假旅游");
newMap.put("9918" ,"其它");
newMap.put("0119" ,"房地产开发");
/**
* 房地产销售 改成 房地产中介
*/
newMap.put("0219" ,"房地产中介");
newMap.put("0319" ,"物业管理");
newMap.put("9919" ,"其它");
newMap.put("0120" ,"政府机构");
newMap.put("0220" ,"行业协会");
newMap.put("0320" ,"军事机构");
newMap.put("0420" ,"水利工程");
newMap.put("0520" ,"电力工程");
newMap.put("0620" ,"环保绿化");
newMap.put("9920" ,"其它");
// newMap.put("0121" ,"再生能源");
// newMap.put("0221" ,"体育用品");
// newMap.put("0321" ,"环保绿化");
newMap.put("0421" ,"直销");
newMap.put("0521" ,"微商");
newMap.put("9921" ,"其它");
}
private static void addUserIndustryCache(){
for (Map.Entry<String, String> e : newMap.entrySet()) {
String code = e.getKey();
Industry one = new Industry( code, e.getValue());
if (code.length() == 2) {
oneList.add(one);
}else {
String s = code.substring(2);
List<Industry> l = new ArrayList<Industry>();
if(temp.containsKey(s)){
l = temp.get(s);
}
l.add(one);
temp.put(s, l);
}
}
}
public static List<Industry> getSecondIndustry(String oneCode){
return temp.get(oneCode);
}
public static List<Industry> getOneIndustry(){
return oneList;
}
public static void main(String[] args) {
}
}
| true |
45523_7 | package com.ecust.equsys.domain.vessel.vesselperiodic;
import com.ecust.equsys.domain.vessel.VesselBaseEntity;
public class VesselPeneTest extends VesselBaseEntity {
public static VesselPeneTest vesselPeneTest = null;
public VesselPeneTest() {
super();
this.db_Description = "渗透检测记录";
this.method = "updateVesselPermTest";//上传servlet的方法名称,很重要
}
public static VesselPeneTest getInstance() {
if (vesselPeneTest == null) {
vesselPeneTest = new VesselPeneTest();
}
return vesselPeneTest;
}
public String v_Perm_JFC;//渗透剂型号
public String v_Perm_Surface;//表面状况
public String v_Perm_Clean;//清洗剂型号
public String v_Perm_Tem;//环境温度
public String v_Perm_Image;//显像剂型号
public String v_Perm_Contrast;//对比试块及编号
public String v_Perm_JFC_Time;//渗透时间
public String v_Perm_Image_Time;//显像时间
public String v_Perm_Cri;//检测标准
public String v_Perm_Len;//检测比例、长度
public String v_Perm_Value;//
public String v_Perm_Result;//
public String v_Perm_Date;//检测
public String v_Perm_Check_Date;//校对
@Override
public String toString() {
return "VesselPeneTest{" +
"v_Perm_JFC='" + v_Perm_JFC + '\'' +
", v_Perm_Surface='" + v_Perm_Surface + '\'' +
", v_Perm_Clean='" + v_Perm_Clean + '\'' +
", v_Perm_Tem='" + v_Perm_Tem + '\'' +
", v_Perm_Image='" + v_Perm_Image + '\'' +
", v_Perm_Contrast='" + v_Perm_Contrast + '\'' +
", v_Perm_JFC_Time='" + v_Perm_JFC_Time + '\'' +
", v_Perm_Image_Time='" + v_Perm_Image_Time + '\'' +
", v_Perm_Cri='" + v_Perm_Cri + '\'' +
", v_Perm_Len='" + v_Perm_Len + '\'' +
", v_Perm_Value='" + v_Perm_Value + '\'' +
", v_Perm_Result='" + v_Perm_Result + '\'' +
", v_Perm_Date='" + v_Perm_Date + '\'' +
", v_Perm_Check_Date='" + v_Perm_Check_Date + '\'' +
'}';
}
}
| ArexChu/SSEI_KT | equManSysForScan/src/main/java/com/ecust/equsys/domain/vessel/vesselperiodic/VesselPeneTest.java | 683 | //渗透时间 | line_comment | zh-cn | package com.ecust.equsys.domain.vessel.vesselperiodic;
import com.ecust.equsys.domain.vessel.VesselBaseEntity;
public class VesselPeneTest extends VesselBaseEntity {
public static VesselPeneTest vesselPeneTest = null;
public VesselPeneTest() {
super();
this.db_Description = "渗透检测记录";
this.method = "updateVesselPermTest";//上传servlet的方法名称,很重要
}
public static VesselPeneTest getInstance() {
if (vesselPeneTest == null) {
vesselPeneTest = new VesselPeneTest();
}
return vesselPeneTest;
}
public String v_Perm_JFC;//渗透剂型号
public String v_Perm_Surface;//表面状况
public String v_Perm_Clean;//清洗剂型号
public String v_Perm_Tem;//环境温度
public String v_Perm_Image;//显像剂型号
public String v_Perm_Contrast;//对比试块及编号
public String v_Perm_JFC_Time;//渗透 <SUF>
public String v_Perm_Image_Time;//显像时间
public String v_Perm_Cri;//检测标准
public String v_Perm_Len;//检测比例、长度
public String v_Perm_Value;//
public String v_Perm_Result;//
public String v_Perm_Date;//检测
public String v_Perm_Check_Date;//校对
@Override
public String toString() {
return "VesselPeneTest{" +
"v_Perm_JFC='" + v_Perm_JFC + '\'' +
", v_Perm_Surface='" + v_Perm_Surface + '\'' +
", v_Perm_Clean='" + v_Perm_Clean + '\'' +
", v_Perm_Tem='" + v_Perm_Tem + '\'' +
", v_Perm_Image='" + v_Perm_Image + '\'' +
", v_Perm_Contrast='" + v_Perm_Contrast + '\'' +
", v_Perm_JFC_Time='" + v_Perm_JFC_Time + '\'' +
", v_Perm_Image_Time='" + v_Perm_Image_Time + '\'' +
", v_Perm_Cri='" + v_Perm_Cri + '\'' +
", v_Perm_Len='" + v_Perm_Len + '\'' +
", v_Perm_Value='" + v_Perm_Value + '\'' +
", v_Perm_Result='" + v_Perm_Result + '\'' +
", v_Perm_Date='" + v_Perm_Date + '\'' +
", v_Perm_Check_Date='" + v_Perm_Check_Date + '\'' +
'}';
}
}
| false |
60828_2 | package cn.argento.askia.entry;
import java.lang.reflect.Array;
import java.net.InetAddress;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
public class UserBean {
// 数字
private int number;
// 字符串
protected String address;
protected String name;
// 不转json的字段
private transient int age;
// 逻辑值
boolean isGrow;
// 数组
double[] flag;
// 对象
@JavaBean
public Country country;
public List<String> skillList;
// null
private InetAddress nullObj;
public List<String> getSkillList() {
return skillList;
}
public void setSkillList(List<String> skillList) {
this.skillList = skillList;
}
public UserBean(int number, String address, String name, int age, boolean isGrow, double[] flag, Country country, List<String> skillList) {
this.number = number;
this.address = address;
this.name = name;
this.age = age;
this.isGrow = isGrow;
this.flag = flag;
this.country = country;
this.skillList = skillList;
}
public UserBean() {
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isGrow() {
return isGrow;
}
public void setGrow(boolean grow) {
isGrow = grow;
}
public double[] getFlag() {
return flag;
}
public void setFlag(double[] flag) {
this.flag = flag;
}
public Country getCountry() {
return country;
}
public void setCountry(Country country) {
this.country = country;
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer("UserBean{");
sb.append("number=").append(number);
sb.append(", address='").append(address).append('\'');
sb.append(", name='").append(name).append('\'');
sb.append(", age=").append(age);
sb.append(", isGrow=").append(isGrow);
sb.append(", flag=");
if (flag == null) sb.append("null");
else {
sb.append('[');
for (int i = 0; i < flag.length; ++i)
sb.append(i == 0 ? "" : ", ").append(flag[i]);
sb.append(']');
}
sb.append(", country=").append(country);
sb.append(", skillList=").append(skillList);
sb.append(", nullObj=").append(nullObj);
sb.append('}');
return sb.toString();
}
public static UserBean newBean(){
// String[] countries = new String[]{"美国", "中国", "日本", "新加坡", "俄罗斯", "白俄罗斯", "缅甸", "蒙古", "墨西哥"};
Random random = new Random();
UserBean userBean = new UserBean();
userBean.setAddress("XXX省XXX市XXX镇XXXXX");
userBean.setAge(random.nextInt(100));
Country country = new Country();
country.setNow(LocalDateTime.now());
country.setZoneId(ZoneId.systemDefault());
country.setCountryName(ZoneId.systemDefault().getId());
userBean.setCountry(country);
userBean.setFlag(new double[]{2.5f, 3.6f, 4.8f, 5.1f, 3.9f});
userBean.setGrow(random.nextBoolean());
userBean.setName(UUID.randomUUID().toString());
userBean.setNumber(random.nextInt(300));
userBean.setSkillList(new ArrayList<>(Arrays.asList("C++", "Java", "C")));
return userBean;
}
}
| ArgentoAskia/JavaTutorial | Java-Json/src/main/java/cn/argento/askia/entry/UserBean.java | 1,019 | // 逻辑值 | line_comment | zh-cn | package cn.argento.askia.entry;
import java.lang.reflect.Array;
import java.net.InetAddress;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
public class UserBean {
// 数字
private int number;
// 字符串
protected String address;
protected String name;
// 不转json的字段
private transient int age;
// 逻辑 <SUF>
boolean isGrow;
// 数组
double[] flag;
// 对象
@JavaBean
public Country country;
public List<String> skillList;
// null
private InetAddress nullObj;
public List<String> getSkillList() {
return skillList;
}
public void setSkillList(List<String> skillList) {
this.skillList = skillList;
}
public UserBean(int number, String address, String name, int age, boolean isGrow, double[] flag, Country country, List<String> skillList) {
this.number = number;
this.address = address;
this.name = name;
this.age = age;
this.isGrow = isGrow;
this.flag = flag;
this.country = country;
this.skillList = skillList;
}
public UserBean() {
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isGrow() {
return isGrow;
}
public void setGrow(boolean grow) {
isGrow = grow;
}
public double[] getFlag() {
return flag;
}
public void setFlag(double[] flag) {
this.flag = flag;
}
public Country getCountry() {
return country;
}
public void setCountry(Country country) {
this.country = country;
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer("UserBean{");
sb.append("number=").append(number);
sb.append(", address='").append(address).append('\'');
sb.append(", name='").append(name).append('\'');
sb.append(", age=").append(age);
sb.append(", isGrow=").append(isGrow);
sb.append(", flag=");
if (flag == null) sb.append("null");
else {
sb.append('[');
for (int i = 0; i < flag.length; ++i)
sb.append(i == 0 ? "" : ", ").append(flag[i]);
sb.append(']');
}
sb.append(", country=").append(country);
sb.append(", skillList=").append(skillList);
sb.append(", nullObj=").append(nullObj);
sb.append('}');
return sb.toString();
}
public static UserBean newBean(){
// String[] countries = new String[]{"美国", "中国", "日本", "新加坡", "俄罗斯", "白俄罗斯", "缅甸", "蒙古", "墨西哥"};
Random random = new Random();
UserBean userBean = new UserBean();
userBean.setAddress("XXX省XXX市XXX镇XXXXX");
userBean.setAge(random.nextInt(100));
Country country = new Country();
country.setNow(LocalDateTime.now());
country.setZoneId(ZoneId.systemDefault());
country.setCountryName(ZoneId.systemDefault().getId());
userBean.setCountry(country);
userBean.setFlag(new double[]{2.5f, 3.6f, 4.8f, 5.1f, 3.9f});
userBean.setGrow(random.nextBoolean());
userBean.setName(UUID.randomUUID().toString());
userBean.setNumber(random.nextInt(300));
userBean.setSkillList(new ArrayList<>(Arrays.asList("C++", "Java", "C")));
return userBean;
}
}
| false |
5677_6 | /*
* Copyright (C) 2016 AriaLyy(https://github.com/AriaLyy/Aria)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.arialyy.simple.core.upload;
import android.content.Context;
import android.os.Environment;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import com.arialyy.aria.core.Aria;
import com.arialyy.aria.core.upload.UploadEntity;
import com.arialyy.frame.base.BaseViewModule;
import com.arialyy.simple.util.AppUtil;
public class UploadModule extends BaseViewModule {
private final String FTP_URL_KEY = "FTP_URL_KEY";
private final String FTP_PATH_KEY = "FTP_PATH_KEY";
private MutableLiveData<UploadEntity> liveData = new MutableLiveData<>();
UploadEntity uploadInfo;
/**
* 获取Ftp上传信息
*/
LiveData<UploadEntity> getFtpInfo(Context context) {
//String url = AppUtil.getConfigValue(context, FTP_URL_KEY, "ftp://9.9.9.72:2121/aab/你好");
//String filePath = AppUtil.getConfigValue(context, FTP_PATH_KEY,
// Environment.getExternalStorageDirectory().getPath() + "/Download/AndroidAria.db");
String url = "ftp://192.168.0.105:2121/aab/你好";
String filePath = "/mnt/sdcard/QQMusic-import-1.2.1.zip";
UploadEntity entity = Aria.upload(context).getFirstUploadEntity(filePath);
if (entity != null) {
uploadInfo = entity;
AppUtil.setConfigValue(context, FTP_URL_KEY, uploadInfo.getUrl());
AppUtil.setConfigValue(context, FTP_PATH_KEY, uploadInfo.getFilePath());
} else {
uploadInfo = new UploadEntity();
uploadInfo.setUrl(url);
uploadInfo.setFilePath(filePath);
}
liveData.postValue(uploadInfo);
return liveData;
}
/**
* 获取Ftp上传信息
*/
LiveData<UploadEntity> getSFtpInfo(Context context) {
//String url = AppUtil.getConfigValue(context, FTP_URL_KEY, "ftp://9.9.9.72:2121/aab/你好");
//String filePath = AppUtil.getConfigValue(context, FTP_PATH_KEY,
// Environment.getExternalStorageDirectory().getPath() + "/Download/AndroidAria.db");
String url = "ftp://9.9.9.72:22/aab/你好";
String filePath = "/mnt/sdcard/QQMusic-import-1.2.1.zip";
UploadEntity entity = Aria.upload(context).getFirstUploadEntity(filePath);
if (entity != null) {
uploadInfo = entity;
AppUtil.setConfigValue(context, FTP_URL_KEY, uploadInfo.getUrl());
AppUtil.setConfigValue(context, FTP_PATH_KEY, uploadInfo.getFilePath());
} else {
uploadInfo = new UploadEntity();
uploadInfo.setUrl(url);
uploadInfo.setFilePath(filePath);
}
liveData.postValue(uploadInfo);
return liveData;
}
/**
* 更新Url
*/
void updateFtpUrl(Context context, String url) {
uploadInfo.setUrl(url);
AppUtil.setConfigValue(context, FTP_URL_KEY, url);
liveData.postValue(uploadInfo);
}
/**
* 更新文件路径
*/
void updateFtpFilePath(Context context, String filePath) {
uploadInfo.setFilePath(filePath);
AppUtil.setConfigValue(context, FTP_PATH_KEY, filePath);
liveData.postValue(uploadInfo);
}
}
| AriaLyy/Aria | app/src/main/java/com/arialyy/simple/core/upload/UploadModule.java | 1,031 | /**
* 获取Ftp上传信息
*/ | block_comment | zh-cn | /*
* Copyright (C) 2016 AriaLyy(https://github.com/AriaLyy/Aria)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.arialyy.simple.core.upload;
import android.content.Context;
import android.os.Environment;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import com.arialyy.aria.core.Aria;
import com.arialyy.aria.core.upload.UploadEntity;
import com.arialyy.frame.base.BaseViewModule;
import com.arialyy.simple.util.AppUtil;
public class UploadModule extends BaseViewModule {
private final String FTP_URL_KEY = "FTP_URL_KEY";
private final String FTP_PATH_KEY = "FTP_PATH_KEY";
private MutableLiveData<UploadEntity> liveData = new MutableLiveData<>();
UploadEntity uploadInfo;
/**
* 获取Ftp上传信息
*/
LiveData<UploadEntity> getFtpInfo(Context context) {
//String url = AppUtil.getConfigValue(context, FTP_URL_KEY, "ftp://9.9.9.72:2121/aab/你好");
//String filePath = AppUtil.getConfigValue(context, FTP_PATH_KEY,
// Environment.getExternalStorageDirectory().getPath() + "/Download/AndroidAria.db");
String url = "ftp://192.168.0.105:2121/aab/你好";
String filePath = "/mnt/sdcard/QQMusic-import-1.2.1.zip";
UploadEntity entity = Aria.upload(context).getFirstUploadEntity(filePath);
if (entity != null) {
uploadInfo = entity;
AppUtil.setConfigValue(context, FTP_URL_KEY, uploadInfo.getUrl());
AppUtil.setConfigValue(context, FTP_PATH_KEY, uploadInfo.getFilePath());
} else {
uploadInfo = new UploadEntity();
uploadInfo.setUrl(url);
uploadInfo.setFilePath(filePath);
}
liveData.postValue(uploadInfo);
return liveData;
}
/**
* 获取F <SUF>*/
LiveData<UploadEntity> getSFtpInfo(Context context) {
//String url = AppUtil.getConfigValue(context, FTP_URL_KEY, "ftp://9.9.9.72:2121/aab/你好");
//String filePath = AppUtil.getConfigValue(context, FTP_PATH_KEY,
// Environment.getExternalStorageDirectory().getPath() + "/Download/AndroidAria.db");
String url = "ftp://9.9.9.72:22/aab/你好";
String filePath = "/mnt/sdcard/QQMusic-import-1.2.1.zip";
UploadEntity entity = Aria.upload(context).getFirstUploadEntity(filePath);
if (entity != null) {
uploadInfo = entity;
AppUtil.setConfigValue(context, FTP_URL_KEY, uploadInfo.getUrl());
AppUtil.setConfigValue(context, FTP_PATH_KEY, uploadInfo.getFilePath());
} else {
uploadInfo = new UploadEntity();
uploadInfo.setUrl(url);
uploadInfo.setFilePath(filePath);
}
liveData.postValue(uploadInfo);
return liveData;
}
/**
* 更新Url
*/
void updateFtpUrl(Context context, String url) {
uploadInfo.setUrl(url);
AppUtil.setConfigValue(context, FTP_URL_KEY, url);
liveData.postValue(uploadInfo);
}
/**
* 更新文件路径
*/
void updateFtpFilePath(Context context, String filePath) {
uploadInfo.setFilePath(filePath);
AppUtil.setConfigValue(context, FTP_PATH_KEY, filePath);
liveData.postValue(uploadInfo);
}
}
| true |
51312_6 | package lab14;
import java.util.*;
//import junit.framework.Assert;
public class MAx {
int maxdata = Integer.MAX_VALUE;
int[][] capacity;
int[] flow;
int[] pre;
int n;
Queue<Integer> queue;
public MAx(int[][] capacity) {
this.capacity = capacity;
this.n = capacity.length;
this.pre = new int[n];
}
//广度优先遍历的查找一条src到des的路径
int BFS(int src, int des) {
int i;
this.queue = new LinkedList<Integer>();
this.flow = new int[n];
for (i = 0; i < n; ++i) {
pre[i] = -1;
}
pre[src] = -2;
flow[src] = maxdata;
queue.add(src);
while (!queue.isEmpty()) {
int index = queue.poll();
if (index == des) //找到了增广路径
break;
for (i = 0; i < n; ++i) {
//找到非源节点未被访问过的可达结点,计算其流量
if (i != src && capacity[index][i] > 0 && pre[i] == -1) {
pre[i] = index; //记录前驱
flow[i] = Math.min(capacity[index][i], flow[index]); //关键:迭代的找到增量
queue.add(i);
}
}
}
if (pre[des] == -1) //残留图中不再存在增广路径
return -1;
else
return flow[des];
}
int maxFlow(int src, int des) {
int increasement = 0;
int sumflow = 0;
while ((increasement = BFS(src, des)) != -1) {
int k = des; //利用前驱寻找路径
while (k != src) {
int last = pre[k];
capacity[last][k] -= increasement; //改变正向边的容量
capacity[k][last] += increasement; //改变反向边的容量
k = last;
}
System.out.println("-------改变后---------");
// for(int j=0;j<n;j++)
// {
// for(int x=0;x<n;x++)
// {
// System.out.print("---"+capacity[j][x]);
// }
// System.out.println();
// }
sumflow += increasement;
}
return sumflow;
}
public static void main(String args[]) {
int[][] matrix = new int[4][4];
matrix[0][1] = 4;
matrix[0][3] = 2;
matrix[1][2] = 3;
matrix[1][3] = 2;
matrix[2][3] = 1;
MAx edm = new MAx(matrix);
System.out.println("-------初始化---------");
// for (int j = 0; j < edm.n; j++) {
// for (int k = 0; k < edm.n; k++) {
// System.out.print("---" + edm.capacity[j][k]);
// }
// System.out.println();
// }
int actual = edm.maxFlow(0, 3);
int expected = 5;
// System.out.println("-------最终结果---------");
// for (int j = 0; j < edm.n; j++) {
// for (int k = 0; k < edm.n; k++) {
// System.out.print("---" + edm.capacity[j][k]);
// }
// System.out.println();
// }
}
} | Aries-Dawn/CS208-Algorithm-Design-and-Analysis | src/lab14/MAx.java | 931 | //残留图中不再存在增广路径
| line_comment | zh-cn | package lab14;
import java.util.*;
//import junit.framework.Assert;
public class MAx {
int maxdata = Integer.MAX_VALUE;
int[][] capacity;
int[] flow;
int[] pre;
int n;
Queue<Integer> queue;
public MAx(int[][] capacity) {
this.capacity = capacity;
this.n = capacity.length;
this.pre = new int[n];
}
//广度优先遍历的查找一条src到des的路径
int BFS(int src, int des) {
int i;
this.queue = new LinkedList<Integer>();
this.flow = new int[n];
for (i = 0; i < n; ++i) {
pre[i] = -1;
}
pre[src] = -2;
flow[src] = maxdata;
queue.add(src);
while (!queue.isEmpty()) {
int index = queue.poll();
if (index == des) //找到了增广路径
break;
for (i = 0; i < n; ++i) {
//找到非源节点未被访问过的可达结点,计算其流量
if (i != src && capacity[index][i] > 0 && pre[i] == -1) {
pre[i] = index; //记录前驱
flow[i] = Math.min(capacity[index][i], flow[index]); //关键:迭代的找到增量
queue.add(i);
}
}
}
if (pre[des] == -1) //残留 <SUF>
return -1;
else
return flow[des];
}
int maxFlow(int src, int des) {
int increasement = 0;
int sumflow = 0;
while ((increasement = BFS(src, des)) != -1) {
int k = des; //利用前驱寻找路径
while (k != src) {
int last = pre[k];
capacity[last][k] -= increasement; //改变正向边的容量
capacity[k][last] += increasement; //改变反向边的容量
k = last;
}
System.out.println("-------改变后---------");
// for(int j=0;j<n;j++)
// {
// for(int x=0;x<n;x++)
// {
// System.out.print("---"+capacity[j][x]);
// }
// System.out.println();
// }
sumflow += increasement;
}
return sumflow;
}
public static void main(String args[]) {
int[][] matrix = new int[4][4];
matrix[0][1] = 4;
matrix[0][3] = 2;
matrix[1][2] = 3;
matrix[1][3] = 2;
matrix[2][3] = 1;
MAx edm = new MAx(matrix);
System.out.println("-------初始化---------");
// for (int j = 0; j < edm.n; j++) {
// for (int k = 0; k < edm.n; k++) {
// System.out.print("---" + edm.capacity[j][k]);
// }
// System.out.println();
// }
int actual = edm.maxFlow(0, 3);
int expected = 5;
// System.out.println("-------最终结果---------");
// for (int j = 0; j < edm.n; j++) {
// for (int k = 0; k < edm.n; k++) {
// System.out.print("---" + edm.capacity[j][k]);
// }
// System.out.println();
// }
}
} | false |
15116_3 | package com.aries.smart.impl;
import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.view.View;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
import com.aries.library.fast.i.FastObserverControl;
import com.aries.library.fast.i.FastRecyclerViewControl;
import com.aries.library.fast.i.IFastRefreshLoadView;
import com.aries.library.fast.i.LoadMoreFoot;
import com.aries.library.fast.i.LoadingDialog;
import com.aries.library.fast.i.MultiStatusView;
import com.aries.library.fast.i.QuitAppControl;
import com.aries.library.fast.i.TitleBarViewControl;
import com.aries.library.fast.i.ToastControl;
import com.aries.library.fast.manager.LoggerManager;
import com.aries.library.fast.retrofit.FastNullException;
import com.aries.library.fast.retrofit.FastObserver;
import com.aries.library.fast.util.FastStackUtil;
import com.aries.library.fast.util.SizeUtil;
import com.aries.library.fast.util.ToastUtil;
import com.aries.library.fast.widget.FastLoadDialog;
import com.aries.library.fast.widget.FastLoadMoreView;
import com.aries.smart.R;
import com.aries.ui.util.DrawableUtil;
import com.aries.ui.util.StatusBarUtil;
import com.aries.ui.view.radius.RadiusTextView;
import com.aries.ui.view.title.TitleBarView;
import com.aries.ui.widget.progress.UIProgressDialog;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.animation.ScaleInAnimation;
import com.chad.library.adapter.base.loadmore.BaseLoadMoreView;
import com.scwang.smart.refresh.header.MaterialHeader;
import com.scwang.smart.refresh.layout.api.RefreshHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.DefaultRefreshHeaderCreator;
import me.bakumon.statuslayoutmanager.library.StatusLayoutManager;
/**
* @Author: AriesHoo on 2018/7/30 11:34
* @E-Mail: AriesHoo@126.com
* Function: 应用全局配置管理实现
* Description:
* 1、新增友盟统计功能对接
*/
public class AppImpl implements DefaultRefreshHeaderCreator, LoadMoreFoot,
FastRecyclerViewControl, MultiStatusView, LoadingDialog,
TitleBarViewControl, QuitAppControl, ToastControl, FastObserverControl {
private Context mContext;
private String TAG = this.getClass().getSimpleName();
public AppImpl(@Nullable Context context) {
this.mContext = context;
}
/**
* 下拉刷新头配置
*
* @param context
* @param layout
* @return
*/
@NonNull
@Override
public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
layout.setEnableHeaderTranslationContent(false)
.setPrimaryColorsId(R.color.colorAccent)
.setEnableOverScrollDrag(false);
MaterialHeader materialHeader = new MaterialHeader(mContext);
materialHeader.setColorSchemeColors(ContextCompat.getColor(mContext, R.color.colorTextBlack),
ContextCompat.getColor(mContext, R.color.colorTextBlackLight));
return materialHeader;
}
/**
* Adapter加载更多配置
*
* @param adapter
* @return
*/
@Nullable
@Override
public BaseLoadMoreView createDefaultLoadMoreView(BaseQuickAdapter adapter) {
if (adapter != null) {
//设置动画是否一直开启
adapter.setAnimationFirstOnly(false);
//设置动画
adapter.setAdapterAnimation(new ScaleInAnimation());
adapter.setAnimationEnable(true);
}
//方式一:设置FastLoadMoreView--可参考FastLoadMoreView.Builder相应set方法
//默认配置请参考FastLoadMoreView.Builder(mContext)里初始化
return new FastLoadMoreView.Builder(mContext)
.setLoadingTextFakeBold(true)
.setLoadingSize(SizeUtil.dp2px(20))
// .setLoadTextColor(Color.MAGENTA)
// //设置Loading 颜色-5.0以上有效
// .setLoadingProgressColor(Color.MAGENTA)
// //设置Loading drawable--会使Loading颜色失效
// .setLoadingProgressDrawable(R.drawable.dialog_loading_wei_bo)
// //设置全局TextView颜色
// .setLoadTextColor(Color.MAGENTA)
// //设置全局TextView文字字号
// .setLoadTextSize(SizeUtil.dp2px(14))
// .setLoadingText("努力加载中...")
// .setLoadingTextColor(Color.GREEN)
// .setLoadingTextSize(SizeUtil.dp2px(14))
// .setLoadEndText("我是有底线的")
// .setLoadEndTextColor(Color.GREEN)
// .setLoadEndTextSize(SizeUtil.dp2px(14))
// .setLoadFailText("哇哦!出错了")
// .setLoadFailTextColor(Color.RED)
// .setLoadFailTextSize(SizeUtil.dp2px(14))
.build();
//方式二:使用adapter自带--其实我默认设置的和这个基本一致只是提供了相应设置方法
// return new SimpleLoadMoreView();
//方式三:参考SimpleLoadMoreView或FastLoadMoreView完全自定义自己的LoadMoreView
// return MyLoadMoreView();
}
/**
* 全局设置
*
* @param recyclerView
* @param cls
*/
@Override
public void setRecyclerView(RecyclerView recyclerView, Class<?> cls) {
LoggerManager.i(TAG, "setRecyclerView-" + cls.getSimpleName() + "context:" + recyclerView.getContext() + ";:" + (Activity.class.isAssignableFrom(recyclerView.getContext().getClass())) + ";:" + (recyclerView.getContext() instanceof Activity));
}
@Override
public void setMultiStatusView(StatusLayoutManager.Builder statusView, IFastRefreshLoadView iFastRefreshLoadView) {
}
/**
* 这里将局部设置的FastLoadDialog 抛至该处用于全局设置,在局部使用{@link com.aries.library.fast.retrofit.FastLoadingObserver}
*
* @param activity
* @return
*/
@Nullable
@Override
public FastLoadDialog createLoadingDialog(@Nullable Activity activity) {
return new FastLoadDialog(activity,
new UIProgressDialog.WeBoBuilder(activity)
.setMessage("加载中")
.create())
.setCanceledOnTouchOutside(false)
.setMessage("请求数据中,请稍候...");
//注意使用UIProgressDialog时最好在Builder里设置提示文字setMessage不然后续再设置文字信息也不会显示
// return new FastLoadDialog(activity, new UIProgressDialog.WeChatBuilder(activity)
// .setBackgroundColor(Color.parseColor("#FCFCFC"))
//// .setMinHeight(SizeUtil.dp2px(140))
//// .setMinWidth(SizeUtil.dp2px(270))
// .setTextSizeUnit(TypedValue.COMPLEX_UNIT_PX)
// .setMessage(R.string.fast_loading)
// .setLoadingSize(SizeUtil.dp2px(30))
// .setTextSize(SizeUtil.dp2px(16f))
// .setTextPadding(SizeUtil.dp2px(10))
// .setTextColorResource(R.color.colorTextGray)
// .setIndeterminateDrawable(FastUtil.getTintDrawable(ContextCompat.getDrawable(mContext, R.drawable.dialog_loading), ContextCompat.getColor(mContext, R.color.colorTitleText)))
// .setBackgroundRadius(SizeUtil.dp2px(6f))
// .create());
// Dialog dialog = new PictureDialog(activity);
// return new FastLoadDialog(activity, dialog)
// .setCancelable(true)
// .setCanceledOnTouchOutside(true);
}
/**
* 控制全局TitleBarView
*
* @param titleBar
* @return
*/
@Override
public boolean createTitleBarViewControl(TitleBarView titleBar, Class<?> cls) {
//默认的MD风格返回箭头icon如使用该风格可以不用设置
Drawable mDrawable = DrawableUtil.setTintDrawable(ContextCompat.getDrawable(mContext, R.drawable.fast_ic_back),
ContextCompat.getColor(mContext, R.color.colorTitleText));
//是否支持状态栏白色
boolean isSupport = StatusBarUtil.isSupportStatusBarFontChange();
boolean isActivity = Activity.class.isAssignableFrom(cls);
Activity activity = FastStackUtil.getInstance().getActivity(cls);
//设置TitleBarView 所有TextView颜色
titleBar.setStatusBarLightMode(isSupport)
//不支持黑字的设置白透明
.setStatusAlpha(isSupport ? 0 : 102)
.setLeftTextDrawable(isActivity ? mDrawable : null)
.setDividerHeight(Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP ? SizeUtil.dp2px(0.5f) : 0);
if (activity != null) {
titleBar.setTitleMainText(activity.getTitle())
.setOnLeftTextClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
activity.finish();
}
});
}
return false;
}
/**
* @param isFirst 是否首次提示
* @param activity 操作的Activity
* @return 延迟间隔--如不需要设置两次提示可设置0--最佳方式是直接在回调中执行你想要的操作
*/
@Override
public long quipApp(boolean isFirst, Activity activity) {
//默认配置
if (isFirst) {
ToastUtil.show(R.string.fast_quit_app);
} else {
FastStackUtil.getInstance().exit(false);
}
return 2000;
}
@Override
public Toast getToast() {
return null;
}
@Override
public void setToast(Toast toast, RadiusTextView textView) {
}
/**
* @param o {@link FastObserver} 对象用于后续事件逻辑
* @param e 原始错误
* @return true 拦截操作不进行原始{@link FastObserver#onError(Throwable)}后续逻辑
* false 不拦截继续后续逻辑
* {@link FastNullException} 已在{@link FastObserver#onError} }处理如果为该类型Exception可不用管,参考
*/
@Override
public boolean onError(FastObserver o, Throwable e) {
return false;
}
}
| AriesHoo/FastLib | template/src/main/java/com/aries/smart/impl/AppImpl.java | 2,618 | //设置动画是否一直开启 | line_comment | zh-cn | package com.aries.smart.impl;
import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.view.View;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
import com.aries.library.fast.i.FastObserverControl;
import com.aries.library.fast.i.FastRecyclerViewControl;
import com.aries.library.fast.i.IFastRefreshLoadView;
import com.aries.library.fast.i.LoadMoreFoot;
import com.aries.library.fast.i.LoadingDialog;
import com.aries.library.fast.i.MultiStatusView;
import com.aries.library.fast.i.QuitAppControl;
import com.aries.library.fast.i.TitleBarViewControl;
import com.aries.library.fast.i.ToastControl;
import com.aries.library.fast.manager.LoggerManager;
import com.aries.library.fast.retrofit.FastNullException;
import com.aries.library.fast.retrofit.FastObserver;
import com.aries.library.fast.util.FastStackUtil;
import com.aries.library.fast.util.SizeUtil;
import com.aries.library.fast.util.ToastUtil;
import com.aries.library.fast.widget.FastLoadDialog;
import com.aries.library.fast.widget.FastLoadMoreView;
import com.aries.smart.R;
import com.aries.ui.util.DrawableUtil;
import com.aries.ui.util.StatusBarUtil;
import com.aries.ui.view.radius.RadiusTextView;
import com.aries.ui.view.title.TitleBarView;
import com.aries.ui.widget.progress.UIProgressDialog;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.animation.ScaleInAnimation;
import com.chad.library.adapter.base.loadmore.BaseLoadMoreView;
import com.scwang.smart.refresh.header.MaterialHeader;
import com.scwang.smart.refresh.layout.api.RefreshHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.DefaultRefreshHeaderCreator;
import me.bakumon.statuslayoutmanager.library.StatusLayoutManager;
/**
* @Author: AriesHoo on 2018/7/30 11:34
* @E-Mail: AriesHoo@126.com
* Function: 应用全局配置管理实现
* Description:
* 1、新增友盟统计功能对接
*/
public class AppImpl implements DefaultRefreshHeaderCreator, LoadMoreFoot,
FastRecyclerViewControl, MultiStatusView, LoadingDialog,
TitleBarViewControl, QuitAppControl, ToastControl, FastObserverControl {
private Context mContext;
private String TAG = this.getClass().getSimpleName();
public AppImpl(@Nullable Context context) {
this.mContext = context;
}
/**
* 下拉刷新头配置
*
* @param context
* @param layout
* @return
*/
@NonNull
@Override
public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
layout.setEnableHeaderTranslationContent(false)
.setPrimaryColorsId(R.color.colorAccent)
.setEnableOverScrollDrag(false);
MaterialHeader materialHeader = new MaterialHeader(mContext);
materialHeader.setColorSchemeColors(ContextCompat.getColor(mContext, R.color.colorTextBlack),
ContextCompat.getColor(mContext, R.color.colorTextBlackLight));
return materialHeader;
}
/**
* Adapter加载更多配置
*
* @param adapter
* @return
*/
@Nullable
@Override
public BaseLoadMoreView createDefaultLoadMoreView(BaseQuickAdapter adapter) {
if (adapter != null) {
//设置 <SUF>
adapter.setAnimationFirstOnly(false);
//设置动画
adapter.setAdapterAnimation(new ScaleInAnimation());
adapter.setAnimationEnable(true);
}
//方式一:设置FastLoadMoreView--可参考FastLoadMoreView.Builder相应set方法
//默认配置请参考FastLoadMoreView.Builder(mContext)里初始化
return new FastLoadMoreView.Builder(mContext)
.setLoadingTextFakeBold(true)
.setLoadingSize(SizeUtil.dp2px(20))
// .setLoadTextColor(Color.MAGENTA)
// //设置Loading 颜色-5.0以上有效
// .setLoadingProgressColor(Color.MAGENTA)
// //设置Loading drawable--会使Loading颜色失效
// .setLoadingProgressDrawable(R.drawable.dialog_loading_wei_bo)
// //设置全局TextView颜色
// .setLoadTextColor(Color.MAGENTA)
// //设置全局TextView文字字号
// .setLoadTextSize(SizeUtil.dp2px(14))
// .setLoadingText("努力加载中...")
// .setLoadingTextColor(Color.GREEN)
// .setLoadingTextSize(SizeUtil.dp2px(14))
// .setLoadEndText("我是有底线的")
// .setLoadEndTextColor(Color.GREEN)
// .setLoadEndTextSize(SizeUtil.dp2px(14))
// .setLoadFailText("哇哦!出错了")
// .setLoadFailTextColor(Color.RED)
// .setLoadFailTextSize(SizeUtil.dp2px(14))
.build();
//方式二:使用adapter自带--其实我默认设置的和这个基本一致只是提供了相应设置方法
// return new SimpleLoadMoreView();
//方式三:参考SimpleLoadMoreView或FastLoadMoreView完全自定义自己的LoadMoreView
// return MyLoadMoreView();
}
/**
* 全局设置
*
* @param recyclerView
* @param cls
*/
@Override
public void setRecyclerView(RecyclerView recyclerView, Class<?> cls) {
LoggerManager.i(TAG, "setRecyclerView-" + cls.getSimpleName() + "context:" + recyclerView.getContext() + ";:" + (Activity.class.isAssignableFrom(recyclerView.getContext().getClass())) + ";:" + (recyclerView.getContext() instanceof Activity));
}
@Override
public void setMultiStatusView(StatusLayoutManager.Builder statusView, IFastRefreshLoadView iFastRefreshLoadView) {
}
/**
* 这里将局部设置的FastLoadDialog 抛至该处用于全局设置,在局部使用{@link com.aries.library.fast.retrofit.FastLoadingObserver}
*
* @param activity
* @return
*/
@Nullable
@Override
public FastLoadDialog createLoadingDialog(@Nullable Activity activity) {
return new FastLoadDialog(activity,
new UIProgressDialog.WeBoBuilder(activity)
.setMessage("加载中")
.create())
.setCanceledOnTouchOutside(false)
.setMessage("请求数据中,请稍候...");
//注意使用UIProgressDialog时最好在Builder里设置提示文字setMessage不然后续再设置文字信息也不会显示
// return new FastLoadDialog(activity, new UIProgressDialog.WeChatBuilder(activity)
// .setBackgroundColor(Color.parseColor("#FCFCFC"))
//// .setMinHeight(SizeUtil.dp2px(140))
//// .setMinWidth(SizeUtil.dp2px(270))
// .setTextSizeUnit(TypedValue.COMPLEX_UNIT_PX)
// .setMessage(R.string.fast_loading)
// .setLoadingSize(SizeUtil.dp2px(30))
// .setTextSize(SizeUtil.dp2px(16f))
// .setTextPadding(SizeUtil.dp2px(10))
// .setTextColorResource(R.color.colorTextGray)
// .setIndeterminateDrawable(FastUtil.getTintDrawable(ContextCompat.getDrawable(mContext, R.drawable.dialog_loading), ContextCompat.getColor(mContext, R.color.colorTitleText)))
// .setBackgroundRadius(SizeUtil.dp2px(6f))
// .create());
// Dialog dialog = new PictureDialog(activity);
// return new FastLoadDialog(activity, dialog)
// .setCancelable(true)
// .setCanceledOnTouchOutside(true);
}
/**
* 控制全局TitleBarView
*
* @param titleBar
* @return
*/
@Override
public boolean createTitleBarViewControl(TitleBarView titleBar, Class<?> cls) {
//默认的MD风格返回箭头icon如使用该风格可以不用设置
Drawable mDrawable = DrawableUtil.setTintDrawable(ContextCompat.getDrawable(mContext, R.drawable.fast_ic_back),
ContextCompat.getColor(mContext, R.color.colorTitleText));
//是否支持状态栏白色
boolean isSupport = StatusBarUtil.isSupportStatusBarFontChange();
boolean isActivity = Activity.class.isAssignableFrom(cls);
Activity activity = FastStackUtil.getInstance().getActivity(cls);
//设置TitleBarView 所有TextView颜色
titleBar.setStatusBarLightMode(isSupport)
//不支持黑字的设置白透明
.setStatusAlpha(isSupport ? 0 : 102)
.setLeftTextDrawable(isActivity ? mDrawable : null)
.setDividerHeight(Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP ? SizeUtil.dp2px(0.5f) : 0);
if (activity != null) {
titleBar.setTitleMainText(activity.getTitle())
.setOnLeftTextClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
activity.finish();
}
});
}
return false;
}
/**
* @param isFirst 是否首次提示
* @param activity 操作的Activity
* @return 延迟间隔--如不需要设置两次提示可设置0--最佳方式是直接在回调中执行你想要的操作
*/
@Override
public long quipApp(boolean isFirst, Activity activity) {
//默认配置
if (isFirst) {
ToastUtil.show(R.string.fast_quit_app);
} else {
FastStackUtil.getInstance().exit(false);
}
return 2000;
}
@Override
public Toast getToast() {
return null;
}
@Override
public void setToast(Toast toast, RadiusTextView textView) {
}
/**
* @param o {@link FastObserver} 对象用于后续事件逻辑
* @param e 原始错误
* @return true 拦截操作不进行原始{@link FastObserver#onError(Throwable)}后续逻辑
* false 不拦截继续后续逻辑
* {@link FastNullException} 已在{@link FastObserver#onError} }处理如果为该类型Exception可不用管,参考
*/
@Override
public boolean onError(FastObserver o, Throwable e) {
return false;
}
}
| false |
8113_57 | package com.aries.ui.widget.demo.module.alert;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.CompoundButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import com.aries.ui.helper.navigation.KeyboardHelper;
import com.aries.ui.view.radius.RadiusEditText;
import com.aries.ui.view.radius.RadiusTextView;
import com.aries.ui.widget.BasisDialog;
import com.aries.ui.widget.alert.UIAlertDialog;
import com.aries.ui.widget.demo.R;
import com.aries.ui.widget.demo.base.BaseActivity;
import com.aries.ui.widget.demo.util.SizeUtil;
import androidx.appcompat.widget.SwitchCompat;
import butterknife.BindView;
import butterknife.OnClick;
import static android.content.DialogInterface.BUTTON_NEGATIVE;
import static android.content.DialogInterface.BUTTON_NEUTRAL;
import static android.content.DialogInterface.BUTTON_POSITIVE;
/**
* @Author: AriesHoo on 2019/4/11 12:21
* @E-Mail: AriesHoo@126.com
* @Function: UIAlertDialog示例
* @Description:
*/
public class AlertActivity extends BaseActivity {
@BindView(R.id.sBar_num) SeekBar sBarNum;
@BindView(R.id.tv_statusNum) TextView tvNum;
@BindView(R.id.sBtn_titleAlert) SwitchCompat sBtnTitle;
@BindView(R.id.sBtn_titleColorAlert) SwitchCompat sBtnTitleColor;
@BindView(R.id.sBtn_msgColorAlert) SwitchCompat sBtnMsgColor;
@BindView(R.id.sBtn_buttonColorAlert) SwitchCompat sBtnButtonColor;
@BindView(R.id.sBtn_backAlert) SwitchCompat sBtnBack;
@BindView(R.id.rtv_showAlert) RadiusTextView rtvShow;
private boolean isShowTitle = true;
private boolean isDefaultTitleColor = false;
private boolean isDefaultMsgColor = false;
private boolean isDefaultButtonColor = false;
private boolean isBackDim = true;
private int num = 2;
private String mFormatName = "%1s<font color=\"red\">%2s</font>%3s";
@Override
protected void setTitleBar() {
}
@Override
protected int getLayout() {
return R.layout.activity_alert;
}
@Override
protected void initView(Bundle var1) {
sBarNum.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
num = progress + 1;
tvNum.setText(num + "");
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
sBtnTitle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
isShowTitle = isChecked;
sBtnTitle.setText(isShowTitle ? "显示Title" : "隐藏Title");
sBtnTitleColor.setVisibility(isShowTitle ? View.VISIBLE : View.GONE);
}
});
sBtnTitleColor.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
isDefaultTitleColor = isChecked;
sBtnTitleColor.setText(isDefaultTitleColor ? "默认Title文本颜色" : "自定义Title文本颜色");
}
});
sBtnMsgColor.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
isDefaultMsgColor = isChecked;
sBtnMsgColor.setText(isDefaultMsgColor ? "默认Message文本颜色" : "自定义Message文本颜色");
}
});
sBtnButtonColor.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
isDefaultButtonColor = isChecked;
sBtnButtonColor.setText(isDefaultButtonColor ? "默认Button文本颜色" : "自定义Button文本颜色");
}
});
sBtnBack.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
isBackDim = isChecked;
sBtnBack.setText(isBackDim ? "背景半透明" : "背景全透明");
}
});
sBtnTitle.setChecked(true);
sBtnTitleColor.setChecked(true);
sBtnMsgColor.setChecked(true);
sBtnButtonColor.setChecked(true);
sBtnBack.setChecked(true);
sBarNum.setProgress(1);
}
@OnClick({R.id.rtv_showAlert, R.id.rtv_showQqAlert, R.id.rtv_showAllAlert, R.id.rtv_editAlert
, R.id.rtv_fragmentAlert})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.rtv_showAlert:
new UIAlertDialog.DividerIOSBuilder(this)
.setTitle(isShowTitle ? UIAlertDialog.class.getSimpleName() : "")
.setTitleTextColorResource(isDefaultTitleColor ? R.color.colorAlertTitle : android.R.color.holo_blue_dark)
.setMessage("1、本次更新修复多个重大BUG\n2、新增用户反馈接口")
.setMessageTextColorResource(isDefaultMsgColor ? R.color.colorAlertMessage : android.R.color.holo_green_dark)
.setNegativeButton(num > 1 ? "否定" : "", onAlertClick)
.setNegativeButtonTextColorResource(isDefaultButtonColor ? R.color.colorAlertButton : android.R.color.holo_red_dark)
.setPositiveButton("肯定", onAlertClick)
.setMinHeight(SizeUtil.dp2px(160))
.setPositiveButtonTextColorResource(isDefaultButtonColor ? R.color.colorAlertButton : android.R.color.holo_orange_dark)
.setNeutralButton(num > 2 ? "中性" : "", onAlertClick)
.setNeutralButtonTextColorResource(isDefaultButtonColor ? R.color.colorAlertButton : android.R.color.holo_purple)
.create()
.setDimAmount(isBackDim ? 0.6f : 0f)
.show();
break;
case R.id.rtv_showQqAlert:
UIAlertDialog dialog = new UIAlertDialog.DividerQQBuilder(this)
.setTitle(isShowTitle ? "退出群聊" : "")
.setTitleTextColor(isDefaultTitleColor ? Color.BLACK : Color.BLUE)
.setMessage("你将退出 四川移动爱分享抢流量(XXXXXXXX) 退群通知仅群管理员可见。")
.setMessageTextColor(isDefaultMsgColor ? Color.BLACK : Color.GREEN)
.setNegativeButton(num > 1 ? "取消" : "", onAlertClick)
.setNegativeButtonTextColor(isDefaultButtonColor ? Color.BLACK : Color.RED)
.setPositiveButton("退出", onAlertClick)
.setPositiveButtonTextColor(isDefaultButtonColor ? Color.BLACK : Color.YELLOW)
.setNeutralButton(num > 2 ? "中性" : "", onAlertClick)
.setNeutralButtonTextColor(isDefaultButtonColor ? Color.BLACK : Color.BLUE)
.create()
.setDimAmount(isBackDim ? 0.6f : 0f);
dialog.show();
break;
case R.id.rtv_showAllAlert:
UIAlertDialog alertDialog = new UIAlertDialog.DividerQQBuilder(this)
//设置背景--包括根布局及Button
.setBackgroundColor(Color.WHITE)
// .setBackground(drawable)
// .setBackgroundResource(resId)
//设置按下背景--Button
.setBackgroundPressedColor(Color.argb(255, 240, 240, 240))
// .setBackgroundPressed(drawable)
// .setBackgroundPressedResource(resId)
//背景圆角(当背景及按下背景为ColorDrawable有效)-根布局及Button
.setBackgroundRadius(6f)
// .setBackgroundRadiusResource(resId)
//设置统一padding
.setPadding(SizeUtil.dp2px(20))
//设置根布局最小高度
.setMinHeight(SizeUtil.dp2px(160))
.setElevation(12f)
//设置Title上边分割线颜色--推荐
.setTitleDividerColor(Color.RED)
// .setTitleDividerResource(resId)
// .setTitleDivider(drawable)
//设置Title分割线高度
.setTitleDividerHeight(SizeUtil.dp2px(4))
// .setTitleDividerHeightResource(resId)
//设置TextView对应的尺寸单位
.setTextSizeUnit(TypedValue.COMPLEX_UNIT_DIP)
.setLineSpacingExtra(0f)
.setLineSpacingMultiplier(1.0f)
//设置Title文本
.setTitle("UIAlertDialog示例头部")
// .setTitle(resId)
//设置Title文本颜色
.setTitleTextColor(Color.BLACK)
// .setTitleTextColor(ColorStateList)
// .setTitleTextColorResource(resId)
//设置Title文本尺寸
.setTitleTextSize(20f)
//设置Title文本对齐方式
.setTitleTextGravity(Gravity.CENTER)
//设置Title文本是否加粗
.setTitleTextFakeBoldEnable(false)
//设置Message文本
.setMessage(Html.fromHtml(String.format(mFormatName, "你将退出 ", "四川移动爱分享抢流量(XXXXXXXX)", "退群通知仅群管理员可见。")))
// .setMessage(resId)
//设置Message文本颜色
.setMessageTextColor(Color.BLACK)
// .setMessageTextColor(ColorStateList)
// .setMessageTextColorResource(resId)
//设置Message文本尺寸
.setMessageTextSize(16f)
//设置Message文本对齐方式
.setMessageTextGravity(Gravity.CENTER)
//设置Title文本是否加粗
.setMessageTextFakeBoldEnable(false)
//设置View --始终在Message下边
// .setView(View)
// .setView(layoutId)
//设置是否去掉Button按下阴影-5.0以后的新特性
.setBorderLessButtonEnable(true)
//文本及点击事件
.setNegativeButton("取消", onAlertClick)
// .setNegativeButton(resId,click)
//文本颜色
.setNegativeButtonTextColor(Color.BLACK)
// .setNegativeButtonTextColor(ColorStateList)
// .setNegativeButtonTextColorResource(resId)
//文本尺寸
.setNegativeButtonTextSize(18f)
//是否粗体
.setNegativeButtonFakeBoldEnable(false)
//文本及点击事件
.setNeutralButton("考虑", onAlertClick)
// .setNeutralButton(resId,click)
//文本颜色
.setNeutralButtonTextColor(Color.BLACK)
// .setNeutralButtonTextColor(ColorStateList)
// .setNeutralButtonTextColorResource(resId)
//文本尺寸
.setNeutralButtonTextSize(18f)
//是否粗体
.setNeutralButtonFakeBoldEnable(false)
//文本及点击事件
.setPositiveButton("退出", onAlertClick)
// .setPositiveButton(resId,click)
//文本颜色
.setPositiveButtonTextColor(Color.BLACK)
// .setPositiveButtonTextColor(ColorStateList)
// .setPositiveButtonTextColorResource(resId)
//文本尺寸
.setPositiveButtonTextSize(18f)
//是否粗体
.setPositiveButtonFakeBoldEnable(false)
//设置点击返回键是否可关闭Window
.setCancelable(true)
//设置点击非布局是否关闭Window
.setCanceledOnTouchOutside(true)
//设置Window dismiss()监听
.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
}
})
//设置Window cancel()监听
.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
}
})
//设置 window show()监听
.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
}
})
//设置Window 键盘事件监听
.setOnKeyListener(new DialogInterface.OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
return false;
}
})
.setOnTextViewLineListener(new BasisDialog.OnTextViewLineListener() {
@Override
public void onTextViewLineListener(TextView textView, int lineCount) {
switch (textView.getId()) {
case R.id.tv_titleAlertDialog:
break;
case R.id.tv_messageAlertDialog:
break;
case R.id.btn_negativeAlertDialog:
break;
case R.id.btn_neutralAlertDialog:
break;
case R.id.btn_positiveAlertDialog:
break;
}
}
})
//创建Dialog
.create()
//设置Window宽度
.setWidth(WindowManager.LayoutParams.WRAP_CONTENT)
//设置Window高度
.setHeight(WindowManager.LayoutParams.WRAP_CONTENT)
//设置Window 阴影程度
.setDimAmount(0.6f)
//设置window其它属性
// .setAttributes(WindowManager.LayoutParams)
//设置window动画
// .setWindowAnimations(resId)
//设置Window 位置
.setGravity(Gravity.CENTER);
alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE);
alertDialog.getButton(DialogInterface.BUTTON_NEUTRAL);
alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
alertDialog.show();
break;
case R.id.rtv_editAlert:
final RadiusEditText editText = new RadiusEditText(AlertActivity.this);
ViewGroup.MarginLayoutParams params = new ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
// params.topMargin = SizeUtil.dp2px(12);
editText.getDelegate()
.setTextColor(Color.GRAY)
.setRadius(6f)
.setLeftDrawableWidth(SizeUtil.dp2px(16))
.setLeftDrawableHeight(SizeUtil.dp2px(16))
.setLeftDrawable(R.drawable.ic_search_normal)
.setBackgroundColor(Color.WHITE)
.setStrokeColor(Color.GRAY)
.setStrokeWidth(SizeUtil.dp2px(0.5f));
editText.setMinHeight(SizeUtil.dp2px(40));
editText.setGravity(Gravity.CENTER_VERTICAL);
editText.setCompoundDrawablePadding(SizeUtil.dp2px(6));
editText.setPadding(SizeUtil.dp2px(12), 0, SizeUtil.dp2px(12), 0);
editText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
editText.setHint("请输入内容");
editText.setLayoutParams(params);
new UIAlertDialog.DividerIOSBuilder(this)
.setTitle(isShowTitle ? UIAlertDialog.class.getSimpleName() : "")
.setTitleTextColorResource(isDefaultTitleColor ? R.color.colorAlertTitle : android.R.color.holo_blue_dark)
.setView(editText)
.setNegativeButton(R.string.cancel, null)
.setPositiveButton(R.string.ensure, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String text = editText.getText().toString().trim();
if (TextUtils.isEmpty(text)) {
return;
}
Toast.makeText(mContext, "你输入的是:" + text, Toast.LENGTH_SHORT).show();
}
})
.create()
.setDimAmount(isBackDim ? 0.6f : 0f)
.setGravity(Gravity.BOTTOM)
.show();
//决定是否自动弹出软键盘
KeyboardHelper.openKeyboard(editText);
break;
case R.id.rtv_fragmentAlert:
new AlertDialogFragment().show(getSupportFragmentManager(),"AlertDialogFragment");
break;
default:
break;
}
}
DialogInterface.OnClickListener onAlertClick = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String msg = "";
switch (which) {
case BUTTON_NEGATIVE:
msg = "否定";
break;
case BUTTON_POSITIVE:
msg = "肯定";
break;
case BUTTON_NEUTRAL:
msg = "中性";
break;
}
if (dialog instanceof UIAlertDialog) {
msg = ((UIAlertDialog) dialog).getButton(which).getText().toString();
}
Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
}
};
}
| AriesHoo/UIWidget | app/src/main/java/com/aries/ui/widget/demo/module/alert/AlertActivity.java | 4,108 | //是否粗体 | line_comment | zh-cn | package com.aries.ui.widget.demo.module.alert;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.CompoundButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import com.aries.ui.helper.navigation.KeyboardHelper;
import com.aries.ui.view.radius.RadiusEditText;
import com.aries.ui.view.radius.RadiusTextView;
import com.aries.ui.widget.BasisDialog;
import com.aries.ui.widget.alert.UIAlertDialog;
import com.aries.ui.widget.demo.R;
import com.aries.ui.widget.demo.base.BaseActivity;
import com.aries.ui.widget.demo.util.SizeUtil;
import androidx.appcompat.widget.SwitchCompat;
import butterknife.BindView;
import butterknife.OnClick;
import static android.content.DialogInterface.BUTTON_NEGATIVE;
import static android.content.DialogInterface.BUTTON_NEUTRAL;
import static android.content.DialogInterface.BUTTON_POSITIVE;
/**
* @Author: AriesHoo on 2019/4/11 12:21
* @E-Mail: AriesHoo@126.com
* @Function: UIAlertDialog示例
* @Description:
*/
public class AlertActivity extends BaseActivity {
@BindView(R.id.sBar_num) SeekBar sBarNum;
@BindView(R.id.tv_statusNum) TextView tvNum;
@BindView(R.id.sBtn_titleAlert) SwitchCompat sBtnTitle;
@BindView(R.id.sBtn_titleColorAlert) SwitchCompat sBtnTitleColor;
@BindView(R.id.sBtn_msgColorAlert) SwitchCompat sBtnMsgColor;
@BindView(R.id.sBtn_buttonColorAlert) SwitchCompat sBtnButtonColor;
@BindView(R.id.sBtn_backAlert) SwitchCompat sBtnBack;
@BindView(R.id.rtv_showAlert) RadiusTextView rtvShow;
private boolean isShowTitle = true;
private boolean isDefaultTitleColor = false;
private boolean isDefaultMsgColor = false;
private boolean isDefaultButtonColor = false;
private boolean isBackDim = true;
private int num = 2;
private String mFormatName = "%1s<font color=\"red\">%2s</font>%3s";
@Override
protected void setTitleBar() {
}
@Override
protected int getLayout() {
return R.layout.activity_alert;
}
@Override
protected void initView(Bundle var1) {
sBarNum.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
num = progress + 1;
tvNum.setText(num + "");
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
sBtnTitle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
isShowTitle = isChecked;
sBtnTitle.setText(isShowTitle ? "显示Title" : "隐藏Title");
sBtnTitleColor.setVisibility(isShowTitle ? View.VISIBLE : View.GONE);
}
});
sBtnTitleColor.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
isDefaultTitleColor = isChecked;
sBtnTitleColor.setText(isDefaultTitleColor ? "默认Title文本颜色" : "自定义Title文本颜色");
}
});
sBtnMsgColor.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
isDefaultMsgColor = isChecked;
sBtnMsgColor.setText(isDefaultMsgColor ? "默认Message文本颜色" : "自定义Message文本颜色");
}
});
sBtnButtonColor.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
isDefaultButtonColor = isChecked;
sBtnButtonColor.setText(isDefaultButtonColor ? "默认Button文本颜色" : "自定义Button文本颜色");
}
});
sBtnBack.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
isBackDim = isChecked;
sBtnBack.setText(isBackDim ? "背景半透明" : "背景全透明");
}
});
sBtnTitle.setChecked(true);
sBtnTitleColor.setChecked(true);
sBtnMsgColor.setChecked(true);
sBtnButtonColor.setChecked(true);
sBtnBack.setChecked(true);
sBarNum.setProgress(1);
}
@OnClick({R.id.rtv_showAlert, R.id.rtv_showQqAlert, R.id.rtv_showAllAlert, R.id.rtv_editAlert
, R.id.rtv_fragmentAlert})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.rtv_showAlert:
new UIAlertDialog.DividerIOSBuilder(this)
.setTitle(isShowTitle ? UIAlertDialog.class.getSimpleName() : "")
.setTitleTextColorResource(isDefaultTitleColor ? R.color.colorAlertTitle : android.R.color.holo_blue_dark)
.setMessage("1、本次更新修复多个重大BUG\n2、新增用户反馈接口")
.setMessageTextColorResource(isDefaultMsgColor ? R.color.colorAlertMessage : android.R.color.holo_green_dark)
.setNegativeButton(num > 1 ? "否定" : "", onAlertClick)
.setNegativeButtonTextColorResource(isDefaultButtonColor ? R.color.colorAlertButton : android.R.color.holo_red_dark)
.setPositiveButton("肯定", onAlertClick)
.setMinHeight(SizeUtil.dp2px(160))
.setPositiveButtonTextColorResource(isDefaultButtonColor ? R.color.colorAlertButton : android.R.color.holo_orange_dark)
.setNeutralButton(num > 2 ? "中性" : "", onAlertClick)
.setNeutralButtonTextColorResource(isDefaultButtonColor ? R.color.colorAlertButton : android.R.color.holo_purple)
.create()
.setDimAmount(isBackDim ? 0.6f : 0f)
.show();
break;
case R.id.rtv_showQqAlert:
UIAlertDialog dialog = new UIAlertDialog.DividerQQBuilder(this)
.setTitle(isShowTitle ? "退出群聊" : "")
.setTitleTextColor(isDefaultTitleColor ? Color.BLACK : Color.BLUE)
.setMessage("你将退出 四川移动爱分享抢流量(XXXXXXXX) 退群通知仅群管理员可见。")
.setMessageTextColor(isDefaultMsgColor ? Color.BLACK : Color.GREEN)
.setNegativeButton(num > 1 ? "取消" : "", onAlertClick)
.setNegativeButtonTextColor(isDefaultButtonColor ? Color.BLACK : Color.RED)
.setPositiveButton("退出", onAlertClick)
.setPositiveButtonTextColor(isDefaultButtonColor ? Color.BLACK : Color.YELLOW)
.setNeutralButton(num > 2 ? "中性" : "", onAlertClick)
.setNeutralButtonTextColor(isDefaultButtonColor ? Color.BLACK : Color.BLUE)
.create()
.setDimAmount(isBackDim ? 0.6f : 0f);
dialog.show();
break;
case R.id.rtv_showAllAlert:
UIAlertDialog alertDialog = new UIAlertDialog.DividerQQBuilder(this)
//设置背景--包括根布局及Button
.setBackgroundColor(Color.WHITE)
// .setBackground(drawable)
// .setBackgroundResource(resId)
//设置按下背景--Button
.setBackgroundPressedColor(Color.argb(255, 240, 240, 240))
// .setBackgroundPressed(drawable)
// .setBackgroundPressedResource(resId)
//背景圆角(当背景及按下背景为ColorDrawable有效)-根布局及Button
.setBackgroundRadius(6f)
// .setBackgroundRadiusResource(resId)
//设置统一padding
.setPadding(SizeUtil.dp2px(20))
//设置根布局最小高度
.setMinHeight(SizeUtil.dp2px(160))
.setElevation(12f)
//设置Title上边分割线颜色--推荐
.setTitleDividerColor(Color.RED)
// .setTitleDividerResource(resId)
// .setTitleDivider(drawable)
//设置Title分割线高度
.setTitleDividerHeight(SizeUtil.dp2px(4))
// .setTitleDividerHeightResource(resId)
//设置TextView对应的尺寸单位
.setTextSizeUnit(TypedValue.COMPLEX_UNIT_DIP)
.setLineSpacingExtra(0f)
.setLineSpacingMultiplier(1.0f)
//设置Title文本
.setTitle("UIAlertDialog示例头部")
// .setTitle(resId)
//设置Title文本颜色
.setTitleTextColor(Color.BLACK)
// .setTitleTextColor(ColorStateList)
// .setTitleTextColorResource(resId)
//设置Title文本尺寸
.setTitleTextSize(20f)
//设置Title文本对齐方式
.setTitleTextGravity(Gravity.CENTER)
//设置Title文本是否加粗
.setTitleTextFakeBoldEnable(false)
//设置Message文本
.setMessage(Html.fromHtml(String.format(mFormatName, "你将退出 ", "四川移动爱分享抢流量(XXXXXXXX)", "退群通知仅群管理员可见。")))
// .setMessage(resId)
//设置Message文本颜色
.setMessageTextColor(Color.BLACK)
// .setMessageTextColor(ColorStateList)
// .setMessageTextColorResource(resId)
//设置Message文本尺寸
.setMessageTextSize(16f)
//设置Message文本对齐方式
.setMessageTextGravity(Gravity.CENTER)
//设置Title文本是否加粗
.setMessageTextFakeBoldEnable(false)
//设置View --始终在Message下边
// .setView(View)
// .setView(layoutId)
//设置是否去掉Button按下阴影-5.0以后的新特性
.setBorderLessButtonEnable(true)
//文本及点击事件
.setNegativeButton("取消", onAlertClick)
// .setNegativeButton(resId,click)
//文本颜色
.setNegativeButtonTextColor(Color.BLACK)
// .setNegativeButtonTextColor(ColorStateList)
// .setNegativeButtonTextColorResource(resId)
//文本尺寸
.setNegativeButtonTextSize(18f)
//是否粗体
.setNegativeButtonFakeBoldEnable(false)
//文本及点击事件
.setNeutralButton("考虑", onAlertClick)
// .setNeutralButton(resId,click)
//文本颜色
.setNeutralButtonTextColor(Color.BLACK)
// .setNeutralButtonTextColor(ColorStateList)
// .setNeutralButtonTextColorResource(resId)
//文本尺寸
.setNeutralButtonTextSize(18f)
//是否粗体
.setNeutralButtonFakeBoldEnable(false)
//文本及点击事件
.setPositiveButton("退出", onAlertClick)
// .setPositiveButton(resId,click)
//文本颜色
.setPositiveButtonTextColor(Color.BLACK)
// .setPositiveButtonTextColor(ColorStateList)
// .setPositiveButtonTextColorResource(resId)
//文本尺寸
.setPositiveButtonTextSize(18f)
//是否 <SUF>
.setPositiveButtonFakeBoldEnable(false)
//设置点击返回键是否可关闭Window
.setCancelable(true)
//设置点击非布局是否关闭Window
.setCanceledOnTouchOutside(true)
//设置Window dismiss()监听
.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
}
})
//设置Window cancel()监听
.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
}
})
//设置 window show()监听
.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
}
})
//设置Window 键盘事件监听
.setOnKeyListener(new DialogInterface.OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
return false;
}
})
.setOnTextViewLineListener(new BasisDialog.OnTextViewLineListener() {
@Override
public void onTextViewLineListener(TextView textView, int lineCount) {
switch (textView.getId()) {
case R.id.tv_titleAlertDialog:
break;
case R.id.tv_messageAlertDialog:
break;
case R.id.btn_negativeAlertDialog:
break;
case R.id.btn_neutralAlertDialog:
break;
case R.id.btn_positiveAlertDialog:
break;
}
}
})
//创建Dialog
.create()
//设置Window宽度
.setWidth(WindowManager.LayoutParams.WRAP_CONTENT)
//设置Window高度
.setHeight(WindowManager.LayoutParams.WRAP_CONTENT)
//设置Window 阴影程度
.setDimAmount(0.6f)
//设置window其它属性
// .setAttributes(WindowManager.LayoutParams)
//设置window动画
// .setWindowAnimations(resId)
//设置Window 位置
.setGravity(Gravity.CENTER);
alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE);
alertDialog.getButton(DialogInterface.BUTTON_NEUTRAL);
alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
alertDialog.show();
break;
case R.id.rtv_editAlert:
final RadiusEditText editText = new RadiusEditText(AlertActivity.this);
ViewGroup.MarginLayoutParams params = new ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
// params.topMargin = SizeUtil.dp2px(12);
editText.getDelegate()
.setTextColor(Color.GRAY)
.setRadius(6f)
.setLeftDrawableWidth(SizeUtil.dp2px(16))
.setLeftDrawableHeight(SizeUtil.dp2px(16))
.setLeftDrawable(R.drawable.ic_search_normal)
.setBackgroundColor(Color.WHITE)
.setStrokeColor(Color.GRAY)
.setStrokeWidth(SizeUtil.dp2px(0.5f));
editText.setMinHeight(SizeUtil.dp2px(40));
editText.setGravity(Gravity.CENTER_VERTICAL);
editText.setCompoundDrawablePadding(SizeUtil.dp2px(6));
editText.setPadding(SizeUtil.dp2px(12), 0, SizeUtil.dp2px(12), 0);
editText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
editText.setHint("请输入内容");
editText.setLayoutParams(params);
new UIAlertDialog.DividerIOSBuilder(this)
.setTitle(isShowTitle ? UIAlertDialog.class.getSimpleName() : "")
.setTitleTextColorResource(isDefaultTitleColor ? R.color.colorAlertTitle : android.R.color.holo_blue_dark)
.setView(editText)
.setNegativeButton(R.string.cancel, null)
.setPositiveButton(R.string.ensure, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String text = editText.getText().toString().trim();
if (TextUtils.isEmpty(text)) {
return;
}
Toast.makeText(mContext, "你输入的是:" + text, Toast.LENGTH_SHORT).show();
}
})
.create()
.setDimAmount(isBackDim ? 0.6f : 0f)
.setGravity(Gravity.BOTTOM)
.show();
//决定是否自动弹出软键盘
KeyboardHelper.openKeyboard(editText);
break;
case R.id.rtv_fragmentAlert:
new AlertDialogFragment().show(getSupportFragmentManager(),"AlertDialogFragment");
break;
default:
break;
}
}
DialogInterface.OnClickListener onAlertClick = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String msg = "";
switch (which) {
case BUTTON_NEGATIVE:
msg = "否定";
break;
case BUTTON_POSITIVE:
msg = "肯定";
break;
case BUTTON_NEUTRAL:
msg = "中性";
break;
}
if (dialog instanceof UIAlertDialog) {
msg = ((UIAlertDialog) dialog).getButton(which).getText().toString();
}
Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
}
};
}
| false |
20071_17 | package com.shanpiao.common.utils;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2016/8/11
* desc : 常量相关工具类
* </pre>
*/
public class ConstUtils {
private ConstUtils() {
throw new UnsupportedOperationException("u can't instantiate me...");
}
/******************** 存储相关常量 ********************/
/**
* Byte与Byte的倍数
*/
public static final int BYTE = 1;
/**
* KB与Byte的倍数
*/
public static final int KB = 1024;
/**
* MB与Byte的倍数
*/
public static final int MB = 1048576;
/**
* GB与Byte的倍数
*/
public static final int GB = 1073741824;
public enum MemoryUnit {
BYTE,
KB,
MB,
GB
}
/******************** 时间相关常量 ********************/
/**
* 毫秒与毫秒的倍数
*/
public static final int MSEC = 1;
/**
* 秒与毫秒的倍数
*/
public static final int SEC = 1000;
/**
* 分与毫秒的倍数
*/
public static final int MIN = 60000;
/**
* 时与毫秒的倍数
*/
public static final int HOUR = 3600000;
/**
* 天与毫秒的倍数
*/
public static final int DAY = 86400000;
public enum TimeUnit {
MSEC,
SEC,
MIN,
HOUR,
DAY
}
/******************** 正则相关常量 ********************/
/**
* 正则:手机号(简单)
*/
public static final String REGEX_MOBILE_SIMPLE = "^[1]\\d{10}$";
/**
* 正则:手机号(精确)
* <p>移动:134(0-8)、135、136、137、138、139、147、150、151、152、157、158、159、178、182、183、184、187、188</p>
* <p>联通:130、131、132、145、155、156、175、176、185、186</p>
* <p>电信:133、153、173、177、180、181、189</p>
* <p>全球星:1349</p>
* <p>虚拟运营商:170</p>
*/
public static final String REGEX_MOBILE_EXACT = "^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|(147))\\d{8}$";
/**
* 正则:电话号码
*/
public static final String REGEX_TEL = "^0\\d{2,3}[- ]?\\d{7,8}";
/**
* 正则:身份证号码15位
*/
public static final String REGEX_IDCARD15 = "^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$";
/**
* 正则:身份证号码18位
*/
public static final String REGEX_IDCARD18 = "^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9Xx])$";
/**
* 正则:邮箱
*/
public static final String REGEX_EMAIL = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";
/**
* 正则:URL
*/
public static final String REGEX_URL = "http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w-./?%&=]*)?";
/**
* 正则:汉字
*/
public static final String REGEX_CHZ = "^[\\u4e00-\\u9fa5]+$";
/**
* 正则:用户名,取值范围为a-z,A-Z,0-9,"_",汉字,不能以"_"结尾,用户名必须是6-20位
*/
public static final String REGEX_USERNAME = "^[\\w\\u4e00-\\u9fa5]{6,20}(?<!_)$";
/**
* 正则:yyyy-MM-dd格式的日期校验,已考虑平闰年
*/
public static final String REGEX_DATE = "^(?:(?!0000)[0-9]{4}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)-02-29)$";
/**
* 正则:IP地址
*/
public static final String REGEX_IP = "((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)";
} | Army1990/MyUtils | utils/ConstUtils.java | 1,506 | /**
* 正则:身份证号码18位
*/ | block_comment | zh-cn | package com.shanpiao.common.utils;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2016/8/11
* desc : 常量相关工具类
* </pre>
*/
public class ConstUtils {
private ConstUtils() {
throw new UnsupportedOperationException("u can't instantiate me...");
}
/******************** 存储相关常量 ********************/
/**
* Byte与Byte的倍数
*/
public static final int BYTE = 1;
/**
* KB与Byte的倍数
*/
public static final int KB = 1024;
/**
* MB与Byte的倍数
*/
public static final int MB = 1048576;
/**
* GB与Byte的倍数
*/
public static final int GB = 1073741824;
public enum MemoryUnit {
BYTE,
KB,
MB,
GB
}
/******************** 时间相关常量 ********************/
/**
* 毫秒与毫秒的倍数
*/
public static final int MSEC = 1;
/**
* 秒与毫秒的倍数
*/
public static final int SEC = 1000;
/**
* 分与毫秒的倍数
*/
public static final int MIN = 60000;
/**
* 时与毫秒的倍数
*/
public static final int HOUR = 3600000;
/**
* 天与毫秒的倍数
*/
public static final int DAY = 86400000;
public enum TimeUnit {
MSEC,
SEC,
MIN,
HOUR,
DAY
}
/******************** 正则相关常量 ********************/
/**
* 正则:手机号(简单)
*/
public static final String REGEX_MOBILE_SIMPLE = "^[1]\\d{10}$";
/**
* 正则:手机号(精确)
* <p>移动:134(0-8)、135、136、137、138、139、147、150、151、152、157、158、159、178、182、183、184、187、188</p>
* <p>联通:130、131、132、145、155、156、175、176、185、186</p>
* <p>电信:133、153、173、177、180、181、189</p>
* <p>全球星:1349</p>
* <p>虚拟运营商:170</p>
*/
public static final String REGEX_MOBILE_EXACT = "^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|(147))\\d{8}$";
/**
* 正则:电话号码
*/
public static final String REGEX_TEL = "^0\\d{2,3}[- ]?\\d{7,8}";
/**
* 正则:身份证号码15位
*/
public static final String REGEX_IDCARD15 = "^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$";
/**
* 正则: <SUF>*/
public static final String REGEX_IDCARD18 = "^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9Xx])$";
/**
* 正则:邮箱
*/
public static final String REGEX_EMAIL = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";
/**
* 正则:URL
*/
public static final String REGEX_URL = "http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w-./?%&=]*)?";
/**
* 正则:汉字
*/
public static final String REGEX_CHZ = "^[\\u4e00-\\u9fa5]+$";
/**
* 正则:用户名,取值范围为a-z,A-Z,0-9,"_",汉字,不能以"_"结尾,用户名必须是6-20位
*/
public static final String REGEX_USERNAME = "^[\\w\\u4e00-\\u9fa5]{6,20}(?<!_)$";
/**
* 正则:yyyy-MM-dd格式的日期校验,已考虑平闰年
*/
public static final String REGEX_DATE = "^(?:(?!0000)[0-9]{4}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)-02-29)$";
/**
* 正则:IP地址
*/
public static final String REGEX_IP = "((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)";
} | true |
15071_21 | package com.arronlong.httpclientutil.common.util;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.Header;
import org.apache.http.client.HttpClient;
import com.arronlong.httpclientutil.HttpClientUtil;
import com.arronlong.httpclientutil.builder.HCB;
import com.arronlong.httpclientutil.common.HttpConfig;
import com.arronlong.httpclientutil.common.HttpHeader;
import com.arronlong.httpclientutil.common.Utils;
import com.arronlong.httpclientutil.exception.HttpProcessException;
/**
* 识别验证码
*
* @author arron
* @version 1.0
*/
public class OCR {
/**
* 接口说明:
* https://github.com/AvensLab/OcrKing/blob/master/线上识别http接口说明.txt
*/
private static final String apiUrl = "http://lab.ocrking.com/ok.html";
private static final String apiKey = PropertiesUtil.getProperty("OCR.key");
private static HttpClient client =null; //=HCB.custom().proxy("127.0.0.1", 8888).build();
public static void enableCatch(){
client =HCB.custom().proxy("127.0.0.1", 8888).build();
}
public static void unEnableCatch(){
client =null;
}
//获取固定参数
private static Map<String, Object> getParaMap(){
//加载所有参数
Map<String , Object> map = new HashMap<String, Object>();
map.put("service", "OcrKingForCaptcha");
map.put("language", "eng");
map.put("charset", "7");//7-数字大写小写,5-数字大写字母
map.put("type", "http://www.unknown.com");
map.put("apiKey", apiKey);
return map;
}
/**
* 识别本地校验码(英文:字母+大小写)
*
* @param filePath 验证码地址
* @return 返回识别的验证码结果
*/
public static String ocrCode(String filePath){
return ocrCode(filePath, 0);
}
/**
* 识别本地校验码(英文:字母+大小写)
*
* @param imgFilePath 验证码地址
* @param limitCodeLen 验证码长度(如果结果与设定长度不一致,则返回获取失败的提示)
* @return 返回识别的验证码结果
*/
public static String ocrCode(String imgFilePath, int limitCodeLen){
//读取文件
File f = new File(imgFilePath);
if(!f.exists()){
return "Error:文件不存在!";
}
String html;
try {
html = HttpClientUtil.upload(HttpConfig.custom().client(client).url(apiUrl).files(new String[]{imgFilePath},"ocrfile",true).map(getParaMap()));
//System.out.println(html);
String[] results = StringUtil.regex("<Result>([^<]*)</Result>\\s*<Status>([^<]*)</Status>", html);
if(results.length>0){
//System.out.println(results[0]);
if(Boolean.parseBoolean(results[1])){
if(limitCodeLen<=0 || limitCodeLen==results[0].length()){//不判断长度或者长度一致时,直接返回
return results[0];
}else{
return "Error:获取失败! 原因:识别结果长度为:"+results[0].length()+"(期望长度:"+limitCodeLen+")";
}
}else{
return "Error:获取失败! 原因:"+results[0];
}
}
} catch (HttpProcessException e) {
Utils.exception(e);
}
return "Error:获取失败!";
}
/**
* 直接获取网络验证码(验证码不刷新)
*
* @param imgUrl 验证码地址
* @return 返回识别的验证码结果
*/
public static String ocrCode4Net(String imgUrl){
return ocrCode4Net(imgUrl, 0);
}
/**
* 直接获取网络验证码(验证码不刷新)
*
* @param imgUrl 验证码地址
* @param limitCodeLen 验证码长度
* @return 返回识别的验证码结果
*/
public static String ocrCode4Net(String imgUrl, int limitCodeLen){
Map<String, Object> map = getParaMap();
map.put("url", imgUrl);
Header[] headers = HttpHeader.custom().userAgent("Mozilla/5.0 (Windows NT 5.1; zh-CN; rv:1.9.1.3) Gecko/20100101 Firefox/8.0").build();
try {
String html = HttpClientUtil.post(HttpConfig.custom().client(client).url(apiUrl).headers(headers).map(map));
//System.out.println(html);
String[] results = StringUtil.regex("<Result>([^<]*)</Result>\\s*<Status>([^<]*)</Status>", html);
if(results.length>0){
//System.out.println(results[0]);
if(Boolean.parseBoolean(results[1])){
if(limitCodeLen<=0 || limitCodeLen==results[0].length()){//不判断长度或者长度一致时,直接返回
return results[0];
}else{
return "Error:获取失败! 原因:识别结果长度为:"+results[0].length()+"(期望长度:"+limitCodeLen+")";
}
}else{
return "Error:获取失败! 原因:"+results[0];
}
}
} catch (HttpProcessException e) {
Utils.exception(e);
}
return "Error:获取失败!";
}
/**
* 直接获取网络验证码(通过获取图片流,然后识别验证码)
*
* @param config HttpConfig对象(设置cookie)
* @param savePath 图片保存的完整路径(值为null时,不保存),如:c:/1.png
* @return 返回识别的验证码结果
*/
public static String ocrCode4Net(HttpConfig config, String savePath){
return ocrCode4Net(config, savePath, 0);
}
/**
* 直接获取网络验证码(通过获取图片流,然后识别验证码)
*
* @param config HttpConfig对象(设置cookie)
* @param savePath 图片保存的完整路径(值为null时,不保存),如:c:/1.png
* @param limitCodeLen 验证码长度
* @return 返回识别的验证码结果
*/
@SuppressWarnings("resource")
public static String ocrCode4Net(HttpConfig config, String savePath, int limitCodeLen){
if(savePath==null || savePath.equals("")){//如果不保存图片,则直接使用图片地址的方式获取验证码
return ocrCode4Net(config.url(), limitCodeLen);
}
//下载图片
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
out = (ByteArrayOutputStream) HttpClientUtil.down(config.client(client).out(out));
//本地测试,可以保存一下图片,方便核验
FileOutputStream fos = new FileOutputStream(savePath);
fos.write(out.toByteArray());
return ocrCode(savePath, limitCodeLen);
} catch (HttpProcessException e) {
Utils.exception(e);
} catch (IOException e) {
Utils.exception(e);
}
return "Error:获取失败!";
}
public static void main(String[] args) throws HttpProcessException, IOException {
String filePath="C:/Users/160049/Desktop/中国.png";
String url = "http://file.ocrking.net:6080/small/20161104/w4fCjnzCl8KTwphpwqnCv2bCn8Kp/66fcff8d-61b1-49d6-bbfe-7428cf7accdf_debug.png?e9gFvJmkLbmgsZNTUCCNkjfi8J0Wbpn1CZHeP98eT1kxZ0ISBDt8Ql6h6zQ79pJg";
String url2 = "http://59.41.9.91/GZCX/WebUI/Content/Handler/ValidateCode.ashx?0.3271647585525703";
String code1 = ocrCode(filePath, 5);
String code2 = ocrCode4Net(url,5);
String code3 = ocrCode4Net(HttpConfig.custom().url(url2), System.getProperty("user.dir")+System.getProperty("file.separator")+"123.png", 5);
System.out.println(code1);
System.out.println(code2);
System.out.println(code3);
System.out.println("----");
}
}
| Arronlong/httpclientutil | src/main/java/com/arronlong/httpclientutil/common/util/OCR.java | 2,259 | //如果不保存图片,则直接使用图片地址的方式获取验证码
| line_comment | zh-cn | package com.arronlong.httpclientutil.common.util;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.Header;
import org.apache.http.client.HttpClient;
import com.arronlong.httpclientutil.HttpClientUtil;
import com.arronlong.httpclientutil.builder.HCB;
import com.arronlong.httpclientutil.common.HttpConfig;
import com.arronlong.httpclientutil.common.HttpHeader;
import com.arronlong.httpclientutil.common.Utils;
import com.arronlong.httpclientutil.exception.HttpProcessException;
/**
* 识别验证码
*
* @author arron
* @version 1.0
*/
public class OCR {
/**
* 接口说明:
* https://github.com/AvensLab/OcrKing/blob/master/线上识别http接口说明.txt
*/
private static final String apiUrl = "http://lab.ocrking.com/ok.html";
private static final String apiKey = PropertiesUtil.getProperty("OCR.key");
private static HttpClient client =null; //=HCB.custom().proxy("127.0.0.1", 8888).build();
public static void enableCatch(){
client =HCB.custom().proxy("127.0.0.1", 8888).build();
}
public static void unEnableCatch(){
client =null;
}
//获取固定参数
private static Map<String, Object> getParaMap(){
//加载所有参数
Map<String , Object> map = new HashMap<String, Object>();
map.put("service", "OcrKingForCaptcha");
map.put("language", "eng");
map.put("charset", "7");//7-数字大写小写,5-数字大写字母
map.put("type", "http://www.unknown.com");
map.put("apiKey", apiKey);
return map;
}
/**
* 识别本地校验码(英文:字母+大小写)
*
* @param filePath 验证码地址
* @return 返回识别的验证码结果
*/
public static String ocrCode(String filePath){
return ocrCode(filePath, 0);
}
/**
* 识别本地校验码(英文:字母+大小写)
*
* @param imgFilePath 验证码地址
* @param limitCodeLen 验证码长度(如果结果与设定长度不一致,则返回获取失败的提示)
* @return 返回识别的验证码结果
*/
public static String ocrCode(String imgFilePath, int limitCodeLen){
//读取文件
File f = new File(imgFilePath);
if(!f.exists()){
return "Error:文件不存在!";
}
String html;
try {
html = HttpClientUtil.upload(HttpConfig.custom().client(client).url(apiUrl).files(new String[]{imgFilePath},"ocrfile",true).map(getParaMap()));
//System.out.println(html);
String[] results = StringUtil.regex("<Result>([^<]*)</Result>\\s*<Status>([^<]*)</Status>", html);
if(results.length>0){
//System.out.println(results[0]);
if(Boolean.parseBoolean(results[1])){
if(limitCodeLen<=0 || limitCodeLen==results[0].length()){//不判断长度或者长度一致时,直接返回
return results[0];
}else{
return "Error:获取失败! 原因:识别结果长度为:"+results[0].length()+"(期望长度:"+limitCodeLen+")";
}
}else{
return "Error:获取失败! 原因:"+results[0];
}
}
} catch (HttpProcessException e) {
Utils.exception(e);
}
return "Error:获取失败!";
}
/**
* 直接获取网络验证码(验证码不刷新)
*
* @param imgUrl 验证码地址
* @return 返回识别的验证码结果
*/
public static String ocrCode4Net(String imgUrl){
return ocrCode4Net(imgUrl, 0);
}
/**
* 直接获取网络验证码(验证码不刷新)
*
* @param imgUrl 验证码地址
* @param limitCodeLen 验证码长度
* @return 返回识别的验证码结果
*/
public static String ocrCode4Net(String imgUrl, int limitCodeLen){
Map<String, Object> map = getParaMap();
map.put("url", imgUrl);
Header[] headers = HttpHeader.custom().userAgent("Mozilla/5.0 (Windows NT 5.1; zh-CN; rv:1.9.1.3) Gecko/20100101 Firefox/8.0").build();
try {
String html = HttpClientUtil.post(HttpConfig.custom().client(client).url(apiUrl).headers(headers).map(map));
//System.out.println(html);
String[] results = StringUtil.regex("<Result>([^<]*)</Result>\\s*<Status>([^<]*)</Status>", html);
if(results.length>0){
//System.out.println(results[0]);
if(Boolean.parseBoolean(results[1])){
if(limitCodeLen<=0 || limitCodeLen==results[0].length()){//不判断长度或者长度一致时,直接返回
return results[0];
}else{
return "Error:获取失败! 原因:识别结果长度为:"+results[0].length()+"(期望长度:"+limitCodeLen+")";
}
}else{
return "Error:获取失败! 原因:"+results[0];
}
}
} catch (HttpProcessException e) {
Utils.exception(e);
}
return "Error:获取失败!";
}
/**
* 直接获取网络验证码(通过获取图片流,然后识别验证码)
*
* @param config HttpConfig对象(设置cookie)
* @param savePath 图片保存的完整路径(值为null时,不保存),如:c:/1.png
* @return 返回识别的验证码结果
*/
public static String ocrCode4Net(HttpConfig config, String savePath){
return ocrCode4Net(config, savePath, 0);
}
/**
* 直接获取网络验证码(通过获取图片流,然后识别验证码)
*
* @param config HttpConfig对象(设置cookie)
* @param savePath 图片保存的完整路径(值为null时,不保存),如:c:/1.png
* @param limitCodeLen 验证码长度
* @return 返回识别的验证码结果
*/
@SuppressWarnings("resource")
public static String ocrCode4Net(HttpConfig config, String savePath, int limitCodeLen){
if(savePath==null || savePath.equals("")){//如果 <SUF>
return ocrCode4Net(config.url(), limitCodeLen);
}
//下载图片
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
out = (ByteArrayOutputStream) HttpClientUtil.down(config.client(client).out(out));
//本地测试,可以保存一下图片,方便核验
FileOutputStream fos = new FileOutputStream(savePath);
fos.write(out.toByteArray());
return ocrCode(savePath, limitCodeLen);
} catch (HttpProcessException e) {
Utils.exception(e);
} catch (IOException e) {
Utils.exception(e);
}
return "Error:获取失败!";
}
public static void main(String[] args) throws HttpProcessException, IOException {
String filePath="C:/Users/160049/Desktop/中国.png";
String url = "http://file.ocrking.net:6080/small/20161104/w4fCjnzCl8KTwphpwqnCv2bCn8Kp/66fcff8d-61b1-49d6-bbfe-7428cf7accdf_debug.png?e9gFvJmkLbmgsZNTUCCNkjfi8J0Wbpn1CZHeP98eT1kxZ0ISBDt8Ql6h6zQ79pJg";
String url2 = "http://59.41.9.91/GZCX/WebUI/Content/Handler/ValidateCode.ashx?0.3271647585525703";
String code1 = ocrCode(filePath, 5);
String code2 = ocrCode4Net(url,5);
String code3 = ocrCode4Net(HttpConfig.custom().url(url2), System.getProperty("user.dir")+System.getProperty("file.separator")+"123.png", 5);
System.out.println(code1);
System.out.println(code2);
System.out.println(code3);
System.out.println("----");
}
}
| true |