file_id
int64 1
66.7k
| content
stringlengths 14
343k
| repo
stringlengths 6
92
| path
stringlengths 5
169
|
---|---|---|---|
64,956 | import java.util.*;
import java.io.*;
public class _背包与魔法 {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int n = (int) in.nval;
in.nextToken();
int c = (int) in.nval;
in.nextToken();
int k = (int) in.nval;
int[] f = new int[c + 1], g = new int[c + 1];
for (int i = 0; i < n; ++i) {
in.nextToken();
int v = (int) in.nval;
in.nextToken();
int w = (int) in.nval;
for (int j = c; j >= v; --j) {
f[j] = Math.max(f[j], f[j - v] + w);
g[j] = Math.max(g[j], g[j - v] + w);
if (j >= v + k) g[j] = Math.max(g[j], f[j - v - k] + 2 * w);
}
}
System.out.println(Math.max(g[c], f[c]));
}
}
| GabrielxDuO/algorithm_practice | lanqiao/_背包与魔法.java |
64,957 | package actions;
import action.Action;
import action.ActionMagic;
import chr.Chr;
import others.Calc;
import others.IO;
public class ActionMagicCyclone extends ActionMagic {
public ActionMagicCyclone(Chr me) {
super(me);
name = "サイクロン";
MPCons = 20;
multi = 25;
element = Action.ACTION_ELEMENT_AIR;
}
// 対象:敵全体
public boolean playerTarget() {
return IO.selectAllTargets(me.party.enemy.member, me);
}
// ダメージ:魔法、掛け算方式
public void execute() {
IO.msgln("【%sは%sを唱えた!】", me.name, name);
Calc.mgcMultiDmg(me);
me.MP -= MPCons;
}
}
| kiskfjt/randomQuest | src/actions/ActionMagicCyclone.java |
64,958 | package action.magics;
import action.Action;
import action.ActionMagic;
import chr.Chr;
import others.Calc;
import others.IO;
public class ActionMagicRay extends ActionMagic {
public ActionMagicRay(Chr me) {
super(me);
name = "レイ";
MPCons = 20;
multi = 25;
element = Action.ACTION_ELEMENT_LIGHT;
}
// 対象:敵全体
public boolean playerTarget() {
return IO.selectAllTargets(me.party.enemy.member, me);
}
// ダメージ:魔法、掛け算方式
public void execute() {
IO.msgln("【%sは%sを唱えた!】", me.name, name);
Calc.mgcMultiDmg(me);
me.MP -= MPCons;
}
}
| kiskfjt/randomQuest | src/action/magics/ActionMagicRay.java |
64,959 | package 头条实习;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class 魔法权值 {
private static Scanner sc;
private static int n,k;
private static List<String> strings=new ArrayList<>();
public static void main(String[] args) {
sc=new Scanner(System.in);
while(sc.hasNext()){
int n=sc.nextInt();
int k=sc.nextInt();
if (n>8||k>200) {
System.out.println(0);
}else {
String[] input=new String[n];
for(int i=0;i<n;i++){
input[i]=sc.next();
}
sort(Arrays.asList(input), new ArrayList<>(),n);
List<Integer> list=doSome();
int count=0;
for(Integer i:list)
if(i==k) count++;
System.out.println(count);
}
}
}
private static List<Integer> doSome() {
List<Integer> result=new ArrayList<>();
for(String string:strings){
result.add(calculate(n, k,string)) ;
}
return result;
}
private static int calculate(int n,int k,String str){
int count=0;
for(int i=1;i<=str.length();i++){
String tmpStr=str.substring(i,str.length())+str.substring(0,i);
if (tmpStr.equals(str)) {
count++;
}
}
return count;
}
private static void sort(List datas, List target,int n) {
if (target.size() == n) {
StringBuffer sb=new StringBuffer();
for (Object obj : target)
sb.append(obj) ;
strings.add(sb.toString());
return;
}
for (int i = 0; i < datas.size(); i++) {
List<String> newDatas = new ArrayList<String>(datas);
List<String> newTarget = new ArrayList<String>(target);
newTarget.add(newDatas.get(i));
newDatas.remove(i);
sort(newDatas, newTarget,n);
}
}
}
| cherlas/AllDemoProgrames | NewCoder/src/头条实习/魔法权值.java |
64,960 | package action.magics;
import action.Action;
import action.ActionMagic;
import chr.Chr;
import others.Calc;
import others.IO;
public class ActionMagicStorm extends ActionMagic {
public ActionMagicStorm(Chr me) {
super(me);
name = "ストーム";
MPCons = 10;
multi = 25;
element = Action.ACTION_ELEMENT_AIR;
}
// 対象:敵単体
public boolean playerTarget() {
return IO.selectSingleAliveTarget(me.party.enemy.member, me);
}
// ダメージ:魔法、掛け算方式
public void execute() {
IO.changeTargetsRandomlyIfDead(me.party.enemy.member, me);
IO.msgln("【%sは%sを唱えた!】", me.name, name);
Calc.mgcSingleDmg(me);
me.MP -= MPCons;
}
}
| kiskfjt/randomQuest | src/action/magics/ActionMagicStorm.java |
64,961 | package l1j.server;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import l1j.server.server.utils.IntRange;
public final class Config {
private static final Logger _log = Logger.getLogger(Config.class.getName());
/**
* ロボットシステム
**/
public static String ROBOT_NAME;
/** ロボットシステム **/
/**
* 製作のテーブルアイテムの検索用
**/
public static int CRAFT_TABLE_ONE;
public static int CRAFT_TABLE_TWO;
public static int CRAFT_TABLE_THREE;
public static int CRAFT_TABLE_FOUR;
public static int CRAFT_TABLE_FIVE;
public static int CRAFT_TABLE_SIX;
public static int CRAFT_TABLE_SEVEN;
public static int CRAFT_TABLE_EIGHT;
public static int CRAFT_TABLE_NINE;
public static int CRAFT_TABLE_TEN;
public static int CRAFT_TABLE;
public static int GLUDIN_DUNGEON_OPEN_CYCLE;
public static String EVENTITEM_ITEMID;
public static String EVENTITEM_NUMBER;
public static int SHOCK_STUN;
public static int ARMOR_BREAK;
public static int COUNTER_BARRIER;
public static int DESPERADO;
public static int POWER_GRIP;
public static int ERASE_MAGIC;
public static int EARTH_BIND;
public static int WIND_SHACKLE;
public static int BONE_BREAK;
public static int DEATH_HEAL;
public static int CRAFTSMAN_WEAPON_SCROLL;
public static int BLESS_SCROLL;
public static int ORIM_SCROLL;
public static int CREST_ENCHANT_CHANCE;
// アーノルドイベント
public static int ARNOLD_EVENT_TIME;
public static boolean ARNOLD_EVENTS;
public static boolean SUPPLY_SCARECROW_TAM;
public static boolean PURE_WHITE_T;
// ルームティス黒い光のイヤリングダメージ追加追加確率
public static int ROOMTIECE_CHANCE; // 黒い光ピアス追加ダメージ確率
public static int FEATHER_SHOP_NUM; // 羽店の使用本数制限
public static int FEATHER_TIME; // 羽支給時間
public static int FISH_EXP; // 成長釣りの基本経験値獲得量
public static int FISH_TIME; // 成長釣り時間
public static boolean FISH_COM; // 成長釣りギフト
// 強化バフ(活力、攻撃、魔法、ホールド、スタン、防御)時間外部化
// 強化バフ_活力、強化バフ_攻撃、強化バフ_防御、強化バフ_魔法、強化バフ_スターン、強化バフ_ホールド
public static int ENCHANT_BUFF_TIME_VITALITY;
public static int ENCHANT_BUFF_TIME_ATTACK;
public static int ENCHANT_BUFF_TIME_DEFENCE;
public static int ENCHANT_BUFF_TIME_MAGIC;
public static int ENCHANT_BUFF_TIME_STUN;
public static int ENCHANT_BUFF_TIME_HOLD;
public static int ENCHANT_BUFF_TIME_STR;
public static int ENCHANT_BUFF_TIME_DEX;
public static int ENCHANT_BUFF_TIME_INT;
public static int RAID_TIME;
public static int STAGE_1;
public static int STAGE_2;
public static int STAGE_3;
/**
* NPC 物理ダメージ/魔法ダメージ
**/
public static int npcdmg;
public static int npcmagicdmg;
/**
* ギラン監獄週末イベント用
**/
public static int mapid;
public static int mapid1;
public static int mapid2;
public static int mapid3;
public static int mapid4;
public static int mapid5;
public static int EXP;
public static int EVENT_ITEMS;
public static int EVENT_NUMBERS;
// 血盟経験値
public static int CLAN_EXP_ONE;
public static int CLAN_EXP_TWO;
public static int CLAN_EXP_THREE;
public static int CLAN_EXP_FOUR;
public static int CLAN_EXP_FIVE;
public static int CLAN_EXP_SIX;
public static int CLAN_EXP_SEVEN;
public static int ADEN_SHOP_NPC;
public static int Tam_Time;
/**
* 階級別アビスポイントの外部化
**/
public static int ABYSS_POINT; // ギラン監獄1〜4階狩りの時得るポイントの幅(ランダム)
public static int CLASS_START_LEVEL; // 階級算定開始レベル
public static int SUPREMECOMMANDER; // 総司令官
public static int COMMANDER; // 司令官
public static int IMPERATOR; // 大将軍
public static int GENERAL; // 将軍
public static int STAR_FIVE; // 5将校
public static int STAR_FOUR; // 4将校
public static int STAR_THREE; // 3将校
public static int STAR_TWO; // 2将校
public static int STAR_ONE; // 1将校
public static int ONE_CLASS; // 1等兵
public static int TWO_CLASS; // 2等兵
public static int THREE_CLASS; // 3等兵
public static int FOUR_CLASS; // 四等兵
public static int FIVE_CLASS; // 五等兵
public static int SIX_CLASS; // 六等兵
public static int SEVEN_CLASS; // 七等兵
public static int EIGHT_CLASS; // 八等兵
public static int NINE_CLASS; // 九等兵
public static int SUPREMECOMMANDER_DAMAGE; // 総司令官
public static int COMMANDER_DAMAGE; // 司令官
public static int IMPERATOR_DAMAGE; // 大将軍
public static int GENERAL_DAMAGE; // 将軍
public static int STAR_FIVE_DAMAGE; // 5将校
/**
* サーバーマネージャー
**/
public static boolean normal = false;
public static boolean world = false;
public static boolean whisper = false;
public static boolean alliance = false;
public static boolean party = false;
public static boolean shout = false;
public static boolean business = false;
public static boolean shutdownCheck = false;
/** サーバーマネージャー **/
/**
* Debug/release mode
*/
public static final boolean DEBUG = false;
public static boolean STANDBY_SERVER = false;
/**
* Thread pools size
*/
public static int THREAD_P_EFFECTS;
public static int THREAD_P_GENERAL;
public static int AI_MAX_THREAD;
public static int THREAD_P_SIZE_GENERAL;
public static int THREAD_P_TYPE_GENERAL;
public static int SELECT_THREAD_COUNT;
/**
* Server control
*/
public static String GAME_SERVER_NAME;
public static int GAME_SERVER_PORT;
public static int AD_REPORT_SERVER_PORT;
public static String DB_DRIVER;
public static String DB_URL;
public static String DB_LOGIN;
public static String DB_PASSWORD;
public static String TIME_ZONE;
public static int CLIENT_LANGUAGE;
public static boolean HOSTNAME_LOOKUPS;
public static int AUTOMATIC_KICK;
public static boolean AUTO_CREATE_ACCOUNTS;
public static short MAX_ONLINE_USERS;
public static boolean CACHE_MAP_FILES;
public static boolean LOAD_V2_MAP_FILES;
public static boolean CHECK_MOVE_INTERVAL;
public static boolean CHECK_ATTACK_INTERVAL;
public static boolean CHECK_SPELL_INTERVAL;
public static byte LOGGING_WEAPON_ENCHANT;
public static byte LOGGING_ARMOR_ENCHANT;
public static boolean LOGGING_CHAT_NORMAL;
public static boolean LOGGING_CHAT_WHISPER;
public static boolean LOGGING_CHAT_SHOUT;
public static boolean LOGGING_CHAT_WORLD;
public static boolean LOGGING_CHAT_CLAN;
public static boolean LOGGING_CHAT_PARTY;
public static boolean LOGGING_CHAT_COMBINED;
public static boolean LOGGING_CHAT_CHAT_PARTY;
public static boolean BROADCAST_KILL_LOG;
public static int BROADCAST_KILL_LOG_LEVEL;
public static double ACCEL_ALLOW;
public static String PRIVATE_SHOP_CHAT;
public static int STORE_USAGE_LEVEL;
public static int HAJA;
public static int PC_RECOGNIZE_RANGE;
public static boolean CHARACTER_CONFIG_IN_SERVER_SIDE;
public static boolean ALLOW_2PC;
public static boolean CHECK_AUTO;
public static boolean CHECK_AUTO_ENCHANT;
public static int LEVEL_DOWN_RANGE;
public static boolean SEND_PACKET_BEFORE_TELEPORT;
public static boolean DETECT_DB_RESOURCE_LEAKS;
public static boolean AUTH_CONNECT; // TODO LINALL CONNECT
public static int AUTH_KEY; // TODO LINALL CONNECT
public static int AUTH_IP;
/**
* Rate control
*/
public static int FG_ISVAL; // 忘れられた島レプジェ
public static double RATE_XP;
public static double RATE_LAWFUL;
public static double RATE_KARMA;
public static double RATE_DROP_ADENA;
public static double RATE_DROP_ITEMS;
public static double RATE_DROP_RABBIT;// 辛卯年のイベント
public static int ENCHANT_CHANCE_WEAPON;
public static int ENCHANT_CHANCE_ARMOR;
public static int ENCHANT_CHANCE_ACCESSORY;
public static int ARNOLD_WEAPON_CHANCE;
public static double RATE_WEIGHT_LIMIT;
public static double RATE_WEIGHT_LIMIT_PET;
public static double RATE_SHOP_SELLING_PRICE;
public static double RATE_SHOP_PURCHASING_PRICE;
public static int CREATE_CHANCE_DIARY;
public static int CREATE_CHANCE_RECOLLECTION;
public static int CREATE_CHANCE_MYSTERIOUS;
public static int CREATE_CHANCE_PROCESSING;
public static int CREATE_CHANCE_PROCESSING_DIAMOND;
public static int CREATE_CHANCE_DANTES;
public static int CREATE_CHANCE_ANCIENT_AMULET;
public static int CREATE_CHANCE_HISTORY_BOOK;
public static int FEATHER_NUM;
public static int FEATHER_NUM1;
public static int FEATHER_NUM2;
public static int FEATHER_NUM3;
public static int TAM_COUNT;
public static int TAM_CLAN_COUNT;
public static int TAM_EX_COUNT;
public static int TAM_EX2_COUNT;
public static boolean BATTLE_ZONE_OPERATION;
public static boolean TI_DUNGEON_FEATHER;
public static boolean GLUDIO_DUNGEON_FEATHER;
public static boolean SKT_DUNGEON_FEATHER;
public static boolean FI_FEATHER;
public static int BATTLE_ZONE_ENTRY_LEVEL;
public static String BATTLE_ZONE_ITEM;
public static String BATTLE_ZONE_ITEM_COUNT;
public static String PIC_BOOK_1_ITEM;
public static String PIC_BOOK_1_ITEM_COUNT;
public static String PIC_BOOK_2_ITEM;
public static String PIC_BOOK_2_ITEM_COUNT;
public static String PIC_BOOK_3_ITEM;
public static String PIC_BOOK_3_ITEM_COUNT;
public static boolean DEMON_KING_OPERATION;
public static boolean BOSS_SPAWN_OPERATION;
public static boolean ALL_GIFT_OPERATION;
public static int DEMON_KING_ENTRY_LEVEL;
public static int DEMON_KING_TIME;
public static boolean ADEN_HUNTING_OPERATION;
public static int ADEN_HUNTING_ENTRY_LEVEL;
public static int ADEN_HUNTING_TIME;
/**
* イベント靴下支給
**/
public static boolean SOCKS_OPERATION;
public static boolean EVENT_A_OPERATION;
public static int EVENT_TIME;
public static int EVENT_NUMBER;
public static int EVENT_ITEM;
public static int systime;
public static String sys1;
public static String sys2;
public static String sys3;
public static String sys4;
public static String sys5;
public static String sys6;
public static String sys7;
public static String sys8;
public static String sys9;
public static String sys10;
public static String sys11;
public static String sys12;
public static String sys13;
public static String sys14;
public static String sys15;
public static String sys16;
/**
* モンスタージュクウェレベルの難易度
**/
public static int WeekLevel1;
public static int WeekLevel2;
/**
* ミニ攻城補償段階
**/
public static int Tower;
public static int MTower;
public static int LTower;
public static int TowerC;
public static int MTowerC;
public static int LTowerC;
public static double RATE_7_DMG_RATE;// エンチャンツタ外部化
public static int RATE_7_DMG_PER;
public static double RATE_8_DMG_RATE;
public static int RATE_8_DMG_PER;
public static double RATE_9_DMG_RATE;
public static int RATE_9_DMG_PER;
public static double RATE_10_DMG_RATE;
public static int RATE_10_DMG_PER;
public static double RATE_11_DMG_RATE;
public static int RATE_11_DMG_PER;
public static double RATE_12_DMG_RATE;
public static int RATE_12_DMG_PER;
public static double RATE_13_DMG_RATE;
public static int RATE_13_DMG_PER;
public static double RATE_14_DMG_RATE;
public static int RATE_14_DMG_PER;
public static double RATE_15_DMG_RATE;
public static int RATE_15_DMG_PER;
public static double RATE_16_DMG_RATE;
public static int RATE_16_DMG_PER;
public static double RATE_17_DMG_RATE;
public static int RATE_17_DMG_PER;
public static double RATE_18_DMG_RATE;
public static int RATE_18_DMG_PER;
public static int DISCHARGE1;
public static int DISCHARGE2;
public static int DISCHARGE3;
public static int DISCHARGE4;
public static int DISCHARGE5;
public static int DISCHARGE6;
public static int DISCHARGE7;
/**
* AltSettings control
*/
public static short GLOBAL_CHAT_LEVEL;
public static short WHISPER_CHAT_LEVEL;
public static byte AUTO_LOOT;
public static int LOOTING_RANGE;
public static boolean ALT_NONPVP;
public static boolean ALT_ATKMSG;
public static boolean CHANGE_TITLE_BY_ONESELF;
public static int MAX_CLAN_MEMBER;
public static boolean CLAN_ALLIANCE;
public static int MAX_PT;
public static int MAX_CHAT_PT;
public static boolean SIM_WAR_PENALTY;
public static boolean GET_BACK;
public static String ALT_ITEM_DELETION_TYPE;
public static int ALT_ITEM_DELETION_TIME;
public static int ALT_ITEM_DELETION_RANGE;
public static boolean ALT_GMSHOP;
public static int ALT_GMSHOP_MIN_ID;
public static int ALT_GMSHOP_MAX_ID;
public static boolean ALT_BASETOWN;
public static int ALT_BASETOWN_MIN_ID;
public static int ALT_BASETOWN_MAX_ID;
public static boolean ALT_HALLOWEENIVENT;
public static int WHOIS_CONTER;
public static boolean ALT_BEGINNER_BONUS;
public static int NOTIS_TIME; // お知らせ
public static int CLAN_COUNT; // 血盟バフ人員
public static double EX_EXP;
public static int AUTO_REMOVELEVEL;
public static int BUFFLEVEL; // バフレベル以下
// とりあえずわかんないから和訳まんまえローマ字に
// 「つつくウィザード」
public static int TSUTSUKUGEN;
public static int NORMAL_PROTECTION;
public static int LASTAVARD_ENTRY_LEVEL; // ラバー入場レベル
public static double WIZARD_MAGIC_DAMAGE; // ウィザードツタ
public static double WIZARD_MONSTER_DAMAGE; // ウィザードツタ
/**
* 新たに追加
**/
public static int useritem;
public static int usercount;
public static int KIRINGKU;
public static int DEATH_KNIGHT_HELLFIRE;
public static int DOLL_CHANCE;
public static int LIGHT_OF_ETERNAL_LIFE;
public static int LEAVES_OF_LIFE;
public static double KNIGHT;
public static double DRAGON_KNIGHT;
public static double ELF;
public static double CROWN;
public static double WIZARD;
public static double DARK_ELF;
public static double ILLUSIONIST;
public static double WARRIOR;
public static double RECOVERY_EXP;
public static boolean EXP_POT_LIMIT;
public static int NEW_CLAN_PROTECTION_LEVEL;
public static int NEW_CLAN;
public static boolean NEW_CLAN_PROTECTION_PROCESS;
public static int WEAPON_ENCHANT;
public static int WEAPON_PREMIUM_ENCHANT;
public static int ARMOR_ENCHANT;
public static int ARMOR_PREMIUM_ENCHANT;
public static int ROOMTIS;
public static int SNAPPER;
public static int ACCESSORIES;
public static boolean SPAWN_ROBOT;
/**
* [幻想イベント本サーバー化]
**/
public static boolean ALT_FANTASYEVENT;
public static boolean ALT_RABBITEVENT; // 神妙イベント(2011)
public static boolean ALT_FISHEVENT;
public static int EXP_PAYMENT_TEAM; // 経験値支給団
public static int DECLARATION_LEVEL; // 宣言レベル
public static int CLAN_CONNECT_COUNT; // 血盟接続人数
public static boolean ALT_JPPRIVILEGED;
public static boolean ALT_WHO_COMMAND;
public static boolean ALT_REVIVAL_POTION;
public static int ALT_WAR_TIME;
public static int ALT_WAR_TIME_UNIT;
public static int ALT_WAR_INTERVAL;
public static int ALT_WAR_INTERVAL_UNIT;
public static int ALT_RATE_OF_DUTY;
public static boolean SPAWN_HOME_POINT;
public static int SPAWN_HOME_POINT_RANGE;
public static int SPAWN_HOME_POINT_COUNT;
public static int SPAWN_HOME_POINT_DELAY;
public static boolean INIT_BOSS_SPAWN;
public static int ELEMENTAL_STONE_AMOUNT;
public static int HOUSE_TAX_INTERVAL;
public static int MAX_DOLL_COUNT;
public static boolean RETURN_TO_NATURE;
public static int MAX_NPC_ITEM;
public static int MAX_PERSONAL_WAREHOUSE_ITEM;
public static int MAX_CLAN_WAREHOUSE_ITEM;
public static boolean DELETE_CHARACTER_AFTER_7DAYS;
public static int GMCODE;
public static int NEW_PLAYER;
public static int ALT_DROPLEVELLIMIT;
public static int DVC_ENTRY_LEVEL;
public static int DVC_LIMIT_LEVEL;
public static int HC_ENTRY_LEVEL;
public static int HC_LIMIT_LEVEL;
public static int TIC_ENTRY_LEVEL;
public static int TIC_LIMIT_LEVEL;
public static int SKTC_ENTRY_LEVEL;
public static int SKTC_LIMIT_LEVEL;
public static int DISCARDED_LAND_ENTRY_LEVEL;
public static int ANCIENT_WEAPON;
public static int ANCIENT_ARMOR;
public static boolean Use_Show_Announcecycle; // 追加
public static int Show_Announcecycle_Time; // 追加
public static int HELL_TIME;
public static int HELL_LEVEL;
/**
* CharSettings control
*/
public static int PRINCE_MAX_HP;
public static int PRINCE_MAX_MP;
public static int KNIGHT_MAX_HP;
public static int KNIGHT_MAX_MP;
public static int ELF_MAX_HP;
public static int ELF_MAX_MP;
public static int WIZARD_MAX_HP;
public static int WIZARD_MAX_MP;
public static int DARKELF_MAX_HP;
public static int DARKELF_MAX_MP;
public static int DRAGONKNIGHT_MAX_HP;
public static int DRAGONKNIGHT_MAX_MP;
public static int BLACKWIZARD_MAX_HP;
public static int BLACKWIZARD_MAX_MP;
public static int WARRIOR_MAX_HP;
public static int WARRIOR_MAX_MP;
public static int PRINCE_ADD_DAMAGEPC;
public static int KNIGHT_ADD_DAMAGEPC;
public static int ELF_ADD_DAMAGEPC;
public static int WIZARD_ADD_DAMAGEPC;
public static int DARKELF_ADD_DAMAGEPC;
public static int DRAGONKNIGHT_ADD_DAMAGEPC;
public static int BLACKWIZARD_ADD_DAMAGEPC;
public static int WARRIOR_ADD_DAMAGEPC;
public static int LIMITLEVEL;
public static int LV50_EXP;
public static int LV51_EXP;
public static int LV52_EXP;
public static int LV53_EXP;
public static int LV54_EXP;
public static int LV55_EXP;
public static int LV56_EXP;
public static int LV57_EXP;
public static int LV58_EXP;
public static int LV59_EXP;
public static int LV60_EXP;
public static int LV61_EXP;
public static int LV62_EXP;
public static int LV63_EXP;
public static int LV64_EXP;
public static int LV65_EXP;
public static int LV66_EXP;
public static int LV67_EXP;
public static int LV68_EXP;
public static int LV69_EXP;
public static int LV70_EXP;
public static int LV71_EXP;
public static int LV72_EXP;
public static int LV73_EXP;
public static int LV74_EXP;
public static int LV75_EXP;
public static int LV76_EXP;
public static int LV77_EXP;
public static int LV78_EXP;
public static int LV79_EXP;
public static int LV80_EXP;
public static int LV81_EXP;
public static int LV82_EXP;
public static int LV83_EXP;
public static int LV84_EXP;
public static int LV85_EXP;
public static int LV86_EXP;
public static int LV87_EXP;
public static int LV88_EXP;
public static int LV89_EXP;
public static int LV90_EXP;
public static int LV91_EXP;
public static int LV92_EXP;
public static int LV93_EXP;
public static int LV94_EXP;
public static int LV95_EXP;
public static int LV96_EXP;
public static int LV97_EXP;
public static int LV98_EXP;
public static int LV99_EXP;
/**
* データベースフル関連
*/
public static int min;
public static int max;
public static boolean run;
// デバッグ用パラメータ
public static boolean SHOW_CLIENT_PACKET;
/**
* Configuration files
*/
public static final String SERVER_CONFIG_FILE = "./config/server.properties";
public static final String RATES_CONFIG_FILE = "./config/rates.properties";
public static final String ALT_SETTINGS_FILE = "./config/altsettings.properties";
public static final String CHAR_SETTINGS_CONFIG_FILE = "./config/charsettings.properties";
public static final String CHOLONG_SETTINGS_CONFIG_FILE = "./config/Eventlink.properties";
/**
* その他の設定
*/
// NPCからは飲むことができるMPの限界
public static final int MANA_DRAIN_LIMIT_PER_NPC = 40;
// 1回の攻撃では、飲むことができるMP限界(SOM、鋼鉄SOM)
public static final int MANA_DRAIN_LIMIT_PER_SOM_ATTACK = 9;
public static void load() {
_log.info("loading gameserver config");
/** server.properties **/
try {
Properties serverSettings = new Properties();
InputStream is = new FileInputStream(new File(SERVER_CONFIG_FILE));
serverSettings.load(is);
is.close();
/** データベースフル */
min = Integer.parseInt(serverSettings.getProperty("min"));
max = Integer.parseInt(serverSettings.getProperty("max"));
run = Boolean.parseBoolean(serverSettings.getProperty("run"));
GAME_SERVER_NAME = serverSettings.getProperty("GameServerName", "フォアザサーバー");
GAME_SERVER_PORT = Integer.parseInt(serverSettings.getProperty("GameserverPort", "2000"));
System.out.println("G:" + GAME_SERVER_PORT);
AD_REPORT_SERVER_PORT = Integer.parseInt(serverSettings.getProperty("AdReportServerPort", "18182"));
DB_DRIVER = serverSettings.getProperty("Driver", "com.mysql.jdbc.Driver");
DB_URL = serverSettings.getProperty("URL",
"jdbc:mysql://localhost/l1jdb?useUnicode=true&characterEncoding=utf8");
DB_LOGIN = serverSettings.getProperty("Login", "root");
DB_PASSWORD = serverSettings.getProperty("Password", "");
THREAD_P_TYPE_GENERAL = Integer.parseInt(serverSettings.getProperty("GeneralThreadPoolType", "0"), 10);
THREAD_P_SIZE_GENERAL = Integer.parseInt(serverSettings.getProperty("GeneralThreadPoolSize", "0"), 10);
SELECT_THREAD_COUNT = Integer.parseInt(serverSettings.getProperty("IoThreadPoolSize", "4"));
CLIENT_LANGUAGE = Integer.parseInt(serverSettings.getProperty("ClientLanguage", "4"));
TIME_ZONE = serverSettings.getProperty("TimeZone", "JST");
HOSTNAME_LOOKUPS = Boolean.parseBoolean(serverSettings.getProperty("HostnameLookups", "false"));
AUTOMATIC_KICK = Integer.parseInt(serverSettings.getProperty("AutomaticKick", "10"));
AUTO_CREATE_ACCOUNTS = Boolean.parseBoolean(serverSettings.getProperty("AutoCreateAccounts", "true"));
MAX_ONLINE_USERS = Short.parseShort(serverSettings.getProperty("MaximumOnlineUsers", "30"));
CACHE_MAP_FILES = Boolean.parseBoolean(serverSettings.getProperty("CacheMapFiles", "false"));
LOAD_V2_MAP_FILES = Boolean.parseBoolean(serverSettings.getProperty("LoadV2MapFiles", "false"));
LOGGING_WEAPON_ENCHANT = Byte.parseByte(serverSettings.getProperty("LoggingWeaponEnchant", "0"));
LOGGING_ARMOR_ENCHANT = Byte.parseByte(serverSettings.getProperty("LoggingArmorEnchant", "0"));
LOGGING_CHAT_NORMAL = Boolean.parseBoolean(serverSettings.getProperty("LoggingChatNormal", "false"));
LOGGING_CHAT_WHISPER = Boolean.parseBoolean(serverSettings.getProperty("LoggingChatWhisper", "false"));
LOGGING_CHAT_SHOUT = Boolean.parseBoolean(serverSettings.getProperty("LoggingChatShout", "false"));
LOGGING_CHAT_WORLD = Boolean.parseBoolean(serverSettings.getProperty("LoggingChatWorld", "false"));
LOGGING_CHAT_CLAN = Boolean.parseBoolean(serverSettings.getProperty("LoggingChatClan", "false"));
LOGGING_CHAT_PARTY = Boolean.parseBoolean(serverSettings.getProperty("LoggingChatParty", "false"));
LOGGING_CHAT_COMBINED = Boolean.parseBoolean(serverSettings.getProperty("LoggingChatCombined", "false"));
LOGGING_CHAT_CHAT_PARTY = Boolean.parseBoolean(serverSettings.getProperty("LoggingChatChatParty", "false"));
PC_RECOGNIZE_RANGE = Integer.parseInt(serverSettings.getProperty("PcRecognizeRange", "20"));
BROADCAST_KILL_LOG = Boolean.parseBoolean(serverSettings.getProperty("BroadcastKillLog", "true"));
BROADCAST_KILL_LOG_LEVEL = Integer.parseInt(serverSettings.getProperty("BroadcastKillLogLevel", "1"));
ACCEL_ALLOW = ((double) (Integer.parseInt(serverSettings.getProperty("AccelAllow", "10")))) / 100.f;
PRIVATE_SHOP_CHAT = new String(serverSettings.getProperty("PrivateShopChat").getBytes("ISO-8859-1"),
"MS932");
HAJA = Integer.parseInt(serverSettings.getProperty("Haja", "2"));
CHARACTER_CONFIG_IN_SERVER_SIDE = Boolean
.parseBoolean(serverSettings.getProperty("CharacterConfigInServerSide", "true"));
ALLOW_2PC = Boolean.parseBoolean(serverSettings.getProperty("Allow2PC", "true"));
CHECK_AUTO = Boolean.parseBoolean(serverSettings.getProperty("CheckAuto", "true"));
CHECK_AUTO_ENCHANT = Boolean.parseBoolean(serverSettings.getProperty("CheckAutoEnchant", "true"));
LEVEL_DOWN_RANGE = Integer.parseInt(serverSettings.getProperty("LevelDownRange", "0"));
SEND_PACKET_BEFORE_TELEPORT = Boolean
.parseBoolean(serverSettings.getProperty("SendPacketBeforeTeleport", "true"));
DETECT_DB_RESOURCE_LEAKS = Boolean
.parseBoolean(serverSettings.getProperty("EnableDatabaseResourceLeaksDetection", "false"));
// TODO LINALL CONNECT
AUTH_CONNECT = Boolean.parseBoolean(serverSettings.getProperty("AuthConnect", "false"));
// TODO LINALL CONNECT
AUTH_KEY = Integer.parseInt(serverSettings.getProperty("AuthKey", "136"));
AUTH_IP = Integer.parseInt(serverSettings.getProperty("CheckIpCount", "2"));
SHOW_CLIENT_PACKET = Boolean.parseBoolean(serverSettings.getProperty("ShowClientPacket", "false"));
} catch (Exception e) {
_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
throw new Error("Failed to Load " + SERVER_CONFIG_FILE + " File.");
}
/** rates.properties **/
try {
Properties rateSettings = new Properties();
FileReader is = new FileReader(new File(RATES_CONFIG_FILE));
rateSettings.load(is);
is.close();
systime = Integer.parseInt(rateSettings.getProperty("systime", "30"));
sys1 = rateSettings.getProperty("sys1", "");
sys2 = rateSettings.getProperty("sys2", "");
sys3 = rateSettings.getProperty("sys3", "");
sys4 = rateSettings.getProperty("sys4", "");
sys5 = rateSettings.getProperty("sys5", "");
sys6 = rateSettings.getProperty("sys6", "");
sys7 = rateSettings.getProperty("sys7", "");
sys8 = rateSettings.getProperty("sys8", "");
sys9 = rateSettings.getProperty("sys9", "");
sys10 = rateSettings.getProperty("sys10", "");
sys11 = rateSettings.getProperty("sys11", "");
sys12 = rateSettings.getProperty("sys12", "");
sys13 = rateSettings.getProperty("sys13", "");
sys14 = rateSettings.getProperty("sys14", "");
sys15 = rateSettings.getProperty("sys15", "");
sys16 = rateSettings.getProperty("sys16", "");
RATE_XP = Double.parseDouble(rateSettings.getProperty("RateXp", "1.0"));
EX_EXP = Double.parseDouble(rateSettings.getProperty("BloodBonus", "1.0"));
RATE_LAWFUL = Double.parseDouble(rateSettings.getProperty("RateLawful", "1.0"));
RATE_KARMA = Double.parseDouble(rateSettings.getProperty("RateKarma", "1.0"));
RATE_DROP_ADENA = Double.parseDouble(rateSettings.getProperty("RateDropAdena", "1.0"));
RATE_DROP_ITEMS = Double.parseDouble(rateSettings.getProperty("RateDropItems", "1.0"));
RATE_DROP_RABBIT = Double.parseDouble(rateSettings.getProperty("RateDropRabbit", "10.0"));
ENCHANT_CHANCE_WEAPON = Integer.parseInt(rateSettings.getProperty("EnchantChanceWeapon", "68"));
ENCHANT_CHANCE_ARMOR = Integer.parseInt(rateSettings.getProperty("EnchantChanceArmor", "52"));
ENCHANT_CHANCE_ACCESSORY = Integer.parseInt(rateSettings.getProperty("EnchantChanceAccessory", "5"));
ARNOLD_WEAPON_CHANCE = Integer.parseInt(rateSettings.getProperty("ArnoldWeapon", "5"));
CREST_ENCHANT_CHANCE = Integer.parseInt(rateSettings.getProperty("文章強化確率", "30"));
FG_ISVAL = Integer.parseInt(rateSettings.getProperty("EnterLevel", "0"));
WeekLevel1 = Integer.parseInt(rateSettings.getProperty("ジュクウェレベル1", "65"));
WeekLevel2 = Integer.parseInt(rateSettings.getProperty("ジュクウェレベル2", "85"));
RATE_WEIGHT_LIMIT = Double.parseDouble(rateSettings.getProperty("RateWeightLimit", "1"));
RATE_WEIGHT_LIMIT_PET = Double.parseDouble(rateSettings.getProperty("RateWeightLimitforPet", "1"));
RATE_SHOP_SELLING_PRICE = Double.parseDouble(rateSettings.getProperty("RateShopSellingPrice", "1.0"));
RATE_SHOP_PURCHASING_PRICE = Double.parseDouble(rateSettings.getProperty("RateShopPurchasingPrice", "1.0"));
CREATE_CHANCE_DIARY = Integer.parseInt(rateSettings.getProperty("CreateChanceDiary", "33"));
CREATE_CHANCE_RECOLLECTION = Integer.parseInt(rateSettings.getProperty("CreateChanceRecollection", "90"));
CREATE_CHANCE_MYSTERIOUS = Integer.parseInt(rateSettings.getProperty("CreateChanceMysterious", "90"));
CREATE_CHANCE_PROCESSING = Integer.parseInt(rateSettings.getProperty("CreateChanceProcessing", "90"));
CREATE_CHANCE_PROCESSING_DIAMOND = Integer
.parseInt(rateSettings.getProperty("CreateChanceProcessingDiamond", "90"));
CREATE_CHANCE_DANTES = Integer.parseInt(rateSettings.getProperty("CreateChanceDantes", "90"));
CREATE_CHANCE_ANCIENT_AMULET = Integer
.parseInt(rateSettings.getProperty("CreateChanceAncientAmulet", "90"));
CREATE_CHANCE_HISTORY_BOOK = Integer.parseInt(rateSettings.getProperty("CreateChanceHistoryBook", "50"));
FEATHER_NUM = Integer.parseInt(rateSettings.getProperty("FeatherNum", "6"));
FEATHER_NUM1 = Integer.parseInt(rateSettings.getProperty("FeatherNum1", "2"));
FEATHER_NUM2 = Integer.parseInt(rateSettings.getProperty("FeatherNum2", "3"));
FEATHER_NUM3 = Integer.parseInt(rateSettings.getProperty("FeatherNum3", "12"));
RATE_7_DMG_RATE = Double.parseDouble(rateSettings.getProperty("Rate_7_Dmg_Rate", "1.5"));
RATE_8_DMG_RATE = Double.parseDouble(rateSettings.getProperty("Rate_8_Dmg_Rate", "1.5"));
RATE_9_DMG_RATE = Double.parseDouble(rateSettings.getProperty("Rate_9_Dmg_Rate", "2.0"));
RATE_10_DMG_RATE = Double.parseDouble(rateSettings.getProperty("Rate_10_Dmg_Rate", "2.0"));
RATE_11_DMG_RATE = Double.parseDouble(rateSettings.getProperty("Rate_11_Dmg_Rate", "2.0"));
RATE_12_DMG_RATE = Double.parseDouble(rateSettings.getProperty("Rate_12_Dmg_Rate", "2.0"));
RATE_13_DMG_RATE = Double.parseDouble(rateSettings.getProperty("Rate_13_Dmg_Rate", "2.0"));
RATE_14_DMG_RATE = Double.parseDouble(rateSettings.getProperty("Rate_14_Dmg_Rate", "2.0"));
RATE_15_DMG_RATE = Double.parseDouble(rateSettings.getProperty("Rate_15_Dmg_Rate", "2.0"));
RATE_16_DMG_RATE = Double.parseDouble(rateSettings.getProperty("Rate_16_Dmg_Rate", "2.5"));
RATE_17_DMG_RATE = Double.parseDouble(rateSettings.getProperty("Rate_17_Dmg_Rate", "2.5"));
RATE_18_DMG_RATE = Double.parseDouble(rateSettings.getProperty("Rate_18_Dmg_Rate", "2.5"));
RATE_7_DMG_PER = Integer.parseInt(rateSettings.getProperty("Rate_7_Dmg_Per", "5"));
RATE_8_DMG_PER = Integer.parseInt(rateSettings.getProperty("Rate_8_Dmg_Per", "10"));
RATE_9_DMG_PER = Integer.parseInt(rateSettings.getProperty("Rate_9_Dmg_Per", "20"));
RATE_10_DMG_PER = Integer.parseInt(rateSettings.getProperty("Rate_10_Dmg_Per", "30"));
RATE_11_DMG_PER = Integer.parseInt(rateSettings.getProperty("Rate_11_Dmg_Per", "40"));
RATE_12_DMG_PER = Integer.parseInt(rateSettings.getProperty("Rate_12_Dmg_Per", "50"));
RATE_13_DMG_PER = Integer.parseInt(rateSettings.getProperty("Rate_13_Dmg_Per", "60"));
RATE_14_DMG_PER = Integer.parseInt(rateSettings.getProperty("Rate_14_Dmg_Per", "70"));
RATE_15_DMG_PER = Integer.parseInt(rateSettings.getProperty("Rate_15_Dmg_Per", "80"));
RATE_16_DMG_PER = Integer.parseInt(rateSettings.getProperty("Rate_16_Dmg_Per", "90"));
RATE_17_DMG_PER = Integer.parseInt(rateSettings.getProperty("Rate_17_Dmg_Per", "90"));
RATE_18_DMG_PER = Integer.parseInt(rateSettings.getProperty("Rate_18_Dmg_Per", "100"));
DISCHARGE1 = Integer.parseInt(rateSettings.getProperty("Discharge1", "1"));
DISCHARGE2 = Integer.parseInt(rateSettings.getProperty("Discharge2", "2"));
DISCHARGE3 = Integer.parseInt(rateSettings.getProperty("Discharge3", "3"));
DISCHARGE4 = Integer.parseInt(rateSettings.getProperty("Discharge4", "4"));
DISCHARGE5 = Integer.parseInt(rateSettings.getProperty("Discharge5", "5"));
DISCHARGE6 = Integer.parseInt(rateSettings.getProperty("Discharge6", "6"));
DISCHARGE7 = Integer.parseInt(rateSettings.getProperty("Discharge7", "7"));
// 地獄
HELL_TIME = Integer.parseInt(rateSettings.getProperty("HellTime", "6"));
HELL_LEVEL = Integer.parseInt(rateSettings.getProperty("HellLevel", "70"));
TAM_COUNT = Integer.parseInt(rateSettings.getProperty("TamNum", "6"));
TAM_CLAN_COUNT = Integer.parseInt(rateSettings.getProperty("TamNum1", "6"));
TAM_EX_COUNT = Integer.parseInt(rateSettings.getProperty("TamNum2", "6"));
TAM_EX2_COUNT = Integer.parseInt(rateSettings.getProperty("TamNum3", "6"));
SOCKS_OPERATION = Boolean.parseBoolean(rateSettings.getProperty("Eventof", "false"));
EVENT_A_OPERATION = Boolean.parseBoolean(rateSettings.getProperty("BugRace", "false"));
EVENT_TIME = Integer.parseInt(rateSettings.getProperty("EventTime", "1"));
EVENT_NUMBER = Integer.parseInt(rateSettings.getProperty("EventNumber", "1"));
EVENT_ITEM = Integer.parseInt(rateSettings.getProperty("EventItem", "1"));
BATTLE_ZONE_ENTRY_LEVEL = Integer.parseInt(rateSettings.getProperty("BattleLevel", "55"));
BATTLE_ZONE_OPERATION = Boolean.parseBoolean(rateSettings.getProperty("BattleZone", "true"));
DEMON_KING_OPERATION = Boolean.parseBoolean(rateSettings.getProperty("DevilZone", "true"));
BOSS_SPAWN_OPERATION = Boolean.parseBoolean(rateSettings.getProperty("BossZone", "true"));
DEMON_KING_TIME = Integer.parseInt(rateSettings.getProperty("DevilTime", "3"));
DEMON_KING_ENTRY_LEVEL = Integer.parseInt(rateSettings.getProperty("DevilLevel", "55"));
TI_DUNGEON_FEATHER = Boolean.parseBoolean(rateSettings.getProperty("TIダンジョン羽", "true"));
GLUDIO_DUNGEON_FEATHER = Boolean.parseBoolean(rateSettings.getProperty("メインランドのダンジョン羽", "true"));
SKT_DUNGEON_FEATHER = Boolean.parseBoolean(rateSettings.getProperty("修練ケイブ羽", "true"));
FI_FEATHER = Boolean.parseBoolean(rateSettings.getProperty("忘れられた島羽", "true"));
BATTLE_ZONE_ITEM = rateSettings.getProperty("BattleItem", "");
BATTLE_ZONE_ITEM_COUNT = rateSettings.getProperty("BattleCount", "");
PIC_BOOK_1_ITEM = rateSettings.getProperty("Dogamone", "");
PIC_BOOK_1_ITEM_COUNT = rateSettings.getProperty("DogamoneCount", "");
PIC_BOOK_2_ITEM = rateSettings.getProperty("Dogamto", "");
PIC_BOOK_2_ITEM_COUNT = rateSettings.getProperty("DogamtoCount", "");
PIC_BOOK_3_ITEM = rateSettings.getProperty("Dogamthr", "");
PIC_BOOK_3_ITEM_COUNT = rateSettings.getProperty("DogamthrCount", "");
EVENTITEM_ITEMID = rateSettings.getProperty("Eventitemid", "");
EVENTITEM_NUMBER = rateSettings.getProperty("Eventitemcount", "");
RAID_TIME = Integer.parseInt(rateSettings.getProperty("Raidtime", "1"));
} catch (Exception e) {
_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
throw new Error("Failed to Load " + RATES_CONFIG_FILE + " File.");
}
/** altsettings.properties **/
try {
Properties altSettings = new Properties();
InputStream is = new FileInputStream(new File(ALT_SETTINGS_FILE));
altSettings.load(is);
is.close();
GLOBAL_CHAT_LEVEL = Short.parseShort(altSettings.getProperty("GlobalChatLevel", "30"));
WHISPER_CHAT_LEVEL = Short.parseShort(altSettings.getProperty("WhisperChatLevel", "7"));
AUTO_LOOT = Byte.parseByte(altSettings.getProperty("AutoLoot", "2"));
LOOTING_RANGE = Integer.parseInt(altSettings.getProperty("LootingRange", "3"));
CLAN_COUNT = Integer.parseInt(altSettings.getProperty("Clancount", "5"));
ALT_NONPVP = Boolean.parseBoolean(altSettings.getProperty("NonPvP", "true"));
ALT_ATKMSG = Boolean.parseBoolean(altSettings.getProperty("AttackMessageOn", "true"));
CHANGE_TITLE_BY_ONESELF = Boolean.parseBoolean(altSettings.getProperty("ChangeTitleByOneself", "false"));
MAX_CLAN_MEMBER = Integer.parseInt(altSettings.getProperty("MaxClanMember", "0"));
CLAN_ALLIANCE = Boolean.parseBoolean(altSettings.getProperty("ClanAlliance", "true"));
MAX_PT = Integer.parseInt(altSettings.getProperty("MaxPT", "8"));
MAX_CHAT_PT = Integer.parseInt(altSettings.getProperty("MaxChatPT", "8"));
SIM_WAR_PENALTY = Boolean.parseBoolean(altSettings.getProperty("SimWarPenalty", "true"));
GET_BACK = Boolean.parseBoolean(altSettings.getProperty("GetBack", "false"));
ALT_ITEM_DELETION_TYPE = altSettings.getProperty("ItemDeletionType", "auto");
ALT_ITEM_DELETION_TIME = Integer.parseInt(altSettings.getProperty("ItemDeletionTime", "10"));
ALT_ITEM_DELETION_RANGE = Integer.parseInt(altSettings.getProperty("ItemDeletionRange", "5"));
ALT_GMSHOP = Boolean.parseBoolean(altSettings.getProperty("GMshop", "false"));
ALT_GMSHOP_MIN_ID = Integer.parseInt(altSettings.getProperty("GMshopMinID", "0xffffffff"));
ALT_GMSHOP_MAX_ID = Integer.parseInt(altSettings.getProperty("GMshopMaxID", "0xffffffff"));
ALT_BASETOWN = Boolean.parseBoolean(altSettings.getProperty("BaseTown", "false"));
ALT_BASETOWN_MIN_ID = Integer.parseInt(altSettings.getProperty("BaseTownMinID", "0xffffffff"));
ALT_BASETOWN_MAX_ID = Integer.parseInt(altSettings.getProperty("BaseTownMaxID", "0xffffffff"));
ALT_HALLOWEENIVENT = Boolean.parseBoolean(altSettings.getProperty("HalloweenIvent", "true"));
WHOIS_CONTER = Integer.parseInt(altSettings.getProperty("WhoisConter", "0")); //
/** [幻想イベント本サーバー化] **/
ALT_FANTASYEVENT = Boolean.parseBoolean(altSettings.getProperty("FantasyEvent", "true"));
/** [幻想イベント本サーバー化] **/
ALT_JPPRIVILEGED = Boolean.parseBoolean(altSettings.getProperty("JpPrivileged", "false"));
ALT_WHO_COMMAND = Boolean.parseBoolean(altSettings.getProperty("WhoCommand", "false"));
ALT_REVIVAL_POTION = Boolean.parseBoolean(altSettings.getProperty("RevivalPotion", "false"));
ALT_BEGINNER_BONUS = Boolean.parseBoolean(altSettings.getProperty("BeginnerEvent", "false"));
ALT_RABBITEVENT = Boolean.parseBoolean(altSettings.getProperty("RabbitEvent", "false"));
ALT_FISHEVENT = Boolean.parseBoolean(altSettings.getProperty("FishEvent", "true"));
ALT_DROPLEVELLIMIT = Integer.parseInt(altSettings.getProperty("DropLevelLimit", "90"));
DVC_ENTRY_LEVEL = Integer.parseInt(altSettings.getProperty("dvdgate1", "75"));
DVC_LIMIT_LEVEL = Integer.parseInt(altSettings.getProperty("dvdgate2", "80"));
HC_ENTRY_LEVEL = Integer.parseInt(altSettings.getProperty("dvdgate3", "75"));
HC_LIMIT_LEVEL = Integer.parseInt(altSettings.getProperty("dvdgate4", "80"));
STORE_USAGE_LEVEL = Integer.parseInt(altSettings.getProperty("ShopLevel", "99"));
TIC_ENTRY_LEVEL = Integer.parseInt(altSettings.getProperty("dvdgate5", "55"));
TIC_LIMIT_LEVEL = Integer.parseInt(altSettings.getProperty("dvdgate6", "70"));
SKTC_ENTRY_LEVEL = Integer.parseInt(altSettings.getProperty("dvdgate7", "70"));
SKTC_LIMIT_LEVEL = Integer.parseInt(altSettings.getProperty("dvdgate8", "70"));
DISCARDED_LAND_ENTRY_LEVEL = Integer.parseInt(altSettings.getProperty("dvdgate9", "70"));
ANCIENT_WEAPON = Integer.parseInt(altSettings.getProperty("PopWeapon", "100"));
ANCIENT_ARMOR = Integer.parseInt(altSettings.getProperty("PopArmor", "100"));
AUTO_REMOVELEVEL = Integer.parseInt(altSettings.getProperty("AutoRemoveLevel", "75"));
BUFFLEVEL = Integer.parseInt(altSettings.getProperty("BuffLevel", "75"));
TSUTSUKUGEN = Integer.parseInt(altSettings.getProperty("BuffLevel1", "79"));
NORMAL_PROTECTION = Integer.parseInt(altSettings.getProperty("TopGrace", "60"));
LASTAVARD_ENTRY_LEVEL = Integer.parseInt(altSettings.getProperty("LarvaLevel", "70"));
WIZARD_MAGIC_DAMAGE = Double.parseDouble(altSettings.getProperty("Wizdmg", "1.0"));
WIZARD_MONSTER_DAMAGE = Double.parseDouble(altSettings.getProperty("Wizdmg1", "1.0"));
NEW_CLAN_PROTECTION_LEVEL = Integer.parseInt(altSettings.getProperty("NewClanLevel", "60"));
NEW_CLAN = Integer.parseInt(altSettings.getProperty("NewClanid", "1"));
NEW_CLAN_PROTECTION_PROCESS = Boolean.parseBoolean(altSettings.getProperty("NewClanPvP", "true"));
WEAPON_ENCHANT = Integer.parseInt(altSettings.getProperty("LimitWeapon", "13")); // 一般武器
WEAPON_PREMIUM_ENCHANT = Integer.parseInt(altSettings.getProperty("LimitWeapon2", "5")); // 特殊武器
ARMOR_ENCHANT = Integer.parseInt(altSettings.getProperty("LimitArmor", "11")); // 一般鎧
ARMOR_PREMIUM_ENCHANT = Integer.parseInt(altSettings.getProperty("LimitArmor2", "7")); // 特殊アーマー
ROOMTIS = Integer.parseInt(altSettings.getProperty("RoomT", "8"));
SNAPPER = Integer.parseInt(altSettings.getProperty("Snapper", "8"));
ACCESSORIES = Integer.parseInt(altSettings.getProperty("Accessory", "9"));
CRAFTSMAN_WEAPON_SCROLL = Integer.parseInt(altSettings.getProperty("職人武器強化スクロール", "10"));
BLESS_SCROLL = Integer.parseInt(altSettings.getProperty("祝福書", "15"));
ORIM_SCROLL = Integer.parseInt(altSettings.getProperty("クリップボード書", "70"));
String strWar;
strWar = altSettings.getProperty("WarTime", "1h");
if (strWar.indexOf("d") >= 0) {
ALT_WAR_TIME_UNIT = Calendar.DATE;
strWar = strWar.replace("d", "");
} else if (strWar.indexOf("h") >= 0) {
ALT_WAR_TIME_UNIT = Calendar.HOUR_OF_DAY;
strWar = strWar.replace("h", "");
} else if (strWar.indexOf("m") >= 0) {
ALT_WAR_TIME_UNIT = Calendar.MINUTE;
strWar = strWar.replace("m", "");
}
ALT_WAR_TIME = Integer.parseInt(strWar);
strWar = altSettings.getProperty("WarInterval", "2d");
if (strWar.indexOf("d") >= 0) {
ALT_WAR_INTERVAL_UNIT = Calendar.DATE;
strWar = strWar.replace("d", "");
} else if (strWar.indexOf("h") >= 0) {
ALT_WAR_INTERVAL_UNIT = Calendar.HOUR_OF_DAY;
strWar = strWar.replace("h", "");
} else if (strWar.indexOf("m") >= 0) {
ALT_WAR_INTERVAL_UNIT = Calendar.MINUTE;
strWar = strWar.replace("m", "");
}
ALT_WAR_INTERVAL = Integer.parseInt(strWar);
SPAWN_HOME_POINT = Boolean.parseBoolean(altSettings.getProperty("SpawnHomePoint", "true"));
SPAWN_HOME_POINT_COUNT = Integer.parseInt(altSettings.getProperty("SpawnHomePointCount", "2"));
SPAWN_HOME_POINT_DELAY = Integer.parseInt(altSettings.getProperty("SpawnHomePointDelay", "100"));
SPAWN_HOME_POINT_RANGE = Integer.parseInt(altSettings.getProperty("SpawnHomePointRange", "8"));
INIT_BOSS_SPAWN = Boolean.parseBoolean(altSettings.getProperty("InitBossSpawn", "true"));
ELEMENTAL_STONE_AMOUNT = Integer.parseInt(altSettings.getProperty("ElementalStoneAmount", "300"));
HOUSE_TAX_INTERVAL = Integer.parseInt(altSettings.getProperty("HouseTaxInterval", "10"));
MAX_DOLL_COUNT = Integer.parseInt(altSettings.getProperty("MaxDollCount", "1"));
RETURN_TO_NATURE = Boolean.parseBoolean(altSettings.getProperty("ReturnToNature", "false"));
MAX_NPC_ITEM = Integer.parseInt(altSettings.getProperty("MaxNpcItem", "8"));
MAX_PERSONAL_WAREHOUSE_ITEM = Integer.parseInt(altSettings.getProperty("MaxPersonalWarehouseItem", "100"));
MAX_CLAN_WAREHOUSE_ITEM = Integer.parseInt(altSettings.getProperty("MaxClanWarehouseItem", "200"));
DELETE_CHARACTER_AFTER_7DAYS = Boolean
.parseBoolean(altSettings.getProperty("DeleteCharacterAfter7Days", "True"));
GMCODE = Integer.parseInt(altSettings.getProperty("GMCODE", "9999"));
EXP_PAYMENT_TEAM = Integer.parseInt(altSettings.getProperty("Expreturn", "75"));
DECLARATION_LEVEL = Integer.parseInt(altSettings.getProperty("WarLevel", "60"));
CLAN_CONNECT_COUNT = Integer.parseInt(altSettings.getProperty("WarPlayer", "60"));
NEW_PLAYER = Integer.parseInt(altSettings.getProperty("NewPlayer", "0"));
NOTIS_TIME = Integer.parseInt(altSettings.getProperty("NotisTime", "10"));
SPAWN_ROBOT = Boolean.parseBoolean(altSettings.getProperty("SpawnRobot", "false"));
} catch (Exception e) {
_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
throw new Error("Failed to Load " + ALT_SETTINGS_FILE + " File.");
}
/** charsettings.properties **/
try {
Properties charSettings = new Properties();
InputStream is = new FileInputStream(new File(CHAR_SETTINGS_CONFIG_FILE));
charSettings.load(is);
is.close();
PRINCE_MAX_HP = Integer.parseInt(charSettings.getProperty("PrinceMaxHP", "1000"));
PRINCE_MAX_MP = Integer.parseInt(charSettings.getProperty("PrinceMaxMP", "800"));
KNIGHT_MAX_HP = Integer.parseInt(charSettings.getProperty("KnightMaxHP", "1400"));
KNIGHT_MAX_MP = Integer.parseInt(charSettings.getProperty("KnightMaxMP", "600"));
ELF_MAX_HP = Integer.parseInt(charSettings.getProperty("ElfMaxHP", "1000"));
ELF_MAX_MP = Integer.parseInt(charSettings.getProperty("ElfMaxMP", "900"));
WIZARD_MAX_HP = Integer.parseInt(charSettings.getProperty("WizardMaxHP", "800"));
WIZARD_MAX_MP = Integer.parseInt(charSettings.getProperty("WizardMaxMP", "1200"));
DARKELF_MAX_HP = Integer.parseInt(charSettings.getProperty("DarkelfMaxHP", "1000"));
DARKELF_MAX_MP = Integer.parseInt(charSettings.getProperty("DarkelfMaxMP", "900"));
DRAGONKNIGHT_MAX_HP = Integer.parseInt(charSettings.getProperty("DragonknightMaxHP", "1000"));
DRAGONKNIGHT_MAX_MP = Integer.parseInt(charSettings.getProperty("DragonknightMaxMP", "900"));
BLACKWIZARD_MAX_HP = Integer.parseInt(charSettings.getProperty("BlackwizardMaxHP", "900"));
BLACKWIZARD_MAX_MP = Integer.parseInt(charSettings.getProperty("BlackwizardMaxMP", "1100"));
WARRIOR_MAX_HP = Integer.parseInt(charSettings.getProperty("WarriorMaxHP", "1400"));
WARRIOR_MAX_MP = Integer.parseInt(charSettings.getProperty("WarriorMaxMP", "600"));
LIMITLEVEL = Integer.parseInt(charSettings.getProperty("LimitLevel", "99"));
PRINCE_ADD_DAMAGEPC = Integer.parseInt(charSettings.getProperty("PrinceAddDamagePc", "0"));
KNIGHT_ADD_DAMAGEPC = Integer.parseInt(charSettings.getProperty("KnightAddDamagePc", "0"));
ELF_ADD_DAMAGEPC = Integer.parseInt(charSettings.getProperty("ElfAddDamagePc", "0"));
WIZARD_ADD_DAMAGEPC = Integer.parseInt(charSettings.getProperty("WizardAddDamagePc", "0"));
DARKELF_ADD_DAMAGEPC = Integer.parseInt(charSettings.getProperty("DarkelfAddDamagePc", "0"));
DRAGONKNIGHT_ADD_DAMAGEPC = Integer.parseInt(charSettings.getProperty("DragonknightAddDamagePc", "0"));
BLACKWIZARD_ADD_DAMAGEPC = Integer.parseInt(charSettings.getProperty("BlackwizardAddDamagePc", "0"));
WARRIOR_ADD_DAMAGEPC = Integer.parseInt(charSettings.getProperty("WarriorAddDamagePc", "0"));
LV50_EXP = Integer.parseInt(charSettings.getProperty("Lv50Exp", "1"));
LV51_EXP = Integer.parseInt(charSettings.getProperty("Lv51Exp", "1"));
LV52_EXP = Integer.parseInt(charSettings.getProperty("Lv52Exp", "1"));
LV53_EXP = Integer.parseInt(charSettings.getProperty("Lv53Exp", "1"));
LV54_EXP = Integer.parseInt(charSettings.getProperty("Lv54Exp", "1"));
LV55_EXP = Integer.parseInt(charSettings.getProperty("Lv55Exp", "1"));
LV56_EXP = Integer.parseInt(charSettings.getProperty("Lv56Exp", "1"));
LV57_EXP = Integer.parseInt(charSettings.getProperty("Lv57Exp", "1"));
LV58_EXP = Integer.parseInt(charSettings.getProperty("Lv58Exp", "1"));
LV59_EXP = Integer.parseInt(charSettings.getProperty("Lv59Exp", "1"));
LV60_EXP = Integer.parseInt(charSettings.getProperty("Lv60Exp", "1"));
LV61_EXP = Integer.parseInt(charSettings.getProperty("Lv61Exp", "1"));
LV62_EXP = Integer.parseInt(charSettings.getProperty("Lv62Exp", "1"));
LV63_EXP = Integer.parseInt(charSettings.getProperty("Lv63Exp", "1"));
LV64_EXP = Integer.parseInt(charSettings.getProperty("Lv64Exp", "1"));
LV65_EXP = Integer.parseInt(charSettings.getProperty("Lv65Exp", "2"));
LV66_EXP = Integer.parseInt(charSettings.getProperty("Lv66Exp", "2"));
LV67_EXP = Integer.parseInt(charSettings.getProperty("Lv67Exp", "2"));
LV68_EXP = Integer.parseInt(charSettings.getProperty("Lv68Exp", "2"));
LV69_EXP = Integer.parseInt(charSettings.getProperty("Lv69Exp", "2"));
LV70_EXP = Integer.parseInt(charSettings.getProperty("Lv70Exp", "4"));
LV71_EXP = Integer.parseInt(charSettings.getProperty("Lv71Exp", "4"));
LV72_EXP = Integer.parseInt(charSettings.getProperty("Lv72Exp", "4"));
LV73_EXP = Integer.parseInt(charSettings.getProperty("Lv73Exp", "4"));
LV74_EXP = Integer.parseInt(charSettings.getProperty("Lv74Exp", "4"));
LV75_EXP = Integer.parseInt(charSettings.getProperty("Lv75Exp", "8"));
LV76_EXP = Integer.parseInt(charSettings.getProperty("Lv76Exp", "8"));
LV77_EXP = Integer.parseInt(charSettings.getProperty("Lv77Exp", "8"));
LV78_EXP = Integer.parseInt(charSettings.getProperty("Lv78Exp", "8"));
LV79_EXP = Integer.parseInt(charSettings.getProperty("Lv79Exp", "16"));
LV80_EXP = Integer.parseInt(charSettings.getProperty("Lv80Exp", "32"));
LV81_EXP = Integer.parseInt(charSettings.getProperty("Lv81Exp", "64"));
LV82_EXP = Integer.parseInt(charSettings.getProperty("Lv82Exp", "128"));
LV83_EXP = Integer.parseInt(charSettings.getProperty("Lv83Exp", "256"));
LV84_EXP = Integer.parseInt(charSettings.getProperty("Lv84Exp", "512"));
LV85_EXP = Integer.parseInt(charSettings.getProperty("Lv85Exp", "1024"));
LV86_EXP = Integer.parseInt(charSettings.getProperty("Lv86Exp", "2048"));
LV87_EXP = Integer.parseInt(charSettings.getProperty("Lv87Exp", "4096"));
LV88_EXP = Integer.parseInt(charSettings.getProperty("Lv88Exp", "8192"));
LV89_EXP = Integer.parseInt(charSettings.getProperty("Lv89Exp", "16384"));
LV90_EXP = Integer.parseInt(charSettings.getProperty("Lv90Exp", "32768"));
LV91_EXP = Integer.parseInt(charSettings.getProperty("Lv91Exp", "65536"));
LV92_EXP = Integer.parseInt(charSettings.getProperty("Lv92Exp", "131072"));
LV93_EXP = Integer.parseInt(charSettings.getProperty("Lv93Exp", "262144"));
LV94_EXP = Integer.parseInt(charSettings.getProperty("Lv94Exp", "524288"));
LV95_EXP = Integer.parseInt(charSettings.getProperty("Lv95Exp", "1048576"));
LV96_EXP = Integer.parseInt(charSettings.getProperty("Lv96Exp", "2097152"));
LV97_EXP = Integer.parseInt(charSettings.getProperty("Lv97Exp", "4194304"));
LV98_EXP = Integer.parseInt(charSettings.getProperty("Lv98Exp", "8388608"));
LV99_EXP = Integer.parseInt(charSettings.getProperty("Lv99Exp", "16777216"));
} catch (Exception e) {
_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
throw new Error("Failed to Load " + CHAR_SETTINGS_CONFIG_FILE + " File.");
}
try {
Properties Eventlink = new Properties();
// InputStream is = new FileInputStream(new
// File(CHOLONG_SETTINGS_CONFIG_FILE));
FileReader is = new FileReader(new File(CHOLONG_SETTINGS_CONFIG_FILE));
Eventlink.load(is);
is.close();
/** イベントライン設定ファイル **/
CLAN_EXP_ONE = Integer.parseInt(Eventlink.getProperty("ClanExpOne", "200"));
CLAN_EXP_TWO = Integer.parseInt(Eventlink.getProperty("ClanExpTwo", "400"));
CLAN_EXP_THREE = Integer.parseInt(Eventlink.getProperty("ClanExpThree", "600"));
CLAN_EXP_FOUR = Integer.parseInt(Eventlink.getProperty("ClanExpFour", "900"));
CLAN_EXP_FIVE = Integer.parseInt(Eventlink.getProperty("ClanExpFive", "1200"));
CLAN_EXP_SIX = Integer.parseInt(Eventlink.getProperty("ClanExpSix", "1500"));
CLAN_EXP_SEVEN = Integer.parseInt(Eventlink.getProperty("ClanExpSeven", "2000"));
ADEN_SHOP_NPC = Integer.parseInt(Eventlink.getProperty("AdenShopNpc", "5"));
NINE_CLASS = Integer.parseInt(Eventlink.getProperty("NineClass", "100"));
EIGHT_CLASS = Integer.parseInt(Eventlink.getProperty("EightClass", "200"));
SEVEN_CLASS = Integer.parseInt(Eventlink.getProperty("SevenClass", "300"));
SIX_CLASS = Integer.parseInt(Eventlink.getProperty("SixClass", "400"));
FIVE_CLASS = Integer.parseInt(Eventlink.getProperty("FiveClass", "500"));
FOUR_CLASS = Integer.parseInt(Eventlink.getProperty("FourClass", "600"));
THREE_CLASS = Integer.parseInt(Eventlink.getProperty("ThreeClass", "700"));
TWO_CLASS = Integer.parseInt(Eventlink.getProperty("TwoClass", "800"));
ONE_CLASS = Integer.parseInt(Eventlink.getProperty("OneClass", "900"));
STAR_ONE = Integer.parseInt(Eventlink.getProperty("StarOne", "1000"));
STAR_TWO = Integer.parseInt(Eventlink.getProperty("StarTwo", "1100"));
STAR_THREE = Integer.parseInt(Eventlink.getProperty("StarThree", "1200"));
STAR_FOUR = Integer.parseInt(Eventlink.getProperty("StarFour", "1300"));
STAR_FIVE = Integer.parseInt(Eventlink.getProperty("StarFive", "1400"));
SUPREMECOMMANDER = Integer.parseInt(Eventlink.getProperty("SupremeCommander", "1400"));
; // 総司令官
COMMANDER = Integer.parseInt(Eventlink.getProperty("Commander", "1400")); // 司令官
IMPERATOR = Integer.parseInt(Eventlink.getProperty("Imperator", "1400")); // 大将軍
GENERAL = Integer.parseInt(Eventlink.getProperty("General", "1400")); // 将軍
STAR_FIVE_DAMAGE = Integer.parseInt(Eventlink.getProperty("StarFiveDamege", "40"));
SUPREMECOMMANDER_DAMAGE = Integer.parseInt(Eventlink.getProperty("SupremeCommanderDamege", "200"));
; // 総司令官
COMMANDER_DAMAGE = Integer.parseInt(Eventlink.getProperty("CommanderDamege", "160")); // 司令官
IMPERATOR_DAMAGE = Integer.parseInt(Eventlink.getProperty("ImperatorDamege", "120")); // 大将軍
GENERAL_DAMAGE = Integer.parseInt(Eventlink.getProperty("GeneralDamege", "80")); // 将軍
CLASS_START_LEVEL = Integer.parseInt(Eventlink.getProperty("ClassStartLevel", "99"));
ABYSS_POINT = Integer.parseInt(Eventlink.getProperty("AbyssPoint", "10"));
ROOMTIECE_CHANCE = Integer.parseInt(Eventlink.getProperty("RoomtieceChance", "9"));
Tam_Time = Integer.parseInt(Eventlink.getProperty("TamTime", "15"));
FEATHER_SHOP_NUM = Integer.parseInt(Eventlink.getProperty("FeatherShopNum", "100000"));
;
FEATHER_TIME = Integer.parseInt(Eventlink.getProperty("FeatherTime", "15"));
FISH_EXP = Integer.parseInt(Eventlink.getProperty("FishExp", "5000"));
FISH_TIME = Integer.parseInt(Eventlink.getProperty("FishTime", "80"));
FISH_COM = Boolean.parseBoolean(Eventlink.getProperty("FishCom", "false"));
ADEN_HUNTING_OPERATION = Boolean.parseBoolean(Eventlink.getProperty("AdenZone", "true"));
ADEN_HUNTING_TIME = Integer.parseInt(Eventlink.getProperty("AdenTime", "3"));
ADEN_HUNTING_ENTRY_LEVEL = Integer.parseInt(Eventlink.getProperty("AdenLevel", "55"));
ENCHANT_BUFF_TIME_VITALITY = Integer.parseInt(Eventlink.getProperty("強化バフ活力時間", "3"));
ENCHANT_BUFF_TIME_ATTACK = Integer.parseInt(Eventlink.getProperty("強化バフ攻撃時間", "3"));
ENCHANT_BUFF_TIME_DEFENCE = Integer.parseInt(Eventlink.getProperty("強化バフ防御時間", "3"));
ENCHANT_BUFF_TIME_MAGIC = Integer.parseInt(Eventlink.getProperty("強化バフ魔法の時間", "3"));
ENCHANT_BUFF_TIME_STUN = Integer.parseInt(Eventlink.getProperty("強化バフスタン時間", "3"));
ENCHANT_BUFF_TIME_HOLD = Integer.parseInt(Eventlink.getProperty("強化バフホールド時間", "3"));
ENCHANT_BUFF_TIME_STR = Integer.parseInt(Eventlink.getProperty("強化バフ力時間", "3"));
ENCHANT_BUFF_TIME_DEX = Integer.parseInt(Eventlink.getProperty("強化バフデックス時間", "3"));
ENCHANT_BUFF_TIME_INT = Integer.parseInt(Eventlink.getProperty("強化バフポイント時間", "3"));
STAGE_1 = Integer.parseInt(Eventlink.getProperty("WantedONE", "20000000"));
STAGE_2 = Integer.parseInt(Eventlink.getProperty("WantedToo", "40000000"));
STAGE_3 = Integer.parseInt(Eventlink.getProperty("WantedThree", "60000000"));
/** NPC物理ダメージ/魔法ダメージ修正 **/
npcdmg = Integer.parseInt(Eventlink.getProperty("npcdmg", "14"));
npcmagicdmg = Integer.parseInt(Eventlink.getProperty("npcmagicdmg", "10"));
/** イベント用 **/
mapid = Integer.parseInt(Eventlink.getProperty("mapid", "1"));
mapid1 = Integer.parseInt(Eventlink.getProperty("mapid1", "1"));
mapid2 = Integer.parseInt(Eventlink.getProperty("mapid2", "1"));
mapid3 = Integer.parseInt(Eventlink.getProperty("mapid3", "1"));
mapid4 = Integer.parseInt(Eventlink.getProperty("mapid4", "1"));
mapid5 = Integer.parseInt(Eventlink.getProperty("mapid5", "1"));
EXP = Integer.parseInt(Eventlink.getProperty("経験値", "1"));
EVENT_NUMBERS = Integer.parseInt(Eventlink.getProperty("イベント本数", "1"));
EVENT_ITEMS = Integer.parseInt(Eventlink.getProperty("イベントアイテム", "1"));
GLUDIN_DUNGEON_OPEN_CYCLE = Integer.parseInt(Eventlink.getProperty("OldLastavard", "4"));
CRAFT_TABLE_ONE = Integer.parseInt(Eventlink.getProperty("one", "0")); // 将軍;
CRAFT_TABLE_TWO = Integer.parseInt(Eventlink.getProperty("two", "0")); // 将軍;;
CRAFT_TABLE_THREE = Integer.parseInt(Eventlink.getProperty("three", "0")); // 将軍;;
CRAFT_TABLE_FOUR = Integer.parseInt(Eventlink.getProperty("four", "0")); // 将軍;;
CRAFT_TABLE_FIVE = Integer.parseInt(Eventlink.getProperty("five", "0")); // 将軍;;
CRAFT_TABLE_SIX = Integer.parseInt(Eventlink.getProperty("six", "0")); // 将軍;;
CRAFT_TABLE_SEVEN = Integer.parseInt(Eventlink.getProperty("seven", "0")); // 将軍;;
CRAFT_TABLE_EIGHT = Integer.parseInt(Eventlink.getProperty("eight", "0")); // 将軍;;
CRAFT_TABLE_NINE = Integer.parseInt(Eventlink.getProperty("nine", "0")); // 将軍;
CRAFT_TABLE_TEN = Integer.parseInt(Eventlink.getProperty("ten", "0")); // 将軍;;
CRAFT_TABLE = Integer.parseInt(Eventlink.getProperty("zero", "1")); // 将軍;;
ARNOLD_EVENT_TIME = Integer.parseInt(Eventlink.getProperty("AnoldeEventTime", "1")); // 将軍;;
ARNOLD_EVENTS = Boolean.parseBoolean(Eventlink.getProperty("アーノルドイベント", "false"));
SUPPLY_SCARECROW_TAM = Boolean.parseBoolean(Eventlink.getProperty("かかし乗車支給するかどうか", "false"));
PURE_WHITE_T = Boolean.parseBoolean(Eventlink.getProperty("TWhite", "false"));
SHOCK_STUN = Integer.parseInt(Eventlink.getProperty("ShockStun", "60"));
ARMOR_BREAK = Integer.parseInt(Eventlink.getProperty("ARMOR_BRAKE", "38"));
COUNTER_BARRIER = Integer.parseInt(Eventlink.getProperty("COUNTER_BARRIER", "20"));
DESPERADO = Integer.parseInt(Eventlink.getProperty("DESPERADO", "40"));
POWER_GRIP = Integer.parseInt(Eventlink.getProperty("POWERRIP", "40"));
ERASE_MAGIC = Integer.parseInt(Eventlink.getProperty("ERASE_MAGIC", "40"));
EARTH_BIND = Integer.parseInt(Eventlink.getProperty("EARTH_BIND", "40"));
WIND_SHACKLE = Integer.parseInt(Eventlink.getProperty("WIND_SHACKLE", "30"));
BONE_BREAK = Integer.parseInt(Eventlink.getProperty("BONE_BREAK", "40"));
DEATH_HEAL = Integer.parseInt(Eventlink.getProperty("DEATH_HEAL", "30"));
/** 新たに追加 **/
useritem = Integer.parseInt(Eventlink.getProperty("useritem", "1"));
usercount = Integer.parseInt(Eventlink.getProperty("usercount", "1"));
KIRINGKU = Integer.parseInt(Eventlink.getProperty("KingD", "12"));// キーリンク
DEATH_KNIGHT_HELLFIRE = Integer.parseInt(Eventlink.getProperty("dethshellpa", "1"));
DOLL_CHANCE = Integer.parseInt(Eventlink.getProperty("dollchance", "1"));
LIGHT_OF_ETERNAL_LIFE = Integer.parseInt(Eventlink.getProperty("yungsang", "1"));
LEAVES_OF_LIFE = Integer.parseInt(Eventlink.getProperty("Leafitem", "100"));
KNIGHT = Double.parseDouble(Eventlink.getProperty("KK", "1.5"));
DRAGON_KNIGHT = Double.parseDouble(Eventlink.getProperty("DK", "1.5"));
ELF = Double.parseDouble(Eventlink.getProperty("EF", "1.5"));
CROWN = Double.parseDouble(Eventlink.getProperty("KC", "1.5"));
WIZARD = Double.parseDouble(Eventlink.getProperty("MM", "1.5"));
DARK_ELF = Double.parseDouble(Eventlink.getProperty("DE", "1.5"));
ILLUSIONIST = Double.parseDouble(Eventlink.getProperty("MB", "1.5"));
WARRIOR = Double.parseDouble(Eventlink.getProperty("WR", "1.5"));
RECOVERY_EXP = Double.parseDouble(Eventlink.getProperty("経験値復旧", "0.049"));
EXP_POT_LIMIT = Boolean.parseBoolean(Eventlink.getProperty("ExpMax", "true"));
ALL_GIFT_OPERATION = Boolean.parseBoolean(Eventlink.getProperty("GiftItem", "true"));
Tower = Integer.parseInt(Eventlink.getProperty("タワー1段階補償", "40308"));
MTower = Integer.parseInt(Eventlink.getProperty("タワー2段階補償", "40308"));
LTower = Integer.parseInt(Eventlink.getProperty("タワー3段階の補償", "40308"));
TowerC = Integer.parseInt(Eventlink.getProperty("タワー1段階補償本数", "1"));
MTowerC = Integer.parseInt(Eventlink.getProperty("タワー2段階補償本数", "1"));
LTowerC = Integer.parseInt(Eventlink.getProperty("タワー3段階補償本数", "1"));
} catch (Exception e) {
_log.log(Level.SEVERE, "Config.でエラーが発生しました。", e);
throw new Error("Failed to Load " + CHOLONG_SETTINGS_CONFIG_FILE + " File.");
}
validate();
}
private static void validate() {
if (!IntRange.includes(Config.ALT_ITEM_DELETION_RANGE, 0, 5)) {
throw new IllegalStateException("ItemDeletionRangeの値が設定可能範囲外です。 ");
}
if (!IntRange.includes(Config.ALT_ITEM_DELETION_TIME, 1, 35791)) {
throw new IllegalStateException("ItemDeletionTimeの値が設定可能範囲外です。 ");
}
}
public static boolean setParameterValue(String pName, String pValue) {
/** server.properties **/
if (pName.equalsIgnoreCase("GameserverName")) {
GAME_SERVER_NAME = pValue;
} else if (pName.equalsIgnoreCase("GameserverPort")) {
GAME_SERVER_PORT = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Driver")) {
DB_DRIVER = pValue;
} else if (pName.equalsIgnoreCase("URL")) {
DB_URL = pValue;
} else if (pName.equalsIgnoreCase("Login")) {
DB_LOGIN = pValue;
} else if (pName.equalsIgnoreCase("Password")) {
DB_PASSWORD = pValue;
} else if (pName.equalsIgnoreCase("ClientLanguage")) {
CLIENT_LANGUAGE = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("TimeZone")) {
TIME_ZONE = pValue;
} else if (pName.equalsIgnoreCase("AutomaticKick")) {
AUTOMATIC_KICK = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("AutoCreateAccounts")) {
AUTO_CREATE_ACCOUNTS = Boolean.parseBoolean(pValue);
} else if (pName.equalsIgnoreCase("MaximumOnlineUsers")) {
MAX_ONLINE_USERS = Short.parseShort(pValue);
} else if (pName.equalsIgnoreCase("LoggingWeaponEnchant")) {
LOGGING_WEAPON_ENCHANT = Byte.parseByte(pValue);
} else if (pName.equalsIgnoreCase("LoggingArmorEnchant")) {
LOGGING_ARMOR_ENCHANT = Byte.parseByte(pValue);
} else if (pName.equalsIgnoreCase("CharacterConfigInServerSide")) {
CHARACTER_CONFIG_IN_SERVER_SIDE = Boolean.parseBoolean(pValue);
} else if (pName.equalsIgnoreCase("Allow2PC")) {
ALLOW_2PC = Boolean.parseBoolean(pValue);
} else if (pName.equalsIgnoreCase("LevelDownRange")) {
LEVEL_DOWN_RANGE = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("SendPacketBeforeTeleport")) {
SEND_PACKET_BEFORE_TELEPORT = Boolean.parseBoolean(pValue);
} else if (pName.equalsIgnoreCase("ShowClientPacket")) {
SHOW_CLIENT_PACKET = Boolean.parseBoolean(pValue);
} else if (pName.equalsIgnoreCase("RateXp")) {
RATE_XP = Double.parseDouble(pValue);
} else if (pName.equalsIgnoreCase("BloodBonus")) {
EX_EXP = Double.parseDouble(pValue);
} else if (pName.equalsIgnoreCase("RateLawful")) {
RATE_LAWFUL = Double.parseDouble(pValue);
} else if (pName.equalsIgnoreCase("RateKarma")) {
RATE_KARMA = Double.parseDouble(pValue);
} else if (pName.equalsIgnoreCase("RateDropAdena")) {
RATE_DROP_ADENA = Double.parseDouble(pValue);
} else if (pName.equalsIgnoreCase("RateDropItems")) {
RATE_DROP_ITEMS = Double.parseDouble(pValue);
} else if (pName.equalsIgnoreCase("RateDropRabbit")) {
RATE_DROP_RABBIT = Double.parseDouble(pValue);
} else if (pName.equalsIgnoreCase("EnchantChanceWeapon")) {
ENCHANT_CHANCE_WEAPON = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("EnchantChanceArmor")) {
ENCHANT_CHANCE_ARMOR = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("EnchantChanceAccessory")) {
ENCHANT_CHANCE_ACCESSORY = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("文章強化確率")) {
CREST_ENCHANT_CHANCE = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("ArnoldWeapon")) {
ARNOLD_WEAPON_CHANCE = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("FreeLevel")) {
FG_ISVAL = Integer.parseInt("pValue");
} else if (pName.equalsIgnoreCase("Weightrate")) {
RATE_WEIGHT_LIMIT = Byte.parseByte(pValue);
} else if (pName.equalsIgnoreCase("FeatherNum")) {
FEATHER_NUM = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("FeatherNum1")) {
FEATHER_NUM1 = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("FeatherNum2")) {
FEATHER_NUM2 = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("FeatherNum3")) {
FEATHER_NUM3 = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("HellTime")) { // 高ラス時間
HELL_TIME = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("HellLevel")) { // 高ラス入場レベル
HELL_LEVEL = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("TamNum")) {
TAM_COUNT = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("TamNum1")) {
TAM_CLAN_COUNT = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("TamNum2")) {
TAM_EX_COUNT = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("TamNum3")) {
TAM_EX2_COUNT = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Eventof")) {
SOCKS_OPERATION = Boolean.valueOf(pValue);
} else if (pName.equalsIgnoreCase("BugRace")) {
EVENT_A_OPERATION = Boolean.valueOf(pValue);
} else if (pName.equalsIgnoreCase("EventTime")) {
EVENT_TIME = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("EventNumber")) {
EVENT_NUMBER = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("EventItem")) {
EVENT_ITEM = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("BattleZone")) {
BATTLE_ZONE_OPERATION = Boolean.valueOf(pValue);
} else if (pName.equalsIgnoreCase("BattleLevel")) {
BATTLE_ZONE_ENTRY_LEVEL = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("DevilZone")) {
DEMON_KING_OPERATION = Boolean.valueOf(pValue);
} else if (pName.equalsIgnoreCase("BossZone")) {
BOSS_SPAWN_OPERATION = Boolean.valueOf(pValue);
} else if (pName.equalsIgnoreCase("DevilTime")) {
DEMON_KING_TIME = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("DevilLevel")) {
DEMON_KING_ENTRY_LEVEL = Integer.parseInt(pValue);
}
/** altsettings.properties **/
else if (pName.equalsIgnoreCase("GlobalChatLevel")) {
GLOBAL_CHAT_LEVEL = Short.parseShort(pValue);
} else if (pName.equalsIgnoreCase("WhisperChatLevel")) {
WHISPER_CHAT_LEVEL = Short.parseShort(pValue);
} else if (pName.equalsIgnoreCase("AutoLoot")) {
AUTO_LOOT = Byte.parseByte(pValue);
} else if (pName.equalsIgnoreCase("LOOTING_RANGE")) {
LOOTING_RANGE = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("CLAN_COUNT")) {
CLAN_COUNT = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("AltNonPvP")) {
ALT_NONPVP = Boolean.valueOf(pValue);
} else if (pName.equalsIgnoreCase("AttackMessageOn")) {
ALT_ATKMSG = Boolean.valueOf(pValue);
} else if (pName.equalsIgnoreCase("ChangeTitleByOneself")) {
CHANGE_TITLE_BY_ONESELF = Boolean.valueOf(pValue);
} else if (pName.equalsIgnoreCase("MaxClanMember")) {
MAX_CLAN_MEMBER = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("ClanAlliance")) {
CLAN_ALLIANCE = Boolean.valueOf(pValue);
} else if (pName.equalsIgnoreCase("MaxPT")) {
MAX_PT = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("MaxChatPT")) {
MAX_CHAT_PT = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("SimWarPenalty")) {
SIM_WAR_PENALTY = Boolean.valueOf(pValue);
} else if (pName.equalsIgnoreCase("GetBack")) {
GET_BACK = Boolean.valueOf(pValue);
} else if (pName.equalsIgnoreCase("AutomaticItemDeletionTime")) {
ALT_ITEM_DELETION_TIME = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("AutomaticItemDeletionRange")) {
ALT_ITEM_DELETION_RANGE = Byte.parseByte(pValue);
} else if (pName.equalsIgnoreCase("GMshop")) {
ALT_GMSHOP = Boolean.valueOf(pValue);
} else if (pName.equalsIgnoreCase("GMshopMinID")) {
ALT_GMSHOP_MIN_ID = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("GMshopMaxID")) {
ALT_GMSHOP_MAX_ID = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("BaseTown")) {
ALT_BASETOWN = Boolean.valueOf(pValue);
} else if (pName.equalsIgnoreCase("BaseTownMinID")) {
ALT_BASETOWN_MIN_ID = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("BaseTownMaxID")) {
ALT_BASETOWN_MAX_ID = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("HalloweenIvent")) {
ALT_HALLOWEENIVENT = Boolean.valueOf(pValue);
} else if (pName.equalsIgnoreCase("Whoiscount")) {
WHOIS_CONTER = Integer.valueOf(pValue); // 追加
/** 幻想イベント **/
} else if (pName.equalsIgnoreCase("FantasyEvent")) {
ALT_FANTASYEVENT = Boolean.valueOf(pValue);
/** 幻想イベント **/
} else if (pName.equalsIgnoreCase("RabbitEvent")) {
ALT_RABBITEVENT = Boolean.valueOf(pValue);
} else if (pName.equalsIgnoreCase("FishEvent")) {
ALT_FISHEVENT = Boolean.valueOf(pValue);
} else if (pName.equalsIgnoreCase("JpPrivileged")) {
ALT_JPPRIVILEGED = Boolean.valueOf(pValue);
} else if (pName.equalsIgnoreCase("HouseTaxInterval")) {
HOUSE_TAX_INTERVAL = Integer.valueOf(pValue);
} else if (pName.equalsIgnoreCase("MaxDollCount")) {
MAX_DOLL_COUNT = Integer.valueOf(pValue);
} else if (pName.equalsIgnoreCase("ReturnToNature")) {
RETURN_TO_NATURE = Boolean.valueOf(pValue);
} else if (pName.equalsIgnoreCase("MaxNpcItem")) {
MAX_NPC_ITEM = Integer.valueOf(pValue);
} else if (pName.equalsIgnoreCase("MaxPersonalWarehouseItem")) {
MAX_PERSONAL_WAREHOUSE_ITEM = Integer.valueOf(pValue);
} else if (pName.equalsIgnoreCase("MaxClanWarehouseItem")) {
MAX_CLAN_WAREHOUSE_ITEM = Integer.valueOf(pValue);
} else if (pName.equalsIgnoreCase("DeleteCharacterAfter7Days")) {
DELETE_CHARACTER_AFTER_7DAYS = Boolean.valueOf(pValue);
} else if (pName.equalsIgnoreCase("GMCODE")) {
GMCODE = Integer.valueOf(pValue);
} else if (pName.equalsIgnoreCase("AutoRemoveLevel")) {
AUTO_REMOVELEVEL = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("BuffLevel")) {
BUFFLEVEL = Integer.valueOf(pValue);
} else if (pName.equalsIgnoreCase("BuffLevel1")) {
TSUTSUKUGEN = Integer.valueOf(pValue);
} else if (pName.equalsIgnoreCase("TopGrace")) {
NORMAL_PROTECTION = Integer.valueOf(pValue);
} else if (pName.equalsIgnoreCase("LarvaLevel")) {
LASTAVARD_ENTRY_LEVEL = Integer.valueOf(pValue);
} else if (pName.equalsIgnoreCase("Wizdmg")) {
WIZARD_MAGIC_DAMAGE = Double.parseDouble(pValue);
} else if (pName.equalsIgnoreCase("Wizdmg1")) {
WIZARD_MONSTER_DAMAGE = Double.parseDouble(pValue);
} else if (pName.equalsIgnoreCase("NewClanLevel")) {
NEW_CLAN_PROTECTION_LEVEL = Integer.valueOf(pValue);
} else if (pName.equalsIgnoreCase("NewClanid")) {
NEW_CLAN = Integer.valueOf(pValue);
} else if (pName.equalsIgnoreCase("NewClanPvP")) {
NEW_CLAN_PROTECTION_PROCESS = Boolean.valueOf(pValue);
} else if (pName.equalsIgnoreCase("SpawnRobot")) {
SPAWN_ROBOT = Boolean.valueOf(pValue);
}
/** charsettings.properties **/
else if (pName.equalsIgnoreCase("PrinceMaxHP")) {
PRINCE_MAX_HP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("PrinceMaxMP")) {
PRINCE_MAX_MP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("KnightMaxHP")) {
KNIGHT_MAX_HP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("KnightMaxMP")) {
KNIGHT_MAX_MP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("ElfMaxHP")) {
ELF_MAX_HP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("ElfMaxMP")) {
ELF_MAX_MP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("WizardMaxHP")) {
WIZARD_MAX_HP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("WizardMaxMP")) {
WIZARD_MAX_MP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("DarkelfMaxHP")) {
DARKELF_MAX_HP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("DarkelfMaxMP")) {
DARKELF_MAX_MP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("DragonknightMaxHP")) {
DRAGONKNIGHT_MAX_HP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("DragonknightMaxMP")) {
DRAGONKNIGHT_MAX_MP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("BlackwizardMaxHP")) {
BLACKWIZARD_MAX_HP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("BlackwizardMaxMP")) {
BLACKWIZARD_MAX_MP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("LimitLevel")) {
LIMITLEVEL = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("PrinceAddDamagePc")) {
PRINCE_ADD_DAMAGEPC = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("KnightAddDamagePc")) {
KNIGHT_ADD_DAMAGEPC = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("ElfAddDamagePc")) {
ELF_ADD_DAMAGEPC = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("WizardAddDamagePc")) {
WIZARD_ADD_DAMAGEPC = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("DarkelfAddDamagePc")) {
DARKELF_ADD_DAMAGEPC = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("DragonknightAddDamagePc")) {
DRAGONKNIGHT_ADD_DAMAGEPC = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("BlackwizardAddDamagePc")) {
BLACKWIZARD_ADD_DAMAGEPC = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv50Exp")) {
LV50_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv51Exp")) {
LV51_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv52Exp")) {
LV52_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv53Exp")) {
LV53_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv54Exp")) {
LV54_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv55Exp")) {
LV55_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv56Exp")) {
LV56_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv57Exp")) {
LV57_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv58Exp")) {
LV58_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv59Exp")) {
LV59_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv60Exp")) {
LV60_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv61Exp")) {
LV61_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv62Exp")) {
LV62_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv63Exp")) {
LV63_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv64Exp")) {
LV64_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv65Exp")) {
LV65_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv66Exp")) {
LV66_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv67Exp")) {
LV67_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv68Exp")) {
LV68_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv69Exp")) {
LV69_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv70Exp")) {
LV70_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv71Exp")) {
LV71_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv72Exp")) {
LV72_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv73Exp")) {
LV73_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv74Exp")) {
LV74_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv75Exp")) {
LV75_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv76Exp")) {
LV76_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv77Exp")) {
LV77_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv78Exp")) {
LV78_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv79Exp")) {
LV79_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv80Exp")) {
LV80_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv81Exp")) {
LV81_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv82Exp")) {
LV82_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv83Exp")) {
LV83_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv84Exp")) {
LV84_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv85Exp")) {
LV85_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv86Exp")) {
LV86_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv87Exp")) {
LV87_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv88Exp")) {
LV88_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv89Exp")) {
LV89_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv90Exp")) {
LV90_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv91Exp")) {
LV91_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv92Exp")) {
LV92_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv93Exp")) {
LV93_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv94Exp")) {
LV94_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv95Exp")) {
LV95_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv96Exp")) {
LV96_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv97Exp")) {
LV97_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv98Exp")) {
LV98_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Lv99Exp")) {
LV99_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("UseShowAnnouncecycle")) {
Use_Show_Announcecycle = Boolean.valueOf(pValue);
} else if (pName.equalsIgnoreCase("ShowAnnouncecycleTime")) {
Show_Announcecycle_Time = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Raidtime")) {
RAID_TIME = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("タワー1段階補償")) {
Tower = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("タワー2段階補償")) {
MTower = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("タワー3段階の補償")) {
LTower = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("タワー1段階補償本数")) {
Tower = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("タワー1段階補償本数")) {
Tower = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("タワー1段階補償本数")) {
Tower = Integer.parseInt(pValue);
// Eventlink set file
} else if (pName.equalsIgnoreCase("AnoldeEventTime")) {
ARNOLD_EVENT_TIME = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("OldLastavard")) {
GLUDIN_DUNGEON_OPEN_CYCLE = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("one")) {
CRAFT_TABLE_ONE = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("two")) {
CRAFT_TABLE_TWO = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("three")) {
CRAFT_TABLE_THREE = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("four")) {
CRAFT_TABLE_FOUR = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("five")) {
CRAFT_TABLE_FIVE = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("six")) {
CRAFT_TABLE_SIX = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("seven")) {
CRAFT_TABLE_SEVEN = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("eight")) {
CRAFT_TABLE_EIGHT = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("nine")) {
CRAFT_TABLE_NINE = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("ten")) {
CRAFT_TABLE_TEN = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("zero")) {
CRAFT_TABLE = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("ClanExpOne")) {
CLAN_EXP_ONE = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("ClanExpTwo")) {
CLAN_EXP_TWO = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("ClanExpThree")) {
CLAN_EXP_THREE = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("ClanExpFour")) {
CLAN_EXP_FOUR = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("ClanExpFive")) {
CLAN_EXP_FIVE = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("ClanExpSix")) {
CLAN_EXP_SIX = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("ClanExpSeven")) {
CLAN_EXP_SEVEN = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("AdenShopNpc")) {
ADEN_SHOP_NPC = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("NineClass")) {
NINE_CLASS = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("EightClass")) {
EIGHT_CLASS = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("SevenClass")) {
SEVEN_CLASS = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("SixClass")) {
SIX_CLASS = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("FiveClass")) {
FIVE_CLASS = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("FourClass")) {
FOUR_CLASS = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("ThreeClass")) {
THREE_CLASS = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("TwoClass")) {
TWO_CLASS = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("OneClass")) {
ONE_CLASS = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("StarOne")) {
STAR_ONE = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("StarTwo")) {
STAR_TWO = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("StarThree")) {
STAR_THREE = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("StarFour")) {
STAR_FOUR = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("StarFive")) {
STAR_FIVE = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("General")) {
GENERAL = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Imperator")) {
IMPERATOR = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("Commander")) {
COMMANDER = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("SupremeCommander")) {
SUPREMECOMMANDER = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("StarFiveDamage")) {
STAR_FIVE_DAMAGE = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("GeneralDamage")) {
GENERAL_DAMAGE = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("ImperatorDamage")) {
IMPERATOR_DAMAGE = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("CommanderDamage")) {
COMMANDER_DAMAGE = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("SupremeCommanderDamage")) {
SUPREMECOMMANDER_DAMAGE = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("ClassStartLevel")) {
CLASS_START_LEVEL = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("AbyssPoint")) {
ABYSS_POINT = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("FeatherShopNum")) {
FEATHER_SHOP_NUM = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("RoomtieceChance")) {
ROOMTIECE_CHANCE = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("TamTime")) {
Tam_Time = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("FeatherTime")) {
FEATHER_TIME = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("FishExp")) {
FISH_EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("FishTime")) {
FISH_TIME = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("FishCom")) {
FISH_COM = Boolean.valueOf(pValue);
} else if (pName.equalsIgnoreCase("AdenZone")) {
ADEN_HUNTING_OPERATION = Boolean.valueOf(pValue);
} else if (pName.equalsIgnoreCase("AdenLevel")) {
ADEN_HUNTING_ENTRY_LEVEL = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("AdenTime")) {
ADEN_HUNTING_TIME = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("強化バフ活力時間")) {
ENCHANT_BUFF_TIME_VITALITY = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("強化バフ攻撃時間")) {
ENCHANT_BUFF_TIME_ATTACK = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("強化バフ防御時間")) {
ENCHANT_BUFF_TIME_DEFENCE = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("強化バフ魔法の時間")) {
ENCHANT_BUFF_TIME_MAGIC = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("強化バフスタン時間")) {
ENCHANT_BUFF_TIME_STUN = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("強化バフホールド時間")) {
ENCHANT_BUFF_TIME_HOLD = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("強化バフ力時間")) {
ENCHANT_BUFF_TIME_STR = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("強化バフデックス時間")) {
ENCHANT_BUFF_TIME_DEX = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("強化バフポイント時間")) {
ENCHANT_BUFF_TIME_INT = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("WantedONE")) {
STAGE_1 = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("WantedToo")) {
STAGE_2 = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("WantedThree")) {
STAGE_3 = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("npcdmg")) {
npcdmg = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("npcmagicdmg")) {
npcmagicdmg = Integer.parseInt(pValue);
/** イベント用 **/
} else if (pName.equalsIgnoreCase("mapid")) {
mapid = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("mapid1")) {
mapid1 = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("mapid2")) {
mapid2 = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("mapid3")) {
mapid3 = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("mapid4")) {
mapid4 = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("mapid5")) {
mapid5 = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("経験値")) {
EXP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("イベント本数")) {
EVENT_NUMBERS = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("イベントアイテム")) {
EVENT_ITEMS = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("useritem")) {
useritem = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("usercount")) {
usercount = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("ShockStun")) {
SHOCK_STUN = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("TWhite")) {
PURE_WHITE_T = Boolean.valueOf(pValue);
} else if (pName.equalsIgnoreCase("ARMOR_BRAKE")) {
ARMOR_BREAK = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("COUNTER_BARRIER")) {
COUNTER_BARRIER = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("DESPERADO")) {
DESPERADO = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("POWERRIP")) {
POWER_GRIP = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("ERASE_MAGIC")) {
ERASE_MAGIC = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("EARTH_BIND")) {
EARTH_BIND = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("WIND_SHACKLE")) {
WIND_SHACKLE = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("BONE_BREAK")) {
BONE_BREAK = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("DEATH_HEAL")) {
DEATH_HEAL = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("ExpMax")) {
EXP_POT_LIMIT = Boolean.valueOf(pValue);
} else if (pName.equalsIgnoreCase("GiftItem")) {
ALL_GIFT_OPERATION = Boolean.valueOf(pValue);
/** 新たに追加 **/
} else if (pName.equalsIgnoreCase("KingD")) {
KIRINGKU = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("KK")) {
KNIGHT = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("DK")) {
DRAGON_KNIGHT = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("EF")) {
ELF = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("KC")) {
CROWN = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("MM")) {
WIZARD = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("DE")) {
DARK_ELF = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("MB")) {
ILLUSIONIST = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("WR")) {
WARRIOR = Integer.parseInt(pValue);
} else if (pName.equalsIgnoreCase("経験値復旧")) {
RECOVERY_EXP = Integer.parseInt(pValue);
} else {
return false;
}
return true;
}
private Config() {
}
public final static int etc_arrow = 0;
public final static int etc_wand = 1;
public final static int etc_light = 2;
public final static int etc_gem = 3;
public final static int etc_potion = 6;
public final static int etc_firecracker = 5;
public final static int etc_food = 7;
public final static int etc_scroll = 8;
public final static int etc_questitem = 9;
public final static int etc_spellbook = 10;
public final static int etc_other = 12;
public final static int etc_material = 13;
public final static int etc_sting = 15;
public final static int etc_treasurebox = 16;
} | L1j-Kiyoshi/kys8.1 | src/l1j/server/Config.java |
64,962 | package shift.sextiarysector;
import java.util.ArrayList;
import cpw.mods.fml.common.registry.GameRegistry;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.Item.ToolMaterial;
import net.minecraft.item.ItemHoe;
import net.minecraft.item.ItemSpade;
import net.minecraft.item.ItemSword;
import shift.sextiarysector.api.SextiarySectorAPI;
import shift.sextiarysector.item.ItemBottle;
import shift.sextiarysector.item.ItemCalendar;
import shift.sextiarysector.item.ItemContactLenses;
import shift.sextiarysector.item.ItemCrop;
import shift.sextiarysector.item.ItemDrink;
import shift.sextiarysector.item.ItemFigureBox;
import shift.sextiarysector.item.ItemFoodCrop;
import shift.sextiarysector.item.ItemFoodDrink;
import shift.sextiarysector.item.ItemFullBottle;
import shift.sextiarysector.item.ItemGFContactLenses;
import shift.sextiarysector.item.ItemGearStorage;
import shift.sextiarysector.item.ItemGuiUnit;
import shift.sextiarysector.item.ItemKnife;
import shift.sextiarysector.item.ItemLavaBottle;
import shift.sextiarysector.item.ItemLeafBed;
import shift.sextiarysector.item.ItemMineboat;
import shift.sextiarysector.item.ItemMineboatTank;
import shift.sextiarysector.item.ItemOxygenTank;
import shift.sextiarysector.item.ItemProtectionRing;
import shift.sextiarysector.item.ItemQuiver;
import shift.sextiarysector.item.ItemRucksack;
import shift.sextiarysector.item.ItemSSArmor;
import shift.sextiarysector.item.ItemSSAxe;
import shift.sextiarysector.item.ItemSSPickaxe;
import shift.sextiarysector.item.ItemSSShears;
import shift.sextiarysector.item.ItemScoop;
import shift.sextiarysector.item.ItemSeasonStone;
import shift.sextiarysector.item.ItemSeed;
import shift.sextiarysector.item.ItemShiftHat;
import shift.sextiarysector.item.ItemShopMemory;
import shift.sextiarysector.item.ItemSimpleBucket;
import shift.sextiarysector.item.ItemSoap;
import shift.sextiarysector.item.ItemSoup;
import shift.sextiarysector.item.ItemSpanner;
import shift.sextiarysector.item.ItemSpray;
import shift.sextiarysector.item.ItemUnit;
import shift.sextiarysector.item.ItemWaterBottle;
import shift.sextiarysector.item.ItemWateringCan;
import shift.sextiarysector.module.ModuleToolMaterial;
public class SSItems {
//Gear
public static Item unit;
public static Item woodGear;
public static Item stoneGear;
public static Item steelGear;
public static Item ninjaGear;
public static Item orichalcumGear;
public static Item woodUnitGear;
public static Item stoneUnitGear;
public static Item steelUnitGear;
public static Item ninjaUnitGear;
public static Item orichalcumUnitGear;
public static Item woodGFStorage;
public static Item stoneGFStorage;
public static Item steelGFStorage;
public static Item ninjaGFStorage;
public static Item orichalcumGFStorage;
//hammer
public static Item hammer;
public static Item ironSpanner;
public static Item colorSpray;
public static Item calendar;
public static Item seasonStone;
//石鹸
public static Item soap;
//ベッド
public static Item leafBed;
//素材
public static Item leaf;
public static Item ash;
public static Item glaze;
public static Item kawara;
public static Item animalOil;
public static Item dustWaterLily;
public static Item stoneDust;
public static Item blueStoneDust;
public static Item yellowStoneDust;
public static Item coalDust;
public static Item ironDust;
public static Item goldDust;
public static Item diamondDust;
public static Item copperDust;
public static Item zincDust;
public static Item silverDust;
public static Item mithrilDust;
public static Item ironNugget;
public static Item copperNugget;
public static Item zincNugget;
public static Item silverNugget;
public static Item steelNugget;
public static Item ninjaNugget;
public static Item obsidianNugget;
public static Item steelIngot;
public static Item brassIngot;
public static Item blueStoneIngot;
public static Item yellowStoneIngot;
public static Item copperIngot;
public static Item zincIngot;
public static Item silverIngot;
public static Item mithrilIngot;
public static Item orichalcumGem;
public static Item ninjaIngot;
public static Item redGel;
public static Item blueGel;
public static Item yellowGel;
public static Item craftReactor;
public static Item energyReactor;
public static Item objectReactor;
//液体
public static Item emptyBottle;
public static Item waterBottle;
public static Item lavaBottle;
public static Item sapBottle;
public static Item steamBucket;
public static Item ironFluidBucket;
public static Item goldFluidBucket;
//魔法
public static Item magicDust;
//布
public static Item silkBobbin;
public static Item smallCloth;
public static Item silkCloth;
public static Item canvas;
public static Item dryingFlesh;
public static Item fleshBobbin;
public static Item stringMass;
public static Item strongString;
public static Item strongStringBobbin;
public static Item strongCloth;
public static Item strongCanvas;
//public static Item bottle;
public static Item figureBox;
//道具
public static Item woodScoop;
public static Item stoneScoop;
public static Item ironScoop;
public static Item goldScoop;
public static Item diamondScoop;
public static Item copperScoop;
public static Item brassScoop;
public static Item ninjaScoop;
//public static Item diamondScoop;
public static Item woodKnife;
public static Item stoneKnife;
public static Item ironKnife;
public static Item goldKnife;
public static Item diamondKnife;
public static Item copperKnife;
public static Item brassKnife;
public static Item ninjaKnife;
//道具 バニラ
// 銅
public static Item copperShovel;
public static Item copperPickaxe;
public static Item copperAxe;
public static Item copperSword;
public static Item copperHoe;
// 黄銅
public static Item brassShovel;
public static Item brassPickaxe;
public static Item brassAxe;
public static Item brassSword;
public static Item brassHoe;
// ニンジャ
public static Item ninjaShovel;
public static Item ninjaPickaxe;
public static Item ninjaAxe;
public static Item ninjaSword;
public static Item ninjaHoe;
//防具
// 銅
public static Item copperHelmet;
public static Item copperChestplate;
public static Item copperLeggings;
public static Item copperBoots;
// ニンジャ
public static Item ninjaHelmet;
public static Item ninjaChestplate;
public static Item ninjaLeggings;
public static Item ninjaBoots;
//その他
public static Item woodWateringCan;
public static Item brassShears;
//水産
public static Item mineboatChest;
public static Item mineboatTank;
public static Item laver;
//野菜
public static ArrayList<Item> farmlandCrops = new ArrayList<Item>();
public static ArrayList<Item> paddyCrops = new ArrayList<Item>();
public static ArrayList<Item> woodCrops = new ArrayList<Item>();
public static ItemSeed seeds;
//突然変異用のList(骨粉)
public static ArrayList<Item> mutationCrops = new ArrayList<Item>();
public static Item turnip;
public static Item cucumber;
public static Item ironTurnip;
public static Item onion;
public static Item tomato;
public static Item corn;
public static Item copperOnion;
public static Item goldenCorn;
public static Item eggplant;
public static Item sweetPotato;
public static Item greenPepper;
public static Item bluePotato;
public static Item radish;
public static Item rice;
public static Item shiitake;
//魚
public static Item squidSashimi;
//料理
public static Item whiteRice;
public static Item salt;
public static Item curryPowder;
public static Item laverRoasted;
public static Item chickenSmoked;
public static Item porkchopSmoked;
public static Item beefSmoked;
public static Item riceBall;
public static Item curryRice;
public static Item carrotSoup;
public static Item cornSoup;
public static Item eggSoup;
public static Item mushroomStew;
public static Item onionSoup;
public static Item enderSoup;
public static Item tomatoSoup;
public static Item chocolate;
//飲み物
//public static Item drinkingWaterSmallBottle;
public static Item drinkingWaterBottle;
public static Item takumiTeaBottle;
//装備
public static Item shiftHat;
public static Item rucksack;
public static Item quiver;
public static Item oxygenTank;
public static Item gfContactLenses;
public static Item waterContactLenses;
//unit
public static Item craftUnit;
public static Item attackUnit;
public static Item defenseUnit;
public static Item attackRustUnit;
public static Item defenseRustUnit;
public static Item jumpUnit;
public static Item dashUnit;
public static Item slowlyUnit;
public static Item pullingUnit;
public static Item multiSchottUnit;
public static Item bedMonsterUnit;
public static Item pickaxeUnit;
public static Item debugUnit;
//リング
public static Item ironRing;
//public static Item creeperRing;
public static Item mpRing;
public static Item xpRing;
//経済
public static ItemShopMemory creeperMemory;
public static ItemShopMemory skeletonMemory;
public static void initItems() {
unit = new Item().setUnlocalizedName("ss.unit").setTextureName("sextiarysector:machine/unit")
.setCreativeTab(SextiarySectorAPI.TabSSIndustry);
GameRegistry.registerItem(unit, "Unit");
woodGear = new Item().setUnlocalizedName("ss.wood_gear").setTextureName("sextiarysector:machine/wood_gear")
.setCreativeTab(SextiarySectorAPI.TabSSIndustry);
GameRegistry.registerItem(woodGear, "WoodGear");
stoneGear = new Item().setUnlocalizedName("ss.stone_gear").setTextureName("sextiarysector:machine/stone_gear")
.setCreativeTab(SextiarySectorAPI.TabSSIndustry);
GameRegistry.registerItem(stoneGear, "StoneGear");
steelGear = new Item().setUnlocalizedName("ss.steel_gear").setTextureName("sextiarysector:machine/steel_gear")
.setCreativeTab(SextiarySectorAPI.TabSSIndustry);
GameRegistry.registerItem(steelGear, "SteelGear");
ninjaGear = new Item().setUnlocalizedName("ss.ninja_gear").setTextureName("sextiarysector:machine/ninja_gear")
.setCreativeTab(SextiarySectorAPI.TabSSIndustry);
GameRegistry.registerItem(ninjaGear, "NinjaGear");
orichalcumGear = new Item().setUnlocalizedName("ss.orichalcum_gear")
.setTextureName("sextiarysector:machine/orichalcum_gear")
.setCreativeTab(SextiarySectorAPI.TabSSIndustry);
GameRegistry.registerItem(orichalcumGear, "OrichalcumGear");
woodUnitGear = new Item().setUnlocalizedName("ss.wood_unit_gear")
.setTextureName("sextiarysector:machine/wood_unit_gear")
.setCreativeTab(SextiarySectorAPI.TabSSIndustry);
GameRegistry.registerItem(woodUnitGear, "WoodUnitGear");
stoneUnitGear = new Item().setUnlocalizedName("ss.stone_unit_gear")
.setTextureName("sextiarysector:machine/stone_unit_gear")
.setCreativeTab(SextiarySectorAPI.TabSSIndustry);
GameRegistry.registerItem(stoneUnitGear, "StoneUnitGear");
steelUnitGear = new Item().setUnlocalizedName("ss.steel_unit_gear")
.setTextureName("sextiarysector:machine/steel_unit_gear")
.setCreativeTab(SextiarySectorAPI.TabSSIndustry);
GameRegistry.registerItem(steelUnitGear, "steelUnitGear");
ninjaUnitGear = new Item().setUnlocalizedName("ss.ninja_unit_gear")
.setTextureName("sextiarysector:machine/ninja_unit_gear")
.setCreativeTab(SextiarySectorAPI.TabSSIndustry);
GameRegistry.registerItem(ninjaUnitGear, "NinjaUnitGear");
orichalcumUnitGear = new Item().setUnlocalizedName("ss.orichalcum_unit_gear")
.setTextureName("sextiarysector:machine/orichalcum_unit_gear")
.setCreativeTab(SextiarySectorAPI.TabSSIndustry);
GameRegistry.registerItem(orichalcumUnitGear, "OrichalcumUnitGear");
woodGFStorage = new ItemGearStorage(1, 10000, 1).setUnlocalizedName("ss.wood_gf_storage")
.setTextureName("sextiarysector:gearforce/wood_gear_storage")
.setCreativeTab(SextiarySectorAPI.TabSSIndustry);
GameRegistry.registerItem(woodGFStorage, "WoodGFStorage");
stoneGFStorage = new ItemGearStorage(2, 10000, 2).setUnlocalizedName("ss.stone_gf_storage")
.setTextureName("sextiarysector:gearforce/stone_gear_storage")
.setCreativeTab(SextiarySectorAPI.TabSSIndustry);
GameRegistry.registerItem(stoneGFStorage, "StoneGFStorage");
steelGFStorage = new ItemGearStorage(3, 10000, 3).setUnlocalizedName("ss.steel_gf_storage")
.setTextureName("sextiarysector:gearforce/steel_gear_storage")
.setCreativeTab(SextiarySectorAPI.TabSSIndustry);
GameRegistry.registerItem(steelGFStorage, "SteelGFStorage");
ninjaGFStorage = new ItemGearStorage(4, 10000, 4).setUnlocalizedName("ss.ninja_gf_storage")
.setTextureName("sextiarysector:gearforce/ninja_gear_storage")
.setCreativeTab(SextiarySectorAPI.TabSSIndustry);
GameRegistry.registerItem(ninjaGFStorage, "NinjaGFStorage");
orichalcumGFStorage = new ItemGearStorage(5, 10000, 5).setUnlocalizedName("ss.orichalcum_gf_storage")
.setTextureName("sextiarysector:gearforce/orichalcum_gear_storage")
.setCreativeTab(SextiarySectorAPI.TabSSIndustry);
GameRegistry.registerItem(orichalcumGFStorage, "OrichalcumGFStorage");
//ハンマー
//hammer = new ItemHammer().setUnlocalizedName("ss.iron_spanner").setTextureName("sextiarysector:gearforce/iron_spanner").setCreativeTab(SextiarySectorAPI.TabSSIndustry);
ironSpanner = new ItemSpanner().setUnlocalizedName("ss.iron_spanner")
.setTextureName("sextiarysector:gearforce/iron_spanner")
.setCreativeTab(SextiarySectorAPI.TabSSIndustry);
GameRegistry.registerItem(ironSpanner, "IronSpanner");
hammer = ironSpanner;
colorSpray = new ItemSpray().setUnlocalizedName("ss.color_spray")
.setTextureName("sextiarysector:fluid/color_spray").setCreativeTab(SextiarySectorAPI.TabSSCore);
GameRegistry.registerItem(colorSpray, "ColorSpray");
calendar = new ItemCalendar().setUnlocalizedName("ss.calendar").setTextureName("sextiarysector:calendar")
.setCreativeTab(SextiarySectorAPI.TabSSCore);
GameRegistry.registerItem(calendar, "Calendar");
seasonStone = new ItemSeasonStone().setUnlocalizedName("ss.season_stone")
.setTextureName("sextiarysector:season_stone").setCreativeTab(SextiarySectorAPI.TabSSCore);
GameRegistry.registerItem(seasonStone, "SeasonStone");
//石鹸
soap = new ItemSoap().setUnlocalizedName("ss.soap").setTextureName("sextiarysector:soap/soap");
GameRegistry.registerItem(soap, "Soap");
leafBed = new ItemLeafBed().setUnlocalizedName("ss.leaf_bed").setTextureName("sextiarysector:leaf_bed")
.setCreativeTab(SextiarySectorAPI.TabSSCore);
GameRegistry.registerItem(leafBed, "ItemLeafBed");
//素材
leaf = new Item().setUnlocalizedName("ss.leaf").setTextureName("sextiarysector:leaf")
.setCreativeTab(SextiarySectorAPI.TabSSCore);
GameRegistry.registerItem(leaf, "Leaf");
ash = new Item().setUnlocalizedName("ss.ash").setTextureName("sextiarysector:dust/ash").setCreativeTab(SextiarySectorAPI.TabSSCore);
GameRegistry.registerItem(ash, "Ash");
glaze = new Item().setUnlocalizedName("ss.glaze").setTextureName("sextiarysector:gel/glaze").setCreativeTab(SextiarySectorAPI.TabSSCore);
GameRegistry.registerItem(glaze, "Glaze");
kawara = new Item().setUnlocalizedName("ss.kawara").setTextureName("sextiarysector:kawara")
.setCreativeTab(SextiarySectorAPI.TabSSCore);
GameRegistry.registerItem(kawara, "Kawara");
animalOil = new Item().setUnlocalizedName("ss.animal_oil").setTextureName("sextiarysector:animal_oil").setCreativeTab(SextiarySectorAPI.TabSSCooking);
GameRegistry.registerItem(animalOil, "AnimalOil");
dustWaterLily = new Item().setUnlocalizedName("ss.dust_waterlily")
.setTextureName("sextiarysector:dust/waterlily_dust").setCreativeTab(SextiarySectorAPI.TabSSCore);
GameRegistry.registerItem(dustWaterLily, "DustWaterLily");
stoneDust = new Item().setUnlocalizedName("ss.stone_dust").setTextureName("sextiarysector:dust/stone_dust")
.setCreativeTab(SextiarySectorAPI.TabSSMining);
GameRegistry.registerItem(stoneDust, "StoneDust");
blueStoneDust = new Item().setUnlocalizedName("ss.dust_blue_stone")
.setTextureName("sextiarysector:dust/bluestone_dust").setCreativeTab(SextiarySectorAPI.TabSSMining);
GameRegistry.registerItem(blueStoneDust, "DustBlueStone");
yellowStoneDust = new Item().setUnlocalizedName("ss.dust_yellow_stone")
.setTextureName("sextiarysector:dust/yellowstone_dust").setCreativeTab(SextiarySectorAPI.TabSSMining);
GameRegistry.registerItem(yellowStoneDust, "DustYellowStone");
coalDust = new Item().setUnlocalizedName("ss.coal_dust").setTextureName("sextiarysector:dust/coal_dust")
.setCreativeTab(SextiarySectorAPI.TabSSMining);
GameRegistry.registerItem(coalDust, "CoalDust");
ironDust = new Item().setUnlocalizedName("ss.iron_dust").setTextureName("sextiarysector:dust/iron_dust")
.setCreativeTab(SextiarySectorAPI.TabSSMining);
GameRegistry.registerItem(ironDust, "IronDust");
goldDust = new Item().setUnlocalizedName("ss.gold_dust").setTextureName("sextiarysector:dust/gold_dust")
.setCreativeTab(SextiarySectorAPI.TabSSMining);
GameRegistry.registerItem(goldDust, "GoldDust");
diamondDust = new Item().setUnlocalizedName("ss.diamond_dust")
.setTextureName("sextiarysector:dust/diamond_dust").setCreativeTab(SextiarySectorAPI.TabSSMining);
GameRegistry.registerItem(diamondDust, "DiamondDust");
copperDust = new Item().setUnlocalizedName("ss.copper_dust").setTextureName("sextiarysector:dust/copper_dust")
.setCreativeTab(SextiarySectorAPI.TabSSMining);
GameRegistry.registerItem(copperDust, "CopperDust");
zincDust = new Item().setUnlocalizedName("ss.zinc_dust").setTextureName("sextiarysector:dust/zinc_dust")
.setCreativeTab(SextiarySectorAPI.TabSSMining);
GameRegistry.registerItem(zincDust, "ZincDust");
silverDust = new Item().setUnlocalizedName("ss.silver_dust").setTextureName("sextiarysector:dust/silver_dust")
.setCreativeTab(SextiarySectorAPI.TabSSMining);
GameRegistry.registerItem(silverDust, "SilverDust");
mithrilDust = new Item().setUnlocalizedName("ss.mithril_dust")
.setTextureName("sextiarysector:dust/mithril_dust").setCreativeTab(SextiarySectorAPI.TabSSMining);
GameRegistry.registerItem(mithrilDust, "MithrilDust");
//ナゲット
ironNugget = new Item().setUnlocalizedName("ss.iron_nugget").setTextureName("sextiarysector:nugget/iron_nugget")
.setCreativeTab(SextiarySectorAPI.TabSSMining);
GameRegistry.registerItem(ironNugget, "IronNugget");
copperNugget = new Item().setUnlocalizedName("ss.copper_nugget")
.setTextureName("sextiarysector:nugget/copper_nugget").setCreativeTab(SextiarySectorAPI.TabSSMining);
GameRegistry.registerItem(copperNugget, "CopperNugget");
zincNugget = new Item().setUnlocalizedName("ss.zinc_nugget").setTextureName("sextiarysector:nugget/zinc_nugget")
.setCreativeTab(SextiarySectorAPI.TabSSMining);
GameRegistry.registerItem(zincNugget, "ZincNugget");
silverNugget = new Item().setUnlocalizedName("ss.silver_nugget")
.setTextureName("sextiarysector:nugget/silver_nugget").setCreativeTab(SextiarySectorAPI.TabSSMining);
GameRegistry.registerItem(silverNugget, "SilverNugget");
steelNugget = new Item().setUnlocalizedName("ss.steel_nugget")
.setTextureName("sextiarysector:nugget/steel_nugget").setCreativeTab(SextiarySectorAPI.TabSSMining);
GameRegistry.registerItem(steelNugget, "SteelNugget");
ninjaNugget = new Item().setUnlocalizedName("ss.ninja_nugget")
.setTextureName("sextiarysector:nugget/ninja_nugget").setCreativeTab(SextiarySectorAPI.TabSSMining);
GameRegistry.registerItem(ninjaNugget, "NinjaNugget");
obsidianNugget = new Item().setUnlocalizedName("ss.obsidian_nugget")
.setTextureName("sextiarysector:nugget/obsidian_nugget").setCreativeTab(SextiarySectorAPI.TabSSMining);
GameRegistry.registerItem(obsidianNugget, "ObsidianNugget");
//ナゲット 特殊
//インゴット
steelIngot = new Item().setUnlocalizedName("ss.steel_ingot").setTextureName("sextiarysector:ingot/steel_ingot")
.setCreativeTab(SextiarySectorAPI.TabSSMining);
GameRegistry.registerItem(steelIngot, "SteelIngot");
brassIngot = new Item().setUnlocalizedName("ss.brass_ingot").setTextureName("sextiarysector:ingot/brass_ingot")
.setCreativeTab(SextiarySectorAPI.TabSSMining);
GameRegistry.registerItem(brassIngot, "BrassIngot");
blueStoneIngot = new Item().setUnlocalizedName("ss.bluestone_ingot")
.setTextureName("sextiarysector:ingot/bluestone_ingot").setCreativeTab(SextiarySectorAPI.TabSSMining);
GameRegistry.registerItem(blueStoneIngot, "BlueStoneIngot");
yellowStoneIngot = new Item().setUnlocalizedName("ss.yellowstone_ingot")
.setTextureName("sextiarysector:ingot/yellowstone_ingot").setCreativeTab(SextiarySectorAPI.TabSSMining);
GameRegistry.registerItem(yellowStoneIngot, "YellowStoneIngot");
copperIngot = new Item().setUnlocalizedName("ss.copper_ingot")
.setTextureName("sextiarysector:ingot/copper_ingot").setCreativeTab(SextiarySectorAPI.TabSSMining);
GameRegistry.registerItem(copperIngot, "CopperIngot");
zincIngot = new Item().setUnlocalizedName("ss.zinc_ingot").setTextureName("sextiarysector:ingot/zinc_ingot")
.setCreativeTab(SextiarySectorAPI.TabSSMining);
GameRegistry.registerItem(zincIngot, "ZincIngot");
silverIngot = new Item().setUnlocalizedName("ss.silver_ingot")
.setTextureName("sextiarysector:ingot/silver_ingot").setCreativeTab(SextiarySectorAPI.TabSSMining);
GameRegistry.registerItem(silverIngot, "SilverIngot");
mithrilIngot = new Item().setUnlocalizedName("ss.mithril_ingot")
.setTextureName("sextiarysector:ingot/mithril_ingot").setCreativeTab(SextiarySectorAPI.TabSSMining);
GameRegistry.registerItem(mithrilIngot, "MithrilIngot");
orichalcumGem = new Item().setUnlocalizedName("ss.orichalcum_gem")
.setTextureName("sextiarysector:gem/orichalcum_gem").setCreativeTab(SextiarySectorAPI.TabSSMining);
GameRegistry.registerItem(orichalcumGem, "OrichalcumGem");
ninjaIngot = new Item().setUnlocalizedName("ss.ninja_ingot").setTextureName("sextiarysector:ingot/ninja_ingot")
.setCreativeTab(SextiarySectorAPI.TabSSMining);
GameRegistry.registerItem(ninjaIngot, "NinjaIngot");
redGel = new Item().setUnlocalizedName("ss.red_gel").setTextureName("sextiarysector:gel/red_gel")
.setCreativeTab(SextiarySectorAPI.TabSSCore);
GameRegistry.registerItem(redGel, "RedGel");
blueGel = new Item().setUnlocalizedName("ss.blue_gel").setTextureName("sextiarysector:gel/blue_gel")
.setCreativeTab(SextiarySectorAPI.TabSSCore);
GameRegistry.registerItem(blueGel, "BlueGel");
yellowGel = new Item().setUnlocalizedName("ss.yellow_gel").setTextureName("sextiarysector:gel/yellow_gel")
.setCreativeTab(SextiarySectorAPI.TabSSCore);
GameRegistry.registerItem(yellowGel, "YellowGel");
craftReactor = new Item().setUnlocalizedName("ss.craft_reactor")
.setTextureName("sextiarysector:reactor/craft_reactor").setCreativeTab(SextiarySectorAPI.TabSSCore);
GameRegistry.registerItem(craftReactor, "CraftReactor");
energyReactor = new Item().setUnlocalizedName("ss.energy_reactor")
.setTextureName("sextiarysector:reactor/energy_reactor").setCreativeTab(SextiarySectorAPI.TabSSCore);
GameRegistry.registerItem(energyReactor, "EnergyReactor");
objectReactor = new Item().setUnlocalizedName("ss.object_reactor")
.setTextureName("sextiarysector:reactor/object_reactor").setCreativeTab(SextiarySectorAPI.TabSSCore);
GameRegistry.registerItem(objectReactor, "ObjectReactor");
//液体
//ボトル
emptyBottle = new ItemBottle().setUnlocalizedName("ss.empty_bottle")
.setTextureName("sextiarysector:fluid/empty_bottle");
GameRegistry.registerItem(emptyBottle, "EmptyBottle");
waterBottle = new ItemWaterBottle().setUnlocalizedName("ss.water_bottle")
.setTextureName("sextiarysector:fluid/water_bottle");
GameRegistry.registerItem(waterBottle, "WaterBottle");
lavaBottle = new ItemLavaBottle().setUnlocalizedName("ss.lava_bottle")
.setTextureName("sextiarysector:fluid/lava_bottle");
GameRegistry.registerItem(lavaBottle, "LavaBottle");
sapBottle = new ItemFullBottle().setUnlocalizedName("ss.sap_bottle")
.setTextureName("sextiarysector:fluid/sap_bottle");
GameRegistry.registerItem(sapBottle, "SapBottle");
//バケツ
steamBucket = new ItemSimpleBucket().setUnlocalizedName("ss.steam_bucket")
.setTextureName("sextiarysector:fluid/steam_bucket");
GameRegistry.registerItem(steamBucket, "SteamBucket");
ironFluidBucket = new ItemSimpleBucket().setUnlocalizedName("ss.iron_fluid_bucket")
.setTextureName("sextiarysector:fluid/iron_fluid_bucket");
GameRegistry.registerItem(ironFluidBucket, "IronFluidBucket");
goldFluidBucket = new ItemSimpleBucket().setUnlocalizedName("ss.gold_fluid_bucket")
.setTextureName("sextiarysector:fluid/gold_fluid_bucket");
GameRegistry.registerItem(goldFluidBucket, "GoldFluidBucket");
//魔法
magicDust = new Item().setUnlocalizedName("ss.magic_dust").setTextureName("sextiarysector:dust/magic_dust")
.setCreativeTab(SextiarySectorAPI.TabSSMagic);
GameRegistry.registerItem(magicDust, "MagicDust");
//布
silkBobbin = new Item().setUnlocalizedName("ss.silk_bobbin").setTextureName("sextiarysector:loom/silk_bobbin")
.setCreativeTab(SextiarySectorAPI.TabSSCore);
GameRegistry.registerItem(silkBobbin, "SilkBobbin");
smallCloth = new Item().setUnlocalizedName("ss.small_cloth").setTextureName("sextiarysector:loom/small_cloth")
.setCreativeTab(SextiarySectorAPI.TabSSCore);
GameRegistry.registerItem(smallCloth, "SmallCloth");
silkCloth = new Item().setUnlocalizedName("ss.silk_cloth").setTextureName("sextiarysector:loom/silk_cloth")
.setCreativeTab(SextiarySectorAPI.TabSSCore);
GameRegistry.registerItem(silkCloth, "silkCloth");
canvas = new Item().setUnlocalizedName("ss.canvas").setTextureName("sextiarysector:loom/canvas")
.setCreativeTab(SextiarySectorAPI.TabSSCore);
GameRegistry.registerItem(canvas, "Canvas");
dryingFlesh = new Item().setUnlocalizedName("ss.drying_flesh")
.setTextureName("sextiarysector:loom/drying_flesh").setCreativeTab(SextiarySectorAPI.TabSSCore);
GameRegistry.registerItem(dryingFlesh, "DryingFlesh");
fleshBobbin = new Item().setUnlocalizedName("ss.flesh_bobbin")
.setTextureName("sextiarysector:loom/flesh_bobbin").setCreativeTab(SextiarySectorAPI.TabSSCore);
GameRegistry.registerItem(fleshBobbin, "FleshBobbin");
stringMass = new Item().setUnlocalizedName("ss.string_mass").setTextureName("sextiarysector:loom/string_mass")
.setCreativeTab(SextiarySectorAPI.TabSSCore);
GameRegistry.registerItem(stringMass, "StringMass");
strongString = new Item().setUnlocalizedName("ss.strong_string")
.setTextureName("sextiarysector:loom/strong_string").setCreativeTab(SextiarySectorAPI.TabSSCore);
GameRegistry.registerItem(strongString, "StrongString");
strongStringBobbin = new Item().setUnlocalizedName("ss.strong_string_bobbin")
.setTextureName("sextiarysector:loom/strong_string_bobbin").setCreativeTab(SextiarySectorAPI.TabSSCore);
GameRegistry.registerItem(strongStringBobbin, "StrongStringBobbin");
strongCloth = new Item().setUnlocalizedName("ss.strong_cloth")
.setTextureName("sextiarysector:loom/strong_cloth").setCreativeTab(SextiarySectorAPI.TabSSCore);
GameRegistry.registerItem(strongCloth, "StrongCloth");
strongCanvas = new Item().setUnlocalizedName("ss.strong_canvas")
.setTextureName("sextiarysector:loom/strong_canvas").setCreativeTab(SextiarySectorAPI.TabSSCore);
GameRegistry.registerItem(strongCanvas, "StrongCanvas");
//bottle = new ItemBlockBottle().setUnlocalizedName("ss.bottle").setTextureName("sextiarysector:drink/empty_bottle");
//GameRegistry.registerItem(bottle, "Bottle");
figureBox = new ItemFigureBox().setUnlocalizedName("ss.figure_box").setTextureName("sextiarysector:figure_box")
.setCreativeTab(SextiarySectorAPI.TabSSCore);
GameRegistry.registerItem(figureBox, "FigureBox");
//道具
woodScoop = new ItemScoop(ToolMaterial.WOOD).setUnlocalizedName("ss.wood_scoop").setTextureName("wood_scoop");
stoneScoop = new ItemScoop(ToolMaterial.STONE).setUnlocalizedName("ss.stone_scoop")
.setTextureName("stone_scoop");
ironScoop = new ItemScoop(ToolMaterial.IRON).setUnlocalizedName("ss.iron_scoop").setTextureName("iron_scoop");
goldScoop = new ItemScoop(ToolMaterial.GOLD).setUnlocalizedName("ss.gold_scoop").setTextureName("gold_scoop");
diamondScoop = new ItemScoop(ToolMaterial.EMERALD).setUnlocalizedName("ss.diamond_scoop")
.setTextureName("diamond_scoop");
GameRegistry.registerItem(woodScoop, "WoodScoop");
GameRegistry.registerItem(stoneScoop, "StoneScoop");
GameRegistry.registerItem(ironScoop, "IronScoop");
GameRegistry.registerItem(goldScoop, "GoldScoop");
GameRegistry.registerItem(diamondScoop, "DiamondScoop");
copperScoop = new ItemScoop(ModuleToolMaterial.copperTool).setUnlocalizedName("ss.copper_scoop").setTextureName("copper_scoop");
GameRegistry.registerItem(copperScoop, "CopperScoop");
brassScoop = new ItemScoop(ModuleToolMaterial.brassTool).setUnlocalizedName("ss.brass_scoop").setTextureName("brass_scoop");
GameRegistry.registerItem(brassScoop, "BrassScoop");
ninjaScoop = new ItemScoop(ModuleToolMaterial.ninjaTool).setUnlocalizedName("ss.ninja_scoop").setTextureName("ninja_scoop");
GameRegistry.registerItem(ninjaScoop, "NinjaScoop");
woodKnife = new ItemKnife(ToolMaterial.WOOD).setUnlocalizedName("ss.wood_knife").setTextureName("wood_knife");
stoneKnife = new ItemKnife(ToolMaterial.STONE).setUnlocalizedName("ss.stone_knife").setTextureName("stone_knife");
ironKnife = new ItemKnife(ToolMaterial.IRON).setUnlocalizedName("ss.iron_knife").setTextureName("iron_knife");
goldKnife = new ItemKnife(ToolMaterial.GOLD).setUnlocalizedName("ss.gold_knife").setTextureName("gold_knife");
diamondKnife = new ItemKnife(ToolMaterial.EMERALD).setUnlocalizedName("ss.diamond_knife").setTextureName("diamond_knife");
GameRegistry.registerItem(woodKnife, "WoodKnife");
GameRegistry.registerItem(stoneKnife, "StoneKnife");
GameRegistry.registerItem(ironKnife, "IronKnife");
GameRegistry.registerItem(goldKnife, "GoldKnife");
GameRegistry.registerItem(diamondKnife, "DiamondKnife");
copperKnife = new ItemKnife(ModuleToolMaterial.copperTool).setUnlocalizedName("ss.copper_knife").setTextureName("copper_knife");
GameRegistry.registerItem(copperKnife, "CopperKnife");
brassKnife = new ItemKnife(ModuleToolMaterial.brassTool).setUnlocalizedName("ss.brass_knife").setTextureName("brass_knife");
GameRegistry.registerItem(brassKnife, "BrassKnife");
ninjaKnife = new ItemKnife(ModuleToolMaterial.ninjaTool).setUnlocalizedName("ss.ninja_knife").setTextureName("ninja_knife");
GameRegistry.registerItem(ninjaKnife, "NinjaKnife");
//バニラ
// 銅
copperShovel = new ItemSpade(ModuleToolMaterial.copperTool).setUnlocalizedName("ss.copper_shovel")
.setTextureName("sextiarysector:tool/copper_shovel").setCreativeTab(SextiarySectorAPI.TabSSCore);
GameRegistry.registerItem(copperShovel, "CopperShovel");
copperPickaxe = new ItemSSPickaxe(ModuleToolMaterial.copperTool).setUnlocalizedName("ss.copper_pickaxe")
.setTextureName("sextiarysector:tool/copper_pickaxe").setCreativeTab(SextiarySectorAPI.TabSSCore);
GameRegistry.registerItem(copperPickaxe, "CopperPickaxe");
copperAxe = new ItemSSAxe(ModuleToolMaterial.copperTool).setUnlocalizedName("ss.copper_axe")
.setTextureName("sextiarysector:tool/copper_axe").setCreativeTab(SextiarySectorAPI.TabSSCore);
GameRegistry.registerItem(copperAxe, "CopperAxe");
copperSword = new ItemSword(ModuleToolMaterial.copperTool).setUnlocalizedName("ss.copper_sword")
.setTextureName("sextiarysector:tool/copper_sword").setCreativeTab(SextiarySectorAPI.TabSSCore);
GameRegistry.registerItem(copperSword, "CopperSword");
copperHoe = new ItemHoe(ModuleToolMaterial.copperTool).setUnlocalizedName("ss.copper_hoe")
.setTextureName("sextiarysector:tool/copper_hoe").setCreativeTab(SextiarySectorAPI.TabSSCore);
GameRegistry.registerItem(copperHoe, "CopperHoe");
//黄銅
brassShovel = new ItemSpade(ModuleToolMaterial.brassTool).setUnlocalizedName("ss.brass_shovel")
.setTextureName("sextiarysector:tool/brass_shovel").setCreativeTab(SextiarySectorAPI.TabSSCore);
GameRegistry.registerItem(brassShovel, "BrassShovel");
brassPickaxe = new ItemSSPickaxe(ModuleToolMaterial.brassTool).setUnlocalizedName("ss.brass_pickaxe")
.setTextureName("sextiarysector:tool/brass_pickaxe").setCreativeTab(SextiarySectorAPI.TabSSCore);
GameRegistry.registerItem(brassPickaxe, "BrassPickaxe");
brassAxe = new ItemSSAxe(ModuleToolMaterial.brassTool).setUnlocalizedName("ss.brass_axe")
.setTextureName("sextiarysector:tool/brass_axe").setCreativeTab(SextiarySectorAPI.TabSSCore);
GameRegistry.registerItem(brassAxe, "BrassAxe");
brassSword = new ItemSword(ModuleToolMaterial.brassTool).setUnlocalizedName("ss.brass_sword")
.setTextureName("sextiarysector:tool/brass_sword").setCreativeTab(SextiarySectorAPI.TabSSCore);
GameRegistry.registerItem(brassSword, "BrassSword");
brassHoe = new ItemHoe(ModuleToolMaterial.brassTool).setUnlocalizedName("ss.brass_hoe")
.setTextureName("sextiarysector:tool/brass_hoe").setCreativeTab(SextiarySectorAPI.TabSSCore);
GameRegistry.registerItem(brassHoe, "BrassHoe");
// ニンジャ
ninjaShovel = new ItemSpade(ModuleToolMaterial.ninjaTool).setUnlocalizedName("ss.ninja_shovel")
.setTextureName("sextiarysector:tool/ninja_shovel").setCreativeTab(SextiarySectorAPI.TabSSCore);
GameRegistry.registerItem(ninjaShovel, "NinjaShovel");
ninjaPickaxe = new ItemSSPickaxe(ModuleToolMaterial.ninjaTool).setUnlocalizedName("ss.ninja_pickaxe")
.setTextureName("sextiarysector:tool/ninja_pickaxe").setCreativeTab(SextiarySectorAPI.TabSSCore);
GameRegistry.registerItem(ninjaPickaxe, "NinjaPickaxe");
ninjaAxe = new ItemSSAxe(ModuleToolMaterial.ninjaTool).setUnlocalizedName("ss.ninja_axe")
.setTextureName("sextiarysector:tool/ninja_axe").setCreativeTab(SextiarySectorAPI.TabSSCore);
GameRegistry.registerItem(ninjaAxe, "NinjaAxe");
ninjaSword = new ItemSword(ModuleToolMaterial.ninjaTool).setUnlocalizedName("ss.ninja_sword")
.setTextureName("sextiarysector:tool/ninja_sword").setCreativeTab(SextiarySectorAPI.TabSSCore);
GameRegistry.registerItem(ninjaSword, "NinjaSword");
ninjaHoe = new ItemHoe(ModuleToolMaterial.ninjaTool).setUnlocalizedName("ss.ninja_hoe")
.setTextureName("sextiarysector:tool/ninja_hoe").setCreativeTab(SextiarySectorAPI.TabSSCore);
GameRegistry.registerItem(ninjaHoe, "NinjaHoe");
//Item i = Items.iron_axe;
//防具
// 銅
copperHelmet = new ItemSSArmor(ModuleToolMaterial.copperArmor, 0, 0).setUnlocalizedName("ss.copper_helmet")
.setTextureName("sextiarysector:armor/copper_helmet");
GameRegistry.registerItem(copperHelmet, "CopperHelmet");
copperChestplate = new ItemSSArmor(ModuleToolMaterial.copperArmor, 0, 1)
.setUnlocalizedName("ss.copper_chestplate").setTextureName("sextiarysector:armor/copper_chestplate");
GameRegistry.registerItem(copperChestplate, "CopperChestplate");
copperLeggings = new ItemSSArmor(ModuleToolMaterial.copperArmor, 0, 2).setUnlocalizedName("ss.copper_leggings")
.setTextureName("sextiarysector:armor/copper_leggings");
GameRegistry.registerItem(copperLeggings, "CopperLeggings");
copperBoots = new ItemSSArmor(ModuleToolMaterial.copperArmor, 0, 3).setUnlocalizedName("ss.copper_boots")
.setTextureName("sextiarysector:armor/copper_boots");
GameRegistry.registerItem(copperBoots, "CopperBoots");
// ニンジャ
ninjaHelmet = new ItemSSArmor(ModuleToolMaterial.ninjaArmor, 0, 0).setUnlocalizedName("ss.ninja_helmet")
.setTextureName("sextiarysector:armor/ninja_helmet");
GameRegistry.registerItem(ninjaHelmet, "NinjaHelmet");
ninjaChestplate = new ItemSSArmor(ModuleToolMaterial.ninjaArmor, 0, 1).setUnlocalizedName("ss.ninja_chestplate")
.setTextureName("sextiarysector:armor/ninja_chestplate");
GameRegistry.registerItem(ninjaChestplate, "NinjaChestplate");
ninjaLeggings = new ItemSSArmor(ModuleToolMaterial.ninjaArmor, 0, 2).setUnlocalizedName("ss.ninja_leggings")
.setTextureName("sextiarysector:armor/ninja_leggings");
GameRegistry.registerItem(ninjaLeggings, "NinjaLeggings");
ninjaBoots = new ItemSSArmor(ModuleToolMaterial.ninjaArmor, 0, 3).setUnlocalizedName("ss.ninja_boots")
.setTextureName("sextiarysector:armor/ninja_boots");
GameRegistry.registerItem(ninjaBoots, "NinjaBoots");
//水やり
woodWateringCan = new ItemWateringCan(ToolMaterial.WOOD).setUnlocalizedName("ss.wood_watering_can")
.setTextureName("wood_watering_can");
GameRegistry.registerItem(woodWateringCan, "WoodWateringCan");
brassShears = new ItemSSShears(ModuleToolMaterial.brassTool).setUnlocalizedName("ss.brass_shears")
.setTextureName("sextiarysector:tool/brass_shears");
GameRegistry.registerItem(brassShears, "BrassShears");
//水産
mineboatChest = new ItemMineboat().setUnlocalizedName("ss.mineboat_chest")
.setTextureName("sextiarysector:mineboat_chest");
GameRegistry.registerItem(mineboatChest, "MineboatChest");
mineboatTank = new ItemMineboatTank().setUnlocalizedName("ss.mineboat_tank")
.setTextureName("sextiarysector:mineboat_tank");
GameRegistry.registerItem(mineboatTank, "MineboatTank");
laver = new Item().setUnlocalizedName("ss.laver").setTextureName("sextiarysector:food/fish/laver")
.setCreativeTab(SextiarySectorAPI.TabSSFishery);
GameRegistry.registerItem(laver, "Laver");
//農業
seeds = new ItemSeed();
GameRegistry.registerItem(seeds, "Seeds");
//野菜
turnip = new ItemFoodCrop(3, 1, 1, 4, 0, 0, false).setUnlocalizedName("ss.turnip")
.setTextureName("sextiarysector:food/vegetable/turnip");
GameRegistry.registerItem(turnip, "Turnip");
cucumber = new ItemFoodCrop(1, 1, 3, 4, 0, 2, false).setUnlocalizedName("ss.cucumber")
.setTextureName("sextiarysector:food/vegetable/cucumber");
GameRegistry.registerItem(cucumber, "Cucumber");
ironTurnip = new ItemFoodCrop(0, 1, 0, 0, 0, 0, false).setUnlocalizedName("ss.iron_turnip")
.setTextureName("sextiarysector:food/vegetable/iron_turnip");
GameRegistry.registerItem(ironTurnip, "IronTurnip");
onion = new ItemFoodCrop(2, 1, 1, 0, 0, 0, false).setUnlocalizedName("ss.onion")
.setTextureName("sextiarysector:food/vegetable/onion");
GameRegistry.registerItem(onion, "Onion");
tomato = new ItemFoodCrop(1, 1, 4, 5, 0, 0, false).setUnlocalizedName("ss.tomato")
.setTextureName("sextiarysector:food/vegetable/tomato");
GameRegistry.registerItem(tomato, "Tomato");
corn = new ItemFoodCrop(0, 1, 1, 6, 4, 2, false).setUnlocalizedName("ss.corn")
.setTextureName("sextiarysector:food/vegetable/corn");
GameRegistry.registerItem(corn, "corn");
copperOnion = new ItemFoodCrop(0, 2, 0, 0, 0, 0, false).setUnlocalizedName("ss.copper_onion")
.setTextureName("sextiarysector:food/vegetable/copper_onion");
GameRegistry.registerItem(copperOnion, "CopperOnion");
goldenCorn = new ItemFoodCrop(0, 2, 0, 0, 0, 0, false).setUnlocalizedName("ss.golden_corn")
.setTextureName("sextiarysector:food/vegetable/golden_corn");
GameRegistry.registerItem(goldenCorn, "GoldCorn");
eggplant = new ItemFoodCrop(1, 1, 4, 2, 0, 0, false).setUnlocalizedName("ss.eggplant")
.setTextureName("sextiarysector:food/vegetable/eggplant");
GameRegistry.registerItem(eggplant, "Eggplant");
sweetPotato = new ItemFoodCrop(4, 1, 0, 0, 6, 0, false).setUnlocalizedName("ss.sweet_potato")
.setTextureName("sextiarysector:food/vegetable/sweet_potato");
GameRegistry.registerItem(sweetPotato, "SweetPotato");
greenPepper = new ItemFoodCrop(2, 1, 2, 1, 0, 0, false).setUnlocalizedName("ss.green_pepper")
.setTextureName("sextiarysector:food/vegetable/green_pepper");
GameRegistry.registerItem(greenPepper, "GreenPepper");
bluePotato = new ItemFoodCrop(1, 0, 5, 8, 2, 0, false).setUnlocalizedName("ss.blue_potato")
.setTextureName("sextiarysector:food/vegetable/blue_potato");
GameRegistry.registerItem(bluePotato, "BluePotato");
radish = new ItemFoodCrop(3, 1, 2, 1, 0, 0, false).setUnlocalizedName("ss.radish")
.setTextureName("sextiarysector:food/vegetable/radish");
GameRegistry.registerItem(radish, "Radish");
rice = new ItemCrop().setUnlocalizedName("ss.rice").setTextureName("sextiarysector:food/grain/rice")
.setCreativeTab(SextiarySectorAPI.TabSSAgriculture);
GameRegistry.registerItem(rice, "Rice");
shiitake = new ItemFoodCrop(2, 1, 0, 0, 2, 0, false).setUnlocalizedName("ss.shiitake")
.setTextureName("sextiarysector:food/mushroom/shiitake");
GameRegistry.registerItem(shiitake, "Shiitake");
//さかな
squidSashimi = new ItemFoodDrink(2, 1.2f, 0, 0.4f, 0, 4, false).setUnlocalizedName("ss.squid_sashimi")
.setTextureName("sextiarysector:food/fish/squid_sashimi")
.setCreativeTab(SextiarySectorAPI.TabSSCooking);
GameRegistry.registerItem(squidSashimi, "SquidSashimi");
//料理
whiteRice = new Item().setUnlocalizedName("ss.white_rice")
.setTextureName("sextiarysector:food/grain/white_rice").setCreativeTab(SextiarySectorAPI.TabSSCooking);
GameRegistry.registerItem(whiteRice, "WhiteRice");
salt = new Item().setUnlocalizedName("ss.salt").setTextureName("sextiarysector:food/condiment/salt")
.setCreativeTab(SextiarySectorAPI.TabSSCooking);
GameRegistry.registerItem(salt, "Salt");
curryPowder = new Item().setUnlocalizedName("ss.curry_powder")
.setTextureName("sextiarysector:food/condiment/curry_powder")
.setCreativeTab(SextiarySectorAPI.TabSSCooking);
GameRegistry.registerItem(curryPowder, "CurryPowder");
laverRoasted = new ItemFoodDrink(3, 1.2f, 0, 0, 2, 0, false).setUnlocalizedName("ss.laver_roasted")
.setTextureName("sextiarysector:food/fish/laver_roasted")
.setCreativeTab(SextiarySectorAPI.TabSSCooking);
GameRegistry.registerItem(laverRoasted, "LaverRoasted");
chickenSmoked = new ItemFoodDrink(2, 4.6f, 0, 0, 4, 2.0f, false).setUnlocalizedName("ss.chicken_smoked")
.setTextureName("sextiarysector:food/meat/chicken_smoked")
.setCreativeTab(SextiarySectorAPI.TabSSCooking);
GameRegistry.registerItem(chickenSmoked, "ChickenSmoked");
porkchopSmoked = new ItemFoodDrink(3, 7.6f, 0, 0, 4, 2.0f, false).setUnlocalizedName("ss.porkchop_smoked")
.setTextureName("sextiarysector:food/meat/porkchop_smoked")
.setCreativeTab(SextiarySectorAPI.TabSSCooking);
GameRegistry.registerItem(porkchopSmoked, "PorkchopSmoked");
beefSmoked = new ItemFoodDrink(3, 7.6f, 0, 0, 4, 2.0f, false).setUnlocalizedName("ss.beef_smoked")
.setTextureName("sextiarysector:food/meat/beef_smoked").setCreativeTab(SextiarySectorAPI.TabSSCooking);
GameRegistry.registerItem(beefSmoked, "BeefSmoked");
riceBall = new ItemFoodDrink(4, 0.6f, 0, 0, 4, 6.0f, false).setUnlocalizedName("ss.rice_ball")
.setTextureName("sextiarysector:food/rice/rice_ball").setCreativeTab(SextiarySectorAPI.TabSSCooking);
GameRegistry.registerItem(riceBall, "RiceBall");
curryRice = new ItemFoodDrink(9, 12.6f, 0, 0, 15, 2.0f, false).setUnlocalizedName("ss.curry_rice")
.setTextureName("sextiarysector:food/rice/curry_rice").setContainerItem(Items.bowl)
.setCreativeTab(SextiarySectorAPI.TabSSCooking);
GameRegistry.registerItem(curryRice, "CurryRice");
carrotSoup = new ItemSoup(2, 0.6f, 4, 1, 0, 0.0f, false).setUnlocalizedName("ss.carrot_soup")
.setTextureName("sextiarysector:food/soup/carrot_soup");
GameRegistry.registerItem(carrotSoup, "CarrotSoup");
cornSoup = new ItemSoup(1, 0.6f, 5, 1, 0, 0.0f, false).setUnlocalizedName("ss.corn_soup")
.setTextureName("sextiarysector:food/soup/corn_soup");
GameRegistry.registerItem(cornSoup, "CornSoup");
eggSoup = new ItemSoup(3, 0.6f, 4, 2, 0, 0.0f, false).setUnlocalizedName("ss.egg_soup")
.setTextureName("sextiarysector:food/soup/egg_soup");
GameRegistry.registerItem(eggSoup, "EggSoup");
onionSoup = new ItemSoup(1, 0.6f, 5, 1, 0, 0.0f, false).setUnlocalizedName("ss.onion_soup")
.setTextureName("sextiarysector:food/soup/onion_soup");
GameRegistry.registerItem(onionSoup, "OnionSoup");
enderSoup = new ItemSoup(0, 0.6f, 4, 1, 20, 0.0f, false).setUnlocalizedName("ss.ender_soup")
.setTextureName("sextiarysector:food/soup/ender_soup");
GameRegistry.registerItem(enderSoup, "EnderSoup");
tomatoSoup = new ItemSoup(1, 0.6f, 3, 4.0f, 0, 0.0f, false).setUnlocalizedName("ss.tomato_soup")
.setTextureName("sextiarysector:food/soup/tomato_soup");
GameRegistry.registerItem(tomatoSoup, "TomatoSoup");
chocolate = new ItemFoodDrink(2, 1.2f, 0, 0, 6, 4.0f, false).setUnlocalizedName("ss.chocolate")
.setTextureName("sextiarysector:food/dessert/chocolate").setCreativeTab(SextiarySectorAPI.TabSSCooking);
GameRegistry.registerItem(chocolate, "Chocolate");
//飲み物
drinkingWaterBottle = new ItemDrink(0, 2.5f, 5, 7.8f, 0, 0, false)
.setUnlocalizedName("ss.drinking_water_bottle")
.setTextureName("sextiarysector:fluid/drinking_water_bottle");
GameRegistry.registerItem(drinkingWaterBottle, "DrinkingWaterBottle");
takumiTeaBottle = new ItemDrink(0, 0.0f, 6, 9.5f, 0, 0, false).setUnlocalizedName("ss.takumi_tea_bottle")
.setTextureName("sextiarysector:fluid/takumi_tea_bottle");
GameRegistry.registerItem(takumiTeaBottle, "TAKUMITeaBottle");
//装備
shiftHat = new ItemShiftHat().setUnlocalizedName("ss.shift_hat").setTextureName("sextiarysector:shift_hat");
GameRegistry.registerItem(shiftHat, "ShiftHat");
rucksack = new ItemRucksack().setUnlocalizedName("ss.rucksack").setTextureName("sextiarysector:rucksack");
GameRegistry.registerItem(rucksack, "Rucksack");
quiver = new ItemQuiver().setUnlocalizedName("ss.quiver").setTextureName("quiver");
GameRegistry.registerItem(quiver, "Quiver");
oxygenTank = new ItemOxygenTank().setUnlocalizedName("ss.oxygen_tank")
.setTextureName("sextiarysector:oxygen_tank").setCreativeTab(SextiarySectorAPI.TabSSPlayer);
GameRegistry.registerItem(oxygenTank, "OxygenTank");
gfContactLenses = new ItemGFContactLenses().setUnlocalizedName("ss.gf_contact_lenses")
.setTextureName("sextiarysector:face/gf_contact_lenses");
GameRegistry.registerItem(gfContactLenses, "GFContactLenses");
waterContactLenses = new ItemContactLenses().setUnlocalizedName("ss.water_contact_lenses")
.setTextureName("sextiarysector:face/water_contact_lenses");
GameRegistry.registerItem(waterContactLenses, "WaterContactLenses");
//Unit
craftUnit = new ItemGuiUnit(201).setUnlocalizedName("ss.craft_unit").setTextureName("sextiarysector:unit/craft_unit").setCreativeTab(SextiarySectorAPI.TabSSPlayer);
GameRegistry.registerItem(craftUnit, "CraftUnit");
attackUnit = new ItemUnit().setUnlocalizedName("ss.attack_unit")
.setTextureName("sextiarysector:unit/attack_unit").setCreativeTab(SextiarySectorAPI.TabSSPlayer);
GameRegistry.registerItem(attackUnit, "AttackUnit");
defenseUnit = new ItemUnit().setUnlocalizedName("ss.defense_unit")
.setTextureName("sextiarysector:unit/defense_unit").setCreativeTab(SextiarySectorAPI.TabSSPlayer);
GameRegistry.registerItem(defenseUnit, "DefenseUnit");
attackRustUnit = new ItemUnit().setUnlocalizedName("ss.attack_rust_unit")
.setTextureName("sextiarysector:unit/attack_rust_unit").setCreativeTab(SextiarySectorAPI.TabSSPlayer);
GameRegistry.registerItem(attackRustUnit, "AttackRustUnit");
defenseRustUnit = new ItemUnit().setUnlocalizedName("ss.defense_rust_unit")
.setTextureName("sextiarysector:unit/defense_rust_unit").setCreativeTab(SextiarySectorAPI.TabSSPlayer);
GameRegistry.registerItem(defenseRustUnit, "DefenseRustUnit");
jumpUnit = new ItemUnit().setUnlocalizedName("ss.jump_unit").setTextureName("sextiarysector:unit/jump_unit")
.setCreativeTab(SextiarySectorAPI.TabSSPlayer);
GameRegistry.registerItem(jumpUnit, "JumpUnit");
dashUnit = new ItemUnit().setUnlocalizedName("ss.dash_unit").setTextureName("sextiarysector:unit/dash_unit")
.setCreativeTab(SextiarySectorAPI.TabSSPlayer);
GameRegistry.registerItem(dashUnit, "DashUnit");
slowlyUnit = new ItemUnit().setUnlocalizedName("ss.slowly_unit")
.setTextureName("sextiarysector:unit/slowly_unit").setCreativeTab(SextiarySectorAPI.TabSSPlayer);
GameRegistry.registerItem(slowlyUnit, "SlowlyUnit");
pullingUnit = new ItemUnit().setUnlocalizedName("ss.pulling_unit").setTextureName("sextiarysector:unit/pulling_unit")
.setCreativeTab(SextiarySectorAPI.TabSSPlayer);
GameRegistry.registerItem(pullingUnit, "PullingUnit");
multiSchottUnit = new ItemUnit().setUnlocalizedName("ss.multi_schott_unit").setTextureName("sextiarysector:unit/multi_schott_unit")
.setCreativeTab(SextiarySectorAPI.TabSSPlayer);
GameRegistry.registerItem(multiSchottUnit, "MultiSchottUnit");
//bedMonsterUnit = new ItemUnit().setUnlocalizedName("ss.bed_monster_unit").setTextureName("sextiarysector:unit/bed_monster_unit").setCreativeTab(SextiarySectorAPI.TabSSPlayer);
//GameRegistry.registerItem(bedMonsterUnit, "BedMonsterUnit");
pickaxeUnit = new ItemUnit().setUnlocalizedName("ss.pickaxe_unit")
.setTextureName("sextiarysector:unit/pickaxe_unit").setCreativeTab(SextiarySectorAPI.TabSSPlayer);
GameRegistry.registerItem(pickaxeUnit, "PickaxeUnit");
debugUnit = new ItemUnit().setUnlocalizedName("ss.debug_unit").setTextureName("sextiarysector:unit/debug_unit")
.setCreativeTab(SextiarySectorAPI.TabSSPlayer);
GameRegistry.registerItem(debugUnit, "DebugUnit");
//Ring
ironRing = new Item().setUnlocalizedName("ss.iron_ring").setTextureName("sextiarysector:ring/iron_ring")
.setCreativeTab(SextiarySectorAPI.TabSSPlayer);
GameRegistry.registerItem(ironRing, "IronRing");
//creeperRing = new ItemShopRing().setUnlocalizedName("ss.creeper_ring")
// .setTextureName("sextiarysector:ring/creeper_ring");
//GameRegistry.registerItem(creeperRing, "CreeperRing");
mpRing = new ItemProtectionRing().setUnlocalizedName("ss.mp_ring").setTextureName("sextiarysector:ring/mp_ring")
.setCreativeTab(SextiarySectorAPI.TabSSPlayer);
GameRegistry.registerItem(mpRing, "MPRing");
xpRing = new ItemProtectionRing().setUnlocalizedName("ss.xp_ring").setTextureName("sextiarysector:ring/xp_ring")
.setCreativeTab(SextiarySectorAPI.TabSSPlayer);
GameRegistry.registerItem(xpRing, "XPRing");
//経済
creeperMemory = (ItemShopMemory) new ItemShopMemory("creeper").setUnlocalizedName("ss.creeper_memory").setTextureName("sextiarysector:memory/creeper_memory");
GameRegistry.registerItem(creeperMemory, "CreeperMemory");
skeletonMemory = (ItemShopMemory) new ItemShopMemory("skeleton").setUnlocalizedName("ss.skeleton_memory").setTextureName("sextiarysector:memory/skeleton_memory");
GameRegistry.registerItem(skeletonMemory, "SkeletonMemory");
}
}
| shift02/SextiarySector2 | src/main/java/shift/sextiarysector/SSItems.java |
64,963 | package cc.openhome;
public class RPG {
public static void main(String[] args) {
SwordsMan swordsMan = new SwordsMan();
swordsMan.setName("Justin");
swordsMan.setLevel(1);
swordsMan.setBlood(200);
System.out.printf("劍士 (%s, %d, %d)%n", swordsMan.getName(),
swordsMan.getLevel(), swordsMan.getBlood());
Magician magician = new Magician();
magician.setName("Monica");
magician.setLevel(1);
magician.setBlood(100);
System.out.printf("魔法師 (%s, %d, %d)%n", magician.getName(),
magician.getLevel(), magician.getBlood());
}
}
| JustinSDK/JavaSE8Tutorial | labs/CH06/Game5/src/cc/openhome/RPG.java |
64,965 | package action.magics;
import action.ActionMagic;
import chr.Chr;
import others.Calc;
import others.IO;
public class ActionMagicFireBall extends ActionMagic {
public ActionMagicFireBall(Chr me) {
super(me);
name = "ファイアボール";
MPCons = 10;
multi = 25;
element = ACTION_ELEMENT_FIRE;
}
// 対象:敵単体
public boolean playerTarget() {
return IO.selectSingleAliveTarget(me.party.enemy.member, me);
}
// ダメージ:魔法、掛け算方式
public void execute() {
IO.changeTargetsRandomlyIfDead(me.party.enemy.member, me);
IO.msgln("【%sは%sを唱えた!】", me.name, name);
Calc.mgcSingleDmg(me);
me.MP -= MPCons;
}
}
| kiskfjt/randomQuest | src/action/magics/ActionMagicFireBall.java |
64,966 | /*
聊天
时间限制:1秒
空间限制:32768K
A和B是好友,他们经常在空闲时间聊天,A的空闲时间为[a1 ,b1 ],[a2 ,b2 ]..[ap ,bp ]。
B的空闲时间是[c1 +t,d1 +t]..[cq +t,dq +t],这里t为B的起床时间。这些时间包括了边界点。
B的起床时间为[l,r]的一个时刻。若一个起床时间能使两人在某一时刻聊天,那么这个时间就是合适的,问有多少个合适的起床时间?
输入描述:
第一行数据四个整数:p,q,l,r(1≤p,q≤50,0≤l≤r≤1000)。接下来p行数据每一行有一对整数ai,bi(0≤ai+1>bi,ci+1>di)
输出描述:
输出答案个数
输入例子1:
2 3 0 20
15 17
23 26
1 4
7 11
15 17
输出例子1:
20
*/
/**
* Approach: Simulation (Find Overlap Interval)
* 没啥水平的题...初看区间类题,以为会涉及到扫描线或者线段树结果发现直接暴力遍历一遍
* 判断两个区间是否有交集即可...
* 题目描述有些坑爹,这边直接做了下修改。
*
* 时间复杂度:O(N*M*(R-L))
*/
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int p = sc.nextInt(), q = sc.nextInt();
int l = sc.nextInt(), r = sc.nextInt();
int[][] A = new int[p][2];
int[][] B = new int[q][2];
for (int i = 0; i < p; i++) {
A[i][0] = sc.nextInt();
A[i][1] = sc.nextInt();
}
for (int i = 0; i < q; i++) {
B[i][0] = sc.nextInt();
B[i][1] = sc.nextInt();
}
int count = 0;
for (int i = l; i <= r; i++) {
if (isProperTime(A, B, i)) {
count++;
}
}
System.out.println(count);
}
}
// 判断 A[] 和 B[] 中所有的时间区间,只要有一个区间有交集即可
private static boolean isProperTime(int[][] A, int[][] B, int time) {
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < B.length; j++) {
// 如果发现 A[i] 和 B[j] 这两个区间有交集,则返回 true
if ((B[j][0] + time >= A[i][0] && B[j][0] + time <= A[i][1])
|| (A[i][0] >= B[j][0] + time && A[i][0] <= B[j][1] + time)) {
return true;
}
}
}
return false;
}
} | cherryljr/NowCoder | 蘑菇街_聊天.java |
64,969 | package org.sword.wechat4j.csc;
/**
* 聊天记录
* @author Zhangxs
* @date 2015-7-7
* @version
*/
public class Record {
private String openid;//用户的标识
private int opercode;//操作ID(会话状态)
private String text;//聊天记录
private int time;//操作时间,UNIX时间戳
private String worker;//客服账号
public Record() {
super();
}
public Record(String openid, int opercode,
String text, int time, String worker) {
super();
this.openid = openid;
this.opercode = opercode;
this.text = text;
this.time = time;
this.worker = worker;
}
/**
* 用户的标识
* @return
*/
public String getOpenid() {
return openid;
}
public void setOpenid(String openid) {
this.openid = openid;
}
/**
* 操作ID(会话状态)
* @see RecordOperCode#getSessionState(int)
*/
public int getOpercode() {
return opercode;
}
public void setOpercode(int opercode) {
this.opercode = opercode;
}
/**
* 聊天记录
* @return
*/
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
/**
* 操作时间,UNIX时间戳
* @return
*/
public int getTime() {
return time;
}
public void setTime(int time) {
this.time = time;
}
/**
* 客服账号
* @return
*/
public String getWorker() {
return worker;
}
public void setWorker(String worker) {
this.worker = worker;
}
}
| sword-org/wechat4j | src/org/sword/wechat4j/csc/Record.java |
64,970 | package model;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
/**
* 聊天群
*
* @author wangfei
* @time 2015-04-02
*/
@Entity
@Table(name = "user_group")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Group {
public static final String GROUP_ID = "groupId";
private int groupId;
private String createrId;
private String groupName;
private List<User> memberList;
public Group() {
}
public Group(String groupName) {
setGroupName(groupName);
}
@Id
@Column(name = "group_id", columnDefinition = "int(8) COMMENT '聊天群Id'")
@GeneratedValue(strategy = GenerationType.AUTO)
public int getGroupId() {
return groupId;
}
public void setGroupId(int groupId) {
this.groupId = groupId;
}
@Column(name = "creater_id", columnDefinition = "char(20) COMMENT '微信号'")
public String getCreaterId() {
return createrId;
}
public void setCreaterId(String createrId) {
this.createrId = createrId;
}
@Column(name = "group_name", columnDefinition = "char(20) COMMENT '聊天群昵称'")
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
@ManyToMany(targetEntity = User.class, cascade = { CascadeType.PERSIST, CascadeType.MERGE })
@JoinTable(name = "group_members", joinColumns = @JoinColumn(name = "group_id"), inverseJoinColumns = @JoinColumn(name = "user_id"))
public List<User> getMemberList() {
return memberList;
}
public void setMemberList(List<User> memberList) {
this.memberList = memberList;
}
public String toString() {
return "GroupId : " + this.groupId
+ "; GroupName : " + this.groupName
+ "; CreaterId : " + this.getCreaterId()
+ "; MemberList : " + this.getMemberList().toString();
}
}
| Feng14/MiniWeChat-Server | src/model/Group.java |
64,971 | package server;
import client.MapleCharacter;
import client.MapleClient;
import client.inventory.IItem;
import client.inventory.ItemFlag;
import client.inventory.MapleInventoryType;
import client.messages.CommandProcessor;
import constants.GameConstants;
import constants.ServerConfig;
import constants.ServerConstants.CommandType;
import handling.channel.ChannelServer;
import handling.world.World;
import tools.FileoutputUtil;
import tools.MaplePacketCreator;
import tools.packet.PlayerShopPacket;
import java.lang.ref.WeakReference;
import java.util.LinkedList;
import java.util.List;
public class MapleTrade {
private MapleTrade partner = null;
private final List<IItem> items = new LinkedList<>();
private List<IItem> exchangeItems;
private int meso = 0, exchangeMeso = 0;
private boolean locked = false;
private final WeakReference<MapleCharacter> chr;
private final byte tradingslot;
public MapleTrade(final byte tradingslot, final MapleCharacter chr) {
this.tradingslot = tradingslot;
this.chr = new WeakReference<>(chr);
}
public final void CompleteTrade() {
final MapleTrade local = chr.get().getTrade();
final MapleTrade partner = local.getPartner();
if (exchangeItems != null) { // just to be on the safe side...
for (final IItem item : exchangeItems) {
byte flag = item.getFlag();
if (ItemFlag.KARMA_EQ.check(flag)) {
item.setFlag((byte) (flag - ItemFlag.KARMA_EQ.getValue()));
} else if (ItemFlag.KARMA_USE.check(flag)) {
item.setFlag((byte) (flag - ItemFlag.KARMA_USE.getValue()));
}
MapleInventoryManipulator.addFromDrop(chr.get().getClient(), item, false);
}
String output = "";
for (IItem item : exchangeItems) {
output += item.getItemId() + "(" + item.getQuantity() + "), ";
}
if ((exchangeMeso - GameConstants.getTaxAmount(exchangeMeso)) >= 50000000) {
FileoutputUtil.logToFile("logs/Data/大额金币交易.txt", FileoutputUtil.NowTime() + "角色名字:" + chr.get().getName() + " 和 " + partner.chr.get().getName() + " 交易获得 金币" + (exchangeMeso - GameConstants.getTaxAmount(exchangeMeso)) + "\r\n");
World.Broadcast.broadcastGMMessage(MaplePacketCreator.serverNotice(6, "[GM密语] " + "大额金币交易 疑似卖游戏币 角色名字:" + chr.get().getName() + " 和 " + partner.chr.get().getName() + " 交易获得 金币" + (exchangeMeso - GameConstants.getTaxAmount(exchangeMeso))));
}
FileoutputUtil.logToFile("logs/Data/交易记录.txt", FileoutputUtil.NowTime() + " 帐号角色名字:" + chr.get().getClient().getAccountName() + " " + chr.get().getName() + " 和 " + partner.chr.get().getClient().getAccountName() + " " + partner.chr.get().getName() + " 交易获得 金币" + (exchangeMeso - GameConstants.getTaxAmount(exchangeMeso)) + " 和 " + exchangeItems.size() + "件物品[" + output + "]\r\n");
World.Broadcast.broadcastGMMessage(MaplePacketCreator.serverNotice(6, "[GM密语] " + "角色名字:" + chr.get().getName() + " 和 " + partner.chr.get().getName() + " 交易获得 金币" + (exchangeMeso - GameConstants.getTaxAmount(exchangeMeso)) + " 和 " + exchangeItems.size() + "件物品[" + output + "]"));
exchangeItems.clear();
}
if (exchangeMeso > 0) {
chr.get().gainMeso(exchangeMeso - GameConstants.getTaxAmount(exchangeMeso), false, true, false);
}
exchangeMeso = 0;
chr.get().getClient().sendPacket(MaplePacketCreator.TradeMessage(tradingslot, (byte) 0x08));
try {
chr.get().saveToDB(false, false);
} catch (Exception ex) {
FileoutputUtil.logToFile("logs/交易存档保存数据异常.txt", "\r\n " + FileoutputUtil.NowTime() + " IP: " + chr.get().getClient().getSession().remoteAddress().toString().split(":")[0] + " 帐号 " + chr.get().getClient().getAccountName() + " 帐号ID " + chr.get().getClient().getAccID() + " 角色名 " + chr.get().getName() + " 角色ID " + chr.get().getId());
FileoutputUtil.outError("logs/交易存档保存数据异常.txt", ex);
System.err.println("封锁出现错误 " + ex);
FileoutputUtil.outError("logs/交易异常.txt", ex);
}
}
public final void cancel(final MapleClient c) {
cancel(c, 0, false);
}
public final void cancel(final MapleClient c, final int unsuccessful, boolean check) {
final MapleTrade local = c.getPlayer().getTrade();
final MapleTrade partners = local.getPartner();
if (local.isLocked() && partners.isLocked()) {
if (!check) {
meso = 0;
items.clear();
}
}
if (items != null) { // just to be on the safe side...
for (final IItem item : items) {
MapleInventoryManipulator.addFromDrop(c, item, false);
}
items.clear();
}
if (meso > 0) {
c.getPlayer().gainMeso(meso, false, true, false);
}
meso = 0;
c.sendPacket(MaplePacketCreator.getTradeCancel(tradingslot, unsuccessful));
}
public final boolean isLocked() {
return locked;
}
public final void setMeso(final int meso) {
if (locked || partner == null || meso <= 0 || this.meso + meso <= 0) {
return;
}
if (chr.get().getMeso() >= meso) {
chr.get().gainMeso(-meso, false, true, false);
this.meso += meso;
chr.get().getClient().sendPacket(MaplePacketCreator.getTradeMesoSet((byte) 0, this.meso));
if (partner != null) {
partner.getChr().getClient().sendPacket(MaplePacketCreator.getTradeMesoSet((byte) 1, this.meso));
}
}
}
public final void addItem(final IItem item) {
if (locked || partner == null) {
return;
}
items.add(item);
chr.get().getClient().sendPacket(MaplePacketCreator.getTradeItemAdd((byte) 0, item));
if (partner != null) {
partner.getChr().getClient().sendPacket(MaplePacketCreator.getTradeItemAdd((byte) 1, item));
}
}
public final void chat(final String message) {
if (partner == null) {
return;
}
if (!CommandProcessor.processCommand(chr.get().getClient(), message, CommandType.TRADE)) {
if (chr.get().getCanTalk()) {
chr.get().dropMessage(-2, chr.get().getName() + " : " + message);
}
if (ServerConfig.LOG_CHAT) {
FileoutputUtil.logToFile("logs/聊天/交易聊天.txt", " " + FileoutputUtil.NowTime() + " IP: " + chr.get().getClient().getSession().remoteAddress().toString().split(":")[0] + " 『" + chr.get().getName() + "』对『" + partner.getChr().getName() + "』的交易聊天: " + message + "\r\n");
}
final StringBuilder sb = new StringBuilder("[GM 密语] 『" + chr.get().getName() + "』对『" + partner.getChr().getName() + "』的交易聊天: " + message);
for (ChannelServer cserv : ChannelServer.getAllInstances()) {
for (MapleCharacter chr_ : cserv.getPlayerStorage().getAllCharactersThreadSafe()) {
if (chr_.get_control_玩家私聊()) {
chr_.dropMessage(sb.toString());
}
}
}
if (partner != null) {
if (chr.get().getCanTalk()) {
partner.getChr().getClient().sendPacket(PlayerShopPacket.shopChat(chr.get().getName() + " : " + message, 1));
}
}
}
}
public final MapleTrade getPartner() {
return partner;
}
public final void setPartner(final MapleTrade partner) {
if (locked) {
return;
}
this.partner = partner;
}
public final MapleCharacter getChr() {
return chr.get();
}
public final int getNextTargetSlot() {
if (items.size() >= 9) {
return -1;
}
int ret = 1; //first slot
for (IItem item : items) {
if (item.getPosition() == ret) {
ret++;
}
}
return ret;
}
public final boolean setItems(final MapleClient c, final IItem item, byte targetSlot, final int quantity) {
int target = getNextTargetSlot();
final MapleItemInformationProvider ii = MapleItemInformationProvider.getInstance();
if (target == -1 || GameConstants.isPet(item.getItemId()) || isLocked() || (GameConstants.getInventoryType(item.getItemId()) == MapleInventoryType.CASH && quantity != 1) || (GameConstants.getInventoryType(item.getItemId()) == MapleInventoryType.EQUIP && quantity != 1)) {
return false;
}
if (ii.isCash(item.getItemId())) {
c.sendPacket(MaplePacketCreator.enableActions());
return false;
}
final byte flag = item.getFlag();
if (ItemFlag.UNTRADEABLE.check(flag) || ItemFlag.LOCK.check(flag)) {
c.sendPacket(MaplePacketCreator.enableActions());
return false;
}
if (ii.isDropRestricted(item.getItemId()) || ii.isAccountShared(item.getItemId())) {
if (!(ItemFlag.KARMA_EQ.check(flag) || ItemFlag.KARMA_USE.check(flag))) {
c.sendPacket(MaplePacketCreator.enableActions());
return false;
}
}
IItem tradeItem = item.copy();
if (GameConstants.isThrowingStar(item.getItemId()) || GameConstants.isBullet(item.getItemId())) {
tradeItem.setQuantity(item.getQuantity());
MapleInventoryManipulator.removeFromSlot(c, GameConstants.getInventoryType(item.getItemId()), item.getPosition(), item.getQuantity(), true);
} else {
tradeItem.setQuantity((short) quantity);
MapleInventoryManipulator.removeFromSlot(c, GameConstants.getInventoryType(item.getItemId()), item.getPosition(), (short) quantity, true);
}
if (targetSlot < 0) {
targetSlot = (byte) target;
} else {
for (IItem itemz : items) {
if (itemz.getPosition() == targetSlot) {
targetSlot = (byte) target;
break;
}
}
}
tradeItem.setPosition(targetSlot);
addItem(tradeItem);
return true;
}
private int check() { //0 = fine, 1 = invent space not, 2 = pickupRestricted
if (chr.get().getMeso() + exchangeMeso < 0) {
return 1;
}
final MapleItemInformationProvider ii = MapleItemInformationProvider.getInstance();
byte eq = 0, use = 0, setup = 0, etc = 0, cash = 0;
for (final IItem item : exchangeItems) {
switch (GameConstants.getInventoryType(item.getItemId())) {
case EQUIP:
eq++;
break;
case USE:
use++;
break;
case SETUP:
setup++;
break;
case ETC:
etc++;
break;
case CASH: // Not allowed, probably hacking
cash++;
break;
}
if (ii.isPickupRestricted(item.getItemId()) && chr.get().getInventory(GameConstants.getInventoryType(item.getItemId())).findById(item.getItemId()) != null) {
return 2;
} else if (ii.isPickupRestricted(item.getItemId()) && chr.get().haveItem(item.getItemId(), 1, true, true)) {
return 2;
}
}
if (chr.get().getInventory(MapleInventoryType.EQUIP).getNumFreeSlot() < eq || chr.get().getInventory(MapleInventoryType.USE).getNumFreeSlot() < use || chr.get().getInventory(MapleInventoryType.SETUP).getNumFreeSlot() < setup || chr.get().getInventory(MapleInventoryType.ETC).getNumFreeSlot() < etc || chr.get().getInventory(MapleInventoryType.CASH).getNumFreeSlot() < cash) {
return 1;
}
return 0;
}
public final static void completeTrade(final MapleCharacter c) {
final MapleTrade local = c.getTrade();
final MapleTrade partner = local.getPartner();
if (partner == null || local.locked) {
return;
}
local.locked = true; // Locking the trade
partner.getChr().getClient().sendPacket(MaplePacketCreator.getTradeConfirmation());
partner.exchangeItems = local.items; // Copy this to partner's trade since it's alreadt accepted
partner.exchangeMeso = local.meso; // Copy this to partner's trade since it's alreadt accepted
if (partner.isLocked()) { // Both locked
int lz = local.check(), lz2 = partner.check();
if (lz == 0 && lz2 == 0) {
local.CompleteTrade();
partner.CompleteTrade();
} else {
// NOTE : IF accepted = other party but inventory is full, the item is lost.
partner.cancel(partner.getChr().getClient(), lz == 0 ? lz2 : lz, true);
local.cancel(c.getClient(), lz == 0 ? lz2 : lz, true);
}
partner.getChr().setTrade(null);
c.setTrade(null);
if (local.getChr().getClient().getAccID() == partner.getChr().getClient().getAccID()) {
local.getChr().ban("修改数据包 - 同帐号角色交易", true, true, false);
partner.getChr().ban("修改数据包 - 同帐号角色交易", true, true, false);
FileoutputUtil.logToFile("logs/Hack/ban/交易异常.txt", "时间: " + FileoutputUtil.NowTime() + " IP: " + local.getChr().getClient().getSessionIPAddress() + " MAC: " + local.getChr().getNowMacs() + " " + local.getChr().getName() + " 和 " + partner.getChr().getName() + " 为同个帐号的角色且进行交易\r\n");
local.getChr().getClient().getSession().close();
partner.getChr().getClient().getSession().close();
}
}
}
public static final void cancelTrade(final MapleTrade Localtrade, final MapleClient c) {
Localtrade.cancel(c);
final MapleTrade partner = Localtrade.getPartner();
if (partner != null && partner.getChr() != null) {
if (partner.getChr().getClient() != null) {
partner.cancel(partner.getChr().getClient());
}
partner.getChr().setTrade(null);
}
if (Localtrade.chr.get() != null) {
Localtrade.chr.get().setTrade(null);
}
}
public static final void startTrade(final MapleCharacter c) {
if (c.getTrade() == null) {
c.setTrade(new MapleTrade((byte) 0, c));
c.getClient().sendPacket(MaplePacketCreator.getTradeStart(c.getClient(), c.getTrade(), (byte) 0));
} else {
c.getClient().sendPacket(MaplePacketCreator.serverNotice(5, "您目前已经在交易了"));
}
}
public static final void inviteTrade(final MapleCharacter c1, final MapleCharacter c2) {
if (World.isShutDown) {
c1.getTrade().cancel(c1.getClient(), 1, false);
c1.setTrade(null);
c1.getClient().sendPacket(MaplePacketCreator.serverNotice(5, "目前无法交易。"));
return;
}
if (c1 == null || c1.getTrade() == null || c2 == null) {
return;
}
if (c2.getPlayerShop() != null) {
c1.getTrade().cancel(c1.getClient(), 1, false);
c1.setTrade(null);
c1.getClient().sendPacket(MaplePacketCreator.serverNotice(5, "对方正在忙碌中。"));
return;
}
if (c1.getTrade().getPartner() != null) {
c1.getClient().sendPacket(MaplePacketCreator.serverNotice(5, "对方正在忙碌中。"));
c1.getClient().sendPacket(MaplePacketCreator.enableActions());
return;
}
if (c2.getTrade() == null && c1.getTrade().getPartner() == null) {
c2.setTrade(new MapleTrade((byte) 1, c2));
c2.getTrade().setPartner(c1.getTrade());
c1.getTrade().setPartner(c2.getTrade());
c2.getClient().sendPacket(MaplePacketCreator.getTradeInvite(c1));
} else {
c1.getClient().sendPacket(MaplePacketCreator.serverNotice(5, "另一位玩家正在交易中"));
}
}
public static final void visitTrade(final MapleCharacter c1, final MapleCharacter c2) {
if (c1.getTrade() != null && c1.getTrade().getPartner() == c2.getTrade() && c2.getTrade() != null && c2.getTrade().getPartner() == c1.getTrade()) {
// We don't need to check for map here as the user is found via MapleMap.getCharacterById()
c2.getClient().sendPacket(MaplePacketCreator.getTradePartnerAdd(c1));
c1.getClient().sendPacket(MaplePacketCreator.getTradeStart(c1.getClient(), c1.getTrade(), (byte) 1));
// c1.dropMessage(-2, "System : Use @tradehelp to see the list of trading commands");
// c2.dropMessage(-2, "System : Use @tradehelp to see the list of trading commands");
} else {
c1.getClient().sendPacket(MaplePacketCreator.serverNotice(5, "交易已经被关闭."));
}
}
public static final void declineTrade(final MapleCharacter c) {
final MapleTrade trade = c.getTrade();
if (trade != null) {
if (trade.getPartner() != null) {
MapleCharacter other = trade.getPartner().getChr();
if (other != null) {
other.getTrade().cancel(other.getClient());
other.setTrade(null);
other.dropMessage(5, c.getName() + " 拒绝了你的邀请.");
}
}
trade.cancel(c.getClient());
c.setTrade(null);
}
}
}
| huangshushu/ZLHSS2 | src/server/MapleTrade.java |
64,972 | import java.io.*;
import java.net.*;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.*;
import java.nio.charset.*;
import java.text.*;
public class Client {
//建立客户端
public static Socket client=null;
//消息接收者uid
public static StringBuilder uidReceiver = null;
public static void main(String[] args) throws Exception{
//创建客户端窗口对象
ClientFrame cframe = new ClientFrame();
//窗口关闭键无效,必须通过退出键退出客户端以便善后
cframe.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
//获取本机屏幕横向分辨率
int w = Toolkit.getDefaultToolkit().getScreenSize().width;
//获取本机屏幕纵向分辨率
int h = Toolkit.getDefaultToolkit().getScreenSize().height;
//将窗口置中
cframe.setLocation((w - cframe.WIDTH)/2, (h - cframe.HEIGHT)/2);
//设置客户端窗口为可见
cframe.setVisible(true);
try {
//连接服务器
client = new Socket(InetAddress.getLocalHost(), 6666);
//获取输入输出流
InputStream in = client.getInputStream();
OutputStream out = client.getOutputStream();
//获取服务端欢迎信息
byte[] bytes = new byte[1024];
int len = in.read(bytes);
//将服务端发来的连接成功信息打印在聊天消息框
cframe.jtaChat.append(new String(bytes, 0, len));
cframe.jtaChat.append("\n");
//持续等待服务器信息直至退出
while (true) {
//读取服务器发来的信息
in = client.getInputStream();
len = in.read(bytes);
// System.out.println(len);
//处理服务器传来的消息
String msg = new String(bytes, 0, len);
//获取消息类型:更新在线名单或者聊天
String type = msg.substring(0, msg.indexOf("/"));
//消息本体:更新后的名单或者聊天内容
String chat = msg.substring(msg.indexOf("/")+1);
//根据消息类型分别处理
//更新在线名单
if (type.equals("OnlineListUpdate")) {
//提取在线列表的数据
DefaultTableModel dtm = (DefaultTableModel) cframe.jtbOnline.getModel();
//清除在线名单列表
dtm.setRowCount(0);
//更新在线列表
String[] onlineList = chat.split(",");
for (String member : onlineList) {
//保存在线成员的IP、端口号
String[] tmp = new String[3];
//自己不能在列表里
String me=member.substring(member.indexOf("~") + 1);
if (me.equals(InetAddress.getLocalHost().getHostAddress() + ":" + client.getLocalPort())) {
continue;
}
//获取成员信息
tmp[0]="";
tmp[1] = member.substring(0, member.indexOf(":"));
tmp[2] = member.substring(member.indexOf(":") + 1);
//在在线列表中添加在线者信息
dtm.addRow(tmp);
}
//提取在线列表的渲染模型
DefaultTableCellRenderer tbr = new DefaultTableCellRenderer();
//表格数据居中显示
tbr.setHorizontalAlignment(JLabel.CENTER);
//设置单元格的渲染器为复选框
cframe.jtbOnline.setDefaultRenderer(Object.class, tbr);
}
//聊天
else if (type.equals("Chat")) {
//获取发送信息者和信息内容
String sender = chat.substring(0, chat.indexOf("/"));
String word = chat.substring(chat.indexOf("/") + 1);
//在聊天窗打印聊天信息
cframe.jtaChat.append(cframe.sdf.format(new Date()) + "\n来自 " + sender + ":\n" + word + "\n\n");
//显示最新消息
//这个方法只是一个观察文本的字段的功能显示,参数指明观察的位置
// 但注意一定不能超出文本的总长度,因为不可能在文本外观察到文本的字段,所以会抛出异样
cframe.jtaChat.setCaretPosition(cframe.jtaChat.getDocument().getLength());
}
}
}catch(Exception e)
{
cframe.jtaChat.append("服务器挂了.....\n");
e.printStackTrace();
}
}
}
| HLHL1/chatRoom | com/miter/Client.java |
64,973 | package com.rsc.yim.plugin;
import android.util.Log;
import com.netease.nim.uikit.NimUIKit;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.auth.AuthService;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.netease.nim.uikit.session.activity.P2PMessageActivity;
import com.netease.nim.uikit.session.activity.TeamMessageActivity;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* This class echoes a string called from JavaScript.
*/
public class yimPlugin extends CordovaPlugin {
CallbackContext callback;
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
callback = callbackContext;
if (action.equals("login")) { // 登录
PluginResult result = null;
String userName = args.getString(0);
String passWord = args.getString(1);
if (userName == null || userName.equals("") || userName.equals("null") ||
passWord == null || passWord.equals("") || passWord.equals("null")) {
result = new PluginResult(PluginResult.Status.ERROR, "请输入用户名或密码");
callback.sendPluginResult(result);
return false;
}
// // 调用云信sdk登陆方法登陆聊天服务器
// LoginInfo info = new LoginInfo(userName, passWord); //账号 密码
// RequestCallback<LoginInfo> callback_netease = new RequestCallback<LoginInfo>() {
// @Override
// public void onSuccess(LoginInfo param) {
// Log.i("SQW", "登陆聊天服务器成功!");
// // 启动单聊界面
// // NimUIKit.startP2PSession( yimPlugin.this.cordova.getActivity().getApplication() , "单聊对方ID");
// // NimUIKit.startTeamSession(MainActivity.this, "群聊 群ID");
// }
//
// @Override
// public void onFailed(int code) {
// Log.i("SQW", "登陆聊天服务器失败,code=" + code);
// }
//
// @Override
// public void onException(Throwable exception) {
// Log.i("SQW", "登陆聊天服务器异常");
// }
// };
//
// NIMClient.getService(AuthService.class).login(info).setCallback(callback_netease);//进行登录
LoginInfo info = new LoginInfo(userName, passWord); //账号 密码
NimUIKit.doLogin(info, new RequestCallback<LoginInfo>() {
@Override
public void onSuccess(LoginInfo loginInfo) {
Log.i("SQW","登陆成功");
}
@Override
public void onFailed(int i) {
Log.i("SQW","登陆失败: "+i);
}
@Override
public void onException(Throwable throwable) {
Log.i("SQW","登陆异常");
}
});
result = new PluginResult(PluginResult.Status.OK, "userName: " + userName + "/" + "passWord: " + passWord);
callback.sendPluginResult(result);
return true;
} else if (action.equals("chat")) { // 聊天
PluginResult result = null;
String touserName = args.getString(0);
int chatType = args.getInt(1);
if (touserName == null || touserName.equals("") || touserName.equals("null")) {
result = new PluginResult(PluginResult.Status.ERROR, "请输入用户名");
callback.sendPluginResult(result);
return false;
}
if (chatType == 0){ // 单聊
NimUIKit.startP2PSession(yimPlugin.this.cordova.getActivity().getApplication(), touserName);
}else if (chatType == 1){ // 群聊
NimUIKit.startTeamSession(yimPlugin.this.cordova.getActivity().getApplication(), touserName);
}
result = new PluginResult(PluginResult.Status.OK, "touserName: " + touserName);
callback.sendPluginResult(result);
return true;
}else if (action.equals("addNavigationToHtmlListener")) { // 从原生界面返回web界面的监听 需要注册
PluginResult result = null;
// 注册通知
EventBus.getDefault().register((CordovaPlugin) this);// 注册
result = new PluginResult(PluginResult.Status.OK, "注册监听成功");
callback.sendPluginResult(result);
return true;
}
return false;
}
/**
* 接收通知 (聊天界面关闭时 单聊)
* @param event
*/
@Subscribe(threadMode = ThreadMode.MAIN) // 在ui线程执行
public void onSendP2PMessageActivityFinishEvent(P2PMessageActivity.SendP2PMessageActivityFinishEvent event) {
String format = "cordova.plugins.yimPlugin.onNavigationToHtmlCallBack(%s);";
JSONObject jExtras = new JSONObject();
String userid = event.getToUserID();
String type = "normal";
try {
jExtras.put("type", type);
jExtras.put("user_id", userid);
jExtras.put("data", "{}");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
final String js = String.format(format, jExtras.toString());
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
webView.loadUrl("javascript:" + js);
}
});
}
/**
* 接收通知 (聊天界面关闭时 群聊)
* @param event
*/
@Subscribe(threadMode = ThreadMode.MAIN) // 在ui线程执行
public void onSendTeamMessageActivityFinishEvent(TeamMessageActivity.SendTeamMessageActivityFinishEvent event) {
String format = "cordova.plugins.yimPlugin.onNavigationToHtmlCallBack(%s);";
JSONObject jExtras = new JSONObject();
String userid = event.getToUserID();
String type = "normal";
try {
jExtras.put("type", type);
jExtras.put("user_id", userid);
jExtras.put("data", "{}");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
final String js = String.format(format, jExtras.toString());
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
webView.loadUrl("javascript:" + js);
}
});
}
}
| shenqiwen/cordova-plugin-uikit | src/android/yimPlugin.java |
64,974 | /*
需求:使用java类描述一个社交账号
问题:性别出现了问题
根本的原因:由于其他人可以直接操作sex属性,可以sex属性进行直接的赋值
面向对象的三大特征:
1)封装;
2)继承;
3)多态
封装:
1)使用private修饰需要被封装的属性
2)提供一个公共的方法设置或者是获取该私有的成员变量
命名规范:
set属性名()
get属性名()
权限修饰符:权限修饰符就是控制变量或者是方法的可见范围
public:公共的。public修饰的成员变量或者是方法任何人都可以直接访问的
private:私有的。private修饰的成员变量或者是方法只能在本类中进行直接访问
*/
class Account{
// 用户名 性别
private String username;
private String sex;
public void setSex(String s) {
if (s.equals("男") || s.equals("女")) { // 注意:如果比较两个字符串中的内容是否相同,不要使用==
// 而是使用equals方法
sex = s;
System.out.println("设置性别成功");
} else {
sex = "男";
System.out.println("您的输入不符合规范");
}
}
public void setUsername(String name) {
username = name;
}
public String getUsername() {
return username;
}
public String getSex() {
return sex;
}
// 聊天
public void talk() {
System.out.println("聊得很开心");
}
}
public class Demo6{
public static void main(String[] args) {
Account a = new Account();
/*
a.username = "Adolph";
a.sex = "不男不女";
System.out.println("username:" + a.username +" sex:" + a.sex);
*/
a.setUsername("Adolph");
a.setSex("不男不女");
String name = a.getUsername();
String sex = a.getSex();
System.out.println("name:" + name);
System.out.println("sex:" + sex);
}
} | lwstudio/AndroidClass | JavaSE/day04/code/Demo6.java |
64,975 | package client;
import javax.swing.*;
import common.Account;
import java.awt.*;
import java.util.ArrayList;
public class MenuGui {
private JFrame frame;
private DefaultListModel<Account> listModel;
public JList<Account> friendList;
public JButton chatBtn;
/**
* Launch the application.
*/
public static void main(String[] args) {
new MenuGui().run();
}
public void run() {
try {
this.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
public void close() {
frame.setVisible(false);
}
/**
* Create the application.
*/
public MenuGui() {
initialize();
}
/**
* Update friend list
* @param friendList
*/
public void updateFriend(ArrayList<Account> friendList) {
for (Account u : friendList) {
listModel.addElement(u);
}
}
public Account getFriend() {
return friendList.getSelectedValue();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
listModel = new DefaultListModel<>();
listModel.addElement(new Account(null, null, "<隨機配對>"));
friendList = new JList<Account>(listModel);
chatBtn = new JButton("聊天");
frame.getContentPane().add(new JLabel("好友名單"), BorderLayout.NORTH);
frame.getContentPane().add(new JScrollPane(friendList), BorderLayout.CENTER);
frame.getContentPane().add(chatBtn, BorderLayout.SOUTH);
}
}
| andy920262/java-chatroom | src/client/MenuGui.java |
64,976 | package javacore.net.day23;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
/**
* 网络编程(UDP-聊天)<br>
* <p>
* 编写一个聊天程序。<br>
* 有收数据的部分,和发数据的部分。<br>
* 这两部分需要同时执行。<br>
* 那就需要用到多线程技术。<br>
* 一个线程控制收,一个线程控制发。<br>
* <p>
* 因为收和发的动作是不一致的,所以要定义两个run()方法。<br>
* 而且这两个方法要封装到不同的类中。<br>
*
* @author [email protected]
* @see 传智播客毕向东Java基础视频教程-day23-10-网络编程(UDP-聊天)
*/
public class ChatDemo {
public static void main(String[] args) throws IOException {
DatagramSocket sendSocket = new DatagramSocket();
DatagramSocket receSocket = new DatagramSocket(10002);
new Thread(new Send(sendSocket)).start();
new Thread(new Rece(receSocket)).start();
}
}
class Send implements Runnable {
private DatagramSocket ds;
Send(DatagramSocket ds) {
this.ds = ds;
}
@Override
public void run() {
try {
BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
String line = null;
while ((line = bufr.readLine()) != null) {
if ("886".equals(line)) {
break;
}
byte[] buf = line.getBytes();
DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getByName("192.158.159.1"), 10002);
ds.send(dp);
}
} catch (Exception e) {
throw new RuntimeException("发送端失败");
}
}
}
class Rece implements Runnable {
private DatagramSocket ds;
Rece(DatagramSocket ds) {
this.ds = ds;
}
@Override
public void run() {
while (true) {
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, buf.length);
try {
ds.receive(dp);
String ip = dp.getAddress().getHostAddress();
String data = new String(dp.getData(), 0, dp.getLength());
System.out.println(ip + "::" + data);
} catch (IOException e) {
throw new RuntimeException("接收端失败");
}
}
}
} | xiaguliuxiang/java-core | src/javacore/net/day23/ChatDemo.java |
64,977 | package com.test.yxq.yxq_media_player.beans;
/**
* Created by Administrator on 2016/5/20.
*/
public class MyMessage {
public int type; // 消息类型 0:系统 1:聊天 2:礼物
public SystemMessage sm; //系统消息
public ChatMessage cm; // 聊天消息
public GiftMessage gm; // 礼物消息
public MyMessage(int type, SystemMessage sm, ChatMessage cm, GiftMessage gm) {
this.type = type;
this.sm = sm;
this.cm = cm;
this.gm = gm;
}
}
| yq8308/yxq_media_player | yxq_media_player/beans/MyMessage.java |
64,978 | package View;
import Controller.Entrance_Static;
import Model.BaseForm;
import Model.MyException;
import Model.User;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.SimpleDateFormat;
/**
* @author xiell
*/
public class ChatForm extends BaseForm {
/**
* 当前聊天好友的ID号
*/
private String chatID;
/**
* 获取发送消息时间
*/
private SimpleDateFormat df;
/**
* 对话消息记录
*/
private static String message;
private static JTextArea textArea;
private JTextField text;
private JButton btnSent;
private JScrollPane scrollPane;
public ChatForm() {
super("聊天");
//富文本框用来显示聊天记录
textArea = new JTextArea();
//设置为只读
textArea.setEditable(false);
textArea.setBounds(0, 0, 350, 400);
//激活自动换行
textArea.setLineWrap(true);
//激活断行不断字
textArea.setWrapStyleWord(true);
textArea.setFont(new Font("标楷体", Font.BOLD, 12));
//设置滚动条
scrollPane = new JScrollPane(textArea);
scrollPane.setBounds(0, 0, 350, 400);
super.panel.add(scrollPane);
text = new JTextField();
text.setBounds(1, 401, 250, 60);
super.panel.add(text);
btnSent = new JButton("发送");
btnSent.setBounds(253, 401, 80, 60);
super.panel.add(btnSent);
df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
btnSent.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
try {
Entrance_Static.client.isSent(chatID, text.getText());
setMessage(df.format(System.currentTimeMillis()) + "\n" + User.getName() + "(我):" + text.getText() + "\n");
text.setText("");
} catch (MyException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), "错误", JOptionPane.CLOSED_OPTION);
ex.printStackTrace();
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "不可知异常,请让技术人员来处理!", "错误", JOptionPane.CLOSED_OPTION);
ex.printStackTrace();
}
}
});
}
/**
* 设置聊天框内容
*/
public void setStyle(String title, String chatID, String message) {
frame.setTitle(title);
frame.setBounds(100, 100, 350, 500);
this.chatID = chatID;
ChatForm.message = message;
textArea.setText(message);
text.setText("");
}
public static void setMessage(String s) {
message += s;
textArea.setText(message);
}
}
| fishdive/IM | IMform/src/View/ChatForm.java |
64,979 | package net;
//消息结构类型名称定义
public class MSGTYPE {
public final static String broadcastUrl = "cc.broadcast.client"; //广播接收注册id
public static final int BEATS = -5; //心跳
public static final int LOG = -4;
public static final int CLOSE = -3;
public static final int TOAST = -2;
public final static int ERROR = -1; //错误
public final static int OK = 0; //成功
//////////////////////////////////////////////////////////////////////
public final static int PROFILE_PATH_BY_ID = 1; //获取头像,
public final static int LOGIN_BY_ID_PWD = 2; //登陆,id, pwd
public static final int REGISTE_BY_USERNAME_EMAIL_SEX_PWD = 3; //注册
public static final int FIND_USERS_GROUPS_BY_ID = 4; //查询 cc群 cc用户 列表
public static final int GET_USER_GROUP_DETAIL_BY_TYPE_ID = 5; //查询群/用户详情
public static final int ADD_USER_GROP_BY_TYPE_ID_YANZHEN_NICKNAME = 6; //添加好友/群操作
public static final int CONTACT_USER_GROUP_MAP = 7; //服务器发送过来的 好友列表map
public static final int GET_USER_GROUP_CHAT_BY_TYPE_ID_START = 8; //聊天消息获取,并添加会话列表记录
public static final int ADD_CHAT_SESSION_BY_TYPE_ID = 9; //聊天会话 添加
public static final int GET_CHAT_SESSIONS = 10; //获取会话列表
public static final int UPDATE_NICKNAME_BY_ID_NICKNAME_GROUPID = 11; //更新昵称
public static final int SEND_CHATMSG_BY_GTYPE_TOID_TYPE_TIME_MSG = 12; //发送消息,收到消息
public static final int SEND_CHATMSG_RESULT = 13; //发送消息结果 true false 发送成功失败,发送时间作为标志
public static final int UPDATE_BY_USERNAME_SIGN_SEX_OLDPWD_NEWPWD = 14; //更新用户信息,密码可选
public static final int RESULT_USER_GROP_BY_TYPE_ID_RESULT_NICKNAME = 15; //同意/拒绝添加好友/群组
public static final int UPDATE_PROFILE_BY_ID_TYPE = 16; //更新头像等图片数据
public static final int LINE_STATUS_ID_TYPE = 17; //上线通知,下线通知
public static final int CREATE_GROUP_BY_NAME_NUM_CHECK = 18; //创建/更新群?讨论组?
public static final int UPDATE_GROUP_BY_ID_NAME_SIGN_NUM_CHECK = 19; // 更新群?讨论组?
public static final int FIND_USERS_BY_GROUPID = 20; //查询 cc群 cc用户 列表
public static final int GET_USER_GROUP_CHAT_BY_TYPE_ID_START_HISTORY = 21; //聊天消息获取,并添加会话列表记录
public static final int REMOVE_CHAT_SESSION_BY_ID = 22; //删除会话
public static final int TURN_DELETE_RELEATIONSHIP_BY_GROUPNAME = 97;//被踢出群
public static final int TURN_DELETE_RELEATIONSHIP_BY_FRIENDNAME = 98;//被删除好友
public static final int DELETE_RELEATIONSHIP_BY_GROUPID_USERID = 99;//踢出群
public static final int DELETE_RELEATIONSHIP_BY_TYPE_ID = 100;//删除关系
////////////////////////////////////////////////////////////////////////////
//匿名模块消息,用户只能加入一个聊天室,返回即退出,文本消息不存储,可是语音呢,图片呢?暂缓到聊天室关闭删除, 私聊功能?
public static final int DOLL_CREATE_BY_NAME_NUM = 200;//创建聊天室,name,num
public static final int DOLL_INTO_BY_NAME = 201;//加入聊天室
public static final int DOLL_CHAT_BY_TONAME_TYPE_MSG = 202;//聊天
public static final int DOLL_EXIT = 203;//退出聊天室
public static final int DOLL_ROOM_LIST = 204;//聊天室 列表
public static final int DOLL_ROOM_UPDATE_BY_NAME = 205;//聊天室 刷新
public static final int DOLL_IN_OR_OUT_BY_NAME_TYPE = 206;//某房间进入退出房间信息
///////////////////////////////////////////////////////////////////
//图片传输监控模块
public static final int SYS_DECT_ON = 300;//检测提醒
public static final int SYS_PHOTO = 301;//图片数据
public static final int SYS_PHOTO_DETAIL = 302;//图片大数据
}
| 1424234500/cc | app/src/main/java/net/MSGTYPE.java |
64,980 | package chatbot;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
@WebService
@SOAPBinding(style = SOAPBinding.Style.RPC)
public interface 聊天接口 {
@WebMethod String 回答(String 听到的);
} | nobodxbodon/java_in_hours_chn | chatbot/聊天接口.java |
64,981 | package com.qq.client;
import com.qq.common.Message;
import com.qq.common.MessageType;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Date;
public class ClientChatView extends JFrame implements ActionListener{
JTextArea jta;
JTextField jtf;
JButton jb,jb2;
JPanel jp;
JScrollPane jsp;
JFileChooser fc;
private String ownerId;
private String friendId;
public String getOwnerId(){
return ownerId;
}
public void setOwnerId(String ownerId){
this.ownerId = ownerId;
}
public String getFriendId(){
return friendId;
}
public void setFriendId(String friendId) {
this.friendId = friendId;
}
public void showMessage(Message m){
String info = null;
if (m.getMesType().equals(MessageType.MESSAGE_FILE)){
info ="文件: "+m.getFile().getName()+" 接受成功\r\n";
}
else {
info = m.getSender() + "对" + m.getGetter() + "说:" + m.getContent() + "\r\n";
}
jta.append(info);
}
public ClientChatView(String ownerId,String friendId){
this.ownerId = ownerId;
this.friendId = friendId;
jta = new JTextArea();
jtf = new JTextField(20);
jsp = new JScrollPane(jta);
jb = new JButton("发送");
jb2 = new JButton("文件");
fc = new JFileChooser();
jb2.addActionListener(this);
jp = new JPanel();
jb.addActionListener(this);
jp.add(jb2);
jp.add(jtf);
jp.add(jb);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
super.windowClosing(e);
ManageQQChat.removeQQChat(ownerId+" "+friendId);
}
});
add(jsp,"Center");
add(jp,"South");
setIconImage(new ImageIcon("images/icon.jpg").getImage());
setTitle(this.getOwnerId()+"和"+this.getFriendId()+"聊天");
setSize(400,300);
setLocationRelativeTo(null);
setVisible(true);
//setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent e){
if(e.getSource() == jb){//发送消息
Message m = new Message();
m.setSender(this.ownerId);
m.setGetter(this.friendId);
m.setContent(jtf.getText());
m.setMesType(MessageType.MESSAGE_COMM);
m.setSendTime(new Date().toString());
String info = m.getSender()+"对"+m.getGetter()+"说:"+m.getContent()+"\r\n";
jta.append(info);
jtf.setText("");
try{
ObjectOutputStream oos = new ObjectOutputStream(ManageClientConServerThread.getClientServerThread(this.ownerId).getS().getOutputStream());
oos.writeObject(m);
} catch (IOException e1){
e1.printStackTrace();
}
}
else if (e.getSource() == jb2){//文件传输功能
int select = fc.showOpenDialog(this);
if(select == JFileChooser.APPROVE_OPTION){//选择的是否为确认
File file = fc.getSelectedFile();
System.out.println("文件"+file.getName()+" 被打开");
Message m = new Message();
m.setSender(this.ownerId);
m.setGetter(this.friendId);
m.setMesType(MessageType.MESSAGE_FILE);
m.setSendTime(new Date().toString());
m.setFile(file);
String info = m.getSender()+" 给 "+m.getGetter()+"传输文件: "+file.getName()+"\r\n";
jta.append(info);
jtf.setText("");
try{
ObjectOutputStream oos = new ObjectOutputStream(ManageClientConServerThread.getClientServerThread(this.ownerId).getS().getOutputStream());
oos.writeObject(m);
} catch (IOException e1){
e1.printStackTrace();
}
}
}
}
//public static void main(String[] args){
// ClientChatView c = new ClientChatView("33","22");
//}
}
| MorpheusCheng/myQQ | src/com/qq/client/ClientChatView.java |
64,982 | package com.ouser.util;
import android.os.Environment;
import com.ouser.OuserApplication;
public class Const {
/** startyActivityForResult中的request code */
public static class RequestCode {
// 不关注,仅仅占位
public static final int AnyOne = 0;
// 从相册获取照片
public static final int PhotoFromAlbum = 1000;
// 拍照过去照片
public static final int PhotoFromCamera = 1001;
// 剪裁照片
public static final int PhotoCrop = 1002;
// 地图位置选择
public static final int Location = 1003;
// 发布友约
public static final int PublishAppoint = 1004;
// 友约详情
public static final int AppointDetail = 1005;
// 聊天
public static final int Chat = 1006;
}
/** intent中的extra的key */
public static class Intent {
/** ouser的uid */
public static final String Uid = "uid";
/** ouser的昵称 */
public static final String NickName = "nickname";
/** 聊天对象的id */
public static final String ChatId = "chatid";
/** 友约对象 */
public static final String Appoint = "appoint";
/** 友约发布者uid */
public static final String PublisherUid = "publisheruid";
/** 友约内容 */
public static final String AppointContent = "aname";
/** 针对不同页有不同的含义 */
public static final String Type = "type";
/** 转到top时需要选择的页面 */
public static final String SwitchPage = "page";
}
public static class DefaultValue {
public static final int Age = -1;
public static final int Time = -1;
public static final int Distance = -1;
}
public static class SharedPreferenceKey {
public static final String DefaultName = "ouser";
public static final String FirstStartup = "v1_0_first";
}
/** 升级服务器地址 */
public static final String UpgradeServer = "http://ouser.zhengre.com/upgrade";
public static OuserApplication Application = null;
// 调试
public static final boolean FakeProtocol = false;
public static final String WorkDir = Environment
.getExternalStorageDirectory().getAbsolutePath() + "/ouser/";
// 地图缩放
public static final int MapZoom = 16;
public static final int PoiResultCount = 25;
public static final int PoiSearchRaduis = 5 * 1000;
/**
* time
*/
public static final int MessageCountInterval = 5;
public static final int MessageChatInterval = 10;
/** 消息会话间隔 */
public static final int SessionInterval = 15 * 60 * 1000;
/** 语音聊天的最小间隔 */
public static final int ChatVoiceMinDuring = 1000;
/** 两次点击back退出应用的最小应用 */
public static final int ExitAppClickBackMinInterval = 2000;
/**
* limit
*/
/** 获取藕丝每次获取的条数 */
public static final int OuserFetchCount = 20;
/** 所有友约每次获取的条数 */
public static final int AppointsFetchCount = 20;
/** 动态每次获取条数 */
public static final int TimelineFetchCount = 20;
/** 消息每次获取条数 */
public static final int MessagFetchCount = 20;
/**
* cache
*/
/** 照片下载最大失败次数 */
public static final int PhotoMaxTryTime = 3;
/** 藕丝数据的失效时间间隔,毫秒 */
public static final int OuserInvalidTimeout = 5 * 60 * 1000;
}
| tassadar2002/ouser | src/com/ouser/util/Const.java |
64,983 | package com.xk.chatlogs;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.ImageLoader;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.xk.bean.ImageNode;
import com.xk.bean.ImageNode.TYPE;
import com.xk.chatlogs.interfaces.IChatLogChain;
import com.xk.pojo.WechatLogPojo;
import com.xk.utils.Constant;
import com.xk.utils.ImageCache;
import com.xk.utils.JSONUtil;
import com.xk.utils.SWTTools;
/**
* 用途:聊天记录
*
* @author xiaokui
* @date 2017年1月3日
*/
public class ChatLog {
public Long seqNum;
public String msgid;
public Long newMsgId;
public Integer msgType;
public String imgPath;
public String relatedPath;
public String content;
public String fromId;
public String toId;
public String url;
public Long createTime;
public Integer voiceLength;
@JsonIgnore
public Map<String, Object> recommendInfo;
@JsonIgnore
public ImageNode img;
@JsonIgnore
public File file;
@JsonIgnore
public int persent = 0;
@JsonIgnore
public boolean recalled = false;
@JsonIgnore
public boolean sent = true;
/**
* 创建普通聊天记录
* 作者 :肖逵
* 时间 :2019年8月31日 下午12:44:14
* @param msg
* @param to
* @return
*/
public static ChatLog createSimpleLog(String msg, String to) {
ChatLog log = new ChatLog();
log.createTime = System.currentTimeMillis();
log.toId = to;
log.fromId = Constant.user.UserName;
log.msgType = 1;
log.content = msg;
return log;
}
/**
* 创建文件发送接收记录
* 作者 :肖逵
* 时间 :2019年8月31日 下午12:44:27
* @param file
* @param to
* @return
*/
public static ChatLog createFileLog(File file, String to) {
ChatLog log = new ChatLog();
log.createTime = System.currentTimeMillis();
log.toId = to;
log.fromId = Constant.user.UserName;
log.msgType = 6;
log.content = "[" + file.getName() + "]";
log.file = file;
return log;
}
/**
* 创建图片聊天记录
* 作者 :肖逵
* 时间 :2019年8月31日 下午12:44:42
* @param file
* @param to
* @return
*/
public static ChatLog createImageLog(File file, String to) {
ChatLog log = new ChatLog();
log.sent = false;
log.createTime = System.currentTimeMillis();
log.toId = to;
log.fromId = Constant.user.UserName;
log.msgType = 3;
log.content = "[图片]";
log.file = file;
ImageLoader loader = new ImageLoader();
loader.load(file.getAbsolutePath());
ImageData data = loader.data[0];
ImageNode node = new ImageNode(TYPE.IMAGE, new Image(null, loader.data[0]), loader, null);
log.img = node;
//图片宽高固定不能超过200
if(data.width > 200 || data.height > 200) {
if(data.width > data.height) {
Integer w = 200;
Integer h = (int) (data.height * 200D / data.width);
log.img.setImg(SWTTools.scaleImage(data, w, h));
}else {
Integer h = 200;
Integer w = (int) (data.width * 200D / data.height);
log.img.setImg(SWTTools.scaleImage(data, w, h));
}
}
return log;
}
/**
* 用途:从服务器返回的数据转化成记录
* @date 2017年1月3日
* @param msg
* @return
*/
public static ChatLog fromMap(Map<String, Object> msg) {
ChatLog log = new ChatLog();
log.msgid = (String) msg.get("MsgId");
log.newMsgId = (Long) msg.get("NewMsgId");
log.msgType = (Integer) msg.get("MsgType");
log.content = (String) msg.get("Content");
log.fromId = (String) msg.get("FromUserName");
log.toId = (String) msg.get("ToUserName");
log.url = (String) msg.get("Url");
log.voiceLength = (Integer) msg.get("VoiceLength");
log.createTime = System.currentTimeMillis();
IChatLogChain firstChain = new GroupChain();
return firstChain.fromMap(log, msg);
}
public WechatLogPojo toPojo() {
WechatLogPojo pojo = new WechatLogPojo();
pojo.seqNum = seqNum;
pojo.msgid = msgid;
pojo.newMsgId = newMsgId;
pojo.msgType = msgType;
pojo.imgPath = imgPath;
pojo.relatedPath = relatedPath;
pojo.content = content;
pojo.fromId = fromId;
pojo.toId = toId;
pojo.url = url;
pojo.createTime = createTime;
pojo.voiceLength = voiceLength;
pojo.recommendInfo = JSONUtil.toJson(recommendInfo);
pojo.imgType = img.type.getType();
pojo.base = img.getBase();
pojo.filePath = file == null ? null : file.getAbsolutePath();
pojo.recalled = recalled ? 0 : 1;
pojo.sent = sent ? 0 : 1;
return pojo;
}
public static ChatLog fromPojo(WechatLogPojo pojo) {
ChatLog log = new ChatLog();
log.seqNum = pojo.seqNum;
log.msgid = pojo.msgid;
log.newMsgId = pojo.newMsgId;
log.msgType = pojo.msgType;
log.imgPath = pojo.imgPath;
log.relatedPath = pojo.relatedPath;
log.content = pojo.content;
log.fromId = pojo.fromId;
log.toId = pojo.toId;
log.url = pojo.url;
log.createTime = pojo.createTime;
log.voiceLength = pojo.voiceLength;
log.recommendInfo = JSONUtil.fromJson(pojo.recommendInfo);
if(null != pojo.imgPath && !"".equals(pojo.imgPath)) {
ImageLoader loader = new ImageLoader();
loader.load(pojo.imgPath);
log.img = new ImageNode(pojo.imgType == 0 ? TYPE.IMOJ : TYPE.IMAGE, new Image(null, loader.data[0]), loader, pojo.base);
}
if(null != pojo.filePath && !"".equals(pojo.filePath)) {
log.file = new File(pojo.filePath);
}
log.recalled = pojo.recalled == 0;
log.sent = pojo.sent == 0;
return log;
}
}
| smokingrain/WeChat | src/com/xk/chatlogs/ChatLog.java |
64,984 | package tf3;
import gg3.C107803k;
import kf3.C61082e;
import kf3.C99143g;
/* renamed from: tf3.l */
public final class C37070l extends C99143g {
/* renamed from: a */
public String mo54531a() {
return "RepairerConfig_GlobalNewForwardSwitch";
}
/* renamed from: b */
public String mo54532b() {
return "新转发开关(场景:聊天,类型:文本)";
}
/* renamed from: d */
public Class<? extends C61082e> mo54533d() {
return C107803k.class;
}
/* renamed from: g */
public Object mo54534g() {
return 0;
}
/* renamed from: i */
public String mo54535i() {
return "clicfg_new_forward_switch_and";
}
}
| Durjoy-majumdar/DeChat | p-v/tf3/C37070l.java |
64,985 | package Kernel;
import java.awt.Color;
import java.awt.Font;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import Other.FrndCardFrame;
public class FrndChatFrame extends JFrame {
// 对方信息资源
FrndNode fn_ctpt;// 对方的信息结点,注意复制来的是引用
String ctptUsr;// 对方的帐号
String ctptNm;// 对方的网名
int ctptHID;// 对方的头像号
String ctptSig;// 对方的个性签名
ImageIcon ii_ctptHd;// 对方的头像
// 组件
JLabel jl_hd;// 存放对方头像,用户名等的左上角标签
JButton jb_snd, jb_ext;// 发送按钮,关闭按钮
JTextField jtf_inpt;// 输入框
JTextArea jta_rcv;// 接收框,可以改成JPanel
// 发送图片,资料卡,清屏,保存聊天记录,修改背景颜色
JButton jb_pic, jb_card, jb_cln, jb_hstry, jb_clr;
// 其它
private Font ft_jt = new Font("黑体", 1, 20);// 发送/接收框字体
public FrndCardFrame fcrdf = null;// 该好友的资料卡,仅能通过单击头像打开
Color clr_jb = Color.WHITE;
// 构造器,传入双击的那个联系人结点
public FrndChatFrame(FrndNode fn) {
super("正在和" + fn.Name + "聊天");
this.fn_ctpt = fn;// 保留一份引用,但不要随意修改
myInit();// 窗体初始化
jtf_inpt.grabFocus();// 输入栏获取焦点
}
// 窗体初始化
private void myInit() {
// 从对方的信息结点中把信息读出来
this.ctptUsr = fn_ctpt.UsrNum;
this.ctptNm = fn_ctpt.Name;
this.ctptSig = fn_ctpt.Signature;
this.ctptHID = fn_ctpt.HeadID;
this.ii_ctptHd = fn_ctpt.ii_head;
// 左上角标签
jl_hd = new JLabel();
// 两步缩放对方的头像
Image img = ii_ctptHd.getImage().getScaledInstance(50, 50, Image.SCALE_DEFAULT);
jl_hd.setIcon(new ImageIcon(img));// 头像放入
jl_hd.setText("<HTML><font size=\"6\" color=\"#330066\">" + ctptNm + "</font><br>" + ctptSig + "</HTML>");// 名字和个性签名放入
jl_hd.setIconTextGap(15);// 设置JLabel文字图片间距
jl_hd.addMouseListener(new MouseAdapter() {
// 单击头像
@Override
public void mouseClicked(MouseEvent e) {
// 发送给服务器消息以获取好友资料
try {
KernelFrame.dos.writeUTF("[msg]" + ctptUsr);
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
jl_hd.setBounds(20, 10, 500, 60);
jl_hd.setLayout(null);
jl_hd.setBackground(new Color(200, 200, 240));
jl_hd.setForeground(Color.BLACK);
jl_hd.setOpaque(true);
this.add(jl_hd);
// 接收框
jta_rcv = new JTextArea(6, 20);
jta_rcv.setFont(ft_jt);
jta_rcv.setEditable(false);
jta_rcv.setLineWrap(true);// 自动换行
JScrollPane jsp = new JScrollPane(jta_rcv);// 放入滚动条
jsp.setBounds(20, 80, 455, 200);
this.add(jsp);
// 输入栏
jtf_inpt = new JTextField(20);
jtf_inpt.setFont(ft_jt);
jtf_inpt.setBounds(20, 320, 370, 40);
jtf_inpt.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
// 按下了回车,并且有内容时允许发送
if (e.getKeyChar() == '\n' && jtf_inpt.getText().length() > 0) {
try {
send();// 发送给服务器
} catch (IOException e1) {
e1.printStackTrace();// 发送失败
}
}
// 按完回车焦点一定还在这个发送栏里,不必重新取回
}
});
this.add(jtf_inpt);
// 清屏按钮
jb_cln = new JButton();
jb_cln.setIcon(new ImageIcon("./krnl_pic/cln.png"));
jb_cln.setFocusable(false);
jb_cln.setBounds(20, 285, 30, 30);
jb_cln.setBackground(clr_jb);
jb_cln.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
jta_rcv.setText("");
jtf_inpt.grabFocus();
}
});
this.add(jb_cln);
// 发送图片按钮
jb_pic = new JButton();
jb_pic.setIcon(new ImageIcon("./krnl_pic/pic.png"));
jb_pic.setFocusable(false);
jb_pic.setBounds(60, 285, 30, 30);
jb_pic.setBackground(clr_jb);
this.add(jb_pic);
// 资料卡按钮
jb_card = new JButton();
jb_card.setIcon(new ImageIcon("./krnl_pic/card.png"));
jb_card.setFocusable(false);
jb_card.setBounds(100, 285, 30, 30);
jb_card.setBackground(clr_jb);
jb_card.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
// 发送给服务器消息以获取好友资料
try {
KernelFrame.dos.writeUTF("[msg]" + ctptUsr);
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
this.add(jb_card);
// 保存历史按钮
jb_hstry = new JButton();
jb_hstry.setIcon(new ImageIcon("./krnl_pic/hstry.png"));
jb_hstry.setFocusable(false);
jb_hstry.setBounds(140, 285, 30, 30);
jb_hstry.setBackground(clr_jb);
jb_hstry.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
// FIXME
}
});
this.add(jb_hstry);
// 修改背景颜色按钮
jb_clr = new JButton();
jb_clr.setIcon(new ImageIcon("./krnl_pic/clr.png"));
jb_clr.setFocusable(false);
jb_clr.setBounds(180, 285, 30, 30);
jb_clr.setBackground(clr_jb);
jb_clr.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
// 颜色对话框
Color newClr = JColorChooser.showDialog(null, "修改聊天窗体背景色", KernelFrame.clr_ppl);
if (newClr != null) {
getContentPane().setBackground(newClr);
}
}
});
this.add(jb_clr);
// 发送按钮
jb_snd = new JButton("发送");
jb_snd.setBounds(405, 320, 70, 40);
jb_snd.addActionListener(new MyActionAdapter() {
@Override
public void actionPerformed(ActionEvent e) {
// 仅当文本框内有内容时允许发送
if (jtf_inpt.getText().length() > 0) {
try {
send();// 发送给服务器
} catch (IOException e1) {
e1.printStackTrace();// 发送失败
}
}
jtf_inpt.grabFocus();// 取回焦点
}
});
jb_snd.setFocusable(false);
jb_snd.setBackground(new Color(210, 200, 250));
this.add(jb_snd);
// 有关窗体
this.setLayout(null);
// 关闭时什么都不做,而是在后面覆写windowClosing里隐藏窗体
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
this.setBounds(250, 150, 500, 400);
this.setResizable(false);
this.setVisible(true);
// 窗体关闭时只是隐藏它,不析构存窗体引用HashMap里对应的窗体
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
setVisible(false);// 隐藏本窗体
// KernelFrame.hm_usrTOfcf.remove(ctptUsr);
}
});
this.getContentPane().setBackground(KernelFrame.clr_ppl);
}
// 发送时做的事情,将发送时的异常抛出去,在调用send()时捕获
// 这样一旦发生异常,整个send()立即停止执行
// 所以只要自己窗口内看到了发出去消息,而且发送框清空,消息就发出去了
private void send() throws IOException {
// TODO
// 构造要发送给服务器的消息,格式"[to对方帐号][im自己帐号]消息内容"
String s = "[to" + ctptUsr + "][im" + KernelFrame.str_nmbr + "]" + jtf_inpt.getText();
KernelFrame.dos.writeUTF(s);// 发给服务器,此处抛异常
jta_rcv.append("[自己]:" + jtf_inpt.getText() + "\n");// 成功发送后在文本区显示
jta_rcv.selectAll();// 选中所有,从而让滚动条始终在最下边
jtf_inpt.setText("");// 同时清空发送框
// 获得焦点在不同的发送方式下未必都需要,所以不写在send()里
}
}
| LauZyHou/ChatCat_Client | src/Kernel/FrndChatFrame.java |
64,987 | package websocket;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.List;
enum ChatType {
Connection, // 连接
Msg, // 聊天
}
public class ChatMsg {
String type;
String nickname;
String msg;
List<String> users = new ArrayList<>(); // 在线用户昵称数组
// 客户端发来的消息
static ChatMsg fromClientMsg(String msg) {
Gson gson = new Gson();
ChatMsg cm = gson.fromJson(msg, ChatMsg.class);
// cm.type = ChatType.Msg.name();
return cm;
}
static ChatMsg newUser(String newUser, List<String> users) {
ChatMsg cm = new ChatMsg();
cm.type = ChatType.Msg.name();
cm.nickname = "系统消息";
cm.msg = "【" + newUser + "】上线了";
cm.users = users;
return cm;
}
String toJson() {
Gson gson = new Gson();
return gson.toJson(this);
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public List<String> getUsers() {
return users;
}
public void setUsers(List<String> users) {
this.users = users;
}
}
| yswift/LearnJava | JavaWeb/src/websocket/ChatMsg.java |
64,988 | package com.dao;
import com.entity.ChatEntity;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import java.util.List;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.pagination.Pagination;
import org.apache.ibatis.annotations.Param;
import com.entity.vo.ChatVO;
import com.entity.view.ChatView;
/**
* 聊天
*
* @author
* @email
* @date 2021-01-19 21:46:13
*/
public interface ChatDao extends BaseMapper<ChatEntity> {
List<ChatVO> selectListVO(@Param("ew") Wrapper<ChatEntity> wrapper);
ChatVO selectVO(@Param("ew") Wrapper<ChatEntity> wrapper);
List<ChatView> selectListView(@Param("ew") Wrapper<ChatEntity> wrapper);
List<ChatView> selectListView(Pagination page,@Param("ew") Wrapper<ChatEntity> wrapper);
ChatView selectView(@Param("ew") Wrapper<ChatEntity> wrapper);
}
| giteecode/psychlolgyCounselPublic | src/main/java/com/dao/ChatDao.java |
64,989 | package com.demo1.view;
import com.demo1.model.TimeThread;
import com.demo1.net.NetTool;
import org.apache.log4j.Logger;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
/**
* 人人对战页面
* 接收信息线程
*
* @author admin
*/
public class PPMainBoard extends MainBoard {
private PPChessBoard cb;
private JButton startGame;
private JButton exitGame;
private JButton back;//悔棋按钮
private JButton send; //聊天发送按钮
private JLabel timecount;//计时器标签
//双方状态
private JLabel people1;//自己标签
private JLabel people2;//对手标签
private JLabel p1lv;//自己等级标签
private JLabel p2lv;//对手等级标签
private JLabel situation1;//自己状态标签
private JLabel situation2;//对手状态标签
private JLabel jLabel1;
private JLabel jLabel2;//
private JTextArea talkArea;
private JTextField tf_ip; //输入IP框
private JTextField talkField; //聊天文本框
private String ip;
private DatagramSocket socket;
private String gameState;
private String enemyGameState;//敌人状态
private Logger logger = Logger.getLogger("游戏");
public JButton getstart() {
return startGame;
}
public String getIp() {
return ip;
}
public JTextField getTf() {
return tf_ip;
}
public DatagramSocket getSocket() {
return socket;
}
public JLabel getLabel1() {
return jLabel1;
}
public JLabel getLabel2() {
return jLabel2;
}
public JLabel getSituation1() {
return situation1;
}
public JLabel getSituation2() {
return situation2;
}
public PPMainBoard() {
init();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
/**
* 初始化页面
*/
public void init() {
gameState = "NOT_START";
enemyGameState = "NOT_START";
cb = new PPChessBoard(this);
cb.setClickable(PPMainBoard.CAN_NOT_CLICK_INFO);
cb.setBounds(210, 40, 570, 585);
cb.setVisible(true);
cb.setInfoBoard(talkArea);
tf_ip = new JTextField("请输入对手IP地址");
tf_ip.setBounds(780, 75, 200, 30);
tf_ip.addMouseListener(this);
startGame = new JButton("准备游戏");//设置名称,下同
startGame.setBounds(780, 130, 200, 50);//设置起始位置,宽度和高度,下同
startGame.setBackground(new Color(50, 205, 50));//设置颜色,下同
startGame.setFont(new Font("宋体", Font.BOLD, 20));//设置字体,下同
startGame.addActionListener(this);
back = new JButton("悔 棋");
back.setBounds(780, 185, 200, 50);
back.setBackground(new Color(85, 107, 47));
back.setFont(new Font("宋体", Font.BOLD, 20));
back.addActionListener(this);
send = new JButton("发送");
send.setBounds(840, 550, 60, 30);
send.setBackground(new Color(50, 205, 50));
send.addActionListener(this);
talkField = new JTextField("聊天");
talkField.setBounds(780, 510, 200, 30);
talkField.addMouseListener(this);
exitGame = new JButton("返 回");
exitGame.setBackground(new Color(218, 165, 32));
exitGame.setBounds(780, 240, 200, 50);
exitGame.setFont(new Font("宋体", Font.BOLD, 20));//设置字体,下同
exitGame.addActionListener(this);
people1 = new JLabel(" 我:");
people1.setOpaque(true);
people1.setBackground(new Color(82, 109, 165));
people1.setBounds(10, 410, 200, 50);
people1.setFont(new Font("宋体", Font.BOLD, 20));
people2 = new JLabel(" 对手:");
people2.setOpaque(true);
people2.setBackground(new Color(82, 109, 165));
people2.setBounds(10, 75, 200, 50);
people2.setFont(new Font("宋体", Font.BOLD, 20));
timecount = new JLabel(" 计时器:");
timecount.setBounds(320, 1, 200, 50);
timecount.setFont(new Font("宋体", Font.BOLD, 30));
p1lv = new JLabel(" 等 级:LV.1");
p1lv.setOpaque(true);
p1lv.setBackground(new Color(82, 109, 165));
p1lv.setBounds(10, 130, 200, 50);
p1lv.setFont(new Font("宋体", Font.BOLD, 20));
p2lv = new JLabel(" 等 级:LV.1");
p2lv.setOpaque(true);
p2lv.setBackground(new Color(82, 109, 165));
p2lv.setBounds(10, 465, 200, 50);
p2lv.setFont(new Font("宋体", Font.BOLD, 20));
situation1 = new JLabel(" 状态:");
situation1.setOpaque(true);
situation1.setBackground(new Color(82, 109, 165));
situation1.setBounds(10, 185, 200, 50);
situation1.setFont(new Font("宋体", Font.BOLD, 20));
situation2 = new JLabel(" 状态:");
situation2.setOpaque(true);
situation2.setBackground(new Color(82, 109, 165));
situation2.setBounds(10, 520, 200, 50);
situation2.setFont(new Font("宋体", Font.BOLD, 20));
jLabel1 = new JLabel();
add(jLabel1);
jLabel1.setBounds(130, 75, 200, 50);
jLabel2 = new JLabel();
add(jLabel2);
jLabel2.setBounds(130, 410, 200, 50);
timecount = new JLabel(" 计时器:");
timecount.setBounds(320, 1, 200, 50);
timecount.setFont(new Font("宋体", Font.BOLD, 30));
talkArea = new JTextArea(); //对弈信息
talkArea.setEnabled(false);
talkArea.setBackground(Color.BLUE);
//滑动条
JScrollPane p = new JScrollPane(talkArea);
p.setBounds(780, 295, 200, 200);
add(tf_ip);
add(cb);
add(startGame);
add(back);
add(exitGame);
add(people1);
add(people2);
add(p1lv);
add(p2lv);
add(situation1);
add(situation2);
add(timecount);
add(p);
add(send);
add(talkField);
//加载线程
ReicThread();
repaint();
}
/**
* 接收信息放在线程中
*/
public void ReicThread() {
new Thread(new Runnable() {
public void run() {
try {
byte buf[] = new byte[1024];
socket = new DatagramSocket(10086);
DatagramPacket dp = new DatagramPacket(buf, buf.length);
while (true) {
socket.receive(dp);
//0.接收到的发送端的主机名
InetAddress ia = dp.getAddress();
//enemyMsg.add(new String(ia.getHostName())); //对方端口
logger.info("对手IP:" + ia.getHostName());
//1.接收到的内容
String data = new String(dp.getData(), 0, dp.getLength());
if (data.isEmpty()) {
cb.setClickable(MainBoard.CAN_NOT_CLICK_INFO);
} else {
String[] msg = data.split(",");
System.out.println(msg[0] + " " + msg[1]);
//接收到对面准备信息并且自己点击了准备
if (msg[0].equals("ready")) {
enemyGameState = "ready";
System.out.println("对方已准备");
if (gameState.equals("ready")) {
gameState = "FIGHTING";
cb.setClickable(MainBoard.CAN_CLICK_INFO);
startGame.setText("正在游戏");
situation1.setText(" 状态:等待...");
situation2.setText(" 状态:下棋...");
logger.info("等待对方消息");
timer = new TimeThread(label_timeCount);
timer.start();
}
} else if (msg[0].equals("POS")) {
System.out.println("发送坐标");
//接受坐标以及角色
situation1.setText(" 状态:等待...");
situation2.setText(" 状态:下棋...");
//重新启动计时线程
timer = new TimeThread(label_timeCount);
timer.start();
cb.setCoord(Integer.parseInt(msg[1]), Integer.parseInt(msg[2]), Integer.parseInt(msg[3]));
} else if (msg[0].equals("enemy")) {
talkArea.append("对手:" + msg[1] + "\n");
logger.info("对手发送的消息" + msg[1]);
} else if (msg[0].equals("back")) {
int n = JOptionPane.showConfirmDialog(cb, "是否同意对方悔棋", "选择", JOptionPane.YES_NO_OPTION);
//点击确定按钮则可以悔棋
if (n == JOptionPane.YES_OPTION) {
cb.backstep();
NetTool.sendUDPBroadCast(ia.getHostName(), "canBack" + ", ");
} else {
NetTool.sendUDPBroadCast(ia.getHostName(), "noBack" + ", ");
}
}
//允许悔棋
else if (msg[0].equals("canBack")) {
JOptionPane.showMessageDialog(cb, "对方允许您悔棋");
cb.backstep();
}
//不允许悔棋
else if (msg[0].equals("noBack")) {
JOptionPane.showMessageDialog(cb, "对方不允许您悔棋");
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == startGame) {
if (!tf_ip.getText().isEmpty() &&
!tf_ip.getText().equals("不能为空") &&
!tf_ip.getText().equals("请输入IP地址") &&
!tf_ip.getText().equals("不能连接到此IP")) {
ip = tf_ip.getText();
startGame.setEnabled(false);
startGame.setText("等待对方准备");
tf_ip.setEditable(false);
//发送准备好信息
NetTool.sendUDPBroadCast(ip, "ready, ");
gameState = "ready";
if (enemyGameState == "ready") {
gameState = "FIGHTING";
cb.setClickable(CAN_CLICK_INFO);
startGame.setText("正在游戏");
situation1.setText(" 状态:等待...");
situation2.setText(" 状态:下棋...");
timer = new TimeThread(label_timeCount);
timer.start();
}
} else {
tf_ip.setText("不能为空");
}
}
//点击悔棋后的操作
else if (e.getSource() == back) {
//发送悔棋信息
NetTool.sendUDPBroadCast(ip, "back" + ", ");
logger.info("玩家选择悔棋");
}
// 聊天发送按钮
else if (e.getSource() == send) {
if (!talkField.getText().isEmpty() && !talkField.getText().equals("不能为空")) {
//获得输入的内容
String msg = talkField.getText();
talkArea.append("我:" + msg + "\n");
talkField.setText("");
ip = tf_ip.getText();
NetTool.sendUDPBroadCast(ip, "enemy" + "," + msg);
} else {
talkField.setText("不能为空");
}
}
//退出游戏,加载主菜单
else if (e.getSource() == exitGame) {
dispose();
new SelectModel();
}
}
@Override
public void mouseClicked(MouseEvent e) {
if (e.getSource() == tf_ip) {
tf_ip.setText("");
} else if (e.getSource() == talkField) {
talkField.setText("");
}
}
}
| MSJeinlong/JavaSE_Gobang | src/com/demo1/view/PPMainBoard.java |
64,990 | package client.socket;
import java.applet.Applet;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.JOptionPane;
import javax.xml.transform.Templates;
import client.common.MyTextPane;
import client.control.Chat;
import client.control.Main;
import client.control.RecieveThread;
import client.frame.PublicMessageFrame;
import client.frame.SendFileFrame;
import com.MyTools;
import com.MyTools.Flag;
import com.socket.TCP;
import com.socket.TCPServer;
public class S_TCP extends TCPServer
{
ArrayList<Chat> chats=new ArrayList<Chat>();//存放所有的打开的聊天窗体集合
Main main=null;//传过来的主窗体
public S_TCP(int serverPort,Main main)
{
super(serverPort);
this.main=main;
}
/**
* 处理客户端发来的各种信息
* @param flag 信息标志
* @param message 消息内容
*/
@Override
public void dealWithMessage(Flag flag,String message,TCP tcp)
{
switch (flag)
{
case START_CHAT:doStartChat(message,tcp);break;
case MESSAGE:showMessage(message,tcp);break;
case SENDFILE:doSendFile(message,tcp);break;
case SENDIMG: dogetImg(message ,tcp);break;
case FACE:doFace(message,tcp);break;//如果是表情
default:break;
}
}
/**
* 接收图片
* @param message
* @param tcp
*/
private void dogetImg(String message,TCP tcp)
{
Chat currentChatWindoew =
null;
for(Chat chat:chats)
{
if(chat.friendName.equals(tcp.getClientName()))
currentChatWindoew = chat;
}
tcp.getImg(currentChatWindoew ,message);
}
/**
* 处理客户端退出的相关事件
* @param tcp TCP连接
*/
@Override
public void dealWithExit(TCP tcp)
{
}
/**
* 服务端启动后要做的事情,把这部分单独提取出来的目的是为了方便子类继承时重写
*/
@Override
public void afterServerStart()
{
}
public void doStartChat(String message,TCP tcp)
{
tcp.setClientName(message);//设置对方的名字
if(!message.equals(main.lbl用户名.getText()))
{
Chat chat=new Chat(tcp,tcp.getClientName(),main.lbl用户名.getText());
chat.setTitle("与" + tcp.getClientName()+"("+tcp.getClientIP()+")聊天中");// 设置窗体标题
chats.add(chat);
}
else
{
JOptionPane.showMessageDialog(null, "您正在与自己聊天,MyQQ将只会打开一个聊天框!");
}
}
public void showMessage(String message,TCP tcp)
{
for(Chat chat:chats)
{
if(chat.friendName.equals(tcp.getClientName()))
{
if(!chat.isVisible())
{
new PublicMessageFrame(tcp.getClientName()+"给您发来消息",message,chat);
//对方未打开聊天窗体时就播放声音
MyTools.playMsgSound();
}
chat.setReceivePaneText(false, message);
}
}
}
/**
* 处理接收文件的相关事件
*/
public void doSendFile(String message,TCP tcp)
{
for(Chat chat:chats)
{
if(chat.friendName.equals(tcp.getClientName()))
{
chat.friendGetFilePort=Integer.parseInt(message);
System.out.println("已成功获取好友的接收文件端口:"+message);
}
}
}
/**
* 处理表情
* @param message
* @param tcp
*/
public void doFace(String message,TCP tcp)
{
for(Chat chat:chats)
{
if(chat.friendName.equals(tcp.getClientName()))
{
new MyTextPane(chat.jTextPane接收框).addIcon(MyTools.getFaceByIdx(Integer.parseInt(message)), chat.friendName);
}
}
}
}
| sxei/myqq | src/client/socket/S_TCP.java |
64,991 | package client.control;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import com.MyTools;
import com.MyTools.Flag;
import com.socket.TCP;
import com.socket.UDP;
import client.common.MyLabel;
import client.common.MyTextPane;
import client.control.Main;
import client.frame.ChatFrame;
import client.frame.FaceFrame;
import client.frame.ScreenFram;
import client.frame.SendFileFrame;
import client.socket.CC_TCP;
import client.socket.CS_TCP;
import client.socket.S_TCP;
import client.socket.UDPChat;
/**
* @author LXA 聊天的窗体,继承自ChatFrame
*/
public class Chat extends ChatFrame
{
public String friendIP = null;// 好友的IP地址
public int friendTCPPort=0;//好友的TCP端口
public String friendName="";//好友的名字
public String myName="";//自己的名字
public CC_TCP cc_TCP=null;//发起聊天的TCP
public TCP tcp=null;//接收聊天的TCP
public UDPChat chatUDP=null;
int width = 680;// 窗体宽度
int height = 600;// 窗体高度
private StyledDocument receiveDocument = null;// 用来存放接收框的文本或图片
private StyledDocument sendDocument = null;// 用来存放发送框的文本或图片
public ServerSocket getFileServer=null;
public int myGetFilePort=10000;
public int friendGetFilePort=0;
public CS_TCP cs_TCP=null;//用来当对方不在线时给服务器发送离线消息
public String ImgPath = "";
String screenCutImgName = "";
public int faceIdx=-1;//表情的索引
/**
* 通过UDP构造聊天窗体
*/
/*public Chat(String friendIP,String friendName,String myName)
{
chatUDP=new UDPChat(friendIP,this);//实例化一个已经封装好的ChatUDP类
init();
}*/
/**
* 通过TCP主动发起聊天
* @param friendIP
* @param friendTCPPort
* @param friendName
* @param myName
*/
public Chat(String friendIP,int friendTCPPort,String friendName,String myName)
{
this.friendIP=friendIP;
this.friendTCPPort=friendTCPPort;
this.friendName=friendName;
this.myName=myName;
try
{
cc_TCP=new CC_TCP(this.friendIP, this.friendTCPPort,this);
cc_TCP.sendMessage(Flag.START_CHAT+MyTools.FLAGEND+myName);//发起聊天请求
}
catch (Exception e)
{
e.printStackTrace();
}
init();
initGetFileServer();//初始化接收文件的服务
}
/**
* 通过TCP被动接受聊天
* @param tcp
* @param friendName
* @param myName
*/
public Chat(TCP tcp,String friendName,String myName)
{
this.tcp=tcp;
this.friendName=friendName;
this.myName=myName;
init();
initGetFileServer();//初始化接收文件的服务
}
/**
* 发送离线消息时的构造方法
* @param cs_TCP
* @param friendName
*/
public Chat(CS_TCP cs_TCP,String friendName)
{
this.cs_TCP=cs_TCP;
this.friendName=friendName;
init();
setTitle("给"+friendName+"发送离线消息中……");
}
public void init()
{
this.setMinimumSize(new Dimension(width, height));// 设置窗体的最小大小
if(cc_TCP!=null)//如果是发起方则直接设置标题,接收方因为对方IP还未知,所以这里还不能设置
setTitle("与" + friendName+"("+friendIP+":"+friendTCPPort+")聊天中");// 设置窗体标题
initLabelEvent();// 初始化窗体上所有Label的鼠标移动事件
MyTools.setWindowsMiddleShow(this,width,height);//设置窗体居中显示
jButton发送.setMnemonic(KeyEvent.VK_ENTER);// 设置发送按钮的快捷键为Alt+Enter
receiveDocument = jTextPane接收框.getStyledDocument();
sendDocument = jTextPane发送框.getStyledDocument();
jTextPane接收框.insertIcon(MyTools.getIcon("../img/warning.png"));
String warning="交谈中请勿轻信汇款、中奖信息、陌生电话,勿使用外挂软件。\n";
try
{
SimpleAttributeSet warn=MyTextPane.getFontAttribute("黑体", 12, Color.blue, false, false);
receiveDocument.insertString(receiveDocument.getLength(), warning, warn);
// 设置窗体的顶部图标
this.setIconImage(ImageIO.read(Main.class.getResource("../img/QQ_64.png")));
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* 初始化接收文件的服务
*/
public void initGetFileServer()
{
while (true)
{
try
{
getFileServer = new ServerSocket(myGetFilePort);
System.out.println("已开启文件接收监听!");
if(cc_TCP!=null)
cc_TCP.sendMessage(Flag.SENDFILE+MyTools.FLAGEND+myGetFilePort);
else
tcp.sendMessage(Flag.SENDFILE+MyTools.FLAGEND+myGetFilePort);
break;
}
catch (Exception e)
{
myGetFilePort++;
}
}
Runnable runnable=new Runnable()
{
@Override
public void run()
{
//tcp.sendMessage(Flag.GETFILE_OK+MyTools.FLAGEND+TCP.getLocalHostIP()+MyTools.SPLIT1+myPort);
RecieveThread recieveThread;
while (true)
{
try
{
Socket socket = getFileServer.accept();
System.out.println("与文件发送方连接成功!");
recieveThread = new RecieveThread(new SendFileFrame(), socket);
recieveThread.start();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
};
new Thread(runnable).start();
}
/**
* 初始化窗体上所有Label的鼠标移动事件
*/
public void initLabelEvent()
{
new MyLabel(jLabel字体).addEvent();
new MyLabel(jLabel表情).addEvent();
new MyLabel(jLabel音乐).addEvent();
new MyLabel(jLabel图片).addEvent();
new MyLabel(jLabel截图).addEvent();
new MyLabel(jLabel聊天记录).addEvent();
new MyLabel(jLabel视频).addEvent();
new MyLabel(jLabel语音).addEvent();
new MyLabel(jLabel发送文件).addEvent();
new MyLabel(jLabelQQ空间).addEvent();
new MyLabel(jLabel我的好友).addEvent();
new MyLabel(jLabel加好友).addEvent();
}
/*
* 给好友发送消息
*/
@Override
public void sendMessage()
{
//发送的是文本信息
if ("".equals(ImgPath) && "".equals(screenCutImgName))
{
if(faceIdx<0)
{
if(cc_TCP!=null)//如果是发起聊天的一方
cc_TCP.sendMessage(Flag.MESSAGE+MyTools.FLAGEND+jTextPane发送框.getText());
else if(tcp!=null)//如果是接收聊天的一方
tcp.sendMessage(Flag.MESSAGE+MyTools.FLAGEND+jTextPane发送框.getText());
else if(cs_TCP!=null)//发送未读消息
cs_TCP.sendMessage(Flag.UNDERLINE_MESSAGE+MyTools.FLAGEND+friendName+MyTools.SPLIT1+jTextPane发送框.getText());
setReceivePaneText(true,jTextPane发送框.getText());//将用户发送的消息显示在聊天框中
jTextPane发送框.setText("");// 清空发送框
}
else
{
if(cc_TCP!=null)//如果是发起聊天的一方
cc_TCP.sendMessage(Flag.FACE+MyTools.FLAGEND+faceIdx);
else if(tcp!=null)//如果是接收聊天的一方
tcp.sendMessage(Flag.FACE+MyTools.FLAGEND+faceIdx);
new MyTextPane(jTextPane接收框).addIcon(MyTools.getFaceByIdx(faceIdx), myName);
jTextPane发送框.setText("");// 清空发送框
faceIdx=-1;//图片表情发完后置为默认
}
}
//发送的是图片
else if(!"".equals(ImgPath))
{
try
{
//置空发送框
jTextPane发送框.setText("");
//接收框显示图片
jTextPane接收框.insertIcon(new ImageIcon(ImageIO
.read(new FileInputStream(ImgPath))));
//发送图片给对方
cc_TCP.sendImg(ImgPath);
//发送完图片后置空图片路径
ImgPath ="";
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else if(!"".equals(screenCutImgName))
{
try
{ //置空发送框
jTextPane发送框.setText("");
//接收框显示图片
jTextPane接收框.insertIcon(new ImageIcon(ImageIO
.read(new FileInputStream("./screenCut/snap.jpg"))));
//发送图片给对方
cc_TCP.sendImg("./screenCut/snap.jpg");
//发送完图片后置空图片路径
screenCutImgName ="";
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 设置发送框文本
*
* @param text
* 需要设置的文本
*/
public void setSendPaneText(String text)
{
try
{
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* 设置接收框的文本
*
* @param text
* 需要设置的文本
*/
public void setReceivePaneText(boolean isFromMyself, String text)
{
if (isFromMyself)
{
String time= DateFormat.getTimeInstance().format(new Date());
new MyTextPane(jTextPane接收框).addText(myName+" "+time+ "\n",MyTextPane.getTimeAttribute());
new MyTextPane(jTextPane接收框).addText(text+ "\n",MyTextPane.getMyAttribute());
}
else
{
String time= DateFormat.getTimeInstance().format(new Date());
new MyTextPane(jTextPane接收框).addText(friendName+" "+time+ "\n",MyTextPane.getTimeAttribute());
new MyTextPane(jTextPane接收框).addText(text+ "\n",MyTextPane.getFriendAttribute());
}
}
/**
* 发送文件
*/
public void sendFile()
{
System.out.println("对方已开启文件接收监听!");
SendFileFrame sendFileFrame=new SendFileFrame();
sendFileFrame.lblProgress.setText("正在等待文件被接收....");
String filePath = sendFileFrame.showDialog(JFileChooser.FILES_ONLY);
sendFileFrame.setVisible(true);
SendTread sendThread;
//sendThread = new SendTread(sendFileFrame, filePath,message.split(MyTools.SPLIT1)[0],Integer.parseInt(message.split(MyTools.SPLIT1)[1]));
sendThread = new SendTread(sendFileFrame, filePath,friendIP,friendGetFilePort);
sendThread.start();
}
/*
* 发生在窗体关闭之前
*/
public void beforeClose()
{
}
public void selectFace()
{
new FaceFrame(this);
}
/*
* 发送图片
*/
public void sendImg()
{
JFileChooser chooser = new JFileChooser();
// 添加过滤器
chooser.addChoosableFileFilter(new FileFilter()
{
@Override
public String getDescription()
{
// TODO Auto-generated method stub
return ".jpg/.png/.bmp";
}
@Override
public boolean accept(File file)
{
// 获取文件名
String fileName = file.getName();
if (file.isDirectory())
return true;
// 过滤文件名
if (fileName.endsWith(".jpg") || fileName.endsWith(".png")
|| fileName.endsWith(".bmp"))
{
return true;
}
return false;
}
});
int result = chooser.showOpenDialog(null);
// 选择打开时
if (result == JFileChooser.APPROVE_OPTION)
{
String filePath = chooser.getSelectedFile().getAbsolutePath();
// 给图片添加;路径
ImgPath = filePath;
try
{
jTextPane发送框.insertIcon(new ImageIcon(ImageIO
.read(new FileInputStream(filePath))));
}
catch (FileNotFoundException e)
{
System.out.println("文件未找到");
e.printStackTrace();
}
catch (IOException e)
{
System.out.println("io异常");
e.printStackTrace();
}
}
// 选择关闭是
else
{
dispose();
}
}
/*
* @截图
*/
@Override
public void screenFram()
{
try
{
ScreenFram.main();
System.out.println("截图的名字是"+screenCutImgName);
jTextPane发送框.insertIcon(new ImageIcon(ImageIO
.read(new FileInputStream("./screenCut/snap.jpg"))));
screenCutImgName="snap";
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
| sxei/myqq | src/client/control/Chat.java |
64,992 | package client.control;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.tree.DefaultMutableTreeNode;
import com.MyTools;
import com.MyTools.Flag;
import com.socket.TCPServer;
import client.common.*;
import client.control.MyTree;
import client.frame.MainFrame;
import client.socket.CC_TCP;
import client.socket.CS_TCP;
import client.socket.S_TCP;
public class Main extends MainFrame
{
public CS_TCP cs_TCP=null;
public S_TCP s_TCP=null;
private int serverPort=5000;//端口从5000开始分配
final int width=350;//窗体宽度
final int height=630;//窗体高度
public QunChat qunChat;//群聊天室
public Main()
{
init();
}
public Main(CS_TCP cs_TCP)
{
this.cs_TCP=cs_TCP;
init();
}
/**
* 初始化主窗体
*/
public void init()
{
new MyLabel(lbl设置,"../img/button/QQ_settings","png").addEvent();//给最底下的设置按钮添加事件
MyTools.setWindowsMiddleShow(this,width,height);//设置窗体居中显示
initUserStatus();//初始化用户是否在线等状态
s_TCP=new S_TCP(serverPort,this);
}
/**
* 当登录成功后,将登录窗体的CS_TCP传给主窗体
* @param cs_TCP
*/
public void setCS_TCP(CS_TCP cs_TCP)
{
this.cs_TCP=cs_TCP;
}
public int getServerPort()
{
return s_TCP.getServerPort();
}
/**
* 初始化用户是否在线等状态
*/
public void initUserStatus()
{
comboBox状态.removeAllItems();
comboBox状态.addItem(MyTools.getIcon("../img/status/status_online.png"));
comboBox状态.addItem(MyTools.getIcon("../img/status/status_qme.png"));
comboBox状态.addItem(MyTools.getIcon("../img/status/status_leave.png"));
comboBox状态.addItem(MyTools.getIcon("../img/status/status_busy.png"));
comboBox状态.addItem(MyTools.getIcon("../img/status/status_invisible.png"));
}
/**
* 初始化好友列表
*/
public void initjTree(String[] groupNames,ArrayList<String[]> friendNames)
{
new MyTree(tree, groupNames, friendNames);
}
/*
* 开始给对方好友聊天
*/
@Override
public void startChat(ActionEvent e)
{
if(tree.getSelectionPath().getPathCount()==3)
{
String str=tree.getSelectionPath().getLastPathComponent().toString();
String friendName=str.substring(0,str.indexOf("("));
String friendIP=str.substring(str.indexOf("(")+1,str.indexOf(":"));
int friendPort=Integer.parseInt(str.substring(str.indexOf(":")+1,str.indexOf(")")));
if(!friendIP.equals("下线或隐身"))
{
Chat chat=new Chat(friendIP,friendPort,friendName,this.lbl用户名.getText());
chat.setVisible(true);
}
else
{
Chat chat=new Chat(cs_TCP, friendName);
chat.setVisible(true);
}
}
else
{
JOptionPane.showMessageDialog(null, "对不起,您未选中任何好友!");
}
}
/*
* 请求获取好友资料
*/
@Override
public void getFriendInfo(ActionEvent e)
{
String str=tree.getSelectionPath().getLastPathComponent().toString();
String userName=str.substring(0,str.indexOf("("));
cs_TCP.sendMessage(Flag.GET_FRIEND_INFO+MyTools.FLAGEND+userName);
}
/**
* 发送文件
* @param e
*/
@Override
public void sendFile(ActionEvent e)
{
}
/**
* 删除好友
* @param e
*/
public void deleteFriend(ActionEvent e)
{
DefaultMutableTreeNode node=(DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
node.removeFromParent();
JOptionPane.showMessageDialog(null, "删除好友成功!请关闭并打开当前分组以刷新好友列表!");
}
/**
* 进入聊天室
*/
@Override
public void gotoChatRoom()
{
qunChat=new QunChat(this);
}
/**
* 新建聊天室
*/
@Override
public void buildNewChatRoom()
{
JOptionPane.showMessageDialog(null, "新建聊天室属于会员专属功能,您还不是会员,是否想要加入会员,更多功能等你玩转,仅需10元每月哦!","提示",JOptionPane.YES_NO_CANCEL_OPTION);
}
}
| sxei/myqq | src/client/control/Main.java |
64,993 | package socket.sender;
import dao.LayIMDao;
import pojo.SocketUser;
import pojo.message.ToClientTextMessage;
import pojo.message.ToDBMessage;
import pojo.message.ToServerMessageMine;
import pojo.message.ToServerTextMessage;
import pojo.result.ToClientMessageResult;
import pojo.result.ToClientMessageType;
import socket.LayIMChatType;
import socket.manager.GroupUserManager;
import util.LayIMFactory;
import util.log.LayIMLog;
import javax.websocket.Session;
import java.math.BigInteger;
import java.util.Date;
import java.util.List;
/**
* 发送信息类
* 所有从客户端到服务端的消息转发到此类进行消息处理
* ToServerTextMessage转换为ToClientTextMessage
* 如果是单聊,直接从缓存取出对象的session进行消息发送,群聊则需要从缓存中取出该群里所有人的id进行遍历发送消息,
* 遍历过后需要优化在线与否,假如100人中只有一个人在线,则会浪费99次(未做优化)
*/
public class MessageSender {
//发送信息业务逻辑
public void sendMessage(ToServerTextMessage message){
int toUserId = message.getTo().getId();
//获取发送人
String sendUserId = Integer.toString(message.getMine().getId());
String type = message.getTo().getType();
//消息提前生成,否则进行循环内生成会浪费资源
String toClientMessage = getToClientMessage(message);
System.out.println("当前消息类型是"+type);
//不能用==做比较,因为一个是static final 值,另外一个是在对象中 == 为false
if(type.equals(LayIMChatType.GROUP)){
//群聊,需要遍历该群组里的所有人
//第一次从缓存中取userId,否则,从数据库中取在存到缓存中
List<String> users = new GroupUserManager().getGroupMembers(message.getTo().getId());
for (String userid : users) {
//遍历发送消息 自己过滤,不给自己发送(发送人id和群成员内的某个id相同)
if (!sendUserId.equals(userid)) {
sendMessage(Integer.parseInt(userid), toClientMessage);
}
}
}else {
sendMessage(toUserId, toClientMessage);
}
//最后保存到数据库
saveMessage(message);
}
//给单个用户发
private void sendMessage(Integer userId,String message){
SocketUser user = LayIMFactory.createManager().getUser(userId);
if (user.isExist()) {
if (user.getSession() == null) {
LayIMLog.info("该用户不在线 ");
} else {
Session session = user.getSession();
if (session.isOpen()) {
//构造用户需要接收到的消息
session.getAsyncRemote().sendText(message);
}
}
}else{
LayIMLog.info("该用户不在线 ");
}
}
//保存到数据库
//需要加入到队列
private void saveMessage(ToServerTextMessage message){
ToDBMessage dbMessage = new ToDBMessage();
dbMessage.setSendUserId(message.getMine().getId());
dbMessage.setAddtime(new Date().getTime());
dbMessage.setChatType( message.getTo().getType().equals(LayIMChatType.FRIEND) ? LayIMChatType.CHATFRIEND:LayIMChatType.CHATGROUP);
dbMessage.setMsgType(1);//这个参数先不管就是普通聊天记录
long groupId = getGroupId(message.getMine().getId(),message.getTo().getId(),message.getTo().getType());
dbMessage.setGroupId(groupId);
dbMessage.setMsg(message.getMine().getContent());
LayIMDao dao = new LayIMDao();
dao.addMsgRecord(dbMessage);
}
//根据客户端发送来的消息,构造发送出去的消息
/*
* username: data.mine.username
, avatar: data.mine.avatar
, id: data.mine.id
, type: data.to.type
, content:data.mine.content
, timestamp: new Date().getTime()
* */
private String getToClientMessage(ToServerTextMessage message) {
ToClientTextMessage toClientTextMessage = new ToClientTextMessage();
ToServerMessageMine mine = message.getMine();
toClientTextMessage.setUsername(mine.getUsername());
toClientTextMessage.setAvatar(mine.getAvatar());
toClientTextMessage.setContent(mine.getContent());
toClientTextMessage.setType(message.getTo().getType());
//群组和好友直接聊天不同,群组的id 是 组id,否则是发送人的id
if (toClientTextMessage.getType().equals(LayIMChatType.GROUP)) {
toClientTextMessage.setId(message.getTo().getId());
} else {
toClientTextMessage.setId(mine.getId());
}
toClientTextMessage.setTimestamp(new Date().getTime());
//返回统一消息接口
ToClientMessageResult result = new ToClientMessageResult();
result.setMsg(toClientTextMessage);
result.setType(ToClientMessageType.TYPE_TEXT_MESSAGE);
return LayIMFactory.createSerializer().toJSON(result);
}
//生成对应的groupId
private long getGroupId(int sendUserId,int toUserId,String type){
//如果是组内聊天,直接返回组id,否则返回 两个id的组合
if (type.equals(LayIMChatType.GROUP)){
return toUserId;
}
String sendUserIdStr = Integer.toString(sendUserId);
String toUserIdStr = Integer.toString(toUserId);
String groupIdStr = "";
//按照固定次序生成相应的聊天组
if (sendUserId > toUserId){
groupIdStr = sendUserIdStr + toUserIdStr;
}else{
groupIdStr = toUserIdStr + sendUserIdStr;
}
long groupId = Long.parseLong(groupIdStr);
return groupId;
}
}
| fanpan26/LayIM_JavaClient-Deprecated | src/socket/sender/MessageSender.java |
64,994 | package clients.UI;
import clients.clientSocket.Client;
import clients.clientSocket.ClientThread;
import controller.Control;
import eachOther.Command;
import eachOther.Transporter;
import servers.JDBC.GetNameByqq;
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.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by 沈小水 on 2018/6/6.
*/
public class ChatUI extends JFrame implements ActionListener {
private final String PATH = Control.PATH;
private Client client;//客户端
private ClientThread clientThread;//客户端服务线程
private String myQQ;//本人qq
private String friendQQ;//好友qq
private String name;//本人名字
private String friend;//好友名字
private JTextArea chatTxt;
private JTextArea inputTxt;
private JButton send;
public ChatUI(String myQQ, String friendQQ, Client client) {
this.client = client;
this.myQQ = myQQ;
this.friendQQ = friendQQ;
name = GetNameByqq.getName(myQQ);//从数据库中获取名字
friend = GetNameByqq.getName(friendQQ);
setTitle(name + "与" + friend + "聊天");
init();
setVisible(true);
pack();
setLocationRelativeTo(null);
setResizable(false);
//启动客户端线程
clientThread = new ClientThread(client, chatTxt);
clientThread.start();
}
public void init() {
//init
chatTxt = new JTextArea(15, 28);
inputTxt = new JTextArea(2, 28);
send = new JButton("发送", new ImageIcon(PATH + "sendIcon.png"));
chatTxt.setEditable(false);
chatTxt.setFont(new Font("宋体", Font.BOLD, 20));
inputTxt.setFont(new Font("宋体", Font.BOLD, 15));
//注册事件
send.addActionListener(this);
//布局
Box v = Box.createVerticalBox();
JPanel input = new JPanel();
input.add(inputTxt);
input.add(send);
v.add(new JScrollPane(chatTxt));
v.add(input);
add(v);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
clientThread.setOnline(false);//标志关闭聊天
/*
* 问题:关闭聊天窗口后,再次打开,会出现前几次发送发送消息无效的情况
* 解决:发送缓存消息,用于将缓存的后台线程给结束掉
* */
Transporter transporter = new Transporter();
transporter.setSENDER(myQQ);
transporter.setRECEIVER(friendQQ);
transporter.setCOMMAND(Command.CACHE);
client.sendData(transporter);
}
});
}
@Override
public void actionPerformed(ActionEvent e) {
//如果点击了发送按钮且不为空时,就向服务器发送消息
if (e.getSource() == send && !"".equals(inputTxt.getText())) {
Date date = new Date();//获取时间
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置时间格式
String message = name + " " + format.format(date) + " :\n" + inputTxt.getText();
chatTxt.append(message + "\n");
Transporter transporter = new Transporter();
//构造初始数据
transporter.setSENDER(myQQ);
transporter.setRECEIVER(friendQQ);
transporter.setCOMMAND(Command.MESSAGE);
transporter.setDATA(inputTxt.getText());
//向服务端发送数据
client.sendData(transporter);
//发送之后清空输入框
inputTxt.setText("");
}
}
}
| metaStor/chat | src/clients/UI/ChatUI.java |
64,996 | import java.util.Objects;
/**
* @Author: LvDaMing
* @Date: 2020-08-29
* @Description: 机器人能否返回原点
*/
public class Robot {
public static void main(String[] args) {
System.out.println(judgeCircle("RRLLUUDD"));
}
/**
* 在二维平面上,有一个机器人从原点(0,0)开始.给出它的移动顺序,判断这个机器人在完成
* 移动后是否在(0,0)处结束.
*
* 移动顺序由字符串表示.字符move[i]表示第i次移动.机器人的有效动作有R(右),L(左),
* U(上)和D(下).如果机器人在完成所有动作后返回原点,则返回true.否则,返回false.
*
* 注意:机器人"面朝"的方向无关紧要."R"将始终使机器人向右移动一次,"L"将始终向左移动等.
* 此外,假设每次移动机器人的移动幅度相同.
*
*
*/
/**
*
* 1.先将字符串转换为字符数组
* 2.根据数组下标找到对应的移动操作进行移动
* 3.x和y为0,则移动回原点
* @param moves
* @return
*/
public static boolean judgeCircle(String moves) {
if (Objects.isNull(moves) || moves.trim().length()<=0){
return false;
}
char [] chars = moves.toCharArray();
int x=0;
int y=0;
for (int i=0;i<chars.length;i++){
if (chars[i]!='R' && chars[i]!='L' && chars[i]!='U' && chars[i]!='D'){
return false;
}else if (chars[i] == 'R'){
x++;
}else if (chars[i] == 'L'){
x--;
}else if (chars[i] == 'U'){
y++;
}else if (chars[i] == 'D'){
y--;
}
}
return x==0&&y==0;
}
/**
* 1.获取字符串的长度
* 2.通过String的charAt(int x),循环每个字符进行比较,操作机器人移动
* 3.x和y为0,则移动回原点
* @param moves
* @return
*/
public static boolean judgeCircle_1(String moves) {
if (Objects.isNull(moves) || moves.trim().length()<=0){
return false;
}
int x=0;
int y=0;
int length = moves.length();
for (int i=0;i<length;i++){
switch (moves.charAt(i)){
case 'R':
x++;
break;
case 'L':
x--;
break;
case 'U':
y++;
break;
case 'D':
y--;
break;
default:
return false;
}
}
return x==0&&y==0;
}
}
| elastic-work/algorithm | 数组/机器人能否返回原点/Robot.java |
64,997 | package frame.game;
import lombok.Getter;
/**
* @author KAZER
* @version 创建时间:2019年7月13日 下午6:02:07 类说明
*/
@Getter
public class Banker {
/**
* 系统
*/
public static final int SYSTEM_BANKER = 1;
/**
* 机器人
*/
public static final int ROBOT_BANKER = 2;
/**
* 玩家
*/
public static final int PLAYER_BANKER = 3;
/**
* 庄家
*/
private Role banker;
/**
* 庄家身份 (1:系统 2:机器人 3:玩家)
*/
private int identity;
/**
* 庄家输赢
*/
private long winLoseMoney;
/**
* 最大当庄数
*/
private int bankerMaxNum;
/**
* 当庄次数
*/
private int bankerNum;
public Banker() {
createSystemBanker();
}
/**
* 新建系统当庄
*/
protected void createSystemBanker() {
this.identity = SYSTEM_BANKER;
this.banker = SystemBanker.instance();
this.bankerNum = 0;
}
/**
* 更新庄家(玩家)
*
* @param role
* @param bankerMaxNum
*/
protected void updataBanker(Role role, int bankerMaxNum) {
if (role instanceof Robot) {
this.identity = ROBOT_BANKER;
} else if (role instanceof Player) {
this.identity = PLAYER_BANKER;
} else {
this.identity = SYSTEM_BANKER;
}
this.bankerMaxNum = bankerMaxNum;
this.bankerNum = 0;
this.banker = role;
this.winLoseMoney = 0;
}
/**
* 添加一次当庄次数
*/
protected void updataMasterNum() {
this.bankerNum += 1;
this.winLoseMoney = 0;
if(this.bankerNum >= 99999) {
this.bankerNum = 0;
}
}
/**
* 保存庄家输赢
* @param money
*/
protected void saveWinLose(long money) {
this.winLoseMoney = money;
}
/**
*
* @param num
*/
protected void addBankerMaxNum(int num) {
this.bankerMaxNum += num;
}
}
| DaddyXjy/ChessGameServeFrame | frame/game/Banker.java |
64,999 | import java.util.Set;
/*
* @lc app=leetcode.cn id=874 lang=java
*
* [874] 模拟行走机器人
*/
// @lc code=start
class Solution {
public int robotSim(int[] commands, int[][] obstacles) {
Set<String> set = new HashSet<String>();
for(int[] o : obstacles)
set.add(o[0] + " " + o[1]);
int max =0, x = 0,y = 0,dir = 0,dirs[][] = {{0,1},{1,0},{0,-1},{-1,0}};
for(int c :commands){
if(c == -2)
dir = dir == 0 ? 3 : dir - 1;
else if(c == -1)
dir = dir == 3 ? 0 : dir + 1;
else{
int[] xy = dirs[dir];
while(c-- > 0 && !set.contains((x + xy[0]) + " " + (y + xy[1]))){
x += xy[0];y += xy[1];
}
}
max = Math.max(max, x *x + y * y);
}
return max;
}
}
// @lc code=end
| algorithm004-01/algorithm004-01 | Week 03/id_611/LeetCode_874_611.java |
65,000 | //在二维平面上,有一个机器人从原点 (0, 0) 开始。给出它的移动顺序,判断这个机器人在完成移动后是否在 (0, 0) 处结束。
//
// 移动顺序由字符串 moves 表示。字符 move[i] 表示其第 i 次移动。机器人的有效动作有 R(右),L(左),U(上)和 D(下)。
//
// 如果机器人在完成所有动作后返回原点,则返回 true。否则,返回 false。
//
// 注意:机器人“面朝”的方向无关紧要。 “R” 将始终使机器人向右移动一次,“L” 将始终向左移动等。此外,假设每次移动机器人的移动幅度相同。
//
//
//
// 示例 1:
//
//
//输入: moves = "UD"
//输出: true
//解释:机器人向上移动一次,然后向下移动一次。所有动作都具有相同的幅度,因此它最终回到它开始的原点。因此,我们返回 true。
//
// 示例 2:
//
//
//输入: moves = "LL"
//输出: false
//解释:机器人向左移动两次。它最终位于原点的左侧,距原点有两次 “移动” 的距离。我们返回 false,因为它在移动结束时没有返回原点。
//
//
//
// 提示:
//
//
// 1 <= moves.length <= 2 * 10⁴
// moves 只包含字符 'U', 'D', 'L' 和 'R'
//
//
// Related Topics 字符串 模拟 👍 253 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public boolean judgeCircle(String moves) {
int x = 0, y = 0;
for (char c : moves.toCharArray()) {
switch (c) {
case 'U':
y++;
break;
case 'D':
y--;
break;
case 'R':
x++;
break;
case 'L':
x--;
break;
}
}
return x == 0 && y == 0;
}
}
//leetcode submit region end(Prohibit modification and deletion)
| xftxyz2001/leetcode-editor-cn | [657]机器人能否返回原点.java |
65,001 | package com.unsan.core;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.unsan.core.classLoader.PrivateClassLoader;
import com.unsan.core.classLoader.PrivateURLClassLoader;
import com.unsan.core.constants.UnsanParameters;
import com.unsan.core.robot.BaseRobot;
import com.unsan.core.utils.FileUtils;
public class RobotFactory {
private Logger log;
/*
* 机器人
*/
private Hashtable<String, BaseRobot> robots = new Hashtable<>();
/*
* 机器人配置
*/
private List<Map<String,String>> robotConf = new ArrayList<>();
private SAXReader read = new SAXReader();
/**
* 单例模式 延迟加载+线程安全
*
* @return
*/
public static RobotFactory getInstance() {
return ClientHolder.instance;
}
private static class ClientHolder {
private static RobotFactory instance = new RobotFactory();
}
/**
* 从零件组装成机器人
*/
@SuppressWarnings("unchecked")
public void buildRobots() {
this.log = LoggerFactory.getLogger(getClass());
log.info("机器工厂从文件中组装机器人...");
//从核心目录下读取
readCoreFile();
//从拓展目录下读取
readExpandFile();
// 整理启动顺序
Collections.sort(robotConf,new Comparator<Map<String,String>>(){
@Override
public int compare(Map<String,String> o1, Map<String,String> o2) {
double priority1 = 0d;
double priority2 = 0d;
if(o1 != null ){
String o1P = o1.get("loadPriority");
priority1 = Double.parseDouble(o1P) ;
}else{
}
if(o2 != null){
String o2P = o2.get("loadPriority");
priority2 = Double.parseDouble(o2P) ;
}
int rt = new Double(priority1 - priority2).intValue();
return rt;
}
});
}
/*
* 从核心目录下获取
*/
private void readCoreFile(){
try {
read.setEncoding("UTF-8");
log.debug("核心目录: "+UnsanParameters.RUNTIME_PATH+File.separatorChar+"conf"+File.separatorChar+UnsanParameters.CONFILE);
Document doc = read.read(new File(UnsanParameters.RUNTIME_PATH+File.separatorChar+"conf"+File.separatorChar+UnsanParameters.CONFILE));
Element unsan = doc.getRootElement();
// Element unsan = root.element("robot");
Iterator<?> it = unsan.elementIterator("robot");
while (it.hasNext()) {
Element mod = (Element)it.next();
Map<String, String> map = new HashMap<String, String>();
map.put("name", mod.element("name").getTextTrim());
map.put("class", mod.element("class").getTextTrim());
if(mod.element("confPath")!=null){
map.put("confPath", mod.element("confPath").getTextTrim());
}
if(mod.element("privateLib")!=null){
map.put("privateLib", mod.element("privateLib").getTextTrim());
}
if(mod.element("loadPriority")!=null){
map.put("loadPriority", mod.element("loadPriority").getTextTrim());
}else{
map.put("loadPriority", UnsanParameters.DEFAULT_LOAD_PRIORITY);
}
if(mod.element("workThreadNum")!=null){
map.put("workThreadNum", mod.element("workThreadNum").getTextTrim());
}else{
map.put("workThreadNum", UnsanParameters.DEFAULT_THREAD_NUM);
}
robotConf.add(map);
}
} catch (DocumentException e) {
log.info("机器工厂 扫描文件位置或者读取失败 详情 "+e.toString());
e.printStackTrace();
}
}
/*
* 从拓展目录下获取
* 以Unsan开头 以。xml结尾的module
*/
private void readExpandFile(){
//TODO:://从拓展目录下获得机器人
read.setEncoding("UTF-8");
log.debug("拓展路径: "+UnsanParameters.External_PATH);
File exRootDir = new File(UnsanParameters.External_PATH);
//Document doc = read.read();
if (!exRootDir.exists()) {
this.log.info("无外部模块需要加载");
return;
}
List<File> unsanXml = new ArrayList<>();
FileUtils.readUnsanXml(unsanXml, exRootDir);
for(File fxml: unsanXml ){
//String privateLib = FileUtils.readPrivateLibPath(fxml);
try {
FileInputStream in = new FileInputStream(fxml);
Document doc = read.read(in);
Element unsan = doc.getRootElement();
Iterator<?> it = unsan.elementIterator("robot");
while (it.hasNext()) {
Element mod = (Element)it.next();
Map<String, String> map = new HashMap<String, String>();
map.put("name", mod.element("name").getTextTrim());
map.put("class", mod.element("class").getTextTrim());
if(mod.element("confPath")!=null){
map.put("confPath", mod.element("confPath").getTextTrim());
}
if(mod.element("privateLib")!=null){
map.put("privateLib", mod.element("privateLib").getTextTrim());
}
if(mod.element("loadPriority")!=null){
map.put("loadPriority", mod.element("loadPriority").getTextTrim());
}else{
map.put("loadPriority", UnsanParameters.DEFAULT_LOAD_PRIORITY);
}
if(mod.element("workThreadNum")!=null){
map.put("workThreadNum", mod.element("workThreadNum").getTextTrim());
}else{
map.put("workThreadNum", UnsanParameters.DEFAULT_THREAD_NUM);
}
map.put("xmlPath", fxml.getAbsolutePath());
robotConf.add(map);
}
} catch (DocumentException | FileNotFoundException e) {
this.log.error(String.format("获取模块[%s]配置失败", new Object[] { fxml.getName() }), e);
e.printStackTrace();
}
}
}
/**
* 装载机器人到JVM
*/
public void loadRobots() {
log.info("机器工厂装载机器人到JVM...");
for(Map robot : this.robotConf){
loadRobot(robot);
}
}
/*
* 加载机器到JVM
*/
@SuppressWarnings("unchecked")
private void loadRobot(Map<String,String> robotMap) {
String robotClassName = robotMap.get("class");
String robotName = robotMap.get("name");
String filePath = robotMap.get("confPath");
String privateLib = robotMap.get("privateLib");
String xmlPath = robotMap.get("xmlPath");
try {
//new PrivateClassLoader(robotName)
//sddnew PrivateClassLoader(robotName).findClass("");
//直接初始化
Class<BaseRobot> robotclass = null;
if(privateLib!=null){
robotclass = (Class<BaseRobot>) Class.forName(robotClassName,true,new PrivateURLClassLoader(FileUtils.searchModuleJarFromXml(xmlPath),privateLib));
}else{
robotclass = (Class<BaseRobot>) Class.forName(robotClassName);
}
// robotclass = (Class<BaseRobot>) Class.forName(robotClassName,true,new URLClassLoader(FileUtils.searchJarURL(privateLib)));
/**
* 判断 该模块下有没有lib包 如果有 先用lib包的jar的classLoader加载类 如果加载不成功则用内存中的类。
*
*/
// try {
// String className = "ceshi.com.jvm.classload.target.Target";
// URLClassLoader load1 = new URLClassLoader(new URL[]{new URL("file:C:\\Users\\Administrator\\Desktop\\target1.jar")});
// URLClassLoader load2 = new URLClassLoader(new URL[]{new URL("file:C:\\Users\\Administrator\\Desktop\\target2.jar")});
//
// Class<BaseRobot> clazz1 = (Class<BaseRobot>)Class.forName(className,true,load1);
//
// Class<BaseRobot> clazz2 = (Class<BaseRobot>)Class.forName(className,true,load2);
// BaseRobot taget1 = clazz1.newInstance();
// BaseRobot taget2 = clazz2.newInstance();
// System.out.println("--------------target start-----------");
// taget1.create();
// System.out.println("");
// taget2.create();
// System.out.println("--------------target end-----------");
//
// } catch (MalformedURLException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
log.debug("【"+robotclass+"】 使用类加载器::: "+robotclass.getClassLoader());
BaseRobot robot = robotclass.newInstance();
robot.assemble(filePath);
robot.create();
robots.put(robotName, robot);
} catch (ClassNotFoundException e) {
log.error(String.format("机器人 %s 类找不到 , 无法加载到内存 详情: %s ", robotName,e.toString()));
e.printStackTrace();
} catch (InstantiationException e) {
log.error(String.format("机器人 %s 初始化错误 , 无法加载到内存 详情: %s ", robotName,e.toString()));
e.printStackTrace();
} catch (IllegalAccessException e) {
log.error(String.format("机器人 %s 初始化参数错误 , 无法加载到内存 详情: %s ", robotName,e.toString()));
e.printStackTrace();
}
}
/**
* 唤醒机器人
*/
public void wakeupAll() {
log.info("机器工厂唤醒机器人...");
for(Map robot : this.robotConf){
startRobot(robot);
}
}
/*
* 唤醒机器人 然后开始工作
*/
private void startRobot(Map robotMap) {
BaseRobot robot = robots.get(robotMap.get("name"));
robot.start();
}
/**
* 销毁所有机器人
*
*/
public void destroyAll() {
log.info("机器工厂销毁所有机器人...");
}
public Hashtable<String, BaseRobot> getRobots() {
return robots;
}
public static void main(String[] args) {
try {
String className = "ceshi.com.jvm.classload.target.Target";
//URLClassLoader load1 = new URLClassLoader(FileUtils.searchJarURL(privateLib));
//URLClassLoader load1 = (Class<BaseRobot>) Class.forName(className,true,new URLClassLoader(FileUtils.searchJarURL("C:\\Users\\Administrator\\Desktop\\Unsan\\Unsan_Robot_External\\wali\\privatelib")));
//URLClassLoader load2 = new URLClassLoader(new URL[]{new URL("file:C:\\Users\\Administrator\\Desktop\\target2.jar")});
Class<BaseRobot> clazz1 = (Class<BaseRobot>)Class.forName(className,true,new PrivateURLClassLoader(FileUtils.searchJarURL("C:\\Users\\Administrator\\Desktop\\Unsan\\Unsan_Robot_External\\wali\\privatelib"),new PrivateClassLoader("ceshi")));
//Class<BaseRobot> clazz2 = (Class<BaseRobot>)Class.forName(className,true,load2);
BaseRobot taget1 = clazz1.newInstance();
//BaseRobot taget2 = clazz2.newInstance();
System.out.println("--------------target start-----------"+clazz1.getClassLoader());
taget1.create();
System.out.println("");
//taget2.create();
System.out.println("--------------target end-----------");
} catch ( ClassNotFoundException | InstantiationException | IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| OMGgogong/Unsan | src/com/unsan/core/RobotFactory.java |
65,002 | package easy;
/**
* 在二维平面上,有一个机器人从原点 (0, 0) 开始。给出它的移动顺序,判断这个机器人在完成移动后是否在 (0, 0) 处结束。
* <p>
* 移动顺序由字符串表示。字符 move[i] 表示其第 i 次移动。机器人的有效动作有 R(右),L(左),U(上)和 D(下)。如果机器人在完成所有动作后返回原点,则返回 true。否则,返回 false。
* <p>
* 注意:机器人“面朝”的方向无关紧要。 “R” 将始终使机器人向右移动一次,“L” 将始终向左移动等。此外,假设每次移动机器人的移动幅度相同。
* 示例 1:
* 输入: "UD"
* 输出: true
* 解释:机器人向上移动一次,然后向下移动一次。所有动作都具有相同的幅度,因此它最终回到它开始的原点。因此,我们返回 true。
* 示例 2:
* <p>
* 输入: "LL"
* 输出: false
* 解释:机器人向左移动两次。它最终位于原点的左侧,距原点有两次 “移动” 的距离。我们返回 false,因为它在移动结束时没有返回原点。
*/
public class RobotReturntoOrigin {
/**
* 题意:机器人走方向,问能否回到原点。
* 解法:模拟即可。
*/
public boolean judgeCircle(String moves) {
int x = 0, y = 0;
int length = moves.length();
for (int i = 0; i < length; i++) {
char move = moves.charAt(i);
if (move == 'U') {
y--;
} else if (move == 'D') {
y++;
} else if (move == 'L') {
x--;
} else if (move == 'R') {
x++;
}
}
return x == 0 && y == 0;
}
}
| chaangliu/leetcode-training | easy/RobotReturntoOrigin.java |
65,004 | import java.util.Timer;
import java.util.TimerTask;
public class RobotAllocation {
public static final int ROBOT_CAPACITY = 10;//机器人容量
public static final long ROBOT_SPEED = 10;//机器人速度
public void allocate(int cargo, double distance, Robot[] robots) throws InterruptedException {
long time = (long)(distance / ROBOT_SPEED);//机器人运输一趟的时间
int count = 0;//空闲机器人数
//统计剩余空闲机器人数
for(int i = 0; i < Constants.ROBOT_QUANTITY; i ++){
if(robots[i].getState() == 0){
count ++;
}
}
int totalNum = cargo / ROBOT_CAPACITY + (cargo % ROBOT_CAPACITY != 0 ? 1 : 0);//总共还需要的机器人数
//机器人数量够
if(totalNum <= count){
//将用到的机器人的状态置为占用,并在运送完成后置为空闲
for(int i = 0; i < Constants.ROBOT_QUANTITY; i ++){
if(robots[i].getState() == 0 && totalNum > 0){
robots[i].setState(1);
System.out.println("机器人"+robots[i].getId()+"被占用");
reset(robots[i], time);
totalNum --;
}
}
//机器人数量不够
}else {
cargo = cargo - count * ROBOT_CAPACITY;//更新剩余货量
//将剩余的所有机器人的状态置为占用,并在运送完成后置为空闲
for(int i = 0; i < Constants.ROBOT_QUANTITY; i ++){
if(robots[i].getState() == 0){
robots[i].setState(1);
System.out.println("机器人"+robots[i].getId()+"被占用");
reset(robots[i], time);
}
}
//等待再次有空闲的机器人并分配
pause(robots);
RobotAllocation temp = new RobotAllocation();
temp.allocate(cargo, distance, robots);
System.out.println("");
}
}
//将机器人状态置为空闲
private static void reset(Robot robot, long time){
Timer timer=new Timer();
TimerTask task=new TimerTask(){
public void run(){
robot.setState(0);
System.out.println("机器人"+robot.getId()+"完成运输,空闲");
cancel();
System.gc();
}
};
timer.schedule(task,time);//延迟执行
}
//等待有空闲的机器人
private static void pause(Robot[] robots) throws InterruptedException {
Thread.currentThread().sleep(1000);
//如果没有空闲的机器人,继续等待
if (isFree(robots) == false){
pause(robots);
}
}
//判断是否有机器人空闲
private static boolean isFree(Robot[] robots){
boolean isFree = false;
for(int i = 0; i < Constants.ROBOT_QUANTITY; i ++){
if(robots[i].getState() == 0){
isFree = true;
}
}
return isFree;
}
}
| simolark/SmartWarehouse | model/allocation/src/RobotAllocation.java |
65,006 | import java.util.HashMap;
import java.util.Map;
/**
* @auth Nannf
* @date 2020/8/28 12:05
* @description: 在二维平面上,有一个机器人从原点 (0, 0) 开始。给出它的移动顺序,判断这个机器人在完成移动后是否在 (0, 0) 处结束。
* <p>
* 移动顺序由字符串表示。字符 move[i] 表示其第 i 次移动。机器人的有效动作有 R(右),L(左),U(上)和 D(下)。
* 如果机器人在完成所有动作后返回原点,则返回 true。否则,返回 false。
* <p>
* 注意:机器人“面朝”的方向无关紧要。 “R” 将始终使机器人向右移动一次,“L” 将始终向左移动等。此外,假设每次移动机器人的移动幅度相同。
* <p>
* <p>
* 输入: "UD"
* 输出: true
* 解释:机器人向上移动一次,然后向下移动一次。所有动作都具有相同的幅度,因此它最终回到它开始的原点。因此,我们返回 true。
* <p>
* <p>
* 输入: "LL"
* 输出: false
* 解释:机器人向左移动两次。它最终位于原点的左侧,距原点有两次 “移动” 的距离。我们返回 false,因为它在移动结束时没有返回原点。
* <p>
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/robot-return-to-origin
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
public class Solution_657 {
public static void main(String[] args) {
String str = "RULDDLLDLRDUUUURULRURRRRLRULRLULLLRRULULDDRDLRULDRRULLUDDURDLRRUDRUDDURLLLUUDULRUDRLURRDRLLDDLLLDLRLLRUUDUURDRLDUDRUDRLUDULRLUDRLDDUULDDLDURULUDUUDDRRDUURRLRDLDLRLLDRRUUURDLULLURRRRDRRURDUURDLRRUULRURRUULULUUDURUDLRDDDDDURRRLRUDRUULUUUULDURDRULLRRRUDDDUUULUURRDRDDRLLDRLDULDLUUDRDLULLDLDDRUUUUDDRRRDLLLLURUURLRUUULRDDULUULUURDURDDDRRURLURDLLLRLULRDLDDLRDRRRRLUURRRRLDUDLLRUDLDRDLDRUULDRDULRULRRDLDLLLUDLDLULLDURUURRLLULUURLRLRDUDULLDURRUDDLDDLLUDURLLRLDLDUDLURLLDRRURRDUDLDUULDUDRRUDULLUUDURRRURLULDDLRRURULUURURRDULUULDDDUUDRLDDRLULDUDDLLLDLDURDLRLUURDDRLUDRLUDLRRLUUULLDUUDUDURRUULLDDUDLURRDDLURLDRDRUDRLDDLDULDRULUDRRDRLLUURULURRRUDRLLUURULURRLUULRDDDRDDLDRLDRLDUDRLDRLDDLDUDDURUDUDDDLRRDLUUUDUDURLRDRURUDUDDRDRRLUDURULDULDDRLDLUURUULUDRLRLRLLLLRLDRURRRUULRDURDRRDDURULLRDUDRLULRRLLLDRLRLRRDULDDUDUURLRULUUUULURULDLDRDRLDDLRLURRUULRRLDULLUULUDUDRLDUDRDLLDULURLUDDUURULDURRUURLRDRRRLDDULLLLDDRRLRRDRDLRUDUUDLRLDRDRURULDLULRRDLLURDLLDLRDRURLRUDURDRRRULURDRURLDRRRDUDUDUDURUUUUULURDUDDRRDULRDDLULRDRULDRUURRURLUDDDDLDRLDLLLLRLDRLRDRRRLLDRDRUULURLDRULLDRRDUUDLURLLDULDUUDLRRRDDUDRLDULRDLLULRRUURRRURLRRLDDUDDLULRUDULDULRDUDRLRDULRUUDDRUURUDLDRDUDDUULLUDDLLRLURURLRRULLDDDLURDRRDLLLLULLDLUDDLURLLDDRLDLLDDRDRDDUDLDURLUUUUUDLLLRLDULDDRDDDDRUDLULDRRLLLDUUUDDDRDDLLULUULRRULRUDRURDDULURDRRURUULDDDDUULLLURRRRDLDDLRLDDDRLUUDRDDRDDLUDLUUULLDLRDLURRRLRDRLURUURLULLLLRDDLLLLRUDURRLDURULURULDDRULUDRLDRLLURURRRDURURDRRUDLDDLLRRDRDDLRLRLUDUDRRUDLLDUURUURRDUDLRRLRURUDURDLRRULLDLLUDURUDDRUDULLDUDRRDDUDLLLDLRDRUURLLDLDRDDLDLLUDRDDRUUUDDULRUULRDRUDUURRRURUDLURLRDDLUULRDULRDURLLRDDDRRUDDUDUDLLDDRRUUDURDLLUURDLRULULDULRUURUDRULDRDULLULRRDDLDRDLLLDULRRDDLDRDLLRDDRLUUULUURULRULRUDULRULRUURUDUUDLDUDUUURLLURDDDUDUDLRLULDLDUDUULULLRDUDLDRUDRUULRURDDLDDRDULRLRLRRRRLRULDLLLDDRLUDLULLUUDLDRRLUDULRDRLLRRRULRLRLLUDRUUDUDDLRLDRDDDDRDLDRURULULRUURLRDLLDDRLLRUDRRDDRDUDULRUDULURRUDRDLRDUUDDLDRUDLLDDLRLULLLRUUDRRRRUULLRLLULURLDUDDURLRULULDLDRURDRLLURRDLURRURLULDLRLDUDLULLLDRDLULDLRULLLUDUDUDUDLDDDDDRDLUDUULLUDRLUURDRLULD";
if (new Solution_657().judgeCircle(str)) {
System.out.println("bingo!");
}
}
public boolean judgeCircle(String moves) {
Map<Character, Integer> map = new HashMap<>();
map.put('R', 0);
map.put('L', 0);
map.put('U', 0);
map.put('D', 0);
for (int i = 0; i < moves.length(); i++) {
map.put(moves.charAt(i),map.get(moves.charAt(i))+1);
}
return map.get('R').intValue() == map.get('L').intValue() && map.get('U').intValue()
== map.get('D').intValue();
}
}
| Nannf/LeetCode | Solution/src/Solution_657.java |
65,009 |
// 题目1408:吃豆机器人
/**
* @author:wangzq
* @email:[email protected]
* @date:2015-06-30 11:01:55
* @url:http://ac.jobdu.com/problem.php?pid=1408
*/
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
public class Main {
/*
* 1408
*/
private static long dp[][] = new long[1002][1002];
private static int len = 1002;
static {
for (int i = 1; i < len; i++) {
dp[i][1] = 1;
dp[1][i] = 1;
}
for (int i = 2; i < len; i++) {
for (int j = 2; j < len; j++) {
dp[i][j] = (dp[i - 1][j] + dp[i][j - 1]) % 10009;
}
}
}
public static void main(String[] args) throws Exception {
StreamTokenizer st = new StreamTokenizer(new BufferedReader(
new InputStreamReader(System.in)));
while (st.nextToken() != StreamTokenizer.TT_EOF) {
int n = (int) st.nval;
st.nextToken();
int m = (int) st.nval;
System.out.println(dp[n][m]);
}
}
}
/**************************************************************
Problem: 1408
User: wzqwsrf
Language: Java
Result: Accepted
Time:580 ms
Memory:35848 kb
****************************************************************/
| wzqwsrf/Jobdu | Java/题目1408:吃豆机器人.java |
65,010 | //--- 可穿戴的机器人 类 ---//
public class WearableRobot implements Color, Wearable {
private int color; // 颜色
public WearableRobot(int color) { changeColor(color); }
public void changeColor(int color) { this.color = color; }
public String toString() {
switch (color) {
case RED : return "红色机器人";
case GREEN : return "绿色机器人";
case BLUE : return "蓝色机器人";
}
return "机器人";
}
public void putOn() {
System.out.println(toString() + " 戴上!!");
}
public void putOff() {
System.out.println(toString() + " 摘下!!");
}
}
| OctopusLian/MingJieJava | Chap14/WearableRobot.java |
65,011 | package com.zdcf.tool;
import java.security.MessageDigest;
/**
* md5加密
* @author 图灵机器人
*
*/
public class Md5 {
/**
* MD5加密算法
*
* 说明:32位加密算法
*
* @param 待加密的数据
* @return 加密结果,全小写的字符串
*/
public static String MD5(String s) {
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f' };
try {
byte[] btInput = s.getBytes("utf-8");
// 获得MD5摘要算法的 MessageDigest 对象
MessageDigest mdInst = MessageDigest.getInstance("MD5");
// 使用指定的字节更新摘要
mdInst.update(btInput);
// 获得密文
byte[] md = mdInst.digest();
// 把密文转换成十六进制的字符串形式
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
| pospospos2007/albert | albert/src/com/zdcf/tool/Md5.java |
65,012 | /**
* 在二维平面上,有一个机器人从原点 (0, 0) 开始。给出它的移动顺序,判断这个机器人在完成移动后是否在 (0, 0) 处结束。
* 移动顺序由字符串表示。字符 move[i] 表示其第 i 次移动。机器人的有效动作有 R(右),L(左),U(上)和 D(下)。如果机器人在完成所有动作后返回原点,则返回 true。否则,返回 false。
* 注意:机器人“面朝”的方向无关紧要。 “R” 将始终使机器人向右移动一次,“L” 将始终向左移动等。此外,假设每次移动机器人的移动幅度相同。
*
* 示例 1:
* 输入: "UD"
* 输出: true
* 解释:机器人向上移动一次,然后向下移动一次。所有动作都具有相同的幅度,因此它最终回到它开始的原点。因此,我们返回 true。
*
* 示例 2:
* 输入: "LL"
* 输出: false
* 解释:机器人向左移动两次。它最终位于原点的左侧,距原点有两次 “移动” 的距离。我们返回 false,因为它在移动结束时没有返回原点。
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/robot-return-to-origin
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
public class Q00657s {
public boolean judgeCircle(String moves) {
if ((moves.length() & 1) == 1) return false; // 奇数一定回不来
int ud = 0, lr = 0;
for (int i = 0; i < moves.length(); i++) {
char c = moves.charAt(i);
if (c == 'L') {
lr--;
} else if (c == 'R') {
lr++;
} else if (c == 'U') {
ud--;
} else {
ud++;
}
}
return ud == 0 && lr == 0;
}
}
| ldang264/openlcs | src/main/java/Q00657s.java |
65,014 | package com.xk.utils;
import java.security.Key;
import java.security.MessageDigest;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Encoder;
/**
* aes加密算法
* @author 图灵机器人
*
*/
public class Aes {
private BASE64Encoder encoder = new BASE64Encoder();
private Key key;
/**
* AES CBC模式使用的Initialization Vector
*/
private IvParameterSpec iv;
/**
* Cipher 物件
*/
private Cipher cipher;
/**
* 构造方法
* @param strKet
* 密钥
*/
public Aes(String strKey) {
try {
this.key = new SecretKeySpec(getHash("MD5", strKey), "AES");
this.iv = new IvParameterSpec(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0 });
this.cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
} catch (final Exception ex) {
throw new RuntimeException(ex.getMessage());
}
}
/**
* 加密方法
*
* 说明:采用128位
*
* @return 加密结果
*/
public String encrypt(String strContent) {
try {
byte[] data = strContent.getBytes("UTF-8");
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
byte[] encryptData = cipher.doFinal(data);
String encryptResult = encoder.encode(encryptData);
return encryptResult;
} catch (Exception ex) {
throw new RuntimeException(ex.getMessage());
}
}
/**
*
* @param algorithm
* @param text
* @return
*/
private static byte[] getHash(String algorithm, String text) {
try {
byte[] bytes = text.getBytes("UTF-8");
final MessageDigest digest = MessageDigest.getInstance(algorithm);
digest.update(bytes);
return digest.digest();
} catch (final Exception ex) {
throw new RuntimeException(ex.getMessage());
}
}
}
| smokingrain/WeChat | src/com/xk/utils/Aes.java |
65,016 | package com.push.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.push.AbstractPush;
import com.push.model.PushMetaInfo;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
/**
* 钉钉机器人.
*
* @author itning
* @since 2021/3/22 19:15
*/
@Slf4j
public class DingTalkPush extends AbstractPush {
private final int DING_TALK_MESSAGE_MAX_LENGTH = 15000;
@Override
protected String generatePushUrl(PushMetaInfo metaInfo) {
return metaInfo.getToken();
}
@Override
protected boolean checkPushStatus(JSONObject jsonObject) {
if (jsonObject == null) {
return false;
}
Integer errcode = jsonObject.getInteger("errcode");
String errmsg = jsonObject.getString("errmsg");
if (null == errcode || null == errmsg) {
return false;
}
return errcode == 0 && "ok".equals(errmsg);
}
@Override
protected String generatePushBody(PushMetaInfo metaInfo, String content) {
return JSON.toJSONString(new MessageModel(content));
}
@Override
protected List<String> segmentation(PushMetaInfo metaInfo, String pushBody) {
if (StringUtils.isBlank(pushBody)) {
return Collections.emptyList();
}
if (pushBody.length() > DING_TALK_MESSAGE_MAX_LENGTH) {
log.info("推送内容长度[{}]大于最大长度[{}]进行分割处理", pushBody.length(), DING_TALK_MESSAGE_MAX_LENGTH);
List<String> pushContent = Arrays.stream(splitStringByLength(pushBody, DING_TALK_MESSAGE_MAX_LENGTH)).collect(Collectors.toList());
log.info("分割数量:{}", pushContent.size());
return pushContent;
}
return Collections.singletonList(pushBody);
}
@Getter
static class MessageModel {
private final String msgtype = "text";
private final String title = "Oldwu-HELPER任务简报";
private final Text text;
public MessageModel(String content) {
this.text = new Text(content);
}
}
@Getter
static class Text {
private final String content;
public Text(String content) {
this.content = content.replaceAll("\r\n\r", "");
}
}
}
| wyt1215819315/autoplan | src/main/java/com/push/impl/DingTalkPush.java |
65,018 | public class LeetCode657 {
//在二维平面上,有一个机器人从原点 (0, 0) 开始。给出它的移动顺序,判断这个机器人在完成移动后是否在 (0, 0) 处结束。
//
//移动顺序由字符串 moves 表示。字符 move[i] 表示其第 i 次移动。机器人的有效动作有 R(右),L(左),U(上)和 D(下)。
//
//如果机器人在完成所有动作后返回原点,则返回 true。否则,返回 false。
//
//注意:机器人“面朝”的方向无关紧要。 “R” 将始终使机器人向右移动一次,“L” 将始终向左移动等。此外,假设每次移动机器人的移动幅度相同。
public boolean judgeCircle(String moves) {
int countR=0,countL=0,countU=0,countD=0;
for(char c : moves.toCharArray()) {
switch(c) {
case 'R':
countR++;
break;
case 'L':
countL++;
break;
case 'U':
countU++;
break;
case 'D':
countD++;
break;
}
}
if(countD==countU && countR==countL) {
return true;
}
return false;
}
}
| ColdGoose77/Java-ds-code | LeetCode657.java |
65,019 | // generics/DogsAndRobots.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Java中并无(直接的)潜在类型机制
import pets.Dog;
// 表演的狗
class PerformingDog extends Dog implements Performs {
@Override
public void speak() {
System.out.println("Woof!");
}
@Override
public void sit() {
System.out.println("Sitting");
}
public void reproduce() {
}
}
class Robot implements Performs {
@Override
public void speak() {
System.out.println("Click!");
}
@Override
public void sit() {
System.out.println("Clank!");
}
public void oilChange() {
}
}
// Communicate 沟通、传达
class Communicate { // 去泛型 版本,见下个示例。
// perform()方法不需要使用泛型来工作,它可以被简单地指定为接受一个Performs 对象
public static <T extends Performs> void perform(T performer) {
performer.speak();
performer.sit();
}
}
/**
* 潜在类型机制
*
* java不具备 潜在类型机制
* 但可以通过接口 实现 直接潜在类型
*
* 这种方式不够泛化,我们只能调用 接口中定义的方法,而不可能是“任意方法”,
* 而且,后期维护新增功能,只能新增继承的接口 或 在已继承的接口中新增方法定义。
*
*
*
* 这里,泛型不是必须的,因此,可改写成以下版本:
* generics/SimpleDogsAndRobots.java
*
* @see SimpleDogsAndRobots
*/
public class DogsAndRobots {
public static void main(String[] args) {
// 使用沟通类 给 狗 传达 表演指令
Communicate.perform(new PerformingDog());
// 使用沟通类 给 机器人 传达 表演指令
Communicate.perform(new Robot());
}
}
/* Output:
Woof!
Sitting
Click!
Clank!
*/
| wuxiongbo/onjava8 | generics/DogsAndRobots.java |
65,023 | package server;
import client.SkillFactory;
import client.ZZMSEvent;
import constants.GameConstants;
import constants.ServerConfig;
import constants.ServerConstants;
import constants.WorldConstants;
import database.DatabaseConnection;
import handling.cashshop.CashShopServer;
import handling.channel.ChannelServer;
import handling.channel.MapleDojoRanking;
import handling.channel.MapleGuildRanking;
import handling.farm.FarmServer;
import handling.login.LoginServer;
import handling.world.World;
import handling.world.guild.MapleGuild;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.concurrent.atomic.AtomicInteger;
import server.Timer.BuffTimer;
import server.Timer.CloneTimer;
import server.Timer.EtcTimer;
import server.Timer.EventTimer;
import server.Timer.MapTimer;
import server.Timer.PingTimer;
import server.Timer.WorldTimer;
import server.life.MapleLifeFactory;
import server.life.PlayerNPC;
import server.maps.MapleMapFactory;
import server.quest.MapleQuest;
import tools.MapleAESOFB;
public class Start {
public static long startTime = System.currentTimeMillis();
public static final Start Instance = new Start();
public static AtomicInteger CompletedLoadingThreads = new AtomicInteger(0);
public void run() throws InterruptedException, IOException {
long start = System.currentTimeMillis();
if (ServerConfig.ADMIN_ONLY || ServerConstants.USE_LOCALHOST) {
System.out.println("Admin Only mode is active.");
}
try (PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement("UPDATE accounts SET loggedin = 0")) {
ps.executeUpdate();
} catch (SQLException ex) {
throw new RuntimeException("运行时错误: 无法连接到MySQL数据库服务器 - " + ex);
}
System.out.println("正在加载" + ServerConfig.SERVER_NAME + "服务端");
World.init();
System.out.println("\r\n主机: " + ServerConfig.IP + ":" + LoginServer.PORT);
System.out.println("支援游戏版本: " + ServerConstants.MAPLE_TYPE + "的" + ServerConstants.MAPLE_VERSION + "." + ServerConstants.MAPLE_PATCH + "版本" + (ServerConstants.TESPIA ? "测试机" : "") + "用户端");
System.out.println("主服务端名称: " + WorldConstants.getMainWorld().name());
System.out.println("");
if (ServerConstants.MAPLE_TYPE == ServerConstants.MapleType.GLOBAL) {
boolean encryptionfound = false;
for (MapleAESOFB.EncryptionKey encryptkey : MapleAESOFB.EncryptionKey.values()) {
if (("V" + ServerConstants.MAPLE_VERSION).equals(encryptkey.name())) {
System.out.println("Packet Encryption: Up-To-Date!");
encryptionfound = true;
break;
}
}
if (!encryptionfound) {
System.out.println("无法找到您输入的枫叶版本的数据包加密。使用前面的数据包加密来代替。");
}
}
runThread();
loadData(false);
LoginServer.run_startup_configurations();
ChannelServer.startChannel_Main();
CashShopServer.run_startup_configurations();
if (ServerConstants.MAPLE_TYPE == ServerConstants.MapleType.GLOBAL) {
FarmServer.run_startup_configurations();
}
World.registerRespawn();
Runtime.getRuntime().addShutdownHook(new Thread(new Shutdown()));
System.out.println("加载地图元素");
//加载自订地图元素
MapleMapFactory.loadCustomLife(false);
//加载玩家NPC
PlayerNPC.loadAll();
LoginServer.setOn();
//System.out.println("Event Script List: " + ServerConfig.getEventList());
if (ServerConfig.LOG_PACKETS) {
System.out.println("数据包日志模式已启用");
}
if (ServerConfig.USE_FIXED_IV) {
System.out.println("反抓包功能已启用");
}
long now = System.currentTimeMillis() - start;
long seconds = now / 1000;
long ms = now % 1000;
System.out.println("\r\n加载完成, 耗时: " + seconds + "秒" + ms + "毫秒");
System.gc();
PingTimer.getInstance().register(System::gc, 1800000); // 每30分钟释放一次
}
public static void runThread() {
System.out.print("正在加载线程");
WorldTimer.getInstance().start();
EtcTimer.getInstance().start();
MapTimer.getInstance().start();
CloneTimer.getInstance().start();
System.out.print(/*"\u25CF"*/".");
EventTimer.getInstance().start();
BuffTimer.getInstance().start();
PingTimer.getInstance().start();
ZZMSEvent.start();
System.out.println("完成!\r\n");
}
public static void loadData(boolean reload) {
System.out.println("载入数据(因为数据量大可能比较久而且记忆体消耗会飙升)");
//加载等级经验
System.out.println("加载等级经验数据");
GameConstants.LoadEXP();
System.out.println("加载排名讯息数据");
//加载道场拍排名
MapleDojoRanking.getInstance().load(reload);
//加载公会排名
MapleGuildRanking.getInstance().load(reload);
//加载排名
// RankingWorker.run();
System.out.println("加载公会数据并清理不存在公会/宠物/机器人");
//清理已经删除的宠物
//MaplePet.clearPet();
//清理已经删除的机器人
//MapleAndroid.clearAndroid();
//加载公会并且清理无人公会
MapleGuild.loadAll();
//加载家族(家族功能已去掉)
// MapleFamily.loadAll();
System.out.println("加载任务数据");
//加载任务讯息
MapleLifeFactory.loadQuestCounts(reload);
//加载转存到数据库的任务讯息
MapleQuest.initQuests(reload);
System.out.println("加载道具数据");
//加载道具讯息(从WZ)
MapleItemInformationProvider.getInstance().runEtc(reload);
//加载道具讯息(从SQL)
MapleItemInformationProvider.getInstance().runItems(reload);
System.out.println("加载技能数据");
//加载技能
//SkillFactory.load(reload);
System.out.println("加载角色卡数据");
//加载角色卡讯息
CharacterCardFactory.getInstance().initialize(reload);
System.out.println("加载商城道具数据");
//加载商城道具讯息
//CashItemFactory.getInstance().initialize(reload);
System.out.println("加载掉宝数据");
//加载掉宝和全域掉宝数据
// MapleMonsterInformationProvider.getInstance().load();
//加载额外的掉宝讯息
// MapleMonsterInformationProvider.getInstance().addExtra();
System.out.println("loadSpeedRuns");
//?
SpeedRunner.loadSpeedRuns(reload);
System.out.println("数据载入完成!\r\n");
}
public static class Shutdown implements Runnable {
@Override
public void run() {
ShutdownServer.getInstance().run();
}
}
public static void main(final String args[]) throws InterruptedException, IOException {
Instance.run();
}
}
| stark24423/ZZMS_update189 | src/server/Start.java |
65,024 | package cn.sciuridae;
import cn.sciuridae.utils.SafeProperties;
import cn.sciuridae.utils.bean.HoreEvent;
import cn.sciuridae.utils.bean.PricnessConfig;
import cn.sciuridae.utils.bean.groupPower;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FileUtils;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import static cn.sciuridae.listener.Intercept.prcnessIntercept.On;
public class constant {
public static final String helpMsg = "1.其他功能帮助\n2.会战帮助\n3.工会帮助\n4.机器人设置\n5.bilibili相关帮助\n请选择命令提示菜单";
public static final String BilibiliMsg = "以下全部为私聊\n1.获取视频封面图片 [视频封面 av/bv号]\nav与bv需统一大小写\n例: 视频封面 av1145124 \n" +
"2.av/bv转换 \n直接输入av/bv号即可 \n例: av11458\n" +
"3.当前up直播状态 [直播 upuid]\n仅仅是b站直播,其他站的在计划中.jpg\n" +
"4.设置开播提示 [设置开播提示 up的uid]\n" +
"5.查看开播提示槽位使用情况 [查看开播提示]\n" +
"6.清除一个开播槽位上的记录 [清除开播提示 槽位]\n示例 清除开播提示 1\n" +
"直播信息均一分钟刷新一次";
public static final String CONFIG_MES = "设置文件均可在机器人运行后自动生成,有些配置项没有自动生成删掉对应的配置文件再[重载设置]即可\n修改配置文件必须使用重载设置命令才可使用编辑后的配置" +
"1.各个群内的开关,保存在config.txt中,true为开启,false为关闭\n若要修改则找到对应群号修改对应值即可\n2.扭蛋池信息保存在扭蛋.txt中 概率以千分之整数存储\n例如up三星出率为千分之七,则设置为7\n若要更换抽卡所发送的人物图片资源,则在旁边建以 image 文件夹\n向里面放入人物资源图片,文件以扭蛋.,txt中设置的人物名字为准,格式为png" +
"3.赛马事件则为 事件.txt文件 中\n赛马所受影响的马号以?占位\n例如有一个事件为 3号马摔倒了 它是坏事件,将其放入bedHorseEvent后面中括号里面,写入3号马摔倒了";
public static final String GROUP_HELP_MSG = "命令总览:\n" +
"打*为管理员指令**的为工会长指令 中括号内为指令不需要中括号 小括号内为可选内容 ,-为需要主人qq\n" +
"工会基础指令:\n" +
"\t1.创建工会[#建会 @机器人 工会名 游戏昵称]\n" +
"\t2.加入工会[#入会 @机器人 游戏昵称]\n" +
"\t3.*批量加入工会[#批量入会 @入会成员1 @入会成员2 ...]\n" +
"\t4.退出工会,[#退会 @机器人]\n" +
"\t\t注意:会长退会则为解散工会\n" +
"\t5.*将一个人踢出工会[#踢人 @那个人(那个人的qq号)]\n" +
"\t6.*更改工会名字[#改工会名 更改后的工会名]\n" +
" 7.更改自己/别人的名字[#改名 (@那个人) 更改后的名字]\n" +
"\t8.**转让会长权限(保留自己的管理员权限)[转让会长 @那个人]\n" +
"\t9.**设置一个人为管理员[设置管理 @那个人]\n" +
"\t10.**撤销他人的管理权限[撤下管理 @那个人]\n" +
"\t11.查看已加入工会 的成员列表[工会成员列表]\n" +
" 12.查看工会一些基本信息[工会信息]\n";
public static final String FIGHT_HELP_MSG = "工会战命令:\n" +
"\t1.开始进行会战[#开始会战 (时间)]\n" +
"\t\t时间参数可选,默认为今天\n" +
"\t\t时间格式举例:2020:05:06\n" +
"\t默认结束时间为8天后,即会战时间为\n" +
"\t2020-06-05 5点到2020-06-13 0点\n" +
"\t2.结束会战[#结束会战]\n" +
"\t3.表示自己正在出刀[#出刀]\n" +
"\t4.表示自己因为太菜挂树了[#挂树]\n" +
"\t5.出完刀向机器人提交成绩[#收刀 伤害值 (队伍编号)]\n" +
"\t这个队伍编号是区分大刀和dd刀的作用,例如1为大刀3为dd刀,可以不填,不填默认以交刀的顺序依次赋值\n"+
"\t\t如果有自信不会挂树可以直接用这个命令提交伤害\n" +
"\t\t但是如果挂了请注意不要透露给工会长自己的住宅地址,注意人身安全\n" +
"\t\t机器人不会接受没有提交出刀请求后的挂树命令\n" +
"\t6.*代替别人提交伤害数据[#代刀 @那个人 伤害值 (队伍编号)]\n" +
"\t7.*撤除出刀资料[#撤刀 出刀编号]\n" +
"\t\t这个命令只是删除了出刀信息,但是并不会更改boss信息,防止发生奇奇怪怪的事情\n" +
"\t\t需要管理手动调整\n" +
"\t8.查询现在的boss信息[boss状态]\n" +
"\t9.查看正在出刀(非挂树)的人[#正在出刀]\n" +
"\t10.查看正在树上的人[#查树]\n" +
"\t11.查询今日全部成员未出刀情况,[未出刀 (@那个人)]\n" +
"\t\t同下\n" +
"\t12.查询今日全部成员已出刀情况,[已出刀 (@那个人)]\n" +
"\t\t没有@其他人的情况下默认查看整个工会\n" +
"\t13.*调整boss血量,周目等一系列信息[#调整boss状态 (调整后的)周目 几王 血量]\\\n" +
"\t\t例:调整boss状态 2 4 2554 为调整到二周目4王2554剩余血量\n";
public static final String OTHER_HELP_MSG = "杂项指令:\n" +
"\t1.抽一发井(300抽)[#(up)井]\n" +
"\t\t带up就是up池,不带up就是白金池\n" +
"\t2.抽一发十连(10抽)[#(up)十连]\n" +
"\t2.抽n发[#(up)抽卡 n]\n" +
"\t-2.清除所有人的抽卡cd,私聊机器人 [清除扭蛋cd]\n" +
"\t3.加 密 通 话[切噜 要加密的话]\n" +
"\t3.有 内 鬼,终 止 交 易[翻译切噜 加密的话]\n" +
"\t4.生成excel统计表格[#生成excel (时间)]\n" +
"\t\t时间参数与上面相同\n" +
"\t5.获取登陆码[获取码],如果没码就会强行造一个码\n" +
"\t5.5登陆码更换 私聊机器人 [更换token]\n" +
"\t6.在一个群里关闭/开启这个机器人[#关闭/开启PcrTool]\n" +
"\t注意.这个关闭为总按钮,需群管才能使用\n" +
"\t7.在一个群里关闭/开启扭蛋[#关闭/开启扭蛋]\n" +
"\t8.在一个群里关闭/开启提醒买药小助手[#关闭/开启提醒买药小助手]\n" +
"\t9.读取使用机器人通用设置文件和扭蛋信息,私聊[重载设置]\n" +
"\t10.查看现在机器人设置,私聊[通用设置]" +
"\t11.查看群内开关设置[#查看本群设置]\n" +
"\t11.赌马准备[#赛马 @机器人]\n" +
"\t12.下注 [押马马号#金额] 示例 押马1#125\n" +
"\t12.赌马开始[#开始赛马 @机器人]\n" +
"\t13.关闭赌马[#关闭赛马]\n" +
"\t14.开启赌马[#开启赛马]\n" +
"\t15.每天免费币 [#给xcw上供]\n" +
"\t查看自己有多少币 [我有多少钱鸭老婆]\n" +
"\t查看群内设置 [#查看本群设置]\n" +
"\t看漂亮小姐姐 私聊机器人[我要看漂亮小姐姐]\n" +
"\t使所有人的签到状态为未签[刷新全部签到]\n" +
"默认设定:\n" +
"\t这个插件和插件的所有功能都是开启的\n" +
"\t每天5点检查树上的人,全 部 撸 下\n" +
"\t每天0点检查工会战结束的工会,生成一个总表\n" +
"\t生成的excel默认在jar文件旁边的excel文件夹下\n" +
"\texcel文件格式为 群号%时间\n" +
"\t抽一发井是有冷却的,具体问开这个机器人的人\n" +
"\t看boss状态不止可以使用上面那个指令,还可以试试boss, boss咋样了, boss还好吗\n" +
"\t设置管理员同理 设置管理, 设置管理员, 添加管理员, 添加管理\n" +
"\t输入老婆并@机器人会被机器人顺着网线过来真人格斗\n" +
"\t只要是管理员就可以踢掉任何人(不包括工会长)" +
"\t自定义卡池部分:\n" +
"\t卡池图片会优先从jar同级文件夹下的image文件夹下找\n" +
"\t图片名称为扭蛋.txt文件中的人物名,后缀为png\n" +
"\t例:扭蛋.txt中的白金池中有 镜华 则image下有一个镜华.png的图片\n";
public static final String coolQAt = "[CQ:at,qq=";
public static final String dateFormat = "yy:MM:dd";
public static final String error = "好像发生了点小错误";
public static final String isHaveGroup = "已经有工会了还想加别的工会,花心大萝卜";
public static final String isFullGroup = "这个工会已经满员啦,再和会长多py一次吧";
public static final String successJoinGroup = "成功加入工会啦,记得每天好好女装哦";
public static final String successOutGroup = "成功退出工会啦,记得每天好好男装哦";
public static final String successDropGroup = "成功销毁工会,一切都已不复存在";
public static final String successChangeSuperPower = "更换会长成功,为王的诞生献上礼炮";
public static final String isTree = "已经挂牢了,不要想偷偷从树上溜走了哟♥";
public static final String commandError = "啊咧咧,这个命令格式我看不懂鸭";
public static final String noThisGroup = "啊咧咧,本群的工会好像还没有建立呢";
public static final String notBossOrNotDate = " 工会战还没开启呢";
public static final String noFindTheOne = "没有找到这个人,是不是还没有入会?";
public static final int[] BossHpLimit = {6000000, 8000000, 10000000, 12000000, 20000000};//各个boss的血量上限
public static final String notPower = "权限不足,或未建立工会";
public static final String StartFightStartDouble = "会战已经开始惹,为什么还要再开一次";
public static final String SuccessEndFight = "会战结束惹";
public static final String EngFightStartDouble = "没有正在进行的会战惹";
public static final String Default_Welcome = "呐,呐~欢迎欧尼酱加入大★家★庭哦(。>V<。) !{bot_name}最喜欢欧尼酱了!欧尼酱,daisiki !让人家来「侍奉」欧尼酱吧< )";
public static final String[] kimo_Definde = {"hentai,谁是你老婆啦", "死肥宅一边玩去啦,不要打扰我", "本小姐不想理你,并向你扔了一只胖次",
"无应答......", "嗷呜%_%", "谁是你老婆啦,哼", "对方无应答", "你是个好人", "对不起!您拨打的用户暂时无法接通,请稍后再拨.Sorry!The subscriber you dialed can not be connected for the moment, please redial later."
, "傲娇与偏见", "刑法第二百三十六条 强奸罪\n" +
"以暴力、胁迫或者其他手段强奸妇女的,处三年以上十年以下有期徒刑。 奸淫不满十四周岁的幼女的,以强奸论,从重处罚。 强奸妇女、奸淫幼女,有下列情形之一的,处十年以上有期徒刑、无期徒刑或者死刑: (一)强奸妇女、奸淫幼女情节恶劣的; (二)强奸妇女、奸淫幼女多人的; (三)在公共场所当众强奸妇女的; (四)二人以上轮奸的; (五)致使被害人重伤、死亡或者造成其他严重后果的。",
"第二百三十七条 强制猥亵、侮辱罪\n" +
"以暴力、胁迫或者其他方法强制猥亵他人或者侮辱妇女的,处五年以下有期徒刑或者拘役。 聚众或者在公共场所当众犯前款罪的,或者有其他恶劣情节的,处五年以上有期徒刑。 猥亵儿童的,依照前两款的规定从重处罚。"};
public static final String[] QieLU = {"切噜", "切哩", "切吉", "噜拉", "啪噜", "切璐", "扣", "啦哩", "啦嘟", "切泼", "啪噼", ",", "嚕嚕", "啰哩", "切拉", "切噼"};
public static final String ExcelDir = "Excel/";
public static final String fileTimeFormat = "yy年MM月dd日";
public static final DateTimeFormatter df = DateTimeFormatter.ofPattern(fileTimeFormat);
public static String robotQQ = "0";//机器人qq
public static String[] one = {"日和莉", "怜", "未奏希", "胡桃", "依里", "由加莉", "铃莓", "碧", "美咲", "莉玛"};
public static String[] two = {"茜里", "宫子", "雪", "铃奈", "香织", "美美", "惠理子", "忍", "真阳", "栞", "千歌", "空花", "珠希", "美冬", "深月", "铃", "绫音", "美里"};
public static String[] Three = {"伊莉亚","杏奈", "真步", "璃乃", "初音", "依绪", "咲恋", "望", "妮胧", "秋乃", "真琴", "静流", "莫妮卡", "姬塔", "纯", "亚里莎", "冰川镜华"};
public static String[] noUpThree = {"初音","杏奈", "真步", "璃乃", "依绪", "望", "妮胧", "秋乃", "真琴", "静流", "莫妮卡", "姬塔", "纯", "咲恋", "冰川镜华"};
public static String[] noUptwo = {"美里","紡希", "绫音", "茜里", "宫子", "雪", "铃奈", "香织", "美美", "惠理子", "忍", "真阳", "栞", "千歌", "空花", "珠希", "美冬", "深月", "铃"};
public static String[] noUpone = {"碧","胡桃", "铃莓", "日和莉", "怜", "未奏希", "依里", "由加莉", "美咲", "莉玛", "茉莉"};
public static String[] Three_plus = {"伊莉亚"};
public static String[] two_plus = {};
public static String[] one_plus = {};
public static int ThreeChance = 25;
public static int TwoChance = 180;
public static int OneChance = 795;
public static int baijinThreeChance = 25;
public static int baijiTwoChance = 180;
public static int baijiOneChance = 795;
public static int upThreeChance = 7;
public static int upTwoChance = 0;//30;
public static int upOneChance = 0;//200;
public static HashMap<String, Integer> reQieLU = new HashMap<>();
public static String ip;
public static PricnessConfig pricnessConfig;
public static String[] emojis = new String[]{"\uD83E\uDD84", "\uD83D\uDC34", "\uD83D\uDC3A", "\uD83D\uDC02", "\uD83D\uDC04", "\uD83D\uDC0E", "\uD83D\uDC07", "\uD83D\uDC13", "\uD83E\uDD8F", "\uD83D\uDC29", "\uD83D\uDC2E", "\uD83D\uDC35", "\uD83D\uDC19", "\uD83D\uDC80", "\uD83D\uDC24", "\uD83D\uDC28", "\uD83D\uDC2E", "\uD83D\uDC14", "\uD83D\uDC38", "\uD83D\uDC7B", "\uD83D\uDC1B", "\uD83D\uDC20", "\uD83D\uDC36", "\uD83D\uDC2F", " ", "\uD83D\uDEBD"};
public static HoreEvent horeEvent;
public static File HeitaiFile = new File("./heitai");
static {
reQieLU.put("切噜", 0);
reQieLU.put("切哩", 1);
reQieLU.put("切吉", 2);
reQieLU.put("噜拉", 3);
reQieLU.put("啪噜", 4);
reQieLU.put("切璐", 5);
reQieLU.put("扣扣", 6);
reQieLU.put("啦哩", 7);
reQieLU.put("啦嘟", 8);
reQieLU.put("切泼", 9);
reQieLU.put("啪噼", 10);
reQieLU.put("%%", 11);
reQieLU.put("嚕嚕", 12);
reQieLU.put("啰哩", 13);
reQieLU.put("切拉", 14);
reQieLU.put("切噼", 15);
}
//加载配置文件
public static void getFile() {
File file = new File("config.txt");
//群组设定
if (!file.exists() || !file.isFile()) {
//没有读取到配置文件
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
} else {
//读取到了
String jsonString;
try {
jsonString = FileUtils.readFileToString(file, "utf-8");
JSONObject jsonObject = JSONObject.parseObject(jsonString);
Set<String> keySet = jsonObject.keySet();
for (String s : keySet) {
String string = jsonObject.getJSONObject(s).toJSONString();
groupPower keyValues = JSONArray.parseObject(string, groupPower.class);
On.put(s, keyValues);
}
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
}
}
}
//加载通用配置
public static void getconfig() {
//通用设定
File file = new File("./通用配置.txt");
if (file.exists() && file.isFile()) {
try {
pricnessConfig=loadconfig(file);
return;
} catch (IOException e) {
try {
frashconfig(file);
} catch (IOException e1) {
e.printStackTrace();
}
}
}else {
try {
frashconfig(file);
pricnessConfig = new PricnessConfig("买药.png", 1000, 30, true, true, true, true, "12345", 2000, 500);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void frashconfig(File file) throws IOException {
OutputStreamWriter outputStream = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8);
SafeProperties pro = new SafeProperties();
pro.addComment("这个图片应和jar在同一文件夹下");
pro.setProperty("提醒买药小助手图片名", "买药.png");
pro.setProperty("抽卡上限", "1000");
pro.addComment("每次抽卡中间所需的冷却时间,单位为秒");
pro.setProperty("抽卡冷却", "30");
pro.addComment("以下四个为机器人开关的默认设置 true为开,false为关");
pro.setProperty("总开关默认开启", "true");
pro.setProperty("抽奖默认开启", "true");
pro.setProperty("抽卡默认开启", "true");
pro.setProperty("赛马默认开启", "true");
pro.addComment("主人qq相当于在所有群里对这个机器人有管理员权限");
pro.setProperty("主人qq", "12345");
pro.addComment("发一次色图所要花费的马币数量,设置为负数可能会越花越多");
pro.setProperty("发一次色图花费", "500");
pro.addComment("给xcw上供指令的增加马币数目,设置为负数则有可能会越签越少");
pro.setProperty("签到一次金币", "2000");
pro.store(outputStream, "通用配置");
outputStream.close();
}
public static PricnessConfig loadconfig(File file) throws IOException {
SafeProperties pro = new SafeProperties();
InputStreamReader in = null;
in = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8);
pro.load(in);
PricnessConfig pricnessConfig ;
pricnessConfig = new PricnessConfig(pro.getProperty("提醒买药小助手图片名"),
Integer.parseInt(pro.getProperty("抽卡上限")),
Integer.parseInt(pro.getProperty("抽卡冷却")),
Boolean.parseBoolean(pro.getProperty("总开关默认开启")),
Boolean.parseBoolean(pro.getProperty("抽奖默认开启")),
Boolean.parseBoolean(pro.getProperty("抽卡默认开启")),
Boolean.parseBoolean(pro.getProperty("赛马默认开启")),
pro.getProperty("主人qq"),
Integer.parseInt(pro.getProperty("签到一次金币")),
Integer.parseInt(pro.getProperty("发一次色图花费"))
);
in.close();
return pricnessConfig;
}
//刷新写入配置文件
public synchronized static void setjson() {
String jsonObject = JSONObject.toJSONString(On);
try {
File file = new File("config.txt");
if (!file.exists() || !file.isFile()) {
file.createNewFile();
}
FileUtils.write(file, jsonObject, "utf-8");
} catch (IOException e) {
e.printStackTrace();
}
}
//读好坏事
public synchronized static void getEvent() {
horeEvent = new HoreEvent();
String jsonObject = JSONObject.toJSONString(horeEvent);
try {
File file = new File("事件.txt");
if (!file.exists() || !file.isFile()) {
file.createNewFile();
FileUtils.write(file, jsonObject, "utf-8");
} else {
JSONObject jsonObject1 = JSONObject.parseObject(FileUtils.readFileToString(file, "utf-8"));
List bedHorseEvent = JSONArray.parseObject(jsonObject1.get("bedHorseEvent").toString(), List.class);
List goodHorseEvent = JSONArray.parseObject(jsonObject1.get("goodHorseEvent").toString(), List.class);
horeEvent.getGoodHorseEvent().addAll(goodHorseEvent);
horeEvent.getBedHorseEvent().addAll(bedHorseEvent);
}
} catch (IOException e) {
e.printStackTrace();
}
}
//读扭蛋信息
public synchronized static void getgachi() {
try {
File file = new File("扭蛋.txt");
if (!file.exists() || !file.isFile()) {
file.createNewFile();
//准备内置的转蛋信息写入内存
//up池
JSONObject upgachi = new JSONObject();
upgachi.put("三星总概率", ThreeChance);
upgachi.put("二星总概率", TwoChance);
upgachi.put("一星总概率", OneChance);
upgachi.put("三星人物池(除去up角)", noUpThree);
upgachi.put("二星人物池(除去up角)", noUptwo);
upgachi.put("一星人物池(除去up角)", noUpone);
upgachi.put("三星人物池(up角)", Three_plus);
upgachi.put("二星人物池(up角)", two_plus);
upgachi.put("一星人物池(up角)", one_plus);
upgachi.put("三星up总概率", upThreeChance);
upgachi.put("二星up总概率", upTwoChance);
upgachi.put("一星up总概率", upOneChance);
//白金池
JSONObject gachi = new JSONObject();
gachi.put("三星总概率", baijinThreeChance);
gachi.put("二星总概率", baijiTwoChance);
gachi.put("一星总概率", baijiOneChance);
gachi.put("三星人物池", Three);
gachi.put("二星人物池", two);
gachi.put("一星人物池", one);
JSONObject jsonObject = new JSONObject();
jsonObject.put("up池信息", upgachi);
jsonObject.put("白金池信息", gachi);
FileUtils.write(file, jsonObject.toJSONString(), "utf-8");
} else {
JSONObject jsonObject = JSONObject.parseObject(FileUtils.readFileToString(file, "utf-8"));
JSONObject gachi = (JSONObject) jsonObject.get("白金池信息");
JSONObject upgachi = (JSONObject) jsonObject.get("up池信息");
baijinThreeChance = (int) gachi.get("三星总概率");
baijiTwoChance = (int) gachi.get("二星总概率");
baijiOneChance = (int) gachi.get("一星总概率");
Three = ((JSONArray) gachi.get("三星人物池")).toArray(new String[0]);
two = ((JSONArray) gachi.get("二星人物池")).toArray(new String[0]);
one = ((JSONArray) gachi.get("一星人物池")).toArray(new String[0]);
ThreeChance = (int) upgachi.get("三星总概率");
TwoChance = (int) upgachi.get("二星总概率");
OneChance = (int) upgachi.get("一星总概率");
noUpThree = ((JSONArray) upgachi.get("三星人物池(除去up角)")).toArray(new String[0]);
noUptwo = ((JSONArray) upgachi.get("二星人物池(除去up角)")).toArray(new String[0]);
noUpone = ((JSONArray) upgachi.get("一星人物池(除去up角)")).toArray(new String[0]);
Three_plus = ((JSONArray) upgachi.get("三星人物池(up角)")).toArray(new String[0]);
two_plus = ((JSONArray) upgachi.get("二星人物池(up角)")).toArray(new String[0]);
try {
one_plus = ((JSONArray) upgachi.get("一星人物池(up角)")).toArray(new String[0]);
} catch (NullPointerException e) {
}
upThreeChance = (int) upgachi.get("三星up总概率");
upTwoChance = (int) upgachi.get("二星up总概率");
try {
upOneChance = (int) upgachi.get("一星up总概率");
} catch (NullPointerException e) {
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
System.out.println("扭蛋配置文件错误,是否删除了一项?");
}
}
}
| sciuridae564/PcrTool | src/main/java/cn/sciuridae/constant.java |
65,026 | import TCFGmodel.TCFGUtil;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;
import org.apache.flink.streaming.connectors.rabbitmq.RMQSource;
import org.apache.flink.streaming.connectors.rabbitmq.common.RMQConnectionConfig;
import org.apache.log4j.Logger;
import workflow.WorkFlow;
import workflow.WorkFlowMode1;
import workflow.WorkFlowMode2;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
public class Entrance {
public static DataStreamSource<String> getDataStream(StreamExecutionEnvironment env, Logger log, ParameterTool parameter){
String source = parameter.get("sourceName");
switch (source) {
default:
log.error("Source type can be file, rabbitmq, socket or kafka.");
break;
case "socket":
return env.socketTextStream(parameter.get("socketHost"), Integer.parseInt(parameter.get("socketPort")), "\n");
case "file":
String input_dir = String.format("src/main/resources/%s/raw", parameter.get("logData"));
return env.readTextFile(input_dir + File.separator + parameter.get("logName"));
case "files":
//String dir = "E:/中兴项目/实验/上电阶段数据_191219/hjm/release 5G AAU/67214_1571794768181";
String dir = "E:/中兴项目/实验/tecs_log_good/tecs_log";
List filelist = new ArrayList();
List<File> newfilelist = getFileList(filelist,dir);
for (File file: newfilelist) {
DataStreamSource<String> dataStream = env.readTextFile(file.getAbsolutePath());
System.out.println(file.getAbsolutePath());
try {
WorkFlow workFlow2 = new WorkFlowMode2();
workFlow2.workflow(env, dataStream, parameter);
}catch (Exception e){
System.out.println("error");
}
}
case "rabbitmq":
RMQConnectionConfig connectionConfig = new RMQConnectionConfig.Builder()
.setHost(parameter.get("rabbitmqHost"))
.setPort(Integer.parseInt(parameter.get("rabbitmqPort")))
.setVirtualHost(parameter.get("virtualHost"))
.setUserName(parameter.get("rabbitmqUser"))
.setPassword(parameter.get("rabbitmqPassword"))
.build();
return env.addSource(new RMQSource<String>(connectionConfig, parameter.get("queue"), true, new SimpleStringSchema()));
case "kafka":
Properties properties = new Properties();
properties.setProperty("bootstrap.servers", parameter.get("bootstrapServer"));
properties.setProperty("zookeeper.connect", parameter.get("zookeeperConnect"));
properties.setProperty("group.id", parameter.get("groupID"));
FlinkKafkaConsumer<String> wordConsumer = new FlinkKafkaConsumer<>(parameter.get("topic"), new SimpleStringSchema(), properties);
wordConsumer.setStartFromEarliest();
return env.addSource(wordConsumer);
}
return null;
}
public static void main(String[] args) throws Exception {
final Logger log = Logger.getLogger(Entrance.class);
ParameterTool parameter = ParameterTool.fromPropertiesFile("src/main/resources/config.properties");
String mode = parameter.get("workFlowMode");
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment().setParallelism(1);
// env.getConfig().setGlobalJobParameters(parameter);
env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);
DataStreamSource<String> dataStream = getDataStream(env, log, parameter);
switch (mode) {
default:
log.error("workFlowMode can only be 1 or 2");
break;
case "1":
WorkFlow workFlow1 = new WorkFlowMode1();
workFlow1.workflow(env, dataStream, parameter);
break;
case "2":
WorkFlow workFlow2 = new WorkFlowMode2();
workFlow2.workflow(env, dataStream, parameter);
}
}
public static List<File> getFileList(List filelist,String strPath) {
File dir = new File(strPath);
File[] files = dir.listFiles(); // 该文件目录下文件全部放入数组
if (files != null) {
for (int i = 0; i < files.length; i++) {
String fileName = files[i].getName();
if (files[i].isDirectory()) { // 判断是文件还是文件夹
getFileList(filelist,files[i].getAbsolutePath()); // 获取文件绝对路径
//} else if (fileName.startsWith("swm_vmp-")) {
} else if (fileName.startsWith("nova-compute")) {
filelist.add(files[i]);
} else {
continue;
}
}
}
return filelist;
}
}
| jia-tong-FINE/LogFlash | src/main/java/Entrance.java |
65,027 | import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by Zhang Chen([email protected]) on 2017/3/2.
*/
public class FileUtils {
public static final String outputDir="E:\\Document\\我的\\研究生毕业论文\\实验\\CloudSim实验\\调度与不调度比较\\";
public static SimpleDateFormat format=new SimpleDateFormat("yyyyMMddHHmmss-");
public static Date date=new Date();
public static final String prefix=format.format(date);
public static boolean writeVarianceTAVMS(String content){
FileWriter fileWriter = null;
try {
fileWriter =new FileWriter("E:\\Document\\我的\\研究生毕业论文\\实验\\CloudSim实验\\调度与不调度比较\\variance-tavms.txt",true);
} catch (IOException e) {
e.printStackTrace();
}
try {
fileWriter.write(content + "\n");
fileWriter.flush();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public static boolean writeVarianceRandom(String content){
FileWriter fileWriter = null;
try {
fileWriter =new FileWriter("E:\\Document\\我的\\研究生毕业论文\\实验\\CloudSim实验\\调度与不调度比较\\variance-random.txt",true);
} catch (IOException e) {
e.printStackTrace();
}
try {
fileWriter.write(content+"\n");
fileWriter.flush();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public static boolean writeUsageTAVMS(String content){
FileWriter fileWriter = null;
try {
fileWriter =new FileWriter("E:\\Document\\我的\\研究生毕业论文\\实验\\CloudSim实验\\调度与不调度比较\\usage-tavms.txt",true);
} catch (IOException e) {
e.printStackTrace();
}
try {
fileWriter.write(content+"\n");
fileWriter.flush();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public static boolean writeUsageRandom(String content){
FileWriter fileWriter = null;
try {
fileWriter =new FileWriter("E:\\Document\\我的\\研究生毕业论文\\实验\\CloudSim实验\\调度与不调度比较\\usage-random.txt",true);
} catch (IOException e) {
e.printStackTrace();
}
try {
fileWriter.write(content+"\n");
fileWriter.flush();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public static boolean writeDiversityTAVMS(String content){
FileWriter fileWriter = null;
try {
fileWriter =new FileWriter("E:\\Document\\我的\\研究生毕业论文\\实验\\CloudSim实验\\调度与不调度比较\\diversity-tavms.txt",true);
} catch (IOException e) {
e.printStackTrace();
}
try {
fileWriter.write(content+"\n");
fileWriter.flush();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public static boolean writeAvgTypeNumberTAVMS(String content){
FileWriter fileWriter = null;
try {
fileWriter =new FileWriter("E:\\Document\\我的\\研究生毕业论文\\实验\\CloudSim实验\\调度与不调度比较\\avgTypeNumber-tavms.txt",true);
} catch (IOException e) {
e.printStackTrace();
}
try {
fileWriter.write(content+"\n");
fileWriter.flush();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public static boolean writeAvgTypeNumberRandom(String content){
FileWriter fileWriter = null;
try {
fileWriter =new FileWriter("E:\\Document\\我的\\研究生毕业论文\\实验\\CloudSim实验\\调度与不调度比较\\avgTypeNumber-random.txt",true);
} catch (IOException e) {
e.printStackTrace();
}
try {
fileWriter.write(content+"\n");
fileWriter.flush();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public static boolean writeMigratedVMCountTAVMS(String content){
FileWriter fileWriter = null;
try {
fileWriter =new FileWriter("E:\\Document\\我的\\研究生毕业论文\\实验\\CloudSim实验\\调度与不调度比较\\migratedVMCount-tavms.txt",true);
} catch (IOException e) {
e.printStackTrace();
}
try {
fileWriter.write(content + "\n");
fileWriter.flush();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public static boolean writeMigratedVMCountRandom(String content){
FileWriter fileWriter = null;
try {
fileWriter =new FileWriter("E:\\Document\\我的\\研究生毕业论文\\实验\\CloudSim实验\\调度与不调度比较\\migratedVMCount-random.txt",true);
} catch (IOException e) {
e.printStackTrace();
}
try {
fileWriter.write(content + "\n");
fileWriter.flush();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public static boolean writeUsageRangeTAVMS(String content){
FileWriter fileWriter = null;
try {
fileWriter =new FileWriter("E:\\Document\\我的\\研究生毕业论文\\实验\\CloudSim实验\\调度与不调度比较\\usageRange-tavms.txt",true);
} catch (IOException e) {
e.printStackTrace();
}
try {
fileWriter.write(content + "\n");
fileWriter.flush();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public static boolean writeUsageRangeRandom(String content){
FileWriter fileWriter = null;
try {
fileWriter =new FileWriter("E:\\Document\\我的\\研究生毕业论文\\实验\\CloudSim实验\\调度与不调度比较\\usageRange-random.txt",true);
} catch (IOException e) {
e.printStackTrace();
}
try {
fileWriter.write(content + "\n");
fileWriter.flush();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public static boolean writeAvgAppDistributionRateTAVMS(String content){
FileWriter fileWriter = null;
try {
fileWriter =new FileWriter("E:\\Document\\我的\\研究生毕业论文\\实验\\CloudSim实验\\调度与不调度比较\\appDistributionRate-tavms.txt",true);
} catch (IOException e) {
e.printStackTrace();
}
try {
fileWriter.write(content + "\n");
fileWriter.flush();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public static boolean writeAvgAppDistributionRateRandom(String content){
FileWriter fileWriter = null;
try {
fileWriter =new FileWriter("E:\\Document\\我的\\研究生毕业论文\\实验\\CloudSim实验\\调度与不调度比较\\appDistributionRate-random.txt",true);
} catch (IOException e) {
e.printStackTrace();
}
try {
fileWriter.write(content + "\n");
fileWriter.flush();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public static boolean writeAvgVarianceOfResUsageInHostTAVMS(String content){
FileWriter fileWriter = null;
try {
fileWriter =new FileWriter("E:\\Document\\我的\\研究生毕业论文\\实验\\CloudSim实验\\调度与不调度比较\\avgVarianceOfUsagesOfEachResInVm-tavms.txt",true);
} catch (IOException e) {
e.printStackTrace();
}
try {
fileWriter.write(content + "\n");
fileWriter.flush();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public static boolean writeAvgVarianceOfResUsageInHostRandom(String content){
FileWriter fileWriter = null;
try {
fileWriter =new FileWriter("E:\\Document\\我的\\研究生毕业论文\\实验\\CloudSim实验\\调度与不调度比较\\avgVarianceOfUsagesOfEachResInVm-random.txt",true);
} catch (IOException e) {
e.printStackTrace();
}
try {
fileWriter.write(content + "\n");
fileWriter.flush();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public static boolean writeAvgResUsageRangeInOneHostTAVMS(String content){
FileWriter fileWriter = null;
try {
fileWriter =new FileWriter("E:\\Document\\我的\\研究生毕业论文\\实验\\CloudSim实验\\调度与不调度比较\\avgResUsageRangeInOneHost-tavms.txt",true);
} catch (IOException e) {
e.printStackTrace();
}
try {
fileWriter.write(content + "\n");
fileWriter.flush();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public static boolean writeAvgResUsageRangeInOneHostRandom(String content){
FileWriter fileWriter = null;
try {
fileWriter =new FileWriter("E:\\Document\\我的\\研究生毕业论文\\实验\\CloudSim实验\\调度与不调度比较\\avgResUsageRangeInOneHost-random.txt",true);
} catch (IOException e) {
e.printStackTrace();
}
try {
fileWriter.write(content + "\n");
fileWriter.flush();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public static boolean writeOverloadHostNumberTAVMS(String content){
FileWriter fileWriter = null;
try {
fileWriter =new FileWriter("E:\\Document\\我的\\研究生毕业论文\\实验\\CloudSim实验\\调度与不调度比较\\overloadHostNumber-tavms.txt",true);
} catch (IOException e) {
e.printStackTrace();
}
try {
fileWriter.write(content + "\n");
fileWriter.flush();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public static boolean writeOverloadHostNumberRandom(String content){
FileWriter fileWriter = null;
try {
fileWriter =new FileWriter("E:\\Document\\我的\\研究生毕业论文\\实验\\CloudSim实验\\调度与不调度比较\\overloadHostNumber-random.txt",true);
} catch (IOException e) {
e.printStackTrace();
}
try {
fileWriter.write(content + "\n");
fileWriter.flush();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public static boolean writeAffectedVmNumberTAVMS(String content){
FileWriter fileWriter = null;
try {
fileWriter =new FileWriter("E:\\Document\\我的\\研究生毕业论文\\实验\\CloudSim实验\\调度与不调度比较\\affectedVmNumber-tavms.txt",true);
} catch (IOException e) {
e.printStackTrace();
}
try {
fileWriter.write(content + "\n");
fileWriter.flush();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public static boolean writeAffectedVmNumberRandom(String content){
FileWriter fileWriter = null;
try {
fileWriter =new FileWriter("E:\\Document\\我的\\研究生毕业论文\\实验\\CloudSim实验\\调度与不调度比较\\affectedVmNumber-random.txt",true);
} catch (IOException e) {
e.printStackTrace();
}
try {
fileWriter.write(content + "\n");
fileWriter.flush();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public static boolean writeVmNumberTAVMS(String content){
FileWriter fileWriter = null;
try {
fileWriter =new FileWriter("E:\\Document\\我的\\研究生毕业论文\\实验\\CloudSim实验\\调度与不调度比较\\vmNumber-tavms.txt",true);
} catch (IOException e) {
e.printStackTrace();
}
try {
fileWriter.write(content + "\n");
fileWriter.flush();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public static boolean writeVmNumberRandom(String content){
FileWriter fileWriter = null;
try {
fileWriter =new FileWriter("E:\\Document\\我的\\研究生毕业论文\\实验\\CloudSim实验\\调度与不调度比较\\vmNumber-random.txt",true);
} catch (IOException e) {
e.printStackTrace();
}
try {
fileWriter.write(content + "\n");
fileWriter.flush();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public static boolean writeSLAViolationVmNumberTAVMS(String content){
FileWriter fileWriter = null;
try {
fileWriter =new FileWriter("E:\\Document\\我的\\研究生毕业论文\\实验\\CloudSim实验\\调度与不调度比较\\slaViolationVmNumber-tavms.txt",true);
} catch (IOException e) {
e.printStackTrace();
}
try {
fileWriter.write(content + "\n");
fileWriter.flush();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public static boolean writeSLAViolationVmNumberRandom(String content){
FileWriter fileWriter = null;
try {
fileWriter =new FileWriter("E:\\Document\\我的\\研究生毕业论文\\实验\\CloudSim实验\\调度与不调度比较\\slaViolationVmNumber-random.txt",true);
} catch (IOException e) {
e.printStackTrace();
}
try {
fileWriter.write(content + "\n");
fileWriter.flush();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public static boolean writeSumSkewnessTAVMS(String content){
FileWriter fileWriter = null;
try {
fileWriter =new FileWriter(outputDir+prefix+"sumSkewness-tavms.txt",true);
} catch (IOException e) {
e.printStackTrace();
}
try {
fileWriter.write(content + "\n");
fileWriter.flush();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public static boolean writeSumSkewnessRandom(String content){
FileWriter fileWriter = null;
try {
fileWriter =new FileWriter(outputDir+prefix+"sumSkewness-random.txt",true);
} catch (IOException e) {
e.printStackTrace();
}
try {
fileWriter.write(content + "\n");
fileWriter.flush();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
}
| chansonzhang/tavms | src/FileUtils.java |
65,029 | package com.lihuanyu.model;
import javax.persistence.*;
import java.util.Date;
/**
* 笔记
* Created by Explorer on 2016/4/20.
*/
@Entity
@Table(name = "t_note")
public class Note {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private long customUserId;//笔记所有者id
private String noteContent;//笔记内容
private String courseOrExptName;//该笔记对应的课程/实验
private Date createDate;
public Note(){};
public Note(long customUserId, String noteContent, String courseOrExptName, Date createDate) {
this.customUserId = customUserId;
this.noteContent = noteContent;
this.courseOrExptName = courseOrExptName;
this.createDate = createDate;
}
public void setCourseOrExptName(String courseOrExptName) {
this.courseOrExptName = courseOrExptName;
}
public String getCourseOrExptName() {
return courseOrExptName;
}
public void setCustomUserId(long customUserId) {
this.customUserId = customUserId;
}
public void setNoteContent(String noteContent) {
this.noteContent = noteContent;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public void setId(long id) {
this.id = id;
}
public long getId() {
return id;
}
public long getCustomUserId() {
return customUserId;
}
public String getNoteContent() {
return noteContent;
}
public Date getCreateDate() {
return createDate;
}
}
| sky-admin/learnmooc | src/main/java/com/lihuanyu/model/Note.java |
65,030 | package Experiment;
import java.util.ArrayList;
import java.util.List;
import processor.CsvProcessor;
import processor.FileProcessor;
import model.Word;
/**
* 算法步骤五
* @author qiusd
*/
public class Step5 {
public ArrayList<Word> getData(List<String> csvPaths) throws Exception {
ArrayList<Word> datasetList = new ArrayList<Word>();
for (String csvPath : csvPaths) {
ArrayList<String[]> csvList = CsvProcessor.readFromCsv(csvPath);
for (String[] csvRow : csvList) {
Word word = new Word();
word.text = csvRow[0];
word.linkFeature = Double.parseDouble(csvRow[1]);
word.tfidf = Double.parseDouble(csvRow[2]);
word.position = Double.parseDouble(csvRow[3]);
word.wordLength = Double.parseDouble(csvRow[4]);
word.textRank = Double.parseDouble(csvRow[5]);
word.textRankValue = Double.parseDouble(csvRow[6]);
word.lable = Double.parseDouble(csvRow[7]);
datasetList.add(word);
}
}
return datasetList;
}
public void excute(String datasetDirPath) throws Exception {
FileProcessor fileProcessor = new FileProcessor();
List<String> datasetPaths = fileProcessor.getFilesByDir(datasetDirPath);
ArrayList<Word> datasetWordList = getData(datasetPaths);
SVM svm = new SVM();
svm.train(datasetWordList);
}
public static void main(String[] args) throws Exception {
Step5 step5 = new Step5();
// 记得配置路径
step5.excute("F:\\百度云\\研究方向\\毕业设计\\实验\\140506\\dataset_selected50_1");
}
}
| JNU-MINT/AbstractExtraction | TestCode/Experiment/Step5.java |
65,031 | package bean;
import java.io.Serializable;
// ab 实验
public class Experiment implements Serializable {
public String userId;
public String domainName;
public String experimentName;
public Experiment() {
}
public Experiment(String userId, String domainName, String experimentName) {
this.userId = userId;
this.domainName = domainName;
this.experimentName = experimentName;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getDomainName() {
return domainName;
}
public void setDomainName(String domainName) {
this.domainName = domainName;
}
public String getExperimentName() {
return experimentName;
}
public void setExperimentName(String experimentName) {
this.experimentName = experimentName;
}
@Override
public String toString() {
return "Experiment{" +
"userId='" + userId + '\'' +
", domainName='" + domainName + '\'' +
", experimentName='" + experimentName + '\'' +
'}';
}
}
| Chris604/flink-online-dw | src/main/java/bean/Experiment.java |
65,032 | /**
*
*/
package com.sidihuo.abtest;
import java.util.Map;
import com.sidihuo.abtest.cache.AbTestCache;
import com.sidihuo.abtest.exception.AbTestException;
import com.sidihuo.abtest.pojo.AbExperiment;
import com.sidihuo.abtest.pojo.AbWhitelist;
import com.sidihuo.abtest.pojo.VersionResult;
import com.sidihuo.abtest.service.AbTestCacheService;
import com.sidihuo.abtest.util.ABTestUtil;
import com.sidihuo.abtest.util.VersionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author XiaoGang
*
* 1.使用 AbTest-sdk 要在spring中注入此类(注意构造函数注入),必须以单例存在
*
* 2.调用AbTest服务的入口
*
* 3.用途:1)配合pv uv 分析最优版本;2)灰度发布;
*
* 4.一个实验,最小流量比颗粒度为5%,如果需要更小粒度,可以两(多)个实现嵌套配合实现;
*/
public class AbTest {
private Logger logger = LoggerFactory.getLogger(getClass());
/**
* 调用AbTest服务成功的返回码
*/
public static final String RESPONSE_CODE_SUCCESS = "000000";
/**
* 调用AbTest服务,客户ID是白名单时的responseDescription
*/
public static final String RESPONSE_DESCRIPTION_WHITELIST = "whitelist client";
/**
* 本地缓存:实验;key=expID,value=exp
*/
private AbTestCache<AbExperiment, AbTestCacheService<AbExperiment>> experimentCache;
/**
* 本地缓存:白名单;key=expID,value=Map(Map中key=clientID,value=白名单)
*/
private AbTestCache<Map<String, AbWhitelist>, AbTestCacheService<Map<String, AbWhitelist>>> whitelistCache;
/**
*
* @param experimentService
* 查询DB实验的服务,结果放进本地缓存,开发者要自己实现
* @param experimentExpireTime
* 从DB查询的数据在缓存中存活时间,秒
* @param experimentMaximumSize
* 缓存最大实验个数
* @param whitelistService
* 查询DB白名单的服务,结果放进本地缓存,开发者要自己实现
* @param whitelistExpireTime
* 从DB查询的数据在缓存中存活时间,秒
* @param whitelistMaximumSize
* 缓存最大实验个数 (一个实验对应一个Map白名单缓存,查询白名单是先查询此实验的所有白名单,在查询这些白名单包含客户ID与否)
*/
public AbTest(AbTestCacheService<AbExperiment> experimentService, long experimentExpireTime,
long experimentMaximumSize, AbTestCacheService<Map<String, AbWhitelist>> whitelistService,
long whitelistExpireTime, long whitelistMaximumSize) {
super();
experimentCache = new AbTestCache<AbExperiment, AbTestCacheService<AbExperiment>>(experimentService,
experimentExpireTime, experimentMaximumSize);
whitelistCache = new AbTestCache<Map<String, AbWhitelist>, AbTestCacheService<Map<String, AbWhitelist>>>(
whitelistService, whitelistExpireTime, whitelistMaximumSize);
logger.info("\n"
+ "*******************************************************************\n"
+ "** AbTest construct success **\n"
+ "*******************************************************************");
}
/**
* AbTest请求调用入口
*
* @param experimentID
* 必填
* @param clientID
* 必填
* @param domain
* 非必填;相同实验分流比配置,不同domain的实验结果不会有相互影响;
* (比如使用同一个实验,domainA是APP端访问,domainB是PC端访问,虽然使用同一个实验,但是分流结果互不干扰)
* 也可用于分层分域设计实验;
* @return
*/
public AbTestResponse getAbTestResponse(String experimentID, String clientID, String domain) {
long startTime = System.currentTimeMillis();
AbTestResponse abTestResponse = new AbTestResponse();
try {
VersionResult versionResult = getVersion(experimentID, clientID, domain);
String version = versionResult.getVersion();
abTestResponse.setVersion(version);
abTestResponse.setResponseCode(RESPONSE_CODE_SUCCESS);
abTestResponse.setResponseMsg("success");
boolean whitelistClient = versionResult.isWhitelistClient();
abTestResponse.setResponseDescription(whitelistClient ? RESPONSE_DESCRIPTION_WHITELIST : "");
} catch (AbTestException e) {
abTestResponse.setResponseCode("100000");
abTestResponse.setResponseMsg("abtest error");
abTestResponse.setResponseDescription(e.getMessage());
logger.warn("AbTest AbTestException-->" + e.getMessage());
} catch (Exception e) {
abTestResponse.setResponseCode("200000");
abTestResponse.setResponseMsg("system error");
abTestResponse.setResponseDescription(e.getMessage());
logger.warn("AbTest Exception", e);
}
long timeConsume = System.currentTimeMillis() - startTime;
logger.info("AbTest Request: experimentID={},clientID={},domain={};\nAbTest★★★Response={};\nTimeConsume={}ms",
experimentID, clientID, domain, abTestResponse, timeConsume);
return abTestResponse;
}
/**
*
* @param experimentID
* @param clientID
* @param domain
* @return
*/
private VersionResult getVersion(String experimentID, String clientID, String domain) {
// 校验必传参数
if (experimentID == null || experimentID.equals("") || clientID == null || clientID.equals("")) {
throw new AbTestException("experimentID and clientID can not be empty");
}
// 校验实验是否存在
AbExperiment abExperiment = getExperimentConfig(experimentID);
if (abExperiment == null || abExperiment.getExperimentID() == null) {
throw new AbTestException("experimentID can not be found or experiment config is illegal");
}
// 开始分流
VersionResult versionResult = new VersionResult();
// 是否在白名单中
String version = getVersionInWhitelist(experimentID, clientID);
if (version != null) {
versionResult.setWhitelistClient(true);
versionResult.setVersion(version);
return versionResult;
}
// 开始分流算法
versionResult.setWhitelistClient(false);
String domainValue = domain == null ? "" : domain;
String hashString = experimentID + clientID + domainValue;
String encodeMD5 = ABTestUtil.encodeMD5(hashString);
int hashAndModulo = ABTestUtil.hashAndModulo(encodeMD5, 100);
version = VersionUtil.getVersion(hashAndModulo, abExperiment);
versionResult.setVersion(version);
return versionResult;
}
/**
* @param experimentID
* @param clientID
* @return
*/
private String getVersionInWhitelist(String experimentID, String clientID) {
Map<String, AbWhitelist> whitelists = getWhitelists(experimentID);
if (whitelists == null) {
return null;
}
AbWhitelist abWhitelist = whitelists.get(clientID);
if (abWhitelist == null) {
return null;
}
String version = abWhitelist.getVersion();
return version;
}
private AbExperiment getExperimentConfig(String experimentID) {
AbExperiment abExperiment = experimentCache.getFromCache(experimentID);
return abExperiment;
}
private Map<String, AbWhitelist> getWhitelists(String experimentID) {
Map<String, AbWhitelist> abWhitelists = whitelistCache.getFromCache(experimentID);
return abWhitelists;
}
}
| sidihuo/abtest-sdk | src/main/java/com/sidihuo/abtest/AbTest.java |
65,033 | /*
* Author: Andliage Pox
* Date: 2020-01-05
*/
package arknights;
public class ProbabilityTest {
public static void main(String[] args) {
double curP = 0.02;
int sTimes = 0, usTimes = 0, i;
int times = 1000000;
for (i = 0; i < times; i++) {
if (Math.random() < curP) {
sTimes++;
System.out.println("sTimes+1 curP: " + curP);
curP = 0.02;
usTimes = 0;
} else {
usTimes++;
if (usTimes >= 50) {
curP = 0.02 * (usTimes - 48);
}
}
}
System.out.println("实验 " + times + " 次");
System.out.println("六星 " + sTimes + " 次");
System.out.println("平均 " + (double)times / sTimes + " 次一只");
System.out.println("平均概率 " + (double)sTimes / times);
}
}
| AndliagePox/ap | src/arknights/ProbabilityTest.java |
65,034 | import guiD.*;
import FastA.FastA;
import FastaInput.FastaInput;
import javax.swing.*;
import java.awt.*;
public class Main {
public static void main(String[] args) {
//所有Swing组件都必须↓
//事件分派线程:将鼠标点击和按键控制转移到用户接口组件
EventQueue.invokeLater(() ->
{
JFrame frame = new jframegg();
//框架属性
frame.setTitle("Bioinformatics");
//定义用户关闭这个框架时的响应动作
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//显示框架
frame.setVisible(true);
//设置窗口大小不可改变
frame.setResizable(false);
//框架大小
frame.setSize(400,300);
//居中
frame.setLocationRelativeTo(null);
});
//项目路径
String path_ = System.getProperty("user.dir");
System.out.print("文件路径:");
System.out.println(path_);
//默认字符大写
String Sx="HARFYAAQIVL";
String Tx="VDMAAQIA";
/*int k=1;
FastA.IPA(Sx,Tx,k);
FastA.printS();
FastA.printT();
FastA.printD();*/
/*//Fasta格式输入
// N:\略略略略\生物信息学\实验\FASTA\input.txt
Scanner in=new Scanner(System.in);
String path=in.nextLine();
File file=new File(path);
FastaInput inp=new FastaInput();
inp.Input(file);
System.out.println(inp.Flprint());
System.out.println(inp.seqprint());*/
}
}
| HaloAncy/BioInformatics | FASTA/src/Main.java |
65,035 | package lab9;
import java.util.List;
public interface TrieSet61B {
/** Clears all items out of Trie */
void clear();
/** 如果Trie包含KEY,则返回true,否则返回false */
boolean contains(String key);
/** Inserts string KEY into Trie */
void add(String key);
/** 返回以prefix开头的所有单词的列表 */
List<String> keysWithPrefix(String prefix);
/** 返回 Trie 中存在的最长 KEY 前缀 实验 9 不需要。如果不实现此功能,则抛出 UnsupportedOperationException。*/
String longestPrefixOf(String key);
} | yanyanran/cs61b | lab9/lab9/TrieSet61B.java |
65,036 | package com.selenium;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
@RunWith(Parameterized.class)
public class SeleniumTest {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
private String testName;
private String testPwd;
private String gitHubUrl;
public SeleniumTest(String testName, String testPwd, String githubUrl) {
this.testName = testName;
this.testPwd = testPwd;
this.gitHubUrl = githubUrl;
}
@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "http://121.193.130.195:8080";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@Parameterized.Parameters
public static Collection<Object[]> getData() {
Object[][] obj = new Object[117][];
try {
BufferedReader reader = new BufferedReader(new FileReader("G://文件夹//天大文件//课程//大三下//软件测试技术//实验//第2次实验//inputgit.csv"));
reader.readLine();
String line;
int count = 0;
while ((line = reader.readLine()) != null) {
String item[] = line.split(",");
String stuNum = item[0];
String pwd = stuNum.substring(4);
String githubUrl = item[2];
obj[count] = new Object[]{stuNum, pwd, githubUrl};
count++;
}
} catch (Exception e) {
e.printStackTrace();
}
return Arrays.asList(obj);
}
@Test
public void testMain() throws Exception {
driver.get(baseUrl + "/");
driver.findElement(By.id("name")).clear();
driver.findElement(By.id("name")).sendKeys(testName);
driver.findElement(By.id("pwd")).clear();
driver.findElement(By.id("pwd")).sendKeys(testPwd);
driver.findElement(By.id("submit")).click();
assertEquals(this.gitHubUrl, driver.findElement(By.xpath("//tbody[@id='table-main']/tr[3]/td[2]")).getText());
}
@After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
| dengfuping/software-testing | lab_2/SeleniumTest.java |
65,037 | import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
/**
* @author ben
*
*/
public final class ContestOperator {
/**
* 全局唯一实例
*/
private static ContestOperator co = null;
private DBAgent dba = null;
private SolutionOperator so = null;
private UserOperator uo = null;
private IOAgent ioa = IOAgent.getInstance();
private ContestOperator(String xmlfilename)
throws ParserConfigurationException, SAXException, IOException {
dba = DBAgent.getInstance(xmlfilename);
so = SolutionOperator.getInstance(xmlfilename);
uo = UserOperator.getInstance(xmlfilename);
}
public static synchronized ContestOperator getInstance(String xmlfilename) {
if (co == null) {
try {
co = new ContestOperator(xmlfilename);
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return co;
}
/**
* 根据比赛号得到题目序号
*
* @param cid
* @return
*/
public ArrayList<Integer> getProblemidsOfAContest(Integer cid) {
String sql = "select problem_id from contest_problem where contest_id = ? order by problem_id";
try {
PreparedStatement ps = dba.prepareStatement(sql);
ps.setInt(1, cid);
ResultSet rs = ps.executeQuery();
rs.beforeFirst();
ArrayList<Integer> list = new ArrayList<Integer>();
while (rs.next()) {
list.add(rs.getInt(1));
}
return list;
} catch (Exception se) {
se.printStackTrace();
return null;
}
}
/**
* 根据竞赛号得到用户名序列(无重复)
*
* @param id
* @return
*/
public ArrayList<String> getNameListOfAContest(Integer id) {
ArrayList<String> namelist = new ArrayList<String>();
String sql = "select user_id from contest_status where contest_id = ? order by user_id";
try {
PreparedStatement ps = dba.prepareStatement(sql);
ps.setString(1, id.toString());
ResultSet rs = ps.executeQuery();
rs.beforeFirst();
while (rs.next()) {
String name = rs.getString(1).trim();
namelist.add(name);
}
} catch (SQLException se) {
se.printStackTrace();
return null;
}
return namelist;
}
/**
* 将一次竞赛中所有用户Accepted的代码按用户分文件存放在指定的目录下
*
* @param id
* 比赛id
*/
public final void getACCodeOfAContestToDir(Integer id, String rootdir) {
ArrayList<String> namelist = co.getNameListOfAContest(id);
String[] tmp = new String[namelist.size()];
getACCodeOfAContestToDir(id, rootdir, namelist.toArray(tmp));
}
/**
* 将一次竞赛中<b>指定用户</b>Accepted的代码按用户分文件存放在指定的目录下
*
* @param id
*/
public final void getACCodeOfAContestToDir(Integer id, String rootdir,
String[] namelist) {
ArrayList<Integer> problemlist = getProblemidsOfAContest(id);
int I = 0;
for (int pid : problemlist) {
String dir = rootdir;
if (problemlist.size() > 1) {
dir += "\\" + (char) ('A' + I);
}
File f = new File(dir);
if (!f.exists()) {
f.mkdir();
}
dir += "\\";
for (String user : namelist) {
ArrayList<String> ids;
ids = so.getSolutionIdByDetail(user, pid, 1, id);
if (ids == null || ids.size() == 0) {
continue;
}
for (String solution_id : ids) {
String code = so.getCodeBySolutionId(solution_id);
String date = so.getDateOfASolution(solution_id);
String time = getMyTime(date);
String res = "Accepted";
String path = formatFilePath(dir, time, res, user, I);
ioa.setFileText(path, code);
}
}
I++;
}
}
/**
* 将一场比赛的所有代码按要求导出到指定目录下
*
* @param cid
* 比赛(在数据库中)的序号
* @param rootdir
* 指定根目录
*/
public final void getCodesToFilesFromAContest(Integer cid, String rootdir) {
ArrayList<String> namelist = co.getNameListOfAContest(cid);
String[] ret = new String[namelist.size()];
getCodesToFilesFromAContest(cid, rootdir, namelist.toArray(ret));
}
/**
* 将一场比赛中<b>指定用户</b>的所有代码按要求导出到指定目录下
*
* @param cid
* 比赛(在数据库中)的序号
* @param rootdir
* 指定根目录
* @param namelist
* 给定的用户名列表
*/
public final void getCodesToFilesFromAContest(Integer cid, String rootdir,
String[] namelist) {
String[] RESULTS = so.getResultNames();
ArrayList<Integer> problemlist = getProblemidsOfAContest(cid);
for (String user : namelist) {
String dir = rootdir + "\\" + user;
File f = new File(dir);
if (!f.exists()) {
f.mkdir();
}
dir += "\\";
int I = 0;
for (int pid : problemlist) {
for (int i = 0; i < RESULTS.length; i++) {
ArrayList<String> sids;
sids = so.getSolutionIdByDetail(user, pid, i, cid);
if (sids == null || sids.size() == 0) {
continue;
}
for (String solution_id : sids) {
String code = so.getCodeBySolutionId(solution_id);
String date = so.getDateOfASolution(solution_id);
String time = getMyTime(date);
String res = RESULTS[i];
String path = formatFilePath(dir, time, res, user, I);
ioa.setFileText(path, code);
}
}
I++;
}
}
}
/**
* 将从数据库中取出的日期时间文本处理成所需格式的时间文本
*
* @param date
* @return
*/
private String getMyTime(String date) {
int index = date.indexOf(' ');
if (index == -1) {
return null;
}
date = date.substring(index + 1);
date = date.replaceAll(":", "-");
return date.trim();
}
/**
* 根据比赛id获取比赛开始及结束时间
*
* @param id
* @return
*/
public Timestamp[] getStartAndEndTimeofContest(int id) {
Timestamp[] ret = new Timestamp[2];
String sql = "select start_time, end_time from contest where contest_id = "
+ id;
try {
ResultSet rs = dba.executeQuery(sql);
rs.beforeFirst();
if (rs.next()) {
ret[0] = rs.getTimestamp(1);
ret[1] = rs.getTimestamp(2);
}
} catch (SQLException se) {
se.printStackTrace();
}
return ret;
}
/**
* 获取指定时间区间的所有登录情况,输出到指定输出流(如System.out标准输出)中
*
* @param username
* 用户名
* @param start
* 开始时间
* @param end
* 结束时间
* @param out
* 输出流
*/
public void getLoginDetail(String username, Timestamp start, Timestamp end,
PrintStream out) {
String sql = "select ip, time from login_log where user_name = ? and time between ? and ?";
out.print(username);
try {
PreparedStatement ps = dba.prepareStatement(sql);
ps.setString(1, username);
ps.setTimestamp(2, start);
ps.setTimestamp(3, end);
ResultSet rs = ps.executeQuery();
rs.beforeFirst();
while (rs.next()) {
out.print(", " + rs.getTime(2));
out.print(", " + rs.getString(1));
}
} catch (Exception se) {
se.printStackTrace();
}
out.println();
}
/**
* 根据给定的信息,得到一个唯一的文件(全)路径
*
* @param dir
* @param pid
* 从0开始编号的题目序号
* @param subtime
* @param result
* @param user_name
* @return
*/
private String formatFilePath(String dir, String subtime, String result,
String user_name, int pid) {
StringBuilder sb = new StringBuilder();
sb.append(dir);
sb.append(user_name);
sb.append("_");
sb.append((char) (pid + 'A'));
sb.append("_");
sb.append(subtime);
sb.append("_");
sb.append(result);
sb.append(".cpp");
return sb.toString();
}
private static void mkdir(String dir) {
File f = new File(dir);
if (!f.exists()) {
f.mkdir();
}
}
/**
* 为了导出数据时筛掉不符合要求的但参加了比赛的用户的函数,当filter参数是true时,此函数会将不符合regex参数所表示正则表达式的用户名去掉
*
* @param namelist
* @param filter
* @param regex
* @return
*/
private static String[] treamNameList(ArrayList<String> namelist,
boolean filter, String regex) {
int size = namelist.size();
for (int i = size - 1; i >= 0; i--) {
String name = namelist.get(i);
if (filter && !name.matches(regex)) {
namelist.remove(i);
}
}
size = namelist.size();
String[] ret = new String[size];
return namelist.toArray(ret);
}
/**
*
* 导出考试数据,包括学生提交的所有代码,ac代码以及考试期间用户登录情况
*
* @param rootdir
* 存储数据文件的根目录
* @param cid
* 比赛的数据库id
* @param filter
* 是否用regex正则表达式来过滤参赛用户名,如果此值为true,则不满足regex正则表达式的用户名将被过滤
* @param regex
* @throws FileNotFoundException
*/
public void exportExamData(String rootdir, Integer cid, boolean filter,
String regex) throws FileNotFoundException {
mkdir(rootdir);
String alldir = rootdir + "\\all";
mkdir(alldir);
String[] namelist = treamNameList(co.getNameListOfAContest(cid),
filter, regex);
getCodesToFilesFromAContest(cid, alldir, namelist);
String acdir = rootdir + "\\ac";
mkdir(acdir);
getACCodeOfAContestToDir(cid, acdir, namelist);
Timestamp[] contestTime = getStartAndEndTimeofContest(cid);
PrintStream login_ip = new PrintStream(rootdir + "\\login_ip.csv");
PrintStream login_detail = new PrintStream(rootdir
+ "\\login_detail.csv");
for (String name : namelist) {
getLoginDetail(name, contestTime[0], contestTime[1], login_detail);
String[] ips = uo.getLoginIPs(name, contestTime[0], contestTime[1]);
if (ips == null) {
continue;
}
login_ip.print(name);
for (String ip : ips) {
login_ip.print(", " + ip);
}
login_ip.println();
}
login_ip.close();
login_detail.close();
}
/**
* 导出实验数据,包括学生提交的所有代码,ac代码等
*
* @param rootdir
* 存储数据文件的根目录
* @param cids
* 比赛的数据库id
*/
public void exportExperimentData(String rootdir, int[] cids) {
mkdir(rootdir);
for (int i = 0; i < cids.length; i++) {
String cdir = rootdir + "\\实验" + (i + 1);
mkdir(cdir);
int cid = cids[i];
String alldir = cdir + "\\all";
mkdir(alldir);
String[] namelist = treamNameList(co.getNameListOfAContest(cid),
true, "\\d+");
co.getCodesToFilesFromAContest(cid, alldir, namelist);
String acdir = cdir + "\\ac";
mkdir(acdir);
co.getACCodeOfAContestToDir(cid, acdir, namelist);
}
}
@SuppressWarnings("unused")
private static void pro_experiment2015() {
ContestOperator co = ContestOperator.getInstance("acm.db.xml");
int[] contestid = { 64, 65, 66, 68, 69, 71, 74 };
String rootdir = "F:\\Experiment";
mkdir(rootdir);
for (int i = 1; i <= 7; i++) {
String cdir = rootdir + "\\实验" + i;
mkdir(cdir);
int cid = contestid[i - 1];
String alldir = cdir + "\\all";
mkdir(alldir);
String[] namelist = treamNameList(co.getNameListOfAContest(cid),
true, "\\d+");
co.getCodesToFilesFromAContest(cid, alldir, namelist);
String acdir = cdir + "\\ac";
mkdir(acdir);
co.getACCodeOfAContestToDir(cid, acdir, namelist);
}
}
@SuppressWarnings("unused")
private static void cpp_xyy_2015() {
// ContestOperator co = ContestOperator.getInstance("166.db.xml");
// String cdir = "F:\\Cpp_XYY";
// try {
// co.exportExamData(cdir + "\\exam", 3);
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// }
ContestOperator co = ContestOperator
.getInstance("acm.bjfu.edu.cn.db.xml");
String cdir = "F:\\C语言复习";
int[] cids = { 63, 67, 34, 70, 73, 76 };
co.exportExperimentData(cdir, cids);
}
private static void cpp_exam_wsr_2015() {
// ContestOperator co = ContestOperator.getInstance("166.db.xml");
// String cdir = "F:\\Exam";
// ContestOperator co = ContestOperator.getInstance(url, user, pass);
// try {
// co.exportExamData(cdir, 2, true, "\\d+");
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// }
ContestOperator co = ContestOperator.getInstance("acm.db.xml");
String cdir = "F:\\C++上机实验";
int[] cids = { 75, 77, 78 };
co.exportExperimentData(cdir, cids);
}
@SuppressWarnings("unused")
private static void pro_exam2015() {
ContestOperator co = ContestOperator.getInstance("166.db.xml");
UserOperator uo = UserOperator.getInstance("166.db.xml");
int cid = 2;
String[] namelist = treamNameList(co.getNameListOfAContest(cid), true,
"\\d+");
Timestamp[] contestTime = co.getStartAndEndTimeofContest(cid);
for (String name : namelist) {
System.out.print("学号:" + name);
System.out.print("\t登录过的ip:");
String[] ips = uo.getLoginIPs(name, contestTime[0], contestTime[1]);
for (String ip : ips) {
System.out.print(" " + ip);
}
System.out.println();
}
}
@SuppressWarnings("unused")
private static void pro_exam2016() {
ContestOperator co = ContestOperator.getInstance("161.db.xml");
String cdir = "H:\\问题求解与编程";
try {
co.exportExamData(cdir, 2, false, null);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
@SuppressWarnings("unused")
private static void cpp_exam2016() {
ContestOperator co = ContestOperator.getInstance("161.db.xml");
String cdir = "H:\\2016cpp\\";
try {
for (int i = 3; i <= 6; i++) {
co.exportExamData(cdir + i, i, false, null);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
/**
* @param args
*/
public static void main(String[] args) {
// cpp_exam2015_detail();
// cpp_xyy_2015();
// pro_exam2016();
cpp_exam2016();
}
}
| xu-ben/BJFUOJTool | src/ContestOperator.java |
65,038 | package article;
import java.io.*;
/**
* Created by ballontt on 2017/11/13.
*/
public class ParseFile {
public static void main(String[] args) throws IOException {
String filePath = "C:\\Users\\ballontt\\Desktop\\论文资料\\实验\\elapsedTime-load.txt";
String newFile = "C:\\Users\\ballontt\\Desktop\\论文资料\\实验\\new-load.txt";
String initCpu = "C:\\Users\\ballontt\\Desktop\\论文资料\\实验\\init-cput.txt";
String initMem = "C:\\Users\\ballontt\\Desktop\\论文资料\\实验\\init-mem.txt";
String execCpu = "C:\\Users\\ballontt\\Desktop\\论文资料\\实验\\exec-cpu.txt";
String execMem = "C:\\Users\\ballontt\\Desktop\\论文资料\\实验\\exec-mem.txt";
FileWriter f1 = new FileWriter(initCpu);
FileWriter f2 = new FileWriter(initMem);
FileWriter f3 = new FileWriter(execCpu);
FileWriter f4 = new FileWriter(execMem);
BufferedWriter b1 = new BufferedWriter(f1);
BufferedWriter b2 = new BufferedWriter(f2);
BufferedWriter b3 = new BufferedWriter(f3);
BufferedWriter b4 = new BufferedWriter(f4);
FileReader fr = new FileReader(filePath);
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter(newFile);
BufferedWriter bw = new BufferedWriter(fw);
String preLine = "";
String currentLine;
while((currentLine = br.readLine()) != null) {
if(currentLine.contains("=") || currentLine.contains("*")) continue;
if(currentLine.contains("seed")) {
bw.write(currentLine, 0, currentLine.length());
bw.newLine();
} else if(currentLine.contains("init")) {
String initLine = currentLine + " " + preLine;
bw.write(initLine, 0, initLine.length());
bw.newLine();
} else if(currentLine.contains("exec")) {
String execLine = currentLine + " " + preLine;
bw.write(execLine, 0, execLine.length());
bw.newLine();
}
if(currentLine.contains("Cpu")) {
preLine = currentLine;
}
}
FileReader f5 = new FileReader(newFile);
BufferedReader r5 = new BufferedReader(f5);
while((currentLine = r5.readLine()) != null) {
if(!currentLine.contains("seed")) {
String[] strs = currentLine.split(":");
if(strs.length >= 4) {
String cpu = strs[2].split("\t")[0];
String mem = strs[3];
if(currentLine.contains("init")) {
b1.write(cpu);
b1.newLine();
b2.write(mem);
b2.newLine();
} else if(currentLine.contains("exec")) {
b3.write(cpu);
b3.newLine();
b4.write(mem);
b4.newLine();
}
}
}
}
b1.flush();
b2.flush();
b3.flush();
b4.flush();
}
}
| ballontt/OJ | src/article/ParseFile.java |
65,039 | import java.util.*;
import java.io.*;
public class _小蓝做实验 {
static boolean isPrime(long n) {
if (n < 2) return false;
for (long i = 2; i <= n / i; ++i) {
if (n % i == 0) return false;
}
return true;
}
public static void main(String[] args) throws IOException {
// BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
// int cnt = 0;
// while (in.ready()) {
// long x = Long.parseLong(in.readLine());
// if (isPrime(x)) ++cnt;
// }
// System.out.println(cnt);
System.out.println(342693);
}
}
| GabrielxDuO/algorithm_practice | lanqiao/_小蓝做实验.java |
65,040 | package ssdut.training.mapreduce.weblog;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.MultipleOutputs;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
//2. 将所有状态为404的记录输出到文件:missed
public class Missed {
public static class MissedMapper extends Mapper<Object, Text, Text, NullWritable> {
private Text k = new Text(); //Map输出key
public void map(Object key, Text value, Context context )
throws IOException, InterruptedException {
String[] strs = value.toString().split(" ");
String status = strs[strs.length-2]; //获取状态码
if (status.equals("404")) {
//context.write(value, NullWritable.get());
String reqResource = strs[6]; //获取被请求的资源
int index = reqResource.indexOf("?");
if ( index > 0 ) {
reqResource = reqResource.substring(0, index); //截取问号前的请求资源名称(去掉请求参数)
}
k.set(reqResource);
context.write(k, NullWritable.get());
}
}
}
public static class MissedReducer extends Reducer<Text,NullWritable,Text,NullWritable> {
//定义MultiOutputs对象
private MultipleOutputs<Text,NullWritable> mos;
//初始化MultiOutputs对象
protected void setup(Context context) throws IOException, InterruptedException {
mos = new MultipleOutputs<Text, NullWritable>(context);
}
//关闭MultiOutputs对象
protected void cleanup(Context context) throws IOException, InterruptedException {
mos.close();
}
public void reduce(Text key, Iterable<NullWritable> values, Context context)
throws IOException, InterruptedException {
mos.write("missed", key, NullWritable.get());
}
}
public static void main(String[] args) throws Exception {
//1.设置HDFS配置信息
String namenode_ip = "192.168.17.10";
String hdfs = "hdfs://" + namenode_ip + ":9000";
Configuration conf = new Configuration();
conf.set("fs.defaultFS", hdfs);
conf.set("mapreduce.app-submission.cross-platform", "true");
//2.设置MapReduce作业配置信息
String jobName = "Missed"; //作业名称
Job job = Job.getInstance(conf, jobName);
job.setJarByClass(Missed.class); //指定运行时作业类
job.setJar("export\\Missed.jar"); //指定本地jar包
job.setMapperClass(MissedMapper.class); //指定Mapper类
job.setMapOutputKeyClass(Text.class); //设置Mapper输出Key类型
job.setMapOutputValueClass(NullWritable.class); //设置Mapper输出Value类型
job.setReducerClass(MissedReducer.class); //指定Reducer类
//定义多文件输出的文件名、输出格式、键类型、值类型
MultipleOutputs.addNamedOutput(job, "missed", TextOutputFormat.class, Text.class, NullWritable.class);
//3.设置作业输入和输出路径
String dataDir = "/expr/weblog/data"; //实验数据目录
String outputDir = "/expr/weblog/output2"; //实验输出目录
Path inPath = new Path(hdfs + dataDir);
Path outPath = new Path(hdfs + outputDir);
FileInputFormat.addInputPath(job, inPath);
FileOutputFormat.setOutputPath(job, outPath);
FileSystem fs = FileSystem.get(conf);
if(fs.exists(outPath)) {
fs.delete(outPath, true);
}
//4.运行作业
System.out.println("Job: " + jobName + " is running...");
if(job.waitForCompletion(true)) {
System.out.println("success!");
System.exit(0);
} else {
System.out.println("failed!");
System.exit(1);
}
}
} | josonle/MapReduce-Demo | src/main/java/weblog/Missed.java |
65,041 | package 测试;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class Testtt
{
public static void main(String[] args)
{
Stu s1=new Stu("阿爸爸",5);
Stu s2=new Stu("safjasof",114514);
try
{
FileOutputStream fos = new FileOutputStream("D:/whu/java/实验/text.data");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(s1);
oos.writeObject(s2);
System.out.println("啊对对对");
oos.close();
}
catch(IOException e)
{
System.out.println("操作错误!");
}
}
}
| benzoin-p/JV-D | src/测试/Testtt.java |
65,042 | import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.geometry.HPos;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.TextInputDialog;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Line;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import java.util.Optional;
import java.util.Random;
public class ShiYan extends Application
{
public TextInputDialog input=new TextInputDialog();
public static Random rd=new Random();
public Image pencil=new Image("铅笔.png");
public ImageView pencilView=new ImageView(pencil);
public Group root=new Group(new Circle(600,400,200,Color.CORAL));//空白的话就没问题了//根在最下面
public Line line=new Line(700,400,500,700);
public Circle circle=new Circle(200,300,200);
public Rectangle rectangle=new Rectangle(300,400,200,100);
public Text text=new Text(80,700,"ff0");
public Button button=new Button("随机"),cut=new Button("cut"),link=new Button("link");
public Line nowLine;
public int cnt=0;
//@Override
public void start(Stage primaryStage)
{
circle.setFill(Color.WHITE);
line.setStroke(Color.DARKTURQUOISE);
rectangle.setStroke(Color.FORESTGREEN);
rectangle.setStrokeWidth(2);
rectangle.setFill(null);
rectangle.getStrokeDashArray().addAll(10.0);//虚化图形,不知道原理
rectangle.setArcHeight(20);
rectangle.setArcWidth(20);
text.setFill(Color.AQUA);
text.setFont(new Font(30));
button.setOnAction(this::processButtonPress);
button.setPrefWidth(100);
button.setPrefHeight(100);
pencilView.setX(50); pencilView.setY(50);
pencilView.setScaleX(1.2);
pencilView.setScaleY(1.2);
cut.setTranslateX(20);
cut.setTranslateY(200);
link.setTranslateX(300);
link.setTranslateY(150);
link.setTranslateX(300);
link.setTranslateY(150);//不可叠加
cut.setOnAction(this::press);
link.setOnAction(this::press);
Group leaf=new Group(line,circle,rectangle);//circle载rectangle下面
leaf.setTranslateX(200);//这里对下面setScaleX产生了影响
root.getChildren().add(text);
root.getChildren().addAll(leaf,button,link,cut);
root.getChildren().add(pencilView);
Scene scene=new Scene(root,1200,800,Color.BLACK);
//scene.setFill(Color.RED);
scene.setOnMouseClicked(this::moveLine);
scene.setOnMousePressed(this::ysl);
scene.setOnMouseDragged(this::YSL);
scene.setOnKeyPressed(this::delete);
primaryStage.setTitle("实验");
primaryStage.setScene(scene);
primaryStage.show();
Object[] obj=root.getChildren().toArray();//找到取数组的方法
for(Object o:obj)
{
if(o instanceof Text) System.out.println(1);//事实证明可行
else System.out.println(0);
}
}
public void delete(KeyEvent event)
{
if(event.getCode()== KeyCode.BACK_SPACE) root.getChildren().removeAll(text);
}
public void ysl(MouseEvent event)
{
nowLine=new Line(event.getX(),event.getY(),event.getX(),event.getY());
nowLine.setFill(Color.BLACK);//什么都没有发生
nowLine.setStroke(Color.RED);//变好了
root.getChildren().add(nowLine);
}
public void YSL(MouseEvent event)
{
++cnt;
nowLine.setEndX(event.getX());
nowLine.setEndY(event.getY());
ysl(event);
}
public void moveLine(MouseEvent event)
{
input.setHeaderText("abc");
input.setTitle("123");
input.setContentText("ABC");
// Optional<String> numString=input.showAndWait();
Alert answer=new Alert(Alert.AlertType.INFORMATION);
answer.setHeaderText(null);
answer.setContentText("12342332532655");
// answer.setContentText("");
answer.showAndWait();
if(event.getClickCount()==2) return;//双击不管直接跑
text.setText(""+cnt+" "+line.getStartX()+" "+line.getStartY()+" "+event.getX()+" "+event.getY());
line.setEndX(event.getX()-200);//????为什么-200
line.setEndY(event.getY());
}
public void processButtonPress(ActionEvent event)
{
circle.setScaleX(1.1);
circle.setScaleY(1.1);//只有第一次会生效
//root.getChildren().removeAll(pencilView);
pencilView.setX(rd.nextInt()%600+600);
pencilView.setY(rd.nextInt(800));
}
public void press(ActionEvent event)
{
Group copy=new Group(pencilView);//居然可以group?
if(event.getSource()==cut) root.getChildren().removeAll(copy);//我理解为指针一样所以操作一样
else { if(!root.getChildren().contains(pencilView)) root.getChildren().add(pencilView); }
}
public static void main(String[] args)
{
launch(args);
}
}
| VictorYuanII/mspaint-for-OI | src/ShiYan.java |
65,044 | package Chapter1_1High;
//Exercise 1.1.27
public class BinomialSample { //二项分布发生k次的概率
/*
* 使用一个二维数组来存储各项二项分布的概率
* 行代表重复N次实验,列代表发生k次,所以在下面循环条件中需要j<=i
* */
public static double[][] binomial(int N, int k, double p) {
double[][] array = new double[N + 1][k + 1];
//给二维数组初始化第一列,避免下面执行时出现数组下标越界
array[0][0] = 1.0;
for (int i = 1; i < N + 1; i++)
array[i][0] = array[i - 1][0] * (1 - p);
for (int i = 1; i < N + 1; i++)
for (int j = 1; j <= i && j < k + 1; j++)
array[i][j] = (1 - p) * array[i - 1][j] + p * array[i - 1][j - 1]; //前i-1次实验中已经发生j-1次的概率加上前i-1次实验中没有已经发生j次的概率
return array;
}
public static void main(String[] args) {
double[][] array = binomial(100, 50, 0.25); //100次实验中发生50次的概率,每一次实验中发生的概率为0.25
System.out.println(array[100][50]);
}
}
| hackeryang/Algorithms-Fourth-Edition-Exercises | src/Chapter1_1High/BinomialSample.java |
65,045 | package c61;
import android.content.Context;
import com.tencent.p014mm.app.C80625v0;
import com.tencent.p014mm.plugin.appbrand.appcache.C29315z2;
import com.tencent.p014mm.sdk.platformtools.BuildInfo;
import com.tencent.p014mm.sdk.platformtools.Log;
import com.tencent.p014mm.sdk.platformtools.MMApplicationContext;
import com.tencent.p014mm.sdk.platformtools.WeChatEnvironment;
import d61.C7239b;
import di0.C86294i;
import di3.C86301e;
import di3.C86312j;
import ei3.C86522b;
import gy3.C87412m;
import h61.C8490d;
import h61.C87455a;
import kr0.C33983a1;
import kr0.C33987b1;
import o40.C61926c;
@C86522b(dependencies = {C86294i.class}, onProcess = {C80625v0.MATCH_MM})
/* renamed from: c61.b */
public final class C79937b extends C86301e implements C7239b {
/* renamed from: c61.b$a */
public static final class C79938a implements C33983a1.C33985b {
/* renamed from: a */
public static final C79938a f234159a = new C79938a();
/* renamed from: b */
public final void mo56555b(C29315z2 z2Var, String str) {
C87412m.m108594g(z2Var, "<anonymous parameter 0>");
C87412m.m108594g(str, "path");
String str2 = "下载代码包成功:" + str;
C87412m.m108594g(str2, "msg");
if (BuildInfo.DEBUG || BuildInfo.IS_FLAVOR_RED || WeChatEnvironment.hasDebugger() || !C87455a.f253425a.f253431a.equals("wx9d5f7f0bf2dc950c")) {
C61926c.m72668M(new C8490d(str2));
return;
}
Log.m105921e("MagicEmojiUtils", "[MagicEmoji]: %s", str2);
}
}
/* renamed from: c61.b$b */
public static final class C79939b implements C33983a1.C33984a {
/* renamed from: a */
public static final C79939b f234160a = new C79939b();
/* renamed from: a */
public final void mo8657a(int i, String str) {
String str2 = "下载代码包失败: codes = " + i + ", msg = " + str;
C87412m.m108594g(str2, "msg");
if (BuildInfo.DEBUG || BuildInfo.IS_FLAVOR_RED || WeChatEnvironment.hasDebugger() || !C87455a.f253425a.f253431a.equals("wx9d5f7f0bf2dc950c")) {
C61926c.m72668M(new C8490d(str2));
return;
}
Log.m105921e("MagicEmojiUtils", "[MagicEmoji]: %s", str2);
}
}
public void nn0(boolean z) {
if (z) {
if (!C87455a.f253429e) {
C87455a.C87456a aVar = C87455a.f253428d;
C87412m.m108593f(aVar, "CURRENT_USING_APPID_BUNDLE_COCOS");
vx0(true, aVar);
} else if (BuildInfo.DEBUG || BuildInfo.IS_FLAVOR_RED || WeChatEnvironment.hasDebugger() || !C87455a.f253425a.f253431a.equals("wx9d5f7f0bf2dc950c")) {
C61926c.m72668M(new C8490d("走 boots 不支持下载"));
} else {
Log.m105921e("MagicEmojiUtils", "[MagicEmoji]: %s", "走 boots 不支持下载");
}
} else if (!C87455a.f253426b) {
C87455a.C87456a aVar2 = C87455a.f253425a;
C87412m.m108593f(aVar2, "CURRENT_USING_APPID_BUNDLE_UNITY");
vx0(false, aVar2);
} else if (BuildInfo.DEBUG || BuildInfo.IS_FLAVOR_RED || WeChatEnvironment.hasDebugger() || !C87455a.f253425a.f253431a.equals("wx9d5f7f0bf2dc950c")) {
C61926c.m72668M(new C8490d("走 boots 不支持下载"));
} else {
Log.m105921e("MagicEmojiUtils", "[MagicEmoji]: %s", "走 boots 不支持下载");
}
}
public void onAccountInitialized(Context context) {
C87412m.m108594g(context, "context");
if (MMApplicationContext.isMainProcess()) {
((C86294i) C86312j.m106911c(C86294i.class)).requireAndWaitForAccountInitialized();
C87455a.C87456a aVar = C87455a.f253425a;
((C33983a1) C86312j.m106911c(C33983a1.class)).mo56532sv(aVar.f253432b, aVar.f253431a, 999);
((C33987b1) C86312j.m106911c(C33987b1.class)).mo59394hF(aVar.f253431a, 0);
}
}
public final void vx0(boolean z, C87455a.C87456a aVar) {
String str = "开始下载代码包,isCocos:" + z + ", appId:" + aVar.f253431a + ", versionType:" + wx0(aVar.f253433c);
C87412m.m108594g(str, "msg");
if (BuildInfo.DEBUG || BuildInfo.IS_FLAVOR_RED || WeChatEnvironment.hasDebugger() || !C87455a.f253425a.f253431a.equals("wx9d5f7f0bf2dc950c")) {
C61926c.m72668M(new C8490d(str));
} else {
Log.m105921e("MagicEmojiUtils", "[MagicEmoji]: %s", str);
}
((C33983a1) C86312j.m106911c(C33983a1.class)).mo56533yv(aVar.f253431a, aVar.f253433c, C79938a.f234159a, C79939b.f234160a);
}
public final String wx0(int i) {
return i != 0 ? i != 1 ? i != 2 ? "unknown" : "体验版" : "开发版" : "正式版";
}
public String zd0() {
StringBuilder sb = new StringBuilder();
C87455a.C87456a aVar = C87455a.f253425a;
sb.append("Unity 包信息:");
sb.append(10);
sb.append("appId: ");
sb.append(aVar.f253431a);
sb.append(10);
sb.append("userName: ");
sb.append(aVar.f253432b);
sb.append(10);
sb.append("versionType: ");
sb.append(wx0(aVar.f253433c));
sb.append(10);
sb.append("debugMode: ");
sb.append(C87455a.f253427c);
sb.append(10);
C87455a.C87456a aVar2 = C87455a.f253428d;
sb.append("Cocos 包信息:");
sb.append(10);
if (aVar2 != null) {
sb.append("appId: ");
sb.append(aVar2.f253431a);
sb.append(10);
sb.append("userName: ");
sb.append(aVar2.f253432b);
sb.append(10);
sb.append("versionType: ");
sb.append(wx0(aVar2.f253433c));
sb.append(10);
} else {
sb.append("没有 cocos 包的 x 实验");
sb.append(10);
}
sb.append("版本类型:");
sb.append("2.0 版本");
String sb4 = sb.toString();
C87412m.m108593f(sb4, "builder.toString()");
return sb4;
}
}
| Durjoy-majumdar/DeChat | c/c61/C79937b.java |
65,046 | package 实验1;
/**
* @author Smartloe
* @create 2023-04-27 11:04
*/
public class Hello {
public static void main(String args[]) {
// 【代码1】命令行窗口输出"你好,很高兴学习Java"
System.out.println("你好,很高兴学习Java");
AB a = new AB();
a.fA();
}
}
class AB {
void fA() {
// 【代码2】命令行窗口输出"We are students"
System.out.println("We are students");
}
} | Smartloe/Java_training | src/实验1/Hello.java |
65,047 | package 实验4;
/**
* @author Smartloe
* @create 2023-05-18 11:17
*/
//----begin-----
//编写抽象类Animal
//Animal抽象类有两个抽象方法cry()和getAnimalName(),即要求各种具体的动物给出自己的叫声和种类名称。
abstract class Animal {
public abstract String cry();
public abstract String getAnimalName();
}
//编写模拟器类Simulator
//该类有一个playSound(Animal animal)方法,该方法的参数是Animal类型。即参数animal可以调用Animal的子类重写的cry()方法播放具体动物的声音,调用子类重写的getAnimalName()方法显示动物种类的名称。
class Simulator {
// 播放指定动物的声音
public void playSound(Animal animal) {
System.out.println("现在播放" + animal.getAnimalName() + "的声音:" + animal.cry());
}
}
//编写Animal类的子类:Dog和Cat类
class Cat extends Animal {
@Override
public String cry() {
return "喵喵...喵喵";
}
@Override
public String getAnimalName() {
return "猫类";
}
}
class Dog extends Animal {
@Override
public String cry() {
return "汪汪...汪汪";
}
@Override
public String getAnimalName() {
return "狗类";
}
}
//----end----
class Main123 {
public static void main(String args[]) {
Simulator simulator = new Simulator();
simulator.playSound(new Dog());
simulator.playSound(new Cat());
}
} | Smartloe/Java_training | src/实验4/Animal.java |
65,048 | package 实验1;
import java.util.Scanner;
/**
* @author Smartloe
* @create 2023-04-27 11:07
*/
public class Student {
public static void main(String args[]) {
Scanner reader = new Scanner(System.in);
System.out.println("输入姓名(回车确认):");
// 【代码1】从键盘为name赋值
String name = reader.nextLine();
System.out.println("输入年龄(回车确认):");
// 【代码2】从键盘为age赋值
int age = reader.nextInt();
System.out.println("输入身高(回车确认):");
// 【代码3】从键盘为height赋值
double height = reader.nextDouble();
System.out.printf("%28s\n", "--基本信息--");
System.out.printf("%10s%-10s", "姓名:", name);
System.out.printf("%4s%-4d", "年龄:", age);
System.out.printf("%4s%-4.2f", "身高:", height);
}
}
| Smartloe/Java_training | src/实验1/Student.java |
65,049 | package 实验4; /**
* @author Smartloe
* @create 2023-05-18 10:50
*/
import java.util.Scanner;
// 请在下面的Begin-End之间按照注释中给出的提示编写正确的代码
/********** Begin **********/
// 定义员工抽象类 Employee,其中包含 2 个受保护的变量和两个抽象方法
abstract class Employee {
// 两个受保护的变量:姓名 name(String),和工资 salary(double);
protected String name;
protected Double salary;
//抽象方法 work,无返回值,表示工作内容
public abstract void work();
//抽象方法 info,无返回值,表示员工信息
public abstract void info();
}
// 定义一个经理类 Manager,该类继承员工类,除了有员工类的基本属性外,还有岗位级别 gender(String)私有属性。
class Manager extends Employee {
private String gender;
// 定义一个有参构造方法
public Manager(String name, Double salary, String gender) {
this.name = name;
this.salary = salary;
this.gender = gender;
}
// 重写 work() 方法,输出:“我负责对施工项目实施全过程、全面管理。”;
@Override
public void work() {
System.out.println("我负责对施工项目实施全过程、全面管理。");
}
// 重写 info() 方法,输出:“姓名:xx,工资:xx,岗位级别:xx”。
@Override
public void info() {
System.out.printf("姓名:%s,工资:%.1f,岗位级别:%s\n", this.name, this.salary, this.gender);
}
}
/********** End **********/
class Main12 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Manager e1 = new Manager(sc.next(), sc.nextDouble(), sc.next());
e1.info();
e1.work();
}
}
| Smartloe/Java_training | src/实验4/Employee.java |
65,050 | package 实验5;
/**
* @author Smartloe
* @create 2023-05-25 10:26
*/
/*
* 接口ICompute
* 抽象方法计算compute(double n,double m)
*/
interface ICompute {
double compute(double n, double m);
}
//----begin----
/*
* 加法类Add实现接口ICompute
* 重写compute(double n,double m)方法,计算n+m的和并输出
*/
class Add implements ICompute {
@Override
public double compute(double n, double m) {
System.out.println(n + "+" + m + "=" + (n + m));
return n + m;
}
}
/*
* 减法类Minus实现接口ICompute
* 重写compute(double n,double m)方法,计算 n-m的差并输出
*/
class Minus1 implements ICompute {
@Override
public double compute(double n, double m) {
System.out.println(n + "-" + m + "=" + (n - m));
return n - m;
}
}
/*
* 乘法类Mul实现接口ICompute
* 重写compute(double n,double m)方法,计算 n*m的积并输出
*/
class Mul implements ICompute {
@Override
public double compute(double n, double m) {
System.out.println(n + "*" + m + "=" + (n * m));
return n * m;
}
}
/*
* 除法类Div实现接口ICompute
* 重写compute(double n,double m)方法,计算 n/m的商并输出
*/
class Div1 implements ICompute {
@Override
public double compute(double n, double m) {
System.out.println(n + "/" + m + "=" + (n / m));
return n / m;
}
}
/*
* UseCompute类
* useCom(ICompute com,double n,double m)方法,输入计算类型和要计算的数据 n,m, 输出对应的运算结果
*/
class UseCompute {
public void useCom(ICompute com, double n, double m) {
com.compute(n, m);
}
}
//----end----
public class JiSuanQi {
public static void main(String[] args) {
UseCompute fun = new UseCompute();
double m = 8, n = 2;
fun.useCom(new Add(), m, n);
fun.useCom(new Minus1(), m, n);
fun.useCom(new Mul(), m, n);
fun.useCom(new Div1(), m, n);
}
}
| Smartloe/Java_training | src/实验5/JiSuanQi.java |
65,051 | package 实验7;
/**
* @author Smartloe
* @create 2023-06-08 11:48
*/
import java.util.Scanner;
// 此类为整个通讯录的总控制,负责启动
public class MenuPhone {
public static void main(String[] args) {
User[] users = new User[50]; // 创建一个对象数组,用于存放所有的通讯录信息
// 请在下面的Begin-End之间按照注释中给出的提示编写正确的代码
/********** Begin **********/
// 实例化 Scanner 对象
Scanner sc = new Scanner(System.in);
// 实例化 PhoneManage 对象
PhoneManage pm = new PhoneManage();
while (true) {
System.out.println("通讯录信息管理页面");
System.out.println("**********");
System.out.println("1.新增");
System.out.println("2.查看");
System.out.println("3.删除");
System.out.println("4.修改");
System.out.println("5.退出");
System.out.println("**********");
System.out.println("请输入选择的操作:");
// 获取键盘输入
int choice = sc.nextInt();
switch (choice) {
case 1:
pm.addPhone(users, sc);
break;
case 2:
pm.showPhone(users);
break;
case 3:
pm.deletePhone(users, sc);
break;
case 4:
pm.changePhone(users, sc);
break;
case 5:
System.out.println("退出成功!");
return;
default:
System.out.println("选择错误!");
break;
}
}
/********** End **********/
}
}
| Smartloe/Java_training | src/实验7/MenuPhone.java |
65,052 | package base_api;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.Test;
public class Demo01 {
/*
* 创建表
*/
@Test
public void testCreateTable() throws Exception{
Configuration conf=HBaseConfiguration.create();
//因为本demo是单机版hbase,其内置zookeeper
conf.set("hbase.zookeeper.quorum","192.168.10.106:2181");
HBaseAdmin admin = new HBaseAdmin(conf);
//指定表名
HTableDescriptor tab1=new HTableDescriptor(TableName.valueOf("tab1"));
//指定列族名
HColumnDescriptor colfam1=new HColumnDescriptor("colfam1".getBytes());
HColumnDescriptor colfam2=new HColumnDescriptor("colfam2".getBytes());
//指定历史版本存留上限
colfam1.setMaxVersions(3);
tab1.addFamily(colfam1);
tab1.addFamily(colfam2);
//创建表
admin.createTable(tab1);
admin.close();
}
/*
* 插入数据
*/
@Test
public void testInsert() throws Exception{
Configuration conf=HBaseConfiguration.create();
conf.set("hbase.zookeeper.quorum",
"linux101:2181");
//尽量复用Htable对象
HTable table=new HTable(conf,"tab1");
Put put=new Put("row-1".getBytes());
//列族,列,值
put.add("colfam1".getBytes(),"col1".getBytes(),"aaa".getBytes());
put.add("colfam1".getBytes(),"col2".getBytes(),"bbb".getBytes());
table.put(put);
table.close();
}
/*
* 实验: 100万条数据写入
*/
@Test
public void testInsertMillion() throws Exception{
Configuration conf=HBaseConfiguration.create();
conf.set("hbase.zookeeper.quorum",
"linux101:2181");
HTable table=new HTable(conf,"tab1");
List<Put> puts=new ArrayList<Put>();
long begin=System.currentTimeMillis();
for(int i=1;i<1000000;i++){
Put put=new Put(("row"+i).getBytes());
put.add("colfam1".getBytes(),"col".getBytes(),(""+i).getBytes());
puts.add(put);
//批处理,批大小为:10000
if(i%10000==0){
table.put(puts);
puts=new ArrayList<>();
}
}
long end=System.currentTimeMillis();
System.out.println(end-begin);
}
/*
* 获取数据
*/
@Test
public void testGet() throws Exception{
Configuration conf=HBaseConfiguration.create();
conf.set("hbase.zookeeper.quorum",
"linux101:2181");
HTable table=new HTable(conf,"tab1");
Get get=new Get("row2".getBytes());
Result result=table.get(get);
byte[] col1_result=result.getValue("colfam1".getBytes(),"col".getBytes());
System.out.println(new String(col1_result));
table.close();
}
/*
* 获取数据集
*/
@Test
public void testScan() throws Exception{
Configuration conf=HBaseConfiguration.create();
conf.set("hbase.zookeeper.quorum",
"linux101:2181");
HTable table = new HTable(conf,"tab1");
//获取row100及以后的行键的值
Scan scan = new Scan("row1000000".getBytes());
ResultScanner scanner = table.getScanner(scan);
Iterator it = scanner.iterator();
while(it.hasNext()){
Result result = (Result) it.next();
byte [] bs = result.getValue(Bytes.toBytes("colfam1"),Bytes.toBytes("col"));
String str = Bytes.toString(bs);
System.out.println(str);
}
table.close();
}
/*
* 删除数据
*/
@Test
public void testDelete() throws Exception{
Configuration conf=HBaseConfiguration.create();
conf.set("hbase.zookeeper.quorum",
"linux101:2181");
HTable table = new HTable(conf,"tab1");
Delete delete=new Delete("row1".getBytes());
table.delete(delete);
table.close();
}
/*
* 删除表
*/
@Test
public void testDeleteTable() throws Exception{
Configuration conf=HBaseConfiguration.create();
conf.set("hbase.zookeeper.quorum",
"linux101:2181");
HBaseAdmin admin=new HBaseAdmin(conf);
admin.disableTable("tab1".getBytes());
admin.deleteTable("tab1".getBytes());
admin.close();
}
}
| shuzhiwei/Test-HBase | base_api/Demo01.java |
65,053 | package 实验3;
/**
* @author Smartloe
* @create 2023-05-11 10:09
*/
public class Tank {
//---begin---
//【代码 1】包含两个变量double 型变量 speed,刻画速度
double speed;
//【代码 2】int 型变量 bulletAmount,刻画炮弹数量
int bulletAmount;
//speedUp(int s) 加速方法,将 s+speed 赋值给 speed
public void speedUp(int s) {
speed += s;
}
//speedDown(int d) 加速方法,将 speed-d 赋值给 speed,如果速度 speed-d<0,不再减速,速度设定为0
public void speedDown(int d) {
speed -= d;
}
void setBulletAmount(int m) {
bulletAmount = m;
}
int getBulletAmount() {
return bulletAmount;
}
double getSpeed() {
return speed;
}
//fire() 开火方法,每开一次,输出:打出一发炮弹,且炮弹数量bulletAmount减1。
//如果炮弹数量低于1,输出:没有炮弹了,无法开火
public void fire() {
bulletAmount--;
if (bulletAmount < 1) {
System.out.println("没有炮弹了,无法开火");
} else {
System.out.println("打出一发炮弹");
}
}
//---end---
}
class Fight {
public static void main(String args[]) {
Tank tank1, tank2;
tank1 = new Tank();
tank2 = new Tank();
tank1.setBulletAmount(10);
tank2.setBulletAmount(10);
System.out.println("tank1 的炮弹数量: " + tank1.getBulletAmount());
System.out.println("tank2 的炮弹数量: " + tank2.getBulletAmount());
tank1.speedUp(80);
tank2.speedUp(90);
System.out.println("tank1 目前的速度: " + tank1.getSpeed());
System.out.println("tank2 目前的速度: " + tank2.getSpeed());
tank1.speedDown(15);
tank2.speedDown(30);
System.out.println("tank1 目前的速度: " + tank1.getSpeed());
System.out.println("tank2 目前的速度: " + tank2.getSpeed());
System.out.println("tank1 开火: ");
tank1.fire();
System.out.println("tank2 开火: ");
tank2.fire();
tank2.fire();
System.out.println("tank1 的炮弹数量: " + tank1.getBulletAmount());
System.out.println("tank2 的炮弹数量: " + tank2.getBulletAmount());
}
} | Smartloe/Java_training | src/实验3/Tank.java |
65,054 | package 实验2;
import javax.swing.*;
import java.util.Scanner;
/**
* @author Smartloe
* @create 2023-05-04 10:47
*/
public class GuessNumber {
public static void main(String args[]) {
Scanner reader = new Scanner(System.in);
int realNumber = reader.nextInt();
System.out.println("输入您的猜测:");
int yourGuess = reader.nextInt();
//----begin----
while (true) {
if (realNumber > yourGuess) {
System.out.println("猜小了,再输入你的猜测:");
} else if (realNumber < yourGuess) {
System.out.println("猜大了,再输入你的猜测:");
} else {
System.out.println("猜对了!");
break;
}
yourGuess = reader.nextInt();
}
//----end----
reader.close();
}
}
| Smartloe/Java_training | src/实验2/GuessNumber.java |
65,055 | package 实验1;
///**
// * @author Smartloe
// * @create 2023-04-27 11:08
// */
public class LargeNum {
public static void main(String args[]) {
int a[] = {9, 9, 7, 3, 3, 4, 5, 9, 6, 7, 8, 9, 0, 8, 9, 9};
int b[] = {5, 9, 8, 8, 0, 7, 9, 0, 8, 0, 8, 0, 8, 7, 6, 5, 5, 4, 4, 8};
// int a[] = {1,0,3};
// int b[] = {1,2,3};
int x[] = null, z[] = null, flag = 0, k = 0;
int i = 0, l = 0, result = 0;
for (int j : a) {
System.out.printf("%d", j);
}
System.out.printf("\n减去:\n");
for (int j : b) {
System.out.printf("%d", j);
}
//---begin---
for (i = 0; i < a.length / 2; i++) {
int temp = a[i];
a[i] = a[a.length - i - 1];
a[a.length - i - 1] = temp;
}
for (i = 0; i < b.length / 2; i++) {
int temp = b[i];
b[i] = b[b.length - i - 1];
b[b.length - i - 1] = temp;
}
if (a.length >= b.length) {
x = a;
z = b;
} else {
x = b;
z = a;
flag = -1;
}
int c[] = new int[x.length];
for (i = 0; i < x.length; i++) {
if (i < z.length) {
result = x[i] - z[i];
} else {
result = x[i];
}
if (result < 0) {
x[i + 1]--;
result += 10;
}
c[i] = result;
}
// 保存数组结果
for (i = 0; i < c.length / 2; i++) {
int temp = c[i];
c[i] = c[c.length - i - 1];
c[c.length - i - 1] = temp;
}
//---end---
System.out.printf("\n等于:\n");
if (flag == 0) {
System.out.printf("%d", 0);
} else {
if (flag < 0) {
System.out.printf("-");
}
for (i = 0; i < c.length; i++) {
if (c[i] != 0) {
k = i;
break;
}
}
for (i = k; i < c.length; i++) {
System.out.printf("%d", c[i]);
}
}
}
}
| Smartloe/Java_training | src/实验1/LargeNum.java |
65,058 | package unit09;
/**
* 现场编程
*
* 将服务器改造为能够接受客户端多次连接; 每次连接只提供一次面积计算服务
*
* 观察:一次连接发送多个半径的客户端(Demo09P2C)会如何导致程序停止
*/
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Demo09P3S {
public static void main(String[] args) {
// Task1. 完成 try-catch-finally 模式
// Task2. 将try改造为 try-with-resource
// Task3. 将服务器改造为支持客户端多次连接
try {
// Create a server socket
ServerSocket serverSocket = new ServerSocket(8000);
System.out.println("Server Started");
while (true) {
// Listen for a connection request
Socket socket = serverSocket.accept();
// Create data input and output streams
DataInputStream inputFromClient = new DataInputStream(socket.getInputStream());
DataOutputStream outputToClient = new DataOutputStream(socket.getOutputStream());
// Receive radius from the client
double radius = inputFromClient.readDouble();
// Compute area
double area = radius * radius * Math.PI;
// Send area back to the client
outputToClient.writeDouble(area);
System.out.println("Radius received from client: " + radius);
System.out.println("Area is: " + area);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
| AlohaWorld/Lessons4JavaSE | src/unit09/Demo09P3S.java |
65,059 | package array;
import tree.TreeNode;
/**
* Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
* <p>
* Created by DrunkPiano on 2017/3/29.
*/
class SymmetricTree {
/**
* 题意:判断两棵树是不是对称树
* 观察,发现对称tree的子树不一定是对称的。所以需要双管齐下去traverse
**/
public boolean isSymmetric(TreeNode root) {
return root == null || dfs(root.left, root.right);
}
private boolean dfs(TreeNode left, TreeNode right) {
if (left == null || right == null) return left == right;
return left.val == right.val && dfs(left.right, right.left) && dfs(left.left, right.right);
}
/**
* //20190207 REVIEW
* //方法1. BFS,观察到序列化的树的序列想到的
* //方法2. BOTTOM-UP递归,这个问题可以转换为,根节点的左右两个child是不是inverse过来就相同结构了;画图想到的
*/
public boolean isSymmetric__20190207(TreeNode root) {
if (root == null) return true;
// if(root.left == null) return root.right == null;
// if(root.right == null) return false;
return helper(root.left, root.right);
}
private boolean helper(TreeNode left, TreeNode right) {
if (left == null) return right == null;
if (right == null) return false;
if (left.val != right.val) return false;
return helper(left.right, right.left) && helper(left.left, right.right);//已犯错误1. 漏掉&&右边的条件
}
public static void main(String args[]) {
TreeNode root = new TreeNode(1);
TreeNode root1 = new TreeNode(2);
TreeNode root2 = new TreeNode(2);
TreeNode root3 = new TreeNode(3);
TreeNode root4 = new TreeNode(3);
root.left = root1;
root.right = root2;
root1.right = root3;
root2.right = root4;
SymmetricTree symmetricTree = new SymmetricTree();
System.out.println(symmetricTree.isSymmetric(root));
System.out.println(symmetricTree.isSymmetric(root));
}
}
| chaangliu/leetcode-training | array/SymmetricTree.java |
65,060 | /*
* Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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 General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.util;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamField;
import java.io.Serializable;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.DoubleConsumer;
import java.util.function.IntConsumer;
import java.util.function.LongConsumer;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
import java.util.stream.StreamSupport;
import jdk.internal.misc.Unsafe;
/**
* An instance of this class is used to generate a stream of
* pseudorandom numbers. The class uses a 48-bit seed, which is
* modified using a linear congruential formula. (See Donald Knuth,
* <i>The Art of Computer Programming, Volume 2</i>, Section 3.2.1.)
* <p>
* If two instances of {@code Random} are created with the same
* seed, and the same sequence of method calls is made for each, they
* will generate and return identical sequences of numbers. In order to
* guarantee this property, particular algorithms are specified for the
* class {@code Random}. Java implementations must use all the algorithms
* shown here for the class {@code Random}, for the sake of absolute
* portability of Java code. However, subclasses of class {@code Random}
* are permitted to use other algorithms, so long as they adhere to the
* general contracts for all the methods.
* <p>
* The algorithms implemented by class {@code Random} use a
* {@code protected} utility method that on each invocation can supply
* up to 32 pseudorandomly generated bits.
* <p>
* Many applications will find the method {@link Math#random} simpler to use.
*
* <p>Instances of {@code java.util.Random} are threadsafe.
* However, the concurrent use of the same {@code java.util.Random}
* instance across threads may encounter contention and consequent
* poor performance. Consider instead using
* {@link java.util.concurrent.ThreadLocalRandom} in multithreaded
* designs.
*
* <p>Instances of {@code java.util.Random} are not cryptographically
* secure. Consider instead using {@link java.security.SecureRandom} to
* get a cryptographically secure pseudo-random number generator for use
* by security-sensitive applications.
*
* @author Frank Yellin
* @since 1.0
*/
/*
* 伪随机数生成器
*
* 线程安全
* 适用于大多数单线程场景
*
* 在多线程中,生成随机数的性能欠佳(存在线程争用)
* 该类更适用于单线程环境,在多线程中可以使用ThreadLocalRandom
*
* 支持使用内置种子计算的原始种子
* 支持自定义原始种子
*/
public class Random implements Serializable {
/** use serialVersionUID from JDK 1.1 for interoperability */
static final long serialVersionUID = 3905348978240129619L;
/**
* Serializable fields for Random.
*
* @serialField seed long
* seed for random computations
* @serialField nextNextGaussian double
* next Gaussian to be returned
* @serialField haveNextNextGaussian boolean
* nextNextGaussian is valid
*/
// 确定哪些字段参与序列化
private static final ObjectStreamField[] serialPersistentFields = {
new ObjectStreamField("seed", Long.TYPE),
new ObjectStreamField("nextNextGaussian", Double.TYPE),
new ObjectStreamField("haveNextNextGaussian", Boolean.TYPE)
};
// IllegalArgumentException messages
static final String BadBound = "bound must be positive";
static final String BadRange = "bound must be greater than origin";
static final String BadSize = "size must be non-negative";
/*▼ 内置种子 ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓┓ */
// 哈希魔数[偶],作为内置种子的初始值
private static final long m0 = 0x5DEECE66DL;
// 哈希魔数[偶],用来更新内置种子
private static final long M = 1181783497276652981L;
/*
* 内置种子,用于为默认的Random实例生成原始种子
*
* 当用户没有显式指定随机数种子时,使用内置种子来推导原始种子的值
* 每创建一个默认的Random实例,内置种子的值就改变一次
*/
private static final AtomicLong seedUniquifier = new AtomicLong(m0); // 初始的种子标记
/*▲ 内置种子 ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓┛ */
/*▼ 原始种子 ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓┓ */
// 哈希魔数,用来更新原始种子
private static final long multiplier = 0x5DEECE66DL;
private static final long addend = 0xBL; // 偏移量
// 更新原始种子时使用的掩码
private static final long mask = (1L << 48) - 1;
/**
* The internal state associated with this pseudorandom number generator.
* (The specs for the methods in this class describe the ongoing computation of this value.)
*/
/*
* 原始种子,Random实例使用该种子生成伪随机数
*
* 原始种子的初值可由系统的内置种子配合系统时间生成,也可由用户指定
* 每生成一个随机数,原始种子的值就改变一次
*
* 如果原始种子被单个线程持有,那么接下来生成的一系列随机数是均匀的
* 如果原始种子被多个线程持有,那么从单个线程的角度观察,其生成的随机数是不均匀的
*/
private final AtomicLong seed;
/*▲ 原始种子 ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓┛ */
// float值的二进制精度
private static final float FLOAT_UNIT = 0x1.0p-24f; // 1.0f/(1 << 24)
// double值的二进制精度
private static final double DOUBLE_UNIT = 0x1.0p-53; // 1.0/(1L << 53)
private double nextNextGaussian;
private boolean haveNextNextGaussian = false;
// Support for resetting seed while deserializing
private static final Unsafe unsafe = Unsafe.getUnsafe();
private static final long seedOffset; // 记录seed属性在JVM内存中的的偏移地址
static {
try {
seedOffset = unsafe.objectFieldOffset(Random.class.getDeclaredField("seed"));
} catch(Exception ex) {
throw new Error(ex);
}
}
/*▼ 构造方法 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Creates a new random number generator. This constructor sets
* the seed of the random number generator to a value very likely
* to be distinct from any other invocation of this constructor.
*/
// 构造默认的伪随机数生成器
public Random() {
// 配合当前的系统时间,生成一个内置种子,并进一步计算出原始种子
this(seedUniquifier() ^ System.nanoTime());
}
/**
* Creates a new random number generator using a single {@code long} seed.
* The seed is the initial value of the internal state of the pseudorandom
* number generator which is maintained by method {@link #next}.
*
* <p>The invocation {@code new Random(seed)} is equivalent to:
* <pre> {@code
* Random rnd = new Random();
* rnd.setSeed(seed);}</pre>
*
* @param seed the initial seed
*
* @see #setSeed(long)
*/
// 构造指定种子的伪随机数生成器
public Random(long seed) {
if(getClass() == Random.class) {
// 对指定的种子加工后作为当前Random实例的种子的初始值
this.seed = new AtomicLong(initialScramble(seed));
} else {
// subclass might have overriden setSeed
this.seed = new AtomicLong();
setSeed(seed);
}
}
/*▲ 构造方法 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 种子 ████████████████████████████████████████████████████████████████████████████████┓ */
// 更新内置种子,每初始化一个默认的Random实例就调用一次
private static long seedUniquifier() {
// L'Ecuyer, "Tables of Linear Congruential Generators of Different Sizes and Good Lattice Structure", 1999
for(; ; ) {
long current = seedUniquifier.get();
long next = current * M;
// 更新seedUniquifier为新值next,更新时参考的期望值是current
if(seedUniquifier.compareAndSet(current, next)) {
return next;
}
}
}
/**
* Sets the seed of this random number generator using a single
* {@code long} seed. The general contract of {@code setSeed} is
* that it alters the state of this random number generator object
* so as to be in exactly the same state as if it had just been
* created with the argument {@code seed} as a seed. The method
* {@code setSeed} is implemented by class {@code Random} by
* atomically updating the seed to
* <pre>{@code (seed ^ 0x5DEECE66DL) & ((1L << 48) - 1)}</pre>
* and clearing the {@code haveNextNextGaussian} flag used by {@link
* #nextGaussian}.
*
* <p>The implementation of {@code setSeed} by class {@code Random}
* happens to use only 48 bits of the given seed. In general, however,
* an overriding method may use all 64 bits of the {@code long}
* argument as a seed value.
*
* @param seed the initial seed
*/
// 设置原始种子,该方法可能由子类重写
public synchronized void setSeed(long seed) {
this.seed.set(initialScramble(seed));
haveNextNextGaussian = false;
}
// 加工原始种子
private static long initialScramble(long seed) {
return (seed ^ multiplier) & mask;
}
// 重置原始种子为seedVal
private void resetSeed(long seedVal) {
unsafe.putObjectVolatile(this, seedOffset, new AtomicLong(seedVal));
}
/*▲ 种子 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 生成伪随机数 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Generates random bytes and places them into a user-supplied
* byte array. The number of random bytes produced is equal to
* the length of the byte array.
*
* <p>The method {@code nextBytes} is implemented by class {@code Random}
* as if by:
* <pre> {@code
* public void nextBytes(byte[] bytes) {
* for (int i = 0; i < bytes.length; )
* for (int rnd = nextInt(), n = Math.min(bytes.length - i, 4);
* n-- > 0; rnd >>= 8)
* bytes[i++] = (byte)rnd;
* }}</pre>
*
* @param bytes the byte array to fill with random bytes
*
* @throws NullPointerException if the byte array is null
* @since 1.1
*/
// 随机填充一个byte数组,有正有负
public void nextBytes(byte[] bytes) {
for(int i = 0, len = bytes.length; i<len; ) {
for(int rnd = nextInt(), n = Math.min(len - i, Integer.SIZE / Byte.SIZE); n-->0; rnd >>= Byte.SIZE) {
bytes[i++] = (byte) rnd;
}
}
}
/**
* Returns the next pseudorandom, uniformly distributed {@code int}
* value from this random number generator's sequence. The general
* contract of {@code nextInt} is that one {@code int} value is
* pseudorandomly generated and returned. All 2<sup>32</sup> possible
* {@code int} values are produced with (approximately) equal probability.
*
* <p>The method {@code nextInt} is implemented by class {@code Random}
* as if by:
* <pre> {@code
* public int nextInt() {
* return next(32);
* }}</pre>
*
* @return the next pseudorandom, uniformly distributed {@code int}
* value from this random number generator's sequence
*/
// 随机生成一个int值,有正有负
public int nextInt() {
return next(32);
}
/**
* Returns a pseudorandom, uniformly distributed {@code int} value
* between 0 (inclusive) and the specified value (exclusive), drawn from
* this random number generator's sequence. The general contract of
* {@code nextInt} is that one {@code int} value in the specified range
* is pseudorandomly generated and returned. All {@code bound} possible
* {@code int} values are produced with (approximately) equal
* probability. The method {@code nextInt(int bound)} is implemented by
* class {@code Random} as if by:
* <pre> {@code
* public int nextInt(int bound) {
* if (bound <= 0)
* throw new IllegalArgumentException("bound must be positive");
*
* if ((bound & -bound) == bound) // i.e., bound is a power of 2
* return (int)((bound * (long)next(31)) >> 31);
*
* int bits, val;
* do {
* bits = next(31);
* val = bits % bound;
* } while (bits - val + (bound-1) < 0);
* return val;
* }}</pre>
*
* <p>The hedge "approximately" is used in the foregoing description only
* because the next method is only approximately an unbiased source of
* independently chosen bits. If it were a perfect source of randomly
* chosen bits, then the algorithm shown would choose {@code int}
* values from the stated range with perfect uniformity.
* <p>
* The algorithm is slightly tricky. It rejects values that would result
* in an uneven distribution (due to the fact that 2^31 is not divisible
* by n). The probability of a value being rejected depends on n. The
* worst case is n=2^30+1, for which the probability of a reject is 1/2,
* and the expected number of iterations before the loop terminates is 2.
* <p>
* The algorithm treats the case where n is a power of two specially: it
* returns the correct number of high-order bits from the underlying
* pseudo-random number generator. In the absence of special treatment,
* the correct number of <i>low-order</i> bits would be returned. Linear
* congruential pseudo-random number generators such as the one
* implemented by this class are known to have short periods in the
* sequence of values of their low-order bits. Thus, this special case
* greatly increases the length of the sequence of values returned by
* successive calls to this method if n is a small power of two.
*
* @param bound the upper bound (exclusive). Must be positive.
*
* @return the next pseudorandom, uniformly distributed {@code int}
* value between zero (inclusive) and {@code bound} (exclusive)
* from this random number generator's sequence
*
* @throws IllegalArgumentException if bound is not positive
* @since 1.2
*/
// 随机生成一个[0, bound)之内的int值
public int nextInt(int bound) {
if(bound<=0) {
throw new IllegalArgumentException(BadBound);
}
int r = next(31);
int m = bound - 1;
if((bound & m) == 0) // i.e., bound is a power of 2
r = (int) ((bound * (long) r) >> 31);
else {
for(int u = r; u - (r = u % bound) + m<0; u = next(31))
;
}
return r;
}
/**
* Returns the next pseudorandom, uniformly distributed {@code long}
* value from this random number generator's sequence. The general
* contract of {@code nextLong} is that one {@code long} value is
* pseudorandomly generated and returned.
*
* <p>The method {@code nextLong} is implemented by class {@code Random}
* as if by:
* <pre> {@code
* public long nextLong() {
* return ((long)next(32) << 32) + next(32);
* }}</pre>
*
* Because class {@code Random} uses a seed with only 48 bits,
* this algorithm will not return all possible {@code long} values.
*
* @return the next pseudorandom, uniformly distributed {@code long}
* value from this random number generator's sequence
*/
// 随机生成一个long值,有正有负
public long nextLong() {
// it's okay that the bottom word remains signed.
return ((long) (next(32)) << 32) + next(32);
}
/**
* Returns the next pseudorandom, uniformly distributed {@code float}
* value between {@code 0.0} and {@code 1.0} from this random
* number generator's sequence.
*
* <p>The general contract of {@code nextFloat} is that one
* {@code float} value, chosen (approximately) uniformly from the
* range {@code 0.0f} (inclusive) to {@code 1.0f} (exclusive), is
* pseudorandomly generated and returned. All 2<sup>24</sup> possible
* {@code float} values of the form <i>m x </i>2<sup>-24</sup>,
* where <i>m</i> is a positive integer less than 2<sup>24</sup>, are
* produced with (approximately) equal probability.
*
* <p>The method {@code nextFloat} is implemented by class {@code Random}
* as if by:
* <pre> {@code
* public float nextFloat() {
* return next(24) / ((float)(1 << 24));
* }}</pre>
*
* <p>The hedge "approximately" is used in the foregoing description only
* because the next method is only approximately an unbiased source of
* independently chosen bits. If it were a perfect source of randomly
* chosen bits, then the algorithm shown would choose {@code float}
* values from the stated range with perfect uniformity.<p>
* [In early versions of Java, the result was incorrectly calculated as:
* <pre> {@code
* return next(30) / ((float)(1 << 30));}</pre>
* This might seem to be equivalent, if not better, but in fact it
* introduced a slight nonuniformity because of the bias in the rounding
* of floating-point numbers: it was slightly more likely that the
* low-order bit of the significand would be 0 than that it would be 1.]
*
* @return the next pseudorandom, uniformly distributed {@code float}
* value between {@code 0.0} and {@code 1.0} from this
* random number generator's sequence
*/
// 随机生成一个[0, 1)之内的double值
public float nextFloat() {
return next(24) * FLOAT_UNIT;
}
/**
* Returns the next pseudorandom, uniformly distributed
* {@code double} value between {@code 0.0} and
* {@code 1.0} from this random number generator's sequence.
*
* <p>The general contract of {@code nextDouble} is that one
* {@code double} value, chosen (approximately) uniformly from the
* range {@code 0.0d} (inclusive) to {@code 1.0d} (exclusive), is
* pseudorandomly generated and returned.
*
* <p>The method {@code nextDouble} is implemented by class {@code Random}
* as if by:
* <pre> {@code
* public double nextDouble() {
* return (((long)next(26) << 27) + next(27))
* / (double)(1L << 53);
* }}</pre>
*
* <p>The hedge "approximately" is used in the foregoing description only
* because the {@code next} method is only approximately an unbiased
* source of independently chosen bits. If it were a perfect source of
* randomly chosen bits, then the algorithm shown would choose
* {@code double} values from the stated range with perfect uniformity.
* <p>[In early versions of Java, the result was incorrectly calculated as:
* <pre> {@code
* return (((long)next(27) << 27) + next(27))
* / (double)(1L << 54);}</pre>
* This might seem to be equivalent, if not better, but in fact it
* introduced a large nonuniformity because of the bias in the rounding
* of floating-point numbers: it was three times as likely that the
* low-order bit of the significand would be 0 than that it would be 1!
* This nonuniformity probably doesn't matter much in practice, but we
* strive for perfection.]
*
* @return the next pseudorandom, uniformly distributed {@code double}
* value between {@code 0.0} and {@code 1.0} from this
* random number generator's sequence
*
* @see Math#random
*/
// 随机生成一个[0, bound)之内的double值
public double nextDouble() {
return (((long) (next(26)) << 27) + next(27)) * DOUBLE_UNIT;
}
/**
* Returns the next pseudorandom, uniformly distributed
* {@code boolean} value from this random number generator's
* sequence. The general contract of {@code nextBoolean} is that one
* {@code boolean} value is pseudorandomly generated and returned. The
* values {@code true} and {@code false} are produced with
* (approximately) equal probability.
*
* <p>The method {@code nextBoolean} is implemented by class {@code Random}
* as if by:
* <pre> {@code
* public boolean nextBoolean() {
* return next(1) != 0;
* }}</pre>
*
* @return the next pseudorandom, uniformly distributed
* {@code boolean} value from this random number generator's
* sequence
*
* @since 1.2
*/
// 随机生成一个boolean值
public boolean nextBoolean() {
return next(1) != 0;
}
/**
* Returns the next pseudorandom, Gaussian ("normally") distributed
* {@code double} value with mean {@code 0.0} and standard
* deviation {@code 1.0} from this random number generator's sequence.
* <p>
* The general contract of {@code nextGaussian} is that one
* {@code double} value, chosen from (approximately) the usual
* normal distribution with mean {@code 0.0} and standard deviation
* {@code 1.0}, is pseudorandomly generated and returned.
*
* <p>The method {@code nextGaussian} is implemented by class
* {@code Random} as if by a threadsafe version of the following:
* <pre> {@code
* private double nextNextGaussian;
* private boolean haveNextNextGaussian = false;
*
* public double nextGaussian() {
* if (haveNextNextGaussian) {
* haveNextNextGaussian = false;
* return nextNextGaussian;
* } else {
* double v1, v2, s;
* do {
* v1 = 2 * nextDouble() - 1; // between -1.0 and 1.0
* v2 = 2 * nextDouble() - 1; // between -1.0 and 1.0
* s = v1 * v1 + v2 * v2;
* } while (s >= 1 || s == 0);
* double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s);
* nextNextGaussian = v2 * multiplier;
* haveNextNextGaussian = true;
* return v1 * multiplier;
* }
* }}</pre>
* This uses the <i>polar method</i> of G. E. P. Box, M. E. Muller, and
* G. Marsaglia, as described by Donald E. Knuth in <i>The Art of
* Computer Programming</i>, Volume 2: <i>Seminumerical Algorithms</i>,
* section 3.4.1, subsection C, algorithm P. Note that it generates two
* independent values at the cost of only one call to {@code StrictMath.log}
* and one call to {@code StrictMath.sqrt}.
*
* @return the next pseudorandom, Gaussian ("normally") distributed
* {@code double} value with mean {@code 0.0} and
* standard deviation {@code 1.0} from this random number
* generator's sequence
*/
// 随机生成一个double值,有正有负。所有生成的double值符合标准正态分布
public synchronized double nextGaussian() {
// See Knuth, ACP, Section 3.4.1 Algorithm C.
if(haveNextNextGaussian) {
haveNextNextGaussian = false;
return nextNextGaussian;
} else {
double v1, v2, s;
do {
v1 = 2 * nextDouble() - 1; // between -1 and 1
v2 = 2 * nextDouble() - 1; // between -1 and 1
s = v1 * v1 + v2 * v2;
} while(s >= 1 || s == 0);
double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s) / s);
nextNextGaussian = v2 * multiplier;
haveNextNextGaussian = true;
return v1 * multiplier;
}
}
/**
* Generates the next pseudorandom number. Subclasses should
* override this, as this is used by all other methods.
*
* <p>The general contract of {@code next} is that it returns an
* {@code int} value and if the argument {@code bits} is between
* {@code 1} and {@code 32} (inclusive), then that many low-order
* bits of the returned value will be (approximately) independently
* chosen bit values, each of which is (approximately) equally
* likely to be {@code 0} or {@code 1}. The method {@code next} is
* implemented by class {@code Random} by atomically updating the seed to
* <pre>{@code (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1)}</pre>
* and returning
* <pre>{@code (int)(seed >>> (48 - bits))}.</pre>
*
* This is a linear congruential pseudorandom number generator, as
* defined by D. H. Lehmer and described by Donald E. Knuth in
* <i>The Art of Computer Programming,</i> Volume 2:
* <i>Seminumerical Algorithms</i>, section 3.2.1.
*
* @param bits random bits
*
* @return the next pseudorandom value from this random number
* generator's sequence
*
* @since 1.1
*/
// 随机生成一个int值,该值范围是[0, 2^bits -1)
protected int next(int bits) {
long oldseed, nextseed;
AtomicLong seed = this.seed;
// 原子地更新原始种子,该种子取值范围是[0, mask]
do {
oldseed = seed.get();
nextseed = (oldseed * multiplier + addend) & mask;
} while(!seed.compareAndSet(oldseed, nextseed));
// 由原始种子计算出哈希值,此时的哈希值与之前的哈希值可能重复
return (int) (nextseed >>> (48 - bits));
}
/*▲ 生成伪随机数 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 流 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns an effectively unlimited stream of pseudorandom {@code int}
* values.
*
* <p>A pseudorandom {@code int} value is generated as if it's the result of
* calling the method {@link #nextInt()}.
*
* @return a stream of pseudorandom {@code int} values
*
* @implNote This method is implemented to be equivalent to {@code
* ints(Long.MAX_VALUE)}.
* @since 1.8
*/
// 返回的流可以生成Long.MAX_VALUE个随机int值
public IntStream ints() {
return StreamSupport.intStream(new RandomIntsSpliterator(this, 0L, Long.MAX_VALUE, Integer.MAX_VALUE, 0), false);
}
/**
* Returns a stream producing the given {@code streamSize} number of
* pseudorandom {@code int} values.
*
* <p>A pseudorandom {@code int} value is generated as if it's the result of
* calling the method {@link #nextInt()}.
*
* @param streamSize the number of values to generate
*
* @return a stream of pseudorandom {@code int} values
*
* @throws IllegalArgumentException if {@code streamSize} is
* less than zero
* @since 1.8
*/
// 返回的流可以生成streamSize个随机int值
public IntStream ints(long streamSize) {
if(streamSize<0L) {
throw new IllegalArgumentException(BadSize);
}
return StreamSupport.intStream(new RandomIntsSpliterator(this, 0L, streamSize, Integer.MAX_VALUE, 0), false);
}
/**
* Returns an effectively unlimited stream of pseudorandom {@code
* int} values, each conforming to the given origin (inclusive) and bound
* (exclusive).
*
* <p>A pseudorandom {@code int} value is generated as if it's the result of
* calling the following method with the origin and bound:
* <pre> {@code
* int nextInt(int origin, int bound) {
* int n = bound - origin;
* if (n > 0) {
* return nextInt(n) + origin;
* }
* else { // range not representable as int
* int r;
* do {
* r = nextInt();
* } while (r < origin || r >= bound);
* return r;
* }
* }}</pre>
*
* @param randomNumberOrigin the origin (inclusive) of each random value
* @param randomNumberBound the bound (exclusive) of each random value
*
* @return a stream of pseudorandom {@code int} values,
* each with the given origin (inclusive) and bound (exclusive)
*
* @throws IllegalArgumentException if {@code randomNumberOrigin}
* is greater than or equal to {@code randomNumberBound}
* @implNote This method is implemented to be equivalent to {@code
* ints(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
* @since 1.8
*/
// 返回的流可以生成Long.MAX_VALUE个随机int值,取值范围是[randomNumberOrigin, randomNumberBound)
public IntStream ints(int randomNumberOrigin, int randomNumberBound) {
if(randomNumberOrigin >= randomNumberBound) {
throw new IllegalArgumentException(BadRange);
}
return StreamSupport.intStream(new RandomIntsSpliterator(this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound), false);
}
/**
* Returns a stream producing the given {@code streamSize} number
* of pseudorandom {@code int} values, each conforming to the given
* origin (inclusive) and bound (exclusive).
*
* <p>A pseudorandom {@code int} value is generated as if it's the result of
* calling the following method with the origin and bound:
* <pre> {@code
* int nextInt(int origin, int bound) {
* int n = bound - origin;
* if (n > 0) {
* return nextInt(n) + origin;
* }
* else { // range not representable as int
* int r;
* do {
* r = nextInt();
* } while (r < origin || r >= bound);
* return r;
* }
* }}</pre>
*
* @param streamSize the number of values to generate
* @param randomNumberOrigin the origin (inclusive) of each random value
* @param randomNumberBound the bound (exclusive) of each random value
*
* @return a stream of pseudorandom {@code int} values,
* each with the given origin (inclusive) and bound (exclusive)
*
* @throws IllegalArgumentException if {@code streamSize} is
* less than zero, or {@code randomNumberOrigin}
* is greater than or equal to {@code randomNumberBound}
* @since 1.8
*/
// 返回的流可以生成streamSize个随机int值,取值范围是[randomNumberOrigin, randomNumberBound)
public IntStream ints(long streamSize, int randomNumberOrigin, int randomNumberBound) {
if(streamSize<0L) {
throw new IllegalArgumentException(BadSize);
}
if(randomNumberOrigin >= randomNumberBound) {
throw new IllegalArgumentException(BadRange);
}
return StreamSupport.intStream(new RandomIntsSpliterator(this, 0L, streamSize, randomNumberOrigin, randomNumberBound), false);
}
/**
* Returns an effectively unlimited stream of pseudorandom {@code long}
* values.
*
* <p>A pseudorandom {@code long} value is generated as if it's the result
* of calling the method {@link #nextLong()}.
*
* @return a stream of pseudorandom {@code long} values
*
* @implNote This method is implemented to be equivalent to {@code
* longs(Long.MAX_VALUE)}.
* @since 1.8
*/
// 返回的流可以生成Long.MAX_VALUE个随机long值
public LongStream longs() {
return StreamSupport.longStream(new RandomLongsSpliterator(this, 0L, Long.MAX_VALUE, Long.MAX_VALUE, 0L), false);
}
/**
* Returns a stream producing the given {@code streamSize} number of
* pseudorandom {@code long} values.
*
* <p>A pseudorandom {@code long} value is generated as if it's the result
* of calling the method {@link #nextLong()}.
*
* @param streamSize the number of values to generate
*
* @return a stream of pseudorandom {@code long} values
*
* @throws IllegalArgumentException if {@code streamSize} is
* less than zero
* @since 1.8
*/
// 返回的流可以生成streamSize个随机long值
public LongStream longs(long streamSize) {
if(streamSize<0L) {
throw new IllegalArgumentException(BadSize);
}
return StreamSupport.longStream(new RandomLongsSpliterator(this, 0L, streamSize, Long.MAX_VALUE, 0L), false);
}
/**
* Returns an effectively unlimited stream of pseudorandom {@code
* long} values, each conforming to the given origin (inclusive) and bound
* (exclusive).
*
* <p>A pseudorandom {@code long} value is generated as if it's the result
* of calling the following method with the origin and bound:
* <pre> {@code
* long nextLong(long origin, long bound) {
* long r = nextLong();
* long n = bound - origin, m = n - 1;
* if ((n & m) == 0L) // power of two
* r = (r & m) + origin;
* else if (n > 0L) { // reject over-represented candidates
* for (long u = r >>> 1; // ensure nonnegative
* u + m - (r = u % n) < 0L; // rejection check
* u = nextLong() >>> 1) // retry
* ;
* r += origin;
* }
* else { // range not representable as long
* while (r < origin || r >= bound)
* r = nextLong();
* }
* return r;
* }}</pre>
*
* @param randomNumberOrigin the origin (inclusive) of each random value
* @param randomNumberBound the bound (exclusive) of each random value
*
* @return a stream of pseudorandom {@code long} values,
* each with the given origin (inclusive) and bound (exclusive)
*
* @throws IllegalArgumentException if {@code randomNumberOrigin}
* is greater than or equal to {@code randomNumberBound}
* @implNote This method is implemented to be equivalent to {@code
* longs(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
* @since 1.8
*/
// 返回的流可以生成Long.MAX_VALUE个随机long值,取值范围是[randomNumberOrigin, randomNumberBound)
public LongStream longs(long randomNumberOrigin, long randomNumberBound) {
if(randomNumberOrigin >= randomNumberBound) {
throw new IllegalArgumentException(BadRange);
}
return StreamSupport.longStream(new RandomLongsSpliterator(this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound), false);
}
/**
* Returns a stream producing the given {@code streamSize} number of
* pseudorandom {@code long}, each conforming to the given origin
* (inclusive) and bound (exclusive).
*
* <p>A pseudorandom {@code long} value is generated as if it's the result
* of calling the following method with the origin and bound:
* <pre> {@code
* long nextLong(long origin, long bound) {
* long r = nextLong();
* long n = bound - origin, m = n - 1;
* if ((n & m) == 0L) // power of two
* r = (r & m) + origin;
* else if (n > 0L) { // reject over-represented candidates
* for (long u = r >>> 1; // ensure nonnegative
* u + m - (r = u % n) < 0L; // rejection check
* u = nextLong() >>> 1) // retry
* ;
* r += origin;
* }
* else { // range not representable as long
* while (r < origin || r >= bound)
* r = nextLong();
* }
* return r;
* }}</pre>
*
* @param streamSize the number of values to generate
* @param randomNumberOrigin the origin (inclusive) of each random value
* @param randomNumberBound the bound (exclusive) of each random value
*
* @return a stream of pseudorandom {@code long} values,
* each with the given origin (inclusive) and bound (exclusive)
*
* @throws IllegalArgumentException if {@code streamSize} is
* less than zero, or {@code randomNumberOrigin}
* is greater than or equal to {@code randomNumberBound}
* @since 1.8
*/
// 返回的流可以生成streamSize个随机long值,取值范围是[randomNumberOrigin, randomNumberBound)
public LongStream longs(long streamSize, long randomNumberOrigin, long randomNumberBound) {
if(streamSize<0L) {
throw new IllegalArgumentException(BadSize);
}
if(randomNumberOrigin >= randomNumberBound) {
throw new IllegalArgumentException(BadRange);
}
return StreamSupport.longStream(new RandomLongsSpliterator(this, 0L, streamSize, randomNumberOrigin, randomNumberBound), false);
}
/**
* Returns an effectively unlimited stream of pseudorandom {@code
* double} values, each between zero (inclusive) and one
* (exclusive).
*
* <p>A pseudorandom {@code double} value is generated as if it's the result
* of calling the method {@link #nextDouble()}.
*
* @return a stream of pseudorandom {@code double} values
*
* @implNote This method is implemented to be equivalent to {@code
* doubles(Long.MAX_VALUE)}.
* @since 1.8
*/
// 返回的流可以生成Long.MAX_VALUE个随机double值,取值范围是[0, 1)
public DoubleStream doubles() {
return StreamSupport.doubleStream(new RandomDoublesSpliterator(this, 0L, Long.MAX_VALUE, Double.MAX_VALUE, 0.0), false);
}
/**
* Returns a stream producing the given {@code streamSize} number of
* pseudorandom {@code double} values, each between zero
* (inclusive) and one (exclusive).
*
* <p>A pseudorandom {@code double} value is generated as if it's the result
* of calling the method {@link #nextDouble()}.
*
* @param streamSize the number of values to generate
*
* @return a stream of {@code double} values
*
* @throws IllegalArgumentException if {@code streamSize} is
* less than zero
* @since 1.8
*/
// 返回的流可以生成streamSize个随机double值,取值范围是[0, 1)
public DoubleStream doubles(long streamSize) {
if(streamSize<0L) {
throw new IllegalArgumentException(BadSize);
}
return StreamSupport.doubleStream(new RandomDoublesSpliterator(this, 0L, streamSize, Double.MAX_VALUE, 0.0), false);
}
/**
* Returns an effectively unlimited stream of pseudorandom {@code
* double} values, each conforming to the given origin (inclusive) and bound
* (exclusive).
*
* <p>A pseudorandom {@code double} value is generated as if it's the result
* of calling the following method with the origin and bound:
* <pre> {@code
* double nextDouble(double origin, double bound) {
* double r = nextDouble();
* r = r * (bound - origin) + origin;
* if (r >= bound) // correct for rounding
* r = Math.nextDown(bound);
* return r;
* }}</pre>
*
* @param randomNumberOrigin the origin (inclusive) of each random value
* @param randomNumberBound the bound (exclusive) of each random value
*
* @return a stream of pseudorandom {@code double} values,
* each with the given origin (inclusive) and bound (exclusive)
*
* @throws IllegalArgumentException if {@code randomNumberOrigin}
* is greater than or equal to {@code randomNumberBound}
* @implNote This method is implemented to be equivalent to {@code
* doubles(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
* @since 1.8
*/
// 返回的流可以生成Long.MAX_VALUE个随机double值,取值范围是[randomNumberOrigin, randomNumberBound)
public DoubleStream doubles(double randomNumberOrigin, double randomNumberBound) {
if(!(randomNumberOrigin<randomNumberBound)) {
throw new IllegalArgumentException(BadRange);
}
return StreamSupport.doubleStream(new RandomDoublesSpliterator(this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound), false);
}
/**
* Returns a stream producing the given {@code streamSize} number of
* pseudorandom {@code double} values, each conforming to the given origin
* (inclusive) and bound (exclusive).
*
* <p>A pseudorandom {@code double} value is generated as if it's the result
* of calling the following method with the origin and bound:
* <pre> {@code
* double nextDouble(double origin, double bound) {
* double r = nextDouble();
* r = r * (bound - origin) + origin;
* if (r >= bound) // correct for rounding
* r = Math.nextDown(bound);
* return r;
* }}</pre>
*
* @param streamSize the number of values to generate
* @param randomNumberOrigin the origin (inclusive) of each random value
* @param randomNumberBound the bound (exclusive) of each random value
*
* @return a stream of pseudorandom {@code double} values,
* each with the given origin (inclusive) and bound (exclusive)
*
* @throws IllegalArgumentException if {@code streamSize} is
* less than zero
* @throws IllegalArgumentException if {@code randomNumberOrigin}
* is greater than or equal to {@code randomNumberBound}
* @since 1.8
*/
// 返回的流可以生成streamSize个随机double值,取值范围是[randomNumberOrigin, randomNumberBound)
public DoubleStream doubles(long streamSize, double randomNumberOrigin, double randomNumberBound) {
if(streamSize<0L) {
throw new IllegalArgumentException(BadSize);
}
if(!(randomNumberOrigin<randomNumberBound)) {
throw new IllegalArgumentException(BadRange);
}
return StreamSupport.doubleStream(new RandomDoublesSpliterator(this, 0L, streamSize, randomNumberOrigin, randomNumberBound), false);
}
/*▲ 流 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 序列化 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Reconstitute the {@code Random} instance from a stream (that is,
* deserialize it).
*/
private void readObject(java.io.ObjectInputStream s) throws IOException, ClassNotFoundException {
ObjectInputStream.GetField fields = s.readFields();
// The seed is read in as {@code long} for historical reasons, but it is converted to an AtomicLong.
long seedVal = fields.get("seed", -1L);
if(seedVal<0)
throw new java.io.StreamCorruptedException("Random: invalid seed");
resetSeed(seedVal);
nextNextGaussian = fields.get("nextNextGaussian", 0.0);
haveNextNextGaussian = fields.get("haveNextNextGaussian", false);
}
/**
* Save the {@code Random} instance to a stream.
*/
private synchronized void writeObject(ObjectOutputStream s) throws IOException {
// set the values of the Serializable fields
ObjectOutputStream.PutField fields = s.putFields();
// The seed is serialized as a long for historical reasons.
fields.put("seed", seed.get());
fields.put("nextNextGaussian", nextNextGaussian);
fields.put("haveNextNextGaussian", haveNextNextGaussian);
// save them
s.writeFields();
}
/*▲ 序列化 ████████████████████████████████████████████████████████████████████████████████┛ */
/**
* The form of nextInt used by IntStream Spliterators.
* For the unbounded case: uses nextInt().
* For the bounded case with representable range: uses nextInt(int bound)
* For the bounded case with unrepresentable range: uses nextInt()
*
* @param origin the least value, unless greater than bound
* @param bound the upper bound (exclusive), must not equal origin
*
* @return a pseudorandom value
*/
// 随机生成一个[origin, bound)之内的int值
final int internalNextInt(int origin, int bound) {
if(origin<bound) {
int n = bound - origin;
if(n>0) {
return nextInt(n) + origin;
} else { // range not representable as int
int r;
do {
r = nextInt();
} while(r<origin || r >= bound);
return r;
}
} else {
return nextInt();
}
}
/**
* The form of nextLong used by LongStream Spliterators.
* If origin is greater than bound, acts as unbounded form of nextLong, else as bounded form.
*
* @param origin the least value, unless greater than bound
* @param bound the upper bound (exclusive), must not equal origin
*
* @return a pseudorandom value
*/
// 随机生成一个[origin, bound)之内的long值
final long internalNextLong(long origin, long bound) {
long r = nextLong();
if(origin<bound) {
long n = bound - origin, m = n - 1;
if((n & m) == 0L) // power of two
r = (r & m) + origin;
else if(n>0L) { // reject over-represented candidates
for(long u = r >>> 1; // ensure nonnegative
u + m - (r = u % n)<0L; // rejection check
u = nextLong() >>> 1) // retry
;
r += origin;
} else { // range not representable as long
while(r<origin || r >= bound)
r = nextLong();
}
}
return r;
}
/**
* The form of nextDouble used by DoubleStream Spliterators.
*
* @param origin the least value, unless greater than bound
* @param bound the upper bound (exclusive), must not equal origin
*
* @return a pseudorandom value
*/
// 随机生成一个[origin, bound)之内的double值
final double internalNextDouble(double origin, double bound) {
double r = nextDouble();
if(origin<bound) {
r = r * (bound - origin) + origin;
if(r >= bound) { // correct for rounding
r = Double.longBitsToDouble(Double.doubleToLongBits(bound) - 1);
}
}
return r;
}
/**
* Spliterator for int streams. We multiplex the four int
* versions into one class by treating a bound less than origin as
* unbounded, and also by treating "infinite" as equivalent to
* Long.MAX_VALUE. For splits, it uses the standard divide-by-two
* approach. The long and double versions of this class are
* identical except for types.
*/
// 可以随机生成int元素的流
static final class RandomIntsSpliterator implements Spliterator.OfInt {
final Random rng; // 随机数生成器
// 随机数数量:fence-index
long index;
final long fence;
// 随机数取值范围:[origin, bound)
final int origin;
final int bound;
RandomIntsSpliterator(Random rng, long index, long fence, int origin, int bound) {
this.rng = rng;
this.index = index;
this.fence = fence;
this.origin = origin;
this.bound = bound;
}
public RandomIntsSpliterator trySplit() {
long i = index, m = (i + fence) >>> 1;
return (m<=i) ? null : new RandomIntsSpliterator(rng, i, index = m, origin, bound);
}
public long estimateSize() {
return fence - index;
}
public int characteristics() {
return (Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.NONNULL | Spliterator.IMMUTABLE);
}
public boolean tryAdvance(IntConsumer consumer) {
if(consumer == null)
throw new NullPointerException();
long i = index, f = fence;
if(i<f) {
consumer.accept(rng.internalNextInt(origin, bound));
index = i + 1;
return true;
}
return false;
}
public void forEachRemaining(IntConsumer consumer) {
if(consumer == null)
throw new NullPointerException();
long i = index, f = fence;
if(i<f) {
index = f;
Random r = rng;
int o = origin, b = bound;
do {
consumer.accept(r.internalNextInt(o, b));
} while(++i<f);
}
}
}
/**
* Spliterator for long streams.
*/
// 可以随机生成long元素的流
static final class RandomLongsSpliterator implements Spliterator.OfLong {
final Random rng;
// 随机数数量:fence-index
long index;
final long fence;
// 随机数取值范围:[origin, bound)
final long origin;
final long bound;
RandomLongsSpliterator(Random rng, long index, long fence, long origin, long bound) {
this.rng = rng;
this.index = index;
this.fence = fence;
this.origin = origin;
this.bound = bound;
}
public RandomLongsSpliterator trySplit() {
long i = index, m = (i + fence) >>> 1;
return (m<=i) ? null : new RandomLongsSpliterator(rng, i, index = m, origin, bound);
}
public long estimateSize() {
return fence - index;
}
public int characteristics() {
return (Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.NONNULL | Spliterator.IMMUTABLE);
}
public boolean tryAdvance(LongConsumer consumer) {
if(consumer == null)
throw new NullPointerException();
long i = index, f = fence;
if(i<f) {
consumer.accept(rng.internalNextLong(origin, bound));
index = i + 1;
return true;
}
return false;
}
public void forEachRemaining(LongConsumer consumer) {
if(consumer == null)
throw new NullPointerException();
long i = index, f = fence;
if(i<f) {
index = f;
Random r = rng;
long o = origin, b = bound;
do {
consumer.accept(r.internalNextLong(o, b));
} while(++i<f);
}
}
}
/**
* Spliterator for double streams.
*/
// 可以随机生成double元素的流
static final class RandomDoublesSpliterator implements Spliterator.OfDouble {
final Random rng;
// 随机数数量:fence-index
long index;
final long fence;
// 随机数取值范围:[origin, bound)
final double origin;
final double bound;
RandomDoublesSpliterator(Random rng, long index, long fence, double origin, double bound) {
this.rng = rng;
this.index = index;
this.fence = fence;
this.origin = origin;
this.bound = bound;
}
public RandomDoublesSpliterator trySplit() {
long i = index, m = (i + fence) >>> 1;
return (m<=i) ? null : new RandomDoublesSpliterator(rng, i, index = m, origin, bound);
}
public long estimateSize() {
return fence - index;
}
public int characteristics() {
return (Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.NONNULL | Spliterator.IMMUTABLE);
}
public boolean tryAdvance(DoubleConsumer consumer) {
if(consumer == null)
throw new NullPointerException();
long i = index, f = fence;
if(i<f) {
consumer.accept(rng.internalNextDouble(origin, bound));
index = i + 1;
return true;
}
return false;
}
public void forEachRemaining(DoubleConsumer consumer) {
if(consumer == null)
throw new NullPointerException();
long i = index, f = fence;
if(i<f) {
index = f;
Random r = rng;
double o = origin, b = bound;
do {
consumer.accept(r.internalNextDouble(o, b));
} while(++i<f);
}
}
}
}
| kangjianwei/LearningJDK | src/java/util/Random.java |
65,063 | package DP.Interval_DP;
/**
* 最少给字符串刷上色的次数,获得目标字符串相应的颜色
* target = aa bb aa cdc aa
* 最少四次
* 1: aa aa aa aaa aa
* 2: aa bb aa aaa aa
* 3: aa bb aa ccc aa
* 4: aa bb aa cdc aa
* 因为我们上色的时候可以跨区间一次性上色,传统区间dp不适用。
* dp[l][r] 为考虑区间 [l, r] 上色的最少次数
* 观察 l 和 切分位置 i 一起转移的情况
*
* dp[l][r] = dp[l + 1][r] + 1 如果 l 单独上色
*
* if s[l] = s[i]: 如果l 可以和 切分位置 i 一起上色,包括右端点 r
* dp[l][r] = min{ dp[l][r], dp[l+1][i] + dp[i+1][r] } (i >= l+1 && i <= r) 可以包括 r, 即不分区)
*
* 举个例子
* a b a c a
*
* dp[1][5] = min{ dp[2][5] + 1, dp[2][3] + dp[4][5], dp[2][5] + dp[6][5](不存在)} = dp[2][5]
* dp[2][5] = dp[3][5] + 1
* dp[3][5] = min{ dp[4][5] + 1, dp[4][5] + dp[6][5](不存在)} = dp[4][5]
* dp[4][5] = dp[5][5] + 1
*/
public class StringPaint {
int maxn = 305;
int n;
char[] str = new char[maxn];
int[][] dp = new int[maxn][maxn];
public int paint(int n) {
this.n = n;
for (int i = 1; i <= n; i++) {
dp[i][i] = 1; // initialize
}
for (int len = 2; len <= n; len++) {
for (int i = 1, j = len; j <= n; i++, j++) {
int min = dp[i + 1][j] + 1; // paint it
for (int k = i + 1; k <= j; k++) {
if (str[i - 1] == str[k - 1]) {
min = Math.min(min, dp[i + 1][k] + (k + 1 <= j ? dp[k + 1][j] : 0));
}
}
dp[i][j] = min;
}
}
return dp[1][n];
}
/**
* 法2:
* dp[l][r] 为考虑区间 [l, r] 上色的最少次数
* 比较 区间两个端点的 颜色决定是否一起上色
* if s[l] == s[r]:
* dp[l][r] = min{ dp[l+1][r], dp[l][r-1] }
* else:
* dp[l][r] = min{ dp[l][k] + dp[k+1][r] for k in [l, r-1]}
*/
public int paint2(int n) {
this.n = n;
for (int i = 1; i <= n; i++) {
dp[i][i] = 1; // initialize
}
for (int len = 2; len <= n; len++) {
for (int i = 1, j = len; j <= n; i++, j++) {
if (str[i - 1] == str[j - 1]) {
dp[i][j] = Math.min(dp[i + 1][j], dp[i][j - 1]);
} else {
for (int k = i; k < j; k++) {
dp[i][j] = Math.min(dp[i][j], dp[i][k] + dp[k + 1][j]);
}
}
}
}
return dp[1][n];
}
}
| weiranfu/algorithms | DP/Interval_DP/StringPaint.java |
65,064 | package bytedance.array;
/**
* 数组与排序 - 接雨水
*
* 示例:
*
* 输入: [0,1,0,2,1,0,1,3,2,1,2,1]
* 输出: 6
*
* 题意: 求可容纳多少水
*
* 思路:
* 1. 观察
* I. 先找到最高点
* II. 在从左往右找,求值
* III.在从右往左找,求值
*/
public class Trap {
public int trap(int[] height) {
int result = 0;
int maxIndex = 0, max = 0;
for (int i = 0; i < height.length; ++i) {
if (max < height[i]) {
max = height[i];
maxIndex = i;
}
}
int currHeight = 0;
for (int i = 0; i < maxIndex; ++i) {
if (currHeight <= height[i]) currHeight = height[i];
else result += currHeight - height[i];
}
currHeight = 0;
for (int i = height.length - 1; i > maxIndex; --i) {
if (currHeight <= height[i]) currHeight = height[i];
else result += currHeight - height[i];
}
return result;
}
}
| DonaldY/LeetCode-Practice | src/main/java/bytedance/array/Trap.java |
65,066 | package question0367;
/**
* @author qianyihui
* @date 2019-07-12
*
* 观察规律:1,4,9,16,25,……
*
* 这些完全平方数的间隔分别为3,5,7,9,……
*
* 时间复杂度是(num ^ 0.5)。空间复杂度是O(1)。
*
* 执行用时:2ms,击败42.73%。消耗内存:33.3MB,击败11.05%。
*/
public class Solution2 {
public boolean isPerfectSquare(int num) {
int i = 1;
while (num > 0) {
num -= i;
i += 2;
}
return num == 0;
}
}
| 617076674/LeetCode | question0367/Solution2.java |
65,068 | package org.conan.myzk;
import java.io.IOException;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
/**
*
* 我的博客地址:http://blog.csdn.net/u010156024/article/details/50151029
*
*/
public class BasicDemo1 {
public static void main(String[] args)
throws IOException, KeeperException, InterruptedException {
/**
* 创建一个与服务器的连接
* 参数一:服务器地址和端口号(该端口号值服务器允许客户端连接的端口号,配置文件的默认端口号2181)
* 参数二:连接会话超时时间
* 参数三:观察者,连接成功会触发该观察者。不过只会触发一次。
* 该Watcher会获取各种事件的通知
*/
ZooKeeper zk = new ZooKeeper("centos:2181", 60000, new Watcher() {
// 监控所有被触发的事件
public void process(WatchedEvent event) {
System.out.println("监控所有被触发的事件:EVENT:" + event.getType());
}
});
System.out.println("*******************************************************");
// 查看根节点的子节点
System.out.println("查看根节点的子节点:ls / => " + zk.getChildren("/", true));
System.out.println("*******************************************************");
// 创建一个目录节点
if (zk.exists("/node", true) == null) {
/**
* 参数一:路径地址
* 参数二:想要保存的数据,需要转换成字节数组
* 参数三:ACL访问控制列表(Access control list),
* 参数类型为ArrayList<ACL>,Ids接口提供了一些默认的值可以调用。
* OPEN_ACL_UNSAFE This is a completely open ACL
* 这是一个完全开放的ACL,不安全
* CREATOR_ALL_ACL This ACL gives the
* creators authentication id's all permissions.
* 这个ACL赋予那些授权了的用户具备权限
* READ_ACL_UNSAFE This ACL gives the world the ability to read.
* 这个ACL赋予用户读的权限,也就是获取数据之类的权限。
* 参数四:创建的节点类型。枚举值CreateMode
* PERSISTENT (0, false, false)
* PERSISTENT_SEQUENTIAL (2, false, true)
* 这两个类型创建的都是持久型类型节点,回话结束之后不会自动删除。
* 区别在于,第二个类型所创建的节点名后会有一个单调递增的数值
* EPHEMERAL (1, true, false)
* EPHEMERAL_SEQUENTIAL (3, true, true)
* 这两个类型所创建的是临时型类型节点,在回话结束之后,自动删除。
* 区别在于,第二个类型所创建的临时型节点名后面会有一个单调递增的数值。
* 最后create()方法的返回值是创建的节点的实际路径
*/
zk.create("/node", "conan".getBytes(),
Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
System.out.println("创建一个目录节点:create /node conan");
/**
* 查看/node节点数据,这里应该输出"conan"
* 参数一:获取节点的路径
* 参数二:说明是否需要观察该节点,设置为true,则设定共享默认的观察器
* 参数三:stat类,保存节点的信息。例如数据版本信息,创建时间,修改时间等信息
*/
System.out.println("查看/node节点数据:get /node => "
+ new String(zk.getData("/node", false, null)));
/**
* 查看根节点
* 在此查看根节点的值,这里应该输出上面所创建的/node节点
*/
System.out.println("查看根节点:ls / => " + zk.getChildren("/", true));
}
System.out.println("*******************************************************");
// 创建一个子目录节点
if (zk.exists("/node/sub1", true) == null) {
zk.create("/node/sub1", "sub1".getBytes(),
Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
System.out.println("创建一个子目录节点:create /node/sub1 sub1");
// 查看node节点
System.out.println("查看node节点:ls /node => "
+ zk.getChildren("/node", true));
}
System.out.println("*******************************************************");
/**
* 修改节点数据
* 修改的数据会覆盖上次所设置的数据
* setData()方法参数一、参数二不多说,与上面类似。
* 参数三:数值型。需要传入该界面的数值类型版本号!!!
* 该信息可以通过Stat类获取,也可以通过命令行获取。
* 如果该值设置为-1,就是忽视版本匹配,直接设置节点保存的值。
*/
if (zk.exists("/node", true) != null) {
zk.setData("/node", "changed".getBytes(), -1);
// 查看/node节点数据
System.out.println("修改节点数据:get /node => "
+ new String(zk.getData("/node", false, null)));
}
System.out.println("*******************************************************");
// 删除节点
if (zk.exists("/node/sub1", true) != null) {
zk.delete("/node/sub1", -1);
zk.delete("/node", -1);
// 查看根节点
System.out.println("删除节点:ls / => " + zk.getChildren("/", true));
}
// 关闭连接
zk.close();
}
}
/**
15/12/02 19:14:04 INFO zookeeper.ZooKeeper: Client environment:zookeeper.version=3.4.5-1392090, built on 09/30/2012 17:52 GMT
15/12/02 19:14:04 INFO zookeeper.ZooKeeper: Client environment:host.name=husy
15/12/02 19:14:04 INFO zookeeper.ZooKeeper: Client environment:java.version=1.8.0_66
15/12/02 19:14:04 INFO zookeeper.ZooKeeper: Client environment:java.vendor=Oracle Corporation
15/12/02 19:14:04 INFO zookeeper.ZooKeeper: Client environment:java.home=D:\JRE8
15/12/02 19:14:04 INFO zookeeper.ZooKeeper: Client environment:java.class.path=D:\Program Files (x86)\ADT\workspace\webhadoop\bin;D:\BaiduYunDownload\hadoop-1.1.2\hadoop-ant-1.1.2.jar;D:\BaiduYunDownload\hadoop-1.1.2\hadoop-client-1.1.2.jar;D:\BaiduYunDownload\hadoop-1.1.2\hadoop-core-1.1.2.jar;D:\BaiduYunDownload\hadoop-1.1.2\hadoop-examples-1.1.2.jar;D:\BaiduYunDownload\hadoop-1.1.2\hadoop-minicluster-1.1.2.jar;D:\BaiduYunDownload\hadoop-1.1.2\hadoop-test-1.1.2.jar;D:\BaiduYunDownload\hadoop-1.1.2\hadoop-tools-1.1.2.jar;D:\BaiduYunDownload\zookeeper-3.4.5\zookeeper-3.4.5.jar;D:\BaiduYunDownload\hadoop-1.1.2\lib\commons-logging-1.1.1.jar;D:\BaiduYunDownload\ant.jar;D:\BaiduYunDownload\hadoop-1.1.2\lib\commons-configuration-1.6.jar;D:\BaiduYunDownload\hadoop-1.1.2\lib\commons-lang-2.4.jar;D:\BaiduYunDownload\hadoop-1.1.2\lib\jackson-mapper-asl-1.8.8.jar;D:\BaiduYunDownload\hadoop-1.1.2\lib\jackson-core-asl-1.8.8.jar;D:\BaiduYunDownload\hadoop-1.1.2\lib\jasper-compiler-5.5.12.jar;D:\BaiduYunDownload\hadoop-1.1.2\lib\jasper-runtime-5.5.12.jar;D:\BaiduYunDownload\hadoop-1.1.2\lib\commons-io-2.1.jar;D:\BaiduYunDownload\hadoop-1.1.2\lib\commons-httpclient-3.0.1.jar;D:\BaiduYunDownload\hadoop-1.1.2\lib\slf4j-log4j12-1.4.3.jar;D:\BaiduYunDownload\hadoop-1.1.2\lib\slf4j-api-1.4.3.jar;D:\BaiduYunDownload\hadoop-1.1.2\lib\log4j-1.2.15.jar
15/12/02 19:14:04 INFO zookeeper.ZooKeeper: Client environment:java.library.path=D:\JRE8\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;D:/JRE8/bin/server;D:/JRE8/bin;D:/JRE8/lib/amd64;D:\Python27\;D:\Python27\Scripts;C:\ProgramData\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;D:\JDK8\bin;D:\apache-ant-1.9.6\bin;D:\gradle-2.4\bin;D:\MySQL\mysql-5.6.19-winx64\bin;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;D:\GnuWin32\bin;D:\Program Files (x86)\apache-maven-3.3.9\bin;D:\Program Files (x86)\ADT\adt-bundle-windows-x86_64-20140702\eclipse;;.
15/12/02 19:14:04 INFO zookeeper.ZooKeeper: Client environment:java.io.tmpdir=C:\Users\15361\AppData\Local\Temp\
15/12/02 19:14:04 INFO zookeeper.ZooKeeper: Client environment:java.compiler=<NA>
15/12/02 19:14:04 INFO zookeeper.ZooKeeper: Client environment:os.name=Windows 10
15/12/02 19:14:04 INFO zookeeper.ZooKeeper: Client environment:os.arch=amd64
15/12/02 19:14:04 INFO zookeeper.ZooKeeper: Client environment:os.version=10.0
15/12/02 19:14:04 INFO zookeeper.ZooKeeper: Client environment:user.name=15361
15/12/02 19:14:04 INFO zookeeper.ZooKeeper: Client environment:user.home=C:\Users\15361
15/12/02 19:14:04 INFO zookeeper.ZooKeeper: Client environment:user.dir=D:\Program Files (x86)\ADT\workspace\webhadoop
15/12/02 19:14:04 INFO zookeeper.ZooKeeper: Initiating client connection, connectString=centos:2181 sessionTimeout=60000 watcher=org.conan.myzk.BasicDemo1$1@5c29bfd
*******************************************************
15/12/02 19:14:04 INFO zookeeper.ClientCnxn: Opening socket connection to server centos/192.168.56.100:2181. Will not attempt to authenticate using SASL (unknown error)
15/12/02 19:14:04 INFO zookeeper.ClientCnxn: Socket connection established to centos/192.168.56.100:2181, initiating session
15/12/02 19:14:04 INFO zookeeper.ClientCnxn: Session establishment complete on server centos/192.168.56.100:2181, sessionid = 0x51619ccb840001, negotiated timeout = 40000
监控所有被触发的事件:EVENT:None
查看根节点的子节点:ls / => [zookeeper]
*******************************************************
监控所有被触发的事件:EVENT:NodeCreated
监控所有被触发的事件:EVENT:NodeChildrenChanged
创建一个目录节点:create /node conan
查看/node节点数据:get /node => conan
查看根节点:ls / => [node, zookeeper]
*******************************************************
监控所有被触发的事件:EVENT:NodeCreated
创建一个子目录节点:create /node/sub1 sub1
查看node节点:ls /node => [sub1]
*******************************************************
监控所有被触发的事件:EVENT:NodeDataChanged
修改节点数据:get /node => changed
*******************************************************
监控所有被触发的事件:EVENT:NodeDeleted
监控所有被触发的事件:EVENT:NodeChildrenChanged
监控所有被触发的事件:EVENT:NodeChildrenChanged
删除节点:ls / => [zookeeper]
15/12/02 19:14:04 INFO zookeeper.ZooKeeper: Session: 0x51619ccb840001 closed
15/12/02 19:14:04 INFO zookeeper.ClientCnxn: EventThread shut down
*/ | longyinzaitian/HadoopDemo | src/org/conan/myzk/BasicDemo1.java |
65,069 | You are given an integer array values where values[i] represents the value of the ith sightseeing spot. Two sightseeing spots i and j have a distance j - i between them.
The score of a pair (i < j) of sightseeing spots is values[i] + values[j] + i - j: the sum of the values of the sightseeing spots, minus the distance between them.
Return the maximum score of a pair of sightseeing spots.
Example 1:
Input: values = [8,1,5,2,6]
Output: 11
Explanation: i = 0, j = 2, values[i] + values[j] + i - j = 8 + 5 + 0 - 2 = 11
Example 2:
Input: values = [1,2]
Output: 2
Constraints:
2 <= values.length <= 5 * 104
1 <= values[i] <= 1000
---------------------------------观察 ---------------------------------
/*
利用加法的分配律,可以得到 A[i] + i + A[j] - j,为了使这个表达式最大化,A[i] + i 自然是越大越好,
*/
class Solution {
public int maxScoreSightseeingPair(int[] values) {
int res = 0; int maxA = 0;
for (int j = 0; j < values.length; j++) {
res = Math.max(res, maxA + (values[j] - j));
maxA = Math.max(maxA, values[j] + j);
}
return res;
}
}
| riaing/leetcode | 1014. Best Sightseeing Pair.java |
65,070 | package class082;
// 买卖股票的最佳时机 III
// 给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。
// 设计一个算法来计算你所能获取的最大利润。你最多可以完成 两笔 交易
// 注意:你不能同时参与多笔交易,你必须在再次购买前出售掉之前的股票
// 测试链接 : https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-iii
public class Code03_Stock3 {
// 完全不优化枚举的方法
// 通过不了,会超时
public static int maxProfit1(int[] prices) {
int n = prices.length;
// dp1[i] : 0...i范围上发生一次交易,不要求在i的时刻卖出,最大利润是多少
int[] dp1 = new int[n];
for (int i = 1, min = prices[0]; i < n; i++) {
min = Math.min(min, prices[i]);
dp1[i] = Math.max(dp1[i - 1], prices[i] - min);
}
// dp2[i] : 0...i范围上发生两次交易,并且第二次交易在i时刻卖出,最大利润是多少
int[] dp2 = new int[n];
int ans = 0;
for (int i = 1; i < n; i++) {
// 第二次交易一定要在i时刻卖出
for (int j = 0; j <= i; j++) {
// 枚举第二次交易的买入时机j <= i
dp2[i] = Math.max(dp2[i], dp1[j] + prices[i] - prices[j]);
}
ans = Math.max(ans, dp2[i]);
}
return ans;
}
// 观察出优化枚举的方法
// 引入best数组,需要分析能力
public static int maxProfit2(int[] prices) {
int n = prices.length;
// dp1[i] : 0...i范围上发生一次交易,不要求在i的时刻卖出,最大利润是多少
int[] dp1 = new int[n];
for (int i = 1, min = prices[0]; i < n; i++) {
min = Math.min(min, prices[i]);
dp1[i] = Math.max(dp1[i - 1], prices[i] - min);
}
// best[i] : 0...i范围上,所有的dp1[i]-prices[i],最大值是多少
// 这是数组的设置完全是为了替代最后for循环的枚举行为
int[] best = new int[n];
best[0] = dp1[0] - prices[0];
for (int i = 1; i < n; i++) {
best[i] = Math.max(best[i - 1], dp1[i] - prices[i]);
}
// dp2[i] : 0...i范围上发生两次交易,并且第二次交易在i时刻卖出,最大利润是多少
int[] dp2 = new int[n];
int ans = 0;
for (int i = 1; i < n; i++) {
// 不需要枚举了
// 因为,best[i]已经揭示了,0...i范围上,所有的dp1[i]-prices[i],最大值是多少
dp2[i] = best[i] + prices[i];
ans = Math.max(ans, dp2[i]);
}
return ans;
}
// 发现所有更新行为都可以放在一起
// 并不需要写多个并列的for循环
// 就是等义改写,不需要分析能力
public static int maxProfit3(int[] prices) {
int n = prices.length;
int[] dp1 = new int[n];
int[] best = new int[n];
best[0] = -prices[0];
int[] dp2 = new int[n];
int ans = 0;
for (int i = 1, min = prices[0]; i < n; i++) {
min = Math.min(min, prices[i]);
dp1[i] = Math.max(dp1[i - 1], prices[i] - min);
best[i] = Math.max(best[i - 1], dp1[i] - prices[i]);
dp2[i] = best[i] + prices[i];
ans = Math.max(ans, dp2[i]);
}
return ans;
}
// 发现只需要有限几个变量滚动更新下去就可以了
// 空间压缩的版本
// 就是等义改写,不需要分析能力
public static int maxProfit4(int[] prices) {
int dp1 = 0;
int best = -prices[0];
int ans = 0;
for (int i = 1, min = prices[0]; i < prices.length; i++) {
min = Math.min(min, prices[i]);
dp1 = Math.max(dp1, prices[i] - min);
best = Math.max(best, dp1 - prices[i]);
ans = Math.max(ans, best + prices[i]); // ans = Math.max(ans, dp2);
}
return ans;
}
}
| algorithmzuo/algorithm-journey | src/class082/Code03_Stock3.java |
65,071 | /**
* 观察者接口
*/
public interface Observer {
public void update(float temp,float humidity,float pressure);
}
| jimersylee/DesignPattern | ch2-observer/Observer.java |
65,072 | package learn.freq01;
//The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
//
//P A H N
//A P L S I I G
//Y I R
//
//And then read line by line: "PAHNAPLSIIGYIR"
//
//Write the code that will take a string and make this conversion given a number of rows:
//
//string convert(string text, int nRows);
//
//convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".
/*输入是 123456789 3层
* 1 5 9
* 2 4 6 8 10
* 3 7 11
*
* 输出 1592468103711
*
*/
public class ZigZagConversion {
/*一个数学题 面试不太会考
* 直观的算法,写一下不同行数下的例子就能找到规律了。
nRows = 2
0 2 4 6 ... 一个zig可以认为是0 1 or 2 3
1 3 5 7
nRows = 3
0 4 8 ... 一个zig可以人认为 0123
1 3 5 7 9
2 6 10
nRows = 4
0 6 12 ... 一个zig可以认为是012345
1 5 7 11
2 4 8 10
3 9
*
* 观察可知 zigSize = nRows + nRows – 2
* 然后因为一共有1~n行
* 第一行就只放每个zig的第一个字符 最后一行也只放每个zag的
* 当中的那些行 (假设为i行) 那么第一个字符就是 每个zig的第i个字符
* 第二个在ir行的字符 在每个zig第一个字符在String里位置 +zigSize – 2*ir
*
*
*/
public String convert(String s, int nRows) {
int length = s.length();
if (length <= nRows || nRows == 1) {
return s;
}
char[] chars = new char[length];
int step = 2 * nRows - 2;
int count = 0;
for (int i = 0; i < nRows; i++) {
int interval = step - 2 * i;//这个interval指的是 在一个zig里 在1~n-1行里 同一行同一个zig里2个字母在string里的位置
// nRows = 3 eg 1和3的差距 就是step-2×i
// 0 4 8 ... 一个zig可以人认为 0123
// 1 3 5 7 9
// 2 6 10
//每次循环下一次都就是到下一个zip里了
//一次for循环是一个zip
for (int j = i; j < length; j = j + step) {
chars[count] = s.charAt(j); //eg 这里如果输入1
count++; //每次插入之后 count就++了
//如果大于step就不在本zig内了 //输入都在合法位置
if (interval < step && interval > 0 && j + interval < length && count < length) {
//count已经移到下一位
chars[count] = s.charAt(j + interval);//eg:这里就是输入3
count++;
}
}
}
return new String(chars);
}
}
| duoan/leetcode-java | src/learn/freq01/ZigZagConversion.java |
65,074 | package xdl.day12;
public class TestInteger {
public static void main(String[] args) {
//1.实现Integer类型的构造方法来构造对象
Integer it1 = new Integer(12345);
System.out.println("it1="+it1);
Integer it2 = new Integer(213123123);
System.out.println("it2="+it2);
//2.实现int类型向Integer类型的转换
//实现了从Integer类型到int类型的转换
int num = it1.intValue();
System.out.println("num="+num);
//实现了从int类型到Integer类型的转换
Integer it3 = Integer.valueOf(num);
System.out.println(it3);
//3.String类型向int类型转换
int res = Integer.parseInt("1234566");
System.out.println("res="+res);//结果是1234566,int类型
//4.观察自动装箱和自动拆箱
Integer it4 = 66; //自动装箱,完成int向Integer转换
res = it4; // Integer => int
}
}
| carolcoral/JavaLearn | JavaSE/Code/TestInteger.java |
65,075 | package com.lzb.zk;
import com.alibaba.fastjson.JSON;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
/**
* 主类<br/>
* Created on : 2021-06-17 22:02
*
* @author lizebin
*/
public class Main {
public static final String host = "192.168.56.100:%s";
public static void main(String[] args) throws Exception {
CountDownLatch latch = new CountDownLatch(1);
//zk是有seesion概念的,没有连接池的概念
//watch:观察、回调
//1.new zk时候,传入的watch是session级别的
ZooKeeper zooKeeper = new ZooKeeper(
String.format(host, "2181") + ","
+ String.format(host, "2182") + ","
+ String.format(host, "2183"), 3000, new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
System.out.println("---------------------");
System.out.println("watch callback event:" + JSON.toJSONString(watchedEvent));
System.out.println("---------------------");
if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
latch.countDown();
}
}
});
latch.await();
//异步连接
ZooKeeper.States state = zooKeeper.getState();
System.out.println(state.toString());
//4种类型的节点:持久、临时;顺序、无序
String pathName = zooKeeper.create("/user", "lizebin".getBytes(),
ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
System.out.println(pathName);
//stat放元数据
Stat stat = new Stat();
byte[] node = zooKeeper.getData("/user", new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
System.out.println("------updateNode------");
System.out.println(JSON.toJSONString(watchedEvent));
}
}, stat);
System.out.println("--------------node------------");
System.out.println(new String(node));
System.out.println("--------------stat------------");
System.out.println(JSON.toJSONString(stat));
System.out.println("update---------------->");
zooKeeper.setData("/user", "lizebin-1".getBytes(), 0);
Stat stat1 = new Stat();
byte[] node1 = zooKeeper.getData("/user", false, stat);
System.out.println("--------------node1------------");
System.out.println(new String(node1));
System.out.println("--------------stat1------------");
System.out.println(JSON.toJSONString(stat1));
}
}
| lizebin0918/test | src/main/java/com/lzb/zk/Main.java |
65,076 | import java.util.ArrayList;
import java.util.List;
abstract class Observer{
public abstract void update();
}
abstract class Subject {
private List<Observer> observers = new ArrayList<>();
public void attach(Observer observer){
this.observers.add(observer);
}
public void dettach(Observer observer){
this.observers.remove(observer);
}
public void Notify(){
for(Observer observer : observers) {
observer.update();
}
}
}
class ConcreteSubject extends Subject {
private String state;
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
class ConcreteObserver extends Observer {
private String name;
private String state;
private ConcreteSubject subject;
public ConcreteObserver(ConcreteSubject subject, String name){
this.subject = subject;
this.name = name;
}
@Override
public void update() {
state = subject.getState();
System.out.println("观察者 "+name+" 的状态时 "+state);
}
}
public class ObserverDemo {
public static void main(String[] args) {
ConcreteSubject s = new ConcreteSubject();
s.attach(new ConcreteObserver(s, "X"));
s.attach(new ConcreteObserver(s, "Y"));
s.attach(new ConcreteObserver(s, "Z"));
s.setState("111");
s.Notify();
}
}
| xinghalo/DesignPattern | 14-观察者模式/ObserverDemo.java |
65,077 | package offer;
/**
* @author:Sun Hongwei
* @2020/2/28 上午2:10
* File Description:0~n-1中缺失的数字: 一个长度为n-1的递增排序数组中的所有数字都是唯一的,
* 并且每个数字都在范围0~n-1之内。在范围0~n-1内的n个数字中有且只有一个数字不在该数组中,请找出这个数字。
*
*
* 二分查找,观察num[x]是否等于x,不等于的话,从右半边找,等于的话,从左半边找
*/
public class m53_2 {
public int missingNumber(int[] nums) {
int left=0,right=nums.length,mid;
while(left<right){
mid=left+(right-left)/2;
if(nums[mid]!=mid){
right=mid;
}else{
left=mid+1;
}
}
return left;
}
}
| sunhongwei815/my_leetcode_algorithm | offer/m53_2.java |
65,078 | package demo001_100;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author:Sun Hongwei
* @2020/2/13 下午4:54
* File Description:全排列 II:给定一个可包含重复数字的序列,返回所有不重复的全排列。
*
*
* 回溯+剪枝
* 由于有重复数字,先排序,再在回溯的过程中和前一个数比较,观察是否重复
*/
public class demo047 {
List<List<Integer>> results=new ArrayList<>();
public List<List<Integer>> permuteUnique(int[] nums) {
int[] visited=new int[nums.length];
Arrays.sort(nums); //排序后方便比较
trackback(nums,new ArrayList<Integer>(),visited);
return results;
}
public void trackback(int[] nums,ArrayList<Integer> temp,int[] visited){
if(temp.size()==nums.length){
results.add(new ArrayList<>(temp));
return;
}
for(int i=0;i<nums.length;i++){
//有重复数字的时候,多加一个判断条件作为剪枝处理:是否和前一个数相同(有序数列里)
if(visited[i]==1 || ( i>0 && nums[i]==nums[i-1] &&
visited[i-1]==0)){
//visited[i-1]==0说明和此数相同的那个数不在该排列里
continue;
}
visited[i]=1;
temp.add(nums[i]);
trackback(nums,temp,visited);
temp.remove(temp.size()-1);
visited[i]=0;
}
}
}
| sunhongwei815/my_leetcode_algorithm | demo001-100/demo047.java |
65,079 | package com.designPattern.observer;
/**
* 设计原则:
* 为交互对象之间的松耦合度而努力
*
* 观察者模式( 订阅者 + 发布者 ):
* 当交互对象之间存在一对多的依赖,一的一方状态一旦发生改变,多的一方即会收到通知,进行状态的更新
* 对应的即是:
* 主题(1)与观察者(n)
* 主题的作用是 注册、移除、通知观察者
* 观察者的作用是接收到特定主题的通知,进行状态或者数据的更新
*
* 根据数据在主题与观察者之间的传递方向,又可分为
* 推(push)--当发布者的状态发生变化时,将数据推送给观察者(订阅者)。发布者维护一个观察者列表
* 拉(pull)--当发布者的状态发生变化时,告知给观察者,由观察者自己来决定取什么数据。观察者维护一个发布者列表
*
*
* @author ysj
*
*/
public interface Subject { // 发布者
/**
* 注册观察者
* @param observer
*/
public void registerObserver(Observer obj);
/**
* 移除观察者
* @param observer
*/
public void removeObserver(Observer obj);
/**
* 通知观察者 拉的方式
*/
public void notifyObservers();
}
| yusijia/DesignPattern | 观察者模式/Subject.java |
65,080 | /*
观察者模式又称为发布-订阅模式,属于行为型设计模式的一种,是一个在项目中经常使用的模式。
定义:定义对象间一种一对多的依赖关系,每当一个对象改变状态时,则所有依赖于它的对象都会得到通知并被自动更新。
在观察者模式中有如下角色:
Subject:抽象主题(抽象被观察者)。抽象主题角色把所有观察者对象保存在一个集合里,每个主题都可以有任意数量的观察者。抽象主题提供一个接口,可以增加和删除观察者对象。
ConcreteSubject:具体主题(具体被观察者)。该角色将有关状态存入具体观察者对象,在具体主题的内部状态发生改变时,给所有注册过的观察者发送通知。
Observer:抽象观察者,是观察者的抽象类。它定义了一个更新接口,使得在得到主题更改通知时更新自己。
ConcreteObserver:具体观察者,实现抽象观察者定义的更新接口,以便在得到主题更改通知时更新自身的状态。
*/
/*
观察者模式的简单实现
关于观察者模式这种发布-订阅的形式,我们可以拿微信公众号来举例。假设微信用户就是观察者,微信公众号是被观察者,有多个微信用户关注了“程序猿”这个公众号,当这个公众号更新时就会通知这些订阅的微信用户。
接下来用代码实现:
*/
/*
抽象观察者
里面只定义了一个更新的方法:
*/
public interface Observer {
public void update(String message);
}
/*
具体观察者
微信用户是观察者,里面实现了更新的方法,如下所示:
*/
public class WeixinUser implements Observer {
// 微信用户名
private String name;
public WeixinUser(String name) {
this.name = name;
}
@Override
public void update(String message) {
System.out.println(name + "-" + message);
}
}
/*
抽象被观察者
抽象被观察者,提供了attach、detach、notify三个方法,如下所示:
*/
public interface Subject {
/**
* 增加订阅者
* @param observer
*/
public void attach(Observer observer);
/**
* 删除订阅者
* @param observer
*/
public void detach(Observer observer);
/**
* 通知订阅者更新消息
*/
public void notify(String message);
}
/*
具体被观察者
微信公众号是具体主题(具体被观察者),里面存储了订阅该公众号的微信用户,并实现了抽象主题中的方法:
*/
public class SubscriptionSubject implements Subject {
// 存储订阅公众号的微信用户
private List<Observer> WeixinUserlist = new ArrayList<Observer>();
@Override
public void attach(Observer observer) {
weixinUserlist.add(observer);
}
@Override
public void detach(Observer observer) {
weixinUserlist.remove(observer);
}
@Override
public void notify(String message) {
for (Observer observer : weixinUserlist) {
observer.update(message);
}
}
}
// 客户端调用
public class Client {
public static void main(String[] args) {
SubscriptionSubject mSubjectriptionSubject = new mSubjectriptionSubject();
// 创建微信用户
WeixinUser user1 = new WeixinUser("杨影枫");
WeixinUser user2 = new WeixinUser("月眉儿");
WeixinUser user3 = new WeixinUser("紫轩");
// 订阅公众号
mSubjectriptionSubject.attach(user1);
mSubjectriptionSubject.attach(user2);
mSubjectriptionSubject.attach(user3);
// 公众号更新发出消息给订阅的微信用户
mSubjectriptionSubject.notify("刘望舒的专栏更新了");
}
}
/*
观察者模式的使用场景和优缺点
使用场景:
关联行为场景。需要注意的是,关联行为是可拆分的,而不是“组合”关系。
事件多级触发场景。
跨系统的消息交换场景,如消息队列、事件总线的处理机制。
优点:
观察者和被观察则和之间是抽象耦合,容易扩展。
方便建立一套触发机制。
缺点:
在应用观察者模式时需要考虑一下开发效率和运行效率的问题。
程序中包括一个被观察者。多个观察者,开发、调试等内容会比较复杂,
而且在Java中消息的通知一般是顺序执行的,那么一个观察者卡顿,会影响整体的执行效率,在这种情况下,
一般会采用异步方式。
*/ | qiaopeichen/MyAndroidAdvanced | 设计模式/观察者模式.java |
65,081 | package observer;
//场景类
public class Client {
public static void main(String[] args) {
//被观察者
ConcreteSubject subject = new ConcreteSubject();
//观察者
Observer observer = new ConcreteObserver("aaa");
Observer observer2 = new ConcreteObserver("bbb");
//开始观察
subject.addObserver(observer);
subject.addObserver(observer2);
//开始报告
subject.method();
}
}
| Jdroida/free_learning | src/observer/Client.java |