file_id
stringlengths
5
8
content
stringlengths
131
14.4k
repo
stringlengths
9
59
path
stringlengths
8
120
token_length
int64
53
3.49k
original_comment
stringlengths
5
791
comment_type
stringclasses
2 values
detected_lang
stringclasses
1 value
masked_comment
stringlengths
135
14.3k
excluded
float64
0
0
file-tokens-Qwen/Qwen2-7B
int64
40
3.27k
comment-tokens-Qwen/Qwen2-7B
int64
2
459
file-tokens-bigcode/starcoder2-7b
int64
53
3.49k
comment-tokens-bigcode/starcoder2-7b
int64
3
483
file-tokens-google/codegemma-7b
int64
49
3.61k
comment-tokens-google/codegemma-7b
int64
3
465
file-tokens-ibm-granite/granite-8b-code-base
int64
53
3.49k
comment-tokens-ibm-granite/granite-8b-code-base
int64
3
483
file-tokens-meta-llama/CodeLlama-7b-hf
int64
68
4.13k
comment-tokens-meta-llama/CodeLlama-7b-hf
int64
4
592
excluded-based-on-tokenizer-Qwen/Qwen2-7B
bool
2 classes
excluded-based-on-tokenizer-bigcode/starcoder2-7b
bool
2 classes
excluded-based-on-tokenizer-google/codegemma-7b
bool
2 classes
excluded-based-on-tokenizer-ibm-granite/granite-8b-code-base
bool
2 classes
excluded-based-on-tokenizer-meta-llama/CodeLlama-7b-hf
bool
2 classes
include-for-inference
bool
2 classes
56954_1
package View; import Configure.ViewConfigure; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; /** * @author dmrfcoder * @date 2019-04-17 */ public class SwichButton extends JLabel { //0代表开始/绿色(停止中),1代表结束/红色(运行中) private int curState; private int D; interface StateChangeListener { void changeToRunning(); void changeToStop(); } private StateChangeListener stateChangeListener; public void setStateChangeListener(StateChangeListener stateChangeListener) { this.stateChangeListener = stateChangeListener; } public SwichButton(int D) { curState = 0; this.D = D; initListener(); } private void initListener() { addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent e) { if (curState == 0) { curState = 1; stateChangeListener.changeToRunning(); } else { curState = 0; stateChangeListener.changeToStop(); } repaint(); } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } }); } @Override public void paint(Graphics g) { super.paint(g); if (curState == 0) { g.setColor(ViewConfigure.defaultTextColor); } else { g.setColor(Color.red); } g.fillOval((getWidth() - D) / 2, (getHeight() - D) / 2, D, D); String text = ""; g.setColor(Color.BLACK); if (curState == 0) { text = "开始"; } else { text = "结束"; } g.drawString(text, (getWidth() - 25) / 2, 5 + getHeight() / 2); } }
DmrfCoder/SimulationRouter
src/View/SwichButton.java
524
//0代表开始/绿色(停止中),1代表结束/红色(运行中)
line_comment
zh-cn
package View; import Configure.ViewConfigure; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; /** * @author dmrfcoder * @date 2019-04-17 */ public class SwichButton extends JLabel { //0代 <SUF> private int curState; private int D; interface StateChangeListener { void changeToRunning(); void changeToStop(); } private StateChangeListener stateChangeListener; public void setStateChangeListener(StateChangeListener stateChangeListener) { this.stateChangeListener = stateChangeListener; } public SwichButton(int D) { curState = 0; this.D = D; initListener(); } private void initListener() { addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent e) { if (curState == 0) { curState = 1; stateChangeListener.changeToRunning(); } else { curState = 0; stateChangeListener.changeToStop(); } repaint(); } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } }); } @Override public void paint(Graphics g) { super.paint(g); if (curState == 0) { g.setColor(ViewConfigure.defaultTextColor); } else { g.setColor(Color.red); } g.fillOval((getWidth() - D) / 2, (getHeight() - D) / 2, D, D); String text = ""; g.setColor(Color.BLACK); if (curState == 0) { text = "开始"; } else { text = "结束"; } g.drawString(text, (getWidth() - 25) / 2, 5 + getHeight() / 2); } }
0
463
19
524
22
569
19
524
22
669
34
false
false
false
false
false
true
56936_1
package game; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; public class GameFrame extends JFrame implements ActionListener{ static boolean judge = true; static String name; public GameFrame() { setSize(288, 512);//设置窗口大小(288,512); setLocationRelativeTo(null);//窗口位于电脑的正中间; setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭按键 setResizable(false); setTitle("Flappy Bird终极豪华版"); init(); } public static void main(String[] args){ GameFrame frame = new GameFrame(); GamePanel panel = new GamePanel(); frame.add(panel);//添加到界面 frame.setVisible(true); } public void actionPerformed(ActionEvent e) {} void init() { JMenuBar menubar = new JMenuBar(); JMenu menu = new JMenu("菜单"); JMenu birdcolor = new JMenu("小鸟颜色"); JMenu bgcolor = new JMenu("背景主题"); JMenu column = new JMenu("柱子颜色"); menubar.add(menu); JMenuItem itembc1 = new JMenuItem("黄色"); JMenuItem itembc2 = new JMenuItem("蓝色"); JMenuItem itembc3 = new JMenuItem("红色"); menu.add(birdcolor); birdcolor.add(itembc1); birdcolor.add(itembc2); birdcolor.add(itembc3); JMenuItem itembg1 = new JMenuItem("白天"); JMenuItem itembg2 = new JMenuItem("黑夜"); menu.add(bgcolor); bgcolor.add(itembg1); bgcolor.add(itembg2); JMenuItem itemc1 = new JMenuItem("绿色"); JMenuItem itemc2 = new JMenuItem("橙色"); menu.add(column); column.add(itemc1); column.add(itemc2); setJMenuBar(menubar); itembc1.addActionListener(this); itembc2.addActionListener(this); itembc3.addActionListener(this); itembg1.addActionListener(this); itembg2.addActionListener(this); itemc1.addActionListener(this); itemc2.addActionListener(this); itembc1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Bird.i = 0; } }); itembc2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Bird.i = 1; } }); itembc3.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Bird.i = 2; } }); itemc1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Column.j = 0; } }); itemc2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Column.j = 1; } }); itembg1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { GamePanel.j = 1; } }); itembg2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { GamePanel.j = 0; } }); } }
DmuFreeCoding/DMU-cs-course
Java/MrLeea/src/game/GameFrame.java
884
//窗口位于电脑的正中间;
line_comment
zh-cn
package game; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; public class GameFrame extends JFrame implements ActionListener{ static boolean judge = true; static String name; public GameFrame() { setSize(288, 512);//设置窗口大小(288,512); setLocationRelativeTo(null);//窗口 <SUF> setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭按键 setResizable(false); setTitle("Flappy Bird终极豪华版"); init(); } public static void main(String[] args){ GameFrame frame = new GameFrame(); GamePanel panel = new GamePanel(); frame.add(panel);//添加到界面 frame.setVisible(true); } public void actionPerformed(ActionEvent e) {} void init() { JMenuBar menubar = new JMenuBar(); JMenu menu = new JMenu("菜单"); JMenu birdcolor = new JMenu("小鸟颜色"); JMenu bgcolor = new JMenu("背景主题"); JMenu column = new JMenu("柱子颜色"); menubar.add(menu); JMenuItem itembc1 = new JMenuItem("黄色"); JMenuItem itembc2 = new JMenuItem("蓝色"); JMenuItem itembc3 = new JMenuItem("红色"); menu.add(birdcolor); birdcolor.add(itembc1); birdcolor.add(itembc2); birdcolor.add(itembc3); JMenuItem itembg1 = new JMenuItem("白天"); JMenuItem itembg2 = new JMenuItem("黑夜"); menu.add(bgcolor); bgcolor.add(itembg1); bgcolor.add(itembg2); JMenuItem itemc1 = new JMenuItem("绿色"); JMenuItem itemc2 = new JMenuItem("橙色"); menu.add(column); column.add(itemc1); column.add(itemc2); setJMenuBar(menubar); itembc1.addActionListener(this); itembc2.addActionListener(this); itembc3.addActionListener(this); itembg1.addActionListener(this); itembg2.addActionListener(this); itemc1.addActionListener(this); itemc2.addActionListener(this); itembc1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Bird.i = 0; } }); itembc2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Bird.i = 1; } }); itembc3.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Bird.i = 2; } }); itemc1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Column.j = 0; } }); itemc2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Column.j = 1; } }); itembg1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { GamePanel.j = 1; } }); itembg2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { GamePanel.j = 0; } }); } }
0
688
8
884
10
843
8
884
10
1,132
16
false
false
false
false
false
true
45653_7
package com.dnake.panel; import com.dnake.misc.SysTalk; import com.dnake.misc.sCaller; import com.dnake.misc.Sound; import com.dnake.v700.dmsg; import com.dnake.v700.dxml; import com.dnake.v700.sys; import android.annotation.SuppressLint; import android.content.Intent; import android.media.MediaPlayer; import android.media.MediaPlayer.OnCompletionListener; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.view.WindowManager; import android.widget.TextView; @SuppressLint({ "DefaultLocale", "SetJavaScriptEnabled", "NewApi" }) public class TalkLabel extends BaseLabel { public static Intent mIntent = null; public static TalkLabel mContext = null; public static int build = 0; public static int unit = 0; public static int id; public static int OUT = 0; public static int IN = 1; public static int mMode = 0; // 0:呼出, 1:呼入 private MediaPlayer mPlayer = null; private TextView mText; private long mAutoTs = 0; private long mEndTs = 0; private String mPstnDtmf = null; // 语音网关拨号DTMF @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.talk); this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); int ui_visibility = this.getWindow().getDecorView().getSystemUiVisibility(); if ((ui_visibility & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0) { this.getWindow().getDecorView().setSystemUiVisibility(ui_visibility | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); } mContext = this; mPeriod = 300; mText = (TextView) this.findViewById(R.id.prompt_text); if (mMode == OUT) { mText.setText(R.string.sCaller_call); } else if (mMode == IN) { mText.setText(R.string.sCaller_monitor); } } @Override public void onStart() { super.onStart(); mContext = this; this.onStart2(); } public void onStart2() { sCaller.refresh(); if (mMode == OUT) { String s; if (id == 0) { // 呼叫管理机,使用固定ID id = 10001; s = "10001"; } else { s = String.format("%d%02d%04d", build, unit, id); } sCaller.query(s); OnCompletionListener listener = new OnCompletionListener() { public void onCompletion(MediaPlayer p) { p.stop(); p.reset(); p.release(); mPlayer = null; } }; mPlayer = Sound.play(Sound.ringback, true, listener); } else { mAutoTs = System.currentTimeMillis(); } } @Override public void onStop() { super.onStop(); if (sCaller.running != sCaller.NONE) this.stop(true); mIntent = null; mAutoTs = 0; mContext = null; } @Override public void onTimer() { super.onTimer(); WakeTask.acquire(); int ui_visibility = this.getWindow().getDecorView().getSystemUiVisibility(); if ((ui_visibility & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0) { this.getWindow().getDecorView().setSystemUiVisibility(ui_visibility | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); } if (mMode == OUT) {// 呼叫 if (sCaller.running == sCaller.QUERY) { if (sys.qResult.sip.url != null) { sCaller.start(sys.qResult.sip.url); sCaller.logger(sCaller.logger.CALL); sys.qResult.sip.url = null; } else if (sys.qResult.d600.ip != null) { System.out.println("ip: " + sys.qResult.d600.ip); sCaller.s600(sys.qResult.d600.host, sys.qResult.d600.ip); } else if (sCaller.timeout() >= sCaller.Time.QUERY) this.forward(); } else if (sCaller.running == sCaller.CALL) { if (sCaller.timeout() >= sCaller.Time.CALL || sys.qResult.result >= 400) this.forward(); } else if (sCaller.running == sCaller.RINGING) { // 有转呼25秒超时,其他按系统设置 int timeout = sys.panel.ringing * 1000; if (sCaller.timeout() >= timeout) { // 振铃超时 if (!this.forward()) { // 转呼失败 mText.setText(R.string.sCaller_no_answer); } } } else if (sCaller.running == sCaller.TALK) { if (sCaller.timeout() >= sys.talk.timeout * 1000) {// 对讲结束 mText.setText(R.string.sCaller_finish); this.stop(true); } if (mPstnDtmf != null && sCaller.timeout() > 1000) { char d = mPstnDtmf.charAt(0); mPstnDtmf = mPstnDtmf.substring(1); if (mPstnDtmf.length() <= 0) mPstnDtmf = null; dxml p = new dxml(); dmsg req = new dmsg(); p.setText("/params/dtmf", String.valueOf(d)); req.to("/talk/send_dtmf", p.toString()); } } } else if (mMode == IN) {// 监视 if (mAutoTs != 0 && Math.abs(System.currentTimeMillis() - mAutoTs) > 500) { mAutoTs = 0; sCaller.running = sCaller.TALK; dmsg req = new dmsg(); req.to("/talk/start", null); } if (sCaller.timeout() >= sCaller.Time.MONITOR) {// 监视超时 this.stop(true); if (!this.isFinishing()) this.finish(); } } if (mEndTs != 0) { if (Math.abs(System.currentTimeMillis() - mEndTs) >= 1000) { if (!this.isFinishing()) this.finish(); mEndTs = 0; } } else { if (sCaller.bStop) { // 挂断 this.stop(true); mText.setText(R.string.sCaller_finish); } } } @Override public void onKey(String key) { super.onKey(key); if (key.charAt(0) == '*' || key.charAt(0) == 'X') { if (!this.isFinishing()) { this.finish(); this.stop(true); } } } private Boolean forward() { mText.setText(R.string.sCaller_call_err); Sound.play(Sound.call_err, false); this.stop(true); return false; } public void play() { if (mPlayer != null) { Sound.stop(mPlayer); mPlayer = null; } mText.setText(R.string.sCaller_talk); sCaller.logger(sCaller.logger.ANSWER); } public void stop(Boolean mode) { if (mMode == OUT) { if (sCaller.running == sCaller.RINGING) sCaller.logger(sCaller.logger.FAILED); else if (sCaller.running == sCaller.TALK) sCaller.logger(sCaller.logger.END); } dmsg req = new dmsg(); req.to("/talk/stop", null); sCaller.reset(); if (mode) { if (mPlayer != null) { Sound.stop(mPlayer); mPlayer = null; } mEndTs = System.currentTimeMillis(); } else { mEndTs = 0; } } public static void start(int b, int u, int r) { build = b; unit = u; id = r; mMode = OUT; SysTalk.start(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) return true; return super.onKeyDown(keyCode, event); } }
DnakeFace/Face
ui/talk/src/com/dnake/panel/TalkLabel.java
2,408
// 对讲结束
line_comment
zh-cn
package com.dnake.panel; import com.dnake.misc.SysTalk; import com.dnake.misc.sCaller; import com.dnake.misc.Sound; import com.dnake.v700.dmsg; import com.dnake.v700.dxml; import com.dnake.v700.sys; import android.annotation.SuppressLint; import android.content.Intent; import android.media.MediaPlayer; import android.media.MediaPlayer.OnCompletionListener; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.view.WindowManager; import android.widget.TextView; @SuppressLint({ "DefaultLocale", "SetJavaScriptEnabled", "NewApi" }) public class TalkLabel extends BaseLabel { public static Intent mIntent = null; public static TalkLabel mContext = null; public static int build = 0; public static int unit = 0; public static int id; public static int OUT = 0; public static int IN = 1; public static int mMode = 0; // 0:呼出, 1:呼入 private MediaPlayer mPlayer = null; private TextView mText; private long mAutoTs = 0; private long mEndTs = 0; private String mPstnDtmf = null; // 语音网关拨号DTMF @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.talk); this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); int ui_visibility = this.getWindow().getDecorView().getSystemUiVisibility(); if ((ui_visibility & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0) { this.getWindow().getDecorView().setSystemUiVisibility(ui_visibility | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); } mContext = this; mPeriod = 300; mText = (TextView) this.findViewById(R.id.prompt_text); if (mMode == OUT) { mText.setText(R.string.sCaller_call); } else if (mMode == IN) { mText.setText(R.string.sCaller_monitor); } } @Override public void onStart() { super.onStart(); mContext = this; this.onStart2(); } public void onStart2() { sCaller.refresh(); if (mMode == OUT) { String s; if (id == 0) { // 呼叫管理机,使用固定ID id = 10001; s = "10001"; } else { s = String.format("%d%02d%04d", build, unit, id); } sCaller.query(s); OnCompletionListener listener = new OnCompletionListener() { public void onCompletion(MediaPlayer p) { p.stop(); p.reset(); p.release(); mPlayer = null; } }; mPlayer = Sound.play(Sound.ringback, true, listener); } else { mAutoTs = System.currentTimeMillis(); } } @Override public void onStop() { super.onStop(); if (sCaller.running != sCaller.NONE) this.stop(true); mIntent = null; mAutoTs = 0; mContext = null; } @Override public void onTimer() { super.onTimer(); WakeTask.acquire(); int ui_visibility = this.getWindow().getDecorView().getSystemUiVisibility(); if ((ui_visibility & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0) { this.getWindow().getDecorView().setSystemUiVisibility(ui_visibility | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); } if (mMode == OUT) {// 呼叫 if (sCaller.running == sCaller.QUERY) { if (sys.qResult.sip.url != null) { sCaller.start(sys.qResult.sip.url); sCaller.logger(sCaller.logger.CALL); sys.qResult.sip.url = null; } else if (sys.qResult.d600.ip != null) { System.out.println("ip: " + sys.qResult.d600.ip); sCaller.s600(sys.qResult.d600.host, sys.qResult.d600.ip); } else if (sCaller.timeout() >= sCaller.Time.QUERY) this.forward(); } else if (sCaller.running == sCaller.CALL) { if (sCaller.timeout() >= sCaller.Time.CALL || sys.qResult.result >= 400) this.forward(); } else if (sCaller.running == sCaller.RINGING) { // 有转呼25秒超时,其他按系统设置 int timeout = sys.panel.ringing * 1000; if (sCaller.timeout() >= timeout) { // 振铃超时 if (!this.forward()) { // 转呼失败 mText.setText(R.string.sCaller_no_answer); } } } else if (sCaller.running == sCaller.TALK) { if (sCaller.timeout() >= sys.talk.timeout * 1000) {// 对讲 <SUF> mText.setText(R.string.sCaller_finish); this.stop(true); } if (mPstnDtmf != null && sCaller.timeout() > 1000) { char d = mPstnDtmf.charAt(0); mPstnDtmf = mPstnDtmf.substring(1); if (mPstnDtmf.length() <= 0) mPstnDtmf = null; dxml p = new dxml(); dmsg req = new dmsg(); p.setText("/params/dtmf", String.valueOf(d)); req.to("/talk/send_dtmf", p.toString()); } } } else if (mMode == IN) {// 监视 if (mAutoTs != 0 && Math.abs(System.currentTimeMillis() - mAutoTs) > 500) { mAutoTs = 0; sCaller.running = sCaller.TALK; dmsg req = new dmsg(); req.to("/talk/start", null); } if (sCaller.timeout() >= sCaller.Time.MONITOR) {// 监视超时 this.stop(true); if (!this.isFinishing()) this.finish(); } } if (mEndTs != 0) { if (Math.abs(System.currentTimeMillis() - mEndTs) >= 1000) { if (!this.isFinishing()) this.finish(); mEndTs = 0; } } else { if (sCaller.bStop) { // 挂断 this.stop(true); mText.setText(R.string.sCaller_finish); } } } @Override public void onKey(String key) { super.onKey(key); if (key.charAt(0) == '*' || key.charAt(0) == 'X') { if (!this.isFinishing()) { this.finish(); this.stop(true); } } } private Boolean forward() { mText.setText(R.string.sCaller_call_err); Sound.play(Sound.call_err, false); this.stop(true); return false; } public void play() { if (mPlayer != null) { Sound.stop(mPlayer); mPlayer = null; } mText.setText(R.string.sCaller_talk); sCaller.logger(sCaller.logger.ANSWER); } public void stop(Boolean mode) { if (mMode == OUT) { if (sCaller.running == sCaller.RINGING) sCaller.logger(sCaller.logger.FAILED); else if (sCaller.running == sCaller.TALK) sCaller.logger(sCaller.logger.END); } dmsg req = new dmsg(); req.to("/talk/stop", null); sCaller.reset(); if (mode) { if (mPlayer != null) { Sound.stop(mPlayer); mPlayer = null; } mEndTs = System.currentTimeMillis(); } else { mEndTs = 0; } } public static void start(int b, int u, int r) { build = b; unit = u; id = r; mMode = OUT; SysTalk.start(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) return true; return super.onKeyDown(keyCode, event); } }
0
1,925
5
2,393
5
2,344
5
2,393
5
3,012
11
false
false
false
false
false
true
53010_2
package com.randian.win.model; import java.io.Serializable; import java.util.List; /** * Created by lily on 15-6-24. */ public class Coach implements Serializable { private int id; private int level;//等级 1:中级 2:高级 3:特级 4:专家 private int distance; private int order_num; private int comment_num; private int reputation_num; private float score; private float coach_price; private String sex; private String name; private String city; private String location; private String verified; private String created_at; private String updated_at; private String description; private String hours_class; private String available_areas; private String profile_image_url; private String positive_reputation; private String categoriesStr; private List<Sport> sports;//教练对应的课程列表 private List<Category> categories; //category的结构 [{"name":"瑜伽"},{"name":"健身"}] public class Category implements Serializable{ private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } public List<Category> getCategoriesList() { return categories; } public void setCategoriesList(List<Category> categories) { this.categories = categories; } public String getCategories() { return categoriesStr; } public void setCategories(String categoriesStr) { this.categoriesStr = categoriesStr; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getOrder_num() { return order_num; } public void setOrder_num(int order_num) { this.order_num = order_num; } public int getDistance() { return distance; } public void setDistance(int distance) { this.distance = distance; } public int getReputation_num() { return reputation_num; } public void setReputation_num(int reputation_num) { this.reputation_num = reputation_num; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getPositive_reputation() { return positive_reputation; } public void setPositive_reputation(String positive_reputation) { this.positive_reputation = positive_reputation; } public String getProfile_image_url() { return profile_image_url; } public void setProfile_image_url(String profile_image_url) { this.profile_image_url = profile_image_url; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getVerified() { return verified; } public void setVerified(String verified) { this.verified = verified; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getCreated_at() { return created_at; } public void setCreated_at(String created_at) { this.created_at = created_at; } public String getUpdated_at() { return updated_at; } public void setUpdated_at(String updated_at) { this.updated_at = updated_at; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getHours_class() { return hours_class; } public void setHours_class(String hours_class) { this.hours_class = hours_class; } public String getAvailable_areas() { return available_areas; } public void setAvailable_areas(String available_areas) { this.available_areas = available_areas; } public List<Sport> getSports() { return sports; } public void setSports(List<Sport> sports) { this.sports = sports; } public int getComment_num() { return comment_num; } public void setComment_num(int comment_num) { this.comment_num = comment_num; } public float getScore() { return score; } public void setScore(float score) { this.score = score; } public int getLevel() { return level; } public void setLevel(int level) { this.level = level; } public float getCoach_price() { return coach_price; } public void setCoach_price(float coach_price) { this.coach_price = coach_price; } }
DoTalkLily/AppKit
app/src/main/java/com/randian/win/model/Coach.java
1,205
//教练对应的课程列表
line_comment
zh-cn
package com.randian.win.model; import java.io.Serializable; import java.util.List; /** * Created by lily on 15-6-24. */ public class Coach implements Serializable { private int id; private int level;//等级 1:中级 2:高级 3:特级 4:专家 private int distance; private int order_num; private int comment_num; private int reputation_num; private float score; private float coach_price; private String sex; private String name; private String city; private String location; private String verified; private String created_at; private String updated_at; private String description; private String hours_class; private String available_areas; private String profile_image_url; private String positive_reputation; private String categoriesStr; private List<Sport> sports;//教练 <SUF> private List<Category> categories; //category的结构 [{"name":"瑜伽"},{"name":"健身"}] public class Category implements Serializable{ private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } public List<Category> getCategoriesList() { return categories; } public void setCategoriesList(List<Category> categories) { this.categories = categories; } public String getCategories() { return categoriesStr; } public void setCategories(String categoriesStr) { this.categoriesStr = categoriesStr; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getOrder_num() { return order_num; } public void setOrder_num(int order_num) { this.order_num = order_num; } public int getDistance() { return distance; } public void setDistance(int distance) { this.distance = distance; } public int getReputation_num() { return reputation_num; } public void setReputation_num(int reputation_num) { this.reputation_num = reputation_num; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getPositive_reputation() { return positive_reputation; } public void setPositive_reputation(String positive_reputation) { this.positive_reputation = positive_reputation; } public String getProfile_image_url() { return profile_image_url; } public void setProfile_image_url(String profile_image_url) { this.profile_image_url = profile_image_url; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getVerified() { return verified; } public void setVerified(String verified) { this.verified = verified; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getCreated_at() { return created_at; } public void setCreated_at(String created_at) { this.created_at = created_at; } public String getUpdated_at() { return updated_at; } public void setUpdated_at(String updated_at) { this.updated_at = updated_at; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getHours_class() { return hours_class; } public void setHours_class(String hours_class) { this.hours_class = hours_class; } public String getAvailable_areas() { return available_areas; } public void setAvailable_areas(String available_areas) { this.available_areas = available_areas; } public List<Sport> getSports() { return sports; } public void setSports(List<Sport> sports) { this.sports = sports; } public int getComment_num() { return comment_num; } public void setComment_num(int comment_num) { this.comment_num = comment_num; } public float getScore() { return score; } public void setScore(float score) { this.score = score; } public int getLevel() { return level; } public void setLevel(int level) { this.level = level; } public float getCoach_price() { return coach_price; } public void setCoach_price(float coach_price) { this.coach_price = coach_price; } }
0
1,033
5
1,205
6
1,338
5
1,205
6
1,473
14
false
false
false
false
false
true
11898_0
package xyz.doikki.dkplayer.widget.component; import android.app.Activity; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.animation.Animation; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import xyz.doikki.dkplayer.R; import xyz.doikki.videoplayer.controller.IControlComponent; import xyz.doikki.videoplayer.controller.ControlWrapper; import xyz.doikki.videoplayer.player.VideoView; import xyz.doikki.videoplayer.util.PlayerUtils; public class AdControlView extends FrameLayout implements IControlComponent, View.OnClickListener { protected TextView mAdTime, mAdDetail; protected ImageView mBack, mVolume, mFullScreen, mPlayButton; protected AdControlListener mListener; private ControlWrapper mControlWrapper; public AdControlView(@NonNull Context context) { super(context); } public AdControlView(@NonNull Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public AdControlView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } { LayoutInflater.from(getContext()).inflate(R.layout.layout_ad_control_view, this, true); mAdTime = findViewById(R.id.ad_time); mAdDetail = findViewById(R.id.ad_detail); mAdDetail.setText("了解详情>"); mBack = findViewById(R.id.back); mBack.setVisibility(GONE); mVolume = findViewById(R.id.iv_volume); mFullScreen = findViewById(R.id.fullscreen); mPlayButton = findViewById(R.id.iv_play); mPlayButton.setOnClickListener(this); mAdTime.setOnClickListener(this); mAdDetail.setOnClickListener(this); mBack.setOnClickListener(this); mVolume.setOnClickListener(this); mFullScreen.setOnClickListener(this); this.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (mListener != null) mListener.onAdClick(); } }); } @Override public void attach(@NonNull ControlWrapper controlWrapper) { mControlWrapper = controlWrapper; } @Override public View getView() { return this; } @Override public void onVisibilityChanged(boolean isVisible, Animation anim) { } @Override public void onPlayStateChanged(int playState) { switch (playState) { case VideoView.STATE_PLAYING: mControlWrapper.startProgress(); mPlayButton.setSelected(true); break; case VideoView.STATE_PAUSED: mPlayButton.setSelected(false); break; } } @Override public void onPlayerStateChanged(int playerState) { switch (playerState) { case VideoView.PLAYER_NORMAL: mBack.setVisibility(GONE); mFullScreen.setSelected(false); break; case VideoView.PLAYER_FULL_SCREEN: mBack.setVisibility(VISIBLE); mFullScreen.setSelected(true); break; } //暂未实现全面屏适配逻辑,需要你自己补全 } @Override public void setProgress(int duration, int position) { if (mAdTime != null) mAdTime.setText(String.format("%s | 跳过", (duration - position) / 1000)); } @Override public void onLockStateChanged(boolean isLocked) { } @Override public void onClick(View v) { int id = v.getId(); if (id == R.id.back | id == R.id.fullscreen) { toggleFullScreen(); } else if (id == R.id.iv_volume) { doMute(); } else if (id == R.id.ad_detail) { if (mListener != null) mListener.onAdClick(); } else if (id == R.id.ad_time) { if (mListener != null) mListener.onSkipAd(); } else if (id == R.id.iv_play) { mControlWrapper.togglePlay(); } } private void doMute() { mControlWrapper.setMute(!mControlWrapper.isMute()); mVolume.setImageResource(mControlWrapper.isMute() ? R.drawable.dkplayer_ic_action_volume_up : R.drawable.dkplayer_ic_action_volume_off); } /** * 横竖屏切换 */ private void toggleFullScreen() { Activity activity = PlayerUtils.scanForActivity(getContext()); mControlWrapper.toggleFullScreen(activity); } public void setListener(AdControlListener listener) { this.mListener = listener; } public interface AdControlListener { void onAdClick(); void onSkipAd(); } }
Doikki/DKVideoPlayer
dkplayer-sample/src/main/java/xyz/doikki/dkplayer/widget/component/AdControlView.java
1,178
//暂未实现全面屏适配逻辑,需要你自己补全
line_comment
zh-cn
package xyz.doikki.dkplayer.widget.component; import android.app.Activity; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.animation.Animation; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import xyz.doikki.dkplayer.R; import xyz.doikki.videoplayer.controller.IControlComponent; import xyz.doikki.videoplayer.controller.ControlWrapper; import xyz.doikki.videoplayer.player.VideoView; import xyz.doikki.videoplayer.util.PlayerUtils; public class AdControlView extends FrameLayout implements IControlComponent, View.OnClickListener { protected TextView mAdTime, mAdDetail; protected ImageView mBack, mVolume, mFullScreen, mPlayButton; protected AdControlListener mListener; private ControlWrapper mControlWrapper; public AdControlView(@NonNull Context context) { super(context); } public AdControlView(@NonNull Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public AdControlView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } { LayoutInflater.from(getContext()).inflate(R.layout.layout_ad_control_view, this, true); mAdTime = findViewById(R.id.ad_time); mAdDetail = findViewById(R.id.ad_detail); mAdDetail.setText("了解详情>"); mBack = findViewById(R.id.back); mBack.setVisibility(GONE); mVolume = findViewById(R.id.iv_volume); mFullScreen = findViewById(R.id.fullscreen); mPlayButton = findViewById(R.id.iv_play); mPlayButton.setOnClickListener(this); mAdTime.setOnClickListener(this); mAdDetail.setOnClickListener(this); mBack.setOnClickListener(this); mVolume.setOnClickListener(this); mFullScreen.setOnClickListener(this); this.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (mListener != null) mListener.onAdClick(); } }); } @Override public void attach(@NonNull ControlWrapper controlWrapper) { mControlWrapper = controlWrapper; } @Override public View getView() { return this; } @Override public void onVisibilityChanged(boolean isVisible, Animation anim) { } @Override public void onPlayStateChanged(int playState) { switch (playState) { case VideoView.STATE_PLAYING: mControlWrapper.startProgress(); mPlayButton.setSelected(true); break; case VideoView.STATE_PAUSED: mPlayButton.setSelected(false); break; } } @Override public void onPlayerStateChanged(int playerState) { switch (playerState) { case VideoView.PLAYER_NORMAL: mBack.setVisibility(GONE); mFullScreen.setSelected(false); break; case VideoView.PLAYER_FULL_SCREEN: mBack.setVisibility(VISIBLE); mFullScreen.setSelected(true); break; } //暂未 <SUF> } @Override public void setProgress(int duration, int position) { if (mAdTime != null) mAdTime.setText(String.format("%s | 跳过", (duration - position) / 1000)); } @Override public void onLockStateChanged(boolean isLocked) { } @Override public void onClick(View v) { int id = v.getId(); if (id == R.id.back | id == R.id.fullscreen) { toggleFullScreen(); } else if (id == R.id.iv_volume) { doMute(); } else if (id == R.id.ad_detail) { if (mListener != null) mListener.onAdClick(); } else if (id == R.id.ad_time) { if (mListener != null) mListener.onSkipAd(); } else if (id == R.id.iv_play) { mControlWrapper.togglePlay(); } } private void doMute() { mControlWrapper.setMute(!mControlWrapper.isMute()); mVolume.setImageResource(mControlWrapper.isMute() ? R.drawable.dkplayer_ic_action_volume_up : R.drawable.dkplayer_ic_action_volume_off); } /** * 横竖屏切换 */ private void toggleFullScreen() { Activity activity = PlayerUtils.scanForActivity(getContext()); mControlWrapper.toggleFullScreen(activity); } public void setListener(AdControlListener listener) { this.mListener = listener; } public interface AdControlListener { void onAdClick(); void onSkipAd(); } }
0
986
14
1,178
16
1,264
13
1,178
16
1,430
34
false
false
false
false
false
true
43668_5
import javax.swing.*; import java.awt.*; import java.awt.event.*; /** * 显示帮助信息的对话框 */ public class HelpDialog extends JDialog implements ActionListener { // 确认按钮 private JButton okay; // 取消按钮 private JButton cancel; public HelpDialog(Frame parent,String title) { super(parent,title,true); //不可缺少true addText(); okay.addActionListener(this); cancel.addActionListener(this); pack(); show(); } // 显示面板 public void addText() { setLocation(300, 210); okay = new JButton("确认"); cancel = new JButton("取消"); Panel button = new Panel(); button.setLayout(new FlowLayout()); button.add(okay); button.add(cancel); setLayout(new GridLayout(5,1)); add(new Label("传教士野人过河问题是一个经典的人工智能问题,问题描述如下:")); add(new Label("有N个传教士和N个野人过河,只有一条能装下K个人(包括野人)的船,K<N,")); add(new Label("在河的任何一方或者船上,如果有野人和传教士在一起,必须要求传教士的人数多于或等于野人的人数。")); add(new Label("本程序使用A*搜索算法实现求解传教士野人过河问题,对任意N、K有解时给出其解决方案。")); add(button); } // 监听事件 public void actionPerformed(ActionEvent ae) { //隐藏对话框 dispose(); } };
DolphinHome/java-mc-astar
src/HelpDialog.java
397
// 监听事件
line_comment
zh-cn
import javax.swing.*; import java.awt.*; import java.awt.event.*; /** * 显示帮助信息的对话框 */ public class HelpDialog extends JDialog implements ActionListener { // 确认按钮 private JButton okay; // 取消按钮 private JButton cancel; public HelpDialog(Frame parent,String title) { super(parent,title,true); //不可缺少true addText(); okay.addActionListener(this); cancel.addActionListener(this); pack(); show(); } // 显示面板 public void addText() { setLocation(300, 210); okay = new JButton("确认"); cancel = new JButton("取消"); Panel button = new Panel(); button.setLayout(new FlowLayout()); button.add(okay); button.add(cancel); setLayout(new GridLayout(5,1)); add(new Label("传教士野人过河问题是一个经典的人工智能问题,问题描述如下:")); add(new Label("有N个传教士和N个野人过河,只有一条能装下K个人(包括野人)的船,K<N,")); add(new Label("在河的任何一方或者船上,如果有野人和传教士在一起,必须要求传教士的人数多于或等于野人的人数。")); add(new Label("本程序使用A*搜索算法实现求解传教士野人过河问题,对任意N、K有解时给出其解决方案。")); add(button); } // 监听 <SUF> public void actionPerformed(ActionEvent ae) { //隐藏对话框 dispose(); } };
0
350
5
397
4
400
4
397
4
525
10
false
false
false
false
false
true
38345_5
import java.util.HashMap; /** * LRU算法 最近最常使用算法,内存加载 */ public class LRU { public static class Node<V> { public Node<V> pre; public Node<V> next; public V value; public Node(V value) { this.value = value; } } public static class MyCache<K, V> { //map可保证为(1)的查询对应关系 private HashMap<K, Node<V>> keyNodeMap; private NodeDoubleLinkedList<V> nodeList; private int capacity; public MyCache(int capacity) { if (capacity < 1) { new RuntimeException("should be more than 1 "); } this.capacity = capacity; this.keyNodeMap = new HashMap<>(); this.nodeList = new NodeDoubleLinkedList<>(); } public V get(K key) { if (this.keyNodeMap.containsKey(key)) { Node<V> res = this.keyNodeMap.get(key); this.nodeList.moveNodeToTail(res); return res.value; } return null; } public void set(K key, V value) { if (keyNodeMap.containsKey(key)) { Node<V> res = this.keyNodeMap.get(key); res.value = value; this.nodeList.moveNodeToTail(res); } else { Node<V> res = new Node<>(value); this.nodeList.addNode(res); this.keyNodeMap.put(key, res); //大于指定容量移除掉头部,为最不经常使用的节点,同时移除掉map集合中的元素 if (this.keyNodeMap.size() == capacity + 1) { Node<V> removeNode = this.nodeList.removeHead(); keyNodeMap.remove(removeNode.value); } } } } /** * 双向链表 ,有头尾指针,头指针为最不经常使用的节点,尾指针为刚使用完的节点 * * @param <V> */ public static class NodeDoubleLinkedList<V> { private Node<V> head; private Node<V> tail; public NodeDoubleLinkedList() { this.head = null; this.tail = null; } public void addNode(Node<V> newNode) { if (newNode == null) { return; } if (this.head == null) { this.head = newNode; this.tail = newNode; } else { //双向链表 this.tail.next = newNode; newNode.pre = this.tail; this.tail = newNode; } } public void moveNodeToTail(Node<V> node) { if (this.tail == null) { return; } //先断开之前的位置 if (this.head == node) { head = node.next; this.head.pre = null; } else { node.pre.next = node.next; node.next.pre = node.pre; } //移动到最后的位置 node.pre = this.tail; node.next = null; this.tail.next = node; this.tail = node; } public Node<V> removeHead() { if (head == null) { return null; } Node removeNode = this.head; if (this.head == this.tail) { this.head = null; this.tail = null; } else { this.head = removeNode.next; this.head.pre = null; removeNode.next = null; } return removeNode; } } }
Dongyang666/leetcode
src/LRU.java
967
//先断开之前的位置
line_comment
zh-cn
import java.util.HashMap; /** * LRU算法 最近最常使用算法,内存加载 */ public class LRU { public static class Node<V> { public Node<V> pre; public Node<V> next; public V value; public Node(V value) { this.value = value; } } public static class MyCache<K, V> { //map可保证为(1)的查询对应关系 private HashMap<K, Node<V>> keyNodeMap; private NodeDoubleLinkedList<V> nodeList; private int capacity; public MyCache(int capacity) { if (capacity < 1) { new RuntimeException("should be more than 1 "); } this.capacity = capacity; this.keyNodeMap = new HashMap<>(); this.nodeList = new NodeDoubleLinkedList<>(); } public V get(K key) { if (this.keyNodeMap.containsKey(key)) { Node<V> res = this.keyNodeMap.get(key); this.nodeList.moveNodeToTail(res); return res.value; } return null; } public void set(K key, V value) { if (keyNodeMap.containsKey(key)) { Node<V> res = this.keyNodeMap.get(key); res.value = value; this.nodeList.moveNodeToTail(res); } else { Node<V> res = new Node<>(value); this.nodeList.addNode(res); this.keyNodeMap.put(key, res); //大于指定容量移除掉头部,为最不经常使用的节点,同时移除掉map集合中的元素 if (this.keyNodeMap.size() == capacity + 1) { Node<V> removeNode = this.nodeList.removeHead(); keyNodeMap.remove(removeNode.value); } } } } /** * 双向链表 ,有头尾指针,头指针为最不经常使用的节点,尾指针为刚使用完的节点 * * @param <V> */ public static class NodeDoubleLinkedList<V> { private Node<V> head; private Node<V> tail; public NodeDoubleLinkedList() { this.head = null; this.tail = null; } public void addNode(Node<V> newNode) { if (newNode == null) { return; } if (this.head == null) { this.head = newNode; this.tail = newNode; } else { //双向链表 this.tail.next = newNode; newNode.pre = this.tail; this.tail = newNode; } } public void moveNodeToTail(Node<V> node) { if (this.tail == null) { return; } //先断 <SUF> if (this.head == node) { head = node.next; this.head.pre = null; } else { node.pre.next = node.next; node.next.pre = node.pre; } //移动到最后的位置 node.pre = this.tail; node.next = null; this.tail.next = node; this.tail = node; } public Node<V> removeHead() { if (head == null) { return null; } Node removeNode = this.head; if (this.head == this.tail) { this.head = null; this.tail = null; } else { this.head = removeNode.next; this.head.pre = null; removeNode.next = null; } return removeNode; } } }
0
788
6
967
7
956
6
967
7
1,264
9
false
false
false
false
false
true
53109_2
/** * MIT License * * Copyright (c) 2017 CaiDongyu * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.axe.helper.aop; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.axe.annotation.aop.Aspect; import org.axe.helper.ioc.BeanHelper; import org.axe.helper.ioc.ClassHelper; import org.axe.interface_.base.Helper; import org.axe.interface_.proxy.Proxy; import org.axe.proxy.base.ProxyManger; import org.axe.util.ReflectionUtil; /** * 方法拦截助手类 * @author CaiDongyu on 2016/4/14. */ public final class AopHelper implements Helper{ @Override public void init() throws Exception{ synchronized (this) { Map<Class<?>,Set<Class<?>>> proxyMap = createProxyMap(); Map<Class<?>,List<Proxy>> targetMap = createTargetMap(proxyMap); for (Map.Entry<Class<?>,List<Proxy>> targetEntry:targetMap.entrySet()){ Class<?> targetClass = targetEntry.getKey(); List<Proxy> proxyList = targetEntry.getValue(); //真正的创建目标类的代理对象 Object proxy = ProxyManger.createProxy(targetClass,proxyList); BeanHelper.setBean(targetClass,proxy); } } } /** * 返回代理类与目标类集合的映射 * 比如代理类A,代理了B、C、D三个类 * 通过A类上的注解Aspect指定一个目标注解比如叫M * B、C、D类都拥有这个注解M,就可以了。 */ private static Map<Class<?>,Set<Class<?>>> createProxyMap() throws Exception { Map<Class<?>,Set<Class<?>>> proxyMap = new HashMap<>(); //找到切面抽象类的实现类,就是说,都是切面类 Set<Class<?>> proxyClassSet = ClassHelper.getClassSetBySuper(Proxy.class); for(Class<?> proxyClass : proxyClassSet){ //继承了 AspectProxy 不算,还得是有指定了切面目标类 if(proxyClass.isAnnotationPresent(Aspect.class)){ Aspect aspect = proxyClass.getAnnotation(Aspect.class); //TODO:目前AOP实现,还只是针对有目标注解的类做切面,不能细化到方法,这样一旦拦截,会拦截所有方法 //比如事务切面,实际上是切了整个Server类所有方法,但是在切面加强的时候会判断,判断这个方法开不开事务。 Set<Class<?>> targetClassSet = createTargetClassSet(aspect); proxyMap.put(proxyClass,targetClassSet); } } return proxyMap; } private static Set<Class<?>> createTargetClassSet(Aspect aspect) throws Exception{ Set<Class<?>> targetClassSet = new HashSet<>(); //切面目标的指定,依然是通过注解来匹配 Class<? extends Annotation>[] annotations = aspect.value(); //排除Aspect注解本身,因为Aspect注解就是用来指定目标切面注解的 if(annotations != null){ for(Class<? extends Annotation> annotation:annotations){ if(!annotation.equals(Aspect.class)){ //取出含有目标注解的类,作为目标类 targetClassSet.addAll(ClassHelper.getClassSetByAnnotation(annotation)); } } } return targetClassSet; } /** * 将proxy -> targetClassSet 映射关系逆转 * 变成 targetClass -> proxyList 关系 * 也就是说现在是 一个类,对应有多少个proxy去处理 */ private static Map<Class<?>,List<Proxy>> createTargetMap(Map<Class<?>, Set<Class<?>>> proxyMap) throws Exception{ Map<Class<?>,List<Proxy>> targetMap = new HashMap<>(); for (Map.Entry<Class<?>,Set<Class<?>>> proxyEntry:proxyMap.entrySet()){ Class<?> proxyClass = proxyEntry.getKey(); Set<Class<?>> targetClassSet = proxyEntry.getValue(); Proxy proxy = ReflectionUtil.newInstance(proxyClass); for (Class<?> targetClass : targetClassSet){ if (targetMap.containsKey(targetClass)){ targetMap.get(targetClass).add(proxy); } else { List<Proxy> proxyList = new ArrayList<Proxy>(); proxyList.add(proxy); targetMap.put(targetClass,proxyList); } } } return targetMap; } @Override public void onStartUp() throws Exception {} }
DongyuCai/Axe
axe/src/main/java/org/axe/helper/aop/AopHelper.java
1,335
//真正的创建目标类的代理对象
line_comment
zh-cn
/** * MIT License * * Copyright (c) 2017 CaiDongyu * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.axe.helper.aop; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.axe.annotation.aop.Aspect; import org.axe.helper.ioc.BeanHelper; import org.axe.helper.ioc.ClassHelper; import org.axe.interface_.base.Helper; import org.axe.interface_.proxy.Proxy; import org.axe.proxy.base.ProxyManger; import org.axe.util.ReflectionUtil; /** * 方法拦截助手类 * @author CaiDongyu on 2016/4/14. */ public final class AopHelper implements Helper{ @Override public void init() throws Exception{ synchronized (this) { Map<Class<?>,Set<Class<?>>> proxyMap = createProxyMap(); Map<Class<?>,List<Proxy>> targetMap = createTargetMap(proxyMap); for (Map.Entry<Class<?>,List<Proxy>> targetEntry:targetMap.entrySet()){ Class<?> targetClass = targetEntry.getKey(); List<Proxy> proxyList = targetEntry.getValue(); //真正 <SUF> Object proxy = ProxyManger.createProxy(targetClass,proxyList); BeanHelper.setBean(targetClass,proxy); } } } /** * 返回代理类与目标类集合的映射 * 比如代理类A,代理了B、C、D三个类 * 通过A类上的注解Aspect指定一个目标注解比如叫M * B、C、D类都拥有这个注解M,就可以了。 */ private static Map<Class<?>,Set<Class<?>>> createProxyMap() throws Exception { Map<Class<?>,Set<Class<?>>> proxyMap = new HashMap<>(); //找到切面抽象类的实现类,就是说,都是切面类 Set<Class<?>> proxyClassSet = ClassHelper.getClassSetBySuper(Proxy.class); for(Class<?> proxyClass : proxyClassSet){ //继承了 AspectProxy 不算,还得是有指定了切面目标类 if(proxyClass.isAnnotationPresent(Aspect.class)){ Aspect aspect = proxyClass.getAnnotation(Aspect.class); //TODO:目前AOP实现,还只是针对有目标注解的类做切面,不能细化到方法,这样一旦拦截,会拦截所有方法 //比如事务切面,实际上是切了整个Server类所有方法,但是在切面加强的时候会判断,判断这个方法开不开事务。 Set<Class<?>> targetClassSet = createTargetClassSet(aspect); proxyMap.put(proxyClass,targetClassSet); } } return proxyMap; } private static Set<Class<?>> createTargetClassSet(Aspect aspect) throws Exception{ Set<Class<?>> targetClassSet = new HashSet<>(); //切面目标的指定,依然是通过注解来匹配 Class<? extends Annotation>[] annotations = aspect.value(); //排除Aspect注解本身,因为Aspect注解就是用来指定目标切面注解的 if(annotations != null){ for(Class<? extends Annotation> annotation:annotations){ if(!annotation.equals(Aspect.class)){ //取出含有目标注解的类,作为目标类 targetClassSet.addAll(ClassHelper.getClassSetByAnnotation(annotation)); } } } return targetClassSet; } /** * 将proxy -> targetClassSet 映射关系逆转 * 变成 targetClass -> proxyList 关系 * 也就是说现在是 一个类,对应有多少个proxy去处理 */ private static Map<Class<?>,List<Proxy>> createTargetMap(Map<Class<?>, Set<Class<?>>> proxyMap) throws Exception{ Map<Class<?>,List<Proxy>> targetMap = new HashMap<>(); for (Map.Entry<Class<?>,Set<Class<?>>> proxyEntry:proxyMap.entrySet()){ Class<?> proxyClass = proxyEntry.getKey(); Set<Class<?>> targetClassSet = proxyEntry.getValue(); Proxy proxy = ReflectionUtil.newInstance(proxyClass); for (Class<?> targetClass : targetClassSet){ if (targetMap.containsKey(targetClass)){ targetMap.get(targetClass).add(proxy); } else { List<Proxy> proxyList = new ArrayList<Proxy>(); proxyList.add(proxy); targetMap.put(targetClass,proxyList); } } } return targetMap; } @Override public void onStartUp() throws Exception {} }
0
1,204
8
1,335
9
1,381
7
1,335
9
1,749
14
false
false
false
false
false
true
22120_2
package com.software.job.vo; import java.sql.Date; import com.software.job.po.Users; /* * 此javaBean为了方便展示页面数据,故和数据库类型不一样 */ public class UserInfo { private int id; private String uname; private String pwd; private String email; private String phone; private int age; private String gender;//数据类型改变 private String address; private String degree;//数据类型改变 private Date joinTime; private String ip; public UserInfo() { } public UserInfo(Users users) { super(); this.id = users.getId(); this.uname = users.getUname(); this.pwd = users.getPwd(); this.email = users.getEmail(); this.phone = users.getPhone(); this.age = users.getAge(); setGender(users.getGender()); this.address = users.getAddress(); setDegree(users.getDegree()); this.joinTime = users.getJoinTime(); this.ip = users.getIp(); } public UserInfo(int id, String uname, String pwd, String email, String phone, int age, int gender, String address, int degree, Date joinTime, String ip) { super(); this.id = id; this.uname = uname; this.pwd = pwd; this.email = email; this.phone = phone; this.age = age; setGender(gender); this.address = address; setDegree(degree); this.joinTime = joinTime; this.ip = ip; } public UserInfo(String uname, String pwd, String email, String phone, int age, int gender, String address, int degree, Date joinTime, String ip) { super(); this.uname = uname; this.pwd = pwd; this.email = email; this.phone = phone; this.age = age; setGender(gender); this.address = address; setDegree(degree); this.joinTime = joinTime; this.ip = ip; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUname() { return uname; } public void setUname(String uname) { this.uname = uname; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getGender() { return gender; } public void setGender(int gender) { if(gender==0) { this.gender = "男"; }else { this.gender="女"; } } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getDegree() { return degree; } public void setDegree(int degree) { switch (degree) { case 0: this.degree = "高中"; break; case 1: this.degree = "专科"; break; case 2: this.degree = "本科"; break; case 3: this.degree = "硕士"; break; case 4: this.degree = "博士"; break; } } public Date getJoinTime() { return joinTime; } public void setJoinTime(Date joinTime) { this.joinTime = joinTime; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } }
DonkeyHu/TypicalWebProject
src/com/software/job/vo/UserInfo.java
1,100
//数据类型改变
line_comment
zh-cn
package com.software.job.vo; import java.sql.Date; import com.software.job.po.Users; /* * 此javaBean为了方便展示页面数据,故和数据库类型不一样 */ public class UserInfo { private int id; private String uname; private String pwd; private String email; private String phone; private int age; private String gender;//数据类型改变 private String address; private String degree;//数据 <SUF> private Date joinTime; private String ip; public UserInfo() { } public UserInfo(Users users) { super(); this.id = users.getId(); this.uname = users.getUname(); this.pwd = users.getPwd(); this.email = users.getEmail(); this.phone = users.getPhone(); this.age = users.getAge(); setGender(users.getGender()); this.address = users.getAddress(); setDegree(users.getDegree()); this.joinTime = users.getJoinTime(); this.ip = users.getIp(); } public UserInfo(int id, String uname, String pwd, String email, String phone, int age, int gender, String address, int degree, Date joinTime, String ip) { super(); this.id = id; this.uname = uname; this.pwd = pwd; this.email = email; this.phone = phone; this.age = age; setGender(gender); this.address = address; setDegree(degree); this.joinTime = joinTime; this.ip = ip; } public UserInfo(String uname, String pwd, String email, String phone, int age, int gender, String address, int degree, Date joinTime, String ip) { super(); this.uname = uname; this.pwd = pwd; this.email = email; this.phone = phone; this.age = age; setGender(gender); this.address = address; setDegree(degree); this.joinTime = joinTime; this.ip = ip; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUname() { return uname; } public void setUname(String uname) { this.uname = uname; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getGender() { return gender; } public void setGender(int gender) { if(gender==0) { this.gender = "男"; }else { this.gender="女"; } } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getDegree() { return degree; } public void setDegree(int degree) { switch (degree) { case 0: this.degree = "高中"; break; case 1: this.degree = "专科"; break; case 2: this.degree = "本科"; break; case 3: this.degree = "硕士"; break; case 4: this.degree = "博士"; break; } } public Date getJoinTime() { return joinTime; } public void setJoinTime(Date joinTime) { this.joinTime = joinTime; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } }
0
835
4
1,100
4
1,090
4
1,100
4
1,283
7
false
false
false
false
false
true
63609_7
package priv.fruits.controller.web; import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.io.FileUtil; import cn.hutool.core.util.RandomUtil; import cn.hutool.extra.mail.MailAccount; import cn.hutool.extra.mail.MailUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import priv.fruits.pojo.ResultMessage; import priv.fruits.pojo.User; import priv.fruits.service.UserService; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; /** * @Author 冶生华 * @Description 果蔬超市 */ @Controller @RequestMapping("email") public class EmailController { // 创建配置好的邮箱对象 @Autowired private MailAccount mailAccount; @Autowired private UserService userService; /** * 发送邮箱验证码 * @param userEmail 邮件接收人 * @return */ @GetMapping("sendVerifyCode") @ResponseBody public ResultMessage sendVerifyCode(String userEmail, String type, HttpServletRequest request) { try { // 查询该邮箱是否已注册 User user = userService.getUserInfoByEmail(userEmail); if("register".equals(type) && user != null && user.getId() != null) { return new ResultMessage(207, "该邮箱已被注册!"); } // 生成验证码(随机10000 - 99999的数字) String code = RandomUtil.randomInt(10000, 99999)+""; // 将生成的验证码保存到session中, 用于后期验证 HttpSession session = request.getSession(); // 保存前将之前保存过的记录删除一遍, 防止之前有记录 session.removeAttribute("webEditPassVerifyCode"); session.removeAttribute("webRegisterVerifyCode"); // 判断是注册还是修改密码, 保存不同的名字 if("register".equals(type)) { session.setAttribute("webRegisterVerifyCode", code); } else if("editPassword".equals(type)) { session.setAttribute("webEditPassVerifyCode", code); } // 利用Hutool封装的邮箱工具类发送邮件 String send = MailUtil.send(mailAccount, CollectionUtil.newArrayList(userEmail), "您正在注册果蔬超市账户……", "打死都不要告诉别人!!验证码是:" + "<span style='color:#1E9FFF;font-size:16px;font-weight:800;'>" + code + "</span>", true); System.out.println("邮件发送结果:" + send); return new ResultMessage(0, "邮件已发送!请查收"); } catch (Exception e) { e.printStackTrace(); return new ResultMessage(500, "出现异常:" + e.getMessage()); } } }
DouFoUncle/daily-fruits
src/main/java/priv/fruits/controller/web/EmailController.java
733
// 判断是注册还是修改密码, 保存不同的名字
line_comment
zh-cn
package priv.fruits.controller.web; import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.io.FileUtil; import cn.hutool.core.util.RandomUtil; import cn.hutool.extra.mail.MailAccount; import cn.hutool.extra.mail.MailUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import priv.fruits.pojo.ResultMessage; import priv.fruits.pojo.User; import priv.fruits.service.UserService; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; /** * @Author 冶生华 * @Description 果蔬超市 */ @Controller @RequestMapping("email") public class EmailController { // 创建配置好的邮箱对象 @Autowired private MailAccount mailAccount; @Autowired private UserService userService; /** * 发送邮箱验证码 * @param userEmail 邮件接收人 * @return */ @GetMapping("sendVerifyCode") @ResponseBody public ResultMessage sendVerifyCode(String userEmail, String type, HttpServletRequest request) { try { // 查询该邮箱是否已注册 User user = userService.getUserInfoByEmail(userEmail); if("register".equals(type) && user != null && user.getId() != null) { return new ResultMessage(207, "该邮箱已被注册!"); } // 生成验证码(随机10000 - 99999的数字) String code = RandomUtil.randomInt(10000, 99999)+""; // 将生成的验证码保存到session中, 用于后期验证 HttpSession session = request.getSession(); // 保存前将之前保存过的记录删除一遍, 防止之前有记录 session.removeAttribute("webEditPassVerifyCode"); session.removeAttribute("webRegisterVerifyCode"); // 判断 <SUF> if("register".equals(type)) { session.setAttribute("webRegisterVerifyCode", code); } else if("editPassword".equals(type)) { session.setAttribute("webEditPassVerifyCode", code); } // 利用Hutool封装的邮箱工具类发送邮件 String send = MailUtil.send(mailAccount, CollectionUtil.newArrayList(userEmail), "您正在注册果蔬超市账户……", "打死都不要告诉别人!!验证码是:" + "<span style='color:#1E9FFF;font-size:16px;font-weight:800;'>" + code + "</span>", true); System.out.println("邮件发送结果:" + send); return new ResultMessage(0, "邮件已发送!请查收"); } catch (Exception e) { e.printStackTrace(); return new ResultMessage(500, "出现异常:" + e.getMessage()); } } }
0
625
13
733
12
740
11
733
12
984
24
false
false
false
false
false
true
43767_3
package controllers.admin; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Random; import models.mag_article; import models.mag_banner; import models.mag_works; import models.mag_worksclass; import play.Play; import play.libs.Files; import play.mvc.Controller; import com.alibaba.fastjson.JSON; public class Banner extends Controller{ public static void allBanner(){ mag_banner banner = new mag_banner(); renderJSON("{\"data\":"+banner.allBanner()+"}"); } public static void addBanner(String title,String remark,File image,String artclass ,String ardid){ System.out.println(title); System.out.println(remark); System.out.println(image); System.out.println(artclass); System.out.println(ardid); //文件保存目录路径 String savePath = Play.applicationPath.toString()+Play.configuration.getProperty("newsImg.savePath", "/public/upload/"); //文件保存目录URL String saveUrl = Play.configuration.getProperty("newsImg.savePath", "/public/upload/"); if (image != null) { //检查目录 File uploadDir = new File(savePath); if(!uploadDir.isDirectory()){ renderJSON("{\"state\":\"上传目录不存在。\"}"); return; } //检查目录写权限 if(!uploadDir.canWrite()){ renderJSON("{\"state\":\"上传目录没有写权限。\"}"); return; } String ymd = "banner"; savePath += ymd + "/"; saveUrl += ymd + "/"; File dirFile = new File(savePath); if (!dirFile.exists()) { dirFile.mkdirs(); } //检查扩展名 String fileExt = image.getName().substring(image.getName().lastIndexOf(".") + 1).toLowerCase(); SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt; File f = new File(savePath,newFileName); try { Files.copy(image,f); System.out.println(saveUrl + newFileName); java.text.DateFormat format1 = new java.text.SimpleDateFormat( "yyyy-MM-dd hh:mm"); String timeStr = format1.format(new Date()).toString(); if(artclass == "作品"){ mag_banner banner = new mag_banner( title, remark, saveUrl + newFileName, timeStr,"", ardid, "作品"); banner.save(); }else{ mag_banner banner = new mag_banner( title, remark, saveUrl + newFileName, timeStr,"", ardid, "文章"); banner.save(); } renderJSON("{\"state\":\"操作成功\"}"); } catch (Exception e) { e.printStackTrace(); renderJSON("{\"state\":\"上传失败\"}"); } }else{ renderJSON("{\"state\":\"请选择文件。\"}"); } renderJSON("{\"status\":\"操作成功\"}"); } public static void getBanner(){ } public static void delBanner(){ } public static void allBannerList(){ List<mag_article> artlist = mag_article.find("order by id desc").fetch(); List<mag_works> worklist = mag_works.find("order by id desc").fetch(); String artStr = JSON.toJSONString(artlist); String worksStr = JSON.toJSONString(worklist); renderJSON("{\"artlist\":"+artStr+",\"worklist\":"+worksStr+"}"); } }
DreamCoord/DreamCMS
app/controllers/admin/Banner.java
959
//检查目录写权限
line_comment
zh-cn
package controllers.admin; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Random; import models.mag_article; import models.mag_banner; import models.mag_works; import models.mag_worksclass; import play.Play; import play.libs.Files; import play.mvc.Controller; import com.alibaba.fastjson.JSON; public class Banner extends Controller{ public static void allBanner(){ mag_banner banner = new mag_banner(); renderJSON("{\"data\":"+banner.allBanner()+"}"); } public static void addBanner(String title,String remark,File image,String artclass ,String ardid){ System.out.println(title); System.out.println(remark); System.out.println(image); System.out.println(artclass); System.out.println(ardid); //文件保存目录路径 String savePath = Play.applicationPath.toString()+Play.configuration.getProperty("newsImg.savePath", "/public/upload/"); //文件保存目录URL String saveUrl = Play.configuration.getProperty("newsImg.savePath", "/public/upload/"); if (image != null) { //检查目录 File uploadDir = new File(savePath); if(!uploadDir.isDirectory()){ renderJSON("{\"state\":\"上传目录不存在。\"}"); return; } //检查 <SUF> if(!uploadDir.canWrite()){ renderJSON("{\"state\":\"上传目录没有写权限。\"}"); return; } String ymd = "banner"; savePath += ymd + "/"; saveUrl += ymd + "/"; File dirFile = new File(savePath); if (!dirFile.exists()) { dirFile.mkdirs(); } //检查扩展名 String fileExt = image.getName().substring(image.getName().lastIndexOf(".") + 1).toLowerCase(); SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt; File f = new File(savePath,newFileName); try { Files.copy(image,f); System.out.println(saveUrl + newFileName); java.text.DateFormat format1 = new java.text.SimpleDateFormat( "yyyy-MM-dd hh:mm"); String timeStr = format1.format(new Date()).toString(); if(artclass == "作品"){ mag_banner banner = new mag_banner( title, remark, saveUrl + newFileName, timeStr,"", ardid, "作品"); banner.save(); }else{ mag_banner banner = new mag_banner( title, remark, saveUrl + newFileName, timeStr,"", ardid, "文章"); banner.save(); } renderJSON("{\"state\":\"操作成功\"}"); } catch (Exception e) { e.printStackTrace(); renderJSON("{\"state\":\"上传失败\"}"); } }else{ renderJSON("{\"state\":\"请选择文件。\"}"); } renderJSON("{\"status\":\"操作成功\"}"); } public static void getBanner(){ } public static void delBanner(){ } public static void allBannerList(){ List<mag_article> artlist = mag_article.find("order by id desc").fetch(); List<mag_works> worklist = mag_works.find("order by id desc").fetch(); String artStr = JSON.toJSONString(artlist); String worksStr = JSON.toJSONString(worklist); renderJSON("{\"artlist\":"+artStr+",\"worklist\":"+worksStr+"}"); } }
0
773
5
959
5
970
5
959
5
1,252
12
false
false
false
false
false
true
36160_53
package cwp.moneycharge.dao; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.cwp.cmoneycharge.R; import java.util.ArrayList; import java.util.List; import cwp.moneycharge.model.Tb_ptype; //收入类型的数据库 public class PtypeDAO { // (_id INTEGER NOT NULL PRIMARY KEY,no not null integer ,typename // varchar(50) private DBOpenHelper helper;// 创建DBOpenHelper对象 private SQLiteDatabase db;// 创建SQLiteDatabase对象 int[] imageId = new int[] { R.drawable.icon_spjs_zwwc, R.drawable.icon_spjs_zwwc, R.drawable.icon_spjs_zwwc, R.drawable.icon_spjs_zwwc, R.drawable.icon_jjwy_rcyp, R.drawable.icon_xxyl_wg, R.drawable.icon_yfsp, R.drawable.icon_rqwl_slqk, R.drawable.icon_jltx_sjf, R.drawable.icon_spjs, R.drawable.icon_jrbx_ajhk, R.drawable.icon_jrbx, R.drawable.icon_xcjt_dczc, R.drawable.icon_qtzx, R.drawable.icon_jrbx_lxzc, R.drawable.yysb }; public PtypeDAO(Context context) { // TODO Auto-generated constructor stub helper = new DBOpenHelper(context);// 初始化DBOpenHelper对象 } /** * 新增收入类型 * * @param tb_ptype */ public void add(Tb_ptype tb_ptype) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 db.execSQL( "insert into tb_ptype (_id,no,typename) values (?,?,?)", new Object[] { tb_ptype.get_id(), tb_ptype.getNo(), tb_ptype.getTypename() });// 执行添加支出类型操作 } /** * 修改收入类型 * * @param tb_ptype */ public void modify(Tb_ptype tb_ptype) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 db.execSQL( "update Tb_ptype set typename = ? where _id = ? and no=?", new Object[] { tb_ptype.get_id(), tb_ptype.getNo(), tb_ptype.getTypename() });// 执行修改支出类型操作 } public void modifyByName(int id, String old, String now) { db = helper.getWritableDatabase(); db.execSQL( "update Tb_ptype set typename = ? where _id = ? and typename=?", new Object[] { id, now, old });// 执行修改收入类型操作 } /** * 删除收入类型 * * @param ids */ public void delete(Integer... ids) { if (ids.length > 0)// 判断是否存在要删除的id { StringBuffer sb = new StringBuffer();// 创建StringBuffer对象 for (int i = 0; i < ids.length - 1; i++)// 遍历要删除的id集合 { sb.append('?').append(',');// 将删除条件添加到StringBuffer对象中 } sb.deleteCharAt(sb.length() - 1);// 去掉最后一个“,“字符 db = helper.getWritableDatabase();// 创建SQLiteDatabase对象 // 执行删除便签信息操作 db.execSQL("delete from tb_ptype where _id in (?) and no in (" + sb + ")", (Object[]) ids); } } public void deleteByName(int id, String typename) { db = helper.getWritableDatabase();// 创建SQLiteDatabase对象 // 执行删除便签信息操作 db.execSQL("delete from tb_ptype where _id =? and typename=?", new Object[] { id, typename }); } public void deleteById(int id) { db = helper.getWritableDatabase();// 创建SQLiteDatabase对象 // 执行删除便签信息操作 db.execSQL("delete from tb_ptype where _id =? ", new Object[] { id }); } /** * 获取收入类型信息 * * @param start * 起始位置 * @param count * 每页显示数量 * @return */ public List<Tb_ptype> getScrollData(int id, int start, int count) { List<Tb_ptype> lisTb_ptype = new ArrayList<Tb_ptype>();// 创建集合对象 db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 // 获取所有便签信息 Cursor cursor = db.rawQuery( "select * from tb_ptype where _id=? order by no limit ?,?", new String[] { String.valueOf(id), String.valueOf(start), String.valueOf(count) }); while (cursor.moveToNext())// 遍历所有的便签信息 { // 将遍历到的便签信息添加到集合中 lisTb_ptype.add(new Tb_ptype(cursor.getInt(cursor .getColumnIndex("_id")), cursor.getInt(cursor .getColumnIndex("no")), cursor.getString(cursor .getColumnIndex("typename")))); } return lisTb_ptype;// 返回集合 } /** * 获取总记录数 * * @return */ public long getCount() { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 Cursor cursor = db.rawQuery("select count(no) from tb_ptype", null);// 获取支出类型的记录数 if (cursor.moveToNext())// 判断Cursor中是否有数据 { return cursor.getLong(0);// 返回总记录数 } return 0;// 如果没有数据,则返回0 } public long getCount(int id) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 Cursor cursor = db.rawQuery( "select count(no) from tb_ptype where _id=?", new String[] { String.valueOf(id) });// 获取收入信息的记录数 if (cursor.moveToNext())// 判断Cursor中是否有数据 { return cursor.getLong(0);// 返回总记录数 } return 0;// 如果没有数据,则返回0 } /** * 获取便签最大编号 * * @return */ public int getMaxId() { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 Cursor cursor = db.rawQuery("select max(no) from tb_ptype", null);// 获取收入类型表中的最大编号 while (cursor.moveToLast()) {// 访问Cursor中的最后一条数据 return cursor.getInt(0);// 获取访问到的数据,即最大编号 } return 0;// 如果没有数据,则返回0 } /** * 获取类型名数组 param id * * @return * */ public List<String> getPtypeName(int id) { List<String> lisCharSequence = new ArrayList<String>();// 创建集合对象 db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 Cursor cursor = db.rawQuery( "select typename from tb_ptype where _id=?", new String[] { String.valueOf(id) });// 获取收入类型表中的最大编号 while (cursor.moveToNext()) {// 访问Cursor中的最后一条数据 lisCharSequence.add(cursor.getString(cursor .getColumnIndex("typename"))); } return lisCharSequence;// 如果没有数据,则返回0 } public String getOneName(int id, int no) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 Cursor cursor = db.rawQuery( "select typename from tb_ptype where _id=? and no=?", new String[] { String.valueOf(id), String.valueOf(no) }); if (cursor.moveToNext()) { return cursor.getString(cursor.getColumnIndex("typename")); } return ""; } public int getOneImg(int id, int no) { if (imageId.length < no) { return imageId[14]; } return imageId[no - 1]; } public void initData(int id) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 db.execSQL("delete from tb_ptype where _id=?", new String[] { String.valueOf(id) }); // 确保无该id db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "1", "早餐" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "2", "午餐" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "3", "晚餐" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "4", "夜宵" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "5", "生活用品" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "6", "工作用品" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "7", "衣服" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "8", "应酬" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "9", "电子产品" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "10", "食品" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "11", "租金" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "12", "股票" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "13", "打的" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "14", "基金" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "15", "其他" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "16", "语音识别" }); } }
Dreamer206602/QuickMoney
app/src/main/java/cwp/moneycharge/dao/PtypeDAO.java
2,796
// 获取收入类型表中的最大编号
line_comment
zh-cn
package cwp.moneycharge.dao; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.cwp.cmoneycharge.R; import java.util.ArrayList; import java.util.List; import cwp.moneycharge.model.Tb_ptype; //收入类型的数据库 public class PtypeDAO { // (_id INTEGER NOT NULL PRIMARY KEY,no not null integer ,typename // varchar(50) private DBOpenHelper helper;// 创建DBOpenHelper对象 private SQLiteDatabase db;// 创建SQLiteDatabase对象 int[] imageId = new int[] { R.drawable.icon_spjs_zwwc, R.drawable.icon_spjs_zwwc, R.drawable.icon_spjs_zwwc, R.drawable.icon_spjs_zwwc, R.drawable.icon_jjwy_rcyp, R.drawable.icon_xxyl_wg, R.drawable.icon_yfsp, R.drawable.icon_rqwl_slqk, R.drawable.icon_jltx_sjf, R.drawable.icon_spjs, R.drawable.icon_jrbx_ajhk, R.drawable.icon_jrbx, R.drawable.icon_xcjt_dczc, R.drawable.icon_qtzx, R.drawable.icon_jrbx_lxzc, R.drawable.yysb }; public PtypeDAO(Context context) { // TODO Auto-generated constructor stub helper = new DBOpenHelper(context);// 初始化DBOpenHelper对象 } /** * 新增收入类型 * * @param tb_ptype */ public void add(Tb_ptype tb_ptype) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 db.execSQL( "insert into tb_ptype (_id,no,typename) values (?,?,?)", new Object[] { tb_ptype.get_id(), tb_ptype.getNo(), tb_ptype.getTypename() });// 执行添加支出类型操作 } /** * 修改收入类型 * * @param tb_ptype */ public void modify(Tb_ptype tb_ptype) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 db.execSQL( "update Tb_ptype set typename = ? where _id = ? and no=?", new Object[] { tb_ptype.get_id(), tb_ptype.getNo(), tb_ptype.getTypename() });// 执行修改支出类型操作 } public void modifyByName(int id, String old, String now) { db = helper.getWritableDatabase(); db.execSQL( "update Tb_ptype set typename = ? where _id = ? and typename=?", new Object[] { id, now, old });// 执行修改收入类型操作 } /** * 删除收入类型 * * @param ids */ public void delete(Integer... ids) { if (ids.length > 0)// 判断是否存在要删除的id { StringBuffer sb = new StringBuffer();// 创建StringBuffer对象 for (int i = 0; i < ids.length - 1; i++)// 遍历要删除的id集合 { sb.append('?').append(',');// 将删除条件添加到StringBuffer对象中 } sb.deleteCharAt(sb.length() - 1);// 去掉最后一个“,“字符 db = helper.getWritableDatabase();// 创建SQLiteDatabase对象 // 执行删除便签信息操作 db.execSQL("delete from tb_ptype where _id in (?) and no in (" + sb + ")", (Object[]) ids); } } public void deleteByName(int id, String typename) { db = helper.getWritableDatabase();// 创建SQLiteDatabase对象 // 执行删除便签信息操作 db.execSQL("delete from tb_ptype where _id =? and typename=?", new Object[] { id, typename }); } public void deleteById(int id) { db = helper.getWritableDatabase();// 创建SQLiteDatabase对象 // 执行删除便签信息操作 db.execSQL("delete from tb_ptype where _id =? ", new Object[] { id }); } /** * 获取收入类型信息 * * @param start * 起始位置 * @param count * 每页显示数量 * @return */ public List<Tb_ptype> getScrollData(int id, int start, int count) { List<Tb_ptype> lisTb_ptype = new ArrayList<Tb_ptype>();// 创建集合对象 db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 // 获取所有便签信息 Cursor cursor = db.rawQuery( "select * from tb_ptype where _id=? order by no limit ?,?", new String[] { String.valueOf(id), String.valueOf(start), String.valueOf(count) }); while (cursor.moveToNext())// 遍历所有的便签信息 { // 将遍历到的便签信息添加到集合中 lisTb_ptype.add(new Tb_ptype(cursor.getInt(cursor .getColumnIndex("_id")), cursor.getInt(cursor .getColumnIndex("no")), cursor.getString(cursor .getColumnIndex("typename")))); } return lisTb_ptype;// 返回集合 } /** * 获取总记录数 * * @return */ public long getCount() { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 Cursor cursor = db.rawQuery("select count(no) from tb_ptype", null);// 获取支出类型的记录数 if (cursor.moveToNext())// 判断Cursor中是否有数据 { return cursor.getLong(0);// 返回总记录数 } return 0;// 如果没有数据,则返回0 } public long getCount(int id) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 Cursor cursor = db.rawQuery( "select count(no) from tb_ptype where _id=?", new String[] { String.valueOf(id) });// 获取收入信息的记录数 if (cursor.moveToNext())// 判断Cursor中是否有数据 { return cursor.getLong(0);// 返回总记录数 } return 0;// 如果没有数据,则返回0 } /** * 获取便签最大编号 * * @return */ public int getMaxId() { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 Cursor cursor = db.rawQuery("select max(no) from tb_ptype", null);// 获取收入类型表中的最大编号 while (cursor.moveToLast()) {// 访问Cursor中的最后一条数据 return cursor.getInt(0);// 获取访问到的数据,即最大编号 } return 0;// 如果没有数据,则返回0 } /** * 获取类型名数组 param id * * @return * */ public List<String> getPtypeName(int id) { List<String> lisCharSequence = new ArrayList<String>();// 创建集合对象 db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 Cursor cursor = db.rawQuery( "select typename from tb_ptype where _id=?", new String[] { String.valueOf(id) });// 获取 <SUF> while (cursor.moveToNext()) {// 访问Cursor中的最后一条数据 lisCharSequence.add(cursor.getString(cursor .getColumnIndex("typename"))); } return lisCharSequence;// 如果没有数据,则返回0 } public String getOneName(int id, int no) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 Cursor cursor = db.rawQuery( "select typename from tb_ptype where _id=? and no=?", new String[] { String.valueOf(id), String.valueOf(no) }); if (cursor.moveToNext()) { return cursor.getString(cursor.getColumnIndex("typename")); } return ""; } public int getOneImg(int id, int no) { if (imageId.length < no) { return imageId[14]; } return imageId[no - 1]; } public void initData(int id) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 db.execSQL("delete from tb_ptype where _id=?", new String[] { String.valueOf(id) }); // 确保无该id db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "1", "早餐" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "2", "午餐" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "3", "晚餐" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "4", "夜宵" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "5", "生活用品" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "6", "工作用品" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "7", "衣服" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "8", "应酬" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "9", "电子产品" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "10", "食品" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "11", "租金" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "12", "股票" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "13", "打的" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "14", "基金" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "15", "其他" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "16", "语音识别" }); } }
0
2,374
8
2,796
9
2,756
8
2,796
9
3,683
15
false
false
false
false
false
true
34101_19
package net.paoding.analysis; import java.io.StringReader; import junit.framework.TestCase; import net.paoding.analysis.analyzer.PaodingAnalyzer; import org.apache.lucene.analysis.Token; import org.apache.lucene.analysis.TokenStream; public class AnalyzerTest extends TestCase { protected PaodingAnalyzer analyzer = new PaodingAnalyzer(); protected StringBuilder sb = new StringBuilder(); protected String dissect(String input) { try { TokenStream ts = analyzer.tokenStream("", new StringReader(input)); Token token; sb.setLength(0); while ((token = ts.next()) != null) { sb.append(token.termText()).append('/'); } if (sb.length() > 0) { sb.setLength(sb.length() - 1); } return sb.toString(); } catch (Exception e) { e.printStackTrace(); return "error"; } } /** * */ public void test000() { String result = dissect("a"); assertEquals("", result); } /** * */ public void test001() { String result = dissect("空格 a 空格"); assertEquals("空格/空格", result); } /** * */ public void test002() { String result = dissect("A座"); assertEquals("a座", result); } /** * */ public void test003() { String result = dissect("u盘"); assertEquals("u盘", result); } public void test004() { String result = dissect("刚买的u盘的容量"); assertEquals("刚/买的/u盘/容量", result); } public void test005() { String result = dissect("K歌之王很好听"); assertEquals("k歌之王/很好/好听", result); } // -------------------------------------------------------------- // 仅包含词语的句子分词策略 // -------------------------------------------------------------- /** * 句子全由词典词语组成,但词语之间没有包含、交叉关系 */ public void test100() { String result = dissect("台北中文国际"); assertEquals("台北/中文/国际", result); } /** * 句子全由词典词语组成,但词语之间有包含关系 */ public void test101() { String result = dissect("北京首都机场"); assertEquals("北京/首都/机场", result); } /** * 句子全由词典词语组成,但词语之间有交叉关系 */ public void test102() { String result = dissect("东西已经拍卖了"); assertEquals("东西/已经/拍卖/卖了", result); } /** * 句子全由词典词语组成,但词语之间有包含、交叉等复杂关系 */ public void test103() { String result = dissect("羽毛球拍"); assertEquals("羽毛/羽毛球/球拍", result); } // -------------------------------------------------------------- // noise词汇和单字的分词策略 // -------------------------------------------------------------- /** * 词语之间有一个noise字(的) */ public void test200() { String result = dissect("足球的魅力"); assertEquals("足球/魅力", result); } /** * 词语之间有一个noise词语(因之) */ public void test201() { String result = dissect("主人因之生气"); assertEquals("主人/生气", result); } /** * 词语前后分别有单字和双字的noise词语(与,有关) */ public void test202() { String result = dissect("与谋杀有关"); assertEquals("谋杀", result); } /** * 前有noise词语(哪怕),后面跟随了连续的noise单字(了,你) */ public void test203() { String result = dissect("哪怕朋友背叛了你"); assertEquals("朋友/背叛", result); } /** * 前后连续的noise词汇(虽然,某些),词语中有noise单字(很) */ public void test204() { String result = dissect("虽然某些动物很凶恶"); assertEquals("动物/凶恶", result); } // -------------------------------------------------------------- // 词典没有收录的字符串的分词策略 // -------------------------------------------------------------- /** * 仅1个字的非词汇串(东,西,南,北) */ public void test300() { String result = dissect("东&&西&&南&&北"); assertEquals("东/西/南/北", result); } /** * 仅两个字的非词汇串(古哥,谷歌,收狗,搜狗) */ public void test302() { String result = dissect("古哥&&谷歌&&收狗&&搜狗"); assertEquals("古哥/谷歌/收狗/搜狗", result); } /** * 多个字的非词汇串 */ public void test303() { String result = dissect("这是鸟语:玉鱼遇欲雨"); assertEquals("这是/鸟语/玉鱼/鱼遇/遇欲/欲雨", result); } /** * 两个词语之间有一个非词汇的字(真) */ public void test304() { String result = dissect("朋友真背叛了你了!"); assertEquals("朋友/真/背叛", result); } /** * 两个词语之间有一个非词汇的字符串(盒蟹) */ public void test305() { String result = dissect("建设盒蟹社会"); assertEquals("建设/盒蟹/社会", result); } /** * 两个词语之间有多个非词汇的字符串(盒少蟹) */ public void test306() { String result = dissect("建设盒少蟹社会"); assertEquals("建设/盒少/少蟹/社会", result); } // -------------------------------------------------------------- // 不包含小数点的汉字数字 // -------------------------------------------------------------- /** * 单个汉字数字 */ public void test400() { String result = dissect("二"); assertEquals("2", result); } /** * 两个汉字数字 */ public void test61() { String result = dissect("五六"); assertEquals("56", result); } /** * 多个汉字数字 */ public void test62() { String result = dissect("三四五六"); assertEquals("3456", result); } /** * 十三 */ public void test63() { String result = dissect("十三"); assertEquals("13", result); } /** * 二千 */ public void test65() { String result = dissect("二千"); assertEquals("2000", result); } /** * 两千 */ public void test651() { String result = dissect("两千"); assertEquals("2000", result); } /** * 两千 */ public void test6511() { String result = dissect("两千个"); assertEquals("2000/个", result); } /** * 2千 */ public void test652() { String result = dissect("2千"); assertEquals("2000", result); } /** * */ public void test653() { String result = dissect("3千万"); assertEquals("30000000", result); } /** * */ public void test654() { String result = dissect("3千万个案例"); assertEquals("30000000/个/案例", result); } /** * */ public void test64() { String result = dissect("千万"); assertEquals("千万", result); } public void test66() { String result = dissect("两两"); assertEquals("两两", result); } public void test67() { String result = dissect("二二"); assertEquals("22", result); } public void test68() { String result = dissect("2.2两"); assertEquals("2.2/两", result); } public void test69() { String result = dissect("二两"); assertEquals("2/两", result); } public void test690() { String result = dissect("2两"); assertEquals("2/两", result); } public void test691() { String result = dissect("2千克"); assertEquals("2000/克", result); } public void test692() { String result = dissect("2公斤"); assertEquals("2/公斤", result); } public void test693() { String result = dissect("2世纪"); assertEquals("2/世纪", result); } public void test7() { String result = dissect("哪怕二"); assertEquals("2", result); } }
DrizztLei/code
work/java/ROBOT/src/net/paoding/analysis/AnalyzerTest.java
2,518
/** * 仅两个字的非词汇串(古哥,谷歌,收狗,搜狗) */
block_comment
zh-cn
package net.paoding.analysis; import java.io.StringReader; import junit.framework.TestCase; import net.paoding.analysis.analyzer.PaodingAnalyzer; import org.apache.lucene.analysis.Token; import org.apache.lucene.analysis.TokenStream; public class AnalyzerTest extends TestCase { protected PaodingAnalyzer analyzer = new PaodingAnalyzer(); protected StringBuilder sb = new StringBuilder(); protected String dissect(String input) { try { TokenStream ts = analyzer.tokenStream("", new StringReader(input)); Token token; sb.setLength(0); while ((token = ts.next()) != null) { sb.append(token.termText()).append('/'); } if (sb.length() > 0) { sb.setLength(sb.length() - 1); } return sb.toString(); } catch (Exception e) { e.printStackTrace(); return "error"; } } /** * */ public void test000() { String result = dissect("a"); assertEquals("", result); } /** * */ public void test001() { String result = dissect("空格 a 空格"); assertEquals("空格/空格", result); } /** * */ public void test002() { String result = dissect("A座"); assertEquals("a座", result); } /** * */ public void test003() { String result = dissect("u盘"); assertEquals("u盘", result); } public void test004() { String result = dissect("刚买的u盘的容量"); assertEquals("刚/买的/u盘/容量", result); } public void test005() { String result = dissect("K歌之王很好听"); assertEquals("k歌之王/很好/好听", result); } // -------------------------------------------------------------- // 仅包含词语的句子分词策略 // -------------------------------------------------------------- /** * 句子全由词典词语组成,但词语之间没有包含、交叉关系 */ public void test100() { String result = dissect("台北中文国际"); assertEquals("台北/中文/国际", result); } /** * 句子全由词典词语组成,但词语之间有包含关系 */ public void test101() { String result = dissect("北京首都机场"); assertEquals("北京/首都/机场", result); } /** * 句子全由词典词语组成,但词语之间有交叉关系 */ public void test102() { String result = dissect("东西已经拍卖了"); assertEquals("东西/已经/拍卖/卖了", result); } /** * 句子全由词典词语组成,但词语之间有包含、交叉等复杂关系 */ public void test103() { String result = dissect("羽毛球拍"); assertEquals("羽毛/羽毛球/球拍", result); } // -------------------------------------------------------------- // noise词汇和单字的分词策略 // -------------------------------------------------------------- /** * 词语之间有一个noise字(的) */ public void test200() { String result = dissect("足球的魅力"); assertEquals("足球/魅力", result); } /** * 词语之间有一个noise词语(因之) */ public void test201() { String result = dissect("主人因之生气"); assertEquals("主人/生气", result); } /** * 词语前后分别有单字和双字的noise词语(与,有关) */ public void test202() { String result = dissect("与谋杀有关"); assertEquals("谋杀", result); } /** * 前有noise词语(哪怕),后面跟随了连续的noise单字(了,你) */ public void test203() { String result = dissect("哪怕朋友背叛了你"); assertEquals("朋友/背叛", result); } /** * 前后连续的noise词汇(虽然,某些),词语中有noise单字(很) */ public void test204() { String result = dissect("虽然某些动物很凶恶"); assertEquals("动物/凶恶", result); } // -------------------------------------------------------------- // 词典没有收录的字符串的分词策略 // -------------------------------------------------------------- /** * 仅1个字的非词汇串(东,西,南,北) */ public void test300() { String result = dissect("东&&西&&南&&北"); assertEquals("东/西/南/北", result); } /** * 仅两个 <SUF>*/ public void test302() { String result = dissect("古哥&&谷歌&&收狗&&搜狗"); assertEquals("古哥/谷歌/收狗/搜狗", result); } /** * 多个字的非词汇串 */ public void test303() { String result = dissect("这是鸟语:玉鱼遇欲雨"); assertEquals("这是/鸟语/玉鱼/鱼遇/遇欲/欲雨", result); } /** * 两个词语之间有一个非词汇的字(真) */ public void test304() { String result = dissect("朋友真背叛了你了!"); assertEquals("朋友/真/背叛", result); } /** * 两个词语之间有一个非词汇的字符串(盒蟹) */ public void test305() { String result = dissect("建设盒蟹社会"); assertEquals("建设/盒蟹/社会", result); } /** * 两个词语之间有多个非词汇的字符串(盒少蟹) */ public void test306() { String result = dissect("建设盒少蟹社会"); assertEquals("建设/盒少/少蟹/社会", result); } // -------------------------------------------------------------- // 不包含小数点的汉字数字 // -------------------------------------------------------------- /** * 单个汉字数字 */ public void test400() { String result = dissect("二"); assertEquals("2", result); } /** * 两个汉字数字 */ public void test61() { String result = dissect("五六"); assertEquals("56", result); } /** * 多个汉字数字 */ public void test62() { String result = dissect("三四五六"); assertEquals("3456", result); } /** * 十三 */ public void test63() { String result = dissect("十三"); assertEquals("13", result); } /** * 二千 */ public void test65() { String result = dissect("二千"); assertEquals("2000", result); } /** * 两千 */ public void test651() { String result = dissect("两千"); assertEquals("2000", result); } /** * 两千 */ public void test6511() { String result = dissect("两千个"); assertEquals("2000/个", result); } /** * 2千 */ public void test652() { String result = dissect("2千"); assertEquals("2000", result); } /** * */ public void test653() { String result = dissect("3千万"); assertEquals("30000000", result); } /** * */ public void test654() { String result = dissect("3千万个案例"); assertEquals("30000000/个/案例", result); } /** * */ public void test64() { String result = dissect("千万"); assertEquals("千万", result); } public void test66() { String result = dissect("两两"); assertEquals("两两", result); } public void test67() { String result = dissect("二二"); assertEquals("22", result); } public void test68() { String result = dissect("2.2两"); assertEquals("2.2/两", result); } public void test69() { String result = dissect("二两"); assertEquals("2/两", result); } public void test690() { String result = dissect("2两"); assertEquals("2/两", result); } public void test691() { String result = dissect("2千克"); assertEquals("2000/克", result); } public void test692() { String result = dissect("2公斤"); assertEquals("2/公斤", result); } public void test693() { String result = dissect("2世纪"); assertEquals("2/世纪", result); } public void test7() { String result = dissect("哪怕二"); assertEquals("2", result); } }
0
1,982
25
2,515
33
2,355
27
2,515
33
3,181
44
false
false
false
false
false
true
13765_40
package com.d.greendao; import de.greenrobot.daogenerator.DaoGenerator; import de.greenrobot.daogenerator.Entity; import de.greenrobot.daogenerator.Schema; /** * GreenDaoGenerator * Created by D on 2017/4/27. */ public class GreenDaoGenerator { public static void main(String[] args) throws Exception { // 正如你所见的,你创建了一个用于添加实体(Entity)的模式(Schema)对象。 // 两个参数分别代表:数据库版本号与自动生成代码的包路径。 // Schema schema = new Schema(1, "com.d.music.data.database.greendao.music"); // 当然,如果你愿意,你也可以分别指定生成的 Bean 与 DAO 类所在的目录,只要如下所示: Schema schema = new Schema(1, "com.d.music.data.database.greendao.bean"); schema.setDefaultJavaPackageDao("com.d.music.data.database.greendao.dao"); // 模式(Schema)同时也拥有两个默认的 flags,分别用来标示 entity 是否是 activie 以及是否使用 keep sections。 // schema2.enableActiveEntitiesByDefault(); // schema2.enableKeepSectionsByDefault(); // 一旦你拥有了一个 Schema 对象后,你便可以使用它添加实体(Entities)了。 addMusic(schema); addLocalAllMusic(schema); addCollectionMusic(schema); addCustomList(schema); addCustomMusics(schema); addTransferModel(schema); // 最后我们将使用 DAOGenerator 类的 generateAll() 方法自动生成代码,此处你需要根据自己的情况更改输出目录。 // 其实,输出目录的路径可以在 build.gradle 中设置,有兴趣的朋友可以自行搜索,这里就不再详解。 // 重新运行GreenDaoGenerator时,将此路径更改为本地src路径 new DaoGenerator().generateAll(schema, "D:\\AndroidStudioProjects\\DMusic\\app\\src\\main\\java"); } /** * Music - 歌曲 */ private static void addMusic(Schema schema) { Entity entity = schema.addEntity("MusicModel"); // 表名 addProperty(entity); } /** * LocalAllMusic - 本地歌曲 */ private static void addLocalAllMusic(Schema schema) { Entity entity = schema.addEntity("LocalAllMusic"); // 表名 addProperty(entity); } /** * CollectionMusic - 收藏歌曲 */ private static void addCollectionMusic(Schema schema) { Entity entity = schema.addEntity("CollectionMusic"); // 表名 addProperty(entity); } /** * CustomList - 自定义列表 */ private static void addCustomList(Schema schema) { Entity entity = schema.addEntity("CustomListModel"); // 表名 entity.addIdProperty().autoincrement(); // id主键自增 entity.addStringProperty("name"); // 歌曲列表名 entity.addLongProperty("count"); // 包含歌曲数 entity.addIntProperty("seq"); // 排序显示序号 entity.addIntProperty("sortType"); // 排序方式(1:按名称排序,2:按时间排序,3:自定义排序) entity.addIntProperty("pointer"); // 指针:指向数据库相应表 } /** * CustomMusic - 自定义歌曲(创建20张) */ private static void addCustomMusics(Schema schema) { for (int i = 0; i < 20; i++) { Entity entity = schema.addEntity("CustomMusic" + i); // 表名 addProperty(entity); } } /** * TransferModel - 传输 */ private static void addTransferModel(Schema schema) { Entity entity = schema.addEntity("TransferModel"); // 表名 entity.addStringProperty("transferId").primaryKey(); // 文件完整路径---主键 entity.addIntProperty("transferType"); entity.addIntProperty("transferState"); entity.addLongProperty("transferCurrentLength"); entity.addLongProperty("transferTotalLength"); entity.addStringProperty("id"); // 文件完整路径 entity.addIntProperty("type"); // 类型:本地、百度、网易、QQ等 entity.addIntProperty("seq"); // 自定义序号 entity.addStringProperty("songId"); // 歌曲ID entity.addStringProperty("songName"); // 歌曲名 entity.addStringProperty("songUrl"); // 歌曲url entity.addStringProperty("artistId"); // 艺术家ID entity.addStringProperty("artistName"); // 歌手名 entity.addStringProperty("albumId"); // 专辑ID entity.addStringProperty("albumName"); // 专辑 entity.addStringProperty("albumUrl"); // 专辑url entity.addStringProperty("lrcName"); // 歌词名称 entity.addStringProperty("lrcUrl"); // 歌词路径 entity.addLongProperty("fileDuration"); // 歌曲时长 entity.addLongProperty("fileSize"); // 文件大小 entity.addStringProperty("filePostfix"); // 文件后缀类型 entity.addStringProperty("fileFolder"); // 父文件夹绝对路径 entity.addBooleanProperty("isCollected"); // 是否收藏 entity.addLongProperty("timeStamp"); // 时间戳,插入时间 } /** * 添加公共字段 */ private static void addProperty(Entity entity) { entity.addStringProperty("id").primaryKey(); // 文件完整路径---主键 entity.addIntProperty("type"); // 类型:本地、百度、网易、QQ等 entity.addIntProperty("seq"); // 自定义序号 entity.addStringProperty("songId"); // 歌曲ID entity.addStringProperty("songName"); // 歌曲名 entity.addStringProperty("songUrl"); // 歌曲url entity.addStringProperty("artistId"); // 艺术家ID entity.addStringProperty("artistName"); // 歌手名 entity.addStringProperty("albumId"); // 专辑ID entity.addStringProperty("albumName"); // 专辑 entity.addStringProperty("albumUrl"); // 专辑url entity.addStringProperty("lrcName"); // 歌词名称 entity.addStringProperty("lrcUrl"); // 歌词路径 entity.addLongProperty("fileDuration"); // 歌曲时长 entity.addLongProperty("fileSize"); // 文件大小 entity.addStringProperty("filePostfix"); // 文件后缀类型 entity.addStringProperty("fileFolder"); // 父文件夹绝对路径 entity.addBooleanProperty("isCollected"); // 是否收藏 entity.addLongProperty("timeStamp"); // 时间戳,插入时间 } }
Dsiner/DMusic
lib_greendao_generator/src/main/java/com/d/greendao/GreenDaoGenerator.java
1,588
// 父文件夹绝对路径
line_comment
zh-cn
package com.d.greendao; import de.greenrobot.daogenerator.DaoGenerator; import de.greenrobot.daogenerator.Entity; import de.greenrobot.daogenerator.Schema; /** * GreenDaoGenerator * Created by D on 2017/4/27. */ public class GreenDaoGenerator { public static void main(String[] args) throws Exception { // 正如你所见的,你创建了一个用于添加实体(Entity)的模式(Schema)对象。 // 两个参数分别代表:数据库版本号与自动生成代码的包路径。 // Schema schema = new Schema(1, "com.d.music.data.database.greendao.music"); // 当然,如果你愿意,你也可以分别指定生成的 Bean 与 DAO 类所在的目录,只要如下所示: Schema schema = new Schema(1, "com.d.music.data.database.greendao.bean"); schema.setDefaultJavaPackageDao("com.d.music.data.database.greendao.dao"); // 模式(Schema)同时也拥有两个默认的 flags,分别用来标示 entity 是否是 activie 以及是否使用 keep sections。 // schema2.enableActiveEntitiesByDefault(); // schema2.enableKeepSectionsByDefault(); // 一旦你拥有了一个 Schema 对象后,你便可以使用它添加实体(Entities)了。 addMusic(schema); addLocalAllMusic(schema); addCollectionMusic(schema); addCustomList(schema); addCustomMusics(schema); addTransferModel(schema); // 最后我们将使用 DAOGenerator 类的 generateAll() 方法自动生成代码,此处你需要根据自己的情况更改输出目录。 // 其实,输出目录的路径可以在 build.gradle 中设置,有兴趣的朋友可以自行搜索,这里就不再详解。 // 重新运行GreenDaoGenerator时,将此路径更改为本地src路径 new DaoGenerator().generateAll(schema, "D:\\AndroidStudioProjects\\DMusic\\app\\src\\main\\java"); } /** * Music - 歌曲 */ private static void addMusic(Schema schema) { Entity entity = schema.addEntity("MusicModel"); // 表名 addProperty(entity); } /** * LocalAllMusic - 本地歌曲 */ private static void addLocalAllMusic(Schema schema) { Entity entity = schema.addEntity("LocalAllMusic"); // 表名 addProperty(entity); } /** * CollectionMusic - 收藏歌曲 */ private static void addCollectionMusic(Schema schema) { Entity entity = schema.addEntity("CollectionMusic"); // 表名 addProperty(entity); } /** * CustomList - 自定义列表 */ private static void addCustomList(Schema schema) { Entity entity = schema.addEntity("CustomListModel"); // 表名 entity.addIdProperty().autoincrement(); // id主键自增 entity.addStringProperty("name"); // 歌曲列表名 entity.addLongProperty("count"); // 包含歌曲数 entity.addIntProperty("seq"); // 排序显示序号 entity.addIntProperty("sortType"); // 排序方式(1:按名称排序,2:按时间排序,3:自定义排序) entity.addIntProperty("pointer"); // 指针:指向数据库相应表 } /** * CustomMusic - 自定义歌曲(创建20张) */ private static void addCustomMusics(Schema schema) { for (int i = 0; i < 20; i++) { Entity entity = schema.addEntity("CustomMusic" + i); // 表名 addProperty(entity); } } /** * TransferModel - 传输 */ private static void addTransferModel(Schema schema) { Entity entity = schema.addEntity("TransferModel"); // 表名 entity.addStringProperty("transferId").primaryKey(); // 文件完整路径---主键 entity.addIntProperty("transferType"); entity.addIntProperty("transferState"); entity.addLongProperty("transferCurrentLength"); entity.addLongProperty("transferTotalLength"); entity.addStringProperty("id"); // 文件完整路径 entity.addIntProperty("type"); // 类型:本地、百度、网易、QQ等 entity.addIntProperty("seq"); // 自定义序号 entity.addStringProperty("songId"); // 歌曲ID entity.addStringProperty("songName"); // 歌曲名 entity.addStringProperty("songUrl"); // 歌曲url entity.addStringProperty("artistId"); // 艺术家ID entity.addStringProperty("artistName"); // 歌手名 entity.addStringProperty("albumId"); // 专辑ID entity.addStringProperty("albumName"); // 专辑 entity.addStringProperty("albumUrl"); // 专辑url entity.addStringProperty("lrcName"); // 歌词名称 entity.addStringProperty("lrcUrl"); // 歌词路径 entity.addLongProperty("fileDuration"); // 歌曲时长 entity.addLongProperty("fileSize"); // 文件大小 entity.addStringProperty("filePostfix"); // 文件后缀类型 entity.addStringProperty("fileFolder"); // 父文 <SUF> entity.addBooleanProperty("isCollected"); // 是否收藏 entity.addLongProperty("timeStamp"); // 时间戳,插入时间 } /** * 添加公共字段 */ private static void addProperty(Entity entity) { entity.addStringProperty("id").primaryKey(); // 文件完整路径---主键 entity.addIntProperty("type"); // 类型:本地、百度、网易、QQ等 entity.addIntProperty("seq"); // 自定义序号 entity.addStringProperty("songId"); // 歌曲ID entity.addStringProperty("songName"); // 歌曲名 entity.addStringProperty("songUrl"); // 歌曲url entity.addStringProperty("artistId"); // 艺术家ID entity.addStringProperty("artistName"); // 歌手名 entity.addStringProperty("albumId"); // 专辑ID entity.addStringProperty("albumName"); // 专辑 entity.addStringProperty("albumUrl"); // 专辑url entity.addStringProperty("lrcName"); // 歌词名称 entity.addStringProperty("lrcUrl"); // 歌词路径 entity.addLongProperty("fileDuration"); // 歌曲时长 entity.addLongProperty("fileSize"); // 文件大小 entity.addStringProperty("filePostfix"); // 文件后缀类型 entity.addStringProperty("fileFolder"); // 父文件夹绝对路径 entity.addBooleanProperty("isCollected"); // 是否收藏 entity.addLongProperty("timeStamp"); // 时间戳,插入时间 } }
0
1,513
8
1,588
7
1,572
5
1,588
7
2,073
18
false
false
false
false
false
true
64189_9
package xu.problem.mc; import java.util.ArrayList; import core.problem.Action; import core.problem.Problem; import core.problem.State; public class McProblem extends Problem { @Override public State result(State parent, Action action) { int m = ((McState) parent).getM(); int c = ((McState) parent).getC(); int m1 = ((McAction) action).getM(); int c1 = ((McAction) action).getC(); int d = ((McAction) action).getD(); if (d == 1) { //从左岸划到右岸 return new McState(m - m1, c - c1, 0).setSize(size); //左岸人数减少,船到了右岸 } else { //从右岸划到左岸 return new McState(m + m1, c + c1, 1).setSize(size); //左岸人数增多,船到了左岸 } } @Override public int stepCost(State parent, Action action) { // TODO Auto-generated method stub return 1; } @Override public int heuristic(State state) { // TODO Auto-generated method stub McState s = (McState) state; return s.heuristic(); } //左右岸,船上的任意情况下,传教士野人个数分别为m和c时,是否安全 private boolean isSafe(int m, int c) { return m == 0 || m >= c; } @Override public ArrayList<Action> Actions(State state) { // TODO Auto-generated method stub ArrayList<Action> actions = new ArrayList<>(); int m = ((McState) state).getM(); int c = ((McState) state).getC(); int b = ((McState) state).getB(); //在左岸还是右岸? //如果船在右岸,计算出右岸的人数 if (b == 0) { m = size - m; c = size - c; } for (int i = 0; i <= m; i++) for (int j = 0; j <= c; j++) { if (i + j > 0 && i + j <= k && isSafe(i, j) && isSafe(m - i, c - j) && isSafe(size - m + i, size - c + j)) { McAction action = new McAction(i, j, b); //划船方向,从所在岸划向对岸 actions.add(action); } } return actions; } //帮助自己检查是否正确的复写了父类中已有的方法 //告诉读代码的人,这是一个复写的方法 @Override public void drawWorld() { // TODO Auto-generated method stub this.getInitialState().draw(); } @Override public void simulateResult(State parent, Action action) { // TODO Auto-generated method stub State child = result(parent, action); action.draw(); child.draw(); } public McProblem(McState initialState, McState goal, int size, int k) { super(initialState, goal); this.size = size; this.k = k; } public McProblem(int size, int k) { super(new McState(size, size, 1).setSize(size), new McState(0, 0, 0).setSize(size)); this.size = size; this.k = k; } private int size; //传教士和野人的个数,问题的规模 private int k; //船上可载人数的上限 @Override public boolean solvable() { // TODO Auto-generated method stub return true; } }
Du-Sen-Lin/AI
Searching_student/src/xu/problem/mc/McProblem.java
984
//如果船在右岸,计算出右岸的人数
line_comment
zh-cn
package xu.problem.mc; import java.util.ArrayList; import core.problem.Action; import core.problem.Problem; import core.problem.State; public class McProblem extends Problem { @Override public State result(State parent, Action action) { int m = ((McState) parent).getM(); int c = ((McState) parent).getC(); int m1 = ((McAction) action).getM(); int c1 = ((McAction) action).getC(); int d = ((McAction) action).getD(); if (d == 1) { //从左岸划到右岸 return new McState(m - m1, c - c1, 0).setSize(size); //左岸人数减少,船到了右岸 } else { //从右岸划到左岸 return new McState(m + m1, c + c1, 1).setSize(size); //左岸人数增多,船到了左岸 } } @Override public int stepCost(State parent, Action action) { // TODO Auto-generated method stub return 1; } @Override public int heuristic(State state) { // TODO Auto-generated method stub McState s = (McState) state; return s.heuristic(); } //左右岸,船上的任意情况下,传教士野人个数分别为m和c时,是否安全 private boolean isSafe(int m, int c) { return m == 0 || m >= c; } @Override public ArrayList<Action> Actions(State state) { // TODO Auto-generated method stub ArrayList<Action> actions = new ArrayList<>(); int m = ((McState) state).getM(); int c = ((McState) state).getC(); int b = ((McState) state).getB(); //在左岸还是右岸? //如果 <SUF> if (b == 0) { m = size - m; c = size - c; } for (int i = 0; i <= m; i++) for (int j = 0; j <= c; j++) { if (i + j > 0 && i + j <= k && isSafe(i, j) && isSafe(m - i, c - j) && isSafe(size - m + i, size - c + j)) { McAction action = new McAction(i, j, b); //划船方向,从所在岸划向对岸 actions.add(action); } } return actions; } //帮助自己检查是否正确的复写了父类中已有的方法 //告诉读代码的人,这是一个复写的方法 @Override public void drawWorld() { // TODO Auto-generated method stub this.getInitialState().draw(); } @Override public void simulateResult(State parent, Action action) { // TODO Auto-generated method stub State child = result(parent, action); action.draw(); child.draw(); } public McProblem(McState initialState, McState goal, int size, int k) { super(initialState, goal); this.size = size; this.k = k; } public McProblem(int size, int k) { super(new McState(size, size, 1).setSize(size), new McState(0, 0, 0).setSize(size)); this.size = size; this.k = k; } private int size; //传教士和野人的个数,问题的规模 private int k; //船上可载人数的上限 @Override public boolean solvable() { // TODO Auto-generated method stub return true; } }
0
844
13
983
16
971
13
984
16
1,209
22
false
false
false
false
false
true
669_2
package cn.itcast_03; import java.util.ArrayList; import java.util.Collections; /* * 模拟斗地主洗牌和发牌 * * 扑克牌:54 * 小王 * 大王 * 黑桃A,黑桃2,黑桃3,黑桃4,黑桃...,黑桃10,黑桃J,黑桃Q,黑桃K * 红桃... * 梅花... * 方块... * * 分析: * A:造一个牌盒(集合) * B:造每一张牌,然后存储到牌盒里面去 * C:洗牌 * D:发牌 * E:看牌 */ public class PokerDemo { public static void main(String[] args) { // 造一个牌盒(集合) ArrayList<String> array = new ArrayList<String>(); // 造每一张牌,然后存储到牌盒里面去 // 定义花色数组 String[] colors = { "♠", "♥", "♣", "♦" }; // 定义点数数组 String[] numbers = { "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K" }; for (String color : colors) { for (String number : numbers) { array.add(color.concat(number)); } } array.add("小王"); array.add("大王"); // 看牌 // System.out.println(array); // 洗牌 Collections.shuffle(array); // 发牌 // 三个选手 ArrayList<String> linQingXia = new ArrayList<String>(); ArrayList<String> fengQingYang = new ArrayList<String>(); ArrayList<String> liuYi = new ArrayList<String>(); // 底牌 ArrayList<String> diPai = new ArrayList<String>(); for (int x = 0; x < array.size(); x++) { if (x >= array.size() - 3) { diPai.add(array.get(x)); } else if (x % 3 == 0) { linQingXia.add(array.get(x)); } else if (x % 3 == 1) { fengQingYang.add(array.get(x)); } else if (x % 3 == 2) { liuYi.add(array.get(x)); } } // 看牌 lookPoker("林青霞", linQingXia); lookPoker("风清扬", fengQingYang); lookPoker("刘意", liuYi); lookPoker("底牌", diPai); } // 写一个功能实现遍历 public static void lookPoker(String name, ArrayList<String> array) { System.out.print(name + "的牌是:"); for (String s : array) { System.out.print(s + " "); } System.out.println(); } }
DuGuQiuBai/Java
day18/code/day18_Collections/src/cn/itcast_03/PokerDemo.java
813
// 造每一张牌,然后存储到牌盒里面去
line_comment
zh-cn
package cn.itcast_03; import java.util.ArrayList; import java.util.Collections; /* * 模拟斗地主洗牌和发牌 * * 扑克牌:54 * 小王 * 大王 * 黑桃A,黑桃2,黑桃3,黑桃4,黑桃...,黑桃10,黑桃J,黑桃Q,黑桃K * 红桃... * 梅花... * 方块... * * 分析: * A:造一个牌盒(集合) * B:造每一张牌,然后存储到牌盒里面去 * C:洗牌 * D:发牌 * E:看牌 */ public class PokerDemo { public static void main(String[] args) { // 造一个牌盒(集合) ArrayList<String> array = new ArrayList<String>(); // 造每 <SUF> // 定义花色数组 String[] colors = { "♠", "♥", "♣", "♦" }; // 定义点数数组 String[] numbers = { "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K" }; for (String color : colors) { for (String number : numbers) { array.add(color.concat(number)); } } array.add("小王"); array.add("大王"); // 看牌 // System.out.println(array); // 洗牌 Collections.shuffle(array); // 发牌 // 三个选手 ArrayList<String> linQingXia = new ArrayList<String>(); ArrayList<String> fengQingYang = new ArrayList<String>(); ArrayList<String> liuYi = new ArrayList<String>(); // 底牌 ArrayList<String> diPai = new ArrayList<String>(); for (int x = 0; x < array.size(); x++) { if (x >= array.size() - 3) { diPai.add(array.get(x)); } else if (x % 3 == 0) { linQingXia.add(array.get(x)); } else if (x % 3 == 1) { fengQingYang.add(array.get(x)); } else if (x % 3 == 2) { liuYi.add(array.get(x)); } } // 看牌 lookPoker("林青霞", linQingXia); lookPoker("风清扬", fengQingYang); lookPoker("刘意", liuYi); lookPoker("底牌", diPai); } // 写一个功能实现遍历 public static void lookPoker(String name, ArrayList<String> array) { System.out.print(name + "的牌是:"); for (String s : array) { System.out.print(s + " "); } System.out.println(); } }
0
710
14
813
16
747
13
813
16
1,025
26
false
false
false
false
false
true
51009_11
package com.duan.musicoco.modle; import android.provider.MediaStore; /** * Created by DuanJiaNing on 2017/5/24. */ final public class SongInfo implements MediaStore.Audio.AudioColumns { //用于搜索、排序、分类 private String title_key; private String artist_key; private String album_key; private int id; //时间 ms private long duration; //艺术家 private String artist; //所属专辑 private String album; //专辑 ID private String album_id; //专辑图片路径 private String album_path; //专辑录制时间 private long year; //磁盘上的保存路径 //与服务端的 path 域对应,对于同一首歌曲(文件路径相同),两者应该相同 private String data; //文件大小 bytes private long size; //显示的名字 private String display_name; //内容标题 private String title; //文件被加入媒体库的时间 private long date_added; //文件最后修改时间 private long date_modified; //MIME type private String mime_type; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SongInfo songInfo = (SongInfo) o; return data.equals(songInfo.data); } @Override public int hashCode() { return data.hashCode(); } public void setAlbum_id(String album_id) { this.album_id = album_id; } public void setAlbum_path(String album_path) { this.album_path = album_path; } public void setTitle_key(String title_key) { this.title_key = title_key; } public void setArtist_key(String artist_key) { this.artist_key = artist_key; } public void setAlbum_key(String album_key) { this.album_key = album_key; } public void setArtist(String artist) { this.artist = artist; } public void setAlbum(String album) { this.album = album; } public void setData(String data) { this.data = data; } public void setDisplay_name(String display_name) { this.display_name = display_name; } public void setTitle(String title) { this.title = title; } public void setMime_type(String mime_type) { this.mime_type = mime_type; } public void setYear(long year) { this.year = year; } public void setDuration(long duration) { this.duration = duration; } public void setSize(long size) { this.size = size; } public void setDate_added(long date_added) { this.date_added = date_added; } public void setDate_modified(long date_modified) { this.date_modified = date_modified; } public String getTitle_key() { return title_key; } public String getArtist_key() { return artist_key; } public String getAlbum_key() { return album_key; } public long getDuration() { return duration; } public String getArtist() { return artist; } public String getAlbum() { return album; } public long getYear() { return year; } public String getData() { return data; } public long getSize() { return size; } public String getDisplay_name() { return display_name; } public String getTitle() { return title; } public long getDate_added() { return date_added; } public long getDate_modified() { return date_modified; } public String getMime_type() { return mime_type; } public String getAlbum_id() { return album_id; } public String getAlbum_path() { return album_path; } public int getId() { return id; } public void setId(int id) { this.id = id; } }
DuanJiaNing/Musicoco
app/src/main/java/com/duan/musicoco/modle/SongInfo.java
1,007
//显示的名字
line_comment
zh-cn
package com.duan.musicoco.modle; import android.provider.MediaStore; /** * Created by DuanJiaNing on 2017/5/24. */ final public class SongInfo implements MediaStore.Audio.AudioColumns { //用于搜索、排序、分类 private String title_key; private String artist_key; private String album_key; private int id; //时间 ms private long duration; //艺术家 private String artist; //所属专辑 private String album; //专辑 ID private String album_id; //专辑图片路径 private String album_path; //专辑录制时间 private long year; //磁盘上的保存路径 //与服务端的 path 域对应,对于同一首歌曲(文件路径相同),两者应该相同 private String data; //文件大小 bytes private long size; //显示 <SUF> private String display_name; //内容标题 private String title; //文件被加入媒体库的时间 private long date_added; //文件最后修改时间 private long date_modified; //MIME type private String mime_type; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SongInfo songInfo = (SongInfo) o; return data.equals(songInfo.data); } @Override public int hashCode() { return data.hashCode(); } public void setAlbum_id(String album_id) { this.album_id = album_id; } public void setAlbum_path(String album_path) { this.album_path = album_path; } public void setTitle_key(String title_key) { this.title_key = title_key; } public void setArtist_key(String artist_key) { this.artist_key = artist_key; } public void setAlbum_key(String album_key) { this.album_key = album_key; } public void setArtist(String artist) { this.artist = artist; } public void setAlbum(String album) { this.album = album; } public void setData(String data) { this.data = data; } public void setDisplay_name(String display_name) { this.display_name = display_name; } public void setTitle(String title) { this.title = title; } public void setMime_type(String mime_type) { this.mime_type = mime_type; } public void setYear(long year) { this.year = year; } public void setDuration(long duration) { this.duration = duration; } public void setSize(long size) { this.size = size; } public void setDate_added(long date_added) { this.date_added = date_added; } public void setDate_modified(long date_modified) { this.date_modified = date_modified; } public String getTitle_key() { return title_key; } public String getArtist_key() { return artist_key; } public String getAlbum_key() { return album_key; } public long getDuration() { return duration; } public String getArtist() { return artist; } public String getAlbum() { return album; } public long getYear() { return year; } public String getData() { return data; } public long getSize() { return size; } public String getDisplay_name() { return display_name; } public String getTitle() { return title; } public long getDate_added() { return date_added; } public long getDate_modified() { return date_modified; } public String getMime_type() { return mime_type; } public String getAlbum_id() { return album_id; } public String getAlbum_path() { return album_path; } public int getId() { return id; } public void setId(int id) { this.id = id; } }
0
885
3
1,007
4
1,122
3
1,007
4
1,317
6
false
false
false
false
false
true
11959_6
package com.fuckwzxy.util; import cn.hutool.http.HttpRequest; import cn.hutool.http.HttpResponse; import cn.hutool.json.JSONArray; import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; import com.fuckwzxy.bean.ApiInfo; import com.fuckwzxy.bean.SignMessage; import com.fuckwzxy.bean.UserInfo; import com.fuckwzxy.common.ApiConstant; import lombok.extern.slf4j.Slf4j; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; import javax.sound.midi.Soundbank; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * @author wzh * 2020/9/23 19:15 */ @Component @Slf4j public class SendUtil { @Async public void sendCheckRequest(UserInfo userInfo, ApiInfo apiInfo, int seq) { HttpRequest request = createHttpRequest(apiInfo,userInfo); //body request.body(apiInfo.getBody().replace("seq=3", "seq=" + seq)); //return body request.execute(); } /** * 获取签到的id和logId * * @param userInfo user * @param getSignMessageApiInfo 接口 */ public SignMessage getSignMessage(UserInfo userInfo, ApiInfo getSignMessageApiInfo) { HttpRequest request = createHttpRequest(getSignMessageApiInfo,userInfo); //参数 request.form("page", 1); request.form("size", 5); //得到返回的JSON并解析 String body = request.execute().body(); JSONObject data = (JSONObject) ((JSONArray) JSONUtil.parseObj(body).get("data")).get(0); return new SignMessage((String) data.getObj("id"), (String) data.get("logId")); } @Async public void sendSignRequest(UserInfo userInfo, ApiInfo signApiInfo, SignMessage signMessage) { HttpRequest request = createHttpRequest(signApiInfo,userInfo); //JSON data JSONObject data = new JSONObject(); data.set("id", signMessage.getLogId()); data.set("signId", signMessage.getId()); data.set("latitude", "23.090164"); data.set("longitude", "113.354053"); data.set("country", "中国"); data.set("province", "广东省"); data.set("district", "海珠区"); data.set("township", "官洲街道"); data.set("city", "广州市"); request.body(data.toString()); request.execute(); } public String GetJSON(UserInfo userInfo, ApiInfo getSignMessageApiInfo) { HttpRequest request = createHttpRequest(getSignMessageApiInfo,userInfo); //参数 request.form("page", 1); request.form("size", 5); //得到返回的JSON并解析 String body = request.execute().body(); return body; } public boolean needCheck(ApiInfo apiInfo,UserInfo userInfo, int seq){ HttpRequest request = createHttpRequest(apiInfo,userInfo); HttpResponse response = request.execute(); String body = response.body(); if(!JSONUtil.parseObj(body).containsKey("data")) return false; JSONObject data = (JSONObject) ((JSONArray) JSONUtil.parseObj(body).get("data")).get(seq-1); return Integer.parseInt(data.get("type").toString()) == 0; } public List<String> getAllNoSign(ApiInfo apiInfo,UserInfo userInfo, int seq){ HttpRequest request = createHttpRequest(apiInfo,userInfo); //body SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");// 设置日期格式 String date = df.format(new Date()); String httpbody = apiInfo.getBody().replace("seq=3", "seq=" + seq); httpbody = httpbody.replace("date=20201030","date="+date); request.body(httpbody); String body = request.execute().body(); if(!JSONUtil.parseObj(body).containsKey("data") ){ return null; }else{ List<String> list = new ArrayList<>(); JSONArray arr = (JSONArray) JSONUtil.parseObj(body).get("data"); for (int i = 0; i < arr.size() ; i++) { JSONObject stu = (JSONObject) arr.get(i); list.add((String) stu.get("userId")); } return list; } } public void replaceSign(ApiInfo apiInfo,UserInfo userInfo, int seq,String userId){ HttpRequest request = createHttpRequest(apiInfo,userInfo); //body String httpbody = apiInfo.getBody().replace("seq=", "seq=" + seq); httpbody = httpbody.replace("userId=","userId="+userId); request.body(httpbody); //return body request.execute(); } public boolean JudgeTokenIsValid(ApiInfo apiInfo,UserInfo userInfo){ HttpRequest request = createHttpRequest(apiInfo,userInfo); //得到返回的JSON并解析 String body = request.execute().body(); if(JSONUtil.parseObj(body).containsKey("data")) return true; else return false; } /** * 创建HttpRequest对象 */ private HttpRequest createHttpRequest(ApiInfo apiInfo,UserInfo userInfo) { //请求方法和请求url HttpRequest request = request = apiInfo.getMethod().equals(ApiConstant.METHOD_GET)?HttpRequest.get(apiInfo.getUrl()):HttpRequest.post(apiInfo.getUrl()); //报文头 request.contentType(apiInfo.getContenttype()); //token request.header("token", userInfo.getToken().trim());//总有混蛋 带空格存进来 return request; } }
Duangdi/fuck-wozaixiaoyuan
src/main/java/com/fuckwzxy/util/SendUtil.java
1,384
//得到返回的JSON并解析
line_comment
zh-cn
package com.fuckwzxy.util; import cn.hutool.http.HttpRequest; import cn.hutool.http.HttpResponse; import cn.hutool.json.JSONArray; import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; import com.fuckwzxy.bean.ApiInfo; import com.fuckwzxy.bean.SignMessage; import com.fuckwzxy.bean.UserInfo; import com.fuckwzxy.common.ApiConstant; import lombok.extern.slf4j.Slf4j; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; import javax.sound.midi.Soundbank; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * @author wzh * 2020/9/23 19:15 */ @Component @Slf4j public class SendUtil { @Async public void sendCheckRequest(UserInfo userInfo, ApiInfo apiInfo, int seq) { HttpRequest request = createHttpRequest(apiInfo,userInfo); //body request.body(apiInfo.getBody().replace("seq=3", "seq=" + seq)); //return body request.execute(); } /** * 获取签到的id和logId * * @param userInfo user * @param getSignMessageApiInfo 接口 */ public SignMessage getSignMessage(UserInfo userInfo, ApiInfo getSignMessageApiInfo) { HttpRequest request = createHttpRequest(getSignMessageApiInfo,userInfo); //参数 request.form("page", 1); request.form("size", 5); //得到返回的JSON并解析 String body = request.execute().body(); JSONObject data = (JSONObject) ((JSONArray) JSONUtil.parseObj(body).get("data")).get(0); return new SignMessage((String) data.getObj("id"), (String) data.get("logId")); } @Async public void sendSignRequest(UserInfo userInfo, ApiInfo signApiInfo, SignMessage signMessage) { HttpRequest request = createHttpRequest(signApiInfo,userInfo); //JSON data JSONObject data = new JSONObject(); data.set("id", signMessage.getLogId()); data.set("signId", signMessage.getId()); data.set("latitude", "23.090164"); data.set("longitude", "113.354053"); data.set("country", "中国"); data.set("province", "广东省"); data.set("district", "海珠区"); data.set("township", "官洲街道"); data.set("city", "广州市"); request.body(data.toString()); request.execute(); } public String GetJSON(UserInfo userInfo, ApiInfo getSignMessageApiInfo) { HttpRequest request = createHttpRequest(getSignMessageApiInfo,userInfo); //参数 request.form("page", 1); request.form("size", 5); //得到 <SUF> String body = request.execute().body(); return body; } public boolean needCheck(ApiInfo apiInfo,UserInfo userInfo, int seq){ HttpRequest request = createHttpRequest(apiInfo,userInfo); HttpResponse response = request.execute(); String body = response.body(); if(!JSONUtil.parseObj(body).containsKey("data")) return false; JSONObject data = (JSONObject) ((JSONArray) JSONUtil.parseObj(body).get("data")).get(seq-1); return Integer.parseInt(data.get("type").toString()) == 0; } public List<String> getAllNoSign(ApiInfo apiInfo,UserInfo userInfo, int seq){ HttpRequest request = createHttpRequest(apiInfo,userInfo); //body SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");// 设置日期格式 String date = df.format(new Date()); String httpbody = apiInfo.getBody().replace("seq=3", "seq=" + seq); httpbody = httpbody.replace("date=20201030","date="+date); request.body(httpbody); String body = request.execute().body(); if(!JSONUtil.parseObj(body).containsKey("data") ){ return null; }else{ List<String> list = new ArrayList<>(); JSONArray arr = (JSONArray) JSONUtil.parseObj(body).get("data"); for (int i = 0; i < arr.size() ; i++) { JSONObject stu = (JSONObject) arr.get(i); list.add((String) stu.get("userId")); } return list; } } public void replaceSign(ApiInfo apiInfo,UserInfo userInfo, int seq,String userId){ HttpRequest request = createHttpRequest(apiInfo,userInfo); //body String httpbody = apiInfo.getBody().replace("seq=", "seq=" + seq); httpbody = httpbody.replace("userId=","userId="+userId); request.body(httpbody); //return body request.execute(); } public boolean JudgeTokenIsValid(ApiInfo apiInfo,UserInfo userInfo){ HttpRequest request = createHttpRequest(apiInfo,userInfo); //得到返回的JSON并解析 String body = request.execute().body(); if(JSONUtil.parseObj(body).containsKey("data")) return true; else return false; } /** * 创建HttpRequest对象 */ private HttpRequest createHttpRequest(ApiInfo apiInfo,UserInfo userInfo) { //请求方法和请求url HttpRequest request = request = apiInfo.getMethod().equals(ApiConstant.METHOD_GET)?HttpRequest.get(apiInfo.getUrl()):HttpRequest.post(apiInfo.getUrl()); //报文头 request.contentType(apiInfo.getContenttype()); //token request.header("token", userInfo.getToken().trim());//总有混蛋 带空格存进来 return request; } }
0
1,236
7
1,384
7
1,466
7
1,384
7
1,673
12
false
false
false
false
false
true
36283_1
package com.boring.duanqifeng.tku; /* 段其沣于2017年10月9日 在四川大学江安校区创建 */ import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; public class Leibie extends AppCompatActivity { SharedPreferences sharedPreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_leibie); //每种类别的题目数 sharedPreferences = getSharedPreferences("TMS",MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putInt("gjs_danx",79); editor.putInt("gjs_dx",102); editor.putInt("gjs_pd",191); editor.putInt("jbz_danx",60); editor.putInt("jbz_dx",54); editor.putInt("jbz_lw",3); editor.putInt("jbz_pd",124); editor.putInt("jcjs_danx",47); editor.putInt("jcjs_dx",31); editor.putInt("jcjs_pd",58); editor.putInt("jl_danx",91); editor.putInt("jl_dx",21); editor.putInt("jl_pd",110); editor.putInt("jsll_danx",386); editor.putInt("jsll_dx",41); editor.putInt("jsll_pd",42); editor.putInt("nw_danx",84); editor.putInt("nw_dx",111); editor.putInt("nw_pd",18); editor.putInt("nw_lw",262); editor.putInt("xljc_danx",39); editor.putInt("xljc_dx",45); editor.putInt("xljc_pd",29); editor.putInt("zzjc_danx",24); editor.putInt("zzjc_dx",37); editor.putInt("zzjc_pd",42); editor.putInt("dl_danx",91); editor.putInt("dl_dx",18); editor.putInt("dl_pd",394); editor.apply(); Button 内务 = (Button) findViewById(R.id.内务); Button 队列 = (Button) findViewById(R.id.队列); Button 纪律 = (Button) findViewById(R.id.纪律); Button 军兵种 = (Button) findViewById(R.id.军兵种); Button 军事理论 = (Button) findViewById(R.id.军事理论); Button 军事高技术 = (Button) findViewById(R.id.军事高技术); Button 军队基层建设 = (Button) findViewById(R.id.军队基层建设); Button 训练基础理论 = (Button) findViewById(R.id.训练基础理论); Button 作战基础知识 = (Button) findViewById(R.id.作战基础知识); Button 模拟考试 = (Button) findViewById(R.id.kaoShi); Button 错题集 = (Button) findViewById(R.id.cuoTi); 内务.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Neiwu.class)); } }); 队列.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Duilie.class)); } }); 纪律.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Jilv.class)); } }); 军兵种.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Jbz.class)); } }); 军事理论.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Jsll.class)); } }); 军事高技术.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Gjs.class)); } }); 军队基层建设.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Jcjs.class)); } }); 训练基础理论.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Xljc.class)); } }); 作战基础知识.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Zzjc.class)); } }); 模拟考试.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Moni.class)); } }); 错题集.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Cuotiji.class)); } }); } }
Duanxiaoer/Android_TKU
app/src/main/java/com/boring/duanqifeng/tku/Leibie.java
1,362
//每种类别的题目数
line_comment
zh-cn
package com.boring.duanqifeng.tku; /* 段其沣于2017年10月9日 在四川大学江安校区创建 */ import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; public class Leibie extends AppCompatActivity { SharedPreferences sharedPreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_leibie); //每种 <SUF> sharedPreferences = getSharedPreferences("TMS",MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putInt("gjs_danx",79); editor.putInt("gjs_dx",102); editor.putInt("gjs_pd",191); editor.putInt("jbz_danx",60); editor.putInt("jbz_dx",54); editor.putInt("jbz_lw",3); editor.putInt("jbz_pd",124); editor.putInt("jcjs_danx",47); editor.putInt("jcjs_dx",31); editor.putInt("jcjs_pd",58); editor.putInt("jl_danx",91); editor.putInt("jl_dx",21); editor.putInt("jl_pd",110); editor.putInt("jsll_danx",386); editor.putInt("jsll_dx",41); editor.putInt("jsll_pd",42); editor.putInt("nw_danx",84); editor.putInt("nw_dx",111); editor.putInt("nw_pd",18); editor.putInt("nw_lw",262); editor.putInt("xljc_danx",39); editor.putInt("xljc_dx",45); editor.putInt("xljc_pd",29); editor.putInt("zzjc_danx",24); editor.putInt("zzjc_dx",37); editor.putInt("zzjc_pd",42); editor.putInt("dl_danx",91); editor.putInt("dl_dx",18); editor.putInt("dl_pd",394); editor.apply(); Button 内务 = (Button) findViewById(R.id.内务); Button 队列 = (Button) findViewById(R.id.队列); Button 纪律 = (Button) findViewById(R.id.纪律); Button 军兵种 = (Button) findViewById(R.id.军兵种); Button 军事理论 = (Button) findViewById(R.id.军事理论); Button 军事高技术 = (Button) findViewById(R.id.军事高技术); Button 军队基层建设 = (Button) findViewById(R.id.军队基层建设); Button 训练基础理论 = (Button) findViewById(R.id.训练基础理论); Button 作战基础知识 = (Button) findViewById(R.id.作战基础知识); Button 模拟考试 = (Button) findViewById(R.id.kaoShi); Button 错题集 = (Button) findViewById(R.id.cuoTi); 内务.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Neiwu.class)); } }); 队列.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Duilie.class)); } }); 纪律.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Jilv.class)); } }); 军兵种.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Jbz.class)); } }); 军事理论.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Jsll.class)); } }); 军事高技术.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Gjs.class)); } }); 军队基层建设.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Jcjs.class)); } }); 训练基础理论.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Xljc.class)); } }); 作战基础知识.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Zzjc.class)); } }); 模拟考试.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Moni.class)); } }); 错题集.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Cuotiji.class)); } }); } }
0
1,129
6
1,362
9
1,410
6
1,362
9
1,663
11
false
false
false
false
false
true
33092_8
package net.messi.early.controller; import net.messi.early.request.ProductInventoryCacheRefreshRequest; import net.messi.early.request.ProductInventoryDBUpdateRequest; import net.messi.early.request.Request; import net.messi.early.service.GoodsService; import net.messi.early.service.ProductInventoryService; import net.messi.early.service.RequestAsyncProcessService; import net.messi.early.utils.JSONResult; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("inventory") public class ProductInventoryController { @Autowired private GoodsService goodsService; @Autowired private RequestAsyncProcessService requestAsyncProcessService; @Autowired private ProductInventoryService productInventoryService; /** * 更新缓存 * * @param goodsId * @param inventoryCnt * @return */ @ResponseBody @RequestMapping("/updateInventory") public JSONResult updateInventory(Integer goodsId) { try { Request request = new ProductInventoryDBUpdateRequest(goodsId, goodsService); requestAsyncProcessService.process(request); } catch (Exception e) { e.printStackTrace(); } return JSONResult.ok(); } /** * 获取商品库存的缓存 * * @param goodsId * @return */ @ResponseBody @RequestMapping("/getInventory") public JSONResult getInventory(Integer goodsId) { try { Request request = new ProductInventoryCacheRefreshRequest(goodsId, goodsService); requestAsyncProcessService.process(request); long startTime = System.currentTimeMillis(); long endTime = 0L; long waitTime = 0L; Integer inventoryCnt = 0; //将请求仍给service异步处理以后,就需要while(true)一会儿,在这里hang住 //去尝试等待前面有商品库存更新的操作,同时缓存刷新的操作,将最新的数据刷新到缓存中 while (true) { if (waitTime > 200) { break; } //尝试去redis中读取一次商品库存的缓存 inventoryCnt = productInventoryService.getProductInventoryCache(goodsId); //如果读取到了结果,那么就返回 if (inventoryCnt != null) { return new JSONResult(inventoryCnt); } else { //如果没有读取到 Thread.sleep(20); endTime = System.currentTimeMillis(); waitTime = endTime - startTime; } } //直接从数据库查询 inventoryCnt = goodsService.lasteInventory(goodsId); if (inventoryCnt != null) return new JSONResult(inventoryCnt); } catch (Exception e) { e.printStackTrace(); } //没有查到 return JSONResult.ok(new Long(-1L)); } }
DuncanPlayer/quickearly
controller/ProductInventoryController.java
684
//没有查到
line_comment
zh-cn
package net.messi.early.controller; import net.messi.early.request.ProductInventoryCacheRefreshRequest; import net.messi.early.request.ProductInventoryDBUpdateRequest; import net.messi.early.request.Request; import net.messi.early.service.GoodsService; import net.messi.early.service.ProductInventoryService; import net.messi.early.service.RequestAsyncProcessService; import net.messi.early.utils.JSONResult; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("inventory") public class ProductInventoryController { @Autowired private GoodsService goodsService; @Autowired private RequestAsyncProcessService requestAsyncProcessService; @Autowired private ProductInventoryService productInventoryService; /** * 更新缓存 * * @param goodsId * @param inventoryCnt * @return */ @ResponseBody @RequestMapping("/updateInventory") public JSONResult updateInventory(Integer goodsId) { try { Request request = new ProductInventoryDBUpdateRequest(goodsId, goodsService); requestAsyncProcessService.process(request); } catch (Exception e) { e.printStackTrace(); } return JSONResult.ok(); } /** * 获取商品库存的缓存 * * @param goodsId * @return */ @ResponseBody @RequestMapping("/getInventory") public JSONResult getInventory(Integer goodsId) { try { Request request = new ProductInventoryCacheRefreshRequest(goodsId, goodsService); requestAsyncProcessService.process(request); long startTime = System.currentTimeMillis(); long endTime = 0L; long waitTime = 0L; Integer inventoryCnt = 0; //将请求仍给service异步处理以后,就需要while(true)一会儿,在这里hang住 //去尝试等待前面有商品库存更新的操作,同时缓存刷新的操作,将最新的数据刷新到缓存中 while (true) { if (waitTime > 200) { break; } //尝试去redis中读取一次商品库存的缓存 inventoryCnt = productInventoryService.getProductInventoryCache(goodsId); //如果读取到了结果,那么就返回 if (inventoryCnt != null) { return new JSONResult(inventoryCnt); } else { //如果没有读取到 Thread.sleep(20); endTime = System.currentTimeMillis(); waitTime = endTime - startTime; } } //直接从数据库查询 inventoryCnt = goodsService.lasteInventory(goodsId); if (inventoryCnt != null) return new JSONResult(inventoryCnt); } catch (Exception e) { e.printStackTrace(); } //没有 <SUF> return JSONResult.ok(new Long(-1L)); } }
0
628
4
684
4
731
4
684
4
923
5
false
false
false
false
false
true
64649_2
package org.lanqiao.algo.elementary._03sort; import org.assertj.core.api.Assertions; import org.lanqiao.algo.util.Util; import java.util.Arrays; /** * 思路:首先要知道大顶堆和小顶堆,数组就是一个堆,每个i节点的左右孩子是2i+1和2i+2<br /> * 有了堆,将其堆化:从n/2-1个元素开始向下修复,将每个节点修复为小(大)顶堆<br /> * 修复完成后,数组具有小(大)顶堆的性质<br /> * 按序输出:小顶堆可以对数组逆序排序,每次交换栈顶和末尾元素,对栈顶进行向下修复,这样次小元素又到堆顶了<br /> * * 时间复杂度: 堆化:一半的元素修复,修复是单分支的,所以整体堆化为nlgn/2<br /> * 排序:n个元素都要取出,因此调整n次,每次调整修复同上是lgn的,整体为nlgn * 空间复杂度:不需要开辟辅助空间<br /> * 原址排序<br /> * 稳定性:<br /> */ public class _7HeapSort { static void makeMinHeap(int[] A) { int n = A.length; for (int i = n / 2 - 1; i >= 0; i--) { MinHeapFixDown(A, i, n); } } static void MinHeapFixDown(int[] A, int i, int n) { // 找到左右孩子 int left = 2 * i + 1; int right = 2 * i + 2; //左孩子已经越界,i就是叶子节点 if (left >= n) { return; } int min = left; if (right >= n) { min = left; } else { if (A[right] < A[left]) { min = right; } } //min指向了左右孩子中较小的那个 // 如果A[i]比两个孩子都要小,不用调整 if (A[i] <= A[min]) { return; } //否则,找到两个孩子中较小的,和i交换 int temp = A[i]; A[i] = A[min]; A[min] = temp; //小孩子那个位置的值发生了变化,i变更为小孩子那个位置,递归调整 MinHeapFixDown(A, min, n); } // // public static void sortDesc(int[] arr) { // makeMinHeap( arr ); // 1.建立小顶堆 // int length = arr.length; // for (int i = length - 1; i >= 1; i--) { // Util.swap( arr, i, 0 ); // 堆顶(最小)元素换到元素末尾,末尾元素到了堆顶 // MinHeapFixDown( arr, 0, i );// 调整堆顶,边界递减 // } // } static void sort(int[] A) { //先对A进行堆化 makeMinHeap(A); for (int x = A.length - 1; x >= 0; x--) { //把堆顶,0号元素和最后一个元素对调 Util.swap(A, 0, x); //缩小堆的范围,对堆顶元素进行向下调整 MinHeapFixDown(A, 0, x); } } public static void main(String[] args) { int[] arr = Util.getRandomArr(10, 1, 100); System.out.println( "begin..." + Arrays.toString( arr ) ); sort(arr); System.out.println( "final..." + Arrays.toString( arr ) ); Assertions.assertThat( Util.checkOrdered( arr, false ) ).isTrue(); } }
Dxoca/Algorithm_LanQiao
src/main/java/org/lanqiao/algo/elementary/_03sort/_7HeapSort.java
982
//左孩子已经越界,i就是叶子节点
line_comment
zh-cn
package org.lanqiao.algo.elementary._03sort; import org.assertj.core.api.Assertions; import org.lanqiao.algo.util.Util; import java.util.Arrays; /** * 思路:首先要知道大顶堆和小顶堆,数组就是一个堆,每个i节点的左右孩子是2i+1和2i+2<br /> * 有了堆,将其堆化:从n/2-1个元素开始向下修复,将每个节点修复为小(大)顶堆<br /> * 修复完成后,数组具有小(大)顶堆的性质<br /> * 按序输出:小顶堆可以对数组逆序排序,每次交换栈顶和末尾元素,对栈顶进行向下修复,这样次小元素又到堆顶了<br /> * * 时间复杂度: 堆化:一半的元素修复,修复是单分支的,所以整体堆化为nlgn/2<br /> * 排序:n个元素都要取出,因此调整n次,每次调整修复同上是lgn的,整体为nlgn * 空间复杂度:不需要开辟辅助空间<br /> * 原址排序<br /> * 稳定性:<br /> */ public class _7HeapSort { static void makeMinHeap(int[] A) { int n = A.length; for (int i = n / 2 - 1; i >= 0; i--) { MinHeapFixDown(A, i, n); } } static void MinHeapFixDown(int[] A, int i, int n) { // 找到左右孩子 int left = 2 * i + 1; int right = 2 * i + 2; //左孩 <SUF> if (left >= n) { return; } int min = left; if (right >= n) { min = left; } else { if (A[right] < A[left]) { min = right; } } //min指向了左右孩子中较小的那个 // 如果A[i]比两个孩子都要小,不用调整 if (A[i] <= A[min]) { return; } //否则,找到两个孩子中较小的,和i交换 int temp = A[i]; A[i] = A[min]; A[min] = temp; //小孩子那个位置的值发生了变化,i变更为小孩子那个位置,递归调整 MinHeapFixDown(A, min, n); } // // public static void sortDesc(int[] arr) { // makeMinHeap( arr ); // 1.建立小顶堆 // int length = arr.length; // for (int i = length - 1; i >= 1; i--) { // Util.swap( arr, i, 0 ); // 堆顶(最小)元素换到元素末尾,末尾元素到了堆顶 // MinHeapFixDown( arr, 0, i );// 调整堆顶,边界递减 // } // } static void sort(int[] A) { //先对A进行堆化 makeMinHeap(A); for (int x = A.length - 1; x >= 0; x--) { //把堆顶,0号元素和最后一个元素对调 Util.swap(A, 0, x); //缩小堆的范围,对堆顶元素进行向下调整 MinHeapFixDown(A, 0, x); } } public static void main(String[] args) { int[] arr = Util.getRandomArr(10, 1, 100); System.out.println( "begin..." + Arrays.toString( arr ) ); sort(arr); System.out.println( "final..." + Arrays.toString( arr ) ); Assertions.assertThat( Util.checkOrdered( arr, false ) ).isTrue(); } }
0
879
11
982
14
969
11
982
14
1,301
20
false
false
false
false
false
true
16805_4
package comm; import java.sql.*; import java.util.Objects; import static comm.DBConfig.*; public class Card { private String cardID; private String userName; private String passWord; private int balance; private boolean exist; public int getBalance() { return balance; } // public void setBanlance(float banlance) {this.banlance = banlance;} public String getUserName() {return userName;} public void setUserName(String userName) {this.userName = userName; } public String getCardID() { return cardID; } public void setCardID(String cardID) { this.cardID = cardID; } public String getPassWord() { return passWord; } // public void setPassWord(String passWord) { // this.passWord = passWord; // } public Card(String cardID, String passWord, int balance){ this.cardID = cardID; this.passWord = passWord; this.balance = balance; getInfo(cardID); } public Card(String cardID){ getInfo(cardID); } //从数据库获取信息 public void getInfo(String cardID){ exist = false; Connection conn = null; Statement stmt = null; try{ // 注册 JDBC 驱动 Class.forName(JDBC_DRIVER); // 打开链接 System.out.println("连接数据库..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); // 执行查询 stmt = conn.createStatement(); String sql; sql = "SELECT CardID, UserName, PassWord, Balance FROM user where CardID =" + cardID; ResultSet rs = stmt.executeQuery(sql); // 展开结果集数据库 while(rs.next()){ // 通过字段检索 String id = rs.getString("CardID"); String name = rs.getString("UserName"); String pwd = rs.getString("PassWord"); int balance = rs.getInt("Balance"); // 输出数据 System.out.print("CardID: " + id); System.out.print(" UserName: " + name); System.out.print(" PassWord: " + pwd); System.out.print(" Balance: " + balance); System.out.print("\n"); this.cardID = id; this.userName = name; this.balance = balance; this.passWord=pwd; if(!Objects.equals(id, "")) exist=true; } // 完成后关闭 rs.close(); stmt.close(); conn.close(); }catch(SQLException se){ // 处理 JDBC 错误 se.printStackTrace(); }catch(Exception e){ // 处理 Class.forName 错误 e.printStackTrace(); }finally{ // 关闭资源 try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// 什么都不做 try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); } } } // 判断账号是否存在 public boolean exist(){ System.out.println(exist); return exist; } // 判断密码是否正确 public boolean judgePwd(String pwd){ return Objects.equals(pwd, this.passWord); } // 改密 public boolean setPassWord(String pwd){ if(exist()){ Connection conn = null; Statement stmt = null; try{ // 注册 JDBC 驱动 Class.forName(JDBC_DRIVER); // 打开链接 System.out.println("连接数据库..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); // 执行修改 stmt = conn.createStatement(); String sql; sql = "UPDATE user SET Password=? where CardID =?"; PreparedStatement pst = conn.prepareStatement(sql); pst.setString(1,pwd); pst.setString(2,cardID); pst.executeUpdate(); // 完成后关闭 stmt.close(); conn.close(); }catch(SQLException se){ // 处理 JDBC 错误 se.printStackTrace(); }catch(Exception e){ // 处理 Class.forName 错误 e.printStackTrace(); }finally{ // 关闭资源 try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// 什么都不做 try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); } } passWord=pwd; } return true; } //修改余额 public boolean setBanlance(int balance){ if(exist()){ Connection conn = null; Statement stmt = null; try{ // 注册 JDBC 驱动 Class.forName(JDBC_DRIVER); // 打开链接 System.out.println("连接数据库..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); // 执行修改 stmt = conn.createStatement(); String sql; sql = "UPDATE user SET Balance=? where CardID =?"; PreparedStatement pst = conn.prepareStatement(sql); pst.setInt(1,balance); pst.setString(2,cardID); pst.executeUpdate(); // 完成后关闭 stmt.close(); conn.close(); }catch(SQLException se){ // 处理 JDBC 错误 se.printStackTrace(); }catch(Exception e){ // 处理 Class.forName 错误 e.printStackTrace(); }finally{ // 关闭资源 try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// 什么都不做 try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); } } this.balance=balance; } return true; } }
Dycley/ATM
src/comm/Card.java
1,527
// 注册 JDBC 驱动
line_comment
zh-cn
package comm; import java.sql.*; import java.util.Objects; import static comm.DBConfig.*; public class Card { private String cardID; private String userName; private String passWord; private int balance; private boolean exist; public int getBalance() { return balance; } // public void setBanlance(float banlance) {this.banlance = banlance;} public String getUserName() {return userName;} public void setUserName(String userName) {this.userName = userName; } public String getCardID() { return cardID; } public void setCardID(String cardID) { this.cardID = cardID; } public String getPassWord() { return passWord; } // public void setPassWord(String passWord) { // this.passWord = passWord; // } public Card(String cardID, String passWord, int balance){ this.cardID = cardID; this.passWord = passWord; this.balance = balance; getInfo(cardID); } public Card(String cardID){ getInfo(cardID); } //从数据库获取信息 public void getInfo(String cardID){ exist = false; Connection conn = null; Statement stmt = null; try{ // 注册 <SUF> Class.forName(JDBC_DRIVER); // 打开链接 System.out.println("连接数据库..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); // 执行查询 stmt = conn.createStatement(); String sql; sql = "SELECT CardID, UserName, PassWord, Balance FROM user where CardID =" + cardID; ResultSet rs = stmt.executeQuery(sql); // 展开结果集数据库 while(rs.next()){ // 通过字段检索 String id = rs.getString("CardID"); String name = rs.getString("UserName"); String pwd = rs.getString("PassWord"); int balance = rs.getInt("Balance"); // 输出数据 System.out.print("CardID: " + id); System.out.print(" UserName: " + name); System.out.print(" PassWord: " + pwd); System.out.print(" Balance: " + balance); System.out.print("\n"); this.cardID = id; this.userName = name; this.balance = balance; this.passWord=pwd; if(!Objects.equals(id, "")) exist=true; } // 完成后关闭 rs.close(); stmt.close(); conn.close(); }catch(SQLException se){ // 处理 JDBC 错误 se.printStackTrace(); }catch(Exception e){ // 处理 Class.forName 错误 e.printStackTrace(); }finally{ // 关闭资源 try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// 什么都不做 try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); } } } // 判断账号是否存在 public boolean exist(){ System.out.println(exist); return exist; } // 判断密码是否正确 public boolean judgePwd(String pwd){ return Objects.equals(pwd, this.passWord); } // 改密 public boolean setPassWord(String pwd){ if(exist()){ Connection conn = null; Statement stmt = null; try{ // 注册 JDBC 驱动 Class.forName(JDBC_DRIVER); // 打开链接 System.out.println("连接数据库..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); // 执行修改 stmt = conn.createStatement(); String sql; sql = "UPDATE user SET Password=? where CardID =?"; PreparedStatement pst = conn.prepareStatement(sql); pst.setString(1,pwd); pst.setString(2,cardID); pst.executeUpdate(); // 完成后关闭 stmt.close(); conn.close(); }catch(SQLException se){ // 处理 JDBC 错误 se.printStackTrace(); }catch(Exception e){ // 处理 Class.forName 错误 e.printStackTrace(); }finally{ // 关闭资源 try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// 什么都不做 try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); } } passWord=pwd; } return true; } //修改余额 public boolean setBanlance(int balance){ if(exist()){ Connection conn = null; Statement stmt = null; try{ // 注册 JDBC 驱动 Class.forName(JDBC_DRIVER); // 打开链接 System.out.println("连接数据库..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); // 执行修改 stmt = conn.createStatement(); String sql; sql = "UPDATE user SET Balance=? where CardID =?"; PreparedStatement pst = conn.prepareStatement(sql); pst.setInt(1,balance); pst.setString(2,cardID); pst.executeUpdate(); // 完成后关闭 stmt.close(); conn.close(); }catch(SQLException se){ // 处理 JDBC 错误 se.printStackTrace(); }catch(Exception e){ // 处理 Class.forName 错误 e.printStackTrace(); }finally{ // 关闭资源 try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// 什么都不做 try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); } } this.balance=balance; } return true; } }
0
1,278
8
1,527
6
1,478
5
1,527
6
2,171
13
false
false
false
false
false
true
34199_18
package com.aochat.ui; import com.aochat.ui.module.*; import com.aochat.ui.module.Labels; import com.aochat.ui.module.Menu; import javax.swing.*; import java.awt.*; public class Frame { JPanel rootPanel = new JPanel(); // 新建根窗口 JFrame frame = new JFrame("AoChat"); // 初始化窗口,并命名 Menu menuBar = new Menu(rootPanel, frame); // 新建菜单栏 IPText ipText = new IPText(rootPanel); // 新建IP输入栏 PortTexts portTexts = new PortTexts(rootPanel); // 新建端口输入栏 EnterTextArea enterTextArea = new EnterTextArea(rootPanel); // 新建信息输入栏 public MessageArea messageArea = new MessageArea(rootPanel); // 新建消息输入栏 Labels labels = new Labels(rootPanel); // 新建信息栏 Buttons buttons = new Buttons(rootPanel, menuBar); // 新建按钮组 public Frame(){ panelInit(); // 窗口初始化 setPosition(); // 设置每个组件位置 addActionListener(); // 添加监听器 } private void panelInit(){ // 窗口初始化 // 设置图标 Toolkit took = Toolkit.getDefaultToolkit(); Image image = took.getImage("src/img/icon.png"); frame.setIconImage(image); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 关闭窗口时关闭进程 frame.setContentPane(rootPanel); // 容器添加到面板 frame.setResizable(false); // 不准改大小 frame.setSize(800, 600); // 设置窗口大小 frame.setVisible(true); // 显示窗口 } private void setPosition(){ // 设置每个组件位置 rootPanel.setLayout(null);// 禁用布局器 menuBar.setPosition(); enterTextArea.setPosition(); ipText.setPosition(); portTexts.setPosition(); messageArea.setPosition(); labels.setPosition(); buttons.setPosition(); } private void addActionListener(){ // 添加监听器 menuBar.addActionListener(); buttons.addButtonActionListener(enterTextArea, ipText, portTexts, messageArea, labels, menuBar.ipHistorySet); } }
DylanAo/AHU-AI-Repository
专业选修课/Java/AoChat/com/aochat/ui/Frame.java
519
// 显示窗口
line_comment
zh-cn
package com.aochat.ui; import com.aochat.ui.module.*; import com.aochat.ui.module.Labels; import com.aochat.ui.module.Menu; import javax.swing.*; import java.awt.*; public class Frame { JPanel rootPanel = new JPanel(); // 新建根窗口 JFrame frame = new JFrame("AoChat"); // 初始化窗口,并命名 Menu menuBar = new Menu(rootPanel, frame); // 新建菜单栏 IPText ipText = new IPText(rootPanel); // 新建IP输入栏 PortTexts portTexts = new PortTexts(rootPanel); // 新建端口输入栏 EnterTextArea enterTextArea = new EnterTextArea(rootPanel); // 新建信息输入栏 public MessageArea messageArea = new MessageArea(rootPanel); // 新建消息输入栏 Labels labels = new Labels(rootPanel); // 新建信息栏 Buttons buttons = new Buttons(rootPanel, menuBar); // 新建按钮组 public Frame(){ panelInit(); // 窗口初始化 setPosition(); // 设置每个组件位置 addActionListener(); // 添加监听器 } private void panelInit(){ // 窗口初始化 // 设置图标 Toolkit took = Toolkit.getDefaultToolkit(); Image image = took.getImage("src/img/icon.png"); frame.setIconImage(image); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 关闭窗口时关闭进程 frame.setContentPane(rootPanel); // 容器添加到面板 frame.setResizable(false); // 不准改大小 frame.setSize(800, 600); // 设置窗口大小 frame.setVisible(true); // 显示 <SUF> } private void setPosition(){ // 设置每个组件位置 rootPanel.setLayout(null);// 禁用布局器 menuBar.setPosition(); enterTextArea.setPosition(); ipText.setPosition(); portTexts.setPosition(); messageArea.setPosition(); labels.setPosition(); buttons.setPosition(); } private void addActionListener(){ // 添加监听器 menuBar.addActionListener(); buttons.addButtonActionListener(enterTextArea, ipText, portTexts, messageArea, labels, menuBar.ipHistorySet); } }
0
482
5
515
5
541
4
515
5
733
9
false
false
false
false
false
true
24092_10
package com.dyman.opencvtest.utils; import android.graphics.Bitmap; import android.util.Log; import org.opencv.android.Utils; import org.opencv.core.Mat; import org.opencv.core.MatOfPoint; import org.opencv.core.MatOfPoint2f; import org.opencv.core.Point; import org.opencv.core.RotatedRect; import org.opencv.core.Size; import org.opencv.imgproc.Imgproc; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * Created by dyman on 2017/8/12. * * 智能选区帮助类 */ public class Scanner { private static final String TAG = "Scanner"; private static int resizeThreshold = 500; private static float resizeScale = 1.0f; /** 扫描图片,并返回检测到的矩形的四个顶点的坐标 */ public static android.graphics.Point[] scanPoint(Bitmap srcBitmap) { Mat srcMat = new Mat(); Utils.bitmapToMat(srcBitmap, srcMat); // 图像缩放 Mat image = resizeImage(srcMat); // 图像预处理 Mat scanImage = preProcessImage(image); List<MatOfPoint> contours = new ArrayList<>(); // 检测到的轮廓 Mat hierarchy = new Mat(); // 各轮廓的继承关系 // 提取边框 Imgproc.findContours(scanImage, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_NONE); // 按面积排序,最后只取面积最大的那个 Collections.sort(contours, new Comparator<MatOfPoint>() { @Override public int compare(MatOfPoint matOfPoint1, MatOfPoint matOfPoint2) { double oneArea = Math.abs(Imgproc.contourArea(matOfPoint1)); double twoArea = Math.abs(Imgproc.contourArea(matOfPoint2)); return Double.compare(twoArea, oneArea); } }); Point[] resultArr = new Point[4]; if (contours.size() > 0) { Log.i(TAG, "scanPoint: -------------contours.size="+contours.size()); // 取面积最大的 MatOfPoint2f contour2f = new MatOfPoint2f(contours.get(0).toArray()); double arc = Imgproc.arcLength(contour2f, true); MatOfPoint2f outDpMat = new MatOfPoint2f(); Imgproc.approxPolyDP(contour2f, outDpMat, 0.02 * arc, true); // 多边形逼近 // 筛选去除相近的点 MatOfPoint2f selectMat = selectPoint(outDpMat, 1); if (selectMat.toArray().length != 4) { // 不是四边形,使用最小矩形包裹 RotatedRect rotatedRect = Imgproc.minAreaRect(selectMat); rotatedRect.points(resultArr); } else { resultArr = selectMat.toArray(); } // 比例还原 for (Point p : resultArr) { p.x *= resizeScale; p.y *= resizeScale; } } // 对最终检测出的四个点进行排序:左上、右上、右下、坐下 Point[] result = sortPointClockwise(resultArr); android.graphics.Point[] rs = new android.graphics.Point[result.length]; for (int i = 0; i < result.length; i++) { android.graphics.Point p = new android.graphics.Point((int) result[i].x, (int) result[i].y); rs[i] = p; } return rs; } /** * 为避免处理时间过长,先对图片进行压缩 * @param image * @return */ private static Mat resizeImage(Mat image) { int width = image.cols(); int height = image.rows(); int maxSize = width > height ? width : height; if (maxSize > resizeThreshold) { resizeScale = 1.0f * maxSize / resizeThreshold; width = (int) (width / resizeScale); height = (int) (height / resizeScale); Size size = new Size(width, height); Mat resizeMat = new Mat(); Imgproc.resize(image, resizeMat, size); return resizeMat; } return image; } /** * 对图像进行预处理:灰度化、高斯模糊、Canny边缘检测 * @param image * @return */ private static Mat preProcessImage(Mat image) { Mat grayMat = new Mat(); Imgproc.cvtColor(image, grayMat, Imgproc.COLOR_RGB2GRAY); // 注意RGB和BGR,影响很大 Mat blurMat = new Mat(); Imgproc.GaussianBlur(grayMat, blurMat, new Size(5,5), 0); Mat cannyMat = new Mat(); Imgproc.Canny(blurMat, cannyMat, 0, 5); Mat thresholdMat = new Mat(); Imgproc.threshold(cannyMat, thresholdMat, 0, 255, Imgproc.THRESH_OTSU); return cannyMat; } /** 过滤掉距离相近的点 */ private static MatOfPoint2f selectPoint(MatOfPoint2f outDpMat, int selectTimes) { List<Point> pointList = new ArrayList<>(); pointList.addAll(outDpMat.toList()); if (pointList.size() > 4) { double arc = Imgproc.arcLength(outDpMat, true); for (int i = pointList.size() - 1; i >= 0; i--) { if (pointList.size() == 4) { Point[] resultPoints = new Point[pointList.size()]; for (int j = 0; j < pointList.size(); j++) { resultPoints[j] = pointList.get(j); } return new MatOfPoint2f(resultPoints); } if (i != pointList.size() - 1) { Point itor = pointList.get(i); Point lastP = pointList.get(i + 1); double pointLength = Math.sqrt(Math.pow(itor.x-lastP.x, 2) + Math.pow(itor.y - lastP.y, 2)); if (pointLength < arc * 0.01 * selectTimes && pointList.size() > 4) { pointList.remove(i); } } } if (pointList.size() > 4) { // 要手动逐个强转 Point[] againPoints = new Point[pointList.size()]; for (int i = 0; i < pointList.size(); i++) { againPoints[i] = pointList.get(i); } return selectPoint(new MatOfPoint2f(againPoints), selectTimes + 1); } } return outDpMat; } /** 对顶点进行排序 */ private static Point[] sortPointClockwise(Point[] points) { if (points.length != 4) { return points; } Point unFoundPoint = new Point(); Point[] result = {unFoundPoint, unFoundPoint, unFoundPoint, unFoundPoint}; long minDistance = -1; for (Point point : points) { long distance = (long) (point.x * point.x + point.y * point.y); if (minDistance == -1 || distance < minDistance) { result[0] = point; minDistance = distance; } } if (result[0] != unFoundPoint) { Point leftTop = result[0]; Point[] p1 = new Point[3]; int i = 0; for (Point point : points) { if (point.x == leftTop.x && point.y == leftTop.y) continue; p1[i] = point; i++; } if ((pointSideLine(leftTop, p1[0], p1[1]) * pointSideLine(leftTop, p1[0], p1[2])) < 0) { result[2] = p1[0]; } else if ((pointSideLine(leftTop, p1[1], p1[0]) * pointSideLine(leftTop, p1[1], p1[2])) < 0) { result[2] = p1[1]; } else if ((pointSideLine(leftTop, p1[2], p1[0]) * pointSideLine(leftTop, p1[2], p1[1])) < 0) { result[2] = p1[2]; } } if (result[0] != unFoundPoint && result[2] != unFoundPoint) { Point leftTop = result[0]; Point rightBottom = result[2]; Point[] p1 = new Point[2]; int i = 0; for (Point point : points) { if (point.x == leftTop.x && point.y == leftTop.y) continue; if (point.x == rightBottom.x && point.y == rightBottom.y) continue; p1[i] = point; i++; } if (pointSideLine(leftTop, rightBottom, p1[0]) > 0) { result[1] = p1[0]; result[3] = p1[1]; } else { result[1] = p1[1]; result[3] = p1[0]; } } if (result[0] != unFoundPoint && result[1] != unFoundPoint && result[2] != unFoundPoint && result[3] != unFoundPoint) { return result; } return points; } private static double pointSideLine(Point lineP1, Point lineP2, Point point) { double x1 = lineP1.x; double y1 = lineP1.y; double x2 = lineP2.x; double y2 = lineP2.y; double x = point.x; double y = point.y; return (x - x1)*(y2 - y1) - (y - y1)*(x2 - x1); } }
DymanZy/OpenCVTest
app/src/main/java/com/dyman/opencvtest/utils/Scanner.java
2,479
// 筛选去除相近的点
line_comment
zh-cn
package com.dyman.opencvtest.utils; import android.graphics.Bitmap; import android.util.Log; import org.opencv.android.Utils; import org.opencv.core.Mat; import org.opencv.core.MatOfPoint; import org.opencv.core.MatOfPoint2f; import org.opencv.core.Point; import org.opencv.core.RotatedRect; import org.opencv.core.Size; import org.opencv.imgproc.Imgproc; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * Created by dyman on 2017/8/12. * * 智能选区帮助类 */ public class Scanner { private static final String TAG = "Scanner"; private static int resizeThreshold = 500; private static float resizeScale = 1.0f; /** 扫描图片,并返回检测到的矩形的四个顶点的坐标 */ public static android.graphics.Point[] scanPoint(Bitmap srcBitmap) { Mat srcMat = new Mat(); Utils.bitmapToMat(srcBitmap, srcMat); // 图像缩放 Mat image = resizeImage(srcMat); // 图像预处理 Mat scanImage = preProcessImage(image); List<MatOfPoint> contours = new ArrayList<>(); // 检测到的轮廓 Mat hierarchy = new Mat(); // 各轮廓的继承关系 // 提取边框 Imgproc.findContours(scanImage, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_NONE); // 按面积排序,最后只取面积最大的那个 Collections.sort(contours, new Comparator<MatOfPoint>() { @Override public int compare(MatOfPoint matOfPoint1, MatOfPoint matOfPoint2) { double oneArea = Math.abs(Imgproc.contourArea(matOfPoint1)); double twoArea = Math.abs(Imgproc.contourArea(matOfPoint2)); return Double.compare(twoArea, oneArea); } }); Point[] resultArr = new Point[4]; if (contours.size() > 0) { Log.i(TAG, "scanPoint: -------------contours.size="+contours.size()); // 取面积最大的 MatOfPoint2f contour2f = new MatOfPoint2f(contours.get(0).toArray()); double arc = Imgproc.arcLength(contour2f, true); MatOfPoint2f outDpMat = new MatOfPoint2f(); Imgproc.approxPolyDP(contour2f, outDpMat, 0.02 * arc, true); // 多边形逼近 // 筛选 <SUF> MatOfPoint2f selectMat = selectPoint(outDpMat, 1); if (selectMat.toArray().length != 4) { // 不是四边形,使用最小矩形包裹 RotatedRect rotatedRect = Imgproc.minAreaRect(selectMat); rotatedRect.points(resultArr); } else { resultArr = selectMat.toArray(); } // 比例还原 for (Point p : resultArr) { p.x *= resizeScale; p.y *= resizeScale; } } // 对最终检测出的四个点进行排序:左上、右上、右下、坐下 Point[] result = sortPointClockwise(resultArr); android.graphics.Point[] rs = new android.graphics.Point[result.length]; for (int i = 0; i < result.length; i++) { android.graphics.Point p = new android.graphics.Point((int) result[i].x, (int) result[i].y); rs[i] = p; } return rs; } /** * 为避免处理时间过长,先对图片进行压缩 * @param image * @return */ private static Mat resizeImage(Mat image) { int width = image.cols(); int height = image.rows(); int maxSize = width > height ? width : height; if (maxSize > resizeThreshold) { resizeScale = 1.0f * maxSize / resizeThreshold; width = (int) (width / resizeScale); height = (int) (height / resizeScale); Size size = new Size(width, height); Mat resizeMat = new Mat(); Imgproc.resize(image, resizeMat, size); return resizeMat; } return image; } /** * 对图像进行预处理:灰度化、高斯模糊、Canny边缘检测 * @param image * @return */ private static Mat preProcessImage(Mat image) { Mat grayMat = new Mat(); Imgproc.cvtColor(image, grayMat, Imgproc.COLOR_RGB2GRAY); // 注意RGB和BGR,影响很大 Mat blurMat = new Mat(); Imgproc.GaussianBlur(grayMat, blurMat, new Size(5,5), 0); Mat cannyMat = new Mat(); Imgproc.Canny(blurMat, cannyMat, 0, 5); Mat thresholdMat = new Mat(); Imgproc.threshold(cannyMat, thresholdMat, 0, 255, Imgproc.THRESH_OTSU); return cannyMat; } /** 过滤掉距离相近的点 */ private static MatOfPoint2f selectPoint(MatOfPoint2f outDpMat, int selectTimes) { List<Point> pointList = new ArrayList<>(); pointList.addAll(outDpMat.toList()); if (pointList.size() > 4) { double arc = Imgproc.arcLength(outDpMat, true); for (int i = pointList.size() - 1; i >= 0; i--) { if (pointList.size() == 4) { Point[] resultPoints = new Point[pointList.size()]; for (int j = 0; j < pointList.size(); j++) { resultPoints[j] = pointList.get(j); } return new MatOfPoint2f(resultPoints); } if (i != pointList.size() - 1) { Point itor = pointList.get(i); Point lastP = pointList.get(i + 1); double pointLength = Math.sqrt(Math.pow(itor.x-lastP.x, 2) + Math.pow(itor.y - lastP.y, 2)); if (pointLength < arc * 0.01 * selectTimes && pointList.size() > 4) { pointList.remove(i); } } } if (pointList.size() > 4) { // 要手动逐个强转 Point[] againPoints = new Point[pointList.size()]; for (int i = 0; i < pointList.size(); i++) { againPoints[i] = pointList.get(i); } return selectPoint(new MatOfPoint2f(againPoints), selectTimes + 1); } } return outDpMat; } /** 对顶点进行排序 */ private static Point[] sortPointClockwise(Point[] points) { if (points.length != 4) { return points; } Point unFoundPoint = new Point(); Point[] result = {unFoundPoint, unFoundPoint, unFoundPoint, unFoundPoint}; long minDistance = -1; for (Point point : points) { long distance = (long) (point.x * point.x + point.y * point.y); if (minDistance == -1 || distance < minDistance) { result[0] = point; minDistance = distance; } } if (result[0] != unFoundPoint) { Point leftTop = result[0]; Point[] p1 = new Point[3]; int i = 0; for (Point point : points) { if (point.x == leftTop.x && point.y == leftTop.y) continue; p1[i] = point; i++; } if ((pointSideLine(leftTop, p1[0], p1[1]) * pointSideLine(leftTop, p1[0], p1[2])) < 0) { result[2] = p1[0]; } else if ((pointSideLine(leftTop, p1[1], p1[0]) * pointSideLine(leftTop, p1[1], p1[2])) < 0) { result[2] = p1[1]; } else if ((pointSideLine(leftTop, p1[2], p1[0]) * pointSideLine(leftTop, p1[2], p1[1])) < 0) { result[2] = p1[2]; } } if (result[0] != unFoundPoint && result[2] != unFoundPoint) { Point leftTop = result[0]; Point rightBottom = result[2]; Point[] p1 = new Point[2]; int i = 0; for (Point point : points) { if (point.x == leftTop.x && point.y == leftTop.y) continue; if (point.x == rightBottom.x && point.y == rightBottom.y) continue; p1[i] = point; i++; } if (pointSideLine(leftTop, rightBottom, p1[0]) > 0) { result[1] = p1[0]; result[3] = p1[1]; } else { result[1] = p1[1]; result[3] = p1[0]; } } if (result[0] != unFoundPoint && result[1] != unFoundPoint && result[2] != unFoundPoint && result[3] != unFoundPoint) { return result; } return points; } private static double pointSideLine(Point lineP1, Point lineP2, Point point) { double x1 = lineP1.x; double y1 = lineP1.y; double x2 = lineP2.x; double y2 = lineP2.y; double x = point.x; double y = point.y; return (x - x1)*(y2 - y1) - (y - y1)*(x2 - x1); } }
0
2,294
10
2,478
12
2,611
8
2,479
12
2,927
12
false
false
false
false
false
true
19394_1
package dynamilize; /**所有动态对象依赖的接口,描述了动态对象具有的基本行为,关于接口的实现应当由生成器生成。 * <p>实现此接口通常不应该从外部进行,而应当通过{@link DynamicMaker#makeClassInfo(Class, Class[], Class[])}生成,对于生成器生成的实现类应当满足下列行为: * <ul> * <li>分配对象保存{@linkplain DataPool 数据池}的字段,字段具有private final修饰符 * <li>分配对象保存{@linkplain DynamicClass 动态类}的字段,字段具有private final修饰符 * <li>对每一个超类构造函数生成相应的构造函数,并正确的调用超类的相应超类构造函数 * 参数前新增两个参数分别传入{@linkplain DataPool 数据池}和{@linkplain DynamicClass 动态类}并分配给成员字段 * <li>按此接口内的方法说明,实现接口的各抽象方法 * </ul> * 且委托类型的构造函数应当从{@link DynamicMaker}中的几个newInstance调用,否则你必须为之提供合适的构造函数参数 * * @author EBwilson */ @SuppressWarnings("unchecked") public interface DynamicObject<Self>{ /**获取对象的动态类型 * <p>生成器实施应当实现此方法返回生成的动态类型字段 * * @return 此对象的动态类型*/ DynamicClass getDyClass(); /**获得对象的成员变量 * <p>生成器实施应当实现此方法使之调用数据池的{@link DataPool#getVariable(String)}方法并返回值 * * @param name 变量名称 * @return 变量的值*/ IVariable getVariable(String name); DataPool.ReadOnlyPool baseSuperPointer(); /**设置对象的成员变量 * <p>生成器实施应当实现此方法使之调用数据池的{@link DataPool#setVariable(IVariable)}方法,自身的参数分别传入 * * @param variable 将设置的变量*/ void setVariable(IVariable variable); /**获取对象的某一成员变量的值,若变量尚未定义则会抛出异常 * * @param name 变量名 * @return 变量值*/ default <T> T getVar(String name){ IVariable var = getVariable(name); if(var == null) throw new IllegalHandleException("variable " + name + " was not defined"); return var.get(this); } /**为对象的某一变量设置属性值,若在层次结构中未能找到变量则会定义变量 * * @param name 变量名 * @param value 属性值*/ default <T> void setVar(String name, T value){ IVariable var = getVariable(name); if(var == null){ var = new Variable(name); setVariable(var); } var.set(this, value); } <T> T varValueGet(String name); <T> void varValueSet(String name, T value); /**使用给出的运算器对指定名称的变量进行处理,并用其计算结果设置变量值 * * @param name 变量名称 * @param calculator 计算器 * @return 计算结果*/ default <T> T calculateVar(String name, Calculator<T> calculator){ T res; setVar(name, res = calculator.calculate(getVar(name))); return res; } /**获取对象的函数的匿名函数表示 * <p>生成器实施应当实现此方法使之调用数据池的{@link DataPool#select(String, FunctionType)}方法并返回值 * * @param name 函数名称 * @param type 函数的参数类型 * @return 指定函数的匿名表示*/ IFunctionEntry getFunc(String name, FunctionType type); default <R> Delegate<R> getFunction(String name, FunctionType type){ IFunctionEntry entry = getFunc(name, type); if(entry == null) throw new IllegalHandleException("no such function: " + name + type); return a -> (R) entry.<Self, R>getFunction().invoke(this, a); } default <R> Delegate<R> getFunction(String name, Class<?>... types){ FunctionType type = FunctionType.inst(types); Delegate<R> f = getFunction(name, type); type.recycle(); return f; } default <R> Function<Self, R> getFunc(String name, Class<?>... types){ FunctionType type = FunctionType.inst(types); Function<Self, R> f = getFunc(name, type).getFunction(); type.recycle(); return f; } /**以lambda模式设置对象的成员函数,lambda模式下对对象的函数变更仅对此对象有效,变更即时生效, * 若需要使变更对所有实例都生效,则应当对此对象的动态类型引用{@link DynamicClass#visitClass(Class, JavaHandleHelper)}方法变更行为样版 * <p>生成器实施应当实现此方法使之调用数据池的{@link DataPool#setFunction(String, Function, Class[])}方法,并将参数一一对应传入 * <p><strong>注意,含有泛型的参数,无论类型参数如何,形式参数类型始终为{@link Object}</strong> * * @param name 设置的函数名称 * @param func 描述函数行为的匿名函数 * @param argTypes 形式参数的类型列表*/ <R> void setFunc(String name, Function<Self, R> func, Class<?>... argTypes); <R> void setFunc(String name, Function.SuperGetFunction<Self, R> func, Class<?>... argTypes); /**与{@link DynamicObject#setFunc(String, Function, Class[])}效果一致,只是传入的函数没有返回值*/ default void setFunc(String name, Function.NonRetFunction<Self> func, Class<?>... argTypes){ setFunc(name, (s, a) -> { func.invoke(s, a); return null; }, argTypes); } /**与{@link DynamicObject#setFunc(String, Function.SuperGetFunction, Class[])}效果一致,只是传入的函数没有返回值*/ default void setFunc(String name, Function.NonRetSuperGetFunc<Self> func, Class<?>... argTypes){ setFunc(name, (s, sup, a) -> { func.invoke(s, sup, a); return null; }, argTypes); } /**执行对象的指定成员函数 * * @param name 函数名称 * @param args 传递给函数的实参列表 * @return 函数返回值*/ default <R> R invokeFunc(String name, Object... args){ ArgumentList lis = ArgumentList.as(args); R r = invokeFunc(name, lis); lis.type().recycle(); lis.recycle(); return r; } /**指明形式参数列表执行对象的指定成员函数,如果参数中有从类型派生的对象或者null值,使用type明确指定形参类型可以有效提升执行效率 * * @param name 函数名称 * @param args 传递给函数的实参列表 * @return 函数返回值*/ default <R> R invokeFunc(FunctionType type, String name, Object... args){ ArgumentList lis = ArgumentList.asWithType(type, args); R r = invokeFunc(name, lis); lis.recycle(); return r; } /**直接传入{@link ArgumentList}作为实参列表的函数调用,方法内完成拆箱,便于在匿名函数中对另一函数进行引用而无需拆箱 * * @param name 函数名称 * @param args 是按列表的封装对象 * @return 函数返回值*/ default <R> R invokeFunc(String name, ArgumentList args){ FunctionType type = args.type(); Function<Self, R> res = getFunc(name, type).getFunction(); if(res == null) throw new IllegalHandleException("no such method declared: " + name); return res.invoke( this, args); } /**将对象自身经过一次强转换并返回*/ default <T extends Self> T objSelf(){ return (T) this; } //primitive getters and setters //我讨厌装箱类型,是的,相当讨厌...... default boolean getVar(String name, boolean def){ IVariable var = getVariable(name); if(var == null) throw new IllegalHandleException("variable " + name + " was not defined"); return var.get(this, def); } default byte getVar(String name, byte def){ IVariable var = getVariable(name); if(var == null) throw new IllegalHandleException("variable " + name + " was not defined"); return var.get(this, def); } default short getVar(String name, short def){ IVariable var = getVariable(name); if(var == null) throw new IllegalHandleException("variable " + name + " was not defined"); return var.get(this, def); } default int getVar(String name, int def){ IVariable var = getVariable(name); if(var == null) throw new IllegalHandleException("variable " + name + " was not defined"); return var.get(this, def); } default long getVar(String name, long def){ IVariable var = getVariable(name); if(var == null) throw new IllegalHandleException("variable " + name + " was not defined"); return var.get(this, def); } default float getVar(String name, float def){ IVariable var = getVariable(name); if(var == null) throw new IllegalHandleException("variable " + name + " was not defined"); return var.get(this, def); } default double getVar(String name, double def){ IVariable var = getVariable(name); if(var == null) throw new IllegalHandleException("variable " + name + " was not defined"); return var.get(this, def); } default void setVar(String name, boolean value){ IVariable var = getVariable(name); if(var == null){ var = new Variable(name); setVariable(var); } var.set(this, value); } default void setVar(String name, byte value){ IVariable var = getVariable(name); if(var == null){ var = new Variable(name); setVariable(var); } var.set(this, value); } default void setVar(String name, short value){ IVariable var = getVariable(name); if(var == null){ var = new Variable(name); setVariable(var); } var.set(this, value); } default void setVar(String name, int value){ IVariable var = getVariable(name); if(var == null){ var = new Variable(name); setVariable(var); } var.set(this, value); } default void setVar(String name, long value){ IVariable var = getVariable(name); if(var == null){ var = new Variable(name); setVariable(var); } var.set(this, value); } default void setVar(String name, float value){ IVariable var = getVariable(name); if(var == null){ var = new Variable(name); setVariable(var); } var.set(this, value); } default void setVar(String name, double value){ IVariable var = getVariable(name); if(var == null){ var = new Variable(name); setVariable(var); } var.set(this, value); } default boolean calculateVar(String name, Calculator.BoolCalculator calculator){ boolean res; setVar(name, res = calculator.calculate(getVar(name))); return res; } default byte calculateVar(String name, Calculator.ByteCalculator calculator){ byte res; setVar(name, res = calculator.calculate(getVar(name))); return res; } default short calculateVar(String name, Calculator.ShortCalculator calculator){ short res; setVar(name, res = calculator.calculate(getVar(name))); return res; } default int calculateVar(String name, Calculator.IntCalculator calculator){ int res; setVar(name, res = calculator.calculate(getVar(name))); return res; } default long calculateVar(String name, Calculator.LongCalculator calculator){ long res; setVar(name, res = calculator.calculate(getVar(name))); return res; } default float calculateVar(String name, Calculator.FloatCalculator calculator){ float res; setVar(name, res = calculator.calculate(getVar(name))); return res; } default double calculateVar(String name, Calculator.DoubleCalculator calculator){ double res; setVar(name, res = calculator.calculate(getVar(name))); return res; } }
EB-wilson/JavaDynamilizer
core/src/main/java/dynamilize/DynamicObject.java
3,041
/**获取对象的动态类型 * <p>生成器实施应当实现此方法返回生成的动态类型字段 * * @return 此对象的动态类型*/
block_comment
zh-cn
package dynamilize; /**所有动态对象依赖的接口,描述了动态对象具有的基本行为,关于接口的实现应当由生成器生成。 * <p>实现此接口通常不应该从外部进行,而应当通过{@link DynamicMaker#makeClassInfo(Class, Class[], Class[])}生成,对于生成器生成的实现类应当满足下列行为: * <ul> * <li>分配对象保存{@linkplain DataPool 数据池}的字段,字段具有private final修饰符 * <li>分配对象保存{@linkplain DynamicClass 动态类}的字段,字段具有private final修饰符 * <li>对每一个超类构造函数生成相应的构造函数,并正确的调用超类的相应超类构造函数 * 参数前新增两个参数分别传入{@linkplain DataPool 数据池}和{@linkplain DynamicClass 动态类}并分配给成员字段 * <li>按此接口内的方法说明,实现接口的各抽象方法 * </ul> * 且委托类型的构造函数应当从{@link DynamicMaker}中的几个newInstance调用,否则你必须为之提供合适的构造函数参数 * * @author EBwilson */ @SuppressWarnings("unchecked") public interface DynamicObject<Self>{ /**获取对 <SUF>*/ DynamicClass getDyClass(); /**获得对象的成员变量 * <p>生成器实施应当实现此方法使之调用数据池的{@link DataPool#getVariable(String)}方法并返回值 * * @param name 变量名称 * @return 变量的值*/ IVariable getVariable(String name); DataPool.ReadOnlyPool baseSuperPointer(); /**设置对象的成员变量 * <p>生成器实施应当实现此方法使之调用数据池的{@link DataPool#setVariable(IVariable)}方法,自身的参数分别传入 * * @param variable 将设置的变量*/ void setVariable(IVariable variable); /**获取对象的某一成员变量的值,若变量尚未定义则会抛出异常 * * @param name 变量名 * @return 变量值*/ default <T> T getVar(String name){ IVariable var = getVariable(name); if(var == null) throw new IllegalHandleException("variable " + name + " was not defined"); return var.get(this); } /**为对象的某一变量设置属性值,若在层次结构中未能找到变量则会定义变量 * * @param name 变量名 * @param value 属性值*/ default <T> void setVar(String name, T value){ IVariable var = getVariable(name); if(var == null){ var = new Variable(name); setVariable(var); } var.set(this, value); } <T> T varValueGet(String name); <T> void varValueSet(String name, T value); /**使用给出的运算器对指定名称的变量进行处理,并用其计算结果设置变量值 * * @param name 变量名称 * @param calculator 计算器 * @return 计算结果*/ default <T> T calculateVar(String name, Calculator<T> calculator){ T res; setVar(name, res = calculator.calculate(getVar(name))); return res; } /**获取对象的函数的匿名函数表示 * <p>生成器实施应当实现此方法使之调用数据池的{@link DataPool#select(String, FunctionType)}方法并返回值 * * @param name 函数名称 * @param type 函数的参数类型 * @return 指定函数的匿名表示*/ IFunctionEntry getFunc(String name, FunctionType type); default <R> Delegate<R> getFunction(String name, FunctionType type){ IFunctionEntry entry = getFunc(name, type); if(entry == null) throw new IllegalHandleException("no such function: " + name + type); return a -> (R) entry.<Self, R>getFunction().invoke(this, a); } default <R> Delegate<R> getFunction(String name, Class<?>... types){ FunctionType type = FunctionType.inst(types); Delegate<R> f = getFunction(name, type); type.recycle(); return f; } default <R> Function<Self, R> getFunc(String name, Class<?>... types){ FunctionType type = FunctionType.inst(types); Function<Self, R> f = getFunc(name, type).getFunction(); type.recycle(); return f; } /**以lambda模式设置对象的成员函数,lambda模式下对对象的函数变更仅对此对象有效,变更即时生效, * 若需要使变更对所有实例都生效,则应当对此对象的动态类型引用{@link DynamicClass#visitClass(Class, JavaHandleHelper)}方法变更行为样版 * <p>生成器实施应当实现此方法使之调用数据池的{@link DataPool#setFunction(String, Function, Class[])}方法,并将参数一一对应传入 * <p><strong>注意,含有泛型的参数,无论类型参数如何,形式参数类型始终为{@link Object}</strong> * * @param name 设置的函数名称 * @param func 描述函数行为的匿名函数 * @param argTypes 形式参数的类型列表*/ <R> void setFunc(String name, Function<Self, R> func, Class<?>... argTypes); <R> void setFunc(String name, Function.SuperGetFunction<Self, R> func, Class<?>... argTypes); /**与{@link DynamicObject#setFunc(String, Function, Class[])}效果一致,只是传入的函数没有返回值*/ default void setFunc(String name, Function.NonRetFunction<Self> func, Class<?>... argTypes){ setFunc(name, (s, a) -> { func.invoke(s, a); return null; }, argTypes); } /**与{@link DynamicObject#setFunc(String, Function.SuperGetFunction, Class[])}效果一致,只是传入的函数没有返回值*/ default void setFunc(String name, Function.NonRetSuperGetFunc<Self> func, Class<?>... argTypes){ setFunc(name, (s, sup, a) -> { func.invoke(s, sup, a); return null; }, argTypes); } /**执行对象的指定成员函数 * * @param name 函数名称 * @param args 传递给函数的实参列表 * @return 函数返回值*/ default <R> R invokeFunc(String name, Object... args){ ArgumentList lis = ArgumentList.as(args); R r = invokeFunc(name, lis); lis.type().recycle(); lis.recycle(); return r; } /**指明形式参数列表执行对象的指定成员函数,如果参数中有从类型派生的对象或者null值,使用type明确指定形参类型可以有效提升执行效率 * * @param name 函数名称 * @param args 传递给函数的实参列表 * @return 函数返回值*/ default <R> R invokeFunc(FunctionType type, String name, Object... args){ ArgumentList lis = ArgumentList.asWithType(type, args); R r = invokeFunc(name, lis); lis.recycle(); return r; } /**直接传入{@link ArgumentList}作为实参列表的函数调用,方法内完成拆箱,便于在匿名函数中对另一函数进行引用而无需拆箱 * * @param name 函数名称 * @param args 是按列表的封装对象 * @return 函数返回值*/ default <R> R invokeFunc(String name, ArgumentList args){ FunctionType type = args.type(); Function<Self, R> res = getFunc(name, type).getFunction(); if(res == null) throw new IllegalHandleException("no such method declared: " + name); return res.invoke( this, args); } /**将对象自身经过一次强转换并返回*/ default <T extends Self> T objSelf(){ return (T) this; } //primitive getters and setters //我讨厌装箱类型,是的,相当讨厌...... default boolean getVar(String name, boolean def){ IVariable var = getVariable(name); if(var == null) throw new IllegalHandleException("variable " + name + " was not defined"); return var.get(this, def); } default byte getVar(String name, byte def){ IVariable var = getVariable(name); if(var == null) throw new IllegalHandleException("variable " + name + " was not defined"); return var.get(this, def); } default short getVar(String name, short def){ IVariable var = getVariable(name); if(var == null) throw new IllegalHandleException("variable " + name + " was not defined"); return var.get(this, def); } default int getVar(String name, int def){ IVariable var = getVariable(name); if(var == null) throw new IllegalHandleException("variable " + name + " was not defined"); return var.get(this, def); } default long getVar(String name, long def){ IVariable var = getVariable(name); if(var == null) throw new IllegalHandleException("variable " + name + " was not defined"); return var.get(this, def); } default float getVar(String name, float def){ IVariable var = getVariable(name); if(var == null) throw new IllegalHandleException("variable " + name + " was not defined"); return var.get(this, def); } default double getVar(String name, double def){ IVariable var = getVariable(name); if(var == null) throw new IllegalHandleException("variable " + name + " was not defined"); return var.get(this, def); } default void setVar(String name, boolean value){ IVariable var = getVariable(name); if(var == null){ var = new Variable(name); setVariable(var); } var.set(this, value); } default void setVar(String name, byte value){ IVariable var = getVariable(name); if(var == null){ var = new Variable(name); setVariable(var); } var.set(this, value); } default void setVar(String name, short value){ IVariable var = getVariable(name); if(var == null){ var = new Variable(name); setVariable(var); } var.set(this, value); } default void setVar(String name, int value){ IVariable var = getVariable(name); if(var == null){ var = new Variable(name); setVariable(var); } var.set(this, value); } default void setVar(String name, long value){ IVariable var = getVariable(name); if(var == null){ var = new Variable(name); setVariable(var); } var.set(this, value); } default void setVar(String name, float value){ IVariable var = getVariable(name); if(var == null){ var = new Variable(name); setVariable(var); } var.set(this, value); } default void setVar(String name, double value){ IVariable var = getVariable(name); if(var == null){ var = new Variable(name); setVariable(var); } var.set(this, value); } default boolean calculateVar(String name, Calculator.BoolCalculator calculator){ boolean res; setVar(name, res = calculator.calculate(getVar(name))); return res; } default byte calculateVar(String name, Calculator.ByteCalculator calculator){ byte res; setVar(name, res = calculator.calculate(getVar(name))); return res; } default short calculateVar(String name, Calculator.ShortCalculator calculator){ short res; setVar(name, res = calculator.calculate(getVar(name))); return res; } default int calculateVar(String name, Calculator.IntCalculator calculator){ int res; setVar(name, res = calculator.calculate(getVar(name))); return res; } default long calculateVar(String name, Calculator.LongCalculator calculator){ long res; setVar(name, res = calculator.calculate(getVar(name))); return res; } default float calculateVar(String name, Calculator.FloatCalculator calculator){ float res; setVar(name, res = calculator.calculate(getVar(name))); return res; } default double calculateVar(String name, Calculator.DoubleCalculator calculator){ double res; setVar(name, res = calculator.calculate(getVar(name))); return res; } }
0
2,824
39
3,041
36
3,216
36
3,041
36
3,947
59
false
false
false
false
false
true
29762_1
package Ai; import control.GameControl; import dto.GameInfo; import dto.Grassman; import music.Player; public class Ai { private GameControl gameControl; private GameInfo info; private Grassman aiMan; private int moveDirection; private int offendDirection; public Ai(GameControl gameControl){ this.gameControl = gameControl; } /* * 默认先移动后攻击 */ public void judgeAction(){ //获取游戏信息 this.info=gameControl.getGameInfo(); //获得当前人物 this.aiMan=gameControl.getGrassman(); //随机移动方向 0 1 2 3 上 下 左 右 moveDirection=(int) (Math.random() * 4); doAction(moveDirection); //攻击方向 //随机攻击方向4 5 6 7 上 下 左 右 offendDirection=(int) (Math.random() * 4+4); //判断四个方向是否有敌人 if(isExistUpEnemy(this.gameControl.judgeWeapon())){ offendDirection=4; } if(isExistDownEnemy(this.gameControl.judgeWeapon())){ offendDirection=5; } if(isExistLeftEnemy(this.gameControl.judgeWeapon())){ offendDirection=6; } if(isExistRightEnemy(this.gameControl.judgeWeapon())){ offendDirection=7; } doAction(offendDirection); } /* * 判断攻击范围内是否有敌人 */ private boolean isExistUpEnemy(int weapon){ //向上有敌人 for (int i = 0; i < 7; i++) { if (aiMan.getOx()[weapon][i] != 0 || aiMan.getOy()[weapon][i] != 0) { // 该判断为攻击范围是否越界 if (this.aiMan.getXPosition() + aiMan.getOx()[weapon][i] < 0 || this.aiMan.getXPosition() +aiMan.getOx()[weapon][i] > 9 || this.aiMan.getYPosition() +aiMan.getOy()[weapon][i] < 0 || this.aiMan.getYPosition() +aiMan.getOy()[weapon][i] > 9) { continue; } if ((info.map[this.aiMan.getXPosition() + this.aiMan.getOx()[weapon][i]][this.aiMan.getYPosition() + this.aiMan.getOy()[weapon][i]] < 4) && (info.map[this.aiMan.getXPosition() + this.aiMan.getOx()[weapon][i]][this.aiMan.getYPosition() + this.aiMan.getOy()[weapon][i]] > 0)) { return true; } else { return false; } } } return false; } private boolean isExistDownEnemy(int weapon){ //向下有敌人 for (int i = 0; i < 7; i++) { if (aiMan.getOx()[weapon][i] != 0 || aiMan.getOy()[weapon][i] != 0) { // 该判断为攻击范围是否越界 if (this.aiMan.getXPosition() - aiMan.getOx()[weapon][i] < 0 || this.aiMan.getXPosition() -aiMan.getOx()[weapon][i] > 9 || this.aiMan.getYPosition() -aiMan.getOy()[weapon][i] < 0 || this.aiMan.getYPosition() -aiMan.getOy()[weapon][i] > 9) { continue; } if ((info.map[this.aiMan.getXPosition() - this.aiMan.getOx()[weapon][i]][this.aiMan.getYPosition() - this.aiMan.getOy()[weapon][i]] < 4) && (info.map[this.aiMan.getXPosition() - this.aiMan.getOx()[weapon][i]][this.aiMan.getYPosition() - this.aiMan.getOy()[weapon][i]] > 0)) { return true; } else { return false; } } } return false; } private boolean isExistLeftEnemy(int weapon){ //向左有敌人 for (int i = 0; i < 7; i++) { if (aiMan.getOx()[weapon][i] != 0 || aiMan.getOy()[weapon][i] != 0) { // 该判断为攻击范围是否越界 if (this.aiMan.getXPosition() - aiMan.getOy()[weapon][i] < 0 || this.aiMan.getXPosition() -aiMan.getOy()[weapon][i] > 9 || this.aiMan.getYPosition() +aiMan.getOx()[weapon][i] < 0 || this.aiMan.getYPosition() +aiMan.getOx()[weapon][i] > 9) { continue; } if ((info.map[this.aiMan.getXPosition() - this.aiMan.getOy()[weapon][i]][this.aiMan.getYPosition() + this.aiMan.getOx()[weapon][i]] < 4) && (info.map[this.aiMan.getXPosition() - this.aiMan.getOy()[weapon][i]][this.aiMan.getYPosition() + this.aiMan.getOx()[weapon][i]] > 0)) { return true; } else { return false; } } } return false; } private boolean isExistRightEnemy(int weapon){ //向右有敌人 for (int i = 0; i < 7; i++) { if (aiMan.getOx()[weapon][i] != 0 || aiMan.getOy()[weapon][i] != 0) { // 该判断为攻击范围是否越界 if (this.aiMan.getXPosition() + aiMan.getOy()[weapon][i] < 0 || this.aiMan.getXPosition() +aiMan.getOy()[weapon][i] > 9 || this.aiMan.getYPosition() -aiMan.getOx()[weapon][i] < 0 || this.aiMan.getYPosition() -aiMan.getOx()[weapon][i] > 9) { continue; } if ((info.map[this.aiMan.getXPosition() + this.aiMan.getOy()[weapon][i]][this.aiMan.getYPosition() - this.aiMan.getOx()[weapon][i]] < 4) && (info.map[this.aiMan.getXPosition() + this.aiMan.getOy()[weapon][i]][this.aiMan.getYPosition() - this.aiMan.getOx()[weapon][i]] > 0)) { return true; } else { return false; } } } return false; } public void doAction(int cmd){ Player.playSound("攻击"); switch(cmd){ case 0: if (this.gameControl.canMove()) { this.gameControl.KeyUp(); // System.out.println(0); } break; case 1: if (this.gameControl.canMove()) { this.gameControl.KeyDown(); // System.out.println(1); } break; case 2: if (this.gameControl.canMove()) { this.gameControl.KeyLeft(); // System.out.println(2); } break; case 3: if (this.gameControl.canMove()) { this.gameControl.KeyRight(); // System.out.println(3); } case 4: if(this.gameControl.canOffend()){ this.gameControl.KeyOffendUp(); // System.out.println(4); } break; case 5: if(this.gameControl.canOffend()){ this.gameControl.KeyOffendDown(); // System.out.println(5); } break; case 6: if(this.gameControl.canOffend()){ this.gameControl.KeyOffendLeft(); // System.out.println(6); } break; case 7: if(this.gameControl.canOffend()){ this.gameControl.KeyOffendRight(); // System.out.println(7); } break; default: System.out.println("出错啦! 你这个大笨蛋!"); break; } } }
ELCyber/GrassCraft
src/Ai/Ai.java
2,176
//获取游戏信息
line_comment
zh-cn
package Ai; import control.GameControl; import dto.GameInfo; import dto.Grassman; import music.Player; public class Ai { private GameControl gameControl; private GameInfo info; private Grassman aiMan; private int moveDirection; private int offendDirection; public Ai(GameControl gameControl){ this.gameControl = gameControl; } /* * 默认先移动后攻击 */ public void judgeAction(){ //获取 <SUF> this.info=gameControl.getGameInfo(); //获得当前人物 this.aiMan=gameControl.getGrassman(); //随机移动方向 0 1 2 3 上 下 左 右 moveDirection=(int) (Math.random() * 4); doAction(moveDirection); //攻击方向 //随机攻击方向4 5 6 7 上 下 左 右 offendDirection=(int) (Math.random() * 4+4); //判断四个方向是否有敌人 if(isExistUpEnemy(this.gameControl.judgeWeapon())){ offendDirection=4; } if(isExistDownEnemy(this.gameControl.judgeWeapon())){ offendDirection=5; } if(isExistLeftEnemy(this.gameControl.judgeWeapon())){ offendDirection=6; } if(isExistRightEnemy(this.gameControl.judgeWeapon())){ offendDirection=7; } doAction(offendDirection); } /* * 判断攻击范围内是否有敌人 */ private boolean isExistUpEnemy(int weapon){ //向上有敌人 for (int i = 0; i < 7; i++) { if (aiMan.getOx()[weapon][i] != 0 || aiMan.getOy()[weapon][i] != 0) { // 该判断为攻击范围是否越界 if (this.aiMan.getXPosition() + aiMan.getOx()[weapon][i] < 0 || this.aiMan.getXPosition() +aiMan.getOx()[weapon][i] > 9 || this.aiMan.getYPosition() +aiMan.getOy()[weapon][i] < 0 || this.aiMan.getYPosition() +aiMan.getOy()[weapon][i] > 9) { continue; } if ((info.map[this.aiMan.getXPosition() + this.aiMan.getOx()[weapon][i]][this.aiMan.getYPosition() + this.aiMan.getOy()[weapon][i]] < 4) && (info.map[this.aiMan.getXPosition() + this.aiMan.getOx()[weapon][i]][this.aiMan.getYPosition() + this.aiMan.getOy()[weapon][i]] > 0)) { return true; } else { return false; } } } return false; } private boolean isExistDownEnemy(int weapon){ //向下有敌人 for (int i = 0; i < 7; i++) { if (aiMan.getOx()[weapon][i] != 0 || aiMan.getOy()[weapon][i] != 0) { // 该判断为攻击范围是否越界 if (this.aiMan.getXPosition() - aiMan.getOx()[weapon][i] < 0 || this.aiMan.getXPosition() -aiMan.getOx()[weapon][i] > 9 || this.aiMan.getYPosition() -aiMan.getOy()[weapon][i] < 0 || this.aiMan.getYPosition() -aiMan.getOy()[weapon][i] > 9) { continue; } if ((info.map[this.aiMan.getXPosition() - this.aiMan.getOx()[weapon][i]][this.aiMan.getYPosition() - this.aiMan.getOy()[weapon][i]] < 4) && (info.map[this.aiMan.getXPosition() - this.aiMan.getOx()[weapon][i]][this.aiMan.getYPosition() - this.aiMan.getOy()[weapon][i]] > 0)) { return true; } else { return false; } } } return false; } private boolean isExistLeftEnemy(int weapon){ //向左有敌人 for (int i = 0; i < 7; i++) { if (aiMan.getOx()[weapon][i] != 0 || aiMan.getOy()[weapon][i] != 0) { // 该判断为攻击范围是否越界 if (this.aiMan.getXPosition() - aiMan.getOy()[weapon][i] < 0 || this.aiMan.getXPosition() -aiMan.getOy()[weapon][i] > 9 || this.aiMan.getYPosition() +aiMan.getOx()[weapon][i] < 0 || this.aiMan.getYPosition() +aiMan.getOx()[weapon][i] > 9) { continue; } if ((info.map[this.aiMan.getXPosition() - this.aiMan.getOy()[weapon][i]][this.aiMan.getYPosition() + this.aiMan.getOx()[weapon][i]] < 4) && (info.map[this.aiMan.getXPosition() - this.aiMan.getOy()[weapon][i]][this.aiMan.getYPosition() + this.aiMan.getOx()[weapon][i]] > 0)) { return true; } else { return false; } } } return false; } private boolean isExistRightEnemy(int weapon){ //向右有敌人 for (int i = 0; i < 7; i++) { if (aiMan.getOx()[weapon][i] != 0 || aiMan.getOy()[weapon][i] != 0) { // 该判断为攻击范围是否越界 if (this.aiMan.getXPosition() + aiMan.getOy()[weapon][i] < 0 || this.aiMan.getXPosition() +aiMan.getOy()[weapon][i] > 9 || this.aiMan.getYPosition() -aiMan.getOx()[weapon][i] < 0 || this.aiMan.getYPosition() -aiMan.getOx()[weapon][i] > 9) { continue; } if ((info.map[this.aiMan.getXPosition() + this.aiMan.getOy()[weapon][i]][this.aiMan.getYPosition() - this.aiMan.getOx()[weapon][i]] < 4) && (info.map[this.aiMan.getXPosition() + this.aiMan.getOy()[weapon][i]][this.aiMan.getYPosition() - this.aiMan.getOx()[weapon][i]] > 0)) { return true; } else { return false; } } } return false; } public void doAction(int cmd){ Player.playSound("攻击"); switch(cmd){ case 0: if (this.gameControl.canMove()) { this.gameControl.KeyUp(); // System.out.println(0); } break; case 1: if (this.gameControl.canMove()) { this.gameControl.KeyDown(); // System.out.println(1); } break; case 2: if (this.gameControl.canMove()) { this.gameControl.KeyLeft(); // System.out.println(2); } break; case 3: if (this.gameControl.canMove()) { this.gameControl.KeyRight(); // System.out.println(3); } case 4: if(this.gameControl.canOffend()){ this.gameControl.KeyOffendUp(); // System.out.println(4); } break; case 5: if(this.gameControl.canOffend()){ this.gameControl.KeyOffendDown(); // System.out.println(5); } break; case 6: if(this.gameControl.canOffend()){ this.gameControl.KeyOffendLeft(); // System.out.println(6); } break; case 7: if(this.gameControl.canOffend()){ this.gameControl.KeyOffendRight(); // System.out.println(7); } break; default: System.out.println("出错啦! 你这个大笨蛋!"); break; } } }
0
1,880
4
2,176
4
2,196
4
2,176
4
2,911
11
false
false
false
false
false
true
57884_2
package io.github.emanual.app.ui; import android.app.ProgressDialog; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.widget.Toast; import com.loopj.android.http.AsyncHttpResponseHandler; import java.io.File; import java.io.IOException; import java.util.List; import butterknife.Bind; import cz.msebera.android.httpclient.Header; import de.greenrobot.event.EventBus; import de.greenrobot.event.Subscribe; import de.greenrobot.event.ThreadMode; import io.github.emanual.app.R; import io.github.emanual.app.api.EmanualAPI; import io.github.emanual.app.entity.FeedsItemEntity; import io.github.emanual.app.ui.adapter.FeedsListAdapter; import io.github.emanual.app.ui.base.activity.SwipeRefreshActivity; import io.github.emanual.app.ui.event.InterviewDownloadEndEvent; import io.github.emanual.app.ui.event.InterviewDownloadFaildEvent; import io.github.emanual.app.ui.event.InterviewDownloadProgressEvent; import io.github.emanual.app.ui.event.InterviewDownloadStartEvent; import io.github.emanual.app.ui.event.UnPackFinishEvent; import io.github.emanual.app.utils.AppPath; import io.github.emanual.app.utils.SwipeRefreshLayoutUtils; import io.github.emanual.app.utils.ZipUtils; import timber.log.Timber; public class InterviewFeedsActivity extends SwipeRefreshActivity { ProgressDialog mProgressDialog; @Bind(R.id.recyclerView) RecyclerView recyclerView; @Override protected void initData(Bundle savedInstanceState) { } @Override protected void initLayout(Bundle savedInstanceState) { setSupportActionBar((Toolbar) findViewById(R.id.toolbar)); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setTitle(R.string.acty_feeds_list); mProgressDialog = new ProgressDialog(getContext()); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); fetchData(); } @Override protected int getContentViewId() { return R.layout.acty_interview_feeds; } @Override public void onRefresh() { // EmanualAPI.getIn fetchData(); } @Subscribe(threadMode = ThreadMode.MainThread) public void onDownloadStart(InterviewDownloadStartEvent event) { mProgressDialog.setTitle("正在下载.."); mProgressDialog.setProgress(0); mProgressDialog.setMax(100); mProgressDialog.show(); } @Subscribe(threadMode = ThreadMode.MainThread) public void onDownloadProgress(InterviewDownloadProgressEvent event) { Timber.d(event.getBytesWritten() + "/" + event.getTotalSize()); mProgressDialog.setMessage(String.format("大小:%.2f M", 1.0 * event.getTotalSize() / 1024 / 1024)); mProgressDialog.setMax((int) event.getTotalSize()); mProgressDialog.setProgress((int) event.getBytesWritten()); } @Subscribe(threadMode = ThreadMode.MainThread) public void onDownloadFaild(InterviewDownloadFaildEvent event) { Toast.makeText(getContext(), "出错了,错误码:" + event.getStatusCode(), Toast.LENGTH_LONG).show(); mProgressDialog.dismiss(); } @Subscribe(threadMode = ThreadMode.MainThread) public void onDownloadEnd2(InterviewDownloadEndEvent event) { mProgressDialog.setTitle("正在解压.."); } /** * 下载完毕 * @param event */ @Subscribe(threadMode = ThreadMode.Async) public void onDownloadEnd(InterviewDownloadEndEvent event) { try { ZipUtils.unZipFiles(event.getFile().getAbsolutePath(), AppPath.getInterviewsPath(getContext()) + File.separator + event.getFeedsItemEntity().getName() + File.separator); //删除压缩包 if (event.getFile().exists()) { event.getFile().delete(); } } catch (IOException e) { e.printStackTrace(); EventBus.getDefault().post(new UnPackFinishEvent(e)); return; } EventBus.getDefault().post(new UnPackFinishEvent(null)); } @Subscribe(threadMode = ThreadMode.MainThread) public void onUnpackFinishEvent(UnPackFinishEvent event) { if (event.getException() != null) { toast(event.getException().getMessage()); return; } toast("下载并解压成功"); mProgressDialog.dismiss(); } private void fetchData() { EmanualAPI.getInterviewFeeds(new AsyncHttpResponseHandler() { @Override public void onStart() { super.onStart(); SwipeRefreshLayoutUtils.setRefreshing(getSwipeRefreshLayout(), true); } @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { try { List<FeedsItemEntity> feeds = FeedsItemEntity.createByJSONArray(new String(responseBody), FeedsItemEntity.class); Timber.d(feeds.toString()); recyclerView.setAdapter(new FeedsListAdapter(getContext(), feeds, FeedsListAdapter.TYPE_INTERVIEW)); } catch (Exception e) { toast("哎呀,网络异常!"); } } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { } @Override public void onFinish() { super.onFinish(); SwipeRefreshLayoutUtils.setRefreshing(getSwipeRefreshLayout(), false); } @Override public void onProgress(long bytesWritten, long totalSize) { super.onProgress(bytesWritten, totalSize); } }); } }
EManual/EManual-Android
app/src/main/java/io/github/emanual/app/ui/InterviewFeedsActivity.java
1,433
//删除压缩包
line_comment
zh-cn
package io.github.emanual.app.ui; import android.app.ProgressDialog; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.widget.Toast; import com.loopj.android.http.AsyncHttpResponseHandler; import java.io.File; import java.io.IOException; import java.util.List; import butterknife.Bind; import cz.msebera.android.httpclient.Header; import de.greenrobot.event.EventBus; import de.greenrobot.event.Subscribe; import de.greenrobot.event.ThreadMode; import io.github.emanual.app.R; import io.github.emanual.app.api.EmanualAPI; import io.github.emanual.app.entity.FeedsItemEntity; import io.github.emanual.app.ui.adapter.FeedsListAdapter; import io.github.emanual.app.ui.base.activity.SwipeRefreshActivity; import io.github.emanual.app.ui.event.InterviewDownloadEndEvent; import io.github.emanual.app.ui.event.InterviewDownloadFaildEvent; import io.github.emanual.app.ui.event.InterviewDownloadProgressEvent; import io.github.emanual.app.ui.event.InterviewDownloadStartEvent; import io.github.emanual.app.ui.event.UnPackFinishEvent; import io.github.emanual.app.utils.AppPath; import io.github.emanual.app.utils.SwipeRefreshLayoutUtils; import io.github.emanual.app.utils.ZipUtils; import timber.log.Timber; public class InterviewFeedsActivity extends SwipeRefreshActivity { ProgressDialog mProgressDialog; @Bind(R.id.recyclerView) RecyclerView recyclerView; @Override protected void initData(Bundle savedInstanceState) { } @Override protected void initLayout(Bundle savedInstanceState) { setSupportActionBar((Toolbar) findViewById(R.id.toolbar)); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setTitle(R.string.acty_feeds_list); mProgressDialog = new ProgressDialog(getContext()); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); fetchData(); } @Override protected int getContentViewId() { return R.layout.acty_interview_feeds; } @Override public void onRefresh() { // EmanualAPI.getIn fetchData(); } @Subscribe(threadMode = ThreadMode.MainThread) public void onDownloadStart(InterviewDownloadStartEvent event) { mProgressDialog.setTitle("正在下载.."); mProgressDialog.setProgress(0); mProgressDialog.setMax(100); mProgressDialog.show(); } @Subscribe(threadMode = ThreadMode.MainThread) public void onDownloadProgress(InterviewDownloadProgressEvent event) { Timber.d(event.getBytesWritten() + "/" + event.getTotalSize()); mProgressDialog.setMessage(String.format("大小:%.2f M", 1.0 * event.getTotalSize() / 1024 / 1024)); mProgressDialog.setMax((int) event.getTotalSize()); mProgressDialog.setProgress((int) event.getBytesWritten()); } @Subscribe(threadMode = ThreadMode.MainThread) public void onDownloadFaild(InterviewDownloadFaildEvent event) { Toast.makeText(getContext(), "出错了,错误码:" + event.getStatusCode(), Toast.LENGTH_LONG).show(); mProgressDialog.dismiss(); } @Subscribe(threadMode = ThreadMode.MainThread) public void onDownloadEnd2(InterviewDownloadEndEvent event) { mProgressDialog.setTitle("正在解压.."); } /** * 下载完毕 * @param event */ @Subscribe(threadMode = ThreadMode.Async) public void onDownloadEnd(InterviewDownloadEndEvent event) { try { ZipUtils.unZipFiles(event.getFile().getAbsolutePath(), AppPath.getInterviewsPath(getContext()) + File.separator + event.getFeedsItemEntity().getName() + File.separator); //删除 <SUF> if (event.getFile().exists()) { event.getFile().delete(); } } catch (IOException e) { e.printStackTrace(); EventBus.getDefault().post(new UnPackFinishEvent(e)); return; } EventBus.getDefault().post(new UnPackFinishEvent(null)); } @Subscribe(threadMode = ThreadMode.MainThread) public void onUnpackFinishEvent(UnPackFinishEvent event) { if (event.getException() != null) { toast(event.getException().getMessage()); return; } toast("下载并解压成功"); mProgressDialog.dismiss(); } private void fetchData() { EmanualAPI.getInterviewFeeds(new AsyncHttpResponseHandler() { @Override public void onStart() { super.onStart(); SwipeRefreshLayoutUtils.setRefreshing(getSwipeRefreshLayout(), true); } @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { try { List<FeedsItemEntity> feeds = FeedsItemEntity.createByJSONArray(new String(responseBody), FeedsItemEntity.class); Timber.d(feeds.toString()); recyclerView.setAdapter(new FeedsListAdapter(getContext(), feeds, FeedsListAdapter.TYPE_INTERVIEW)); } catch (Exception e) { toast("哎呀,网络异常!"); } } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { } @Override public void onFinish() { super.onFinish(); SwipeRefreshLayoutUtils.setRefreshing(getSwipeRefreshLayout(), false); } @Override public void onProgress(long bytesWritten, long totalSize) { super.onProgress(bytesWritten, totalSize); } }); } }
0
1,133
4
1,433
4
1,435
4
1,433
4
1,712
10
false
false
false
false
false
true
40957_21
package com.cn.main; import com.cn.util.HttpClientUtil; import org.apache.commons.io.FileUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; public class nyaPictureMain { //存放目录 private static String fileSource = "E://nyaManhua//new//"; public static void main(String[] args) throws Exception { List<String> urlList = new ArrayList<String>(); //地址 urlList.add("https://zha.doghentai.com/g/338012/"); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); nyaPictureMain.crawlerNyaUrl(urlList); String exSite = "cmd /c start " + fileSource ; Runtime.getRuntime().exec(exSite); } public static void crawlerNyaPic(int picSum,String fileUrl,String intputFile,String suffix){ try { for (int i = 1; i <= picSum; i++) { // suffix = ".jpg"; //随时替换文件格式 CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建HttpClient实例 HttpGet httpGet = new HttpGet(fileUrl+i+suffix); // 创建Httpget实例 //设置Http报文头信息 httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"); httpGet.setHeader("accept", "image/avif,image/webp,image/apng,image/*,*/*;q=0.8"); httpGet.setHeader("accept-encoding", "gzip, deflate, br"); httpGet.setHeader("referer", "https://zha.doghentai.com/"); httpGet.setHeader("sec-fetch-dest", "image"); httpGet.setHeader("accept-language", "zh-CN,zh;q=0.9,en;q=0.8"); HttpHost proxy = new HttpHost("127.0.0.1", 7890); //超时时间单位为毫秒 RequestConfig defaultRequestConfig = RequestConfig.custom() .setConnectTimeout(1000).setSocketTimeout(30000) .setProxy(proxy).build(); httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build(); CloseableHttpResponse response = null; response = httpClient.execute(httpGet); // 执行http get请求 HttpEntity entity = response.getEntity(); // 获取返回实体 if(null != entity){ InputStream inputStream = entity.getContent();//返回一个输入流 //输出图片 FileUtils.copyInputStreamToFile(inputStream, new File(intputFile+i+suffix));//引用org.apache.commons.io.FileUtils System.out.println(i+suffix); } response.close(); // 关闭response httpClient.close(); // 关闭HttpClient实体 } }catch (Exception e){ System.out.println(e); } } public static void crawlerNyaUrl(List<String> urlList) throws Exception { Integer rateDow = 1; for(String url:urlList){ String html = ""; if(url.length() != 0){ html = HttpClientUtil.getSource(url); Document document = Jsoup.parse(html); Element element = document.selectFirst("div.container").selectFirst("a"); String coverImgUrl = element.select("img").attr("data-src"); //获取图片载点 String[] ourStr = coverImgUrl.split("/"); //获取后缀 String[] oursuffix = coverImgUrl.split("\\."); //获取数量 Elements picSum = document.select("div.thumb-container"); //获取本子名字 String benziName = element.select("img").attr("alt"); benziName = benziName.replaceAll("\\?","").replaceAll(":","").replaceAll(" ","").replaceAll("\\*",""); int count = picSum.size(); int benziN = Integer.parseInt(ourStr[ourStr.length-2]); String suffix = "."+oursuffix[oursuffix.length-1]; String fileUrl = "https://i0.nyacdn.com/galleries/"+benziN+"/"; String intputFile = fileSource +benziName +"//"; nyaPictureMain.crawlerNyaPic(count,fileUrl,intputFile,suffix); //缓存完后暂停几秒 Thread.sleep(3000); } } System.out.println("喵变态图片缓存成功!!!!"); } }
ERYhua/nyaHentaiCrawler
src/main/java/com/cn/main/nyaPictureMain.java
1,357
//缓存完后暂停几秒
line_comment
zh-cn
package com.cn.main; import com.cn.util.HttpClientUtil; import org.apache.commons.io.FileUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; public class nyaPictureMain { //存放目录 private static String fileSource = "E://nyaManhua//new//"; public static void main(String[] args) throws Exception { List<String> urlList = new ArrayList<String>(); //地址 urlList.add("https://zha.doghentai.com/g/338012/"); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); nyaPictureMain.crawlerNyaUrl(urlList); String exSite = "cmd /c start " + fileSource ; Runtime.getRuntime().exec(exSite); } public static void crawlerNyaPic(int picSum,String fileUrl,String intputFile,String suffix){ try { for (int i = 1; i <= picSum; i++) { // suffix = ".jpg"; //随时替换文件格式 CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建HttpClient实例 HttpGet httpGet = new HttpGet(fileUrl+i+suffix); // 创建Httpget实例 //设置Http报文头信息 httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"); httpGet.setHeader("accept", "image/avif,image/webp,image/apng,image/*,*/*;q=0.8"); httpGet.setHeader("accept-encoding", "gzip, deflate, br"); httpGet.setHeader("referer", "https://zha.doghentai.com/"); httpGet.setHeader("sec-fetch-dest", "image"); httpGet.setHeader("accept-language", "zh-CN,zh;q=0.9,en;q=0.8"); HttpHost proxy = new HttpHost("127.0.0.1", 7890); //超时时间单位为毫秒 RequestConfig defaultRequestConfig = RequestConfig.custom() .setConnectTimeout(1000).setSocketTimeout(30000) .setProxy(proxy).build(); httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build(); CloseableHttpResponse response = null; response = httpClient.execute(httpGet); // 执行http get请求 HttpEntity entity = response.getEntity(); // 获取返回实体 if(null != entity){ InputStream inputStream = entity.getContent();//返回一个输入流 //输出图片 FileUtils.copyInputStreamToFile(inputStream, new File(intputFile+i+suffix));//引用org.apache.commons.io.FileUtils System.out.println(i+suffix); } response.close(); // 关闭response httpClient.close(); // 关闭HttpClient实体 } }catch (Exception e){ System.out.println(e); } } public static void crawlerNyaUrl(List<String> urlList) throws Exception { Integer rateDow = 1; for(String url:urlList){ String html = ""; if(url.length() != 0){ html = HttpClientUtil.getSource(url); Document document = Jsoup.parse(html); Element element = document.selectFirst("div.container").selectFirst("a"); String coverImgUrl = element.select("img").attr("data-src"); //获取图片载点 String[] ourStr = coverImgUrl.split("/"); //获取后缀 String[] oursuffix = coverImgUrl.split("\\."); //获取数量 Elements picSum = document.select("div.thumb-container"); //获取本子名字 String benziName = element.select("img").attr("alt"); benziName = benziName.replaceAll("\\?","").replaceAll(":","").replaceAll(" ","").replaceAll("\\*",""); int count = picSum.size(); int benziN = Integer.parseInt(ourStr[ourStr.length-2]); String suffix = "."+oursuffix[oursuffix.length-1]; String fileUrl = "https://i0.nyacdn.com/galleries/"+benziN+"/"; String intputFile = fileSource +benziName +"//"; nyaPictureMain.crawlerNyaPic(count,fileUrl,intputFile,suffix); //缓存 <SUF> Thread.sleep(3000); } } System.out.println("喵变态图片缓存成功!!!!"); } }
0
1,160
8
1,357
8
1,404
7
1,357
8
1,662
19
false
false
false
false
false
true
50426_10
package exp.libs.ui.cpt.win; import exp.libs.utils.concurrent.ThreadUtils; /** * <PRE> * swing右下角通知窗口 * (使用_show方法显示窗体, 可触发自动渐隐消失) * </PRE> * <br/><B>PROJECT : </B> exp-libs * <br/><B>SUPPORT : </B> <a href="https://exp-blog.com" target="_blank">https://exp-blog.com</a> * @version 2022-03-06 * @author EXP: exp.lqb@foxmail.com * @since JDK 1.8+ */ @SuppressWarnings("serial") public abstract class NoticeWindow extends PopChildWindow implements Runnable { private Thread _this; private boolean isRun = false; protected NoticeWindow() { super("NoticeWindow"); } protected NoticeWindow(String name) { super(name); } protected NoticeWindow(String name, int width, int height) { super(name, width, height); } protected NoticeWindow(String name, int width, int height, boolean relative) { super(name, width, height, relative); } protected NoticeWindow(String name, int width, int height, boolean relative, Object... args) { super(name, width, height, relative, args); } @Override protected int LOCATION() { return LOCATION_RB; // 出现坐标为右下角 } @Override protected boolean WIN_ON_TOP() { return true; // 设置窗口置顶 } /** * 以渐隐方式显示通知消息 */ @Override protected final void AfterView() { if(isRun == false) { isRun = true; _this = new Thread(this); _this.start(); // 渐隐窗体 } } @Deprecated @Override protected final void beforeHide() { // Undo } @Override public void run() { ThreadUtils.tSleep(2000); // 悬停2秒 // 透明度渐隐(大约持续3秒) for(float opacity = 100; opacity > 0; opacity -= 2) { this.setOpacity(opacity / 100); // 设置透明度 ThreadUtils.tSleep(60); if(isVisible() == false) { break; // 窗体被提前销毁了(手工点了X) } } _hide(); // 销毁窗体 } /** * 阻塞等待渐隐关闭过程 */ public void _join() { if(_this == null) { return; } try { _this.join(); } catch (Exception e) {} } }
EXP-Codes/exp-libs-refactor
exp-libs-ui/src/main/java/exp/libs/ui/cpt/win/NoticeWindow.java
724
// 销毁窗体
line_comment
zh-cn
package exp.libs.ui.cpt.win; import exp.libs.utils.concurrent.ThreadUtils; /** * <PRE> * swing右下角通知窗口 * (使用_show方法显示窗体, 可触发自动渐隐消失) * </PRE> * <br/><B>PROJECT : </B> exp-libs * <br/><B>SUPPORT : </B> <a href="https://exp-blog.com" target="_blank">https://exp-blog.com</a> * @version 2022-03-06 * @author EXP: exp.lqb@foxmail.com * @since JDK 1.8+ */ @SuppressWarnings("serial") public abstract class NoticeWindow extends PopChildWindow implements Runnable { private Thread _this; private boolean isRun = false; protected NoticeWindow() { super("NoticeWindow"); } protected NoticeWindow(String name) { super(name); } protected NoticeWindow(String name, int width, int height) { super(name, width, height); } protected NoticeWindow(String name, int width, int height, boolean relative) { super(name, width, height, relative); } protected NoticeWindow(String name, int width, int height, boolean relative, Object... args) { super(name, width, height, relative, args); } @Override protected int LOCATION() { return LOCATION_RB; // 出现坐标为右下角 } @Override protected boolean WIN_ON_TOP() { return true; // 设置窗口置顶 } /** * 以渐隐方式显示通知消息 */ @Override protected final void AfterView() { if(isRun == false) { isRun = true; _this = new Thread(this); _this.start(); // 渐隐窗体 } } @Deprecated @Override protected final void beforeHide() { // Undo } @Override public void run() { ThreadUtils.tSleep(2000); // 悬停2秒 // 透明度渐隐(大约持续3秒) for(float opacity = 100; opacity > 0; opacity -= 2) { this.setOpacity(opacity / 100); // 设置透明度 ThreadUtils.tSleep(60); if(isVisible() == false) { break; // 窗体被提前销毁了(手工点了X) } } _hide(); // 销毁 <SUF> } /** * 阻塞等待渐隐关闭过程 */ public void _join() { if(_this == null) { return; } try { _this.join(); } catch (Exception e) {} } }
0
622
6
724
7
737
5
724
7
921
12
false
false
false
false
false
true
23210_2
import java.io.*; import java.net.ServerSocket; import java.net.Socket; /** * @author yangda * @description: * @create 2023-05-21-14:53 */ public class MyTomcat { public static void main(String[] args) throws IOException { ServerSocket serverSocket = new ServerSocket(9999); int i = 0; while (!serverSocket.isClosed()){ // 如果serverSocket 没有关闭 System.out.println("f服务器等待连接、、、" + ++i); // 等待浏览器/客户端连接,得到socket // 该socket用于通信 Socket socket = serverSocket.accept(); // 拿到 和socket相关的输出流 OutputStream outputStream = socket.getOutputStream(); FileReader fileReader = new FileReader("src/hello.html"); BufferedReader bufferedReader = new BufferedReader(fileReader); String buf = ""; while ((buf = bufferedReader.readLine()) != null){ outputStream.write(buf.getBytes()); } // BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream)); // outputStream.write("hello i am server".getBytes()); System.out.println("信息以打入管道" ); outputStream.close(); socket.close(); } serverSocket.close(); } }
EXsYang/mycode
javaweb/tomcat/src/MyTomcat.java
311
// 等待浏览器/客户端连接,得到socket
line_comment
zh-cn
import java.io.*; import java.net.ServerSocket; import java.net.Socket; /** * @author yangda * @description: * @create 2023-05-21-14:53 */ public class MyTomcat { public static void main(String[] args) throws IOException { ServerSocket serverSocket = new ServerSocket(9999); int i = 0; while (!serverSocket.isClosed()){ // 如果serverSocket 没有关闭 System.out.println("f服务器等待连接、、、" + ++i); // 等待 <SUF> // 该socket用于通信 Socket socket = serverSocket.accept(); // 拿到 和socket相关的输出流 OutputStream outputStream = socket.getOutputStream(); FileReader fileReader = new FileReader("src/hello.html"); BufferedReader bufferedReader = new BufferedReader(fileReader); String buf = ""; while ((buf = bufferedReader.readLine()) != null){ outputStream.write(buf.getBytes()); } // BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream)); // outputStream.write("hello i am server".getBytes()); System.out.println("信息以打入管道" ); outputStream.close(); socket.close(); } serverSocket.close(); } }
0
274
12
311
10
315
10
311
10
390
25
false
false
false
false
false
true
36401_4
package name.ealen.entity; import com.fasterxml.jackson.annotation.JsonIgnore; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; import java.util.Set; /** * Created by EalenXie on 2018/10/16 16:13. * 典型的 多层级 分类 * <p> * :@NamedEntityGraph :注解在实体上 , 解决典型的N+1问题 * name表示实体图名, 与 repository中的注解 @EntityGraph的value属性相对应, * attributeNodes 表示被标注要懒加载的属性节点 比如此例中 : 要懒加载的子分类集合children */ @Entity @Table(name = "jpa_category") @NamedEntityGraphs({ @NamedEntityGraph(name = "Category.findAll", attributeNodes = {@NamedAttributeNode("children")}), @NamedEntityGraph(name = "Category.findByParent", attributeNodes = {@NamedAttributeNode(value = "children", subgraph = "son")}, //一级延伸 subgraphs = {@NamedSubgraph(name = "son", attributeNodes = @NamedAttributeNode(value = "children", subgraph = "grandson")), //二级延伸 @NamedSubgraph(name = "grandson", attributeNodes = @NamedAttributeNode(value = "children", subgraph = "greatGrandSon")), //三级延伸 @NamedSubgraph(name = "greatGrandSon", attributeNodes = @NamedAttributeNode(value = "children"))}) //四级延伸 // 有多少次延伸,就有多少个联表关系,自身关联的表设计中,子节点是可以无限延伸的,所以关联数可能查询的..... }) public class Category { /** * Id 使用UUID生成策略 */ @Id @GeneratedValue(generator = "UUID") @GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator") private String id; /** * 分类名 */ private String name; /** * 一个商品分类下面可能有多个商品子分类(多级) 比如 分类 : 家用电器 (子)分类 : 电脑 (孙)子分类 : 笔记本电脑 */ @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "parent_id") @JsonIgnore private Category parent; //父分类 @OneToMany(mappedBy = "parent", fetch = FetchType.LAZY) private Set<Category> children; //子分类集合 public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Category getParent() { return parent; } public void setParent(Category parent) { this.parent = parent; } public Set<Category> getChildren() { return children; } public void setChildren(Set<Category> children) { this.children = children; } }
EalenXie/springboot-jpa-N-plus-One
src/main/java/name/ealen/entity/Category.java
743
//四级延伸
line_comment
zh-cn
package name.ealen.entity; import com.fasterxml.jackson.annotation.JsonIgnore; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; import java.util.Set; /** * Created by EalenXie on 2018/10/16 16:13. * 典型的 多层级 分类 * <p> * :@NamedEntityGraph :注解在实体上 , 解决典型的N+1问题 * name表示实体图名, 与 repository中的注解 @EntityGraph的value属性相对应, * attributeNodes 表示被标注要懒加载的属性节点 比如此例中 : 要懒加载的子分类集合children */ @Entity @Table(name = "jpa_category") @NamedEntityGraphs({ @NamedEntityGraph(name = "Category.findAll", attributeNodes = {@NamedAttributeNode("children")}), @NamedEntityGraph(name = "Category.findByParent", attributeNodes = {@NamedAttributeNode(value = "children", subgraph = "son")}, //一级延伸 subgraphs = {@NamedSubgraph(name = "son", attributeNodes = @NamedAttributeNode(value = "children", subgraph = "grandson")), //二级延伸 @NamedSubgraph(name = "grandson", attributeNodes = @NamedAttributeNode(value = "children", subgraph = "greatGrandSon")), //三级延伸 @NamedSubgraph(name = "greatGrandSon", attributeNodes = @NamedAttributeNode(value = "children"))}) //四级 <SUF> // 有多少次延伸,就有多少个联表关系,自身关联的表设计中,子节点是可以无限延伸的,所以关联数可能查询的..... }) public class Category { /** * Id 使用UUID生成策略 */ @Id @GeneratedValue(generator = "UUID") @GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator") private String id; /** * 分类名 */ private String name; /** * 一个商品分类下面可能有多个商品子分类(多级) 比如 分类 : 家用电器 (子)分类 : 电脑 (孙)子分类 : 笔记本电脑 */ @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "parent_id") @JsonIgnore private Category parent; //父分类 @OneToMany(mappedBy = "parent", fetch = FetchType.LAZY) private Set<Category> children; //子分类集合 public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Category getParent() { return parent; } public void setParent(Category parent) { this.parent = parent; } public Set<Category> getChildren() { return children; } public void setChildren(Set<Category> children) { this.children = children; } }
0
658
3
743
6
736
4
743
6
949
11
false
false
false
false
false
true
41467_46
package leetcode.One.Thousand.boxDelivering; //你有一辆货运卡车,你需要用这一辆车把一些箱子从仓库运送到码头。这辆卡车每次运输有 箱子数目的限制 和 总重量的限制 。 // // 给你一个箱子数组 boxes 和三个整数 portsCount, maxBoxes 和 maxWeight ,其中 boxes[i] = [portsi, // weighti] 。 // // // portsi 表示第 i 个箱子需要送达的码头, weightsi 是第 i 个箱子的重量。 // portsCount 是码头的数目。 // maxBoxes 和 maxWeight 分别是卡车每趟运输箱子数目和重量的限制。 // // // 箱子需要按照 数组顺序 运输,同时每次运输需要遵循以下步骤: // // // 卡车从 boxes 队列中按顺序取出若干个箱子,但不能违反 maxBoxes 和 maxWeight 限制。 // 对于在卡车上的箱子,我们需要 按顺序 处理它们,卡车会通过 一趟行程 将最前面的箱子送到目的地码头并卸货。如果卡车已经在对应的码头,那么不需要 额外行程 //,箱子也会立马被卸货。 // 卡车上所有箱子都被卸货后,卡车需要 一趟行程 回到仓库,从箱子队列里再取出一些箱子。 // // // 卡车在将所有箱子运输并卸货后,最后必须回到仓库。 // // 请你返回将所有箱子送到相应码头的 最少行程 次数。 // // // // 示例 1: // // 输入:boxes = [[1,1],[2,1],[1,1]], portsCount = 2, maxBoxes = 3, maxWeight = 3 //输出:4 //解释:最优策略如下: //- 卡车将所有箱子装上车,到达码头 1 ,然后去码头 2 ,然后再回到码头 1 ,最后回到仓库,总共需要 4 趟行程。 //所以总行程数为 4 。 //注意到第一个和第三个箱子不能同时被卸货,因为箱子需要按顺序处理(也就是第二个箱子需要先被送到码头 2 ,然后才能处理第三个箱子)。 // // // 示例 2: // // 输入:boxes = [[1,2],[3,3],[3,1],[3,1],[2,4]], portsCount = 3, maxBoxes = 3, //maxWeight = 6 //输出:6 //解释:最优策略如下: //- 卡车首先运输第一个箱子,到达码头 1 ,然后回到仓库,总共 2 趟行程。 //- 卡车运输第二、第三、第四个箱子,到达码头 3 ,然后回到仓库,总共 2 趟行程。 //- 卡车运输第五个箱子,到达码头 3 ,回到仓库,总共 2 趟行程。 //总行程数为 2 + 2 + 2 = 6 。 // // // 示例 3: // // 输入:boxes = [[1,4],[1,2],[2,1],[2,1],[3,2],[3,4]], portsCount = 3, maxBoxes = //6, maxWeight = 7 //输出:6 //解释:最优策略如下: //- 卡车运输第一和第二个箱子,到达码头 1 ,然后回到仓库,总共 2 趟行程。 //- 卡车运输第三和第四个箱子,到达码头 2 ,然后回到仓库,总共 2 趟行程。 //- 卡车运输第五和第六个箱子,到达码头 3 ,然后回到仓库,总共 2 趟行程。 //总行程数为 2 + 2 + 2 = 6 。 // // // 示例 4: // // 输入:boxes = [[2,4],[2,5],[3,1],[3,2],[3,7],[3,1],[4,4],[1,3],[5,2]], //portsCount = 5, maxBoxes = 5, maxWeight = 7 //输出:14 //解释:最优策略如下: //- 卡车运输第一个箱子,到达码头 2 ,然后回到仓库,总共 2 趟行程。 //- 卡车运输第二个箱子,到达码头 2 ,然后回到仓库,总共 2 趟行程。 //- 卡车运输第三和第四个箱子,到达码头 3 ,然后回到仓库,总共 2 趟行程。 //- 卡车运输第五个箱子,到达码头 3 ,然后回到仓库,总共 2 趟行程。 //- 卡车运输第六和第七个箱子,到达码头 3 ,然后去码头 4 ,然后回到仓库,总共 3 趟行程。 //- 卡车运输第八和第九个箱子,到达码头 1 ,然后去码头 5 ,然后回到仓库,总共 3 趟行程。 //总行程数为 2 + 2 + 2 + 2 + 3 + 3 = 14 。 // // // // // 提示: // // // 1 <= boxes.length <= 10⁵ // 1 <= portsCount, maxBoxes, maxWeight <= 10⁵ // 1 <= portsi <= portsCount // 1 <= weightsi <= maxWeight // // Related Topics 线段树 队列 数组 动态规划 单调队列 堆(优先队列) 👍 106 👎 0 import java.util.ArrayDeque; import java.util.Deque; /** * @Desc: * @Author: 泽露 * @Date: 2022/12/5 5:22 PM * @Version: 1.initial version; 2022/12/5 5:22 PM */ public class Solution { public int boxDelivering(int[][] boxes, int portsCount, int maxBoxes, int maxWeight) { int n = boxes.length; int[] p = new int[n + 1]; int[] w = new int[n + 1]; int[] neg = new int[n + 1]; long[] W = new long[n + 1]; for (int i = 1; i <= n; ++i) { p[i] = boxes[i - 1][0]; w[i] = boxes[i - 1][1]; if (i > 1) { neg[i] = neg[i - 1] + (p[i - 1] != p[i] ? 1 : 0); } W[i] = W[i - 1] + w[i]; } Deque<Integer> opt = new ArrayDeque<Integer>(); opt.offerLast(0); int[] f = new int[n + 1]; int[] g = new int[n + 1]; for (int i = 1; i <= n; ++i) { while (i - opt.peekFirst() > maxBoxes || W[i] - W[opt.peekFirst()] > maxWeight) { opt.pollFirst(); } f[i] = g[opt.peekFirst()] + neg[i] + 2; if (i != n) { g[i] = f[i] - neg[i + 1]; while (!opt.isEmpty() && g[i] <= g[opt.peekLast()]) { opt.pollLast(); } opt.offerLast(i); } } return f[n]; } }
EarWheat/LeetCode
src/main/java/leetcode/One/Thousand/boxDelivering/Solution.java
1,965
//- 卡车运输第五个箱子,到达码头 3 ,然后回到仓库,总共 2 趟行程。
line_comment
zh-cn
package leetcode.One.Thousand.boxDelivering; //你有一辆货运卡车,你需要用这一辆车把一些箱子从仓库运送到码头。这辆卡车每次运输有 箱子数目的限制 和 总重量的限制 。 // // 给你一个箱子数组 boxes 和三个整数 portsCount, maxBoxes 和 maxWeight ,其中 boxes[i] = [portsi, // weighti] 。 // // // portsi 表示第 i 个箱子需要送达的码头, weightsi 是第 i 个箱子的重量。 // portsCount 是码头的数目。 // maxBoxes 和 maxWeight 分别是卡车每趟运输箱子数目和重量的限制。 // // // 箱子需要按照 数组顺序 运输,同时每次运输需要遵循以下步骤: // // // 卡车从 boxes 队列中按顺序取出若干个箱子,但不能违反 maxBoxes 和 maxWeight 限制。 // 对于在卡车上的箱子,我们需要 按顺序 处理它们,卡车会通过 一趟行程 将最前面的箱子送到目的地码头并卸货。如果卡车已经在对应的码头,那么不需要 额外行程 //,箱子也会立马被卸货。 // 卡车上所有箱子都被卸货后,卡车需要 一趟行程 回到仓库,从箱子队列里再取出一些箱子。 // // // 卡车在将所有箱子运输并卸货后,最后必须回到仓库。 // // 请你返回将所有箱子送到相应码头的 最少行程 次数。 // // // // 示例 1: // // 输入:boxes = [[1,1],[2,1],[1,1]], portsCount = 2, maxBoxes = 3, maxWeight = 3 //输出:4 //解释:最优策略如下: //- 卡车将所有箱子装上车,到达码头 1 ,然后去码头 2 ,然后再回到码头 1 ,最后回到仓库,总共需要 4 趟行程。 //所以总行程数为 4 。 //注意到第一个和第三个箱子不能同时被卸货,因为箱子需要按顺序处理(也就是第二个箱子需要先被送到码头 2 ,然后才能处理第三个箱子)。 // // // 示例 2: // // 输入:boxes = [[1,2],[3,3],[3,1],[3,1],[2,4]], portsCount = 3, maxBoxes = 3, //maxWeight = 6 //输出:6 //解释:最优策略如下: //- 卡车首先运输第一个箱子,到达码头 1 ,然后回到仓库,总共 2 趟行程。 //- 卡车运输第二、第三、第四个箱子,到达码头 3 ,然后回到仓库,总共 2 趟行程。 //- 卡车运输第五个箱子,到达码头 3 ,回到仓库,总共 2 趟行程。 //总行程数为 2 + 2 + 2 = 6 。 // // // 示例 3: // // 输入:boxes = [[1,4],[1,2],[2,1],[2,1],[3,2],[3,4]], portsCount = 3, maxBoxes = //6, maxWeight = 7 //输出:6 //解释:最优策略如下: //- 卡车运输第一和第二个箱子,到达码头 1 ,然后回到仓库,总共 2 趟行程。 //- 卡车运输第三和第四个箱子,到达码头 2 ,然后回到仓库,总共 2 趟行程。 //- 卡车运输第五和第六个箱子,到达码头 3 ,然后回到仓库,总共 2 趟行程。 //总行程数为 2 + 2 + 2 = 6 。 // // // 示例 4: // // 输入:boxes = [[2,4],[2,5],[3,1],[3,2],[3,7],[3,1],[4,4],[1,3],[5,2]], //portsCount = 5, maxBoxes = 5, maxWeight = 7 //输出:14 //解释:最优策略如下: //- 卡车运输第一个箱子,到达码头 2 ,然后回到仓库,总共 2 趟行程。 //- 卡车运输第二个箱子,到达码头 2 ,然后回到仓库,总共 2 趟行程。 //- 卡车运输第三和第四个箱子,到达码头 3 ,然后回到仓库,总共 2 趟行程。 //- <SUF> //- 卡车运输第六和第七个箱子,到达码头 3 ,然后去码头 4 ,然后回到仓库,总共 3 趟行程。 //- 卡车运输第八和第九个箱子,到达码头 1 ,然后去码头 5 ,然后回到仓库,总共 3 趟行程。 //总行程数为 2 + 2 + 2 + 2 + 3 + 3 = 14 。 // // // // // 提示: // // // 1 <= boxes.length <= 10⁵ // 1 <= portsCount, maxBoxes, maxWeight <= 10⁵ // 1 <= portsi <= portsCount // 1 <= weightsi <= maxWeight // // Related Topics 线段树 队列 数组 动态规划 单调队列 堆(优先队列) 👍 106 👎 0 import java.util.ArrayDeque; import java.util.Deque; /** * @Desc: * @Author: 泽露 * @Date: 2022/12/5 5:22 PM * @Version: 1.initial version; 2022/12/5 5:22 PM */ public class Solution { public int boxDelivering(int[][] boxes, int portsCount, int maxBoxes, int maxWeight) { int n = boxes.length; int[] p = new int[n + 1]; int[] w = new int[n + 1]; int[] neg = new int[n + 1]; long[] W = new long[n + 1]; for (int i = 1; i <= n; ++i) { p[i] = boxes[i - 1][0]; w[i] = boxes[i - 1][1]; if (i > 1) { neg[i] = neg[i - 1] + (p[i - 1] != p[i] ? 1 : 0); } W[i] = W[i - 1] + w[i]; } Deque<Integer> opt = new ArrayDeque<Integer>(); opt.offerLast(0); int[] f = new int[n + 1]; int[] g = new int[n + 1]; for (int i = 1; i <= n; ++i) { while (i - opt.peekFirst() > maxBoxes || W[i] - W[opt.peekFirst()] > maxWeight) { opt.pollFirst(); } f[i] = g[opt.peekFirst()] + neg[i] + 2; if (i != n) { g[i] = f[i] - neg[i + 1]; while (!opt.isEmpty() && g[i] <= g[opt.peekLast()]) { opt.pollLast(); } opt.offerLast(i); } } return f[n]; } }
0
1,631
26
1,965
35
1,797
27
1,965
35
2,585
49
false
false
false
false
false
true
46861_2
package JavaBasicAPI; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import BrowserDrivers.GetBrowserDriver; //10.27 public class GetWebElementAttributeTesting { public WebDriver driver; @Test public void getWebElementAttributeTest() throws InterruptedException { driver.get("http://www.baidu.com"); String text="比利时遭遇恐怖袭击"; WebElement SearchBox = driver.findElement(By.id("kw")); //将搜索框的id实例化 SearchBox.sendKeys(text); String innerText = SearchBox.getAttribute("value"); //调用attribute方法,并获取搜索框value的值(就是搜索文字的内容) Thread.sleep(3000); Assert.assertEquals(innerText, "比利时遭遇恐怖袭击"); } @BeforeMethod public void beforeMethod() { driver = GetBrowserDriver.GetChromeDriver(); } @AfterMethod public void afterMethod() { driver.quit(); } }
Eason0731/MySeleniumCases
src/JavaBasicAPI/GetWebElementAttributeTesting.java
304
//将搜索框的id实例化
line_comment
zh-cn
package JavaBasicAPI; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import BrowserDrivers.GetBrowserDriver; //10.27 public class GetWebElementAttributeTesting { public WebDriver driver; @Test public void getWebElementAttributeTest() throws InterruptedException { driver.get("http://www.baidu.com"); String text="比利时遭遇恐怖袭击"; WebElement SearchBox = driver.findElement(By.id("kw")); //将搜 <SUF> SearchBox.sendKeys(text); String innerText = SearchBox.getAttribute("value"); //调用attribute方法,并获取搜索框value的值(就是搜索文字的内容) Thread.sleep(3000); Assert.assertEquals(innerText, "比利时遭遇恐怖袭击"); } @BeforeMethod public void beforeMethod() { driver = GetBrowserDriver.GetChromeDriver(); } @AfterMethod public void afterMethod() { driver.quit(); } }
0
238
8
304
8
325
8
304
8
409
14
false
false
false
false
false
true
38290_63
package com.example.woops.cookit.activity; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Environment; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.Toast; import com.example.woops.cookit.R; import com.example.woops.cookit.bean.Store; import com.example.woops.cookit.db.CookitDB; import com.example.woops.cookit.test.SpliteGenerate; import com.example.woops.cookit.util.JsonParser; import com.iflytek.cloud.ErrorCode; import com.iflytek.cloud.InitListener; import com.iflytek.cloud.RecognizerListener; import com.iflytek.cloud.RecognizerResult; import com.iflytek.cloud.SpeechConstant; import com.iflytek.cloud.SpeechError; import com.iflytek.cloud.SpeechRecognizer; import com.iflytek.cloud.SpeechSynthesizer; import com.iflytek.cloud.SpeechUtility; import com.iflytek.cloud.SynthesizerListener; /** * 语音转文字类,根据文字识别 */ public class ItaActivity extends AppCompatActivity { //显示框 private EditText mResult; //设置存储容器 private SharedPreferences mSharedPreferences; //设置语音识别对象 private SpeechRecognizer mIat; //迷之Toast,删掉会出现奇怪的错误 private Toast mToast; //后加的内容 // 语音合成对象 private SpeechSynthesizer mTts; //缓冲进度 private int mPercentForBuffering = 0; //播放进度 private int mPercentForPlaying = 0; private String text; private CookitDB mCookit; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_ita); SpeechUtility.createUtility(this, "appid=570b2ef9"); //初始化语音识别对象 mIat = SpeechRecognizer.createRecognizer(this, mInitListener); // 初始化合成对象 mTts = SpeechSynthesizer.createSynthesizer(this, mTtsInitListener); mSharedPreferences = getSharedPreferences("com.iflytek.setting", Activity.MODE_PRIVATE); mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT); //初始化UI initLayout(); //初始化数据库 mCookit = CookitDB.getInstance(this); } private void initLayout() { mResult = (EditText) findViewById(R.id.iat_text); } //设置返回值参数 int ret = 0; //普通的听写功能 public void startClick(View view) { mResult.setText(null); setParams(); ret = mIat.startListening(mRecognizerListener); //貌似没有卵用 if (ret != ErrorCode.SUCCESS) { showTip("听写失败,错误码:" + ret); } else { showTip("请开始BB"); } } //设置跳转至发音Activity按钮 public void ttsClick(View view) { startActivity(new Intent(this, TtsActivity.class)); } //显示数据库 public void readDB(View view){ mCookit.loadDataBaseTest(); } //设置参数 private void setParams() { // 清空参数 mIat.setParameter(SpeechConstant.PARAMS, null); String lag = mSharedPreferences.getString("iat_language_preference", "mandarin"); // 设置引擎 mIat.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD); // 设置返回结果格式 mIat.setParameter(SpeechConstant.RESULT_TYPE, "json"); if (lag.equals("en_us")) { // 设置语言 mIat.setParameter(SpeechConstant.LANGUAGE, "en_us"); } else { // 设置语言 mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn"); // 设置语言区域 mIat.setParameter(SpeechConstant.ACCENT, lag); } // 设置语音前端点:静音超时时间,即用户多长时间不说话则当做超时处理 mIat.setParameter(SpeechConstant.VAD_BOS, mSharedPreferences.getString("iat_vadbos_preference", "4000")); // 设置语音后端点:后端点静音检测时间,即用户停止说话多长时间内即认为不再输入, 自动停止录音 mIat.setParameter(SpeechConstant.VAD_EOS, mSharedPreferences.getString("iat_vadeos_preference", "1000")); // 设置标点符号,设置为"0"返回结果无标点,设置为"1"返回结果有标点 mIat.setParameter(SpeechConstant.ASR_PTT, mSharedPreferences.getString("iat_punc_preference", "1")); // 设置音频保存路径,保存音频格式支持pcm、wav,设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限 // 注:AUDIO_FORMAT参数语记需要更新版本才能生效 mIat.setParameter(SpeechConstant.AUDIO_FORMAT, "wav"); mIat.setParameter(SpeechConstant.ASR_AUDIO_PATH, Environment.getExternalStorageDirectory() + "/msc/iat.wav"); // 清空参数 mTts.setParameter(SpeechConstant.PARAMS, null); //设置合成 //设置使用云端引擎 mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD); //设置发音人 mTts.setParameter(SpeechConstant.VOICE_NAME, "xiaoqian"); //设置合成语速 mTts.setParameter(SpeechConstant.SPEED, mSharedPreferences.getString("speed_preference", "50")); //设置合成音调 mTts.setParameter(SpeechConstant.PITCH, mSharedPreferences.getString("pitch_preference", "50")); //设置合成音量 mTts.setParameter(SpeechConstant.VOLUME, mSharedPreferences.getString("volume_preference", "50")); //设置播放器音频流类型 mTts.setParameter(SpeechConstant.STREAM_TYPE, mSharedPreferences.getString("stream_preference", "3")); // 设置播放合成音频打断音乐播放,默认为true mTts.setParameter(SpeechConstant.KEY_REQUEST_FOCUS, "true"); // 设置音频保存路径,保存音频格式支持pcm、wav,设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限 // 注:AUDIO_FORMAT参数语记需要更新版本才能生效 mTts.setParameter(SpeechConstant.AUDIO_FORMAT, "wav"); mTts.setParameter(SpeechConstant.TTS_AUDIO_PATH, Environment.getExternalStorageDirectory() + "/msc/tts.wav"); } /** * 初始化监听器。 */ private InitListener mInitListener = new InitListener() { @Override public void onInit(int code) { Log.d("TAG", "SpeechRecognizer init() code = " + code); if (code != ErrorCode.SUCCESS) { showTip("初始化失败,错误码:" + code); } } }; /** * 初始化监听。 */ private InitListener mTtsInitListener = new InitListener() { @Override public void onInit(int code) { Log.d("TAG", "InitListener init() code = " + code); if (code != ErrorCode.SUCCESS) { showTip("初始化失败,错误码:" + code); } else { // 初始化成功,之后可以调用startSpeaking方法 // 注:有的开发者在onCreate方法中创建完合成对象之后马上就调用startSpeaking进行合成, // 正确的做法是将onCreate中的startSpeaking调用移至这里 } } }; private void showTip(final String str) { runOnUiThread(new Runnable() { @Override public void run() { mToast.setText(str); mToast.show(); } }); } /** * 合成回调监听。 */ private SynthesizerListener mTtsListener = new SynthesizerListener() { @Override public void onSpeakBegin() { showTip("开始播放"); } @Override public void onSpeakPaused() { showTip("暂停播放"); } @Override public void onSpeakResumed() { showTip("继续播放"); } @Override public void onBufferProgress(int percent, int beginPos, int endPos, String info) { // 合成进度 mPercentForBuffering = percent; showTip(String.format(getString(R.string.tts_toast_format), mPercentForBuffering, mPercentForPlaying)); } @Override public void onSpeakProgress(int percent, int beginPos, int endPos) { // 播放进度 mPercentForPlaying = percent; showTip(String.format(getString(R.string.tts_toast_format), mPercentForBuffering, mPercentForPlaying)); } @Override public void onCompleted(SpeechError error) { if (error == null) { showTip("播放完成"); } else if (error != null) { showTip(error.getPlainDescription(true)); } } @Override public void onEvent(int eventType, int arg1, int arg2, Bundle obj) { // 以下代码用于获取与云端的会话id,当业务出错时将会话id提供给技术支持人员,可用于查询会话日志,定位出错原因 // 若使用本地能力,会话id为null // if (SpeechEvent.EVENT_SESSION_ID == eventType) { // String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID); // Log.d(TAG, "session id =" + sid); // } } }; private RecognizerListener mRecognizerListener = new RecognizerListener() { @Override public void onBeginOfSpeech() { // 此回调表示:sdk内部录音机已经准备好了,用户可以开始语音输入 showTip("开始说话"); } @Override public void onError(SpeechError error) { // Tips: // 错误码:10118(您没有说话),可能是录音机权限被禁,需要提示用户打开应用的录音权限。 showTip(error.getPlainDescription(true)); } @Override public void onEndOfSpeech() { // 此回调表示:检测到了语音的尾端点,已经进入识别过程,不再接受语音输入 showTip("结束说话"); text = mResult.getText().toString(); int num = text.length(); if (num >= 6) { //调用分割测试类显示结果 SpliteGenerate mSpliteGenerate = new SpliteGenerate(text); //获取分类处理好的数据实体类 Store mStore = mSpliteGenerate.classification(); if (mStore.getOperate().equals("放入")){ //将数据存入数据库中 mCookit.savaStore(mStore); }else if (mStore.getOperate().equals("拿走")){ mCookit.deleteDataBaseTest(); } //mSpliteGenerate.displayStore(); } Log.d("MY", String.valueOf(num)); mTts.startSpeaking(text, mTtsListener); } @Override public void onResult(RecognizerResult results, boolean isLast) { text = JsonParser.parseIatResult(results.getResultString()); mResult.append(text); mResult.setSelection(mResult.length()); if (isLast) { //TODO 最后的结果 } } @Override public void onVolumeChanged(int volume, byte[] data) { showTip("当前正在说话,音量大小:" + volume); Log.d("TAG", "返回音频数据:" + data.length); } @Override public void onEvent(int eventType, int arg1, int arg2, Bundle obj) { // 以下代码用于获取与云端的会话id,当业务出错时将会话id提供给技术支持人员,可用于查询会话日志,定位出错原因 // 若使用本地能力,会话id为null // if (SpeechEvent.EVENT_SESSION_ID == eventType) { // String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID); // Log.d(TAG, "session id =" + sid); // } } }; }
Eccolala/BCCookIt
app/src/main/java/com/example/woops/cookit/activity/ItaActivity.java
2,987
// 以下代码用于获取与云端的会话id,当业务出错时将会话id提供给技术支持人员,可用于查询会话日志,定位出错原因
line_comment
zh-cn
package com.example.woops.cookit.activity; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Environment; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.Toast; import com.example.woops.cookit.R; import com.example.woops.cookit.bean.Store; import com.example.woops.cookit.db.CookitDB; import com.example.woops.cookit.test.SpliteGenerate; import com.example.woops.cookit.util.JsonParser; import com.iflytek.cloud.ErrorCode; import com.iflytek.cloud.InitListener; import com.iflytek.cloud.RecognizerListener; import com.iflytek.cloud.RecognizerResult; import com.iflytek.cloud.SpeechConstant; import com.iflytek.cloud.SpeechError; import com.iflytek.cloud.SpeechRecognizer; import com.iflytek.cloud.SpeechSynthesizer; import com.iflytek.cloud.SpeechUtility; import com.iflytek.cloud.SynthesizerListener; /** * 语音转文字类,根据文字识别 */ public class ItaActivity extends AppCompatActivity { //显示框 private EditText mResult; //设置存储容器 private SharedPreferences mSharedPreferences; //设置语音识别对象 private SpeechRecognizer mIat; //迷之Toast,删掉会出现奇怪的错误 private Toast mToast; //后加的内容 // 语音合成对象 private SpeechSynthesizer mTts; //缓冲进度 private int mPercentForBuffering = 0; //播放进度 private int mPercentForPlaying = 0; private String text; private CookitDB mCookit; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_ita); SpeechUtility.createUtility(this, "appid=570b2ef9"); //初始化语音识别对象 mIat = SpeechRecognizer.createRecognizer(this, mInitListener); // 初始化合成对象 mTts = SpeechSynthesizer.createSynthesizer(this, mTtsInitListener); mSharedPreferences = getSharedPreferences("com.iflytek.setting", Activity.MODE_PRIVATE); mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT); //初始化UI initLayout(); //初始化数据库 mCookit = CookitDB.getInstance(this); } private void initLayout() { mResult = (EditText) findViewById(R.id.iat_text); } //设置返回值参数 int ret = 0; //普通的听写功能 public void startClick(View view) { mResult.setText(null); setParams(); ret = mIat.startListening(mRecognizerListener); //貌似没有卵用 if (ret != ErrorCode.SUCCESS) { showTip("听写失败,错误码:" + ret); } else { showTip("请开始BB"); } } //设置跳转至发音Activity按钮 public void ttsClick(View view) { startActivity(new Intent(this, TtsActivity.class)); } //显示数据库 public void readDB(View view){ mCookit.loadDataBaseTest(); } //设置参数 private void setParams() { // 清空参数 mIat.setParameter(SpeechConstant.PARAMS, null); String lag = mSharedPreferences.getString("iat_language_preference", "mandarin"); // 设置引擎 mIat.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD); // 设置返回结果格式 mIat.setParameter(SpeechConstant.RESULT_TYPE, "json"); if (lag.equals("en_us")) { // 设置语言 mIat.setParameter(SpeechConstant.LANGUAGE, "en_us"); } else { // 设置语言 mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn"); // 设置语言区域 mIat.setParameter(SpeechConstant.ACCENT, lag); } // 设置语音前端点:静音超时时间,即用户多长时间不说话则当做超时处理 mIat.setParameter(SpeechConstant.VAD_BOS, mSharedPreferences.getString("iat_vadbos_preference", "4000")); // 设置语音后端点:后端点静音检测时间,即用户停止说话多长时间内即认为不再输入, 自动停止录音 mIat.setParameter(SpeechConstant.VAD_EOS, mSharedPreferences.getString("iat_vadeos_preference", "1000")); // 设置标点符号,设置为"0"返回结果无标点,设置为"1"返回结果有标点 mIat.setParameter(SpeechConstant.ASR_PTT, mSharedPreferences.getString("iat_punc_preference", "1")); // 设置音频保存路径,保存音频格式支持pcm、wav,设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限 // 注:AUDIO_FORMAT参数语记需要更新版本才能生效 mIat.setParameter(SpeechConstant.AUDIO_FORMAT, "wav"); mIat.setParameter(SpeechConstant.ASR_AUDIO_PATH, Environment.getExternalStorageDirectory() + "/msc/iat.wav"); // 清空参数 mTts.setParameter(SpeechConstant.PARAMS, null); //设置合成 //设置使用云端引擎 mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD); //设置发音人 mTts.setParameter(SpeechConstant.VOICE_NAME, "xiaoqian"); //设置合成语速 mTts.setParameter(SpeechConstant.SPEED, mSharedPreferences.getString("speed_preference", "50")); //设置合成音调 mTts.setParameter(SpeechConstant.PITCH, mSharedPreferences.getString("pitch_preference", "50")); //设置合成音量 mTts.setParameter(SpeechConstant.VOLUME, mSharedPreferences.getString("volume_preference", "50")); //设置播放器音频流类型 mTts.setParameter(SpeechConstant.STREAM_TYPE, mSharedPreferences.getString("stream_preference", "3")); // 设置播放合成音频打断音乐播放,默认为true mTts.setParameter(SpeechConstant.KEY_REQUEST_FOCUS, "true"); // 设置音频保存路径,保存音频格式支持pcm、wav,设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限 // 注:AUDIO_FORMAT参数语记需要更新版本才能生效 mTts.setParameter(SpeechConstant.AUDIO_FORMAT, "wav"); mTts.setParameter(SpeechConstant.TTS_AUDIO_PATH, Environment.getExternalStorageDirectory() + "/msc/tts.wav"); } /** * 初始化监听器。 */ private InitListener mInitListener = new InitListener() { @Override public void onInit(int code) { Log.d("TAG", "SpeechRecognizer init() code = " + code); if (code != ErrorCode.SUCCESS) { showTip("初始化失败,错误码:" + code); } } }; /** * 初始化监听。 */ private InitListener mTtsInitListener = new InitListener() { @Override public void onInit(int code) { Log.d("TAG", "InitListener init() code = " + code); if (code != ErrorCode.SUCCESS) { showTip("初始化失败,错误码:" + code); } else { // 初始化成功,之后可以调用startSpeaking方法 // 注:有的开发者在onCreate方法中创建完合成对象之后马上就调用startSpeaking进行合成, // 正确的做法是将onCreate中的startSpeaking调用移至这里 } } }; private void showTip(final String str) { runOnUiThread(new Runnable() { @Override public void run() { mToast.setText(str); mToast.show(); } }); } /** * 合成回调监听。 */ private SynthesizerListener mTtsListener = new SynthesizerListener() { @Override public void onSpeakBegin() { showTip("开始播放"); } @Override public void onSpeakPaused() { showTip("暂停播放"); } @Override public void onSpeakResumed() { showTip("继续播放"); } @Override public void onBufferProgress(int percent, int beginPos, int endPos, String info) { // 合成进度 mPercentForBuffering = percent; showTip(String.format(getString(R.string.tts_toast_format), mPercentForBuffering, mPercentForPlaying)); } @Override public void onSpeakProgress(int percent, int beginPos, int endPos) { // 播放进度 mPercentForPlaying = percent; showTip(String.format(getString(R.string.tts_toast_format), mPercentForBuffering, mPercentForPlaying)); } @Override public void onCompleted(SpeechError error) { if (error == null) { showTip("播放完成"); } else if (error != null) { showTip(error.getPlainDescription(true)); } } @Override public void onEvent(int eventType, int arg1, int arg2, Bundle obj) { // 以下代码用于获取与云端的会话id,当业务出错时将会话id提供给技术支持人员,可用于查询会话日志,定位出错原因 // 若使用本地能力,会话id为null // if (SpeechEvent.EVENT_SESSION_ID == eventType) { // String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID); // Log.d(TAG, "session id =" + sid); // } } }; private RecognizerListener mRecognizerListener = new RecognizerListener() { @Override public void onBeginOfSpeech() { // 此回调表示:sdk内部录音机已经准备好了,用户可以开始语音输入 showTip("开始说话"); } @Override public void onError(SpeechError error) { // Tips: // 错误码:10118(您没有说话),可能是录音机权限被禁,需要提示用户打开应用的录音权限。 showTip(error.getPlainDescription(true)); } @Override public void onEndOfSpeech() { // 此回调表示:检测到了语音的尾端点,已经进入识别过程,不再接受语音输入 showTip("结束说话"); text = mResult.getText().toString(); int num = text.length(); if (num >= 6) { //调用分割测试类显示结果 SpliteGenerate mSpliteGenerate = new SpliteGenerate(text); //获取分类处理好的数据实体类 Store mStore = mSpliteGenerate.classification(); if (mStore.getOperate().equals("放入")){ //将数据存入数据库中 mCookit.savaStore(mStore); }else if (mStore.getOperate().equals("拿走")){ mCookit.deleteDataBaseTest(); } //mSpliteGenerate.displayStore(); } Log.d("MY", String.valueOf(num)); mTts.startSpeaking(text, mTtsListener); } @Override public void onResult(RecognizerResult results, boolean isLast) { text = JsonParser.parseIatResult(results.getResultString()); mResult.append(text); mResult.setSelection(mResult.length()); if (isLast) { //TODO 最后的结果 } } @Override public void onVolumeChanged(int volume, byte[] data) { showTip("当前正在说话,音量大小:" + volume); Log.d("TAG", "返回音频数据:" + data.length); } @Override public void onEvent(int eventType, int arg1, int arg2, Bundle obj) { // 以下 <SUF> // 若使用本地能力,会话id为null // if (SpeechEvent.EVENT_SESSION_ID == eventType) { // String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID); // Log.d(TAG, "session id =" + sid); // } } }; }
0
2,679
37
2,987
40
3,100
34
2,987
40
4,040
62
false
false
false
false
false
true
55510_2
class Solution529 { public char[][] updateBoard(char[][] board, int[] click) { boolean[][] visited = new boolean[board.length][board[0].length]; if (board[click[0]][click[1]] == 'M') { // 规则 1,点到雷改为X退出游戏 board[click[0]][click[1]] = 'X'; } else if (board[click[0]][click[1]] == 'E') { // 只有当点的是未被访问过的格子E才进入递归和判断 dfs(visited, board, click[0], click[1]); } return board; } public void dfs(boolean[][] visited, char[][] board, int x, int y) { // 访问当前结点 visited[x][y] = true; if (count(board, x, y) == 0) { board[x][y] = 'B'; int[] diff = new int[] {-1, 0, 1}; // 访问周围结点 for (int i = 0; i < diff.length; i++) for (int j = 0; j < diff.length; j++) { if (diff[i] == 0 && diff[j] == 0) continue; if (x + diff[i] < 0 || x + diff[i] >= board.length || y + diff[j] < 0 || y + diff[j] >= board[0].length || visited[x + diff[i]][y + diff[j]]) continue; dfs(visited, board, x + diff[i], y + diff[j]); } } else board[x][y] = (char) (count(board, x, y) + '0'); } public int count(char[][] board, int x, int y) { // 确定周围雷的数量 int res = 0; int[] diff = new int[] {-1, 0, 1}; for (int i = 0; i < diff.length; i++) for (int j = 0; j < diff.length; j++) { if (diff[i] == 0 && diff[j] == 0) continue; if (x + diff[i] < 0 || x + diff[i] >= board.length || y + diff[j] < 0 || y + diff[j] >= board[0].length) continue; if (board[x + diff[i]][y + diff[j]] == 'M') res++; } return res; } } /** * 点击的格子是M,直接改为X并退出游戏 * 点击的格子是是B或者数字,什么也不做退出游戏(题解里其实可以加上这个else if的判断) * 点击的格子是E才扩展:计算当前格子周围的雷的数量cnt,决定当前格子从E改为B还是改为数字;若改为数字则终止扩展(这也是为什么示例1还剩一个E),若改为B则继续扩展(遇到E才扩展,遇到B或者数字则终止) */
Echlorine/leetcode-solution
Java/Solution529.java
733
// 访问当前结点
line_comment
zh-cn
class Solution529 { public char[][] updateBoard(char[][] board, int[] click) { boolean[][] visited = new boolean[board.length][board[0].length]; if (board[click[0]][click[1]] == 'M') { // 规则 1,点到雷改为X退出游戏 board[click[0]][click[1]] = 'X'; } else if (board[click[0]][click[1]] == 'E') { // 只有当点的是未被访问过的格子E才进入递归和判断 dfs(visited, board, click[0], click[1]); } return board; } public void dfs(boolean[][] visited, char[][] board, int x, int y) { // 访问 <SUF> visited[x][y] = true; if (count(board, x, y) == 0) { board[x][y] = 'B'; int[] diff = new int[] {-1, 0, 1}; // 访问周围结点 for (int i = 0; i < diff.length; i++) for (int j = 0; j < diff.length; j++) { if (diff[i] == 0 && diff[j] == 0) continue; if (x + diff[i] < 0 || x + diff[i] >= board.length || y + diff[j] < 0 || y + diff[j] >= board[0].length || visited[x + diff[i]][y + diff[j]]) continue; dfs(visited, board, x + diff[i], y + diff[j]); } } else board[x][y] = (char) (count(board, x, y) + '0'); } public int count(char[][] board, int x, int y) { // 确定周围雷的数量 int res = 0; int[] diff = new int[] {-1, 0, 1}; for (int i = 0; i < diff.length; i++) for (int j = 0; j < diff.length; j++) { if (diff[i] == 0 && diff[j] == 0) continue; if (x + diff[i] < 0 || x + diff[i] >= board.length || y + diff[j] < 0 || y + diff[j] >= board[0].length) continue; if (board[x + diff[i]][y + diff[j]] == 'M') res++; } return res; } } /** * 点击的格子是M,直接改为X并退出游戏 * 点击的格子是是B或者数字,什么也不做退出游戏(题解里其实可以加上这个else if的判断) * 点击的格子是E才扩展:计算当前格子周围的雷的数量cnt,决定当前格子从E改为B还是改为数字;若改为数字则终止扩展(这也是为什么示例1还剩一个E),若改为B则继续扩展(遇到E才扩展,遇到B或者数字则终止) */
0
685
7
733
5
739
6
733
5
911
10
false
false
false
false
false
true
66465_14
package alg_02_train_dm._17_day_二叉树二_二刷; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; /** * @Author Wuyj * @DateTime 2023-08-10 19:10 * @Version 1.0 */ public class _10_257_binary_tree_paths2 { // KeyPoint 方法二 BFS => 高性能,打败 100 % => 需要掌握 public List<String> binaryTreePaths(TreeNode root) { // 输入: // 1 // / \ // 2 3 // \ // 5 // // 输出: ["1->2->5", "1->3"] List<String> res = new ArrayList<String>(); if (root == null) return res; Queue<TreeNode> nodeQueue = new LinkedList<TreeNode>(); // 在 BFS 过程中,每遍历一个节点,都会有一个 path 与之对应 // 直到遇到叶子节点,将完整 path 加入到 res 中 Queue<String> pathQueue = new LinkedList<String>(); nodeQueue.offer(root); // KeyPoint 区别:两者 API // 1.Integer.toString() // 2.Integer.parseInt() pathQueue.offer(Integer.toString(root.val)); while (!nodeQueue.isEmpty()) { TreeNode node = nodeQueue.poll(); String path = pathQueue.poll(); // 叶子节点 if (node.left == null && node.right == null) { res.add(path); // 结束后面循环 continue; } if (node.left != null) { nodeQueue.offer(node.left); // KeyPoint 注意事项 // append(node.left.val),不是 node.left,node.left 表示节点 // 同时,因为对 node.left 已经做了判空,不存在空指针异常 pathQueue.offer(new StringBuilder(path).append("->").append(node.left.val).toString()); } if (node.right != null) { nodeQueue.offer(node.right); pathQueue.offer(new StringBuilder(path).append("->").append(node.right.val).toString()); } } return res; } }
EchoWuyj/LeetCode
LC_douma/src/main/java/alg_02_train_dm/_17_day_二叉树二_二刷/_10_257_binary_tree_paths2.java
565
// 同时,因为对 node.left 已经做了判空,不存在空指针异常
line_comment
zh-cn
package alg_02_train_dm._17_day_二叉树二_二刷; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; /** * @Author Wuyj * @DateTime 2023-08-10 19:10 * @Version 1.0 */ public class _10_257_binary_tree_paths2 { // KeyPoint 方法二 BFS => 高性能,打败 100 % => 需要掌握 public List<String> binaryTreePaths(TreeNode root) { // 输入: // 1 // / \ // 2 3 // \ // 5 // // 输出: ["1->2->5", "1->3"] List<String> res = new ArrayList<String>(); if (root == null) return res; Queue<TreeNode> nodeQueue = new LinkedList<TreeNode>(); // 在 BFS 过程中,每遍历一个节点,都会有一个 path 与之对应 // 直到遇到叶子节点,将完整 path 加入到 res 中 Queue<String> pathQueue = new LinkedList<String>(); nodeQueue.offer(root); // KeyPoint 区别:两者 API // 1.Integer.toString() // 2.Integer.parseInt() pathQueue.offer(Integer.toString(root.val)); while (!nodeQueue.isEmpty()) { TreeNode node = nodeQueue.poll(); String path = pathQueue.poll(); // 叶子节点 if (node.left == null && node.right == null) { res.add(path); // 结束后面循环 continue; } if (node.left != null) { nodeQueue.offer(node.left); // KeyPoint 注意事项 // append(node.left.val),不是 node.left,node.left 表示节点 // 同时 <SUF> pathQueue.offer(new StringBuilder(path).append("->").append(node.left.val).toString()); } if (node.right != null) { nodeQueue.offer(node.right); pathQueue.offer(new StringBuilder(path).append("->").append(node.right.val).toString()); } } return res; } }
0
498
21
565
20
584
19
565
20
706
33
false
false
false
false
false
true
24845_2
package ch12DP; import java.util.Scanner; public class Karma46TakeMaterial { public static void main(String[] args) { int[] weight = {1,3,4}; int[] value = {15,20,30}; int bagSize = 4; testWeightBagProblem2(weight,value,bagSize); } /** * 动态规划获得结果 * @param weight 物品的重量 * @param value 物品的价值 * @param bagSize 背包的容量 */ public static void testWeightBagProblem(int[] weight, int[] value, int bagSize){ // 创建dp数组 int goods = weight.length; // 获取物品的数量 int[][] dp = new int[goods][bagSize + 1]; // 初始化dp数组 // 创建数组后,其中默认的值就是0 /* Arrays.sort(weight); for (int j = weight[0]; j <= bagSize; j++) { dp[0][j] = value[0]; }*/ for (int j = 0; j <= bagSize; j++) { if (j >= weight[0]) { dp[0][j] = value[0]; // 当背包容量大于等于第一个物品的重量时,可以选择装入该物品 } else { dp[0][j] = 0; // 否则,背包内无法装入该物品,价值为0 } } // 填充dp数组 for (int i = 1; i < weight.length; i++) { for (int j = 0; j <= bagSize; j++) { if (j < weight[i]) { /** * 当前背包的容量都没有当前物品i大的时候,是不放物品i的 * 那么前i-1个物品能放下的最大价值就是当前情况的最大价值 */ dp[i][j] = dp[i-1][j]; } else { /** * 当前背包的容量可以放下物品i * 那么此时分两种情况: * 1、不放物品i * 2、放物品i * 比较这两种情况下,哪种背包中物品的最大价值最大 */ dp[i][j] = Math.max(dp[i-1][j] , dp[i-1][j-weight[i]] + value[i]); } } } // 打印dp数组 for (int i = 0; i < goods; i++) { for (int j = 0; j <= bagSize; j++) { System.out.print(dp[i][j] + "\t"); } System.out.println("\n"); } } /* * 不能正序可以这么理解: 虽然是一维数组,但是性质和二维背包差不多。 * 我们先来理解倒序遍历,从最后一个元素往前看,看到的都是“上一层的元素”然后每遍历到一个元素,就把当前元素赋值成“当前层”的。 * 这样得到的背包,因为每个元素加上的都是上一层的对应的物品value,所以不会重复。 * 因为二维数组是根据左上元素来求的,一维数组自然就是靠左边来求的。 * 倒序的时候左边元素再刷新前都是上一层的数据,但正序就不一样了,正序的时候,左边的元素刚刚刷新过,也就是左边的元素已经是本层的了, * 意味着什么 这样会导致一个物品反复加好几次。 * */ public static void testWeightBagProblem2(int[] weight, int[] value, int bagWeight){ int[] dp = new int[bagWeight + 1]; dp[0] = 0; //本来 应该每个值都赋一个 不影响后面比较max的最小值 敲定为0 但是这里不用赋值为0 默认都是0 /* * dp[j] = max(dp[j],dp[j - weight[i]] + value[i]) * */ int len = weight.length; for (int i = 0; i < len; i++) { for (int j = bagWeight; j >= weight[i] ; j--) { dp[j] = Math.max(dp[j],dp[j - weight[i]] + value[i]); } } for (int j = 0; j <= bagWeight; j++){ System.out.print(dp[j] + " "); } } }
EddieAy/Leetcode
ch12DP/Karma46TakeMaterial.java
1,097
// 获取物品的数量
line_comment
zh-cn
package ch12DP; import java.util.Scanner; public class Karma46TakeMaterial { public static void main(String[] args) { int[] weight = {1,3,4}; int[] value = {15,20,30}; int bagSize = 4; testWeightBagProblem2(weight,value,bagSize); } /** * 动态规划获得结果 * @param weight 物品的重量 * @param value 物品的价值 * @param bagSize 背包的容量 */ public static void testWeightBagProblem(int[] weight, int[] value, int bagSize){ // 创建dp数组 int goods = weight.length; // 获取 <SUF> int[][] dp = new int[goods][bagSize + 1]; // 初始化dp数组 // 创建数组后,其中默认的值就是0 /* Arrays.sort(weight); for (int j = weight[0]; j <= bagSize; j++) { dp[0][j] = value[0]; }*/ for (int j = 0; j <= bagSize; j++) { if (j >= weight[0]) { dp[0][j] = value[0]; // 当背包容量大于等于第一个物品的重量时,可以选择装入该物品 } else { dp[0][j] = 0; // 否则,背包内无法装入该物品,价值为0 } } // 填充dp数组 for (int i = 1; i < weight.length; i++) { for (int j = 0; j <= bagSize; j++) { if (j < weight[i]) { /** * 当前背包的容量都没有当前物品i大的时候,是不放物品i的 * 那么前i-1个物品能放下的最大价值就是当前情况的最大价值 */ dp[i][j] = dp[i-1][j]; } else { /** * 当前背包的容量可以放下物品i * 那么此时分两种情况: * 1、不放物品i * 2、放物品i * 比较这两种情况下,哪种背包中物品的最大价值最大 */ dp[i][j] = Math.max(dp[i-1][j] , dp[i-1][j-weight[i]] + value[i]); } } } // 打印dp数组 for (int i = 0; i < goods; i++) { for (int j = 0; j <= bagSize; j++) { System.out.print(dp[i][j] + "\t"); } System.out.println("\n"); } } /* * 不能正序可以这么理解: 虽然是一维数组,但是性质和二维背包差不多。 * 我们先来理解倒序遍历,从最后一个元素往前看,看到的都是“上一层的元素”然后每遍历到一个元素,就把当前元素赋值成“当前层”的。 * 这样得到的背包,因为每个元素加上的都是上一层的对应的物品value,所以不会重复。 * 因为二维数组是根据左上元素来求的,一维数组自然就是靠左边来求的。 * 倒序的时候左边元素再刷新前都是上一层的数据,但正序就不一样了,正序的时候,左边的元素刚刚刷新过,也就是左边的元素已经是本层的了, * 意味着什么 这样会导致一个物品反复加好几次。 * */ public static void testWeightBagProblem2(int[] weight, int[] value, int bagWeight){ int[] dp = new int[bagWeight + 1]; dp[0] = 0; //本来 应该每个值都赋一个 不影响后面比较max的最小值 敲定为0 但是这里不用赋值为0 默认都是0 /* * dp[j] = max(dp[j],dp[j - weight[i]] + value[i]) * */ int len = weight.length; for (int i = 0; i < len; i++) { for (int j = bagWeight; j >= weight[i] ; j--) { dp[j] = Math.max(dp[j],dp[j - weight[i]] + value[i]); } } for (int j = 0; j <= bagWeight; j++){ System.out.print(dp[j] + " "); } } }
0
1,017
4
1,097
6
1,086
4
1,097
6
1,468
9
false
false
false
false
false
true
20918_7
/** * 面试题:写一个固定容量同步容器,拥有put和get方法,以及getCount方法, * 能够支持2个生产者线程以及10个消费者线程的阻塞调用 * * 使用wait和notify/notifyAll来实现 * * @author mashibing */ package yxxy.c_021; import java.util.LinkedList; import java.util.concurrent.TimeUnit; public class MyContainer1<T> { final private LinkedList<T> lists = new LinkedList<>(); final private int MAX = 10; //最多10个元素 private int count = 0; public synchronized void put(T t) { while(lists.size() == MAX) { //想想为什么用while而不是用if? try { this.wait(); //effective java } catch (InterruptedException e) { e.printStackTrace(); } } lists.add(t); ++count; this.notifyAll(); //通知消费者线程进行消费 } public synchronized T get() { T t = null; while(lists.size() == 0) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } t = lists.removeFirst(); count --; this.notifyAll(); //通知生产者进行生产 return t; } public static void main(String[] args) { MyContainer1<String> c = new MyContainer1<>(); //启动消费者线程 for(int i=0; i<10; i++) { new Thread(()->{ for(int j=0; j<5; j++) System.out.println(c.get()); }, "c" + i).start(); } try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } //启动生产者线程 for(int i=0; i<2; i++) { new Thread(()->{ for(int j=0; j<25; j++) c.put(Thread.currentThread().getName() + " " + j); }, "p" + i).start(); } } }
EduMoral/edu
concurrent/src/yxxy/c_021/MyContainer1.java
562
//启动生产者线程
line_comment
zh-cn
/** * 面试题:写一个固定容量同步容器,拥有put和get方法,以及getCount方法, * 能够支持2个生产者线程以及10个消费者线程的阻塞调用 * * 使用wait和notify/notifyAll来实现 * * @author mashibing */ package yxxy.c_021; import java.util.LinkedList; import java.util.concurrent.TimeUnit; public class MyContainer1<T> { final private LinkedList<T> lists = new LinkedList<>(); final private int MAX = 10; //最多10个元素 private int count = 0; public synchronized void put(T t) { while(lists.size() == MAX) { //想想为什么用while而不是用if? try { this.wait(); //effective java } catch (InterruptedException e) { e.printStackTrace(); } } lists.add(t); ++count; this.notifyAll(); //通知消费者线程进行消费 } public synchronized T get() { T t = null; while(lists.size() == 0) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } t = lists.removeFirst(); count --; this.notifyAll(); //通知生产者进行生产 return t; } public static void main(String[] args) { MyContainer1<String> c = new MyContainer1<>(); //启动消费者线程 for(int i=0; i<10; i++) { new Thread(()->{ for(int j=0; j<5; j++) System.out.println(c.get()); }, "c" + i).start(); } try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } //启动 <SUF> for(int i=0; i<2; i++) { new Thread(()->{ for(int j=0; j<25; j++) c.put(Thread.currentThread().getName() + " " + j); }, "p" + i).start(); } } }
0
486
7
558
6
561
6
558
6
733
13
false
false
false
false
false
true