blob_id
stringlengths
40
40
__id__
int64
225
39,780B
directory_id
stringlengths
40
40
path
stringlengths
6
313
content_id
stringlengths
40
40
detected_licenses
list
license_type
stringclasses
2 values
repo_name
stringlengths
6
132
repo_url
stringlengths
25
151
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
70
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
7.28k
689M
star_events_count
int64
0
131k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
23 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
40.4M
gha_stargazers_count
int32
0
112k
gha_forks_count
int32
0
39.4k
gha_open_issues_count
int32
0
11k
gha_language
stringlengths
1
21
gha_archived
bool
2 classes
gha_disabled
bool
1 class
content
stringlengths
7
4.37M
src_encoding
stringlengths
3
16
language
stringclasses
1 value
length_bytes
int64
7
4.37M
extension
stringclasses
24 values
filename
stringlengths
4
174
language_id
stringclasses
1 value
entities
list
contaminating_dataset
stringclasses
0 values
malware_signatures
list
redacted_content
stringlengths
7
4.37M
redacted_length_bytes
int64
7
4.37M
alphanum_fraction
float32
0.25
0.94
alpha_fraction
float32
0.25
0.94
num_lines
int32
1
84k
avg_line_length
float32
0.76
99.9
std_line_length
float32
0
220
max_line_length
int32
5
998
is_vendor
bool
2 classes
is_generated
bool
1 class
max_hex_length
int32
0
319
hex_fraction
float32
0
0.38
max_unicode_length
int32
0
408
unicode_fraction
float32
0
0.36
max_base64_length
int32
0
506
base64_fraction
float32
0
0.5
avg_csv_sep_count
float32
0
4
is_autogen_header
bool
1 class
is_empty_html
bool
1 class
shard
stringclasses
16 values
d3ef302c6c12a97b706938978beefcfd88ec8a2b
1,486,058,721,452
14b4b1970c5fc239a0f74cc2a82da720aac30bf1
/src/simuladoraereo/Bodega.java
0c4bec6dba39755f82aead51fbc7fb21537804d2
[]
no_license
maferhdz1496/proyecto_poo
https://github.com/maferhdz1496/proyecto_poo
7e18f9b8599a80804e92b7bb39a96f250ad4348b
6f56af77b4e5d267add168f3a0a90901deb6a150
refs/heads/master
2021-01-20T07:02:32.470000
2017-05-04T02:19:30
2017-05-04T02:19:30
89,949,214
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package simuladoraereo; /** * * @author maferhernandezdiaz */ public class Bodega { protected int carga; protected boolean listo = false; public Bodega(int carga) { this.carga = carga; } public Bodega() { this.carga = 1000; } public boolean isListo() { if (llenarBodega(carga)){ System.out.println("...Bodega lista..."); listo = true; return true; } else{ System.out.println("Llenar bodega..."); return false; } } public void setListo(boolean listo) { this.listo = listo; } public int getCarga() { return carga; } public void setCarga(int carga) { this.carga = carga; } @Override public String toString() { return "\nBODEGA DE CARGA:" + "\n\tLa carga tiene " + carga + "kg." ; } public boolean llenarBodega(int carga){ if(this.getCarga()<=2000){ System.out.println("Se esta llenando la bodega..."); this.setCarga(2000); return true; } else { System.out.println("La bodega esta muy llena favor de vaciarla..."); return false; } } public boolean vaciarBodega(int carga) { if (this.getCarga()>=2000){ System.out.println("Se esta vaciando la bodega..."); this.setCarga(0); return true; }else{ System.out.println("La bodega esta casi vacia, favor de llenarla..."); return false; } } public boolean verificarBodega(int carga) { if (carga<2000 && carga>0 ){ System.out.println("Hay carga suficiente en la bodega..."); return true; }else{ System.out.println("Hay mucha o nada de carga... cambiando... Ya tiene 2000 kg."); this.setCarga(2000); return false; } } }
UTF-8
Java
2,153
java
Bodega.java
Java
[ { "context": "or.\n */\npackage simuladoraereo;\n\n/**\n *\n * @author maferhernandezdiaz\n */\npublic class Bodega {\n protected int carg", "end": 245, "score": 0.9066750407218933, "start": 228, "tag": "USERNAME", "value": "maferhernandezdia" }, { "context": "muladoraereo;\n\n/**\n *\n * @author maferhernandezdiaz\n */\npublic class Bodega {\n protected int carga", "end": 246, "score": 0.5764548778533936, "start": 245, "tag": "NAME", "value": "z" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package simuladoraereo; /** * * @author maferhernandezdiaz */ public class Bodega { protected int carga; protected boolean listo = false; public Bodega(int carga) { this.carga = carga; } public Bodega() { this.carga = 1000; } public boolean isListo() { if (llenarBodega(carga)){ System.out.println("...Bodega lista..."); listo = true; return true; } else{ System.out.println("Llenar bodega..."); return false; } } public void setListo(boolean listo) { this.listo = listo; } public int getCarga() { return carga; } public void setCarga(int carga) { this.carga = carga; } @Override public String toString() { return "\nBODEGA DE CARGA:" + "\n\tLa carga tiene " + carga + "kg." ; } public boolean llenarBodega(int carga){ if(this.getCarga()<=2000){ System.out.println("Se esta llenando la bodega..."); this.setCarga(2000); return true; } else { System.out.println("La bodega esta muy llena favor de vaciarla..."); return false; } } public boolean vaciarBodega(int carga) { if (this.getCarga()>=2000){ System.out.println("Se esta vaciando la bodega..."); this.setCarga(0); return true; }else{ System.out.println("La bodega esta casi vacia, favor de llenarla..."); return false; } } public boolean verificarBodega(int carga) { if (carga<2000 && carga>0 ){ System.out.println("Hay carga suficiente en la bodega..."); return true; }else{ System.out.println("Hay mucha o nada de carga... cambiando... Ya tiene 2000 kg."); this.setCarga(2000); return false; } } }
2,153
0.54157
0.527636
91
22.604395
21.399845
91
false
false
0
0
0
0
0
0
0.362637
false
false
1
ec7f64cf0222cfbb70659f550863e63798877b2a
30,245,159,717,053
8733aab3e9bd73acdae3ebf0053d8cc52647597f
/src/main/java/cc/chungkwong/mathocr/ui/RecognitionPane.java
ed33a5dcabd5b0006dfb06a3e7337d9159921154
[]
no_license
chungkwong/mathocr-myscript
https://github.com/chungkwong/mathocr-myscript
83f79accc4ad67d0b095990f2f4b015b059e2d4d
71143b0a8af1f8efefce86c393a0c34a4df0a3bc
refs/heads/master
2022-11-18T16:06:30.958000
2021-06-06T12:24:45
2021-06-06T12:24:45
187,008,361
34
7
null
false
2022-11-16T08:56:12
2019-05-16T10:46:03
2022-07-12T08:39:23
2022-11-16T08:56:09
225
30
7
3
Java
false
false
/* * Copyright (C) 2019 Chan Chung Kwong * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package cc.chungkwong.mathocr.ui; import cc.chungkwong.mathocr.common.*; import cc.chungkwong.mathocr.common.format.*; import cc.chungkwong.mathocr.offline.extractor.*; import cc.chungkwong.mathocr.online.*; import java.util.*; import javax.swing.*; /** * * @author Chan Chung Kwong */ public class RecognitionPane extends JSplitPane{ private final ResourceBundle bundle=ResourceBundle.getBundle("cc.chungkwong.mathocr.message"); private final TraceListViewer input=new TraceListViewer(); private final JCheckBox realtime=new JCheckBox(bundle.getString("REALTIME"),false); private final JButton recognize=new JButton(bundle.getString("RECOGNIZE")); private final JComboBox<ExpressionFormat> formats=new JComboBox<>(); private final JTextArea code=new JTextArea(); private EncodedExpression expression; private boolean recognizing=false; public RecognitionPane(){ super(JSplitPane.VERTICAL_SPLIT); Box output=Box.createVerticalBox(); Box toolbar=Box.createHorizontalBox(); recognize.setEnabled(false); recognize.addActionListener((e)->recognize()); toolbar.add(recognize); toolbar.add(realtime); //ServiceLoader.load(Format.class).iterator().forEachRemaining((format)->formats.addItem(format)); formats.addItem(new LatexFormat()); formats.addItem(new MathmlFormat()); formats.addActionListener((e)->format()); toolbar.add(formats); output.add(toolbar); output.add(code); setTopComponent(new JScrollPane(input)); setBottomComponent(new JScrollPane(output)); setOneTouchExpandable(true); } public void setTraceList(TraceList traceList){ input.setTraceList(traceList,Collections.emptyList()); recognize.setEnabled(true); if(realtime.isSelected()){ recognize(); } } public void recognize(){ if(recognizing){ return; } recognizing=true; code.setText("Recognizing..."); new Thread(()->{ try{ expression=Extractor.getDefault().recognize(input.getTraceList(),false); SwingUtilities.invokeLater(()->{ recognizing=false; format(); }); }catch(RuntimeException ex){ SwingUtilities.invokeLater(()->{ recognizing=false; code.setText(ex.getLocalizedMessage()); }); } }).start(); } public void format(){ if(expression!=null){ code.setText(expression.getCodes((ExpressionFormat)formats.getSelectedItem())); } } }
UTF-8
Java
3,046
java
RecognitionPane.java
Java
[ { "context": "/*\n * Copyright (C) 2019 Chan Chung Kwong\n *\n * This program is free software: you can redi", "end": 41, "score": 0.9998761415481567, "start": 25, "tag": "NAME", "value": "Chan Chung Kwong" }, { "context": "va.util.*;\nimport javax.swing.*;\n/**\n *\n * @author Chan Chung Kwong\n */\npublic class RecognitionPane extends JSplitPa", "end": 1000, "score": 0.9998770356178284, "start": 984, "tag": "NAME", "value": "Chan Chung Kwong" } ]
null
[]
/* * Copyright (C) 2019 <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package cc.chungkwong.mathocr.ui; import cc.chungkwong.mathocr.common.*; import cc.chungkwong.mathocr.common.format.*; import cc.chungkwong.mathocr.offline.extractor.*; import cc.chungkwong.mathocr.online.*; import java.util.*; import javax.swing.*; /** * * @author <NAME> */ public class RecognitionPane extends JSplitPane{ private final ResourceBundle bundle=ResourceBundle.getBundle("cc.chungkwong.mathocr.message"); private final TraceListViewer input=new TraceListViewer(); private final JCheckBox realtime=new JCheckBox(bundle.getString("REALTIME"),false); private final JButton recognize=new JButton(bundle.getString("RECOGNIZE")); private final JComboBox<ExpressionFormat> formats=new JComboBox<>(); private final JTextArea code=new JTextArea(); private EncodedExpression expression; private boolean recognizing=false; public RecognitionPane(){ super(JSplitPane.VERTICAL_SPLIT); Box output=Box.createVerticalBox(); Box toolbar=Box.createHorizontalBox(); recognize.setEnabled(false); recognize.addActionListener((e)->recognize()); toolbar.add(recognize); toolbar.add(realtime); //ServiceLoader.load(Format.class).iterator().forEachRemaining((format)->formats.addItem(format)); formats.addItem(new LatexFormat()); formats.addItem(new MathmlFormat()); formats.addActionListener((e)->format()); toolbar.add(formats); output.add(toolbar); output.add(code); setTopComponent(new JScrollPane(input)); setBottomComponent(new JScrollPane(output)); setOneTouchExpandable(true); } public void setTraceList(TraceList traceList){ input.setTraceList(traceList,Collections.emptyList()); recognize.setEnabled(true); if(realtime.isSelected()){ recognize(); } } public void recognize(){ if(recognizing){ return; } recognizing=true; code.setText("Recognizing..."); new Thread(()->{ try{ expression=Extractor.getDefault().recognize(input.getTraceList(),false); SwingUtilities.invokeLater(()->{ recognizing=false; format(); }); }catch(RuntimeException ex){ SwingUtilities.invokeLater(()->{ recognizing=false; code.setText(ex.getLocalizedMessage()); }); } }).start(); } public void format(){ if(expression!=null){ code.setText(expression.getCodes((ExpressionFormat)formats.getSelectedItem())); } } }
3,026
0.741957
0.740315
89
33.22472
24.792057
100
false
false
0
0
0
0
0
0
2.101124
false
false
1
64216b4a9ff38318f05c2be30d4c9e08fa57063a
30,245,159,714,417
ee3f6c7123dead913fe6b6745060b6ea82c6b0b9
/src/leetcode/460.java
fc8426c557a2c7c430dd92b8559a8e02d1d4e661
[]
no_license
izayoi5776/leetcode
https://github.com/izayoi5776/leetcode
c1a36570042aa8522eb00bf3aec11ac877ba04f0
4c16f644cecc261302ef9643c9d3352c30c3f381
refs/heads/master
2023-01-08T06:48:52.172000
2023-01-04T13:38:42
2023-01-04T13:38:42
212,962,112
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/****************************************************************************** 460. LFU缓存 https://leetcode-cn.com/problems/lfu-cache/ *******************************************************************************/ import java.util.Arrays; import java.util.Map; import java.util.HashMap; //import java.util.SortedMap; import java.util.TreeMap; import java.util.Comparator; //import java.util.LinkedHashMap; class Rec implements Comparable{ int key; int value; int cnt; // access counter int tm; // last access time Rec(int key, int value){ this.key = key; this.value = value; } public String toString(){ return "(" + key + "/" + value + "/" + cnt + "/" + tm + ")"; } @Override public int compareTo(Object o){ Rec r = (Rec)o; int ret = (cnt==r.cnt ? tm - r.tm : cnt - r.cnt); //int ret = (cnt==r.cnt ? r.tm - tm : r.cnt - cnt); //System.out.println("compareTo(" + this + "," + r + ")=" + ret); return ret; } } class LFUCache { Map<Integer, Rec> m = null; // key 检索用 TreeMap<Rec, Integer> m2 = null; // 排序用 int capacity = 0; int tm = 0; public LFUCache(int capacity) { this.capacity = capacity; m = new HashMap<Integer, Rec>(); /*m2 = new TreeMap<Rec, Integer>(new Comparator<Rec>(){ public int compare(Rec o1, Rec o2){ int ret = 0; if(o1==null && o2==null){ // ret = 0; }else if(o1==null){ ret = -1; }else if(o2==null){ ret = 1; }else if(o1.cnt > o2.cnt){ ret = 1; }else if(o1.cnt < o2.cnt){ ret = -1; // o1.cnt == o2.cnt }else if(o1.tm > o2.tm){ ret = 1; }else if(o1.tm < o2.tm){ ret = -1; } System.out.println("compare(" + o1 + "," + o2 + ")=" + ret); return ret; } });*/ m2 = new TreeMap<Rec, Integer>(); //System.out.println("LFUCache() called cap=" + capacity + " m=" + m); } public int get(int key) { int ret = -1; if(m.containsKey(key)){ Rec r = m.get(key); m2.remove(r); // TreeMap 的排序索引不能改变,想改就删掉重新添加 ret = r.value; r.cnt++; r.tm = this.tm; m2.put(r, key); } this.tm++; printStatus("LFUCache::get(" + key + ")=" + ret); return ret; } public void put(int key, int value) { if(m.containsKey(key)){ Rec r = m.get(key); m2.remove(r); r.value = value; r.cnt++; r.tm = this.tm; m2.put(r, key); }else{ if(chkCap()){ Rec r = new Rec(key, value); r.tm = this.tm; m.put(key, r); m2.put(r, key); } } this.tm++; printStatus("LFUCache::put(" + key + "," + value + ")"); } boolean chkCap(){ if(m2.size() > 0 && m2.size() > capacity -1){ Rec r = m2.firstKey(); //Rec r = m2.lastKey(); int t = m2.get(r); printStatus("LFUCache::chkCap() REMOVE r=" + r); m.remove(r.key); m2.remove(r); } printStatus("LFUCache::chkCap()"); return m2.size() < capacity; } void printStatus(String s){ if(false){ System.out.println("" + this.tm + " " + s + " m=" + m + " m2=" + m2); } } } /** * Your LFUCache object will be instantiated and called as such: * LFUCache obj = new LFUCache(capacity); * int param_1 = obj.get(key); * obj.put(key,value); */ public class Main { public static void main(String[] args) { t1(); t2(); t3(); t4(); t5(); t6(); t7(); } static void tbase(LFUCache cache, int val, int expect){ System.out.println("ret=" + val + " expect=" + expect + (val==expect?" OK":" NG")); } static void t1(){ LFUCache cache = new LFUCache( 2 /* capacity (缓存容量) */ ); cache.put(1, 1); cache.put(2, 2); tbase(cache, cache.get(1), 1); // 返回 1 cache.put(3, 3); // 去除 key 2 tbase(cache, cache.get(2), -1); // 返回 -1 (未找到key 2) tbase(cache, cache.get(3), 3); // 返回 3 cache.put(4, 4); // 去除 key 1 tbase(cache, cache.get(1), -1); // 返回 -1 (未找到 key 1) tbase(cache, cache.get(3), 3); // 返回 3 tbase(cache, cache.get(4), 4); // 返回 4 } static void tbase2(String[] cmds, int[][] parms, Integer[] expects){ System.out.println("---------------"); LFUCache cache = null; for(int i=0; i<cmds.length; i++){ String c = cmds[i]; if(c.equals("LFUCache")){ cache = new LFUCache(parms[i][0]); }else if(c.equals("put")){ cache.put(parms[i][0], parms[i][1]); }else if(c.equals("get")){ tbase(cache, cache.get(parms[i][0]), expects[i]); } try{ //System.in.read(); }catch(Exception ex){ } } } // 注意,put 不计算为使用,所以get(3)得到-1。 // 所以不能用 LinkedHashMap 了 static void t2(){ tbase2(new String[]{"LFUCache","put","put","get","get","get","put","put","get","get","get","get"}, new int[][]{{3},{2,2},{1,1},{2},{1},{2},{3,3},{4,4},{3},{2},{1},{4}}, new Integer[]{null,null,null,2,1,2,null,null,-1,2,1,4} ); } // put() 并不是在最后,而是按顺序。所以同是没有get过的2和3,较老的3被删掉。 static void t3(){ tbase2(new String[]{"LFUCache","put","put","put","put","get"}, new int[][]{{2},{3,1},{2,1},{2,2},{4,4},{2}}, new Integer[]{null,null,null,null,null,2} ); } // cap == 0 时 static void t4(){ tbase2(new String[]{"LFUCache","put","get"}, new int[][]{{0},{0,0},{0}}, new Integer[]{null,null,-1} ); } static void t5(){ tbase2(new String[]{"LFUCache","put","put","get","put","put","get"}, new int[][]{{2},{2,1},{2,2},{2},{1,1},{4,1},{2}}, new Integer[]{null,null,null,2,null,null,2} ); } static void t6(){ tbase2(new String[]{"LFUCache","put","put","put","put","get","get"}, new int[][]{{2},{2,1},{1,1},{2,3},{4,1},{1},{2}}, new Integer[]{null,null,null,null,null,-1,3} ); } static void t7(){ tbase2(new String[]{"LFUCache","put","put","put","put","put","get","put","get","get","put","get","put","put","put","get","put","get","get","get","get","put","put","get","get","get","put","put","get","put","get","put","get","get","get","put","put","put","get","put","get","get","put","put","get","put","put","put","put","get","put","put","get","put","put","get","put","put","put","put","put","get","put","put","get","put","get","get","get","put","get","get","put","put","put","put","get","put","put","put","put","get","get","get","put","put","put","get","put","put","put","get","put","put","put","get","get","get","put","put","put","put","get","put","put","put","put","put","put","put"}, new int[][]{{10},{10,13},{3,17},{6,11},{10,5},{9,10},{13},{2,19},{2},{3},{5,25},{8},{9,22},{5,5},{1,30},{11},{9,12},{7},{5},{8},{9},{4,30},{9,3},{9},{10},{10},{6,14},{3,1},{3},{10,11},{8},{2,14},{1},{5},{4},{11,4},{12,24},{5,18},{13},{7,23},{8},{12},{3,27},{2,12},{5},{2,9},{13,4},{8,18},{1,7},{6},{9,29},{8,21},{5},{6,30},{1,12},{10},{4,15},{7,22},{11,26},{8,17},{9,29},{5},{3,4},{11,30},{12},{4,29},{3},{9},{6},{3,4},{1},{10},{3,29},{10,28},{1,20},{11,13},{3},{3,12},{3,8},{10,9},{3,26},{8},{7},{5},{13,17},{2,27},{11,15},{12},{9,19},{2,15},{3,16},{1},{12,17},{9,1},{6,19},{4},{5},{5},{8,1},{11,7},{5,2},{9,28},{1},{2,2},{7,4},{4,22},{7,24},{9,26},{13,28},{11,26}}, new Integer[]{null,null,null,null,null,null,-1,null,19,17,null,-1,null,null,null,-1,null,-1,5,-1,12,null,null,3,5,5,null,null,1,null,-1,null,30,5,30,null,null,null,-1,null,-1,24,null,null,18,null,null,null,null,14,null,null,18,null,null,11,null,null,null,null,null,18,null,null,-1,null,4,29,30,null,12,11,null,null,null,null,29,null,null,null,null,17,-1,18,null,null,null,-1,null,null,null,20,null,null,null,29,18,18,null,null,null,null,20,null,null,null,null,null,null,null} ); } }
UTF-8
Java
8,649
java
460.java
Java
[]
null
[]
/****************************************************************************** 460. LFU缓存 https://leetcode-cn.com/problems/lfu-cache/ *******************************************************************************/ import java.util.Arrays; import java.util.Map; import java.util.HashMap; //import java.util.SortedMap; import java.util.TreeMap; import java.util.Comparator; //import java.util.LinkedHashMap; class Rec implements Comparable{ int key; int value; int cnt; // access counter int tm; // last access time Rec(int key, int value){ this.key = key; this.value = value; } public String toString(){ return "(" + key + "/" + value + "/" + cnt + "/" + tm + ")"; } @Override public int compareTo(Object o){ Rec r = (Rec)o; int ret = (cnt==r.cnt ? tm - r.tm : cnt - r.cnt); //int ret = (cnt==r.cnt ? r.tm - tm : r.cnt - cnt); //System.out.println("compareTo(" + this + "," + r + ")=" + ret); return ret; } } class LFUCache { Map<Integer, Rec> m = null; // key 检索用 TreeMap<Rec, Integer> m2 = null; // 排序用 int capacity = 0; int tm = 0; public LFUCache(int capacity) { this.capacity = capacity; m = new HashMap<Integer, Rec>(); /*m2 = new TreeMap<Rec, Integer>(new Comparator<Rec>(){ public int compare(Rec o1, Rec o2){ int ret = 0; if(o1==null && o2==null){ // ret = 0; }else if(o1==null){ ret = -1; }else if(o2==null){ ret = 1; }else if(o1.cnt > o2.cnt){ ret = 1; }else if(o1.cnt < o2.cnt){ ret = -1; // o1.cnt == o2.cnt }else if(o1.tm > o2.tm){ ret = 1; }else if(o1.tm < o2.tm){ ret = -1; } System.out.println("compare(" + o1 + "," + o2 + ")=" + ret); return ret; } });*/ m2 = new TreeMap<Rec, Integer>(); //System.out.println("LFUCache() called cap=" + capacity + " m=" + m); } public int get(int key) { int ret = -1; if(m.containsKey(key)){ Rec r = m.get(key); m2.remove(r); // TreeMap 的排序索引不能改变,想改就删掉重新添加 ret = r.value; r.cnt++; r.tm = this.tm; m2.put(r, key); } this.tm++; printStatus("LFUCache::get(" + key + ")=" + ret); return ret; } public void put(int key, int value) { if(m.containsKey(key)){ Rec r = m.get(key); m2.remove(r); r.value = value; r.cnt++; r.tm = this.tm; m2.put(r, key); }else{ if(chkCap()){ Rec r = new Rec(key, value); r.tm = this.tm; m.put(key, r); m2.put(r, key); } } this.tm++; printStatus("LFUCache::put(" + key + "," + value + ")"); } boolean chkCap(){ if(m2.size() > 0 && m2.size() > capacity -1){ Rec r = m2.firstKey(); //Rec r = m2.lastKey(); int t = m2.get(r); printStatus("LFUCache::chkCap() REMOVE r=" + r); m.remove(r.key); m2.remove(r); } printStatus("LFUCache::chkCap()"); return m2.size() < capacity; } void printStatus(String s){ if(false){ System.out.println("" + this.tm + " " + s + " m=" + m + " m2=" + m2); } } } /** * Your LFUCache object will be instantiated and called as such: * LFUCache obj = new LFUCache(capacity); * int param_1 = obj.get(key); * obj.put(key,value); */ public class Main { public static void main(String[] args) { t1(); t2(); t3(); t4(); t5(); t6(); t7(); } static void tbase(LFUCache cache, int val, int expect){ System.out.println("ret=" + val + " expect=" + expect + (val==expect?" OK":" NG")); } static void t1(){ LFUCache cache = new LFUCache( 2 /* capacity (缓存容量) */ ); cache.put(1, 1); cache.put(2, 2); tbase(cache, cache.get(1), 1); // 返回 1 cache.put(3, 3); // 去除 key 2 tbase(cache, cache.get(2), -1); // 返回 -1 (未找到key 2) tbase(cache, cache.get(3), 3); // 返回 3 cache.put(4, 4); // 去除 key 1 tbase(cache, cache.get(1), -1); // 返回 -1 (未找到 key 1) tbase(cache, cache.get(3), 3); // 返回 3 tbase(cache, cache.get(4), 4); // 返回 4 } static void tbase2(String[] cmds, int[][] parms, Integer[] expects){ System.out.println("---------------"); LFUCache cache = null; for(int i=0; i<cmds.length; i++){ String c = cmds[i]; if(c.equals("LFUCache")){ cache = new LFUCache(parms[i][0]); }else if(c.equals("put")){ cache.put(parms[i][0], parms[i][1]); }else if(c.equals("get")){ tbase(cache, cache.get(parms[i][0]), expects[i]); } try{ //System.in.read(); }catch(Exception ex){ } } } // 注意,put 不计算为使用,所以get(3)得到-1。 // 所以不能用 LinkedHashMap 了 static void t2(){ tbase2(new String[]{"LFUCache","put","put","get","get","get","put","put","get","get","get","get"}, new int[][]{{3},{2,2},{1,1},{2},{1},{2},{3,3},{4,4},{3},{2},{1},{4}}, new Integer[]{null,null,null,2,1,2,null,null,-1,2,1,4} ); } // put() 并不是在最后,而是按顺序。所以同是没有get过的2和3,较老的3被删掉。 static void t3(){ tbase2(new String[]{"LFUCache","put","put","put","put","get"}, new int[][]{{2},{3,1},{2,1},{2,2},{4,4},{2}}, new Integer[]{null,null,null,null,null,2} ); } // cap == 0 时 static void t4(){ tbase2(new String[]{"LFUCache","put","get"}, new int[][]{{0},{0,0},{0}}, new Integer[]{null,null,-1} ); } static void t5(){ tbase2(new String[]{"LFUCache","put","put","get","put","put","get"}, new int[][]{{2},{2,1},{2,2},{2},{1,1},{4,1},{2}}, new Integer[]{null,null,null,2,null,null,2} ); } static void t6(){ tbase2(new String[]{"LFUCache","put","put","put","put","get","get"}, new int[][]{{2},{2,1},{1,1},{2,3},{4,1},{1},{2}}, new Integer[]{null,null,null,null,null,-1,3} ); } static void t7(){ tbase2(new String[]{"LFUCache","put","put","put","put","put","get","put","get","get","put","get","put","put","put","get","put","get","get","get","get","put","put","get","get","get","put","put","get","put","get","put","get","get","get","put","put","put","get","put","get","get","put","put","get","put","put","put","put","get","put","put","get","put","put","get","put","put","put","put","put","get","put","put","get","put","get","get","get","put","get","get","put","put","put","put","get","put","put","put","put","get","get","get","put","put","put","get","put","put","put","get","put","put","put","get","get","get","put","put","put","put","get","put","put","put","put","put","put","put"}, new int[][]{{10},{10,13},{3,17},{6,11},{10,5},{9,10},{13},{2,19},{2},{3},{5,25},{8},{9,22},{5,5},{1,30},{11},{9,12},{7},{5},{8},{9},{4,30},{9,3},{9},{10},{10},{6,14},{3,1},{3},{10,11},{8},{2,14},{1},{5},{4},{11,4},{12,24},{5,18},{13},{7,23},{8},{12},{3,27},{2,12},{5},{2,9},{13,4},{8,18},{1,7},{6},{9,29},{8,21},{5},{6,30},{1,12},{10},{4,15},{7,22},{11,26},{8,17},{9,29},{5},{3,4},{11,30},{12},{4,29},{3},{9},{6},{3,4},{1},{10},{3,29},{10,28},{1,20},{11,13},{3},{3,12},{3,8},{10,9},{3,26},{8},{7},{5},{13,17},{2,27},{11,15},{12},{9,19},{2,15},{3,16},{1},{12,17},{9,1},{6,19},{4},{5},{5},{8,1},{11,7},{5,2},{9,28},{1},{2,2},{7,4},{4,22},{7,24},{9,26},{13,28},{11,26}}, new Integer[]{null,null,null,null,null,null,-1,null,19,17,null,-1,null,null,null,-1,null,-1,5,-1,12,null,null,3,5,5,null,null,1,null,-1,null,30,5,30,null,null,null,-1,null,-1,24,null,null,18,null,null,null,null,14,null,null,18,null,null,11,null,null,null,null,null,18,null,null,-1,null,4,29,30,null,12,11,null,null,null,null,29,null,null,null,null,17,-1,18,null,null,null,-1,null,null,null,20,null,null,null,29,18,18,null,null,null,null,20,null,null,null,null,null,null,null} ); } }
8,649
0.457756
0.398507
223
36.843048
71.861771
691
false
false
0
0
0
0
0
0
3.286995
false
false
1
65d257c79105c0e66a02ad21846ae4f658713e4a
22,016,002,422,151
7e4bb9fcbf0fc598a21b8218f91a8cbe219f3ad4
/src/hotel/Hotel.java
ee2a7c5ebc9278cb6cc228abff3e556b5e82120f
[]
no_license
rafaela-amorim/Rafaela_Matheus_LGit
https://github.com/rafaela-amorim/Rafaela_Matheus_LGit
bbf437f14dcad7e081c51bb847b06d498d4f2945
48b9ec6262c406a430693993721fc462d3713d6f
refs/heads/master
2018-09-28T17:57:48.617000
2018-06-12T11:40:29
2018-06-12T11:40:29
136,485,914
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package hotel; public class Hotel { private Recepcao recepcao; /** * Construtor de Hotel, inicializa recepcao. */ public Hotel() { recepcao = new Recepcao(); } /** * Faz o check-in de um Animal, recebe o nome, tipo, idade em meses, total de * dias para passar no hotel e o valor da estadia. O método repassa a função * para a classe Recepção. * * @param nome * Nome do Animal. * @param tipo * Espécie do Animal. * @param idade * Idade, em meses, do Animal. * @param dias * Quantidade total de dias da estadia. * @param valor * Valor da estadia. */ public void checkIn(String nome, String tipo, int idade, int dias, double valor) { recepcao.checkIn(nome, tipo, idade, dias, valor); } /** * Faz o check-out do Animal. Recebe o nome e o remove da lista de Estadia em * Recepção, o método repassa a função para a classe Recepção. * * @param nome * Nome do Animal para a busca e remoção. */ public void checkOut(String nome) { recepcao.checkOut(nome); } /** * Retorna a quantidade de hóspedes cadastrados no Hotel. * * @return total de hóspedes do hotel. */ public int getNumDeHospedes() { return recepcao.getNumDeHospedes(); } /** * Retorna um double com o valor do lucro do hotel. * * @return double com o lucro total. */ public double getLucroTotal() { return recepcao.getLucroTotal(); } /** * Representação textual do hotel. */ @Override public String toString() { return recepcao.toString(); } }
UTF-8
Java
1,593
java
Hotel.java
Java
[]
null
[]
package hotel; public class Hotel { private Recepcao recepcao; /** * Construtor de Hotel, inicializa recepcao. */ public Hotel() { recepcao = new Recepcao(); } /** * Faz o check-in de um Animal, recebe o nome, tipo, idade em meses, total de * dias para passar no hotel e o valor da estadia. O método repassa a função * para a classe Recepção. * * @param nome * Nome do Animal. * @param tipo * Espécie do Animal. * @param idade * Idade, em meses, do Animal. * @param dias * Quantidade total de dias da estadia. * @param valor * Valor da estadia. */ public void checkIn(String nome, String tipo, int idade, int dias, double valor) { recepcao.checkIn(nome, tipo, idade, dias, valor); } /** * Faz o check-out do Animal. Recebe o nome e o remove da lista de Estadia em * Recepção, o método repassa a função para a classe Recepção. * * @param nome * Nome do Animal para a busca e remoção. */ public void checkOut(String nome) { recepcao.checkOut(nome); } /** * Retorna a quantidade de hóspedes cadastrados no Hotel. * * @return total de hóspedes do hotel. */ public int getNumDeHospedes() { return recepcao.getNumDeHospedes(); } /** * Retorna um double com o valor do lucro do hotel. * * @return double com o lucro total. */ public double getLucroTotal() { return recepcao.getLucroTotal(); } /** * Representação textual do hotel. */ @Override public String toString() { return recepcao.toString(); } }
1,593
0.635324
0.635324
71
21.169014
22.256498
83
false
false
0
0
0
0
0
0
1.267606
false
false
1
23a85e0b957a4a1ec2f00a427cfb36850fdada59
32,418,413,151,659
706dae6cc6526064622d4f5557471427441e5c5e
/src/main/java/com/anbo/juja/patterns/nullObject_15/sample/codenjoy/NullParameter.java
d531d593f50e0529668b50bbde515e03c27266f3
[]
no_license
Anton-Bondar/Design-patterns-JUJA-examples-
https://github.com/Anton-Bondar/Design-patterns-JUJA-examples-
414edabfd8c4148640de7de8d01f809b01c3c17c
9e3d628f7e45c0106514f8f459ea30fffed702d5
refs/heads/master
2021-10-09T04:45:42.372000
2018-12-21T12:09:00
2018-12-21T12:11:14
121,509,668
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.anbo.juja.patterns.nullObject_15.sample.codenjoy; import org.apache.commons.lang.StringUtils; /** * Created by oleksandr.baglai on 10.12.2015. */ public class NullParameter implements Parameter<Object> { @Override public Object getValue() { // что-то новенькое! // но не возвращать жеж null // NPE может быть return new Object(); } @Override public String getName() { // и имя у параметра = "" return StringUtils.EMPTY; } @Override public void update(Object value) { // do nothing } }
UTF-8
Java
649
java
NullParameter.java
Java
[ { "context": "pache.commons.lang.StringUtils;\n\n/**\n * Created by oleksandr.baglai on 10.12.2015.\n */\npublic class Null", "end": 129, "score": 0.6702704429626465, "start": 126, "tag": "NAME", "value": "ole" }, { "context": "e.commons.lang.StringUtils;\n\n/**\n * Created by oleksandr.baglai on 10.12.2015.\n */\npublic class NullPa", "end": 131, "score": 0.5219335556030273, "start": 129, "tag": "USERNAME", "value": "ks" }, { "context": "commons.lang.StringUtils;\n\n/**\n * Created by oleksandr.baglai on 10.12.2015.\n */\npublic class NullParame", "end": 135, "score": 0.5143266916275024, "start": 131, "tag": "NAME", "value": "andr" }, { "context": "ons.lang.StringUtils;\n\n/**\n * Created by oleksandr.baglai on 10.12.2015.\n */\npublic class NullParamet", "end": 135, "score": 0.791462242603302, "start": 135, "tag": "USERNAME", "value": "" }, { "context": "ns.lang.StringUtils;\n\n/**\n * Created by oleksandr.baglai on 10.12.2015.\n */\npublic class NullParameter imp", "end": 142, "score": 0.8042860627174377, "start": 136, "tag": "NAME", "value": "baglai" } ]
null
[]
package com.anbo.juja.patterns.nullObject_15.sample.codenjoy; import org.apache.commons.lang.StringUtils; /** * Created by oleksandr.baglai on 10.12.2015. */ public class NullParameter implements Parameter<Object> { @Override public Object getValue() { // что-то новенькое! // но не возвращать жеж null // NPE может быть return new Object(); } @Override public String getName() { // и имя у параметра = "" return StringUtils.EMPTY; } @Override public void update(Object value) { // do nothing } }
649
0.620168
0.603361
27
21.037037
18.042093
61
false
false
0
0
0
0
0
0
0.148148
false
false
1
fdf066d97cd4f6386e91e29add5b98c9030d487e
6,923,487,288,815
012d7699ce43e65d87ef3bfb286f2639fec3a6b5
/Biblioteca/src/ifsp/dsis4/obra/Exemplar.java
0636c3e00783586e4f77a485c1c6e6e919fbd2b3
[]
no_license
georgearaujo/Projeto_DSI
https://github.com/georgearaujo/Projeto_DSI
a07794fb0dcacaeca403a53e51d933d9575f45a3
197f10b5e2a7a91300fe95ad0d237d1f53be4597
refs/heads/master
2020-04-05T01:29:43.914000
2018-12-07T12:23:33
2018-12-07T12:23:33
156,438,643
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ifsp.dsis4.obra; /** * * @author Georg */ public class Exemplar { private boolean disponivel; private int identificador; private Obra obra; public Exemplar(boolean disponivel, int identificador){ this.disponivel = disponivel; this.identificador = identificador; } public Exemplar(Obra obra){ this.obra = obra; } public void setDisponivel(boolean disponivel) { this.disponivel = disponivel; } public void setIdentificador(int identificador) { this.identificador = identificador; } public boolean getDisponivel(){ return disponivel; } public int getIdentificador(){ return identificador; } }
UTF-8
Java
930
java
Exemplar.java
Java
[ { "context": "r.\n */\npackage ifsp.dsis4.obra;\n\n/**\n *\n * @author Georg\n */\npublic class Exemplar {\n \n private bool", "end": 234, "score": 0.9994110465049744, "start": 229, "tag": "NAME", "value": "Georg" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ifsp.dsis4.obra; /** * * @author Georg */ public class Exemplar { private boolean disponivel; private int identificador; private Obra obra; public Exemplar(boolean disponivel, int identificador){ this.disponivel = disponivel; this.identificador = identificador; } public Exemplar(Obra obra){ this.obra = obra; } public void setDisponivel(boolean disponivel) { this.disponivel = disponivel; } public void setIdentificador(int identificador) { this.identificador = identificador; } public boolean getDisponivel(){ return disponivel; } public int getIdentificador(){ return identificador; } }
930
0.651613
0.650538
42
21.142857
20.13002
79
false
false
0
0
0
0
0
0
0.357143
false
false
1
ba04006a3f28544f9b3dbe68f325e39f34402faa
17,566,416,265,945
d0bd6c5bd866d0625d57bc21c9c7aa8029b37c90
/src/main/java/com/semafoor/semaforce/services/utilities/ResultUtilities.java
3ac3cc7d1adf918bb643a4093d4b71b9740912e6
[]
no_license
H-J-Uijterlinde/WorkoutApp_BackEnd
https://github.com/H-J-Uijterlinde/WorkoutApp_BackEnd
ee4bec3cf416a942d7c6f55c937ceb8d72b69346
0d8105eccbdfafdb0614077f85b53adcec61a327
refs/heads/master
2020-08-26T16:57:05.089000
2019-12-19T14:33:08
2019-12-19T14:33:08
217,080,920
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.semafoor.semaforce.services.utilities; import com.semafoor.semaforce.model.entities.result.Score; import com.semafoor.semaforce.model.entities.result.WeeklyResult; import org.springframework.stereotype.Service; import java.util.Optional; import java.util.OptionalDouble; @Service public class ResultUtilities { public double getAverageRepsPerformed(WeeklyResult weeklyResult) { OptionalDouble averageRepsForWeeklyResult = weeklyResult.getNumbersLifted().values().stream(). mapToDouble(Score -> Score.getRepetitionsPerformed() + (10 - Score.getRpe())).average(); return averageRepsForWeeklyResult.orElseThrow(() -> new RuntimeException("No repetitions have been set for this result")); } public double getAverageWeightLifted(WeeklyResult weeklyResult) { OptionalDouble averageWeightForWeeklyResult = weeklyResult.getNumbersLifted().values().stream(). mapToDouble(Score::getWeightLifted).average(); return averageWeightForWeeklyResult.orElseThrow(() -> new RuntimeException("No weights have been set for this result")); } private Score getBestSetFromResult(WeeklyResult weeklyResult) { Optional<Score> bestScore = weeklyResult.getNumbersLifted().values().stream() .max((a, b) -> (int) ((a.getRpe() + a.getRepetitionsPerformed()) * a.getWeightLifted() - (b.getRpe() + b.getRepetitionsPerformed()) * b.getWeightLifted())); return bestScore.orElseThrow(() -> new RuntimeException("No Scores found")); } public double getWeightForDesiredRepNumber(double numReps, WeeklyResult weeklyResult) { Score bestScore = this.getBestSetFromResult(weeklyResult); double weightLifted = bestScore.getWeightLifted(); double repetitionsPerformedRpeCorrected = bestScore.getRepetitionsPerformed() + (10 - bestScore.getRpe()); double estimatedOneRepMax = weightLifted * (1 + repetitionsPerformedRpeCorrected / 30); return estimatedOneRepMax / (1 + (numReps / 30)); } public double getWeightForDesiredRepNumberForMultipleSets(double numReps, WeeklyResult weeklyResult) { double estimatedOneRepMax = this.getAverageWeightLifted(weeklyResult) * (1 + this.getAverageRepsPerformed(weeklyResult) / 30); return estimatedOneRepMax / (1 + (numReps / 30)); } }
UTF-8
Java
2,407
java
ResultUtilities.java
Java
[]
null
[]
package com.semafoor.semaforce.services.utilities; import com.semafoor.semaforce.model.entities.result.Score; import com.semafoor.semaforce.model.entities.result.WeeklyResult; import org.springframework.stereotype.Service; import java.util.Optional; import java.util.OptionalDouble; @Service public class ResultUtilities { public double getAverageRepsPerformed(WeeklyResult weeklyResult) { OptionalDouble averageRepsForWeeklyResult = weeklyResult.getNumbersLifted().values().stream(). mapToDouble(Score -> Score.getRepetitionsPerformed() + (10 - Score.getRpe())).average(); return averageRepsForWeeklyResult.orElseThrow(() -> new RuntimeException("No repetitions have been set for this result")); } public double getAverageWeightLifted(WeeklyResult weeklyResult) { OptionalDouble averageWeightForWeeklyResult = weeklyResult.getNumbersLifted().values().stream(). mapToDouble(Score::getWeightLifted).average(); return averageWeightForWeeklyResult.orElseThrow(() -> new RuntimeException("No weights have been set for this result")); } private Score getBestSetFromResult(WeeklyResult weeklyResult) { Optional<Score> bestScore = weeklyResult.getNumbersLifted().values().stream() .max((a, b) -> (int) ((a.getRpe() + a.getRepetitionsPerformed()) * a.getWeightLifted() - (b.getRpe() + b.getRepetitionsPerformed()) * b.getWeightLifted())); return bestScore.orElseThrow(() -> new RuntimeException("No Scores found")); } public double getWeightForDesiredRepNumber(double numReps, WeeklyResult weeklyResult) { Score bestScore = this.getBestSetFromResult(weeklyResult); double weightLifted = bestScore.getWeightLifted(); double repetitionsPerformedRpeCorrected = bestScore.getRepetitionsPerformed() + (10 - bestScore.getRpe()); double estimatedOneRepMax = weightLifted * (1 + repetitionsPerformedRpeCorrected / 30); return estimatedOneRepMax / (1 + (numReps / 30)); } public double getWeightForDesiredRepNumberForMultipleSets(double numReps, WeeklyResult weeklyResult) { double estimatedOneRepMax = this.getAverageWeightLifted(weeklyResult) * (1 + this.getAverageRepsPerformed(weeklyResult) / 30); return estimatedOneRepMax / (1 + (numReps / 30)); } }
2,407
0.714998
0.708351
58
40.5
41.631493
130
false
false
0
0
0
0
0
0
0.37931
false
false
1
e51d8d80c1c0be7d91d933b3c975ddbac7512ad3
27,908,697,500,085
77b381c3be3f2f81ef10c52223b925470678a57f
/ChaiyiLora/app/src/main/java/com/example/zxpay/chaiyilora/MainActivity.java
2b771070c58f83f2e708a1a0a541d8f71303eeb6
[]
no_license
ZXPAY/IoT_MyAirMonitor
https://github.com/ZXPAY/IoT_MyAirMonitor
aa641da692c90ea25f0c995a647bd39894e3a303
926e2538b3fbdcccd977bfb6b921ed2669f572ca
refs/heads/master
2020-03-21T13:39:00.287000
2018-08-21T17:55:38
2018-08-21T17:55:38
138,617,870
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.zxpay.chaiyilora; import android.content.Intent; import android.content.pm.ActivityInfo; import android.graphics.Color; import android.graphics.Typeface; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.Html; import android.util.Log; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.ScrollView; import android.widget.TextView; import android.widget.Toast; import com.github.anastr.speedviewlib.AwesomeSpeedometer; import com.github.anastr.speedviewlib.DeluxeSpeedView; import com.github.anastr.speedviewlib.Gauge; import com.github.anastr.speedviewlib.ImageLinearGauge; import com.github.anastr.speedviewlib.LinearGauge; import com.github.anastr.speedviewlib.ProgressiveGauge; import com.github.anastr.speedviewlib.RaySpeedometer; import com.github.anastr.speedviewlib.SpeedView; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.firestore.CollectionReference; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.Query; import com.google.firebase.firestore.QuerySnapshot; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Map; /* 12000008: Temperature Humidity 12000009: Temperature Humidity 12000006: Temperature Humidity 12000007: Temperature Humidity Atmosphere CO CO2 DNS LPG PM */ public class MainActivity extends AppCompatActivity implements Button.OnClickListener{ int ButtonID[] = {R.id.BT_DATA_UPDATE, R.id.BT_INDOOR_LABEL,R.id.BT_OUTDOOR_LABEL ,R.id.BT_LOOK_DATA_DETAILS, R.id.BT_ADVANCE_QUERY}; int OutDoor_TXVID[] = {R.id.TXV_CO, R.id.TXV_CO2, R.id.TXV_LPG}; TextView outdoor_txv; TextView txv_show_time; final boolean DEBUG = true; private final int CHOOSE_INDOOR = 1; private final int CHOOSE_OUTDOOR = 0; private String UsingOutdoor = "/OutDoor/0000000012000007/"; private String UsingIndoor = "/InDoor/0000000012000008/"; private String time_name = "time"; private String rssi_name = "rssi"; private String temp_name = "Temperature"; private String humidity_name = "Humidity"; private String CO_name = "CO"; private String CO2_name = "CO2"; private String pressure_name = "Atmosphere"; private String location_name = "DNS"; private String LPG_name = "LPG"; private String dust_name = "PM"; private int show_data_type = 0; // 0 ;indoor , 1:outdoor // Newest data will be saved. Map<String, String> Indoor_Data = new HashMap<String, String>(); Map<String, String> Outdoor_Data = new HashMap<String, String>(); Map<String, String> Temp_Datai = new HashMap<String, String>(); // i => indoor Map<String, String> Humi_Datai = new HashMap<String, String>(); Map<String, String> Temp_Datao = new HashMap<String, String>(); // o => outdoor Map<String, String> Humi_Datao = new HashMap<String, String>(); Map<String, String> LPG_Data = new HashMap<String, String>(); Map<String, String> CO_Data = new HashMap<String, String>(); Map<String, String> CO2_Data = new HashMap<String, String>(); Map<String, String> Pressure_Data = new HashMap<String, String>(); Map<String, String> Pressure_Datao = new HashMap<String, String>(); Map<String, String> Loc_Data = new HashMap<String, String>(); Map<String, String> Dust_Data = new HashMap<String, String>(); Map<String, String> Dust_Datao = new HashMap<String, String>(); //TextView show_indoor, show_outdoor; Button btn_new_window; ImageLinearGauge gauge_humidity; ImageLinearGauge gauge_temperature; ProgressiveGauge gauge_co2; AwesomeSpeedometer gauge_co; SpeedView gauge_lpg; DeluxeSpeedView gauge_pm; RaySpeedometer gauge_pressure; Toast toast; ScrollView first_scrollview, second_scrollview; private long timei = System.currentTimeMillis(); int polling_time = 500; // Query 資料間隔 500 millis // keys for indoor and outdoor (the array define in strings.xml) String[] indoor_array; String[] outdoor_array; float[] details_array = {0f,0f,0f,0f,0f,0f,0f,0f,0f}; // Access a Cloud Firestore instance from your Activity FirebaseFirestore db = FirebaseFirestore.getInstance(); MyQuery myQuery = new MyQuery(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Orientation will not change when the cell phone tilt. setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); // Cell phone will keep screen on. getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); Log.e("Now", Get_Now()); // now for(int id:ButtonID){ Button bt = findViewById(id); bt.setOnClickListener(this); } indoor_array = getResources().getStringArray(R.array.Indoor_Data); outdoor_array = getResources().getStringArray(R.array.Outdoor_Data); txv_show_time = (TextView) findViewById(R.id.TXV_SHOW_TIME); myQuery.VERBOSE = false; show_data_type = CHOOSE_INDOOR; data_update(); gauge_humidity = (ImageLinearGauge ) findViewById(R.id.GAUGE_HUMIDITY); gauge_humidity.setOrientation(LinearGauge.Orientation.VERTICAL); gauge_humidity.setSpeedTextPosition(Gauge.Position.TOP_CENTER); gauge_humidity.setUnitTextSize(50); gauge_humidity.setSpeedTextSize(50); gauge_humidity.setUnit("%"); gauge_humidity.setMaxSpeed(100); gauge_humidity.setMinSpeed(0); gauge_temperature = (ImageLinearGauge) findViewById(R.id.GAUGE_TEMP); gauge_temperature.setOrientation(LinearGauge.Orientation.HORIZONTAL); gauge_temperature.setSpeedTextPosition(Gauge.Position.TOP_CENTER); gauge_temperature.setUnit("\u00b0"+"C"); gauge_temperature.setMaxSpeed(50); gauge_temperature.setMinSpeed(0); gauge_temperature.setUnitTextSize(50); gauge_temperature.setSpeedTextSize(50); gauge_co2 = (ProgressiveGauge) findViewById(R.id.GAUGE_CO2); gauge_co2.setMaxSpeed(2000); gauge_co2.setMinSpeed(0); gauge_co2.setUnit("ppm"); gauge_co2.setUnitTextSize(50); gauge_co = (AwesomeSpeedometer) findViewById(R.id.GAUGE_PRESSURE); gauge_co.setMaxSpeed(2000); gauge_co.setMinSpeed(0); gauge_co.setUnit("ppm"); gauge_co.setUnitTextSize(50); gauge_lpg = (SpeedView) findViewById(R.id.GAUGE_LPG); gauge_lpg.setSpeedTextPosition(Gauge.Position.TOP_CENTER); gauge_lpg.setMaxSpeed(1000); gauge_lpg.setMinSpeed(0); gauge_lpg.setUnit("ppm"); gauge_lpg.setUnitTextSize(50); gauge_pm = (DeluxeSpeedView) findViewById(R.id.GAUGE_PM); gauge_pm.setMaxSpeed(200); gauge_pm.setMinSpeed(0); gauge_pm.setUnit("\u00b5"+"g/m"+"\u00b3"); gauge_pm.setUnitTextSize(50); gauge_pressure = (RaySpeedometer) findViewById(R.id.GAUGE_PRESSURE); gauge_pressure.setMaxSpeed(150000); gauge_pressure.setMinSpeed(10000); gauge_pressure.setUnit("pa"); gauge_pressure.setUnitTextSize(50); first_scrollview = (ScrollView) findViewById(R.id.FIRST_SCROLLVIEW); second_scrollview = (ScrollView) findViewById(R.id.SECOND_SCROLLVIEW); Indoor_Mode(); } private void Outdoor_Mode(){ gauge_co.setVisibility(gauge_co.INVISIBLE); gauge_co2.setVisibility(gauge_co2.INVISIBLE); gauge_lpg.setVisibility(gauge_lpg.INVISIBLE); gauge_pm.setVisibility(gauge_pm.VISIBLE); gauge_pressure.setVisibility(gauge_pressure.VISIBLE); for(int id:OutDoor_TXVID){ outdoor_txv = (TextView) findViewById(id); outdoor_txv.setVisibility(outdoor_txv.INVISIBLE); } Button Bt_outdoor = findViewById(R.id.BT_OUTDOOR_LABEL); Bt_outdoor.setBackgroundColor(getResources().getColor(R.color.colorG, null)); Bt_outdoor.setTextColor(Color.RED); Bt_outdoor.setTypeface(Typeface.DEFAULT_BOLD); String htmlString="<u>"+Bt_outdoor.getText().toString()+"</u>"; Bt_outdoor.setText(Html.fromHtml(htmlString)); Button Bt_indoor = findViewById(R.id.BT_INDOOR_LABEL); Bt_indoor.setBackgroundColor(getResources().getColor(R.color.colorW, null)); Bt_indoor.setTextColor(Color.BLACK); Bt_indoor.setTypeface(Typeface.DEFAULT); Bt_indoor.setText(Bt_indoor.getText().toString()); } private void Indoor_Mode(){ gauge_co.setVisibility(gauge_co.VISIBLE); gauge_co2.setVisibility(gauge_co2.VISIBLE); gauge_lpg.setVisibility(gauge_lpg.VISIBLE); gauge_pm.setVisibility(gauge_pm.VISIBLE); gauge_pressure.setVisibility(gauge_pressure.VISIBLE); second_scrollview.setVisibility(second_scrollview.VISIBLE); for(int id:OutDoor_TXVID){ outdoor_txv = (TextView) findViewById(id); outdoor_txv.setVisibility(outdoor_txv.VISIBLE); } Button Bt_indoor = findViewById(R.id.BT_INDOOR_LABEL); Bt_indoor.setBackgroundColor(getResources().getColor(R.color.colorG, null)); Bt_indoor.setTextColor(Color.RED); Bt_indoor.setTypeface(Typeface.DEFAULT_BOLD); String htmlString="<u>"+Bt_indoor.getText().toString()+"</u>"; Bt_indoor.setText(Html.fromHtml(htmlString)); Button Bt_outdoor = findViewById(R.id.BT_OUTDOOR_LABEL); Bt_outdoor.setBackgroundColor(getResources().getColor(R.color.colorW, null)); Bt_outdoor.setTextColor(Color.BLACK); Bt_outdoor.setTypeface(Typeface.DEFAULT); Bt_outdoor.setText(Bt_outdoor.getText().toString()); } private String Get_Now(){ DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date today = Calendar.getInstance().getTime(); return dateFormat.format(today).toString(); } private class MyQuery{ /* Example below: CollectionReference ref = db.collection("/OutDoor/0000000012000007/CO2"); MyQuery myquery = new MyQuery(); myquery.mode = 1; myquery.Query(ref, "time", "<=", "2018-06-17 15:00:00", 10, "DESCENDING"); */ ArrayList<String> Data_Array = new ArrayList<>(); int mode = 0; int query_numbers = 0; boolean VERBOSE = true; /* This method can query data from firebase. key:parameter you want to query. operator:>,<,>=,== and so on, you can use these operator to find the data you want to query. object:key operator than what, for example temperature is key, > is operator, and value is object. num:how manny data you want to get direction:Ascending or Descending you can choose. */ private void Query(CollectionReference ref, String key, String operator, String object, final int num, String direct){ Data_Array = new ArrayList<>(); query_numbers = num; // Default Query Query myQuery = ref.whereGreaterThan(key, object).limit(num).orderBy(key, Query.Direction.ASCENDING);; if(operator.equals(">")){ if(direct.equals("ASCENDING")) myQuery = ref.whereGreaterThan(key, object).limit(num).orderBy(key, Query.Direction.ASCENDING); else if(direct.equals("DESCENDING")) myQuery = ref.whereGreaterThan(key, object).limit(num).orderBy(key, Query.Direction.DESCENDING); } else if(operator.equals(">=")){ if(direct.equals("ASCENDING")) myQuery = ref.whereGreaterThanOrEqualTo(key, object).limit(num).orderBy(key, Query.Direction.ASCENDING); else if(direct.equals("DESCENDING")) myQuery = ref.whereGreaterThanOrEqualTo(key, object).limit(num).orderBy(key, Query.Direction.DESCENDING); } else if(operator.equals("<")){ if(direct.equals("ASCENDING")) myQuery = ref.whereLessThan(key, object).limit(num).orderBy(key, Query.Direction.ASCENDING); else if(direct.equals("DESCENDING")) myQuery = ref.whereLessThan(key, object).limit(num).orderBy(key, Query.Direction.DESCENDING); } else if(operator.equals("<=")){ if(direct.equals("ASCENDING")) myQuery = ref.whereLessThanOrEqualTo(key, object).limit(num).orderBy(key, Query.Direction.ASCENDING); else if(direct.equals("DESCENDING")) myQuery = ref.whereLessThanOrEqualTo(key, object).limit(num).orderBy(key, Query.Direction.DESCENDING); } else if(operator.equals("==")){ if(direct.equals("ASCENDING")) myQuery = ref.whereEqualTo(key, object).limit(num).orderBy(key, Query.Direction.ASCENDING); else if(direct.equals("DESCENDING")) myQuery = ref.whereEqualTo(key, object).limit(num).orderBy(key, Query.Direction.DESCENDING); } myQuery.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if(task.isSuccessful()){ //Log.e("Query", "Success"); QuerySnapshot QSnap = task.getResult(); if(!QSnap.isEmpty()){ for(int CNT=0;CNT<num;CNT++){ try { Log.e("Query Data", String.valueOf(task.getResult().getDocuments().get(CNT).getData())); String Data = String.valueOf(task.getResult().getDocuments().get(CNT).getData()); Data_Array.add(Data); } catch (Exception e){ Log.e("Query Data", "Error"); e.printStackTrace(); } } Run_Command(); Data_Array = new ArrayList<>(); } } else{ Log.e("Query", "Failure"); } } }); } /* This method will run when query is finished. You can set mode to run the code. */ private void Run_Command(){ switch (mode){ case 0: Log.e("Run", "Start~~~"); break; case 1: ArrayList<String> temp = new ArrayList<>(); ArrayList<String> humi = new ArrayList<>(); ArrayList<String> co = new ArrayList<>(); ArrayList<String> co2 = new ArrayList<>(); ArrayList<String> lpg = new ArrayList<>(); ArrayList<String> pressure = new ArrayList<>(); ArrayList<String> loc = new ArrayList<>(); ArrayList<String> dust = new ArrayList<>(); ArrayList<String> t = new ArrayList<>(); ArrayList<String> rssi = new ArrayList<>(); for(String data:Data_Array){ //Log.e("Data", data); String data_split[] = data.substring(1,data.length()-1).split(","); for(String d:data_split){ String each_data[] = d.split("="); for(int i=0;i<each_data.length;i++){ try { //Log.e("data", each_data[i]); if(each_data[i].replaceAll("\\s", "").equals("TS")){ if(VERBOSE) Log.e("Temperature:", each_data[i+1]); temp.add(each_data[i+1]); } else if(each_data[i].replaceAll("\\s", "").equals("HS")){ if(VERBOSE) Log.e("Humidity:", each_data[i+1]); humi.add(each_data[i+1]); } else if(each_data[i].replaceAll("\\s", "").equals("CS")){ if(VERBOSE) Log.e("CO:", each_data[i+1]); co.add(each_data[i+1]); } else if(each_data[i].replaceAll("\\s", "").equals("IS")){ if(VERBOSE) Log.e("CO2:", each_data[i+1]); co2.add(each_data[i+1]); } else if(each_data[i].replaceAll("\\s", "").equals("AS")){ if(VERBOSE) Log.e("AS:", each_data[i+1]); pressure.add(each_data[i+1]); } else if(each_data[i].replaceAll("\\s", "").equals("MS")){ if(VERBOSE) Log.e("Dust:", each_data[i+1]); dust.add(each_data[i+1]); } else if(each_data[i].replaceAll("\\s", "").equals("LS")){ if(VERBOSE) Log.e("LPG:", each_data[i+1]); lpg.add(each_data[i+1]); } else if(each_data[i].replaceAll("\\s", "").equals("time")){ if(VERBOSE) Log.e("time", each_data[i+1]); t.add(each_data[i+1]); } else if(each_data[i].replaceAll("\\s", "").equals("DNLIST")){ if(VERBOSE) Log.e("DNS", each_data[i+1]); loc.add(each_data[i+1]); } else if(each_data[i].replaceAll("\\s", "").equals("rssi")){ if(VERBOSE) Log.e("rssi", each_data[i+1]); rssi.add(each_data[i+1]); } } catch (Exception e){ e.printStackTrace(); } } } } if(!temp.isEmpty()){ if(show_data_type == CHOOSE_INDOOR){ for(int i=0;i<temp.size();i++){ Temp_Datai.put(t.get(i), temp.get(i)); //Log.e("Tempi", Temp_Datai.toString()); gauge_temperature.speedTo(Float.parseFloat(temp.get(i))); details_array[0] = Float.parseFloat(temp.get(i)); } } else if(show_data_type == CHOOSE_OUTDOOR){ for(int i=0;i<temp.size();i++){ Temp_Datao.put(t.get(i), temp.get(i)); //Log.e("Tempo", Temp_Datao.toString()); gauge_temperature.speedTo(Float.parseFloat(temp.get(i))); details_array[7] = Float.parseFloat(temp.get(i)); } } } if(!humi.isEmpty()){ if(show_data_type == CHOOSE_INDOOR){ for(int i=0;i<humi.size();i++){ Humi_Datai.put(t.get(i), humi.get(i)); // Log.e("ef", humi.get(i)); gauge_humidity.speedTo(Float.parseFloat(humi.get(i))); details_array[1] = Float.parseFloat(humi.get(i)); } } else if(show_data_type == CHOOSE_OUTDOOR){ for(int i=0;i<humi.size();i++){ Humi_Datao.put(t.get(i), humi.get(i)); gauge_humidity.speedTo(Float.parseFloat(humi.get(i))); details_array[8] = Float.parseFloat(humi.get(i)); } } } if(!co.isEmpty()){ if(show_data_type == CHOOSE_OUTDOOR); else if(show_data_type == CHOOSE_INDOOR){ for(int i=0;i<co.size();i++){ CO_Data.put(t.get(i), co.get(i)); gauge_co.speedTo(Float.parseFloat(co.get(i))); details_array[2] = Float.parseFloat(co.get(i)); } } } if(!co2.isEmpty()){ if(show_data_type == CHOOSE_OUTDOOR); else if(show_data_type == CHOOSE_INDOOR){ for(int i=0;i<co2.size();i++){ CO2_Data.put(t.get(i), co2.get(i)); gauge_co2.speedTo(Float.parseFloat(co2.get(i))); details_array[3] = Float.parseFloat(co2.get(i)); } } } if(!lpg.isEmpty()){ if(show_data_type == CHOOSE_OUTDOOR); else if(show_data_type == CHOOSE_INDOOR){ for(int i=0;i<lpg.size();i++){ LPG_Data.put(t.get(i), lpg.get(i)); gauge_lpg.speedTo(Float.parseFloat(lpg.get(i))); details_array[4] = Float.parseFloat(lpg.get(i)); } } } if(!dust.isEmpty()){ if(show_data_type == CHOOSE_OUTDOOR){ for(int i=0;i<dust.size();i++){ Dust_Datao.put(t.get(i), dust.get(i)); gauge_pm.speedTo(Float.parseFloat(dust.get(i))); } } else if(show_data_type == CHOOSE_INDOOR){ for(int i=0;i<dust.size();i++){ Dust_Data.put(t.get(i), dust.get(i)); gauge_pm.speedTo(Float.parseFloat(dust.get(i))); details_array[5] = Float.parseFloat(dust.get(i)); } } } if(!pressure.isEmpty()){ if(show_data_type == CHOOSE_OUTDOOR){ for(int i=0;i<pressure.size();i++){ Pressure_Datao.put(t.get(i), pressure.get(i)); gauge_pressure.speedTo(Float.parseFloat(pressure.get(i))); } } else if(show_data_type == CHOOSE_INDOOR){ for(int i=0;i<pressure.size();i++){ Pressure_Data.put(t.get(i), pressure.get(i)); gauge_pressure.speedTo(Float.parseFloat(pressure.get(i))); details_array[6] = Float.parseFloat(pressure.get(i)); } } } if(!loc.isEmpty()){ if(show_data_type == CHOOSE_OUTDOOR); else if(show_data_type == CHOOSE_INDOOR){ for(int i=0;i<loc.size();i++){ Loc_Data.put(t.get(i), loc.get(i)); } } } break; case 2: break; } } } private void data_update(){ if(show_data_type == CHOOSE_INDOOR){ myQuery.mode = 1; CollectionReference ref = db.collection(UsingIndoor+temp_name); myQuery.Query(ref, time_name, "<=", Get_Now(), 1, "DESCENDING"); ref = db.collection(UsingIndoor+humidity_name); myQuery.Query(ref, time_name, "<=", Get_Now(), 1, "DESCENDING"); ref = db.collection(UsingIndoor+CO_name); myQuery.Query(ref, time_name, "<=", Get_Now(), 1, "DESCENDING"); ref = db.collection(UsingIndoor+CO2_name); myQuery.Query(ref, time_name, "<=", Get_Now(), 1, "DESCENDING"); ref = db.collection(UsingIndoor+LPG_name); myQuery.Query(ref, time_name, "<=", Get_Now(), 1, "DESCENDING"); ref = db.collection(UsingIndoor+dust_name); myQuery.Query(ref, time_name, "<=", Get_Now(), 1, "DESCENDING"); ref = db.collection(UsingIndoor+pressure_name); myQuery.Query(ref, time_name, "<=", Get_Now(), 1, "DESCENDING"); // ref = db.collection(UsingIndoor+location_name); // myQuery.Query(ref, time_name, "<=", Get_Now(), 1, "DESCENDING"); txv_show_time.setText("最後更新時間 : " + Get_Now()); } else if(show_data_type == CHOOSE_OUTDOOR){ myQuery.mode = 1; CollectionReference ref = db.collection(UsingOutdoor+temp_name); myQuery.Query(ref, time_name, "<=", Get_Now(), 1, "DESCENDING"); ref = db.collection(UsingOutdoor+humidity_name); myQuery.Query(ref, time_name, "<=", Get_Now(), 1, "DESCENDING"); // ref = db.collection(UsingOutdoor+CO_name); // myQuery.Query(ref, time_name, "<=", Get_Now(), 1, "DESCENDING"); // ref = db.collection(UsingOutdoor+CO2_name); // myQuery.Query(ref, time_name, "<=", Get_Now(), 1, "DESCENDING"); // ref = db.collection(UsingOutdoor+LPG_name); // myQuery.Query(ref, time_name, "<=", Get_Now(), 1, "DESCENDING"); ref = db.collection(UsingOutdoor+dust_name); myQuery.Query(ref, time_name, "<=", Get_Now(), 1, "DESCENDING"); ref = db.collection(UsingOutdoor+pressure_name); myQuery.Query(ref, time_name, "<=", Get_Now(), 1, "DESCENDING"); // ref = db.collection(UsingOutdoor+location_name); // myQuery.Query(ref, time_name, "<=", Get_Now(), 1, "DESCENDING"); txv_show_time.setText("最後更新時間 : " + Get_Now()); } else{ Log.e("show_data_type", "Not found Query show_data_type."); } } /* mode 0 : Showing recent indoor data or outdoor data. */ private String PrepareShowData(Map data){ String Reture_MSG = ""; if(!data.isEmpty()){ try{ // Log.e("Pre", data.toString()); // Log.e("Pre Length", String.valueOf(data.toString().length())); Reture_MSG = data.toString().replace("}"," ").substring(1,Temp_Datai.toString().length()-1); Reture_MSG = Reture_MSG.replace("=", "\uD83D\uDC49"); //Log.e("Return MSG", Reture_MSG); } catch (Exception e){ Log.e("Error", "Prepare data error"); e.printStackTrace(); } } return Reture_MSG; } // private void show_data(int mode){ // switch (mode){ // case 0: // String msg = ""; // String pre_msg; // if(show_data_type == CHOOSE_INDOOR){ // msg+="溫度 Temperature\n"; // pre_msg = PrepareShowData(Temp_Datai); // msg += pre_msg+" \u00b0"+"C"+"\n"; // msg+="濕度 Humidity\n"; // pre_msg = PrepareShowData(Humi_Datai); // msg+=pre_msg+" %"; // } // else if(show_data_type == CHOOSE_OUTDOOR){ // msg+="溫度 Temperature\n"; // pre_msg = PrepareShowData(Temp_Datao); // msg += pre_msg+" \u00b0"+"C"+"\n"; // msg+="濕度 Humidity\n"; // pre_msg = PrepareShowData(Humi_Datao); // msg+=pre_msg+" %\n"; // msg+="一氧化碳 Carbon Monoxide\n"; // pre_msg = PrepareShowData(CO_Data); // msg+=pre_msg+" ppm\n"; // msg+="二氧化碳 Carbon Dioxide\n"; // pre_msg = PrepareShowData(CO2_Data); // msg+=pre_msg+" ppm\n"; // msg+="瓦斯 LPG\n"; // pre_msg = PrepareShowData(LPG_Data); // msg+=pre_msg+" ppm\n"; // msg+="空氣微粒 PM\n"; // pre_msg = PrepareShowData(Dust_Data); // msg+=pre_msg+"\u00b5"+"g/m"+"\u00b3"+"\n"; // msg+="大氣壓力 Pressure\n"; // pre_msg = PrepareShowData(Pressure_Data); // msg+=pre_msg+" pa"; //// msg+="經緯度 Location\n"; //// pre_msg = PrepareShowData(Loc_Data); //// msg+=pre_msg+""; // } // //Log.e("MSG",msg); //// show_data.setText(msg); // break; // case 1: // // break; // // default: // // break; // // } // // } @Override public void onClick(View v) { switch (v.getId()){ case R.id.BT_DATA_UPDATE: if((System.currentTimeMillis() - timei) > polling_time){ Log.e("Button", "Data Update ..."); data_update(); timei = System.currentTimeMillis(); } else { if(toast != null){ toast.cancel(); } toast = Toast.makeText(getApplicationContext(), "Please Query data later...", Toast.LENGTH_SHORT); toast.show(); } break; case R.id.BT_INDOOR_LABEL: if((System.currentTimeMillis() - timei) > polling_time){ try { if(DEBUG) Log.e("Button", "BT_Indoor"); show_data_type = CHOOSE_INDOOR; Indoor_Mode(); data_update(); } catch (Exception e){ e.printStackTrace(); } timei = System.currentTimeMillis(); } else { if(toast != null){ toast.cancel(); } toast = Toast.makeText(getApplicationContext(), "Please Query data later...", Toast.LENGTH_SHORT); toast.show(); } break; case R.id.BT_OUTDOOR_LABEL: if((System.currentTimeMillis() - timei) > polling_time){ try { if(DEBUG) Log.e("Button", "BT_Outdoor"); show_data_type = CHOOSE_OUTDOOR; Outdoor_Mode(); data_update(); } catch (Exception e){ e.printStackTrace(); } timei = System.currentTimeMillis(); } else { if(toast != null){ toast.cancel(); } toast = Toast.makeText(getApplicationContext(), "Please Query data later...", Toast.LENGTH_SHORT); toast.show(); } break; case R.id.BT_LOOK_DATA_DETAILS: if(DEBUG) Log.e("Button", "BT_Detail"); Intent intent_details = new Intent(); intent_details.setClass(MainActivity.this, MainActivityDetails.class); Bundle bundle_details = new Bundle(); bundle_details.putFloatArray("details",details_array); intent_details.putExtras(bundle_details); startActivity(intent_details); break; case R.id.BT_ADVANCE_QUERY: if(DEBUG) Log.e("Button", "BT Advance Query"); if(show_data_type == CHOOSE_INDOOR){ Intent intent_indoor = new Intent(); intent_indoor.setClass(MainActivity.this, MainAdvanceIndoorQuery.class); startActivity(intent_indoor); } else if(show_data_type == CHOOSE_OUTDOOR){ Intent intent_outdoor = new Intent(); intent_outdoor.setClass(MainActivity.this, MainAdvanceOutdoorQuery.class); startActivity(intent_outdoor); } break; default: Log.e("Button", "No button Click Found !!!"); break; } } // public void Query_Test(View view){ // Log.e("Button", "Click"); // CollectionReference ref = db.collection("/OutDoor/0000000012000007/CO2"); // MyQuery a = new MyQuery(); // a.mode = 1; // a.Query(ref, "time", "<=", "2018-06-17 15:00:00", 10, "DESCENDING"); // Log.e("Run", "OK"); // } }
UTF-8
Java
34,928
java
MainActivity.java
Java
[]
null
[]
package com.example.zxpay.chaiyilora; import android.content.Intent; import android.content.pm.ActivityInfo; import android.graphics.Color; import android.graphics.Typeface; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.Html; import android.util.Log; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.ScrollView; import android.widget.TextView; import android.widget.Toast; import com.github.anastr.speedviewlib.AwesomeSpeedometer; import com.github.anastr.speedviewlib.DeluxeSpeedView; import com.github.anastr.speedviewlib.Gauge; import com.github.anastr.speedviewlib.ImageLinearGauge; import com.github.anastr.speedviewlib.LinearGauge; import com.github.anastr.speedviewlib.ProgressiveGauge; import com.github.anastr.speedviewlib.RaySpeedometer; import com.github.anastr.speedviewlib.SpeedView; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.firestore.CollectionReference; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.Query; import com.google.firebase.firestore.QuerySnapshot; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Map; /* 12000008: Temperature Humidity 12000009: Temperature Humidity 12000006: Temperature Humidity 12000007: Temperature Humidity Atmosphere CO CO2 DNS LPG PM */ public class MainActivity extends AppCompatActivity implements Button.OnClickListener{ int ButtonID[] = {R.id.BT_DATA_UPDATE, R.id.BT_INDOOR_LABEL,R.id.BT_OUTDOOR_LABEL ,R.id.BT_LOOK_DATA_DETAILS, R.id.BT_ADVANCE_QUERY}; int OutDoor_TXVID[] = {R.id.TXV_CO, R.id.TXV_CO2, R.id.TXV_LPG}; TextView outdoor_txv; TextView txv_show_time; final boolean DEBUG = true; private final int CHOOSE_INDOOR = 1; private final int CHOOSE_OUTDOOR = 0; private String UsingOutdoor = "/OutDoor/0000000012000007/"; private String UsingIndoor = "/InDoor/0000000012000008/"; private String time_name = "time"; private String rssi_name = "rssi"; private String temp_name = "Temperature"; private String humidity_name = "Humidity"; private String CO_name = "CO"; private String CO2_name = "CO2"; private String pressure_name = "Atmosphere"; private String location_name = "DNS"; private String LPG_name = "LPG"; private String dust_name = "PM"; private int show_data_type = 0; // 0 ;indoor , 1:outdoor // Newest data will be saved. Map<String, String> Indoor_Data = new HashMap<String, String>(); Map<String, String> Outdoor_Data = new HashMap<String, String>(); Map<String, String> Temp_Datai = new HashMap<String, String>(); // i => indoor Map<String, String> Humi_Datai = new HashMap<String, String>(); Map<String, String> Temp_Datao = new HashMap<String, String>(); // o => outdoor Map<String, String> Humi_Datao = new HashMap<String, String>(); Map<String, String> LPG_Data = new HashMap<String, String>(); Map<String, String> CO_Data = new HashMap<String, String>(); Map<String, String> CO2_Data = new HashMap<String, String>(); Map<String, String> Pressure_Data = new HashMap<String, String>(); Map<String, String> Pressure_Datao = new HashMap<String, String>(); Map<String, String> Loc_Data = new HashMap<String, String>(); Map<String, String> Dust_Data = new HashMap<String, String>(); Map<String, String> Dust_Datao = new HashMap<String, String>(); //TextView show_indoor, show_outdoor; Button btn_new_window; ImageLinearGauge gauge_humidity; ImageLinearGauge gauge_temperature; ProgressiveGauge gauge_co2; AwesomeSpeedometer gauge_co; SpeedView gauge_lpg; DeluxeSpeedView gauge_pm; RaySpeedometer gauge_pressure; Toast toast; ScrollView first_scrollview, second_scrollview; private long timei = System.currentTimeMillis(); int polling_time = 500; // Query 資料間隔 500 millis // keys for indoor and outdoor (the array define in strings.xml) String[] indoor_array; String[] outdoor_array; float[] details_array = {0f,0f,0f,0f,0f,0f,0f,0f,0f}; // Access a Cloud Firestore instance from your Activity FirebaseFirestore db = FirebaseFirestore.getInstance(); MyQuery myQuery = new MyQuery(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Orientation will not change when the cell phone tilt. setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); // Cell phone will keep screen on. getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); Log.e("Now", Get_Now()); // now for(int id:ButtonID){ Button bt = findViewById(id); bt.setOnClickListener(this); } indoor_array = getResources().getStringArray(R.array.Indoor_Data); outdoor_array = getResources().getStringArray(R.array.Outdoor_Data); txv_show_time = (TextView) findViewById(R.id.TXV_SHOW_TIME); myQuery.VERBOSE = false; show_data_type = CHOOSE_INDOOR; data_update(); gauge_humidity = (ImageLinearGauge ) findViewById(R.id.GAUGE_HUMIDITY); gauge_humidity.setOrientation(LinearGauge.Orientation.VERTICAL); gauge_humidity.setSpeedTextPosition(Gauge.Position.TOP_CENTER); gauge_humidity.setUnitTextSize(50); gauge_humidity.setSpeedTextSize(50); gauge_humidity.setUnit("%"); gauge_humidity.setMaxSpeed(100); gauge_humidity.setMinSpeed(0); gauge_temperature = (ImageLinearGauge) findViewById(R.id.GAUGE_TEMP); gauge_temperature.setOrientation(LinearGauge.Orientation.HORIZONTAL); gauge_temperature.setSpeedTextPosition(Gauge.Position.TOP_CENTER); gauge_temperature.setUnit("\u00b0"+"C"); gauge_temperature.setMaxSpeed(50); gauge_temperature.setMinSpeed(0); gauge_temperature.setUnitTextSize(50); gauge_temperature.setSpeedTextSize(50); gauge_co2 = (ProgressiveGauge) findViewById(R.id.GAUGE_CO2); gauge_co2.setMaxSpeed(2000); gauge_co2.setMinSpeed(0); gauge_co2.setUnit("ppm"); gauge_co2.setUnitTextSize(50); gauge_co = (AwesomeSpeedometer) findViewById(R.id.GAUGE_PRESSURE); gauge_co.setMaxSpeed(2000); gauge_co.setMinSpeed(0); gauge_co.setUnit("ppm"); gauge_co.setUnitTextSize(50); gauge_lpg = (SpeedView) findViewById(R.id.GAUGE_LPG); gauge_lpg.setSpeedTextPosition(Gauge.Position.TOP_CENTER); gauge_lpg.setMaxSpeed(1000); gauge_lpg.setMinSpeed(0); gauge_lpg.setUnit("ppm"); gauge_lpg.setUnitTextSize(50); gauge_pm = (DeluxeSpeedView) findViewById(R.id.GAUGE_PM); gauge_pm.setMaxSpeed(200); gauge_pm.setMinSpeed(0); gauge_pm.setUnit("\u00b5"+"g/m"+"\u00b3"); gauge_pm.setUnitTextSize(50); gauge_pressure = (RaySpeedometer) findViewById(R.id.GAUGE_PRESSURE); gauge_pressure.setMaxSpeed(150000); gauge_pressure.setMinSpeed(10000); gauge_pressure.setUnit("pa"); gauge_pressure.setUnitTextSize(50); first_scrollview = (ScrollView) findViewById(R.id.FIRST_SCROLLVIEW); second_scrollview = (ScrollView) findViewById(R.id.SECOND_SCROLLVIEW); Indoor_Mode(); } private void Outdoor_Mode(){ gauge_co.setVisibility(gauge_co.INVISIBLE); gauge_co2.setVisibility(gauge_co2.INVISIBLE); gauge_lpg.setVisibility(gauge_lpg.INVISIBLE); gauge_pm.setVisibility(gauge_pm.VISIBLE); gauge_pressure.setVisibility(gauge_pressure.VISIBLE); for(int id:OutDoor_TXVID){ outdoor_txv = (TextView) findViewById(id); outdoor_txv.setVisibility(outdoor_txv.INVISIBLE); } Button Bt_outdoor = findViewById(R.id.BT_OUTDOOR_LABEL); Bt_outdoor.setBackgroundColor(getResources().getColor(R.color.colorG, null)); Bt_outdoor.setTextColor(Color.RED); Bt_outdoor.setTypeface(Typeface.DEFAULT_BOLD); String htmlString="<u>"+Bt_outdoor.getText().toString()+"</u>"; Bt_outdoor.setText(Html.fromHtml(htmlString)); Button Bt_indoor = findViewById(R.id.BT_INDOOR_LABEL); Bt_indoor.setBackgroundColor(getResources().getColor(R.color.colorW, null)); Bt_indoor.setTextColor(Color.BLACK); Bt_indoor.setTypeface(Typeface.DEFAULT); Bt_indoor.setText(Bt_indoor.getText().toString()); } private void Indoor_Mode(){ gauge_co.setVisibility(gauge_co.VISIBLE); gauge_co2.setVisibility(gauge_co2.VISIBLE); gauge_lpg.setVisibility(gauge_lpg.VISIBLE); gauge_pm.setVisibility(gauge_pm.VISIBLE); gauge_pressure.setVisibility(gauge_pressure.VISIBLE); second_scrollview.setVisibility(second_scrollview.VISIBLE); for(int id:OutDoor_TXVID){ outdoor_txv = (TextView) findViewById(id); outdoor_txv.setVisibility(outdoor_txv.VISIBLE); } Button Bt_indoor = findViewById(R.id.BT_INDOOR_LABEL); Bt_indoor.setBackgroundColor(getResources().getColor(R.color.colorG, null)); Bt_indoor.setTextColor(Color.RED); Bt_indoor.setTypeface(Typeface.DEFAULT_BOLD); String htmlString="<u>"+Bt_indoor.getText().toString()+"</u>"; Bt_indoor.setText(Html.fromHtml(htmlString)); Button Bt_outdoor = findViewById(R.id.BT_OUTDOOR_LABEL); Bt_outdoor.setBackgroundColor(getResources().getColor(R.color.colorW, null)); Bt_outdoor.setTextColor(Color.BLACK); Bt_outdoor.setTypeface(Typeface.DEFAULT); Bt_outdoor.setText(Bt_outdoor.getText().toString()); } private String Get_Now(){ DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date today = Calendar.getInstance().getTime(); return dateFormat.format(today).toString(); } private class MyQuery{ /* Example below: CollectionReference ref = db.collection("/OutDoor/0000000012000007/CO2"); MyQuery myquery = new MyQuery(); myquery.mode = 1; myquery.Query(ref, "time", "<=", "2018-06-17 15:00:00", 10, "DESCENDING"); */ ArrayList<String> Data_Array = new ArrayList<>(); int mode = 0; int query_numbers = 0; boolean VERBOSE = true; /* This method can query data from firebase. key:parameter you want to query. operator:>,<,>=,== and so on, you can use these operator to find the data you want to query. object:key operator than what, for example temperature is key, > is operator, and value is object. num:how manny data you want to get direction:Ascending or Descending you can choose. */ private void Query(CollectionReference ref, String key, String operator, String object, final int num, String direct){ Data_Array = new ArrayList<>(); query_numbers = num; // Default Query Query myQuery = ref.whereGreaterThan(key, object).limit(num).orderBy(key, Query.Direction.ASCENDING);; if(operator.equals(">")){ if(direct.equals("ASCENDING")) myQuery = ref.whereGreaterThan(key, object).limit(num).orderBy(key, Query.Direction.ASCENDING); else if(direct.equals("DESCENDING")) myQuery = ref.whereGreaterThan(key, object).limit(num).orderBy(key, Query.Direction.DESCENDING); } else if(operator.equals(">=")){ if(direct.equals("ASCENDING")) myQuery = ref.whereGreaterThanOrEqualTo(key, object).limit(num).orderBy(key, Query.Direction.ASCENDING); else if(direct.equals("DESCENDING")) myQuery = ref.whereGreaterThanOrEqualTo(key, object).limit(num).orderBy(key, Query.Direction.DESCENDING); } else if(operator.equals("<")){ if(direct.equals("ASCENDING")) myQuery = ref.whereLessThan(key, object).limit(num).orderBy(key, Query.Direction.ASCENDING); else if(direct.equals("DESCENDING")) myQuery = ref.whereLessThan(key, object).limit(num).orderBy(key, Query.Direction.DESCENDING); } else if(operator.equals("<=")){ if(direct.equals("ASCENDING")) myQuery = ref.whereLessThanOrEqualTo(key, object).limit(num).orderBy(key, Query.Direction.ASCENDING); else if(direct.equals("DESCENDING")) myQuery = ref.whereLessThanOrEqualTo(key, object).limit(num).orderBy(key, Query.Direction.DESCENDING); } else if(operator.equals("==")){ if(direct.equals("ASCENDING")) myQuery = ref.whereEqualTo(key, object).limit(num).orderBy(key, Query.Direction.ASCENDING); else if(direct.equals("DESCENDING")) myQuery = ref.whereEqualTo(key, object).limit(num).orderBy(key, Query.Direction.DESCENDING); } myQuery.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if(task.isSuccessful()){ //Log.e("Query", "Success"); QuerySnapshot QSnap = task.getResult(); if(!QSnap.isEmpty()){ for(int CNT=0;CNT<num;CNT++){ try { Log.e("Query Data", String.valueOf(task.getResult().getDocuments().get(CNT).getData())); String Data = String.valueOf(task.getResult().getDocuments().get(CNT).getData()); Data_Array.add(Data); } catch (Exception e){ Log.e("Query Data", "Error"); e.printStackTrace(); } } Run_Command(); Data_Array = new ArrayList<>(); } } else{ Log.e("Query", "Failure"); } } }); } /* This method will run when query is finished. You can set mode to run the code. */ private void Run_Command(){ switch (mode){ case 0: Log.e("Run", "Start~~~"); break; case 1: ArrayList<String> temp = new ArrayList<>(); ArrayList<String> humi = new ArrayList<>(); ArrayList<String> co = new ArrayList<>(); ArrayList<String> co2 = new ArrayList<>(); ArrayList<String> lpg = new ArrayList<>(); ArrayList<String> pressure = new ArrayList<>(); ArrayList<String> loc = new ArrayList<>(); ArrayList<String> dust = new ArrayList<>(); ArrayList<String> t = new ArrayList<>(); ArrayList<String> rssi = new ArrayList<>(); for(String data:Data_Array){ //Log.e("Data", data); String data_split[] = data.substring(1,data.length()-1).split(","); for(String d:data_split){ String each_data[] = d.split("="); for(int i=0;i<each_data.length;i++){ try { //Log.e("data", each_data[i]); if(each_data[i].replaceAll("\\s", "").equals("TS")){ if(VERBOSE) Log.e("Temperature:", each_data[i+1]); temp.add(each_data[i+1]); } else if(each_data[i].replaceAll("\\s", "").equals("HS")){ if(VERBOSE) Log.e("Humidity:", each_data[i+1]); humi.add(each_data[i+1]); } else if(each_data[i].replaceAll("\\s", "").equals("CS")){ if(VERBOSE) Log.e("CO:", each_data[i+1]); co.add(each_data[i+1]); } else if(each_data[i].replaceAll("\\s", "").equals("IS")){ if(VERBOSE) Log.e("CO2:", each_data[i+1]); co2.add(each_data[i+1]); } else if(each_data[i].replaceAll("\\s", "").equals("AS")){ if(VERBOSE) Log.e("AS:", each_data[i+1]); pressure.add(each_data[i+1]); } else if(each_data[i].replaceAll("\\s", "").equals("MS")){ if(VERBOSE) Log.e("Dust:", each_data[i+1]); dust.add(each_data[i+1]); } else if(each_data[i].replaceAll("\\s", "").equals("LS")){ if(VERBOSE) Log.e("LPG:", each_data[i+1]); lpg.add(each_data[i+1]); } else if(each_data[i].replaceAll("\\s", "").equals("time")){ if(VERBOSE) Log.e("time", each_data[i+1]); t.add(each_data[i+1]); } else if(each_data[i].replaceAll("\\s", "").equals("DNLIST")){ if(VERBOSE) Log.e("DNS", each_data[i+1]); loc.add(each_data[i+1]); } else if(each_data[i].replaceAll("\\s", "").equals("rssi")){ if(VERBOSE) Log.e("rssi", each_data[i+1]); rssi.add(each_data[i+1]); } } catch (Exception e){ e.printStackTrace(); } } } } if(!temp.isEmpty()){ if(show_data_type == CHOOSE_INDOOR){ for(int i=0;i<temp.size();i++){ Temp_Datai.put(t.get(i), temp.get(i)); //Log.e("Tempi", Temp_Datai.toString()); gauge_temperature.speedTo(Float.parseFloat(temp.get(i))); details_array[0] = Float.parseFloat(temp.get(i)); } } else if(show_data_type == CHOOSE_OUTDOOR){ for(int i=0;i<temp.size();i++){ Temp_Datao.put(t.get(i), temp.get(i)); //Log.e("Tempo", Temp_Datao.toString()); gauge_temperature.speedTo(Float.parseFloat(temp.get(i))); details_array[7] = Float.parseFloat(temp.get(i)); } } } if(!humi.isEmpty()){ if(show_data_type == CHOOSE_INDOOR){ for(int i=0;i<humi.size();i++){ Humi_Datai.put(t.get(i), humi.get(i)); // Log.e("ef", humi.get(i)); gauge_humidity.speedTo(Float.parseFloat(humi.get(i))); details_array[1] = Float.parseFloat(humi.get(i)); } } else if(show_data_type == CHOOSE_OUTDOOR){ for(int i=0;i<humi.size();i++){ Humi_Datao.put(t.get(i), humi.get(i)); gauge_humidity.speedTo(Float.parseFloat(humi.get(i))); details_array[8] = Float.parseFloat(humi.get(i)); } } } if(!co.isEmpty()){ if(show_data_type == CHOOSE_OUTDOOR); else if(show_data_type == CHOOSE_INDOOR){ for(int i=0;i<co.size();i++){ CO_Data.put(t.get(i), co.get(i)); gauge_co.speedTo(Float.parseFloat(co.get(i))); details_array[2] = Float.parseFloat(co.get(i)); } } } if(!co2.isEmpty()){ if(show_data_type == CHOOSE_OUTDOOR); else if(show_data_type == CHOOSE_INDOOR){ for(int i=0;i<co2.size();i++){ CO2_Data.put(t.get(i), co2.get(i)); gauge_co2.speedTo(Float.parseFloat(co2.get(i))); details_array[3] = Float.parseFloat(co2.get(i)); } } } if(!lpg.isEmpty()){ if(show_data_type == CHOOSE_OUTDOOR); else if(show_data_type == CHOOSE_INDOOR){ for(int i=0;i<lpg.size();i++){ LPG_Data.put(t.get(i), lpg.get(i)); gauge_lpg.speedTo(Float.parseFloat(lpg.get(i))); details_array[4] = Float.parseFloat(lpg.get(i)); } } } if(!dust.isEmpty()){ if(show_data_type == CHOOSE_OUTDOOR){ for(int i=0;i<dust.size();i++){ Dust_Datao.put(t.get(i), dust.get(i)); gauge_pm.speedTo(Float.parseFloat(dust.get(i))); } } else if(show_data_type == CHOOSE_INDOOR){ for(int i=0;i<dust.size();i++){ Dust_Data.put(t.get(i), dust.get(i)); gauge_pm.speedTo(Float.parseFloat(dust.get(i))); details_array[5] = Float.parseFloat(dust.get(i)); } } } if(!pressure.isEmpty()){ if(show_data_type == CHOOSE_OUTDOOR){ for(int i=0;i<pressure.size();i++){ Pressure_Datao.put(t.get(i), pressure.get(i)); gauge_pressure.speedTo(Float.parseFloat(pressure.get(i))); } } else if(show_data_type == CHOOSE_INDOOR){ for(int i=0;i<pressure.size();i++){ Pressure_Data.put(t.get(i), pressure.get(i)); gauge_pressure.speedTo(Float.parseFloat(pressure.get(i))); details_array[6] = Float.parseFloat(pressure.get(i)); } } } if(!loc.isEmpty()){ if(show_data_type == CHOOSE_OUTDOOR); else if(show_data_type == CHOOSE_INDOOR){ for(int i=0;i<loc.size();i++){ Loc_Data.put(t.get(i), loc.get(i)); } } } break; case 2: break; } } } private void data_update(){ if(show_data_type == CHOOSE_INDOOR){ myQuery.mode = 1; CollectionReference ref = db.collection(UsingIndoor+temp_name); myQuery.Query(ref, time_name, "<=", Get_Now(), 1, "DESCENDING"); ref = db.collection(UsingIndoor+humidity_name); myQuery.Query(ref, time_name, "<=", Get_Now(), 1, "DESCENDING"); ref = db.collection(UsingIndoor+CO_name); myQuery.Query(ref, time_name, "<=", Get_Now(), 1, "DESCENDING"); ref = db.collection(UsingIndoor+CO2_name); myQuery.Query(ref, time_name, "<=", Get_Now(), 1, "DESCENDING"); ref = db.collection(UsingIndoor+LPG_name); myQuery.Query(ref, time_name, "<=", Get_Now(), 1, "DESCENDING"); ref = db.collection(UsingIndoor+dust_name); myQuery.Query(ref, time_name, "<=", Get_Now(), 1, "DESCENDING"); ref = db.collection(UsingIndoor+pressure_name); myQuery.Query(ref, time_name, "<=", Get_Now(), 1, "DESCENDING"); // ref = db.collection(UsingIndoor+location_name); // myQuery.Query(ref, time_name, "<=", Get_Now(), 1, "DESCENDING"); txv_show_time.setText("最後更新時間 : " + Get_Now()); } else if(show_data_type == CHOOSE_OUTDOOR){ myQuery.mode = 1; CollectionReference ref = db.collection(UsingOutdoor+temp_name); myQuery.Query(ref, time_name, "<=", Get_Now(), 1, "DESCENDING"); ref = db.collection(UsingOutdoor+humidity_name); myQuery.Query(ref, time_name, "<=", Get_Now(), 1, "DESCENDING"); // ref = db.collection(UsingOutdoor+CO_name); // myQuery.Query(ref, time_name, "<=", Get_Now(), 1, "DESCENDING"); // ref = db.collection(UsingOutdoor+CO2_name); // myQuery.Query(ref, time_name, "<=", Get_Now(), 1, "DESCENDING"); // ref = db.collection(UsingOutdoor+LPG_name); // myQuery.Query(ref, time_name, "<=", Get_Now(), 1, "DESCENDING"); ref = db.collection(UsingOutdoor+dust_name); myQuery.Query(ref, time_name, "<=", Get_Now(), 1, "DESCENDING"); ref = db.collection(UsingOutdoor+pressure_name); myQuery.Query(ref, time_name, "<=", Get_Now(), 1, "DESCENDING"); // ref = db.collection(UsingOutdoor+location_name); // myQuery.Query(ref, time_name, "<=", Get_Now(), 1, "DESCENDING"); txv_show_time.setText("最後更新時間 : " + Get_Now()); } else{ Log.e("show_data_type", "Not found Query show_data_type."); } } /* mode 0 : Showing recent indoor data or outdoor data. */ private String PrepareShowData(Map data){ String Reture_MSG = ""; if(!data.isEmpty()){ try{ // Log.e("Pre", data.toString()); // Log.e("Pre Length", String.valueOf(data.toString().length())); Reture_MSG = data.toString().replace("}"," ").substring(1,Temp_Datai.toString().length()-1); Reture_MSG = Reture_MSG.replace("=", "\uD83D\uDC49"); //Log.e("Return MSG", Reture_MSG); } catch (Exception e){ Log.e("Error", "Prepare data error"); e.printStackTrace(); } } return Reture_MSG; } // private void show_data(int mode){ // switch (mode){ // case 0: // String msg = ""; // String pre_msg; // if(show_data_type == CHOOSE_INDOOR){ // msg+="溫度 Temperature\n"; // pre_msg = PrepareShowData(Temp_Datai); // msg += pre_msg+" \u00b0"+"C"+"\n"; // msg+="濕度 Humidity\n"; // pre_msg = PrepareShowData(Humi_Datai); // msg+=pre_msg+" %"; // } // else if(show_data_type == CHOOSE_OUTDOOR){ // msg+="溫度 Temperature\n"; // pre_msg = PrepareShowData(Temp_Datao); // msg += pre_msg+" \u00b0"+"C"+"\n"; // msg+="濕度 Humidity\n"; // pre_msg = PrepareShowData(Humi_Datao); // msg+=pre_msg+" %\n"; // msg+="一氧化碳 Carbon Monoxide\n"; // pre_msg = PrepareShowData(CO_Data); // msg+=pre_msg+" ppm\n"; // msg+="二氧化碳 Carbon Dioxide\n"; // pre_msg = PrepareShowData(CO2_Data); // msg+=pre_msg+" ppm\n"; // msg+="瓦斯 LPG\n"; // pre_msg = PrepareShowData(LPG_Data); // msg+=pre_msg+" ppm\n"; // msg+="空氣微粒 PM\n"; // pre_msg = PrepareShowData(Dust_Data); // msg+=pre_msg+"\u00b5"+"g/m"+"\u00b3"+"\n"; // msg+="大氣壓力 Pressure\n"; // pre_msg = PrepareShowData(Pressure_Data); // msg+=pre_msg+" pa"; //// msg+="經緯度 Location\n"; //// pre_msg = PrepareShowData(Loc_Data); //// msg+=pre_msg+""; // } // //Log.e("MSG",msg); //// show_data.setText(msg); // break; // case 1: // // break; // // default: // // break; // // } // // } @Override public void onClick(View v) { switch (v.getId()){ case R.id.BT_DATA_UPDATE: if((System.currentTimeMillis() - timei) > polling_time){ Log.e("Button", "Data Update ..."); data_update(); timei = System.currentTimeMillis(); } else { if(toast != null){ toast.cancel(); } toast = Toast.makeText(getApplicationContext(), "Please Query data later...", Toast.LENGTH_SHORT); toast.show(); } break; case R.id.BT_INDOOR_LABEL: if((System.currentTimeMillis() - timei) > polling_time){ try { if(DEBUG) Log.e("Button", "BT_Indoor"); show_data_type = CHOOSE_INDOOR; Indoor_Mode(); data_update(); } catch (Exception e){ e.printStackTrace(); } timei = System.currentTimeMillis(); } else { if(toast != null){ toast.cancel(); } toast = Toast.makeText(getApplicationContext(), "Please Query data later...", Toast.LENGTH_SHORT); toast.show(); } break; case R.id.BT_OUTDOOR_LABEL: if((System.currentTimeMillis() - timei) > polling_time){ try { if(DEBUG) Log.e("Button", "BT_Outdoor"); show_data_type = CHOOSE_OUTDOOR; Outdoor_Mode(); data_update(); } catch (Exception e){ e.printStackTrace(); } timei = System.currentTimeMillis(); } else { if(toast != null){ toast.cancel(); } toast = Toast.makeText(getApplicationContext(), "Please Query data later...", Toast.LENGTH_SHORT); toast.show(); } break; case R.id.BT_LOOK_DATA_DETAILS: if(DEBUG) Log.e("Button", "BT_Detail"); Intent intent_details = new Intent(); intent_details.setClass(MainActivity.this, MainActivityDetails.class); Bundle bundle_details = new Bundle(); bundle_details.putFloatArray("details",details_array); intent_details.putExtras(bundle_details); startActivity(intent_details); break; case R.id.BT_ADVANCE_QUERY: if(DEBUG) Log.e("Button", "BT Advance Query"); if(show_data_type == CHOOSE_INDOOR){ Intent intent_indoor = new Intent(); intent_indoor.setClass(MainActivity.this, MainAdvanceIndoorQuery.class); startActivity(intent_indoor); } else if(show_data_type == CHOOSE_OUTDOOR){ Intent intent_outdoor = new Intent(); intent_outdoor.setClass(MainActivity.this, MainAdvanceOutdoorQuery.class); startActivity(intent_outdoor); } break; default: Log.e("Button", "No button Click Found !!!"); break; } } // public void Query_Test(View view){ // Log.e("Button", "Click"); // CollectionReference ref = db.collection("/OutDoor/0000000012000007/CO2"); // MyQuery a = new MyQuery(); // a.mode = 1; // a.Query(ref, "time", "<=", "2018-06-17 15:00:00", 10, "DESCENDING"); // Log.e("Run", "OK"); // } }
34,928
0.493828
0.484211
764
44.594242
26.821501
126
false
false
26
0.000746
0
0
0
0
0.924084
false
false
1
3f00d6a220e78f4e6efb17bd3a29a9f6d6a348b9
14,826,227,107,416
4acc9de593c16c4f401381523ee2bf409b32c9a5
/src/main/java/cn/edu/hist/mapper/UserareaMapper.java
21fa987b97b2c44b52e28ba65c01a07fd314db58
[]
no_license
duanjinpeng/MpSystem
https://github.com/duanjinpeng/MpSystem
bb806e662a5840c98c62a1e9a5c4d0b132d07c3c
4af56a4773bb3fcb487d6a2e63fdaf8e1d2a74b2
refs/heads/master
2020-09-03T04:54:49.186000
2019-01-08T01:12:10
2019-01-08T01:12:10
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.edu.hist.mapper; import cn.edu.hist.model.Userarea; import cn.edu.hist.model.UserareaExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface UserareaMapper { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table userarea * * @mbggenerated */ int countByExample(UserareaExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table userarea * * @mbggenerated */ int deleteByExample(UserareaExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table userarea * * @mbggenerated */ int deleteByPrimaryKey(@Param("userid") String userid, @Param("areaid") String areaid); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table userarea * * @mbggenerated */ int insert(Userarea record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table userarea * * @mbggenerated */ int insertSelective(Userarea record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table userarea * * @mbggenerated */ List<Userarea> selectByExample(UserareaExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table userarea * * @mbggenerated */ Userarea selectByPrimaryKey(@Param("userid") String userid, @Param("areaid") String areaid); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table userarea * * @mbggenerated */ int updateByExampleSelective(@Param("record") Userarea record, @Param("example") UserareaExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table userarea * * @mbggenerated */ int updateByExample(@Param("record") Userarea record, @Param("example") UserareaExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table userarea * * @mbggenerated */ int updateByPrimaryKeySelective(Userarea record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table userarea * * @mbggenerated */ int updateByPrimaryKey(Userarea record); }
UTF-8
Java
2,726
java
UserareaMapper.java
Java
[]
null
[]
package cn.edu.hist.mapper; import cn.edu.hist.model.Userarea; import cn.edu.hist.model.UserareaExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface UserareaMapper { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table userarea * * @mbggenerated */ int countByExample(UserareaExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table userarea * * @mbggenerated */ int deleteByExample(UserareaExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table userarea * * @mbggenerated */ int deleteByPrimaryKey(@Param("userid") String userid, @Param("areaid") String areaid); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table userarea * * @mbggenerated */ int insert(Userarea record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table userarea * * @mbggenerated */ int insertSelective(Userarea record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table userarea * * @mbggenerated */ List<Userarea> selectByExample(UserareaExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table userarea * * @mbggenerated */ Userarea selectByPrimaryKey(@Param("userid") String userid, @Param("areaid") String areaid); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table userarea * * @mbggenerated */ int updateByExampleSelective(@Param("record") Userarea record, @Param("example") UserareaExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table userarea * * @mbggenerated */ int updateByExample(@Param("record") Userarea record, @Param("example") UserareaExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table userarea * * @mbggenerated */ int updateByPrimaryKeySelective(Userarea record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table userarea * * @mbggenerated */ int updateByPrimaryKey(Userarea record); }
2,726
0.668379
0.668379
96
27.40625
26.871058
110
false
false
0
0
0
0
0
0
0.208333
false
false
1
f9fcb8a55d46a1a4abc47c37cd559c6af84c2c6a
25,005,299,607,173
4634aa00e1a28dc074043596b6df1599d6275964
/src/main/java/com/crosstown/employee_control/domain/Employee.java
d181f3efb4e6181eec5df6bae0b5a4ff80860b0f
[]
no_license
crosstown/employee_control_-app
https://github.com/crosstown/employee_control_-app
74435c16620b0c86dc17eda4625562de967f933a
b612067db3b7c920437b4087bfad90328dee164d
refs/heads/master
2022-01-05T15:51:23.462000
2017-11-22T07:37:19
2017-11-22T07:37:19
111,488,020
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.crosstown.employee_control.domain; import lombok.Getter; import lombok.Setter; import javax.persistence.*; /** * @author F.S.(Crosstown) * @date 11/21/2017 * @time 12:17 AM */ @Getter @Setter @Entity public class Employee { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String firstName; private String middleName; private String lastName; private String ssn; private String email; @OneToOne(fetch = FetchType.EAGER) private Category category; @OneToOne(fetch = FetchType.EAGER) private Location location; @OneToOne(fetch = FetchType.EAGER) private Supervisor supervisor; @OneToOne(fetch = FetchType.EAGER) private BU bu; }
UTF-8
Java
749
java
Employee.java
Java
[ { "context": "tter;\n\nimport javax.persistence.*;\n\n/**\n * @author F.S.(Crosstown)\n * @date 11/21/2017\n * @time 12:17 AM", "end": 140, "score": 0.9998425841331482, "start": 137, "tag": "NAME", "value": "F.S" }, { "context": "\nimport javax.persistence.*;\n\n/**\n * @author F.S.(Crosstown)\n * @date 11/21/2017\n * @time 12:17 AM\n */\n@Gette", "end": 151, "score": 0.9772754907608032, "start": 142, "tag": "NAME", "value": "Crosstown" } ]
null
[]
package com.crosstown.employee_control.domain; import lombok.Getter; import lombok.Setter; import javax.persistence.*; /** * @author F.S.(Crosstown) * @date 11/21/2017 * @time 12:17 AM */ @Getter @Setter @Entity public class Employee { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String firstName; private String middleName; private String lastName; private String ssn; private String email; @OneToOne(fetch = FetchType.EAGER) private Category category; @OneToOne(fetch = FetchType.EAGER) private Location location; @OneToOne(fetch = FetchType.EAGER) private Supervisor supervisor; @OneToOne(fetch = FetchType.EAGER) private BU bu; }
749
0.700935
0.684913
40
17.725
15.321533
55
false
false
0
0
0
0
0
0
0.35
false
false
1
1a5b14c9787ce47241bd6c07a06364c0b46fab6f
25,005,299,603,120
5f811dcd2debd1c7d46822a2800e51a7decd2a1a
/pano-front-web/src/main/java/com/focus3d/pano/member/service/impl/PanoUserBankcardServiceImpl.java
a1a8ef24a5e7d9149d99a5860a71687cfb90203e
[]
no_license
focus3d-fc/pano-front
https://github.com/focus3d-fc/pano-front
f87b4cb8300a826d4f880715ebe689ecfb1ee798
d3cc840720eccba9471f6557c0af34193a58b7ee
refs/heads/master
2021-09-02T23:48:27.963000
2018-01-04T04:26:14
2018-01-04T04:26:14
96,875,392
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.focus3d.pano.member.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.focus3d.pano.common.dao.CommonDao; import com.focus3d.pano.common.service.impl.CommonServiceImpl; import com.focus3d.pano.member.dao.PanoUserBankcardDao; import com.focus3d.pano.member.service.PanoUserBankcardService; import com.focus3d.pano.model.PanoUserBankcardModel; /** * * * * @author lihaijun * */ @Service @Transactional public class PanoUserBankcardServiceImpl extends CommonServiceImpl<PanoUserBankcardModel> implements PanoUserBankcardService<PanoUserBankcardModel> { @Autowired private PanoUserBankcardDao userBankcardDao; @Override public CommonDao<PanoUserBankcardModel> getDao() { return userBankcardDao; } @Override public List<PanoUserBankcardModel> listByUser(long userSn) { return userBankcardDao.listByUser(userSn); } @Override public PanoUserBankcardModel getByCardNo(long userSn, String cardNo) { return userBankcardDao.getByCardNo(userSn, cardNo); } }
UTF-8
Java
1,195
java
PanoUserBankcardServiceImpl.java
Java
[ { "context": "PanoUserBankcardModel;\r\n/**\r\n * \r\n * *\r\n * @author lihaijun\r\n *\r\n */\r\n@Service\r\n@Transactional\r\npublic class ", "end": 577, "score": 0.9994416236877441, "start": 569, "tag": "USERNAME", "value": "lihaijun" } ]
null
[]
package com.focus3d.pano.member.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.focus3d.pano.common.dao.CommonDao; import com.focus3d.pano.common.service.impl.CommonServiceImpl; import com.focus3d.pano.member.dao.PanoUserBankcardDao; import com.focus3d.pano.member.service.PanoUserBankcardService; import com.focus3d.pano.model.PanoUserBankcardModel; /** * * * * @author lihaijun * */ @Service @Transactional public class PanoUserBankcardServiceImpl extends CommonServiceImpl<PanoUserBankcardModel> implements PanoUserBankcardService<PanoUserBankcardModel> { @Autowired private PanoUserBankcardDao userBankcardDao; @Override public CommonDao<PanoUserBankcardModel> getDao() { return userBankcardDao; } @Override public List<PanoUserBankcardModel> listByUser(long userSn) { return userBankcardDao.listByUser(userSn); } @Override public PanoUserBankcardModel getByCardNo(long userSn, String cardNo) { return userBankcardDao.getByCardNo(userSn, cardNo); } }
1,195
0.796653
0.791632
38
29.447369
31.305538
149
false
false
0
0
0
0
0
0
0.868421
false
false
1
e9b43077fd97f09992bb9774b978607d9cee8d06
8,358,006,381,586
410ed6978cb4dd17e0fab38cfe3d18cea8d759e9
/src/main/java/com/mmall/service/IShippingService.java
82cfa454a6c30e22f7c1152bb15fc37899023157
[]
no_license
javazhe/mmall
https://github.com/javazhe/mmall
672cd69678aa9df5f948ffbf8ef8a9947534a254
0d6e90d129e8873e95af60bf1d92818c329fa68c
refs/heads/master
2021-07-01T12:00:39.122000
2018-12-03T08:29:50
2018-12-03T08:29:50
135,582,566
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mmall.service; import com.github.pagehelper.PageInfo; import com.mmall.common.ResponseService; import com.mmall.pojo.Shipping; /** * Created by jia on 2018/6/20. */ public interface IShippingService { ResponseService add(Shipping shipping, Integer userId); ResponseService del(Integer shippingId, Integer userId); ResponseService update(Integer userId,Shipping shipping); ResponseService<Shipping> select(Integer userId, Integer shippingId); ResponseService<PageInfo> list(Integer userId, Integer pageNum, Integer pageSize); }
UTF-8
Java
567
java
IShippingService.java
Java
[ { "context": "import com.mmall.pojo.Shipping;\n\n/**\n * Created by jia on 2018/6/20.\n */\npublic interface IShippingServi", "end": 162, "score": 0.999260425567627, "start": 159, "tag": "USERNAME", "value": "jia" } ]
null
[]
package com.mmall.service; import com.github.pagehelper.PageInfo; import com.mmall.common.ResponseService; import com.mmall.pojo.Shipping; /** * Created by jia on 2018/6/20. */ public interface IShippingService { ResponseService add(Shipping shipping, Integer userId); ResponseService del(Integer shippingId, Integer userId); ResponseService update(Integer userId,Shipping shipping); ResponseService<Shipping> select(Integer userId, Integer shippingId); ResponseService<PageInfo> list(Integer userId, Integer pageNum, Integer pageSize); }
567
0.777778
0.765432
20
27.35
27.796177
86
false
false
0
0
0
0
0
0
0.75
false
false
1
bb56ed5affaec17e73ecb5c1bc317bfd0d972b9c
1,228,360,669,744
b515e4aea875a558e24e74524dff293159c62d4a
/sebinson-sample-web-mis/sebinson-sample-web-mis-service/src/test/java/net/sebinson/sample/web/mis/service/package-info.java
a6799f0e673cbc06cb9fc979d7c74f3aaf24d614
[]
no_license
sebinson/samples
https://github.com/sebinson/samples
a30ff7ec7499a185278b294900a767627c25e2e9
6230e99ed46b541a07f35e4c84e40c7f6badf972
refs/heads/master
2016-09-06T07:48:55.758000
2015-06-02T02:48:47
2015-06-02T02:48:47
32,312,123
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.sebinson.sample.web.mis.service;
UTF-8
Java
44
java
package-info.java
Java
[]
null
[]
package net.sebinson.sample.web.mis.service;
44
0.840909
0.840909
1
44
0
44
false
false
0
0
0
0
0
0
1
false
false
1
ac395ec533d1a67f3202ca4a29ef22a17d8ddc55
14,001,593,389,625
4c3bb44c753f8029ee58c0417973bb42091470d5
/src/main/java/me/seungwoo/MainController.java
30b2d94f74a85bdd5e23e4ffa25bec0b0c23d768
[]
no_license
SonSeungWoo/spring-web-i18n
https://github.com/SonSeungWoo/spring-web-i18n
d37937c7e2034f806ca4a4783f4c3737d96b3027
621a870ddbbc7201eea267402fe42d1cf9ff5a35
refs/heads/master
2020-04-24T08:01:35.024000
2019-04-30T03:26:11
2019-04-30T03:26:11
171,817,744
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package me.seungwoo; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindException; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import java.util.List; /** * Created by Leo. * User: ssw * Date: 2019-02-21 * Time: 15:41 */ @RestController @RequiredArgsConstructor public class MainController { private final MessageByLocale messageSource; private final MainService mainService; private final CustomCollectionValidator customCollectionValidator; @GetMapping("/message") public ResponseEntity<String> message(HttpServletRequest request) { String message = messageSource.getMessage("label.msg", request); return ResponseEntity.ok(message); } @GetMapping("/user") public String user(@Valid @ModelAttribute UserDto userDto) { return "success"; } @PostMapping("/user") public String userTest(@Valid @RequestBody List<UserDto> userDto, BindingResult bindingResult) throws BindException { //mainService.testService(userDto); // 이것만 추가 - List를 직접 validate customCollectionValidator.validate(userDto, bindingResult); if (bindingResult.hasErrors()) { throw new BindException(bindingResult); } return "success"; } }
UTF-8
Java
1,478
java
MainController.java
Java
[ { "context": "t java.util.List;\n\n/**\n * Created by Leo.\n * User: ssw\n * Date: 2019-02-21\n * Time: 15:41\n */\n@RestContr", "end": 402, "score": 0.9996004104614258, "start": 399, "tag": "USERNAME", "value": "ssw" } ]
null
[]
package me.seungwoo; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindException; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import java.util.List; /** * Created by Leo. * User: ssw * Date: 2019-02-21 * Time: 15:41 */ @RestController @RequiredArgsConstructor public class MainController { private final MessageByLocale messageSource; private final MainService mainService; private final CustomCollectionValidator customCollectionValidator; @GetMapping("/message") public ResponseEntity<String> message(HttpServletRequest request) { String message = messageSource.getMessage("label.msg", request); return ResponseEntity.ok(message); } @GetMapping("/user") public String user(@Valid @ModelAttribute UserDto userDto) { return "success"; } @PostMapping("/user") public String userTest(@Valid @RequestBody List<UserDto> userDto, BindingResult bindingResult) throws BindException { //mainService.testService(userDto); // 이것만 추가 - List를 직접 validate customCollectionValidator.validate(userDto, bindingResult); if (bindingResult.hasErrors()) { throw new BindException(bindingResult); } return "success"; } }
1,478
0.730506
0.722298
51
27.666666
25.765661
121
false
false
0
0
0
0
0
0
0.431373
false
false
1
eacaf2c02140c4ca74e36869082c21a312ea3b91
9,139,690,438,517
ad2539ccc19b365a5dddae35a45485bde2aab9fb
/Día01/Ejercicio0401/src/com/hrocha/bucles/Infinitos.java
554f06c6854ed7d866eb739eec22486a3b459417
[]
no_license
hemorale14/curso-ejemplos-java
https://github.com/hemorale14/curso-ejemplos-java
763e0c6b8a98e386eb1fd6d9aa7a915e3f6e8460
0307080cf063a0230db552191757628c8bec7c32
refs/heads/master
2020-02-19T14:57:07.550000
2018-04-13T18:04:14
2018-04-13T18:04:14
106,248,393
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hrocha.bucles; public class Infinitos { public static void main(String[] args) { int i = 0; //evitarlos mala programación for(;;){ if(i==10){ System.out.println("Se rompio el for"); break; } ++i; } while(true){ if(i==10){ System.out.println("Se rompio el while"); break; } ++i; } do{ if(i==10){ System.out.println("Se rompio el do..while"); break; } ++i; }while(i==10); } }
WINDOWS-1250
Java
474
java
Infinitos.java
Java
[]
null
[]
package com.hrocha.bucles; public class Infinitos { public static void main(String[] args) { int i = 0; //evitarlos mala programación for(;;){ if(i==10){ System.out.println("Se rompio el for"); break; } ++i; } while(true){ if(i==10){ System.out.println("Se rompio el while"); break; } ++i; } do{ if(i==10){ System.out.println("Se rompio el do..while"); break; } ++i; }while(i==10); } }
474
0.528541
0.509514
36
12.138889
13.5793
49
false
false
0
0
0
0
0
0
2.583333
false
false
1
a07609eea1d07151639133b6f3546634748aef96
9,139,690,437,192
5f4054b9c21986d44d3346ba06536b6419308dee
/lib/src/main/java/ru/prolib/bootes/lib/config/SchedulerConfigBuilder.java
cbc16753c00c5cfd32a41328d70447e20403cdcc
[]
no_license
robot-aquila/bootes
https://github.com/robot-aquila/bootes
27225fce346c5cb55ee313298770449b89da5d26
18c0c06dbcaa0e1b4c4c0b0e9cbf9bb0974ee298
refs/heads/master
2022-09-14T02:03:07.130000
2020-12-06T23:57:50
2020-12-06T23:57:50
126,428,636
0
0
null
false
2022-09-01T23:08:57
2018-03-23T03:33:22
2020-12-06T23:57:55
2022-09-01T23:08:55
56,399
0
0
1
Java
false
false
package ru.prolib.bootes.lib.config; import java.time.Instant; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ru.prolib.aquila.core.config.ConfigException; @Deprecated public class SchedulerConfigBuilder { private static final Logger logger; static { logger = LoggerFactory.getLogger(SchedulerConfigBuilder.class); } private boolean probeAutoStart, probeAutoShutdown; private Instant probeInitialTime, probeStopTime; public SchedulerConfig build(BasicConfig basicConfig) throws ConfigException { if ( probeAutoShutdown && probeStopTime == null ) { throw new ConfigException("PROBE stop time is required for PROBE auto shutdown"); } if ( basicConfig.isHeadless() && ! probeAutoShutdown ) { throw new ConfigException("PROBE auto shutdown must be enabled in headless mode"); } if ( probeStopTime != null ) { if ( probeInitialTime != null && ! probeStopTime.isAfter(probeInitialTime) ) { throw new ConfigException("PROBE stop time must be greater than initial time"); } else if ( probeInitialTime == null && ! probeStopTime.isAfter(Instant.EPOCH) ) { throw new ConfigException("PROBE stop time must be greater than epoch start time"); } } return new SchedulerConfig( probeAutoStart, probeAutoShutdown, probeInitialTime, probeStopTime ); } public SchedulerConfigBuilder withProbeAutoStart(boolean autoStart) { logger.debug("withProbeAutoStart={}", autoStart); this.probeAutoStart = autoStart; return this; } public SchedulerConfigBuilder withProbeAutoShutdown(boolean autoShutdown) { logger.debug("withProbeAutoShutdown={}", autoShutdown); this.probeAutoShutdown = autoShutdown; return this; } public SchedulerConfigBuilder withProbeInitialTime(Instant initialTime) { logger.debug("withProbeInitialTime={}", initialTime); this.probeInitialTime = initialTime; return this; } public SchedulerConfigBuilder withProbeStopTime(Instant stopTime) { logger.debug("withProbeStopTime={}", stopTime); this.probeStopTime = stopTime; return this; } }
UTF-8
Java
2,070
java
SchedulerConfigBuilder.java
Java
[]
null
[]
package ru.prolib.bootes.lib.config; import java.time.Instant; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ru.prolib.aquila.core.config.ConfigException; @Deprecated public class SchedulerConfigBuilder { private static final Logger logger; static { logger = LoggerFactory.getLogger(SchedulerConfigBuilder.class); } private boolean probeAutoStart, probeAutoShutdown; private Instant probeInitialTime, probeStopTime; public SchedulerConfig build(BasicConfig basicConfig) throws ConfigException { if ( probeAutoShutdown && probeStopTime == null ) { throw new ConfigException("PROBE stop time is required for PROBE auto shutdown"); } if ( basicConfig.isHeadless() && ! probeAutoShutdown ) { throw new ConfigException("PROBE auto shutdown must be enabled in headless mode"); } if ( probeStopTime != null ) { if ( probeInitialTime != null && ! probeStopTime.isAfter(probeInitialTime) ) { throw new ConfigException("PROBE stop time must be greater than initial time"); } else if ( probeInitialTime == null && ! probeStopTime.isAfter(Instant.EPOCH) ) { throw new ConfigException("PROBE stop time must be greater than epoch start time"); } } return new SchedulerConfig( probeAutoStart, probeAutoShutdown, probeInitialTime, probeStopTime ); } public SchedulerConfigBuilder withProbeAutoStart(boolean autoStart) { logger.debug("withProbeAutoStart={}", autoStart); this.probeAutoStart = autoStart; return this; } public SchedulerConfigBuilder withProbeAutoShutdown(boolean autoShutdown) { logger.debug("withProbeAutoShutdown={}", autoShutdown); this.probeAutoShutdown = autoShutdown; return this; } public SchedulerConfigBuilder withProbeInitialTime(Instant initialTime) { logger.debug("withProbeInitialTime={}", initialTime); this.probeInitialTime = initialTime; return this; } public SchedulerConfigBuilder withProbeStopTime(Instant stopTime) { logger.debug("withProbeStopTime={}", stopTime); this.probeStopTime = stopTime; return this; } }
2,070
0.756039
0.755072
68
29.441177
28.662018
87
false
false
0
0
0
0
0
0
2.088235
false
false
1
7c401b817ced488522f2ddc20c458fd5030350ef
29,231,547,451,723
46dca903188fec759063b14ecd2b896ff9f6bed6
/stu_assist_management/src/main/java/cn/edu/uestc/smgt/controller/base/AssistStudentController.java
c363e0bcae0e7211bcafccf31e2f22f6e91cf396
[ "MIT" ]
permissive
nxtpcy/AssistantSystem
https://github.com/nxtpcy/AssistantSystem
0124c27e6658b7313246a30c0dd1c59cac93cd38
ae63bf77d020ef1d8efca00fea432c8635da7ffe
refs/heads/master
2020-03-25T13:39:23.458000
2018-08-06T09:12:14
2018-08-06T09:12:14
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.edu.uestc.smgt.controller.base; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.lang3.StringUtils; import org.apache.poi.ss.usermodel.Sheet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.commons.CommonsMultipartFile; import cn.edu.uestc.smgt.annotation.SysControllerLogAnnotation; import cn.edu.uestc.smgt.common.QueryBase; import cn.edu.uestc.smgt.common.Response; import cn.edu.uestc.smgt.common.StatusType; import cn.edu.uestc.smgt.pojo.AssistStudent; import cn.edu.uestc.smgt.pojo.User; import cn.edu.uestc.smgt.service.base.AssistStudentService; import cn.edu.uestc.smgt.service.base.StudentInSchoolService; import cn.edu.uestc.smgt.utils.ExcelUtil; @Controller @RequestMapping("/base/stu/") public class AssistStudentController { private final Logger logger = LoggerFactory.getLogger(getClass()); @Autowired private AssistStudentService assistStudentService; @Autowired private StudentInSchoolService studentInSchoolService; @SysControllerLogAnnotation(desc = "增加助管") @RequestMapping(value = "add", method = RequestMethod.POST) @ResponseBody public Object add(HttpServletRequest request, HttpServletResponse response, @RequestBody AssistStudent ast) { try { int status = assistStudentService.add(ast); String message = StatusType.value(status).getMessage(); return new Response(status, message); } catch (Exception e) { // TODO: handle exception logger.error( "调用AssistStudentController.add出错,assistStudent={},error={}", new Object[] { ast, e }); return new Response(StatusType.EXCEPTION.getVal(), StatusType.EXCEPTION.getMessage()); } } @SysControllerLogAnnotation(desc = "修改助管信息") @RequestMapping(value = "update", method = RequestMethod.POST) @ResponseBody public Object update(HttpServletRequest request, HttpServletResponse response, @RequestBody AssistStudent ast) { try { int status = assistStudentService.update(ast); String message = StatusType.value(status).getMessage(); return new Response(status, message); } catch (Exception e) { // TODO: handle exception logger.error( "调用AssistStudentController.update出错,assistStudent={},error={}", new Object[] { ast, e }); return new Response(StatusType.EXCEPTION.getVal(), StatusType.EXCEPTION.getMessage()); } } @SysControllerLogAnnotation(desc = "删除助管") @RequestMapping(value = "delete", method = RequestMethod.POST) @ResponseBody public Object delete(HttpServletRequest request, HttpServletResponse response, @RequestBody AssistStudent ast) { try { int status = assistStudentService.delete(ast); String message = StatusType.value(status).getMessage(); return new Response(status, message); } catch (Exception e) { // TODO: handle exception logger.error("调用AssistStudentController.delete出错,ast={},error={}", new Object[] { ast.getDeptId(), e }); return new Response(StatusType.EXCEPTION.getVal(), StatusType.EXCEPTION.getMessage()); } } @RequestMapping(value = "list", method = RequestMethod.POST) @ResponseBody public Object list(HttpServletRequest request, HttpServletResponse response, @RequestBody Map map) { try { QueryBase querybase = new QueryBase(); String banks = (String) map.get("bankName"); String[] bankArray = null; if (banks == null || "".equals(banks)) { bankArray = null; } else { bankArray = banks.split(","); } querybase.addParameter("bankName", bankArray); querybase.addParameter("stuId", map.get("stuId")); querybase.addParameter("name", map.get("name")); HttpSession session = request.getSession(); User user = (User) session.getAttribute("user"); String[] deptIdArray = null; if (user != null && user.getRole() == 1) { deptIdArray = new String[] { user.getDeptId() }; } else { String deptIds = (String) map.get("deptId"); if (deptIds == null || "".equals(deptIds)) { deptIdArray = null; } else { deptIdArray = deptIds.split(","); } } querybase.addParameter("deptId", deptIdArray); querybase.setPageSize(Long.parseLong(map.get("rows").toString())); querybase .setCurrentPage(Long.parseLong(map.get("page").toString())); assistStudentService.query(querybase); HashMap<String, Object> result = new HashMap<String, Object>(); result.put("total", querybase.getTotalRow()); result.put("result", querybase.getResults()); return result; } catch (Exception e) { // TODO: handle exception logger.error("调用AssistStudentController.list1出错,map={},error={}", new Object[] { map, e }); return new Response(StatusType.EXCEPTION.getVal(), StatusType.EXCEPTION.getMessage()); } } @RequestMapping(value = "list1", method = RequestMethod.POST) @ResponseBody public Object list1(HttpServletRequest request, HttpServletResponse response, @RequestParam Map<String, Object> map) { try { QueryBase querybase = new QueryBase(); String banks = (String) map.get("bankName"); String[] bankArray = null; if (banks == null || "".equals(banks)) { bankArray = null; } else { bankArray = banks.split(","); } querybase.addParameter("bankName", bankArray); querybase.addParameter("stuId", map.get("stuId")); querybase.addParameter("name", map.get("name")); HttpSession session = request.getSession(); User user = (User) session.getAttribute("user"); String[] deptIdArray = null; if (user != null && user.getRole() == 1) { deptIdArray = new String[] { user.getDeptId() }; } else { String deptIds = (String) map.get("deptId"); if (deptIds == null || "".equals(deptIds)) { deptIdArray = null; } else { deptIdArray = deptIds.split(","); } } querybase.addParameter("deptId", deptIdArray); querybase.setPageSize(Long.parseLong(map.get("rows").toString())); querybase .setCurrentPage(Long.parseLong(map.get("page").toString())); assistStudentService.query(querybase); HashMap<String, Object> result = new HashMap<String, Object>(); result.put("total", querybase.getTotalRow()); result.put("rows", querybase.getResults()); return result; } catch (Exception e) { // TODO: handle exception logger.error("调用AssistStudentController.list1出错,map={},error={}", new Object[] { map, e }); return new Response(StatusType.EXCEPTION.getVal(), StatusType.EXCEPTION.getMessage()); } } /** * 根据条件查询当前在校生 * * 查询条件:学号,姓名,院系(编号+名称)[下拉列表形式],导师代码(手动输入),导师姓名( 手动输入) * stuId,stuName,deptId,dsId,dsName * * @author ljd * @param request * @param response * @param map * @return */ @RequestMapping(value = "searchStudent", method = RequestMethod.POST) @ResponseBody public Object searchStudentInSchool(HttpServletRequest request, HttpServletResponse response, @RequestBody Map<String, Object> map) { try { QueryBase querybase = new QueryBase(); querybase.addParameter("stuId", map.get("stuId")); querybase.addParameter("stuName", map.get("stuName")); querybase.addParameter("deptId", map.get("deptId")); querybase.addParameter("bankName", map.get("dsId")); querybase.addParameter("dsId", map.get("dsId")); querybase.addParameter("dsName", map.get("dsName")); querybase.setPageSize(Long.parseLong(map.get("rows").toString())); querybase .setCurrentPage(Long.parseLong(map.get("page").toString())); studentInSchoolService.query(querybase); HashMap<String, Object> result = new HashMap<String, Object>(); result.put("total", querybase.getTotalRow()); result.put("result", querybase.getResults()); return result; } catch (Exception e) { // TODO: handle exception logger.error( "调用AssistStudentController.searchStudentInSchool出错,map={},error={}", new Object[] { map, e }); return new Response(StatusType.EXCEPTION.getVal(), StatusType.EXCEPTION.getMessage()); } } /** * 根据条件查询当前在校生 * * 查询条件:学号,姓名,院系(编号+名称)[下拉列表形式],导师代码(手动输入),导师姓名( 手动输入) * stuId,stuName,deptId,dsId,dsName * * @author ljd * @param request * @param response * @param map * @return */ @RequestMapping(value = "searchStudent1", method = RequestMethod.POST) @ResponseBody public Object searchStudentInSchool1(HttpServletRequest request, HttpServletResponse response, @RequestParam Map<String, Object> map) { try { QueryBase querybase = new QueryBase(); querybase.addParameter("stuId", map.get("stuId")); querybase.addParameter("stuName", map.get("stuName")); querybase.addParameter("deptId", map.get("deptId")); querybase.addParameter("bankName", map.get("dsId")); querybase.addParameter("dsId", map.get("dsId")); querybase.addParameter("dsName", map.get("dsName")); querybase.setPageSize(Long.parseLong(map.get("rows").toString())); querybase .setCurrentPage(Long.parseLong(map.get("page").toString())); studentInSchoolService.query(querybase); HashMap<String, Object> result = new HashMap<String, Object>(); result.put("total", querybase.getTotalRow()); result.put("rows", querybase.getResults()); return result; } catch (Exception e) { // TODO: handle exception logger.error( "调用AssistStudentController.searchStudentInSchool出错,map={},error={}", new Object[] { map, e }); return new Response(StatusType.EXCEPTION.getVal(), StatusType.EXCEPTION.getMessage()); } } /** * 根据前端传递的学号集合,批量添加学生信息到助管列表中 * * @author ljd * @param request * @param response * @param map * @return */ @SysControllerLogAnnotation(desc = "添加学生库中学生为助管") @RequestMapping(value = "insertStuToAst", method = RequestMethod.POST) @ResponseBody public Object insertStudentToAssist(HttpServletRequest request, HttpServletResponse response, @RequestBody Map<String, Object> map) { try { String stuIds = (String) map.get("stuIds"); if (stuIds == null) { return new Response(StatusType.PARAMETER_IS_NULL.getVal(), StatusType.PARAMETER_IS_NULL.getMessage()); } // 将stuId分割 String[] ids = stuIds.split(","); String info = assistStudentService.batchAddStudentToAssist(ids); if (!StringUtils.isEmpty(info)) { return new Response(-1, "导入失败信息如下</br>" + info); } else { return new Response(0, "添加成功"); } } catch (Exception e) { // TODO: handle exception logger.error( "调用AssistStudentController.searchStudentInSchool出错,map={},error={}", new Object[] { map, e }); return new Response(StatusType.EXCEPTION.getVal(), StatusType.EXCEPTION.getMessage()); } } /** * 批量上传助管信息,使用xls文件 * */ @SysControllerLogAnnotation(desc = "excel批量上传助管信息") @RequestMapping(value = "upload", method = RequestMethod.POST) @ResponseBody public Object upload(HttpServletRequest request, HttpServletResponse response, @RequestParam("uploadExcel") CommonsMultipartFile files) { System.out.println(files.getOriginalFilename()); if (files != null) { InputStream is = null; try { // 将excel文件转为List,然后调用service层方法批量插入 is = files.getInputStream(); HashMap<String, Object> sheetMap = ExcelUtil.getSheet(is, 1); if (sheetMap.get("sheet") != null) { Sheet sheet = (Sheet) sheetMap.get("sheet"); List<AssistStudent> list = readAststuData(sheet); if (null != list) { // int fileSize = list.size(); String info = assistStudentService .batchAddAssistByExcel(list); if (StringUtils.isEmpty(info)) { return new Response(0, "添加成功"); } else { return new Response(-1, "导入失败信息如下</br>" + info); } } else { return new Response(-1, "数据为空"); } } else { return new Response(-1, "数据为空"); } } catch (Exception e) { // TODO: handle exception logger.error( "调用AssistStudentController.upload出错,files={},error={}", new Object[] { files, e }); return new Response(StatusType.EXCEPTION.getVal(), StatusType.EXCEPTION.getMessage()); } finally { if (is != null) try { is.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return new Response(-1, "未选择文件!"); } /** * 下载填写的模板用于上传使用,用户必须按照这个模板上传 */ @RequestMapping("downloadMB") public void downloadMB(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException { byte[] body = null; InputStream is = request.getSession().getServletContext() .getResourceAsStream("/moban/模板.xlsx"); response.setContentType("application/vnd.ms-excel;charset=utf-8"); response.setHeader("Content-Disposition", "attachment;filename=" + new String(("模板" + ".xls").getBytes(), "iso-8859-1")); ServletOutputStream out = response.getOutputStream(); BufferedInputStream bis = null; BufferedOutputStream bos = null; try { bis = new BufferedInputStream(is); bos = new BufferedOutputStream(out); byte[] buff = new byte[2048]; int bytesRead; // Simple read/write loop. while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { bos.write(buff, 0, bytesRead); } } catch (final IOException e) { throw e; } finally { if (bis != null) bis.close(); if (bos != null) bos.close(); } } /** * 在职助管转为离职状态 在职转离职:先判断当前学生的信息是否已经在离职表中存在。然后更新手机号码,银行信息,银行卡号。 * 然后获取startTime,endTime ,deptName ,然后与原来的info进行拼接。插入 * * 批量助管转离职 * * @return */ @SysControllerLogAnnotation(desc = "在职助管转离职") @RequestMapping(value = "currToHist", method = RequestMethod.POST) @ResponseBody public Object currentToHistory(HttpServletRequest request, HttpServletResponse response, @RequestParam String stuIds) { try { if (stuIds == null) { return new Response(StatusType.PARAMETER_IS_NULL.getVal(), StatusType.PARAMETER_IS_NULL.getMessage()); } // 将stuId分割 String[] ids = stuIds.split(","); int length = ids.length; int successCount = 0; for (int i = 0; i < ids.length; i++) { try { int ans = assistStudentService.currToHist(ids[i]); if (ans == StatusType.SUCCESS.getVal()) successCount++; } catch (Exception e) { // TODO: handle exception logger.error( "调用AssistStudentController.currentToHistory出错,map={},error={}", new Object[] { ids[i], e }); } } if (successCount == length) { return new Response(0, "转离职成功"); } else { return new Response(-1, "失败数据条数:" + (length - successCount)); } } catch (Exception e) { // TODO: handle exception logger.error( "调用AssistStudentController.currentToHistory出错,map={},error={}", new Object[] { stuIds, e }); return new Response(StatusType.EXCEPTION.getVal(), StatusType.EXCEPTION.getMessage()); } } /** * 将excel转为list * * @param sheet * @return */ private List<AssistStudent> readAststuData(Sheet sheet) { // TODO Auto-generated method stub List<AssistStudent> list = new ArrayList<AssistStudent>(); for (int i = 1; i <= sheet.getLastRowNum(); i++) { AssistStudent ast = new AssistStudent(); int j = 0; int nullCount = 0; String stuId = ExcelUtil.getCellValue(sheet, j++, i); if (!ExcelUtil.isNullOrEmpty(stuId)) { ast.setStuId(stuId); } else { nullCount++; } String name = ExcelUtil.getCellValue(sheet, j++, i); if (!ExcelUtil.isNullOrEmpty(name)) { ast.setName(name); } else { nullCount++; } String stuCollId = ExcelUtil.getCellValue(sheet, j++, i); if (!ExcelUtil.isNullOrEmpty(stuCollId)) { ast.setStuCollegeId(stuCollId); } else { nullCount++; } String stuCollName = ExcelUtil.getCellValue(sheet, j++, i); if (!ExcelUtil.isNullOrEmpty(stuCollName)) { ast.setStuCollegeName(stuCollName); } else { nullCount++; } String stuDsId = ExcelUtil.getCellValue(sheet, j++, i); if (!ExcelUtil.isNullOrEmpty(stuDsId)) { ast.setStuDsId(stuDsId); } else { nullCount++; } String stuDsName = ExcelUtil.getCellValue(sheet, j++, i); if (!ExcelUtil.isNullOrEmpty(stuDsName)) { ast.setStuDsName(stuDsName); } else { nullCount++; } String deptId = ExcelUtil.getCellValue(sheet, j++, i); if (!ExcelUtil.isNullOrEmpty(deptId)) { ast.setDeptId(deptId); } else { nullCount++; } String deptName = ExcelUtil.getCellValue(sheet, j++, i); if (!ExcelUtil.isNullOrEmpty(deptName)) { // map.put("deptName", deptName); } else { nullCount++; } String bankNo = ExcelUtil.getCellValue(sheet, j++, i); if (!ExcelUtil.isNullOrEmpty(bankNo)) { ast.setBankNo(bankNo); } else { nullCount++; } String bankName = ExcelUtil.getCellValue(sheet, j++, i); if (!ExcelUtil.isNullOrEmpty(bankName)) { ast.setBankName(bankName); } else { nullCount++; } String tel = ExcelUtil.getCellValue(sheet, j++, i); if (!ExcelUtil.isNullOrEmpty(tel)) { ast.setTelephone(tel); } else { nullCount++; } if (nullCount != j) { list.add(ast); } } return list; } }
UTF-8
Java
18,602
java
AssistStudentController.java
Java
[ { "context": " stuId,stuName,deptId,dsId,dsName\n\t * \n\t * @author ljd\n\t * @param request\n\t * @param response\n\t * @param", "end": 7356, "score": 0.9996752738952637, "start": 7353, "tag": "USERNAME", "value": "ljd" }, { "context": " stuId,stuName,deptId,dsId,dsName\n\t * \n\t * @author ljd\n\t * @param request\n\t * @param response\n\t * @param", "end": 8830, "score": 0.999626874923706, "start": 8827, "tag": "USERNAME", "value": "ljd" }, { "context": "**\n\t * 根据前端传递的学号集合,批量添加学生信息到助管列表中\n\t * \n\t * @author ljd\n\t * @param request\n\t * @param response\n\t * @param", "end": 10222, "score": 0.9996622800827026, "start": 10219, "tag": "USERNAME", "value": "ljd" } ]
null
[]
package cn.edu.uestc.smgt.controller.base; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.lang3.StringUtils; import org.apache.poi.ss.usermodel.Sheet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.commons.CommonsMultipartFile; import cn.edu.uestc.smgt.annotation.SysControllerLogAnnotation; import cn.edu.uestc.smgt.common.QueryBase; import cn.edu.uestc.smgt.common.Response; import cn.edu.uestc.smgt.common.StatusType; import cn.edu.uestc.smgt.pojo.AssistStudent; import cn.edu.uestc.smgt.pojo.User; import cn.edu.uestc.smgt.service.base.AssistStudentService; import cn.edu.uestc.smgt.service.base.StudentInSchoolService; import cn.edu.uestc.smgt.utils.ExcelUtil; @Controller @RequestMapping("/base/stu/") public class AssistStudentController { private final Logger logger = LoggerFactory.getLogger(getClass()); @Autowired private AssistStudentService assistStudentService; @Autowired private StudentInSchoolService studentInSchoolService; @SysControllerLogAnnotation(desc = "增加助管") @RequestMapping(value = "add", method = RequestMethod.POST) @ResponseBody public Object add(HttpServletRequest request, HttpServletResponse response, @RequestBody AssistStudent ast) { try { int status = assistStudentService.add(ast); String message = StatusType.value(status).getMessage(); return new Response(status, message); } catch (Exception e) { // TODO: handle exception logger.error( "调用AssistStudentController.add出错,assistStudent={},error={}", new Object[] { ast, e }); return new Response(StatusType.EXCEPTION.getVal(), StatusType.EXCEPTION.getMessage()); } } @SysControllerLogAnnotation(desc = "修改助管信息") @RequestMapping(value = "update", method = RequestMethod.POST) @ResponseBody public Object update(HttpServletRequest request, HttpServletResponse response, @RequestBody AssistStudent ast) { try { int status = assistStudentService.update(ast); String message = StatusType.value(status).getMessage(); return new Response(status, message); } catch (Exception e) { // TODO: handle exception logger.error( "调用AssistStudentController.update出错,assistStudent={},error={}", new Object[] { ast, e }); return new Response(StatusType.EXCEPTION.getVal(), StatusType.EXCEPTION.getMessage()); } } @SysControllerLogAnnotation(desc = "删除助管") @RequestMapping(value = "delete", method = RequestMethod.POST) @ResponseBody public Object delete(HttpServletRequest request, HttpServletResponse response, @RequestBody AssistStudent ast) { try { int status = assistStudentService.delete(ast); String message = StatusType.value(status).getMessage(); return new Response(status, message); } catch (Exception e) { // TODO: handle exception logger.error("调用AssistStudentController.delete出错,ast={},error={}", new Object[] { ast.getDeptId(), e }); return new Response(StatusType.EXCEPTION.getVal(), StatusType.EXCEPTION.getMessage()); } } @RequestMapping(value = "list", method = RequestMethod.POST) @ResponseBody public Object list(HttpServletRequest request, HttpServletResponse response, @RequestBody Map map) { try { QueryBase querybase = new QueryBase(); String banks = (String) map.get("bankName"); String[] bankArray = null; if (banks == null || "".equals(banks)) { bankArray = null; } else { bankArray = banks.split(","); } querybase.addParameter("bankName", bankArray); querybase.addParameter("stuId", map.get("stuId")); querybase.addParameter("name", map.get("name")); HttpSession session = request.getSession(); User user = (User) session.getAttribute("user"); String[] deptIdArray = null; if (user != null && user.getRole() == 1) { deptIdArray = new String[] { user.getDeptId() }; } else { String deptIds = (String) map.get("deptId"); if (deptIds == null || "".equals(deptIds)) { deptIdArray = null; } else { deptIdArray = deptIds.split(","); } } querybase.addParameter("deptId", deptIdArray); querybase.setPageSize(Long.parseLong(map.get("rows").toString())); querybase .setCurrentPage(Long.parseLong(map.get("page").toString())); assistStudentService.query(querybase); HashMap<String, Object> result = new HashMap<String, Object>(); result.put("total", querybase.getTotalRow()); result.put("result", querybase.getResults()); return result; } catch (Exception e) { // TODO: handle exception logger.error("调用AssistStudentController.list1出错,map={},error={}", new Object[] { map, e }); return new Response(StatusType.EXCEPTION.getVal(), StatusType.EXCEPTION.getMessage()); } } @RequestMapping(value = "list1", method = RequestMethod.POST) @ResponseBody public Object list1(HttpServletRequest request, HttpServletResponse response, @RequestParam Map<String, Object> map) { try { QueryBase querybase = new QueryBase(); String banks = (String) map.get("bankName"); String[] bankArray = null; if (banks == null || "".equals(banks)) { bankArray = null; } else { bankArray = banks.split(","); } querybase.addParameter("bankName", bankArray); querybase.addParameter("stuId", map.get("stuId")); querybase.addParameter("name", map.get("name")); HttpSession session = request.getSession(); User user = (User) session.getAttribute("user"); String[] deptIdArray = null; if (user != null && user.getRole() == 1) { deptIdArray = new String[] { user.getDeptId() }; } else { String deptIds = (String) map.get("deptId"); if (deptIds == null || "".equals(deptIds)) { deptIdArray = null; } else { deptIdArray = deptIds.split(","); } } querybase.addParameter("deptId", deptIdArray); querybase.setPageSize(Long.parseLong(map.get("rows").toString())); querybase .setCurrentPage(Long.parseLong(map.get("page").toString())); assistStudentService.query(querybase); HashMap<String, Object> result = new HashMap<String, Object>(); result.put("total", querybase.getTotalRow()); result.put("rows", querybase.getResults()); return result; } catch (Exception e) { // TODO: handle exception logger.error("调用AssistStudentController.list1出错,map={},error={}", new Object[] { map, e }); return new Response(StatusType.EXCEPTION.getVal(), StatusType.EXCEPTION.getMessage()); } } /** * 根据条件查询当前在校生 * * 查询条件:学号,姓名,院系(编号+名称)[下拉列表形式],导师代码(手动输入),导师姓名( 手动输入) * stuId,stuName,deptId,dsId,dsName * * @author ljd * @param request * @param response * @param map * @return */ @RequestMapping(value = "searchStudent", method = RequestMethod.POST) @ResponseBody public Object searchStudentInSchool(HttpServletRequest request, HttpServletResponse response, @RequestBody Map<String, Object> map) { try { QueryBase querybase = new QueryBase(); querybase.addParameter("stuId", map.get("stuId")); querybase.addParameter("stuName", map.get("stuName")); querybase.addParameter("deptId", map.get("deptId")); querybase.addParameter("bankName", map.get("dsId")); querybase.addParameter("dsId", map.get("dsId")); querybase.addParameter("dsName", map.get("dsName")); querybase.setPageSize(Long.parseLong(map.get("rows").toString())); querybase .setCurrentPage(Long.parseLong(map.get("page").toString())); studentInSchoolService.query(querybase); HashMap<String, Object> result = new HashMap<String, Object>(); result.put("total", querybase.getTotalRow()); result.put("result", querybase.getResults()); return result; } catch (Exception e) { // TODO: handle exception logger.error( "调用AssistStudentController.searchStudentInSchool出错,map={},error={}", new Object[] { map, e }); return new Response(StatusType.EXCEPTION.getVal(), StatusType.EXCEPTION.getMessage()); } } /** * 根据条件查询当前在校生 * * 查询条件:学号,姓名,院系(编号+名称)[下拉列表形式],导师代码(手动输入),导师姓名( 手动输入) * stuId,stuName,deptId,dsId,dsName * * @author ljd * @param request * @param response * @param map * @return */ @RequestMapping(value = "searchStudent1", method = RequestMethod.POST) @ResponseBody public Object searchStudentInSchool1(HttpServletRequest request, HttpServletResponse response, @RequestParam Map<String, Object> map) { try { QueryBase querybase = new QueryBase(); querybase.addParameter("stuId", map.get("stuId")); querybase.addParameter("stuName", map.get("stuName")); querybase.addParameter("deptId", map.get("deptId")); querybase.addParameter("bankName", map.get("dsId")); querybase.addParameter("dsId", map.get("dsId")); querybase.addParameter("dsName", map.get("dsName")); querybase.setPageSize(Long.parseLong(map.get("rows").toString())); querybase .setCurrentPage(Long.parseLong(map.get("page").toString())); studentInSchoolService.query(querybase); HashMap<String, Object> result = new HashMap<String, Object>(); result.put("total", querybase.getTotalRow()); result.put("rows", querybase.getResults()); return result; } catch (Exception e) { // TODO: handle exception logger.error( "调用AssistStudentController.searchStudentInSchool出错,map={},error={}", new Object[] { map, e }); return new Response(StatusType.EXCEPTION.getVal(), StatusType.EXCEPTION.getMessage()); } } /** * 根据前端传递的学号集合,批量添加学生信息到助管列表中 * * @author ljd * @param request * @param response * @param map * @return */ @SysControllerLogAnnotation(desc = "添加学生库中学生为助管") @RequestMapping(value = "insertStuToAst", method = RequestMethod.POST) @ResponseBody public Object insertStudentToAssist(HttpServletRequest request, HttpServletResponse response, @RequestBody Map<String, Object> map) { try { String stuIds = (String) map.get("stuIds"); if (stuIds == null) { return new Response(StatusType.PARAMETER_IS_NULL.getVal(), StatusType.PARAMETER_IS_NULL.getMessage()); } // 将stuId分割 String[] ids = stuIds.split(","); String info = assistStudentService.batchAddStudentToAssist(ids); if (!StringUtils.isEmpty(info)) { return new Response(-1, "导入失败信息如下</br>" + info); } else { return new Response(0, "添加成功"); } } catch (Exception e) { // TODO: handle exception logger.error( "调用AssistStudentController.searchStudentInSchool出错,map={},error={}", new Object[] { map, e }); return new Response(StatusType.EXCEPTION.getVal(), StatusType.EXCEPTION.getMessage()); } } /** * 批量上传助管信息,使用xls文件 * */ @SysControllerLogAnnotation(desc = "excel批量上传助管信息") @RequestMapping(value = "upload", method = RequestMethod.POST) @ResponseBody public Object upload(HttpServletRequest request, HttpServletResponse response, @RequestParam("uploadExcel") CommonsMultipartFile files) { System.out.println(files.getOriginalFilename()); if (files != null) { InputStream is = null; try { // 将excel文件转为List,然后调用service层方法批量插入 is = files.getInputStream(); HashMap<String, Object> sheetMap = ExcelUtil.getSheet(is, 1); if (sheetMap.get("sheet") != null) { Sheet sheet = (Sheet) sheetMap.get("sheet"); List<AssistStudent> list = readAststuData(sheet); if (null != list) { // int fileSize = list.size(); String info = assistStudentService .batchAddAssistByExcel(list); if (StringUtils.isEmpty(info)) { return new Response(0, "添加成功"); } else { return new Response(-1, "导入失败信息如下</br>" + info); } } else { return new Response(-1, "数据为空"); } } else { return new Response(-1, "数据为空"); } } catch (Exception e) { // TODO: handle exception logger.error( "调用AssistStudentController.upload出错,files={},error={}", new Object[] { files, e }); return new Response(StatusType.EXCEPTION.getVal(), StatusType.EXCEPTION.getMessage()); } finally { if (is != null) try { is.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return new Response(-1, "未选择文件!"); } /** * 下载填写的模板用于上传使用,用户必须按照这个模板上传 */ @RequestMapping("downloadMB") public void downloadMB(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException { byte[] body = null; InputStream is = request.getSession().getServletContext() .getResourceAsStream("/moban/模板.xlsx"); response.setContentType("application/vnd.ms-excel;charset=utf-8"); response.setHeader("Content-Disposition", "attachment;filename=" + new String(("模板" + ".xls").getBytes(), "iso-8859-1")); ServletOutputStream out = response.getOutputStream(); BufferedInputStream bis = null; BufferedOutputStream bos = null; try { bis = new BufferedInputStream(is); bos = new BufferedOutputStream(out); byte[] buff = new byte[2048]; int bytesRead; // Simple read/write loop. while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { bos.write(buff, 0, bytesRead); } } catch (final IOException e) { throw e; } finally { if (bis != null) bis.close(); if (bos != null) bos.close(); } } /** * 在职助管转为离职状态 在职转离职:先判断当前学生的信息是否已经在离职表中存在。然后更新手机号码,银行信息,银行卡号。 * 然后获取startTime,endTime ,deptName ,然后与原来的info进行拼接。插入 * * 批量助管转离职 * * @return */ @SysControllerLogAnnotation(desc = "在职助管转离职") @RequestMapping(value = "currToHist", method = RequestMethod.POST) @ResponseBody public Object currentToHistory(HttpServletRequest request, HttpServletResponse response, @RequestParam String stuIds) { try { if (stuIds == null) { return new Response(StatusType.PARAMETER_IS_NULL.getVal(), StatusType.PARAMETER_IS_NULL.getMessage()); } // 将stuId分割 String[] ids = stuIds.split(","); int length = ids.length; int successCount = 0; for (int i = 0; i < ids.length; i++) { try { int ans = assistStudentService.currToHist(ids[i]); if (ans == StatusType.SUCCESS.getVal()) successCount++; } catch (Exception e) { // TODO: handle exception logger.error( "调用AssistStudentController.currentToHistory出错,map={},error={}", new Object[] { ids[i], e }); } } if (successCount == length) { return new Response(0, "转离职成功"); } else { return new Response(-1, "失败数据条数:" + (length - successCount)); } } catch (Exception e) { // TODO: handle exception logger.error( "调用AssistStudentController.currentToHistory出错,map={},error={}", new Object[] { stuIds, e }); return new Response(StatusType.EXCEPTION.getVal(), StatusType.EXCEPTION.getMessage()); } } /** * 将excel转为list * * @param sheet * @return */ private List<AssistStudent> readAststuData(Sheet sheet) { // TODO Auto-generated method stub List<AssistStudent> list = new ArrayList<AssistStudent>(); for (int i = 1; i <= sheet.getLastRowNum(); i++) { AssistStudent ast = new AssistStudent(); int j = 0; int nullCount = 0; String stuId = ExcelUtil.getCellValue(sheet, j++, i); if (!ExcelUtil.isNullOrEmpty(stuId)) { ast.setStuId(stuId); } else { nullCount++; } String name = ExcelUtil.getCellValue(sheet, j++, i); if (!ExcelUtil.isNullOrEmpty(name)) { ast.setName(name); } else { nullCount++; } String stuCollId = ExcelUtil.getCellValue(sheet, j++, i); if (!ExcelUtil.isNullOrEmpty(stuCollId)) { ast.setStuCollegeId(stuCollId); } else { nullCount++; } String stuCollName = ExcelUtil.getCellValue(sheet, j++, i); if (!ExcelUtil.isNullOrEmpty(stuCollName)) { ast.setStuCollegeName(stuCollName); } else { nullCount++; } String stuDsId = ExcelUtil.getCellValue(sheet, j++, i); if (!ExcelUtil.isNullOrEmpty(stuDsId)) { ast.setStuDsId(stuDsId); } else { nullCount++; } String stuDsName = ExcelUtil.getCellValue(sheet, j++, i); if (!ExcelUtil.isNullOrEmpty(stuDsName)) { ast.setStuDsName(stuDsName); } else { nullCount++; } String deptId = ExcelUtil.getCellValue(sheet, j++, i); if (!ExcelUtil.isNullOrEmpty(deptId)) { ast.setDeptId(deptId); } else { nullCount++; } String deptName = ExcelUtil.getCellValue(sheet, j++, i); if (!ExcelUtil.isNullOrEmpty(deptName)) { // map.put("deptName", deptName); } else { nullCount++; } String bankNo = ExcelUtil.getCellValue(sheet, j++, i); if (!ExcelUtil.isNullOrEmpty(bankNo)) { ast.setBankNo(bankNo); } else { nullCount++; } String bankName = ExcelUtil.getCellValue(sheet, j++, i); if (!ExcelUtil.isNullOrEmpty(bankName)) { ast.setBankName(bankName); } else { nullCount++; } String tel = ExcelUtil.getCellValue(sheet, j++, i); if (!ExcelUtil.isNullOrEmpty(tel)) { ast.setTelephone(tel); } else { nullCount++; } if (nullCount != j) { list.add(ast); } } return list; } }
18,602
0.683926
0.681726
557
30.83124
21.61945
76
false
false
0
0
0
0
0
0
3.294435
false
false
1
175e31325e89507ec6d26a5575d778267feca230
3,908,420,287,249
0ffa0ef4e3e86a8e9875666c7fa2c100fcf0c42a
/app/momting/src/com/mamating/adapter/StoryListAdapter.java
157bded0a221961668688ebafde253753540b7f1
[]
no_license
momting/momting
https://github.com/momting/momting
2bc530de14ddfd3a01b96d4ff50b5066cc157949
81e7e089a52706ff4c45a676527c805fe2cef6ea
refs/heads/master
2016-03-20T12:09:49.749000
2014-10-09T10:09:45
2014-10-09T10:09:45
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mamating.adapter; import android.content.Context; import android.database.Cursor; import android.support.v4.widget.CursorAdapter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import butterknife.ButterKnife; import butterknife.InjectView; import com.mamating.R; import com.mamating.bean.Feed; import com.mamating.util.CommonUtility; import com.nostra13.universalimageloader.core.ImageLoader; public class StoryListAdapter extends CursorAdapter { private Context mContext; private ImageLoader mImageLoader; private LayoutInflater mInflater; static class ViewHolder { @InjectView(R.id.iv_picture) ImageView iv_picture; @InjectView(R.id.tv_author) TextView tv_author; @InjectView(R.id.tv_title) TextView tv_title; @InjectView(R.id.tv_publish_time) TextView tv_publish_time; public ViewHolder(View view) { ButterKnife.inject(this, view); view.setTag(this); } } public StoryListAdapter(Context context, Cursor c) { super(context, c); mContext = context; mImageLoader = ImageLoader.getInstance(); mInflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public void bindView(View view, Context arg1, Cursor cursor) { ViewHolder holder = (ViewHolder) view.getTag(); Feed storyFeed = new Feed(); storyFeed.loadFromCursor(cursor); mImageLoader.displayImage(storyFeed.getThumb_path(), holder.iv_picture); holder.tv_author.setText(storyFeed.getUname()); holder.tv_title.setText(storyFeed.getDescription()); if (storyFeed.getPublish_time() != null) { String publishTime = CommonUtility.getPublishTime(Long .parseLong(storyFeed.getPublish_time() + "000")); holder.tv_publish_time.setText(publishTime); } } @Override public View newView(Context arg0, Cursor arg1, ViewGroup arg2) { View view = mInflater.inflate(R.layout.layout_story_item, null); new ViewHolder(view); return view; } }
UTF-8
Java
2,037
java
StoryListAdapter.java
Java
[]
null
[]
package com.mamating.adapter; import android.content.Context; import android.database.Cursor; import android.support.v4.widget.CursorAdapter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import butterknife.ButterKnife; import butterknife.InjectView; import com.mamating.R; import com.mamating.bean.Feed; import com.mamating.util.CommonUtility; import com.nostra13.universalimageloader.core.ImageLoader; public class StoryListAdapter extends CursorAdapter { private Context mContext; private ImageLoader mImageLoader; private LayoutInflater mInflater; static class ViewHolder { @InjectView(R.id.iv_picture) ImageView iv_picture; @InjectView(R.id.tv_author) TextView tv_author; @InjectView(R.id.tv_title) TextView tv_title; @InjectView(R.id.tv_publish_time) TextView tv_publish_time; public ViewHolder(View view) { ButterKnife.inject(this, view); view.setTag(this); } } public StoryListAdapter(Context context, Cursor c) { super(context, c); mContext = context; mImageLoader = ImageLoader.getInstance(); mInflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public void bindView(View view, Context arg1, Cursor cursor) { ViewHolder holder = (ViewHolder) view.getTag(); Feed storyFeed = new Feed(); storyFeed.loadFromCursor(cursor); mImageLoader.displayImage(storyFeed.getThumb_path(), holder.iv_picture); holder.tv_author.setText(storyFeed.getUname()); holder.tv_title.setText(storyFeed.getDescription()); if (storyFeed.getPublish_time() != null) { String publishTime = CommonUtility.getPublishTime(Long .parseLong(storyFeed.getPublish_time() + "000")); holder.tv_publish_time.setText(publishTime); } } @Override public View newView(Context arg0, Cursor arg1, ViewGroup arg2) { View view = mInflater.inflate(R.layout.layout_story_item, null); new ViewHolder(view); return view; } }
2,037
0.763868
0.758959
74
26.527027
20.072317
74
false
false
0
0
0
0
0
0
1.783784
false
false
10
48ab75022d1396031a238c61d2525b74370efc04
28,552,942,637,168
4e196d4bdde75d6b897786cebccab9955e9b491c
/src/fabric/server/dao/AccountSessionDao.java
1e8260279690ca19e9f7fd0ba36fbf8076104775
[]
no_license
kaihualee/FabricApp_Server
https://github.com/kaihualee/FabricApp_Server
fa72205fa611416bf985a5f6f86641cbe3547720
b8491c101b046170bf7f6a2c92fb7285e216dfed
refs/heads/master
2020-04-30T01:35:13.478000
2014-03-19T05:03:04
2014-03-19T05:03:04
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * @(#)AccountSessionDao.java, 2013-7-19. * */ package fabric.server.dao; import fabric.common.db.BaseDao; import fabric.common.db.LogicDao; import fabric.server.entity.Account; import fabric.server.entity.AccountSession; import fabric.server.entity.ClientPower; /** * @author likaihua */ public interface AccountSessionDao extends LogicDao<AccountSession> { /** * 根据账户和IP和登录界面 * * @param account * @param ip * @param power * @return */ public AccountSession getByAccountByIPAndPower(Account account, String ip, ClientPower power); }
UTF-8
Java
647
java
AccountSessionDao.java
Java
[ { "context": "bric.server.entity.ClientPower;\r\n\r\n/**\r\n * @author likaihua\r\n */\r\npublic interface AccountSessionDao extends ", "end": 309, "score": 0.9995928406715393, "start": 301, "tag": "USERNAME", "value": "likaihua" } ]
null
[]
/** * @(#)AccountSessionDao.java, 2013-7-19. * */ package fabric.server.dao; import fabric.common.db.BaseDao; import fabric.common.db.LogicDao; import fabric.server.entity.Account; import fabric.server.entity.AccountSession; import fabric.server.entity.ClientPower; /** * @author likaihua */ public interface AccountSessionDao extends LogicDao<AccountSession> { /** * 根据账户和IP和登录界面 * * @param account * @param ip * @param power * @return */ public AccountSession getByAccountByIPAndPower(Account account, String ip, ClientPower power); }
647
0.658692
0.647528
28
20.392857
20.174841
78
false
false
0
0
0
0
0
0
0.357143
false
false
10
10df603222b1fbffb7cb9dcb26672eb5e8ab688b
2,018,634,635,569
ff33fdc95e43f00f3bfeab883a3e3dc6d4e9f50d
/3-1/p2017_1/Tesk_3/src/com/bean/Renew.java
fd8bcdd920538192c9a7b0e1545f0b0d188b979c
[ "Apache-2.0" ]
permissive
define16/Class
https://github.com/define16/Class
e2da95b744e2be8fc40342d127f0f401787b9a6f
8b0771a348b2bcb19ba338ebff94326828a293ea
refs/heads/master
2021-06-27T20:08:05.578000
2019-09-08T15:49:57
2019-09-08T15:49:57
148,975,197
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bean; import java.io.InputStream; import java.util.ArrayList; import java.util.HashSet; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; import com.cookie.URLManager; public class Renew extends Thread{ String keyword; ArrayList<Data> newcheckArrList,oldList; int gap; public void setkeyword(String keyword) { this.keyword = keyword; } public void setarray( ArrayList<Data> oldList) { this.oldList = oldList; } public void run() { Parser p = new Parser(); try{ for(int i=0; i< 10; i++) { System.out.println(i*100 + "초 경과"); HashSet hscheck = new HashSet(p.goodsSearch(keyword)); //헤쉬셋을 선언해서 중복된 키워드 값을 제거 newcheckArrList = new ArrayList<Data>(hscheck); //새로운 어레이리스트에 다시 저장 if(oldList.size() < newcheckArrList.size()) { //gap = newcheckArrList.size() - oldList.size(); for(int j=newcheckArrList.size(); j<oldList.size(); j++) System.out.println(newcheckArrList.get(j)); } sleep(100000); // 30초간격으로 스레드 실행 } }catch (Exception e) { // TODO: handle exceptions e.printStackTrace(); } } }
UHC
Java
1,280
java
Renew.java
Java
[]
null
[]
package com.bean; import java.io.InputStream; import java.util.ArrayList; import java.util.HashSet; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; import com.cookie.URLManager; public class Renew extends Thread{ String keyword; ArrayList<Data> newcheckArrList,oldList; int gap; public void setkeyword(String keyword) { this.keyword = keyword; } public void setarray( ArrayList<Data> oldList) { this.oldList = oldList; } public void run() { Parser p = new Parser(); try{ for(int i=0; i< 10; i++) { System.out.println(i*100 + "초 경과"); HashSet hscheck = new HashSet(p.goodsSearch(keyword)); //헤쉬셋을 선언해서 중복된 키워드 값을 제거 newcheckArrList = new ArrayList<Data>(hscheck); //새로운 어레이리스트에 다시 저장 if(oldList.size() < newcheckArrList.size()) { //gap = newcheckArrList.size() - oldList.size(); for(int j=newcheckArrList.size(); j<oldList.size(); j++) System.out.println(newcheckArrList.get(j)); } sleep(100000); // 30초간격으로 스레드 실행 } }catch (Exception e) { // TODO: handle exceptions e.printStackTrace(); } } }
1,280
0.641176
0.629412
55
20.636364
20.467592
87
false
false
0
0
0
0
0
0
3.072727
false
false
10
3045e3cbf439a605dc80168d346820972ca5037b
5,626,407,160,757
2611c8b7cecb6ddc286436b3a0b27a9424561193
/src/main/java/com/example/demo/config/CxfConfig.java
9588b5cf6bf664fc97d5a41de17b112cac626493
[]
no_license
saysky/webservice-server-demo
https://github.com/saysky/webservice-server-demo
698b79c344b9c6dcd65185825c1b9f532f0579c7
69028f6da09569e93c4ce24da0af31602f71ab48
refs/heads/master
2020-06-02T02:46:26.834000
2019-06-09T13:34:53
2019-06-09T13:34:53
191,010,433
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
//package com.example.demo.config; // //import com.example.demo.service.UserService; //import org.apache.cxf.Bus; //import org.apache.cxf.jaxws.EndpointImpl; //import org.apache.cxf.transport.servlet.CXFServlet; //import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.boot.web.servlet.ServletRegistrationBean; //import org.springframework.context.annotation.Bean; //import org.springframework.context.annotation.Configuration; // //import javax.xml.ws.Endpoint; ///** // * @author 言曌 // * @date 2019-06-09 17:15 // */ //@Configuration //public class CxfConfig { // @Autowired(required = false) // private Bus bus; // // @Autowired // UserService userService; // // /** // * 此方法作用是改变项目中服务名的前缀名,此处127.0.0.1或者localhost不能访问时,请使用ipconfig查看本机ip来访问 // * 此方法被注释后:wsdl访问地址为http://127.0.0.1:8080/services/user?wsdl // * 去掉注释后:wsdl访问地址为:http://127.0.0.1:8080/soap/user?wsdl // * @return // */ // @SuppressWarnings("all") // @Bean // public ServletRegistrationBean dispatcherServlet() { // return new ServletRegistrationBean(new CXFServlet(), "/soap/*"); // } // // /** JAX-WS // * 站点服务 // * **/ // @Bean // public Endpoint endpoint() { // EndpointImpl endpoint = new EndpointImpl(bus, userService); // endpoint.publish("/user"); // return endpoint; // } // //}
UTF-8
Java
1,520
java
CxfConfig.java
Java
[ { "context": "/import javax.xml.ws.Endpoint;\n///**\n// * @author 言曌\n// * @date 2019-06-09 17:15\n// */\n//@Configuratio", "end": 521, "score": 0.9938061237335205, "start": 519, "tag": "NAME", "value": "言曌" }, { "context": "rvice;\n//\n// /**\n// * 此方法作用是改变项目中服务名的前缀名,此处127.0.0.1或者localhost不能访问时,请使用ipconfig查看本机ip来访问\n// * 此方法", "end": 761, "score": 0.9996189475059509, "start": 752, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "pconfig查看本机ip来访问\n// * 此方法被注释后:wsdl访问地址为http://127.0.0.1:8080/services/user?wsdl\n// * 去掉注释后:wsdl访问地址为:", "end": 841, "score": 0.9992626905441284, "start": 832, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "ervices/user?wsdl\n// * 去掉注释后:wsdl访问地址为:http://127.0.0.1:8080/soap/user?wsdl\n// * @return\n// */\n//", "end": 907, "score": 0.999377965927124, "start": 898, "tag": "IP_ADDRESS", "value": "127.0.0.1" } ]
null
[]
//package com.example.demo.config; // //import com.example.demo.service.UserService; //import org.apache.cxf.Bus; //import org.apache.cxf.jaxws.EndpointImpl; //import org.apache.cxf.transport.servlet.CXFServlet; //import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.boot.web.servlet.ServletRegistrationBean; //import org.springframework.context.annotation.Bean; //import org.springframework.context.annotation.Configuration; // //import javax.xml.ws.Endpoint; ///** // * @author 言曌 // * @date 2019-06-09 17:15 // */ //@Configuration //public class CxfConfig { // @Autowired(required = false) // private Bus bus; // // @Autowired // UserService userService; // // /** // * 此方法作用是改变项目中服务名的前缀名,此处127.0.0.1或者localhost不能访问时,请使用ipconfig查看本机ip来访问 // * 此方法被注释后:wsdl访问地址为http://127.0.0.1:8080/services/user?wsdl // * 去掉注释后:wsdl访问地址为:http://127.0.0.1:8080/soap/user?wsdl // * @return // */ // @SuppressWarnings("all") // @Bean // public ServletRegistrationBean dispatcherServlet() { // return new ServletRegistrationBean(new CXFServlet(), "/soap/*"); // } // // /** JAX-WS // * 站点服务 // * **/ // @Bean // public Endpoint endpoint() { // EndpointImpl endpoint = new EndpointImpl(bus, userService); // endpoint.publish("/user"); // return endpoint; // } // //}
1,520
0.662808
0.635311
47
28.425531
23.027037
76
false
false
0
0
0
0
0
0
0.382979
false
false
10
692966d6780ff8c7f47c5ff5af3084b32dd99810
5,626,407,161,772
d4d7ed014bedf45ad8541f7a4aaaea371d3cde65
/MySpringSecurityACL3.0/src/main/java/com/sjg/PermissionService.java
59fb03e777a7a7f70ed93829995ff9421f06c190
[ "Apache-2.0" ]
permissive
cocodroid/Spring-Security-demo
https://github.com/cocodroid/Spring-Security-demo
2ee470e2490e70fecb29b8333531ec520e2e01fa
87cf8d1b113a13722b9284525af2ad6e5b648ec3
refs/heads/master
2021-06-27T23:33:11.637000
2017-09-17T10:38:34
2017-09-17T10:38:34
103,747,922
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sjg; import java.util.List; import org.springframework.security.acls.domain.BasePermission; import org.springframework.security.acls.domain.ObjectIdentityImpl; import org.springframework.security.acls.domain.PrincipalSid; import org.springframework.security.acls.model.AccessControlEntry; import org.springframework.security.acls.model.MutableAcl; import org.springframework.security.acls.model.MutableAclService; import org.springframework.security.acls.model.NotFoundException; import org.springframework.security.acls.model.ObjectIdentity; import org.springframework.security.acls.model.Permission; import org.springframework.transaction.annotation.Transactional; public class PermissionService { private MutableAclService mutableAclService; public void setMutableAclService(MutableAclService mutableAclService) { this.mutableAclService = mutableAclService; } @Transactional public void addPermission(long id, String clz, String recipient, int mask) { PrincipalSid sid = new PrincipalSid(recipient); // Permission permission = BasePermission.buildFromMask(mask); Permission permission = null; if (mask == 4) { permission = BasePermission.CREATE; } else if (mask == 16) { permission = BasePermission.ADMINISTRATION; } else if (mask == 8) { permission = BasePermission.DELETE; }else if(mask ==1) { permission = BasePermission.READ; }else { System.out.println("tsdf7r6wfwe7gfwef"); } ObjectIdentity oid = null; if (clz.equals("account")) { oid = new ObjectIdentityImpl(Account.class, id); } else if (clz.equals("contract")) { oid = new ObjectIdentityImpl(Contract.class, id); } else if (clz.equals("message")) { oid = new ObjectIdentityImpl(Message.class, id); } MutableAcl acl; try { acl = (MutableAcl) mutableAclService.readAclById(oid); } catch (NotFoundException nfe) { acl = mutableAclService.createAcl(oid); } acl.insertAce(acl.getEntries().size(), permission, sid, true); mutableAclService.updateAcl(acl); } @Transactional public void deletePermission(long id, String clz, String recipient, int mask) { PrincipalSid sid = new PrincipalSid(recipient); // Permission permission = BasePermission.buildFromMask(mask); Permission permission = null; if (mask == 8) permission = BasePermission.DELETE; ObjectIdentity oid = null; if (clz.equals("account")) { oid = new ObjectIdentityImpl(Account.class, id); } else if (clz.equals("contract")) { oid = new ObjectIdentityImpl(Contract.class, id); } else if (clz.equals("message")) { oid = new ObjectIdentityImpl(Message.class, id); } MutableAcl acl = (MutableAcl) mutableAclService.readAclById(oid); /* * AccessControlEntry[] entries = acl.getEntries(); * * for (int i = 0; i < entries.length; i++) { if (entries[i].getSid().equals(sid) && entries[i].getPermission().equals(permission)) { acl.deleteAce(i); } } */ List<AccessControlEntry> entries = acl.getEntries(); for (int i = 0; i < entries.size(); i++) { if (entries.get(i).getSid().equals(sid) && entries.get(i).getPermission().equals(permission)) { acl.deleteAce(i); } } mutableAclService.updateAcl(acl); } }
UTF-8
Java
3,284
java
PermissionService.java
Java
[]
null
[]
package com.sjg; import java.util.List; import org.springframework.security.acls.domain.BasePermission; import org.springframework.security.acls.domain.ObjectIdentityImpl; import org.springframework.security.acls.domain.PrincipalSid; import org.springframework.security.acls.model.AccessControlEntry; import org.springframework.security.acls.model.MutableAcl; import org.springframework.security.acls.model.MutableAclService; import org.springframework.security.acls.model.NotFoundException; import org.springframework.security.acls.model.ObjectIdentity; import org.springframework.security.acls.model.Permission; import org.springframework.transaction.annotation.Transactional; public class PermissionService { private MutableAclService mutableAclService; public void setMutableAclService(MutableAclService mutableAclService) { this.mutableAclService = mutableAclService; } @Transactional public void addPermission(long id, String clz, String recipient, int mask) { PrincipalSid sid = new PrincipalSid(recipient); // Permission permission = BasePermission.buildFromMask(mask); Permission permission = null; if (mask == 4) { permission = BasePermission.CREATE; } else if (mask == 16) { permission = BasePermission.ADMINISTRATION; } else if (mask == 8) { permission = BasePermission.DELETE; }else if(mask ==1) { permission = BasePermission.READ; }else { System.out.println("tsdf7r6wfwe7gfwef"); } ObjectIdentity oid = null; if (clz.equals("account")) { oid = new ObjectIdentityImpl(Account.class, id); } else if (clz.equals("contract")) { oid = new ObjectIdentityImpl(Contract.class, id); } else if (clz.equals("message")) { oid = new ObjectIdentityImpl(Message.class, id); } MutableAcl acl; try { acl = (MutableAcl) mutableAclService.readAclById(oid); } catch (NotFoundException nfe) { acl = mutableAclService.createAcl(oid); } acl.insertAce(acl.getEntries().size(), permission, sid, true); mutableAclService.updateAcl(acl); } @Transactional public void deletePermission(long id, String clz, String recipient, int mask) { PrincipalSid sid = new PrincipalSid(recipient); // Permission permission = BasePermission.buildFromMask(mask); Permission permission = null; if (mask == 8) permission = BasePermission.DELETE; ObjectIdentity oid = null; if (clz.equals("account")) { oid = new ObjectIdentityImpl(Account.class, id); } else if (clz.equals("contract")) { oid = new ObjectIdentityImpl(Contract.class, id); } else if (clz.equals("message")) { oid = new ObjectIdentityImpl(Message.class, id); } MutableAcl acl = (MutableAcl) mutableAclService.readAclById(oid); /* * AccessControlEntry[] entries = acl.getEntries(); * * for (int i = 0; i < entries.length; i++) { if (entries[i].getSid().equals(sid) && entries[i].getPermission().equals(permission)) { acl.deleteAce(i); } } */ List<AccessControlEntry> entries = acl.getEntries(); for (int i = 0; i < entries.size(); i++) { if (entries.get(i).getSid().equals(sid) && entries.get(i).getPermission().equals(permission)) { acl.deleteAce(i); } } mutableAclService.updateAcl(acl); } }
3,284
0.710414
0.707065
96
32.208332
28.068708
157
false
false
0
0
0
0
0
0
2.15625
false
false
10
579bb696a000f65505a684654b522025b56d8044
19,164,144,137,669
765d2a62f14c4e6210b188ca70b450692973995d
/src/br/com/fiap/healthtrack/dao/ConnectionFactory.java
b89de5bc9d46d86a02440b54eab6541af347e823
[]
no_license
stefbitt/Health-Track
https://github.com/stefbitt/Health-Track
1afe9fe992f94704bd26a75be49bb2b705e760bc
bb84c4ebf27bad2944698bd6a987e47713b4e76b
refs/heads/master
2023-01-23T12:16:43.039000
2020-11-23T22:16:48
2020-11-23T22:16:48
272,539,310
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.fiap.healthtrack.dao; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; public final class ConnectionFactory { private static final Logger LOGGER = Logger.getLogger(ConnectionFactory.class.getName()); private static final Factory FACTORY = new Factory(); private ConnectionFactory() { } public static Connection create() { return FACTORY.get(); } public static void close() { FACTORY.remove(); } private static final class Factory extends InheritableThreadLocal<Connection> { private Properties prop = new Properties(); private boolean started = false; public Factory() { try { InputStream resourceAsStream = ConnectionFactory.class.getResourceAsStream("/connection.properties"); prop.load(resourceAsStream); DriverManager.registerDriver(new oracle.jdbc.OracleDriver()); } catch (SQLException | IOException e) { LOGGER.log(Level.WARNING, null, e); } } @Override protected Connection initialValue() { Connection connection = null; try { started = true; connection = DriverManager.getConnection(prop.getProperty("url"), prop.getProperty("username"), prop.getProperty("password")); } catch (SQLException e) { started = false; LOGGER.log(Level.WARNING, null, e); } return connection; } @Override public void remove() { if (started) { Connection connection = get(); started = false; try { connection.close(); } catch (SQLException e) { LOGGER.log(Level.WARNING, null, e); } } super.remove(); } } }
UTF-8
Java
1,746
java
ConnectionFactory.java
Java
[]
null
[]
package br.com.fiap.healthtrack.dao; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; public final class ConnectionFactory { private static final Logger LOGGER = Logger.getLogger(ConnectionFactory.class.getName()); private static final Factory FACTORY = new Factory(); private ConnectionFactory() { } public static Connection create() { return FACTORY.get(); } public static void close() { FACTORY.remove(); } private static final class Factory extends InheritableThreadLocal<Connection> { private Properties prop = new Properties(); private boolean started = false; public Factory() { try { InputStream resourceAsStream = ConnectionFactory.class.getResourceAsStream("/connection.properties"); prop.load(resourceAsStream); DriverManager.registerDriver(new oracle.jdbc.OracleDriver()); } catch (SQLException | IOException e) { LOGGER.log(Level.WARNING, null, e); } } @Override protected Connection initialValue() { Connection connection = null; try { started = true; connection = DriverManager.getConnection(prop.getProperty("url"), prop.getProperty("username"), prop.getProperty("password")); } catch (SQLException e) { started = false; LOGGER.log(Level.WARNING, null, e); } return connection; } @Override public void remove() { if (started) { Connection connection = get(); started = false; try { connection.close(); } catch (SQLException e) { LOGGER.log(Level.WARNING, null, e); } } super.remove(); } } }
1,746
0.705613
0.705613
74
22.594595
23.197693
105
false
false
0
0
0
0
0
0
2.351351
false
false
10
4704ba7941a099bc896ba7a130d394a77cb495f3
33,560,874,513,714
cf7ceadfbdf398c8617c92e2df401d7b6c7cd5f0
/2920.java
8bf4994e4f991ec4520ca4e6830868b7a427fad9
[]
no_license
llordly/Baekjoon
https://github.com/llordly/Baekjoon
0e48696a34b8ce51c6a9e6ca97f586db2fb7830f
e9fc3fd9c9f6b301d4842eae639c2b146008a12c
refs/heads/master
2022-10-27T12:57:36.502000
2022-10-19T18:54:46
2022-10-19T18:54:46
152,554,823
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.Scanner; import java.util.StringTokenizer; public class Main { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); String line = keyboard.nextLine(); StringTokenizer st = new StringTokenizer(line); int list[] = new int[8]; for (int i = 0; i < 8; ++i) { list[i] = Integer.parseInt(st.nextToken()); } boolean asc = true; boolean dsc = true; for (int j = 0 ; j < 7; ++j) { if (list[j] - list[j+1] < 0) { dsc = false; } else if (list[j] - list[j+1] > 0) { asc = false; } } if(asc) System.out.println("ascending"); else if(dsc) System.out.println("descending"); else if (!asc && !dsc) System.out.println("mixed"); } }
UTF-8
Java
743
java
2920.java
Java
[]
null
[]
import java.util.Scanner; import java.util.StringTokenizer; public class Main { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); String line = keyboard.nextLine(); StringTokenizer st = new StringTokenizer(line); int list[] = new int[8]; for (int i = 0; i < 8; ++i) { list[i] = Integer.parseInt(st.nextToken()); } boolean asc = true; boolean dsc = true; for (int j = 0 ; j < 7; ++j) { if (list[j] - list[j+1] < 0) { dsc = false; } else if (list[j] - list[j+1] > 0) { asc = false; } } if(asc) System.out.println("ascending"); else if(dsc) System.out.println("descending"); else if (!asc && !dsc) System.out.println("mixed"); } }
743
0.584118
0.572005
36
19.638889
17.635433
53
false
false
0
0
0
0
0
0
2.472222
false
false
10
38bed3c8a94e62e8b5c22221348683d103b2c6b5
21,706,764,767,143
854af93d6a8f11936a78562921b2c72d017c9a06
/GUESSINGGAME.java
545ee8b65444d8e656774ce84061e2d29a540ec9
[]
no_license
ColintasMerl/cc2-project
https://github.com/ColintasMerl/cc2-project
dfb65b9c7d24dcf1c34572ac50f0854aa714fe66
e4215f45dee9a36128382149c7dc61687ed1cf62
refs/heads/master
2020-04-05T11:23:01.568000
2018-11-20T08:43:28
2018-11-20T08:43:28
156,832,578
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package guessing.game; import java.util.Random; import java.util.Scanner; /** * * @author cc2_1d-6 */ public class GUESSINGGAME { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Random randomNumber = new Random(); Scanner kbd = new Scanner(System.in); int computerValue = randomNumber.nextInt(100); int numberOfTries = 0; int success = 0; int guess = 0; while (success ==0) { System.out.println("please enter an integer betwen 1 and 100 inclusive: "); guess = kbd.nextInt(); numberOfTries++; if (guess < 1 || guess > 100){ System.out.println("Invalid input"); } else if (guess == computerValue){ success++; System.out.println("Congratulations you won! Your numbers of tries was: " + numberOfTries + " and the number was: " + computerValue); } else if (guess < computerValue){ System.out.println("Your guess is too low!"); } else if (guess > computerValue){ System.out.println("Your guess is too high!"); } } } }
UTF-8
Java
1,476
java
GUESSINGGAME.java
Java
[ { "context": "\r\nimport java.util.Scanner;\r\n\r\n/**\r\n *\r\n * @author cc2_1d-6\r\n */\r\npublic class GUESSINGGAME {\r\n\r\n /**\r\n ", "end": 299, "score": 0.9994786977767944, "start": 291, "tag": "USERNAME", "value": "cc2_1d-6" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package guessing.game; import java.util.Random; import java.util.Scanner; /** * * @author cc2_1d-6 */ public class GUESSINGGAME { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Random randomNumber = new Random(); Scanner kbd = new Scanner(System.in); int computerValue = randomNumber.nextInt(100); int numberOfTries = 0; int success = 0; int guess = 0; while (success ==0) { System.out.println("please enter an integer betwen 1 and 100 inclusive: "); guess = kbd.nextInt(); numberOfTries++; if (guess < 1 || guess > 100){ System.out.println("Invalid input"); } else if (guess == computerValue){ success++; System.out.println("Congratulations you won! Your numbers of tries was: " + numberOfTries + " and the number was: " + computerValue); } else if (guess < computerValue){ System.out.println("Your guess is too low!"); } else if (guess > computerValue){ System.out.println("Your guess is too high!"); } } } }
1,476
0.569106
0.556911
54
25.333334
27.371248
147
false
false
0
0
0
0
0
0
0.407407
false
false
10
1d9e0195326cb82f6619a118bc0531785866ff3e
32,401,233,286,881
ca327b3f0c6bff3cba957162b7e16d386a34f650
/src/main/java/org/fasttrackit/Vehicle.java
b7b829df040b51e4ff92e02e9262d543a986721f
[]
no_license
DanielaCozmescu/racingGame
https://github.com/DanielaCozmescu/racingGame
b3aadd406dc1cbed75af12401451aeddbcfa4b97
3a53cc2e09c7bfcd121b70839e61d5e21cc96295
refs/heads/master
2021-01-06T01:34:48.654000
2020-03-16T17:45:49
2020-03-16T17:45:49
241,190,980
0
0
null
false
2020-10-13T19:37:13
2020-02-17T19:32:32
2020-03-16T17:45:58
2020-10-13T19:37:11
14
0
0
1
Java
false
false
package org.fasttrackit; import java.util.SortedMap; public class Vehicle { //instance** variables int racingNumber; String name; int maxSpeed; double mileage; String color; double fuelLevel; double totalDistance; boolean damaged; public double accelerate(double speed, double durationInHours){ if (fuelLevel <= 0){ System.out.println("Not enough fuel."); return 0; } if (speed > maxSpeed){ System.out.println("Max speed exceeded!"); return 0; } else if (speed == maxSpeed){ System.out.println("Be careful! Max speed reached!"); } else { System.out.println("Valid speed entered."); } // use more fuel if speed > 120 double mileageMultiplier = 1; if (speed > 120) { mileageMultiplier = speed / 100; } System.out.println(name + " is accelerating with " + speed + " km/h for " + durationInHours + " h"); // local variables double travelDistance = speed * durationInHours; System.out.println("Travel distance: " + travelDistance); totalDistance += travelDistance; System.out.println("Total travel distance: " + totalDistance); double usedFuel = travelDistance * mileage / 100; // fuelLevel = fuelLevel - usedFuel; fuelLevel -=usedFuel; System.out.println("Remaining fuel: " + fuelLevel); return travelDistance; } public void decelerate(){ // TODO: implement this System.out.println("This is just a demo method."); } }
UTF-8
Java
1,643
java
Vehicle.java
Java
[]
null
[]
package org.fasttrackit; import java.util.SortedMap; public class Vehicle { //instance** variables int racingNumber; String name; int maxSpeed; double mileage; String color; double fuelLevel; double totalDistance; boolean damaged; public double accelerate(double speed, double durationInHours){ if (fuelLevel <= 0){ System.out.println("Not enough fuel."); return 0; } if (speed > maxSpeed){ System.out.println("Max speed exceeded!"); return 0; } else if (speed == maxSpeed){ System.out.println("Be careful! Max speed reached!"); } else { System.out.println("Valid speed entered."); } // use more fuel if speed > 120 double mileageMultiplier = 1; if (speed > 120) { mileageMultiplier = speed / 100; } System.out.println(name + " is accelerating with " + speed + " km/h for " + durationInHours + " h"); // local variables double travelDistance = speed * durationInHours; System.out.println("Travel distance: " + travelDistance); totalDistance += travelDistance; System.out.println("Total travel distance: " + totalDistance); double usedFuel = travelDistance * mileage / 100; // fuelLevel = fuelLevel - usedFuel; fuelLevel -=usedFuel; System.out.println("Remaining fuel: " + fuelLevel); return travelDistance; } public void decelerate(){ // TODO: implement this System.out.println("This is just a demo method."); } }
1,643
0.590383
0.580645
63
25.079365
23.413671
108
false
false
0
0
0
0
0
0
0.47619
false
false
10
7ff4b5278b974a25b583a7c540bb3a2f8a015626
17,119,739,654,233
818776e990768d66d7e90d6f6b27139a6828572f
/src/gwc/FuncionarioDAO.java
e20308ce283f29b423fc8024fa403eb8dc48cd37
[]
no_license
GuilhermeAlbert/gwc
https://github.com/GuilhermeAlbert/gwc
40fdd25ac35a8f82ec71b6e44de21a56c81729e0
5bf7ec3b943026ffcc08baed785b9505c5bea7bb
refs/heads/master
2020-04-16T21:20:14.602000
2019-06-21T20:52:34
2019-06-21T20:52:34
165,921,543
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package gwc; import java.sql.ResultSet; import java.util.ArrayList; import javax.swing.JOptionPane; /** * * @author Camila Desktop */ public class FuncionarioDAO extends Conexao{ public String cadastroFuncionario(Funcionario func) { try { String setenca; setenca = "INSERT INTO FUNCIONARIO VALUES(NULL,'"+func.getCod_endereco()+"','"+func.getNome()+"','"+ func.getSexo()+"','"+ func.getUsuario() + "','" + func.getSenha() + "',"+ func.getNivel()+"," + func.getTelefone()+ ",'"+ func.getEmail()+"');"; return this.atualizarBanco(setenca); } catch(Exception e) { JOptionPane.showMessageDialog(null, "Erro Comando SQL " + e.getMessage() ); return e.getMessage(); } } public String atualizarFuncionario(Funcionario func) { try { String setenca; setenca = "UPDATE FUNCIONARIO SET NOME='"+ func.getNome() + "',SEXO ='" + func.getSexo() + "',USUARIO = '" + func.getUsuario() + "',SENHA = '" + func.getSenha() + "'WHERE CODIGO_FUNCIONARIO =" + func.getCod_funcionario(); return this.atualizarBanco(setenca); } catch(Exception e) { return e.getMessage(); } } public String excluirFuncionario(Funcionario func) { try { String setenca; setenca = "DELETE DROM FUNCIONARIO WHERE CODIGO =" + func.getCod_funcionario(); return this.atualizarBanco(setenca); } catch(Exception e) { return e.getMessage(); } } public ArrayList listarFuncionario() { try { ArrayList funcionarios = new ArrayList(); String setenca = "SELECT * FROM FUNCIONARIO ORDER BY NOME_FUNCIONARIO"; ResultSet rs = this.getResultSet(setenca); while(rs.next()) { Funcionario func = new Funcionario(); func.setCod_funcionario(rs.getInt("COD_FUNCIONARIO")); func.setNome(rs.getString("NOME_FUNCIONARIO")); func.getSexo(); //func.getd(); func.getUsuario(); func.getSenha(); func.setNivel(rs.getInt("NIVEL")); funcionarios.add(func); } return funcionarios; } catch(Exception e) { System.out.println(e.getMessage()); return null; } } public Funcionario autenticacao(String usu, char[] senha) { Funcionario fun = null; try { String setenca = "SELECT * FROM FUNCIONARIO WHERE USUARIO = '"+usu+"' AND SENHA='"+String.valueOf(senha)+" WHERE NIVEL= 1'"; ResultSet rs = this.getResultSet(setenca); if(rs.next()) { fun = new Funcionario(); fun.setNivel(rs.getInt("NIVEL")); } } catch(Exception e) { System.out.println(e.getMessage()); return null; } return fun; } }
UTF-8
Java
3,505
java
FuncionarioDAO.java
Java
[ { "context": "import javax.swing.JOptionPane;\n\n/**\n *\n * @author Camila Desktop\n */\npublic class FuncionarioDAO extends Conexao{\n", "end": 319, "score": 0.9995381832122803, "start": 305, "tag": "NAME", "value": "Camila Desktop" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package gwc; import java.sql.ResultSet; import java.util.ArrayList; import javax.swing.JOptionPane; /** * * @author <NAME> */ public class FuncionarioDAO extends Conexao{ public String cadastroFuncionario(Funcionario func) { try { String setenca; setenca = "INSERT INTO FUNCIONARIO VALUES(NULL,'"+func.getCod_endereco()+"','"+func.getNome()+"','"+ func.getSexo()+"','"+ func.getUsuario() + "','" + func.getSenha() + "',"+ func.getNivel()+"," + func.getTelefone()+ ",'"+ func.getEmail()+"');"; return this.atualizarBanco(setenca); } catch(Exception e) { JOptionPane.showMessageDialog(null, "Erro Comando SQL " + e.getMessage() ); return e.getMessage(); } } public String atualizarFuncionario(Funcionario func) { try { String setenca; setenca = "UPDATE FUNCIONARIO SET NOME='"+ func.getNome() + "',SEXO ='" + func.getSexo() + "',USUARIO = '" + func.getUsuario() + "',SENHA = '" + func.getSenha() + "'WHERE CODIGO_FUNCIONARIO =" + func.getCod_funcionario(); return this.atualizarBanco(setenca); } catch(Exception e) { return e.getMessage(); } } public String excluirFuncionario(Funcionario func) { try { String setenca; setenca = "DELETE DROM FUNCIONARIO WHERE CODIGO =" + func.getCod_funcionario(); return this.atualizarBanco(setenca); } catch(Exception e) { return e.getMessage(); } } public ArrayList listarFuncionario() { try { ArrayList funcionarios = new ArrayList(); String setenca = "SELECT * FROM FUNCIONARIO ORDER BY NOME_FUNCIONARIO"; ResultSet rs = this.getResultSet(setenca); while(rs.next()) { Funcionario func = new Funcionario(); func.setCod_funcionario(rs.getInt("COD_FUNCIONARIO")); func.setNome(rs.getString("NOME_FUNCIONARIO")); func.getSexo(); //func.getd(); func.getUsuario(); func.getSenha(); func.setNivel(rs.getInt("NIVEL")); funcionarios.add(func); } return funcionarios; } catch(Exception e) { System.out.println(e.getMessage()); return null; } } public Funcionario autenticacao(String usu, char[] senha) { Funcionario fun = null; try { String setenca = "SELECT * FROM FUNCIONARIO WHERE USUARIO = '"+usu+"' AND SENHA='"+String.valueOf(senha)+" WHERE NIVEL= 1'"; ResultSet rs = this.getResultSet(setenca); if(rs.next()) { fun = new Funcionario(); fun.setNivel(rs.getInt("NIVEL")); } } catch(Exception e) { System.out.println(e.getMessage()); return null; } return fun; } }
3,497
0.509272
0.508987
114
29.745613
26.865425
136
false
false
0
0
0
0
0
0
0.5
false
false
10
efd58dcf1381c4b845b960283f3086e3277740c7
33,526,514,773,965
5b756956d7cb2027d9c7bf19ee485d577afdacdd
/sml-project/upms-snp/src/main/java/org/hw/sml/test/Hes.java
0122eeb3a2df4075975d26c3dcf7269e0ef28e2c
[]
no_license
huangwenjimmy/sml-module
https://github.com/huangwenjimmy/sml-module
588c50b9e8e21e662dbd13e77fccbe2ff6be342a
22034d6969c6e5a5bf51734452ee111edcc2b8d7
refs/heads/master
2021-01-11T00:57:04.707000
2020-06-11T10:25:05
2020-06-11T10:25:05
70,474,778
10
6
null
false
2020-10-13T01:45:00
2016-10-10T09:50:10
2020-09-15T02:58:01
2020-10-13T01:44:59
12,204
9
5
7
JavaScript
false
false
package org.hw.sml.test; import java.io.IOException; import java.util.Date; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.hw.sml.rest.annotation.SmlResource; import org.hw.sml.support.ioc.annotation.Bean; import org.hw.sml.support.time.annotation.Scheduler; import org.hw.sml.tools.DateTools; import org.hw.sml.tools.Https; @Bean @SmlResource("hello") public class Hes { @Scheduler("0 * * * * ?") public void task(){ } @Scheduler("0 * * * * ?") @SmlResource public Object task2() throws IOException{ try { Thread.sleep(1000*10); } catch (InterruptedException e) { e.printStackTrace(); } return 10; /*while(true){ sum(); System.out.println(DateTools.sdf_mi().format(new Date())); }*/ } public void sum(){ for(int i=0;i<1000000000;i++){ new Date(); } } public static void main(String[] args) throws InterruptedException, IOException { Thread t=new Thread(new Runnable() { public void run() { try { String result=Https.newPostBodyHttps("http://localhost:16010/snp/sml/hello").execute(); System.out.println(result); } catch (IOException e) { e.printStackTrace(); } } }); t.start(); Thread.sleep(100L); t.stop(); Thread.sleep(100L); System.out.println(t.isAlive()); } public static void main1(String[] args) { ScheduledExecutorService ses=Executors.newScheduledThreadPool(10); Future<Void> sf=ses.submit(new Callable<Void>() { public Void call() throws Exception { System.out.println(DateTools.sdf_mi().format(new Date())); String result; try { result = Https.newPostBodyHttps("http://localhost:16010/snp/sml/hello").execute(); System.out.println(result); } catch (IOException e) { e.printStackTrace(); } System.out.println("end"); return null; } }); try { Object obj=sf.get(2,TimeUnit.SECONDS); System.out.println("99999"); } catch (InterruptedException | ExecutionException | TimeoutException e) { e.printStackTrace(); sf.cancel(true); ses.shutdownNow(); } } }
UTF-8
Java
2,470
java
Hes.java
Java
[]
null
[]
package org.hw.sml.test; import java.io.IOException; import java.util.Date; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.hw.sml.rest.annotation.SmlResource; import org.hw.sml.support.ioc.annotation.Bean; import org.hw.sml.support.time.annotation.Scheduler; import org.hw.sml.tools.DateTools; import org.hw.sml.tools.Https; @Bean @SmlResource("hello") public class Hes { @Scheduler("0 * * * * ?") public void task(){ } @Scheduler("0 * * * * ?") @SmlResource public Object task2() throws IOException{ try { Thread.sleep(1000*10); } catch (InterruptedException e) { e.printStackTrace(); } return 10; /*while(true){ sum(); System.out.println(DateTools.sdf_mi().format(new Date())); }*/ } public void sum(){ for(int i=0;i<1000000000;i++){ new Date(); } } public static void main(String[] args) throws InterruptedException, IOException { Thread t=new Thread(new Runnable() { public void run() { try { String result=Https.newPostBodyHttps("http://localhost:16010/snp/sml/hello").execute(); System.out.println(result); } catch (IOException e) { e.printStackTrace(); } } }); t.start(); Thread.sleep(100L); t.stop(); Thread.sleep(100L); System.out.println(t.isAlive()); } public static void main1(String[] args) { ScheduledExecutorService ses=Executors.newScheduledThreadPool(10); Future<Void> sf=ses.submit(new Callable<Void>() { public Void call() throws Exception { System.out.println(DateTools.sdf_mi().format(new Date())); String result; try { result = Https.newPostBodyHttps("http://localhost:16010/snp/sml/hello").execute(); System.out.println(result); } catch (IOException e) { e.printStackTrace(); } System.out.println("end"); return null; } }); try { Object obj=sf.get(2,TimeUnit.SECONDS); System.out.println("99999"); } catch (InterruptedException | ExecutionException | TimeoutException e) { e.printStackTrace(); sf.cancel(true); ses.shutdownNow(); } } }
2,470
0.657085
0.638057
91
25.142857
21.01939
93
false
false
0
0
0
0
0
0
2.802198
false
false
10
8998ce82f11b5b6d871df4c2c9153674b48126b9
21,294,447,907,345
317fb7dd8227c52aa10017adc86d76630f4721e4
/src/cn/zw/part/new2/heatbeat/dto/MsgType.java
14058d639ff13b206b1c57507c980b14c1947f1e
[]
no_license
zwwei1314/dubbo-test
https://github.com/zwwei1314/dubbo-test
19481c59c483f7786df9961cf359bd9528a1b8e4
b47ad1fcefe677c4be2df0c5ae100a6e62ebbbb9
refs/heads/master
2021-01-18T19:09:25.097000
2017-04-01T06:40:29
2017-04-01T06:40:29
86,889,706
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.zw.part.new2.heatbeat.dto; /** * Created by Administrator * on 2016/7/14 * 10:24. */ public enum MsgType { BEAT(1),BUSINESS(2); private int type; MsgType(int type){ this.type = type; } public int getType() { return type; } }
UTF-8
Java
284
java
MsgType.java
Java
[]
null
[]
package cn.zw.part.new2.heatbeat.dto; /** * Created by Administrator * on 2016/7/14 * 10:24. */ public enum MsgType { BEAT(1),BUSINESS(2); private int type; MsgType(int type){ this.type = type; } public int getType() { return type; } }
284
0.570423
0.521127
20
13.2
11.469961
37
false
false
0
0
0
0
0
0
0.3
false
false
10
f8681bf795f254f61a2592bbb852a8d6c1f56fff
34,376,918,238,182
233dfcc32fd942108a3f38d123f5304ff0cf0aa2
/src/main/java/com/bnool/anishop/services/front/express/dao/ExpressDao.java
7773da60bab31c22d5c87956db7bf42f2d70753d
[]
no_license
gashli/animation-shop
https://github.com/gashli/animation-shop
a7f40ba8eadf0b4b8e26d2c484f7f6c03998d29f
c79ff0f2209af1e1e216c6a8e963db11bb938ee8
refs/heads/master
2021-01-20T18:52:15.390000
2016-08-09T13:35:51
2016-08-09T13:36:06
65,292,635
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bnool.anishop.services.front.express.dao; import com.bnool.anishop.core.DaoManager; import com.bnool.anishop.services.front.express.bean.Express; public interface ExpressDao extends DaoManager<Express> { }
UTF-8
Java
220
java
ExpressDao.java
Java
[]
null
[]
package com.bnool.anishop.services.front.express.dao; import com.bnool.anishop.core.DaoManager; import com.bnool.anishop.services.front.express.bean.Express; public interface ExpressDao extends DaoManager<Express> { }
220
0.822727
0.822727
7
30.428572
26.671854
61
false
false
0
0
0
0
0
0
0.428571
false
false
10
00b00e15600a309959bc77ea55ffefbb3c4121a8
25,761,213,842,359
55dca62e858f1a44c2186774339823a301b48dc7
/code/my-app/functions/3/getUnitToSettlement_NativeTrade.java
c3f0637579b9c235aaa640721d7563012d57bc15
[]
no_license
jwiszowata/code_reaper
https://github.com/jwiszowata/code_reaper
4fff256250299225879d1412eb1f70b136d7a174
17dde61138cec117047a6ebb412ee1972886f143
refs/heads/master
2022-12-15T14:46:30.640000
2022-02-10T14:02:45
2022-02-10T14:02:45
84,747,455
0
0
null
false
2022-12-07T23:48:18
2017-03-12T18:26:11
2022-02-10T14:00:02
2022-12-07T23:48:18
16,770
0
0
24
Java
false
false
public List<NativeTradeItem> getUnitToSettlement() { return this.unitToSettlement; }
UTF-8
Java
88
java
getUnitToSettlement_NativeTrade.java
Java
[]
null
[]
public List<NativeTradeItem> getUnitToSettlement() { return this.unitToSettlement; }
88
0.795455
0.795455
3
28.666666
21.044926
52
false
false
0
0
0
0
0
0
0.333333
false
false
10
c098177365712df5d53dd4534ca5ede7a7e247e5
11,312,943,922,224
cb46ce6949d2d0960213827a5d7183fa37f8b498
/src/util/cryptingUtil.java
2a39a8c1696104d8ca70dd0293966df6e0c373ff
[]
no_license
princilia/Gestion_pharm
https://github.com/princilia/Gestion_pharm
10e6949990933768fbed82c507af7bbd317bfdb7
cfb5f856ff9133d0cbafe39813b74c7808b109ed
refs/heads/master
2022-11-09T01:24:38.017000
2020-06-15T21:04:01
2020-06-15T21:04:01
272,544,171
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package util; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.logging.Level; import java.util.logging.Logger; //ma classe text pour la cryptage de mot de passe public class cryptingUtil { public static void main(String []args) throws NoSuchAlgorithmException{ try { System.out.println(encryptPassword("111111111111111111111")); } catch (UnsupportedEncodingException ex) { Logger.getLogger(cryptingUtil.class.getName()).log(Level.SEVERE, null, ex); } } public static String encryptPassword(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest crypt = MessageDigest.getInstance("SHA-1"); crypt.reset(); crypt.update(password.getBytes("UTF-8")); return new BigInteger(1, crypt.digest()).toString(16); } }
UTF-8
Java
1,180
java
cryptingUtil.java
Java
[ { "context": "{\n System.out.println(encryptPassword(\"111111111111111111111\"));\n } catch (UnsupportedEncodingException", "end": 669, "score": 0.9971221685409546, "start": 648, "tag": "PASSWORD", "value": "111111111111111111111" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package util; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.logging.Level; import java.util.logging.Logger; //ma classe text pour la cryptage de mot de passe public class cryptingUtil { public static void main(String []args) throws NoSuchAlgorithmException{ try { System.out.println(encryptPassword("<PASSWORD>")); } catch (UnsupportedEncodingException ex) { Logger.getLogger(cryptingUtil.class.getName()).log(Level.SEVERE, null, ex); } } public static String encryptPassword(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest crypt = MessageDigest.getInstance("SHA-1"); crypt.reset(); crypt.update(password.getBytes("UTF-8")); return new BigInteger(1, crypt.digest()).toString(16); } }
1,169
0.712712
0.690678
36
31.777779
30.34259
121
false
false
0
0
0
0
0
0
0.555556
false
false
10
5f82a4ad0034c3d80c0a9afc3999d4d15f977248
20,744,692,097,709
297133e0cd33b01878e615ab57e48f25660175af
/oms/src/main/java/com/yanyun/oms/service/MemberQuestionnaireService.java
68f4c3feec641ce3c8436013cbe49a0230f5ad3d
[]
no_license
wangguang2018/springboot-jpa-vue
https://github.com/wangguang2018/springboot-jpa-vue
2ba6dea316cbd1f4e11d089c9450ced4b06cceea
0eea9ad79c1795ac1656482fcd286417a920dfe2
refs/heads/master
2020-03-21T05:40:50.943000
2018-06-21T13:40:30
2018-06-21T13:40:30
138,173,204
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yanyun.oms.service; import com.yanyun.oms.dto.MemberQuestionnaireDTO; import com.ydd.framework.core.common.Pagination; import com.ydd.framework.core.service.BaseService; import com.yanyun.oms.entity.MemberQuestionnaire; import java.util.List; /** * Service - 用户问卷信息 * * @author zhaoziyu * @since 2018-03-01 */ public interface MemberQuestionnaireService extends BaseService { /** * 保存用户问卷信息 * * @param memberQuestionnaire 用户问卷信息 */ void save(MemberQuestionnaire memberQuestionnaire); /** * 更新用户问卷信息 * * @param memberQuestionnaire 用户问卷信息 */ void update(MemberQuestionnaire memberQuestionnaire); /** * 删除用户问卷信息 * * @param id 编号 * @return 删除数量 */ Integer delete(Integer id); /** * 删除用户问卷信息 * * @param ids 编号数组 * @return 删除数量 */ Integer deleteByIds(Integer[] ids); /** * 查询用户问卷信息 * * @param id 编号 * @return 用户问卷信息 */ MemberQuestionnaire findById(Integer id); /** * 查询用户问卷信息 * * @param pagination 分页信息 * @return 分页结果 */ Pagination findPage(Pagination pagination); List<MemberQuestionnaireDTO> findByQuestionId(Integer questionnaireId, Integer questionId); /** * 查询该问卷有多少人回答过 * @param questionnaireId * @return */ Integer countQuestionnaireByMember(Integer questionnaireId); /** * 查询问卷下某个题目的某个选项的用户选择数量 * @param questionnaireId * @param questionId * @param optionId * @return */ Integer countQuestionOptionByMember(Integer questionnaireId,Integer questionId,Integer optionId); }
UTF-8
Java
1,920
java
MemberQuestionnaireService.java
Java
[ { "context": ".util.List;\n\n/**\n * Service - 用户问卷信息\n *\n * @author zhaoziyu\n * @since 2018-03-01\n */\npublic interface MemberQ", "end": 304, "score": 0.9994650483131409, "start": 296, "tag": "USERNAME", "value": "zhaoziyu" } ]
null
[]
package com.yanyun.oms.service; import com.yanyun.oms.dto.MemberQuestionnaireDTO; import com.ydd.framework.core.common.Pagination; import com.ydd.framework.core.service.BaseService; import com.yanyun.oms.entity.MemberQuestionnaire; import java.util.List; /** * Service - 用户问卷信息 * * @author zhaoziyu * @since 2018-03-01 */ public interface MemberQuestionnaireService extends BaseService { /** * 保存用户问卷信息 * * @param memberQuestionnaire 用户问卷信息 */ void save(MemberQuestionnaire memberQuestionnaire); /** * 更新用户问卷信息 * * @param memberQuestionnaire 用户问卷信息 */ void update(MemberQuestionnaire memberQuestionnaire); /** * 删除用户问卷信息 * * @param id 编号 * @return 删除数量 */ Integer delete(Integer id); /** * 删除用户问卷信息 * * @param ids 编号数组 * @return 删除数量 */ Integer deleteByIds(Integer[] ids); /** * 查询用户问卷信息 * * @param id 编号 * @return 用户问卷信息 */ MemberQuestionnaire findById(Integer id); /** * 查询用户问卷信息 * * @param pagination 分页信息 * @return 分页结果 */ Pagination findPage(Pagination pagination); List<MemberQuestionnaireDTO> findByQuestionId(Integer questionnaireId, Integer questionId); /** * 查询该问卷有多少人回答过 * @param questionnaireId * @return */ Integer countQuestionnaireByMember(Integer questionnaireId); /** * 查询问卷下某个题目的某个选项的用户选择数量 * @param questionnaireId * @param questionId * @param optionId * @return */ Integer countQuestionOptionByMember(Integer questionnaireId,Integer questionId,Integer optionId); }
1,920
0.641998
0.637184
82
19.256098
20.873493
101
false
false
0
0
0
0
0
0
0.219512
false
false
10
b511d1703f05c837df2e73c651d13d4d344e5977
6,631,429,537,247
1ac6d275aed5924cbbdb26970e9fdbca59a15581
/TEC/PROGRAMMING/SEM2/Object Oriented/007_Inheritance & Polymorphism/src/Videogame.java
cb9fab21447e5813cd91b37751a3366a3aff2ab0
[]
no_license
Mauville/DOCS
https://github.com/Mauville/DOCS
18f608ec2f5510765f8196986f2a59445aefd04d
319c558b42a2d00713c6b96a3feba6114d127393
refs/heads/master
2021-06-19T22:24:09.156000
2019-08-06T08:10:23
2019-08-06T08:10:23
145,639,167
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Videogame extends DigitalMedia { public String publisher, platform, region; @Override public String toString() { return "Im a videogame"; } }
UTF-8
Java
179
java
Videogame.java
Java
[]
null
[]
public class Videogame extends DigitalMedia { public String publisher, platform, region; @Override public String toString() { return "Im a videogame"; } }
179
0.670391
0.670391
8
21.375
17.427977
46
false
false
0
0
0
0
0
0
0.5
false
false
10
9ed4eae849e05d3941b5f3ccff999dd597a6cb33
21,938,693,008,333
c030cfd61f731dd90c61292fb566a72b6c87b919
/V15/src/main/java/servlet/LoginServlet.java
b8103ad1594f5f72440b99496471f0fce0407a31
[]
no_license
HarryLast/WebServer
https://github.com/HarryLast/WebServer
5adf6a828dea8e771a03607a3cf3252c89e948e0
814b3dfcf22293a8c02a0e82b00fb549eb661eb9
refs/heads/master
2023-02-18T17:14:02.475000
2021-01-18T12:44:36
2021-01-18T12:44:36
330,664,650
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package servlet; import com.webserver.http.HttpRequest; import com.webserver.http.HttpResponse; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; public class LoginServlet { public void Service(HttpRequest request, HttpResponse response) { System.out.println("开始处理登录..."); String username = request.getParameters("username"); String password = request.getParameters("password"); if (username == null || password == null) { File file = new File("webapps/myweb/login_success.html"); response.setEntity(file); System.out.println("kdjskaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaah:"+file); return; } try ( RandomAccessFile raf = new RandomAccessFile("user.dat", "r"); ){ for (int i = 0; i < raf.length()/100; i ++) { raf.seek(i * 100); byte[] data = new byte[32]; raf.read(data); String name = new String(data, "UTF-8"); if (name.equals(username)) { raf.read(data); System.out.println("kjsaddddddddddddddddddh:" + data); String password1 = new String(data, "UTF-8"); if (password1.equals(password)) { File file = new File("webapps/myweb/login_fail.html");//成功 response.setEntity(file); return; } break;//走到这里说明用户名对了但是密码不对,停止读取工作 } } File file = new File("webapps/myweb/login_success.html");//失败 response.setEntity(file); System.out.println("suifwqigwqqwgiuqwiuifqwfuiqiu:"+file); } catch (IOException e) { e.printStackTrace(); } } }
UTF-8
Java
1,970
java
LoginServlet.java
Java
[ { "context": "\n String username = request.getParameters(\"username\");\n String password = request.getParameter", "end": 417, "score": 0.5300191640853882, "start": 409, "tag": "USERNAME", "value": "username" } ]
null
[]
package servlet; import com.webserver.http.HttpRequest; import com.webserver.http.HttpResponse; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; public class LoginServlet { public void Service(HttpRequest request, HttpResponse response) { System.out.println("开始处理登录..."); String username = request.getParameters("username"); String password = request.getParameters("password"); if (username == null || password == null) { File file = new File("webapps/myweb/login_success.html"); response.setEntity(file); System.out.println("kdjskaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaah:"+file); return; } try ( RandomAccessFile raf = new RandomAccessFile("user.dat", "r"); ){ for (int i = 0; i < raf.length()/100; i ++) { raf.seek(i * 100); byte[] data = new byte[32]; raf.read(data); String name = new String(data, "UTF-8"); if (name.equals(username)) { raf.read(data); System.out.println("kjsaddddddddddddddddddh:" + data); String password1 = new String(data, "UTF-8"); if (password1.equals(password)) { File file = new File("webapps/myweb/login_fail.html");//成功 response.setEntity(file); return; } break;//走到这里说明用户名对了但是密码不对,停止读取工作 } } File file = new File("webapps/myweb/login_success.html");//失败 response.setEntity(file); System.out.println("suifwqigwqqwgiuqwiuifqwfuiqiu:"+file); } catch (IOException e) { e.printStackTrace(); } } }
1,970
0.543592
0.536765
59
31.271187
25.498974
82
false
false
0
0
0
0
0
0
0.661017
false
false
10
62a62ebe4a99d258e0df967a890537ada81a5a26
24,455,543,785,789
30fa54909ebfe39329c4455ed68b849532f60c31
/example/GreenScreen.java
b37685755b61b28f41514f64651ad0708ce3f5a0
[ "Apache-2.0" ]
permissive
crykn/libgdx-screenmanager
https://github.com/crykn/libgdx-screenmanager
3a6427fdc0648fc883e1ceff5d5351677e7a22e9
90afbe058b720a5ed4243c2abd5caaa7809550b5
refs/heads/master
2023-08-27T04:28:10.875000
2023-07-02T20:55:59
2023-07-02T20:55:59
243,373,824
88
16
Apache-2.0
false
2023-08-16T07:22:29
2020-02-26T21:53:29
2023-08-13T14:12:54
2023-08-16T07:22:28
5,386
79
12
3
Java
false
false
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.InputAdapter; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType; import com.badlogic.gdx.utils.viewport.FitViewport; import com.badlogic.gdx.utils.viewport.Viewport; import de.eskalon.commons.screen.ManagedScreen; public class GreenScreen extends ManagedScreen { private MyGdxGame game; private ShapeRenderer shapeRenderer; private Viewport viewport; public GreenScreen() { this.game = (MyGdxGame) Gdx.app.getApplicationListener(); } @Override protected void create() { this.shapeRenderer = new ShapeRenderer(); this.addInputProcessor(new InputAdapter() { @Override public boolean touchDown(int screenX, int screenY, int pointer, int button) { /* * Switch using a blending transition. */ game.getScreenManager().pushScreen("blue", "blending_transition"); return true; } }); // This screen uses a viewport; resize the window to see the effects viewport = new FitViewport(game.getWidth(), game.getHeight()); } @Override public void render(float delta) { viewport.apply(); // you need to apply your viewport first shapeRenderer.setProjectionMatrix(viewport.getCamera().combined); /* * Render a green circle on a gray background. */ shapeRenderer.begin(ShapeType.Filled); shapeRenderer.setColor(Color.GRAY); shapeRenderer.rect(-2000, -1000, 4000, 2000); shapeRenderer.setColor(Color.GREEN); shapeRenderer.circle(1024 / 2, 720 / 2, 185); shapeRenderer.end(); } @Override public void resize(int width, int height) { viewport.update(width, height, true); } @Override public void dispose() { if (isInitialized()) shapeRenderer.dispose(); } @Override public void hide() { // not needed } }
UTF-8
Java
1,854
java
GreenScreen.java
Java
[]
null
[]
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.InputAdapter; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType; import com.badlogic.gdx.utils.viewport.FitViewport; import com.badlogic.gdx.utils.viewport.Viewport; import de.eskalon.commons.screen.ManagedScreen; public class GreenScreen extends ManagedScreen { private MyGdxGame game; private ShapeRenderer shapeRenderer; private Viewport viewport; public GreenScreen() { this.game = (MyGdxGame) Gdx.app.getApplicationListener(); } @Override protected void create() { this.shapeRenderer = new ShapeRenderer(); this.addInputProcessor(new InputAdapter() { @Override public boolean touchDown(int screenX, int screenY, int pointer, int button) { /* * Switch using a blending transition. */ game.getScreenManager().pushScreen("blue", "blending_transition"); return true; } }); // This screen uses a viewport; resize the window to see the effects viewport = new FitViewport(game.getWidth(), game.getHeight()); } @Override public void render(float delta) { viewport.apply(); // you need to apply your viewport first shapeRenderer.setProjectionMatrix(viewport.getCamera().combined); /* * Render a green circle on a gray background. */ shapeRenderer.begin(ShapeType.Filled); shapeRenderer.setColor(Color.GRAY); shapeRenderer.rect(-2000, -1000, 4000, 2000); shapeRenderer.setColor(Color.GREEN); shapeRenderer.circle(1024 / 2, 720 / 2, 185); shapeRenderer.end(); } @Override public void resize(int width, int height) { viewport.update(width, height, true); } @Override public void dispose() { if (isInitialized()) shapeRenderer.dispose(); } @Override public void hide() { // not needed } }
1,854
0.734088
0.718986
72
24.75
22.791172
80
false
false
0
0
0
0
0
0
1.847222
false
false
10
1c6628a22640aff24a5e8a97f98e634d45dd8818
1,563,368,117,044
d0e45984dceda1acf66be4e3d4fee1080c8a9e14
/blog-servlet/src/main/java/com/hyp/blog/service/ArticleService.java
c26381ad1f92ffa89710aa8243f6f08ffc7294a5
[]
no_license
hanyunpeng0521/blog
https://github.com/hanyunpeng0521/blog
0a17a644756c38c45fb49856614a097281aa2bbf
00861db8467491ae85b07ccbabd03c63351ca7e7
refs/heads/master
2020-11-23T19:11:35.244000
2020-05-13T07:15:29
2020-05-13T07:15:29
183,739,321
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hyp.blog.service; import com.hyp.blog.commons.Page; import com.hyp.blog.commons.service.BaseService; import com.hyp.blog.pojo.Article; import java.sql.SQLException; /** * @author hyp * Project name is blog * Include in com.hyp.blog.service * hyp create at 19-12-12 **/ public interface ArticleService extends BaseService<Article, Long> { Page findByUId(Long uid, int page, int size) throws SQLException; Page findByCId(Long cid, int page, int size) throws SQLException; }
UTF-8
Java
503
java
ArticleService.java
Java
[ { "context": "le;\n\nimport java.sql.SQLException;\n\n/**\n * @author hyp\n * Project name is blog\n * Include in com.hyp.blo", "end": 198, "score": 0.9996219873428345, "start": 195, "tag": "USERNAME", "value": "hyp" } ]
null
[]
package com.hyp.blog.service; import com.hyp.blog.commons.Page; import com.hyp.blog.commons.service.BaseService; import com.hyp.blog.pojo.Article; import java.sql.SQLException; /** * @author hyp * Project name is blog * Include in com.hyp.blog.service * hyp create at 19-12-12 **/ public interface ArticleService extends BaseService<Article, Long> { Page findByUId(Long uid, int page, int size) throws SQLException; Page findByCId(Long cid, int page, int size) throws SQLException; }
503
0.745527
0.733598
21
22.952381
23.68338
69
false
false
0
0
0
0
0
0
0.571429
false
false
10
069ffbbeb4c194d946b4a3ac55542d735120cf4d
9,972,914,066,036
6d94d5327f472441ba6ad4fa3bc3bb37721cce65
/src/main/java/at/technikumwien/personwebapp/DBInitializer.java
0592e4c837fbc89638ee9e130e57b727d211630d
[]
no_license
michelle-haas/fh-technikum-wien-cin
https://github.com/michelle-haas/fh-technikum-wien-cin
0559040e8a8f372f2dc32042c863a28918760b6a
ffd1a655393cd2fc0c010beca0f01d08dbd84491
refs/heads/master
2022-09-26T00:44:57.316000
2020-06-05T13:26:39
2020-06-05T13:26:39
269,640,457
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package at.technikumwien.personwebapp; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.context.event.EventListener; import java.time.LocalDate; import java.util.List; @Configuration // oder @Component, eine @Configuration ist eine Art von @Component // wenn man die Klasse nicht annotiert, wird sie nicht gefunden. @Profile("default") public class DBInitializer { @Autowired // das wird mit Dependency Injection erzeugt private PersonRepository personRepository; // ApplicationReadyEvent -> wenn die App fertig geladen ist, wird diese Methode aufgerufen @EventListener(ApplicationReadyEvent.class) public void handleApplicationEvent(){ // könnte auch foo() heißen // das personRepo wurde automatisch mittels DI erzeugt // außerdem hat es schon viel Funktionalität (vom JpaRepository) personRepository.saveAll( List.of( new Person( null, Sex.MALE, "Markus", "Mustermann", LocalDate.of(1990, 1, 1), false ), new Person( null, Sex.FEMALE, "Martina", "Musterfrau", LocalDate.of(1995, 1, 1), true ) ) ); } }
UTF-8
Java
1,807
java
DBInitializer.java
Java
[ { "context": " Sex.MALE,\n \"Markus\",\n \"Mustermann\",\n ", "end": 1266, "score": 0.9997913837432861, "start": 1260, "tag": "NAME", "value": "Markus" }, { "context": " \"Markus\",\n \"Mustermann\",\n LocalDate.of(19", "end": 1312, "score": 0.999504804611206, "start": 1302, "tag": "NAME", "value": "Mustermann" }, { "context": " Sex.FEMALE,\n \"Martina\",\n \"Musterfrau\",\n ", "end": 1596, "score": 0.999764621257782, "start": 1589, "tag": "NAME", "value": "Martina" }, { "context": " \"Martina\",\n \"Musterfrau\",\n LocalDate.of(19", "end": 1642, "score": 0.9997881650924683, "start": 1632, "tag": "NAME", "value": "Musterfrau" } ]
null
[]
package at.technikumwien.personwebapp; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.context.event.EventListener; import java.time.LocalDate; import java.util.List; @Configuration // oder @Component, eine @Configuration ist eine Art von @Component // wenn man die Klasse nicht annotiert, wird sie nicht gefunden. @Profile("default") public class DBInitializer { @Autowired // das wird mit Dependency Injection erzeugt private PersonRepository personRepository; // ApplicationReadyEvent -> wenn die App fertig geladen ist, wird diese Methode aufgerufen @EventListener(ApplicationReadyEvent.class) public void handleApplicationEvent(){ // könnte auch foo() heißen // das personRepo wurde automatisch mittels DI erzeugt // außerdem hat es schon viel Funktionalität (vom JpaRepository) personRepository.saveAll( List.of( new Person( null, Sex.MALE, "Markus", "Mustermann", LocalDate.of(1990, 1, 1), false ), new Person( null, Sex.FEMALE, "Martina", "Musterfrau", LocalDate.of(1995, 1, 1), true ) ) ); } }
1,807
0.546866
0.540211
46
38.195652
23.176655
94
false
false
0
0
0
0
0
0
0.608696
false
false
10
1a3a0a6706f51f17f868e6631f21a08e12823d1f
9,972,914,066,370
454763b39ae96c2a394c9e7f2c3c7d9dab5d4c08
/app/src/main/java/com/smiler/basketball_scoreboard/preferences/SetDefaultPreference.java
d1ce0ce8a9238e03cd62d170cc82c2e782421de5
[]
no_license
smiler25/BasketballScoreboard
https://github.com/smiler25/BasketballScoreboard
7ab8b60f8c23b075cd68c28b91cce26de81de18b
cebe0aaa4ad133e2b79ba45ba12385edb4a8366f
refs/heads/master
2020-05-21T04:51:48.911000
2018-02-08T20:36:55
2018-02-08T20:36:55
44,486,418
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.smiler.basketball_scoreboard.preferences; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.preference.DialogPreference; import android.util.AttributeSet; public class SetDefaultPreference extends DialogPreference implements DialogInterface.OnClickListener{ public SetDefaultPreference(Context context, AttributeSet attrs) { super(context, attrs); attachListener(context); } public SetDefaultPreference(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); attachListener(context); } interface SetDefaultDialogListener { void onSetPositive(); void onSetNegative(); } private SetDefaultDialogListener mListener; private void attachListener(Context activity) { try { mListener = (SetDefaultDialogListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement SetDefaultDialogListener"); } } @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case Dialog.BUTTON_POSITIVE: mListener.onSetPositive(); break; case Dialog.BUTTON_NEGATIVE: mListener.onSetNegative(); break; } } }
UTF-8
Java
1,434
java
SetDefaultPreference.java
Java
[]
null
[]
package com.smiler.basketball_scoreboard.preferences; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.preference.DialogPreference; import android.util.AttributeSet; public class SetDefaultPreference extends DialogPreference implements DialogInterface.OnClickListener{ public SetDefaultPreference(Context context, AttributeSet attrs) { super(context, attrs); attachListener(context); } public SetDefaultPreference(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); attachListener(context); } interface SetDefaultDialogListener { void onSetPositive(); void onSetNegative(); } private SetDefaultDialogListener mListener; private void attachListener(Context activity) { try { mListener = (SetDefaultDialogListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement SetDefaultDialogListener"); } } @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case Dialog.BUTTON_POSITIVE: mListener.onSetPositive(); break; case Dialog.BUTTON_NEGATIVE: mListener.onSetNegative(); break; } } }
1,434
0.677127
0.677127
46
30.173914
26.455297
107
false
false
0
0
0
0
0
0
0.565217
false
false
10
5833090d17a51c3cc8c8eb1091f575c20242c8c9
22,728,966,957,151
cae969210268c5753b5180d040c417f1332ec961
/src/hostel/serviceImpl/PlanServiceBean.java
6bbab3342bb612d344c6239cf1d70fb9f7faf72f
[]
no_license
pylSER/HostelWorld
https://github.com/pylSER/HostelWorld
0540ab2cb0b63f5f01397ed579121864616b3175
139478e082aa186d78f0c6c13e0eb834f780b3e6
refs/heads/master
2021-01-22T20:09:05.920000
2017-03-17T08:52:20
2017-03-17T08:52:20
85,290,385
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package hostel.serviceImpl; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import hostel.daoService.PlanDao; import hostel.model.PlanEntity; import hostel.service.PlanService; @Service("planservice") public class PlanServiceBean implements PlanService{ @Resource private PlanDao pdao; @Override public PlanEntity getPlanEntityById(int id) { return pdao.getPlanEntityById(id); } @Override public List<PlanEntity> getPlanEntityByInnId(int innid) { // TODO Auto-generated method stub return pdao.getPlanEntityByInnId(innid); } @Override public boolean undoPlan(int pid) { PlanEntity pEntity=pdao.getPlanEntityById(pid); if(pEntity.getAdmission()==0){ pEntity.setAdmission(-2); pdao.updatePlan(pEntity); return true; }else { return false; } } @Override public boolean addPlan(PlanEntity pe) { // TODO Auto-generated method stub return pdao.savePlan(pe); } @Override public List<PlanEntity> getUNCheckPlan() { // TODO Auto-generated method stub return pdao.getUNCheckPlan(); } @Override public boolean updatePlan(PlanEntity pe) { // TODO Auto-generated method stub return pdao.updatePlan(pe); } @Override public List<PlanEntity> getAvailablePlan(int innid) { // TODO Auto-generated method stub return pdao.getAvailablePlan(innid); } }
UTF-8
Java
1,380
java
PlanServiceBean.java
Java
[]
null
[]
package hostel.serviceImpl; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import hostel.daoService.PlanDao; import hostel.model.PlanEntity; import hostel.service.PlanService; @Service("planservice") public class PlanServiceBean implements PlanService{ @Resource private PlanDao pdao; @Override public PlanEntity getPlanEntityById(int id) { return pdao.getPlanEntityById(id); } @Override public List<PlanEntity> getPlanEntityByInnId(int innid) { // TODO Auto-generated method stub return pdao.getPlanEntityByInnId(innid); } @Override public boolean undoPlan(int pid) { PlanEntity pEntity=pdao.getPlanEntityById(pid); if(pEntity.getAdmission()==0){ pEntity.setAdmission(-2); pdao.updatePlan(pEntity); return true; }else { return false; } } @Override public boolean addPlan(PlanEntity pe) { // TODO Auto-generated method stub return pdao.savePlan(pe); } @Override public List<PlanEntity> getUNCheckPlan() { // TODO Auto-generated method stub return pdao.getUNCheckPlan(); } @Override public boolean updatePlan(PlanEntity pe) { // TODO Auto-generated method stub return pdao.updatePlan(pe); } @Override public List<PlanEntity> getAvailablePlan(int innid) { // TODO Auto-generated method stub return pdao.getAvailablePlan(innid); } }
1,380
0.744928
0.743478
70
18.714285
17.596382
58
false
false
0
0
0
0
0
0
1.342857
false
false
10
1157a34dd8f4ec22c8d2eda10c67368e6a83023b
22,728,966,955,777
6552244c7ef44150ea74cef7ec801d5a9f7171e9
/app/src/main/java/com/google/android/gms/googlehelp/internal/common/SimpleGoogleHelpCallbacks.java
e414ea81423ff9ce35b5995b63bc32b07b11460a
[]
no_license
amithbm/cbskeep
https://github.com/amithbm/cbskeep
c9469156efd307fb474d817760a0b426af8f7c5c
a800f00ab617cba49d1a1bea1f0282c0cde525e7
refs/heads/master
2016-09-06T12:42:33.824000
2015-08-24T15:33:50
2015-08-24T15:33:50
41,311,235
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.google.android.gms.googlehelp.internal.common; import com.google.android.gms.googlehelp.GoogleHelp; public class SimpleGoogleHelpCallbacks extends zze.zza { public void onGoogleHelpProcessed(GoogleHelp paramGoogleHelp) { throw new UnsupportedOperationException(); } public void onPipClick() { throw new UnsupportedOperationException(); } public void onPipInCallingAppDisabled() { throw new UnsupportedOperationException(); } public void onPipInCallingAppHidden() { throw new UnsupportedOperationException(); } public void onPipShown() { throw new UnsupportedOperationException(); } public void onTogglingPipProcessed(TogglingData paramTogglingData) { throw new UnsupportedOperationException(); } }
UTF-8
Java
776
java
SimpleGoogleHelpCallbacks.java
Java
[]
null
[]
package com.google.android.gms.googlehelp.internal.common; import com.google.android.gms.googlehelp.GoogleHelp; public class SimpleGoogleHelpCallbacks extends zze.zza { public void onGoogleHelpProcessed(GoogleHelp paramGoogleHelp) { throw new UnsupportedOperationException(); } public void onPipClick() { throw new UnsupportedOperationException(); } public void onPipInCallingAppDisabled() { throw new UnsupportedOperationException(); } public void onPipInCallingAppHidden() { throw new UnsupportedOperationException(); } public void onPipShown() { throw new UnsupportedOperationException(); } public void onTogglingPipProcessed(TogglingData paramTogglingData) { throw new UnsupportedOperationException(); } }
776
0.761598
0.761598
36
20.583334
23.383726
68
false
false
0
0
0
0
0
0
0.222222
false
false
10
ed330d59691e49fae3f36266a29aa78bf1f8b231
5,282,809,793,910
820267f7dcf8c7736f3994f29746abf0af507af5
/core/src/main/java/io/netlibs/bgp/protocol/NLRIHelper.java
bbbe31c29e8b20bd6cc3b9c95ade47789db8e4a6
[]
no_license
netlibs/io.netlibs.bgp
https://github.com/netlibs/io.netlibs.bgp
89d254360fb69fd6a366af4b8855491004075460
afbac4dcef277910ff3982e9a6b39d2221c2220e
refs/heads/master
2020-12-14T07:18:31.563000
2016-04-19T16:32:13
2016-04-19T16:32:13
44,783,938
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package io.netlibs.bgp.protocol; public class NLRIHelper { public static byte[] trimNLRI(int pfxlen, byte[] NLRI){ // we need to trim the prefix such that it is only the length that is expected int expectedOctets = NetworkLayerReachabilityInformation.calculateOctetsForPrefixLength(pfxlen); int roundedPrefixLength = (int) Math.ceil(pfxlen/8); byte[] nprefix = new byte[expectedOctets]; int offset = NLRI.length - expectedOctets; for (int i=0; i<expectedOctets; i++){ nprefix[i] = NLRI[i]; } return nprefix; } }
UTF-8
Java
559
java
NLRIHelper.java
Java
[]
null
[]
package io.netlibs.bgp.protocol; public class NLRIHelper { public static byte[] trimNLRI(int pfxlen, byte[] NLRI){ // we need to trim the prefix such that it is only the length that is expected int expectedOctets = NetworkLayerReachabilityInformation.calculateOctetsForPrefixLength(pfxlen); int roundedPrefixLength = (int) Math.ceil(pfxlen/8); byte[] nprefix = new byte[expectedOctets]; int offset = NLRI.length - expectedOctets; for (int i=0; i<expectedOctets; i++){ nprefix[i] = NLRI[i]; } return nprefix; } }
559
0.701252
0.697674
16
34
28.848743
100
false
false
0
0
0
0
0
0
0.625
false
false
10
0d2a24e4024a326ecf9155c7cb688491784b787f
17,660,905,558,783
a2d03c4fad3fec3c068d6d498f9387207e33a54e
/elevadores/src/elev/net/Logic/dosElevadores/Expresso.java
51f32ea510f39edf17cd4fb20f1d5f82193cda21
[ "Apache-2.0" ]
permissive
sofylopdev/JavaProjects
https://github.com/sofylopdev/JavaProjects
23e06aab901fa5f80d6b566d067c02b9063fac3d
8b713dc564570aa422ffdf9126145b12064205a2
refs/heads/master
2020-03-25T02:29:29.637000
2018-08-05T12:46:51
2018-08-05T12:46:51
143,292,002
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package elev.net.Logic.dosElevadores; import elev.net.Logic.AvisosOut; import elev.net.UserInterface.PainelCriarElevadores; import java.util.concurrent.CountDownLatch; /** * * @author Sofia */ public class Expresso extends Elevator { public Expresso(int max,int min,AvisosOut aout) { super("expresso",10,max,min,aout); } @Override public void addPersonToElevator() { if (getHowManyInElevator() < super.getCapacity()) { super.addPersonToElevator(); }else{ System.out.println("Este elevador nao pode levar mais do que "+super.getCapacity() +" pessoas!!!"); } } }
UTF-8
Java
829
java
Expresso.java
Java
[ { "context": "util.concurrent.CountDownLatch;\n\n/**\n *\n * @author Sofia\n */\npublic class Expresso extends Elevator {\n\n ", "end": 378, "score": 0.9214864373207092, "start": 373, "tag": "NAME", "value": "Sofia" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package elev.net.Logic.dosElevadores; import elev.net.Logic.AvisosOut; import elev.net.UserInterface.PainelCriarElevadores; import java.util.concurrent.CountDownLatch; /** * * @author Sofia */ public class Expresso extends Elevator { public Expresso(int max,int min,AvisosOut aout) { super("expresso",10,max,min,aout); } @Override public void addPersonToElevator() { if (getHowManyInElevator() < super.getCapacity()) { super.addPersonToElevator(); }else{ System.out.println("Este elevador nao pode levar mais do que "+super.getCapacity() +" pessoas!!!"); } } }
829
0.681544
0.679132
30
26.633333
27.600101
112
false
false
0
0
0
0
0
0
0.533333
false
false
10
ee0a11ab99f91d9fbbc293ecdf6b118611611214
21,500,606,299,374
54dfc385cd2b6ececd0888c3defeb9c26a147ed8
/src/main/java/com/helospark/telnetsnake/game/output/ScreenWriter.java
6d3b560920f5e30b0902dd15329d3c5944d27fc8
[ "MIT" ]
permissive
helospark/telnet-snake
https://github.com/helospark/telnet-snake
cede31df47325d386193ae044f6ea1f9d85d6898
625b10464553da46c722a8e86bcc98bb1c6d040d
refs/heads/master
2022-07-13T22:15:19.903000
2019-06-20T18:05:44
2019-06-20T18:05:44
86,938,156
4
1
MIT
false
2022-05-20T20:47:20
2017-04-01T19:41:23
2022-02-15T13:58:32
2022-05-20T20:47:19
996
2
0
2
Java
false
false
package com.helospark.telnetsnake.game.output; import com.helospark.lightdi.annotation.Component; @Component public class ScreenWriter { public void printlnToScreen(String data) { System.out.println(data); } public void printToScreen(String data) { System.out.print(data); System.out.flush(); } public void printlnToScreen(Exception e) { e.printStackTrace(); } }
UTF-8
Java
424
java
ScreenWriter.java
Java
[]
null
[]
package com.helospark.telnetsnake.game.output; import com.helospark.lightdi.annotation.Component; @Component public class ScreenWriter { public void printlnToScreen(String data) { System.out.println(data); } public void printToScreen(String data) { System.out.print(data); System.out.flush(); } public void printlnToScreen(Exception e) { e.printStackTrace(); } }
424
0.676887
0.676887
20
20.200001
18.829763
50
false
false
0
0
0
0
0
0
0.3
false
false
10
91853f3bbd799f38660c4da57ba060f709543747
22,247,930,636,447
32b305b0b6d72c7839a60b220900aa48162e9b57
/TestGit/src/com/cg/mypkg/Calculator3.java
b23188b5309ccce90255ec561ed899c96bd6d315
[]
no_license
mskrepository/gitmaster
https://github.com/mskrepository/gitmaster
724e6ba829debe08207febae94b7e2aebd51058d
84e661f52d0fc2afdcd34780e9334f7cd6e18f4c
refs/heads/master
2022-11-17T01:18:47.209000
2020-07-09T08:48:17
2020-07-09T08:48:17
272,797,546
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cg.mypkg; //package mytestproject; //import mytestproject.Calculator; public class Calculator3 { int num1; int num2; public Calculator3() { num1=10; num2=10; } public Calculator3(int n1, int n2) { num1=n1; num2=n2; } public void add() { System.out.println("num1+num2="+(num1+num2)); } public void sub() { System.out.println("num1-num2="+(num1-num2)); } public void mul() { System.out.println("num1*num2="+(num1*num2)); } public void div() { System.out.println("num1/num2="+(num1/num2)); } public static void main(String[] args) { // TODO Auto-generated method stub Calculator3 calc=new Calculator3(); System.out.println("\n"); System.out.println("num1="+calc.num1); System.out.println("num2="+calc.num2); System.out.println("\n"); System.out.println("\n"); calc.add(); calc.sub(); calc.mul(); calc.div(); System.out.println("\n"); Calculator3 calc1=new Calculator3(30,20); calc1.add(); calc1.sub(); calc1.mul(); calc1.div(); } }
UTF-8
Java
1,083
java
Calculator3.java
Java
[]
null
[]
package com.cg.mypkg; //package mytestproject; //import mytestproject.Calculator; public class Calculator3 { int num1; int num2; public Calculator3() { num1=10; num2=10; } public Calculator3(int n1, int n2) { num1=n1; num2=n2; } public void add() { System.out.println("num1+num2="+(num1+num2)); } public void sub() { System.out.println("num1-num2="+(num1-num2)); } public void mul() { System.out.println("num1*num2="+(num1*num2)); } public void div() { System.out.println("num1/num2="+(num1/num2)); } public static void main(String[] args) { // TODO Auto-generated method stub Calculator3 calc=new Calculator3(); System.out.println("\n"); System.out.println("num1="+calc.num1); System.out.println("num2="+calc.num2); System.out.println("\n"); System.out.println("\n"); calc.add(); calc.sub(); calc.mul(); calc.div(); System.out.println("\n"); Calculator3 calc1=new Calculator3(30,20); calc1.add(); calc1.sub(); calc1.mul(); calc1.div(); } }
1,083
0.603878
0.55771
78
12.884615
14.554038
47
false
false
0
0
0
0
0
0
1.692308
false
false
10
032bb5c5ce187b45ee5585f30c574bc4569cbcb9
5,944,234,770,902
fe4f8695943f7c222d25de874153af00e72647c7
/app/src/main/java/com/markx0823dev/helloworldwebview/MyMath.java
ec277040ca1a16c704b07af3331c4b112a9ed0ed
[]
no_license
MarkX0823/HelloWorldWebView
https://github.com/MarkX0823/HelloWorldWebView
c09b68d0e064f8acc00279b8a91937c34f65ada1
a281edc4db88310d941669aebf3378acfbd20f1c
refs/heads/master
2020-04-17T10:59:56.959000
2019-01-31T07:53:49
2019-01-31T07:53:49
166,522,580
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.markx0823dev.helloworldwebview; public class MyMath { public int add(int first, int second) { return first + second; } public int multiple(int first, int second) { return first * second; } }
UTF-8
Java
237
java
MyMath.java
Java
[ { "context": "package com.markx0823dev.helloworldwebview;\n\npublic class MyMath {\n ", "end": 21, "score": 0.7770906686782837, "start": 16, "tag": "USERNAME", "value": "x0823" } ]
null
[]
package com.markx0823dev.helloworldwebview; public class MyMath { public int add(int first, int second) { return first + second; } public int multiple(int first, int second) { return first * second; } }
237
0.64557
0.628692
11
20.545454
18.217691
48
false
false
0
0
0
0
0
0
0.454545
false
false
10
33a05dc40facbc5ddb7c6ad2da72437988630c22
17,360,257,852,289
b5b0750412c14b4d8a60a7a11d2c4e3e610d987c
/core/edu.utah.cdmcc.decisionsupport.application.core/src/edu/utah/cdmcc/commands/UpdatePatientHandler.java
5003c46984789b3ffc20ac7dba0a8af78744f9bf
[]
no_license
mdean77/DecisionSupportSVNExport
https://github.com/mdean77/DecisionSupportSVNExport
7c7723d3f5f40cf42f0d855a938198771cf6e60e
bd57e2171f46283606a82a350c4ded0e1b040c17
refs/heads/master
2020-05-31T05:37:07.052000
2013-03-30T16:32:43
2013-03-30T16:32:43
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.utah.cdmcc.commands; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.handlers.HandlerUtil; import edu.utah.cdmcc.decisionsupport.controller.core.ApplicationControllers; import edu.utah.cdmcc.wizards.UpdatePatientWizard; public class UpdatePatientHandler extends AbstractHandler { private IWorkbenchWindow window; public Object execute(ExecutionEvent event) throws ExecutionException { window = HandlerUtil.getActiveWorkbenchWindow(event); if (ApplicationControllers.getPatientController().getActivePatient() != null) { UpdatePatientWizard wizard = new UpdatePatientWizard(); wizard.init(window.getWorkbench(), ApplicationControllers.getPatientController().getActivePatient()); WizardDialog dialog = new WizardDialog(window.getShell(), wizard); dialog.create(); wizard.initializeFields(); dialog.open(); } else { MessageDialog.openInformation(null, "No active patient has been selected.", "Please select an active patient first."); } return null; } }
UTF-8
Java
1,259
java
UpdatePatientHandler.java
Java
[]
null
[]
package edu.utah.cdmcc.commands; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.handlers.HandlerUtil; import edu.utah.cdmcc.decisionsupport.controller.core.ApplicationControllers; import edu.utah.cdmcc.wizards.UpdatePatientWizard; public class UpdatePatientHandler extends AbstractHandler { private IWorkbenchWindow window; public Object execute(ExecutionEvent event) throws ExecutionException { window = HandlerUtil.getActiveWorkbenchWindow(event); if (ApplicationControllers.getPatientController().getActivePatient() != null) { UpdatePatientWizard wizard = new UpdatePatientWizard(); wizard.init(window.getWorkbench(), ApplicationControllers.getPatientController().getActivePatient()); WizardDialog dialog = new WizardDialog(window.getShell(), wizard); dialog.create(); wizard.initializeFields(); dialog.open(); } else { MessageDialog.openInformation(null, "No active patient has been selected.", "Please select an active patient first."); } return null; } }
1,259
0.805401
0.805401
30
40.966667
31.005896
121
false
false
0
0
0
0
0
0
1.933333
false
false
10
eff26ad0263f95d6ad227b2620e6773fc35733f9
34,016,141,002,943
c3536f9fdb5865fb32787ffbd80a94edef36abb8
/app/src/main/java/com/taller2/hypechatapp/firebase/FirebaseStorageDownloadInterface.java
8682b3e0cd7bea1b8e81eb47a4659d3d430df9e1
[]
no_license
taller-2-slk-2019/AndroidApp
https://github.com/taller-2-slk-2019/AndroidApp
66a7856296f7832e9cdf741935f40d0641a46b4e
a4818020b75560baac28bd6f57ae8bad640675a9
refs/heads/master
2020-04-29T13:25:41.911000
2019-05-30T01:17:22
2019-05-30T01:17:22
176,168,821
0
0
null
false
2019-05-30T01:17:23
2019-03-17T22:33:13
2019-05-28T21:02:44
2019-05-30T01:17:22
1,003
1
0
0
Java
false
false
package com.taller2.hypechatapp.firebase; import android.content.Context; import android.net.Uri; public interface FirebaseStorageDownloadInterface { void onFileDownloaded(Uri filePath, String contentType); void onFileDownloadError(Exception exception); Context getContext(); }
UTF-8
Java
295
java
FirebaseStorageDownloadInterface.java
Java
[]
null
[]
package com.taller2.hypechatapp.firebase; import android.content.Context; import android.net.Uri; public interface FirebaseStorageDownloadInterface { void onFileDownloaded(Uri filePath, String contentType); void onFileDownloadError(Exception exception); Context getContext(); }
295
0.79661
0.79322
13
21.692308
22.154648
60
false
false
0
0
0
0
0
0
0.538462
false
false
10
51c462ca08662b39a0aa4dd5c674ee0f78093997
5,858,335,428,896
ba9d8178ddcfa3007ed7f5c1079250533fe757db
/Program/src/main/java/basics/Programs/Fibonacci.java
867a0333ce0ef47eb175c0e7ffd156d996f63534
[]
no_license
sekharfly/comman
https://github.com/sekharfly/comman
cecbb9c2faa502cb580a1a88db737750586420a0
9a7674b03f69d3c81d2c6e7d1c201eeac546ff64
refs/heads/master
2020-04-12T15:25:41.451000
2019-02-27T09:08:02
2019-02-27T09:08:02
162,580,649
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package basics.Programs; public class Fibonacci { public static void main(String[] args) { int one = 0, two = 1, three = 1; int n = 10; System.out.println(one); for (int i = 1; i < n; i++) { one = two; System.out.println(one); two = three; three = one + two; } } }
UTF-8
Java
304
java
Fibonacci.java
Java
[]
null
[]
package basics.Programs; public class Fibonacci { public static void main(String[] args) { int one = 0, two = 1, three = 1; int n = 10; System.out.println(one); for (int i = 1; i < n; i++) { one = two; System.out.println(one); two = three; three = one + two; } } }
304
0.552632
0.532895
20
14.2
13.596323
41
false
false
0
0
0
0
0
0
1.85
false
false
10
de17eeb9aad13c7e78f583ebfc10fe0a6a6ef593
33,517,924,825,938
bbfd3058f560ee3d440a78bfc73763f34371be33
/src/main/java/com/kunyao/assistant/core/enums/BaseEnum.java
f44cde6811e290ca9b93e0fb3007086c6b082a4f
[]
no_license
xiaoniao/temp
https://github.com/xiaoniao/temp
34ff1a3670699aca679dc3ab1d9f1979c26eb15b
1bb437c2a2b2b03cbd6b74190bff9b05de57ea29
refs/heads/master
2021-04-26T22:27:52.144000
2018-03-06T15:15:52
2018-03-06T15:15:52
124,095,885
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.kunyao.assistant.core.enums; import com.kunyao.assistant.core.generic.GenericEnum; public class BaseEnum { /** * 基础状态 * @author GeNing * @since 2016.08.16 */ public enum Status implements GenericEnum { BASE_STATUS_ENABLE (1, "启用"), BASE_STATUS_DISABLED(0, "禁用"); private int value; private String text; private Status(int value, String text) { this.value = value; this.text = text; } public int getValue() { // TODO Auto-generated method stub return this.value; } public String getText() { // TODO Auto-generated method stub return this.text; } } }
UTF-8
Java
681
java
BaseEnum.java
Java
[ { "context": "c class BaseEnum {\r\n\t\r\n\t/**\r\n\t * 基础状态\r\n\t * @author GeNing\r\n\t * @since 2016.08.16\r\n\t */\r\n\tpublic enum Statu", "end": 163, "score": 0.9581794738769531, "start": 157, "tag": "USERNAME", "value": "GeNing" } ]
null
[]
package com.kunyao.assistant.core.enums; import com.kunyao.assistant.core.generic.GenericEnum; public class BaseEnum { /** * 基础状态 * @author GeNing * @since 2016.08.16 */ public enum Status implements GenericEnum { BASE_STATUS_ENABLE (1, "启用"), BASE_STATUS_DISABLED(0, "禁用"); private int value; private String text; private Status(int value, String text) { this.value = value; this.text = text; } public int getValue() { // TODO Auto-generated method stub return this.value; } public String getText() { // TODO Auto-generated method stub return this.text; } } }
681
0.621053
0.606015
35
17
15.330642
53
false
false
0
0
0
0
0
0
1.942857
false
false
10
58c53fbb47ae6f96ad5e592590664d99641d5acb
7,937,099,613,721
4b957545858abbd03d5d0e0172a568453a1923fd
/3rd Year/System Design Project/Code/src/computer/ai/Creeper.java
2fd6a31d868c24cfbe1b9009686d00ed5fa99668
[]
no_license
shofman/UniversityCoursework
https://github.com/shofman/UniversityCoursework
0abd398c6391f0a7fda53857ef3f83f049d46828
2da36e87e796c533df6a596e95f6aa5204ca9450
refs/heads/master
2021-01-16T21:21:16.493000
2013-11-28T04:23:48
2013-11-28T04:23:48
14,734,641
0
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package computer.ai; import brick.Brick; import computer.simulator.*; import java.util.Date; /** * * @author Matt Jeffryes <m.j.jeffryes@sms.ed.ac.uk> */ public class Creeper extends Shooter { private boolean firstRun = true; private Coordinates previousPosition; private Date date = new Date(0); private boolean rotated = false; private int lastRotation = 0; public Creeper (Pitch pitch, Robot self) { super(pitch, self); this.pitch = pitch; this.self = self; } @Override public void run() { updateState(); Date currentDate = new Date(); if (firstRun) { self.forward(Brick.MEDIUM); firstRun = false; rotated = false; // System.out.println("First run"); lastRotation = 0; previousPosition = self.getPosition(); } else { long timeDifference = currentDate.getTime() - date.getTime(); Line lineToBall = new Line(self.getPosition(), pitch.ball.getPosition()); Line movementLine = new Line(previousPosition, self.getPosition()); double movementAngle = LineTools.angleBetweenLines(lineToBall, movementLine); if ( rotated && (timeDifference > Math.max(Math.abs(lastRotation) * 10, 500))) { // System.out.println("Not rotating"); rotated = false; self.forward(Brick.MEDIUM); previousPosition = self.getPosition(); date = new Date(); } else if (!rotated && (timeDifference > 500)) { // System.out.println("Maybe rotating"); // System.out.println("Angle " + movementAngle); if (Math.abs(movementAngle) > Math.PI / 10) { System.out.println("Rotate"); self.rotate(movementAngle); lastRotation = (int)Math.toDegrees(movementAngle); rotated = true; } else { self.forward(Brick.MEDIUM); } previousPosition = self.getPosition(); date = new Date(); } } } }
UTF-8
Java
1,786
java
Creeper.java
Java
[ { "context": "lator.*;\nimport java.util.Date;\n\n/**\n *\n * @author Matt Jeffryes <m.j.jeffryes@sms.ed.ac.uk>\n */\npublic class Cree", "end": 126, "score": 0.999887228012085, "start": 113, "tag": "NAME", "value": "Matt Jeffryes" }, { "context": "java.util.Date;\n\n/**\n *\n * @author Matt Jeffryes <m.j.jeffryes@sms.ed.ac.uk>\n */\npublic class Creeper extends Shooter {\n\n\tpri", "end": 153, "score": 0.999931812286377, "start": 128, "tag": "EMAIL", "value": "m.j.jeffryes@sms.ed.ac.uk" } ]
null
[]
package computer.ai; import brick.Brick; import computer.simulator.*; import java.util.Date; /** * * @author <NAME> <<EMAIL>> */ public class Creeper extends Shooter { private boolean firstRun = true; private Coordinates previousPosition; private Date date = new Date(0); private boolean rotated = false; private int lastRotation = 0; public Creeper (Pitch pitch, Robot self) { super(pitch, self); this.pitch = pitch; this.self = self; } @Override public void run() { updateState(); Date currentDate = new Date(); if (firstRun) { self.forward(Brick.MEDIUM); firstRun = false; rotated = false; // System.out.println("First run"); lastRotation = 0; previousPosition = self.getPosition(); } else { long timeDifference = currentDate.getTime() - date.getTime(); Line lineToBall = new Line(self.getPosition(), pitch.ball.getPosition()); Line movementLine = new Line(previousPosition, self.getPosition()); double movementAngle = LineTools.angleBetweenLines(lineToBall, movementLine); if ( rotated && (timeDifference > Math.max(Math.abs(lastRotation) * 10, 500))) { // System.out.println("Not rotating"); rotated = false; self.forward(Brick.MEDIUM); previousPosition = self.getPosition(); date = new Date(); } else if (!rotated && (timeDifference > 500)) { // System.out.println("Maybe rotating"); // System.out.println("Angle " + movementAngle); if (Math.abs(movementAngle) > Math.PI / 10) { System.out.println("Rotate"); self.rotate(movementAngle); lastRotation = (int)Math.toDegrees(movementAngle); rotated = true; } else { self.forward(Brick.MEDIUM); } previousPosition = self.getPosition(); date = new Date(); } } } }
1,761
0.671333
0.664054
64
26.90625
20.81745
83
false
false
0
0
0
0
0
0
2.890625
false
false
10
0ff93bf4780ce6e14632d332b773439b01409b95
9,423,158,252,460
f3b01cac09668c4e06fb406f84fdeb953164031c
/Solution_04_findMedianOfTwoSortedArrays.java
0ebd2e430fa9ab0d047a3ec722cd77fcaea05447
[]
no_license
garachmaulik/LeetCode
https://github.com/garachmaulik/LeetCode
98ee2de63c2c1c06569d05d0cc8d759baf6360a7
05ed1cefce56b3c5e19924aac52cbe6114f25e76
refs/heads/master
2022-12-24T00:35:21.363000
2020-09-12T11:13:06
2020-09-12T11:13:06
294,917,753
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
class Solution_04_findMedianOfTwoSortedArrays { public double findMedianSortedArrays(int[] nums1, int[] nums2) { double median; int m = nums1.length; int n = nums2.length; int merged_array[] = new int[m+n]; int i = 0; int j = 0; int k = 0; while(i < m) { merged_array[k++] = nums1[i++]; } while(j < n) { merged_array[k++] = nums2[j++]; } Arrays.sort(merged_array); int mid = (m+n)/2; if((m+n)%2 == 0) { median = (double)(merged_array[mid-1] + merged_array[mid])/2; } else { median = merged_array[mid]; } return median; } }
UTF-8
Java
761
java
Solution_04_findMedianOfTwoSortedArrays.java
Java
[]
null
[]
class Solution_04_findMedianOfTwoSortedArrays { public double findMedianSortedArrays(int[] nums1, int[] nums2) { double median; int m = nums1.length; int n = nums2.length; int merged_array[] = new int[m+n]; int i = 0; int j = 0; int k = 0; while(i < m) { merged_array[k++] = nums1[i++]; } while(j < n) { merged_array[k++] = nums2[j++]; } Arrays.sort(merged_array); int mid = (m+n)/2; if((m+n)%2 == 0) { median = (double)(merged_array[mid-1] + merged_array[mid])/2; } else { median = merged_array[mid]; } return median; } }
761
0.44021
0.419185
31
23.548388
17.533081
73
false
false
0
0
0
0
0
0
0.483871
false
false
10
ad96d13b5d9fa1c84412520783958944c84aa031
10,574,209,490,619
ca8d6fe613c369037146902cfc5adf31f5310f77
/Java_1/src/com/bg/exceptions/Catcher.java
c904d37593f46a25986696e05dc81261a49ad320
[]
no_license
romanberla/Workspace
https://github.com/romanberla/Workspace
30817721fccc4d714ec94fa8cc34cf53258e6db3
1b27a1edc41840d693489d0ddc83842b84582605
refs/heads/master
2021-01-18T01:49:36.029000
2014-05-28T17:47:11
2014-05-28T17:47:11
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bg.exceptions; public class Catcher { }
UTF-8
Java
58
java
Catcher.java
Java
[]
null
[]
package com.bg.exceptions; public class Catcher { }
58
0.689655
0.689655
7
7.285714
10.633025
26
false
false
0
0
0
0
0
0
0.428571
false
false
10
8602c4269a03aa4d492a30e6834833a927e95228
17,927,193,500,703
8c0e2627d08fee7c25c36ff475ec19bd3701d9b5
/utilslib/src/main/java/com/ashlikun/utils/ui/ScreenInfoUtils.java
6b202bcebb80286433be9236abfb977e64d4d2e4
[]
no_license
ashLikun/CommonUtils
https://github.com/ashLikun/CommonUtils
008ff347e4e3d49faf29b8048afec0ad2ff07bc1
074df796c6c19f28019a8c5283d253e6a5c6cb4c
refs/heads/master
2023-09-04T04:53:20.685000
2019-06-12T01:26:28
2019-06-12T01:26:28
99,587,379
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ashlikun.utils.ui; import android.content.Context; import android.util.DisplayMetrics; import android.view.WindowManager; import com.ashlikun.utils.AppUtils; import com.ashlikun.utils.other.DimensUtils; /** * @author  : 李坤 * 创建时间: 2018/8/22 15:07 * 邮箱  :496546144@qq.com * <p> * 功能介绍:屏幕信息工具类 */ public class ScreenInfoUtils { private static DisplayMetrics metric; public static int getWidth() { init(); return metric.widthPixels; } private static void init() { if (metric == null) { metric = new DisplayMetrics(); WindowManager wm = (WindowManager) AppUtils.getApp().getSystemService(Context.WINDOW_SERVICE); wm.getDefaultDisplay().getMetrics(metric); } } public static int getHeight() { init(); return metric.heightPixels; } public static int width() { return widthSub(0); } /** * @param subDp 减去的dp大小 * @return */ public static int widthSubDp(int subDp) { return widthSub(DimensUtils.dip2px(subDp)); } /** * @param subPx 减去的px大小 * @return */ public static int widthSub(int subPx) { if (AppUtils.getApp() == null) { return 0; } DisplayMetrics displayMetrics = AppUtils.getApp().getResources().getDisplayMetrics(); return displayMetrics.widthPixels - subPx; } public static int height() { return heightSub(0); } /** * @param subDp 减去的dp大小 * @return */ public static int heightSubDp(int subDp) { return heightSub(DimensUtils.dip2px(subDp)); } /** * @param subPx 减去的px大小 * @return */ public static int heightSub(int subPx) { if (AppUtils.getApp() == null) { return 0; } DisplayMetrics displayMetrics = AppUtils.getApp().getResources().getDisplayMetrics(); return displayMetrics.heightPixels - subPx; } /** * 作者  : 李坤 * 创建时间: 2017/7/5 13:29 * 邮箱  :496546144@qq.com * <p> * 方法功能:获取状态栏高度 */ public static int getStatusBarHeight(Context context) { int result = 0; int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { result = context.getResources().getDimensionPixelSize(resourceId); } return result; } /** * 作者  : 李坤 * 创建时间: 2017/7/5 13:29 * 邮箱  :496546144@qq.com * <p> * 方法功能:获取导航栏高度 */ public static int getNavigationBarHeight(Context context) { int result = 0; int resourceId = context.getResources().getIdentifier("navigation_bar_height", "dimen", "android"); if (resourceId > 0) { result = context.getResources().getDimensionPixelSize(resourceId); } return result; } public static float getDensity() { init(); return metric.density; } public static DisplayMetrics getDisplayMetrics() { init(); return metric; } public static int getDensityDpi() { init(); return metric.densityDpi; } }
UTF-8
Java
3,403
java
ScreenInfoUtils.java
Java
[ { "context": "likun.utils.other.DimensUtils;\n\n/**\n * @author  : 李坤\n * 创建时间: 2018/8/22 15:07\n * 邮箱  :496546144@qq.com", "end": 238, "score": 0.9990837574005127, "start": 236, "tag": "NAME", "value": "李坤" }, { "context": " * @author  : 李坤\n * 创建时间: 2018/8/22 15:07\n * 邮箱  :496546144@qq.com\n * <p>\n * 功能介绍:屏幕信息工具类\n */\npublic class ScreenInf", "end": 288, "score": 0.9974215030670166, "start": 272, "tag": "EMAIL", "value": "496546144@qq.com" }, { "context": "heightPixels - subPx;\n }\n\n /**\n * 作者  : 李坤\n * 创建时间: 2017/7/5 13:29\n * 邮箱  :496546144", "end": 2012, "score": 0.9986774921417236, "start": 2010, "tag": "NAME", "value": "李坤" }, { "context": " 作者  : 李坤\n * 创建时间: 2017/7/5 13:29\n * 邮箱  :496546144@qq.com\n * <p>\n * 方法功能:获取状态栏高度\n */\n public", "end": 2069, "score": 0.9998327493667603, "start": 2053, "tag": "EMAIL", "value": "496546144@qq.com" }, { "context": " return result;\n }\n\n /**\n * 作者  : 李坤\n * 创建时间: 2017/7/5 13:29\n * 邮箱  :496546144", "end": 2469, "score": 0.9994283318519592, "start": 2467, "tag": "NAME", "value": "李坤" }, { "context": " 作者  : 李坤\n * 创建时间: 2017/7/5 13:29\n * 邮箱  :496546144@qq.com\n * <p>\n * 方法功能:获取导航栏高度\n */\n public", "end": 2526, "score": 0.9998760223388672, "start": 2510, "tag": "EMAIL", "value": "496546144@qq.com" } ]
null
[]
package com.ashlikun.utils.ui; import android.content.Context; import android.util.DisplayMetrics; import android.view.WindowManager; import com.ashlikun.utils.AppUtils; import com.ashlikun.utils.other.DimensUtils; /** * @author  : 李坤 * 创建时间: 2018/8/22 15:07 * 邮箱  :<EMAIL> * <p> * 功能介绍:屏幕信息工具类 */ public class ScreenInfoUtils { private static DisplayMetrics metric; public static int getWidth() { init(); return metric.widthPixels; } private static void init() { if (metric == null) { metric = new DisplayMetrics(); WindowManager wm = (WindowManager) AppUtils.getApp().getSystemService(Context.WINDOW_SERVICE); wm.getDefaultDisplay().getMetrics(metric); } } public static int getHeight() { init(); return metric.heightPixels; } public static int width() { return widthSub(0); } /** * @param subDp 减去的dp大小 * @return */ public static int widthSubDp(int subDp) { return widthSub(DimensUtils.dip2px(subDp)); } /** * @param subPx 减去的px大小 * @return */ public static int widthSub(int subPx) { if (AppUtils.getApp() == null) { return 0; } DisplayMetrics displayMetrics = AppUtils.getApp().getResources().getDisplayMetrics(); return displayMetrics.widthPixels - subPx; } public static int height() { return heightSub(0); } /** * @param subDp 减去的dp大小 * @return */ public static int heightSubDp(int subDp) { return heightSub(DimensUtils.dip2px(subDp)); } /** * @param subPx 减去的px大小 * @return */ public static int heightSub(int subPx) { if (AppUtils.getApp() == null) { return 0; } DisplayMetrics displayMetrics = AppUtils.getApp().getResources().getDisplayMetrics(); return displayMetrics.heightPixels - subPx; } /** * 作者  : 李坤 * 创建时间: 2017/7/5 13:29 * 邮箱  :<EMAIL> * <p> * 方法功能:获取状态栏高度 */ public static int getStatusBarHeight(Context context) { int result = 0; int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { result = context.getResources().getDimensionPixelSize(resourceId); } return result; } /** * 作者  : 李坤 * 创建时间: 2017/7/5 13:29 * 邮箱  :<EMAIL> * <p> * 方法功能:获取导航栏高度 */ public static int getNavigationBarHeight(Context context) { int result = 0; int resourceId = context.getResources().getIdentifier("navigation_bar_height", "dimen", "android"); if (resourceId > 0) { result = context.getResources().getDimensionPixelSize(resourceId); } return result; } public static float getDensity() { init(); return metric.density; } public static DisplayMetrics getDisplayMetrics() { init(); return metric; } public static int getDensityDpi() { init(); return metric.densityDpi; } }
3,376
0.586895
0.565679
136
22.566177
23.084469
107
false
false
0
0
0
0
0
0
0.308824
false
false
10
5a06a179a7449f44f5b88405d08921b83ff88b9a
28,312,424,421,596
255930375c99cdbbcc2a92594adb914795e42ecf
/src/Chapter_18_Recursion/Programming_Exercise_14.java
ddfe092f2a6ec2fafcacc81b82bf2880a12cae97
[]
no_license
GuanKevin/Intro-to-Java-Programming-Comprehensive-Version-10th-Edition-
https://github.com/GuanKevin/Intro-to-Java-Programming-Comprehensive-Version-10th-Edition-
0100a473d787390b44564b68abbe6564b5c51dc2
932d95e0aad9a94cc6eca3add6e4656c4170eba4
refs/heads/master
2016-06-09T12:58:06.142000
2016-04-29T23:40:59
2016-04-29T23:40:59
57,418,672
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Chapter_18_Recursion; import java.util.Scanner; /** * Find the number of uppercase letters in a string * Write a recursive method to return the number of uppercase letters in a string. * Write a test program that prompts the user to enter a string and displays the number of uppercase letters in the string. * * @author kevgu * */ public class Programming_Exercise_14 { Scanner input = new Scanner(System.in); public static void main(String[] args) { } }
UTF-8
Java
482
java
Programming_Exercise_14.java
Java
[ { "context": "of uppercase letters in the string.\n * \n * @author kevgu\n *\n */\n\npublic class Programming_Exercise_14\n{\n\tS", "end": 341, "score": 0.9994478225708008, "start": 336, "tag": "USERNAME", "value": "kevgu" } ]
null
[]
package Chapter_18_Recursion; import java.util.Scanner; /** * Find the number of uppercase letters in a string * Write a recursive method to return the number of uppercase letters in a string. * Write a test program that prompts the user to enter a string and displays the number of uppercase letters in the string. * * @author kevgu * */ public class Programming_Exercise_14 { Scanner input = new Scanner(System.in); public static void main(String[] args) { } }
482
0.73029
0.721992
20
23.1
31.788206
123
false
false
0
0
0
0
0
0
0.45
false
false
10
a3dd7b812936b7848c088f0f0f71322ca6904f7f
1,838,246,015,164
e5c9fc043092766a8ea81fdf1716e6452f89274c
/Java/chapter13/ThreadTest07answer.java
535f038df21c95401d52b27a9c89bacb820a20dd
[]
no_license
maze51/study
https://github.com/maze51/study
d48beee3cfc21372a30890e6baf3a7b0fb435721
ee7fe39b4c3f5edb1afe1241b2f4e9996e86b9b8
refs/heads/master
2020-04-16T22:32:28.908000
2019-05-02T11:56:04
2019-05-02T11:56:04
165,972,675
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package basic; import javax.swing.JOptionPane; /* 컴퓨터와 가위바위보를 진행하는 프로그램을 작성하시오. 컴퓨터의 가위바위보는 난수를 이용하여 구하고, 사용자는 showInputDialog() 메서드를 이용하여 입력받는다. 입력 시간은 5초로 제한하고 카운트다운을 진행한다. 5초안에 입력이 없으면 게임을 진 것으로 처리하고 프로그램을 종료한다. 5초안에 입력이 완료되면 승패를 구해서 그 결과를 출력한다. 결과예시) === 결 과 === 컴퓨터 : 바위 당 신 : 보 결 과 : 당신이 이겼습니다. (컴퓨터가 이겼습니다 / 비겼습니다) */ public class ThreadTest07answer { public static boolean inputCheck = false; public static void main(String[] args) { GameTimer gt = new GameTimer(); // 난수를 이용하여 컴퓨터의 가위바위보를 정한다. String[] data = {"가위", "바위", "보"}; int index = (int)(Math.random()*3); // 0 ~ 2 사이의 난수 만들기 String com = data[index]; // 사용자로부터 가위바위보 입력받기. String man = null; gt.start(); // 카운트다운 시작 do{ man = JOptionPane.showInputDialog("가위 바위 보를 입력하세요."); }while(man==null || !man.equals("가위") && !man.equals("바위") && !man.equals("보")); inputCheck = true; // 입력이 완료되었다는 표시를 한다. // 결과 판정 String result = ""; if(com.equals(man)){ result = "비겼습니다."; } else if(com.equals("가위") && man.equals("보") || com.equals("바위") && man.equals("가위") || com.equals("보") && man.equals("바위")){ result = "컴퓨터가 이겼습니다."; } else { result = "당신이 이겼습니다."; } // 결과 출력 System.out.println("=== 결 과 ==="); System.out.println("컴퓨터 : " + com); System.out.println("당 신 : " + man); System.out.println("결 과 : " + result); } } // 카운트 다운을 처리하는 쓰레드 class GameTimer extends Thread { @Override public void run() { for(int i=5 ; i>=1 ; i--){ System.out.println(i); try { Thread.sleep(1000); } catch (InterruptedException e) { } if(ThreadTest07answer.inputCheck==true){ return; } } System.out.println("시간이 초과되어 당신이 졌습니다."); System.exit(0); } }
UTF-8
Java
2,449
java
ThreadTest07answer.java
Java
[]
null
[]
package basic; import javax.swing.JOptionPane; /* 컴퓨터와 가위바위보를 진행하는 프로그램을 작성하시오. 컴퓨터의 가위바위보는 난수를 이용하여 구하고, 사용자는 showInputDialog() 메서드를 이용하여 입력받는다. 입력 시간은 5초로 제한하고 카운트다운을 진행한다. 5초안에 입력이 없으면 게임을 진 것으로 처리하고 프로그램을 종료한다. 5초안에 입력이 완료되면 승패를 구해서 그 결과를 출력한다. 결과예시) === 결 과 === 컴퓨터 : 바위 당 신 : 보 결 과 : 당신이 이겼습니다. (컴퓨터가 이겼습니다 / 비겼습니다) */ public class ThreadTest07answer { public static boolean inputCheck = false; public static void main(String[] args) { GameTimer gt = new GameTimer(); // 난수를 이용하여 컴퓨터의 가위바위보를 정한다. String[] data = {"가위", "바위", "보"}; int index = (int)(Math.random()*3); // 0 ~ 2 사이의 난수 만들기 String com = data[index]; // 사용자로부터 가위바위보 입력받기. String man = null; gt.start(); // 카운트다운 시작 do{ man = JOptionPane.showInputDialog("가위 바위 보를 입력하세요."); }while(man==null || !man.equals("가위") && !man.equals("바위") && !man.equals("보")); inputCheck = true; // 입력이 완료되었다는 표시를 한다. // 결과 판정 String result = ""; if(com.equals(man)){ result = "비겼습니다."; } else if(com.equals("가위") && man.equals("보") || com.equals("바위") && man.equals("가위") || com.equals("보") && man.equals("바위")){ result = "컴퓨터가 이겼습니다."; } else { result = "당신이 이겼습니다."; } // 결과 출력 System.out.println("=== 결 과 ==="); System.out.println("컴퓨터 : " + com); System.out.println("당 신 : " + man); System.out.println("결 과 : " + result); } } // 카운트 다운을 처리하는 쓰레드 class GameTimer extends Thread { @Override public void run() { for(int i=5 ; i>=1 ; i--){ System.out.println(i); try { Thread.sleep(1000); } catch (InterruptedException e) { } if(ThreadTest07answer.inputCheck==true){ return; } } System.out.println("시간이 초과되어 당신이 졌습니다."); System.exit(0); } }
2,449
0.580573
0.571028
85
19.682352
17.453947
82
false
false
0
0
0
0
0
0
2.094118
false
false
10
68dcc3fd94f7ddbd81089bb5098dce53f1f04bd2
23,656,679,868,725
64620f50af1bac0c1e8d7967266fb2da77276023
/jvm/src/com/Print.java
6e4d9404c93c93775f631997f7e50351670c5d12
[]
no_license
fumingliu/java
https://github.com/fumingliu/java
ef169a09c25d746cf73de77d248631c2dbfd5fe9
f396af3619ea1465a60493109e17401667fdf61e
refs/heads/master
2020-03-23T21:14:05.467000
2018-11-09T04:13:38
2018-11-09T04:13:38
142,091,758
0
0
null
false
2018-11-09T04:13:38
2018-07-24T02:08:35
2018-07-24T08:53:49
2018-11-09T04:13:38
13
0
0
0
Java
false
null
package com; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.alibaba.fastjson.JSONObject; public class Print { public static void main(String[] args) { //Print.ticket(); String t = " +86,321(+6+8+8686)()+86、/?.,0d3,217,"; t = t.replaceAll("\\+86", ""); System.out.println(t); List<Print.Man> list = new ArrayList<Print.Man>(); list.add((new Print().new Man("zhangsan","1"))); list.add((new Print().new Man("zhangsan","1"))); list.add((new Print().new Man("lisi","2"))); list.add((new Print().new Man("lisi","2"))); list.add((new Print().new Man("zhangsan","3"))); list.add((new Print().new Man("zhangsan","4"))); Set<Print.Man> set = new TreeSet<Print.Man>(new Comparator<Print.Man>() { @Override public int compare(Man o1, Man o2) { return o1.getAge().concat(o1.getName()).compareTo(o2.getAge().concat(o2.getName())); } }); set.addAll(list); list.clear(); list.addAll(set); for (Print.Man m : list){ System.out.println(m); } while(true){ System.err.println(new Random().nextInt(1000) == 888 ? "shooting" : ""); } } class Man { String name ; String age; public Man(String name ,String age){ this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } @Override public String toString() { return "Man [name=" + name + ", age=" + age + "]"; } } protected static void ticket(){ int totalNumber = 44; float price = 5; float totalPrice = 0; float discount = 1; for(int i = 1 ; i <= totalNumber ; i ++){ if(totalPrice < 150){ discount = 1f; }else if (totalPrice < 180 && totalPrice >=150){ discount = 0.8f; }else{ discount = 0.5f; } totalPrice += price * discount; } System.out.println(totalPrice); } }
UTF-8
Java
2,243
java
Print.java
Java
[]
null
[]
package com; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.alibaba.fastjson.JSONObject; public class Print { public static void main(String[] args) { //Print.ticket(); String t = " +86,321(+6+8+8686)()+86、/?.,0d3,217,"; t = t.replaceAll("\\+86", ""); System.out.println(t); List<Print.Man> list = new ArrayList<Print.Man>(); list.add((new Print().new Man("zhangsan","1"))); list.add((new Print().new Man("zhangsan","1"))); list.add((new Print().new Man("lisi","2"))); list.add((new Print().new Man("lisi","2"))); list.add((new Print().new Man("zhangsan","3"))); list.add((new Print().new Man("zhangsan","4"))); Set<Print.Man> set = new TreeSet<Print.Man>(new Comparator<Print.Man>() { @Override public int compare(Man o1, Man o2) { return o1.getAge().concat(o1.getName()).compareTo(o2.getAge().concat(o2.getName())); } }); set.addAll(list); list.clear(); list.addAll(set); for (Print.Man m : list){ System.out.println(m); } while(true){ System.err.println(new Random().nextInt(1000) == 888 ? "shooting" : ""); } } class Man { String name ; String age; public Man(String name ,String age){ this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } @Override public String toString() { return "Man [name=" + name + ", age=" + age + "]"; } } protected static void ticket(){ int totalNumber = 44; float price = 5; float totalPrice = 0; float discount = 1; for(int i = 1 ; i <= totalNumber ; i ++){ if(totalPrice < 150){ discount = 1f; }else if (totalPrice < 180 && totalPrice >=150){ discount = 0.8f; }else{ discount = 0.5f; } totalPrice += price * discount; } System.out.println(totalPrice); } }
2,243
0.624497
0.598122
100
21.370001
18.589596
88
false
false
0
0
0
0
0
0
2.36
false
false
10
0b3e4c6ec10cb111eb21db813d29c846cea26ce5
28,578,712,400,858
32b72e1dc8b6ee1be2e80bb70a03a021c83db550
/ast_results/westnordost_StreetComplete/app/src/main/java/de/westnordost/streetcomplete/about/AboutFragment.java
63a50180d8a1a58b885f957fa47b2a3d53c4a598
[]
no_license
cmFodWx5YWRhdjEyMTA5/smell-and-machine-learning
https://github.com/cmFodWx5YWRhdjEyMTA5/smell-and-machine-learning
d90c41a17e88fcd99d543124eeb6e93f9133cb4a
0564143d92f8024ff5fa6b659c2baebf827582b1
refs/heads/master
2020-07-13T13:53:40.297000
2019-01-11T11:51:18
2019-01-11T11:51:18
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// isComment package de.westnordost.streetcomplete.about; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.preference.PreferenceFragmentCompat; import de.westnordost.streetcomplete.ApplicationConstants; import de.westnordost.streetcomplete.BuildConfig; import de.westnordost.streetcomplete.FragmentContainerActivity; import de.westnordost.streetcomplete.R; public class isClassOrIsInterface extends PreferenceFragmentCompat { @Override public void isMethod(Bundle isParameter, String isParameter) { isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr); isMethod("isStringConstant").isMethod(isNameExpr.isFieldAccessExpr); isMethod("isStringConstant").isMethod(isParameter -> { Intent isVariable = new Intent(isNameExpr.isFieldAccessExpr, isNameExpr.isMethod("isStringConstant")); isMethod(isNameExpr); return true; }); isMethod("isStringConstant").isMethod(isParameter -> { isMethod().isMethod(new CreditsFragment()); return true; }); isMethod("isStringConstant").isMethod(isParameter -> { Fragment isVariable = isNameExpr.isMethod(isMethod().isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr) + isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr) + isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr) + isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr), isNameExpr.isFieldAccessExpr.isFieldAccessExpr); isMethod().isMethod(isNameExpr); return true; }); isMethod("isStringConstant").isMethod(isParameter -> { Intent isVariable = new Intent(isNameExpr.isFieldAccessExpr, isNameExpr.isMethod("isStringConstant")); isMethod(isNameExpr); return true; }); isMethod("isStringConstant").isMethod(isParameter -> { Intent isVariable = new Intent(isNameExpr.isFieldAccessExpr, isNameExpr.isMethod("isStringConstant")); isMethod(isNameExpr); return true; }); isMethod("isStringConstant").isMethod(isParameter -> { Intent isVariable = new Intent(isNameExpr.isFieldAccessExpr); isNameExpr.isMethod(isNameExpr.isMethod("isStringConstant")); isNameExpr.isMethod(isNameExpr.isFieldAccessExpr, new String[] { "isStringConstant" }); isNameExpr.isMethod(isNameExpr.isFieldAccessExpr, isNameExpr.isFieldAccessExpr + "isStringConstant"); if (isNameExpr.isMethod(isMethod().isMethod()) != null) { isMethod(isNameExpr); return true; } return true; }); } @Override public void isMethod() { super.isMethod(); isMethod().isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr); } private FragmentContainerActivity isMethod() { return (FragmentContainerActivity) isMethod(); } }
UTF-8
Java
3,035
java
AboutFragment.java
Java
[]
null
[]
// isComment package de.westnordost.streetcomplete.about; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.preference.PreferenceFragmentCompat; import de.westnordost.streetcomplete.ApplicationConstants; import de.westnordost.streetcomplete.BuildConfig; import de.westnordost.streetcomplete.FragmentContainerActivity; import de.westnordost.streetcomplete.R; public class isClassOrIsInterface extends PreferenceFragmentCompat { @Override public void isMethod(Bundle isParameter, String isParameter) { isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr); isMethod("isStringConstant").isMethod(isNameExpr.isFieldAccessExpr); isMethod("isStringConstant").isMethod(isParameter -> { Intent isVariable = new Intent(isNameExpr.isFieldAccessExpr, isNameExpr.isMethod("isStringConstant")); isMethod(isNameExpr); return true; }); isMethod("isStringConstant").isMethod(isParameter -> { isMethod().isMethod(new CreditsFragment()); return true; }); isMethod("isStringConstant").isMethod(isParameter -> { Fragment isVariable = isNameExpr.isMethod(isMethod().isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr) + isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr) + isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr) + isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr), isNameExpr.isFieldAccessExpr.isFieldAccessExpr); isMethod().isMethod(isNameExpr); return true; }); isMethod("isStringConstant").isMethod(isParameter -> { Intent isVariable = new Intent(isNameExpr.isFieldAccessExpr, isNameExpr.isMethod("isStringConstant")); isMethod(isNameExpr); return true; }); isMethod("isStringConstant").isMethod(isParameter -> { Intent isVariable = new Intent(isNameExpr.isFieldAccessExpr, isNameExpr.isMethod("isStringConstant")); isMethod(isNameExpr); return true; }); isMethod("isStringConstant").isMethod(isParameter -> { Intent isVariable = new Intent(isNameExpr.isFieldAccessExpr); isNameExpr.isMethod(isNameExpr.isMethod("isStringConstant")); isNameExpr.isMethod(isNameExpr.isFieldAccessExpr, new String[] { "isStringConstant" }); isNameExpr.isMethod(isNameExpr.isFieldAccessExpr, isNameExpr.isFieldAccessExpr + "isStringConstant"); if (isNameExpr.isMethod(isMethod().isMethod()) != null) { isMethod(isNameExpr); return true; } return true; }); } @Override public void isMethod() { super.isMethod(); isMethod().isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr); } private FragmentContainerActivity isMethod() { return (FragmentContainerActivity) isMethod(); } }
3,035
0.698188
0.697529
66
44.984848
48.471638
348
false
false
0
0
0
0
0
0
0.742424
false
false
10
c96fe12ac5c2b7b4a2c20d009e00bdb3e1cdc3e2
6,330,781,825,713
bbd7af7ba6febbe3e1d16b2dabd63b0b76455218
/JAVA/Java8/src/com/ustglobal/java8features/Test2.java
583e80bd6f70cf752e8514a977efa8483b62fd23
[]
no_license
ManeeshaVangimalla/USTGlobal-16Sep19-Maneesha1998
https://github.com/ManeeshaVangimalla/USTGlobal-16Sep19-Maneesha1998
b0df9b4f66f9f9044f78be2e9cc84bc9be68eb62
8e7a466bf919310e557a13a769f44ff3eb062807
refs/heads/master
2023-01-13T13:57:18.160000
2019-12-21T13:34:53
2019-12-21T13:34:53
215,543,059
0
0
null
false
2023-01-07T13:04:36
2019-10-16T12:29:37
2019-12-21T13:35:17
2023-01-07T13:04:35
7,115
0
0
116
Java
false
false
package com.ustglobal.java8features; import java.util.function.Predicate; public class Test2 { public static void main(String[] args) { Predicate<Student> p= s -> { if(s.percentage >=35) { return true; }else { return false; } }; Student s1=new Student(11,"maneesha",90.90); boolean value=p.test(s1); System.out.println("Rsult = "+value); } }
UTF-8
Java
393
java
Test2.java
Java
[ { "context": " false;\n\t\t\t}\n\t\t};\n\t Student s1=new Student(11,\"maneesha\",90.90);\n\t boolean value=p.test(s1);\n\t Syst", "end": 303, "score": 0.9998202323913574, "start": 295, "tag": "NAME", "value": "maneesha" } ]
null
[]
package com.ustglobal.java8features; import java.util.function.Predicate; public class Test2 { public static void main(String[] args) { Predicate<Student> p= s -> { if(s.percentage >=35) { return true; }else { return false; } }; Student s1=new Student(11,"maneesha",90.90); boolean value=p.test(s1); System.out.println("Rsult = "+value); } }
393
0.62341
0.592875
20
18.65
15.944513
49
false
false
0
0
0
0
0
0
1.9
false
false
10
d103e136a53ffd16eac7726b5f178c8c9a4aefb0
22,153,441,379,515
b28b2d10f291410622644fa6e368af4f897c125a
/foodie-service/src/main/java/com/hh/service/impl/AddressServiceImpl.java
7b20c14ad1042e303fc8d33ba41b8dd81fd86d22
[]
no_license
afstyle/foodOnline_ht
https://github.com/afstyle/foodOnline_ht
244f713b81a8dd3df2cc3042a5003dd86acb96d8
d528188b7c71896a6e17d26dbd3e8b793c0b11ea
refs/heads/main
2023-03-06T20:31:47.147000
2021-02-26T13:03:17
2021-02-26T13:03:17
327,045,738
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hh.service.impl; import com.hh.bo.AddressBO; import com.hh.enums.YesOrNo; import com.hh.mapper.UserAddressMapper; import com.hh.pojo.UserAddress; import com.hh.service.AddressService; import org.n3r.idworker.Sid; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; import java.util.Date; import java.util.List; /** * @author HuangHao * @date 2020/11/17 20:50 */ @Service public class AddressServiceImpl implements AddressService { @Autowired private UserAddressMapper userAddressMapper; @Autowired private Sid sid; @Transactional(propagation = Propagation.SUPPORTS) @Override public UserAddress queryUserAddress(String userId, String addressId) { UserAddress userAddress = new UserAddress(); userAddress.setUserId(userId); userAddress.setId(addressId); return userAddressMapper.selectOne(userAddress); } @Transactional(propagation = Propagation.SUPPORTS) @Override public List<UserAddress> queryAll(String userId) { UserAddress userAddress = new UserAddress(); userAddress.setUserId(userId); return userAddressMapper.select(userAddress); } @Transactional(propagation = Propagation.REQUIRED) @Override public void addNewUserAddress(AddressBO addressBO) { int isDefault = 0; // 是否默认地址 List<UserAddress> userAddressList = this.queryAll(addressBO.getUserId()); if (CollectionUtils.isEmpty(userAddressList)) { isDefault = 1; } String addressId = sid.nextShort(); UserAddress userAddress = new UserAddress(); BeanUtils.copyProperties(addressBO, userAddress); userAddress.setId(addressId); userAddress.setIsDefault(isDefault); userAddress.setCreatedTime(new Date()); userAddress.setUpdatedTime(new Date()); userAddressMapper.insert(userAddress); } @Transactional(propagation = Propagation.REQUIRED) @Override public void updateUserAddress(AddressBO addressBO) { String addressId = addressBO.getAddressId(); UserAddress userAddress = new UserAddress(); BeanUtils.copyProperties(addressBO, userAddress); userAddress.setId(addressId); userAddress.setUpdatedTime(new Date()); userAddressMapper.updateByPrimaryKeySelective(userAddress); } @Transactional(propagation = Propagation.REQUIRED) @Override public void deleteUserAddress(String userId, String addressId) { UserAddress userAddress = new UserAddress(); userAddress.setId(addressId); userAddress.setUserId(userId); userAddressMapper.delete(userAddress); } @Transactional(propagation = Propagation.REQUIRED) @Override public void setDefalut(String userId, String addressId) { UserAddress queryUserAddress = new UserAddress(); queryUserAddress.setUserId(userId); queryUserAddress.setIsDefault(YesOrNo.YES.type); List<UserAddress> userAddressList = userAddressMapper.select(queryUserAddress); for (UserAddress address : userAddressList) { address.setIsDefault(YesOrNo.NO.type); userAddressMapper.updateByPrimaryKeySelective(address); } UserAddress userAddressNew = new UserAddress(); userAddressNew.setId(addressId); userAddressNew.setUserId(userId); userAddressNew.setIsDefault(YesOrNo.YES.type); userAddressMapper.updateByPrimaryKeySelective(userAddressNew); } }
UTF-8
Java
3,808
java
AddressServiceImpl.java
Java
[ { "context": ".util.Date;\nimport java.util.List;\n\n/**\n * @author HuangHao\n * @date 2020/11/17 20:50\n */\n@Service\npublic cla", "end": 628, "score": 0.9998220205307007, "start": 620, "tag": "NAME", "value": "HuangHao" } ]
null
[]
package com.hh.service.impl; import com.hh.bo.AddressBO; import com.hh.enums.YesOrNo; import com.hh.mapper.UserAddressMapper; import com.hh.pojo.UserAddress; import com.hh.service.AddressService; import org.n3r.idworker.Sid; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; import java.util.Date; import java.util.List; /** * @author HuangHao * @date 2020/11/17 20:50 */ @Service public class AddressServiceImpl implements AddressService { @Autowired private UserAddressMapper userAddressMapper; @Autowired private Sid sid; @Transactional(propagation = Propagation.SUPPORTS) @Override public UserAddress queryUserAddress(String userId, String addressId) { UserAddress userAddress = new UserAddress(); userAddress.setUserId(userId); userAddress.setId(addressId); return userAddressMapper.selectOne(userAddress); } @Transactional(propagation = Propagation.SUPPORTS) @Override public List<UserAddress> queryAll(String userId) { UserAddress userAddress = new UserAddress(); userAddress.setUserId(userId); return userAddressMapper.select(userAddress); } @Transactional(propagation = Propagation.REQUIRED) @Override public void addNewUserAddress(AddressBO addressBO) { int isDefault = 0; // 是否默认地址 List<UserAddress> userAddressList = this.queryAll(addressBO.getUserId()); if (CollectionUtils.isEmpty(userAddressList)) { isDefault = 1; } String addressId = sid.nextShort(); UserAddress userAddress = new UserAddress(); BeanUtils.copyProperties(addressBO, userAddress); userAddress.setId(addressId); userAddress.setIsDefault(isDefault); userAddress.setCreatedTime(new Date()); userAddress.setUpdatedTime(new Date()); userAddressMapper.insert(userAddress); } @Transactional(propagation = Propagation.REQUIRED) @Override public void updateUserAddress(AddressBO addressBO) { String addressId = addressBO.getAddressId(); UserAddress userAddress = new UserAddress(); BeanUtils.copyProperties(addressBO, userAddress); userAddress.setId(addressId); userAddress.setUpdatedTime(new Date()); userAddressMapper.updateByPrimaryKeySelective(userAddress); } @Transactional(propagation = Propagation.REQUIRED) @Override public void deleteUserAddress(String userId, String addressId) { UserAddress userAddress = new UserAddress(); userAddress.setId(addressId); userAddress.setUserId(userId); userAddressMapper.delete(userAddress); } @Transactional(propagation = Propagation.REQUIRED) @Override public void setDefalut(String userId, String addressId) { UserAddress queryUserAddress = new UserAddress(); queryUserAddress.setUserId(userId); queryUserAddress.setIsDefault(YesOrNo.YES.type); List<UserAddress> userAddressList = userAddressMapper.select(queryUserAddress); for (UserAddress address : userAddressList) { address.setIsDefault(YesOrNo.NO.type); userAddressMapper.updateByPrimaryKeySelective(address); } UserAddress userAddressNew = new UserAddress(); userAddressNew.setId(addressId); userAddressNew.setUserId(userId); userAddressNew.setIsDefault(YesOrNo.YES.type); userAddressMapper.updateByPrimaryKeySelective(userAddressNew); } }
3,808
0.720495
0.716544
121
30.371901
24.512142
87
false
false
0
0
0
0
0
0
0.504132
false
false
10
a637ff19e55db473ea15ec1b41e6ac50634419a5
5,789,615,919,391
b17775b3007a8431b7ae6ef287d1bac0ee13c566
/src/nl/thewgbbroz/butils_v2/playerattributes/attributes/IntegerAttribute.java
607aa7913c4294c122eae0c4e826adac339f0bd1
[]
no_license
WouterGritter/bUtils_v2
https://github.com/WouterGritter/bUtils_v2
cdfdce069c71865f4b0bdc87e98640cef5309d28
424c6c655258fe6b95876c0bd1d3993c0cca4e24
refs/heads/master
2020-08-13T02:57:22.936000
2020-05-23T18:26:56
2020-05-23T18:26:56
214,893,848
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package nl.thewgbbroz.butils_v2.playerattributes.attributes; import org.bukkit.configuration.ConfigurationSection; import nl.thewgbbroz.butils_v2.playerattributes.PlayerAttributes; public abstract class IntegerAttribute extends PlayerAttribute { protected int value; public IntegerAttribute(PlayerAttributes parent) { super(parent); } public int get() { return value; } public void set(int value) { if(this.value != value) { this.value = value; save(); } } public void add(int add) { set(get() + add); } public void remove(int remove) { set(get() - remove); } @Override public void serialize(ConfigurationSection config) { config.set("v", value); } @Override public void deserialize(ConfigurationSection config) { this.value = config.getInt("v"); } @Override public String toString() { return getClass().getSimpleName() + "[" + value + "]"; } }
UTF-8
Java
908
java
IntegerAttribute.java
Java
[]
null
[]
package nl.thewgbbroz.butils_v2.playerattributes.attributes; import org.bukkit.configuration.ConfigurationSection; import nl.thewgbbroz.butils_v2.playerattributes.PlayerAttributes; public abstract class IntegerAttribute extends PlayerAttribute { protected int value; public IntegerAttribute(PlayerAttributes parent) { super(parent); } public int get() { return value; } public void set(int value) { if(this.value != value) { this.value = value; save(); } } public void add(int add) { set(get() + add); } public void remove(int remove) { set(get() - remove); } @Override public void serialize(ConfigurationSection config) { config.set("v", value); } @Override public void deserialize(ConfigurationSection config) { this.value = config.getInt("v"); } @Override public String toString() { return getClass().getSimpleName() + "[" + value + "]"; } }
908
0.700441
0.698238
47
18.319149
20.36278
65
false
false
0
0
0
0
0
0
1.404255
false
false
10
37a3b71d4dde42e574b7cfcebc072b65ab244c05
17,111,149,708,274
3201a6a05149aae1fef74917c7b25ffe8e0e2e7d
/tlink/tlink-server/src/main/java/com/esum/hotdeploy/ApplicationContainerUtils.java
10ef368a8b7ca4bbf929cd7382ffc2474c3358c0
[]
no_license
trustlab-repo/T-LiNK
https://github.com/trustlab-repo/T-LiNK
321abdccbec77a672b154443489ce1af7f764eab
a03c9948325e7b25feb80083e4c945db28ebd7ef
refs/heads/master
2018-02-07T19:57:46.861000
2017-08-07T06:27:16
2017-08-07T06:27:16
96,088,303
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.esum.hotdeploy; import java.io.File; import java.net.URL; import com.esum.framework.common.util.ZipUtil; public class ApplicationContainerUtils { private static final int DEFAULT_DEPLOYER_MONITOR_INTERVAL_MS = 5000; private static final int DEFAULT_APPLICATION_MONITOR_INTERVAL_MS = 3000; public static File getXtrusHome() { String home = System.getProperty("xtrus.home", null); if(home!=null) return new File(home); return null; } public static File getAppsDir() { return new File(getXtrusHome(), "apps"); } public static File getHodeployTempDir() { return new File(getXtrusHome(), "deploy/temp"); } public static File getHodeployWorkDir() { return new File(getXtrusHome(), "deploy/works"); } public static int getAppConfigChangeMonitorInterval() { return DEFAULT_APPLICATION_MONITOR_INTERVAL_MS; } public static int getDeployerMonitorInterval() { return DEFAULT_DEPLOYER_MONITOR_INTERVAL_MS; } public static String getAnchorFileMessage() { return "anchor"; } public static void backup(String appName) { try { File appDir = new File(getAppsDir(), appName); File errorArchive = new File(appDir + ".zip.ERR"); ZipUtil.zip(errorArchive, appDir); } catch (Exception ex) { } } public static void backup(URL url, File appDir) { try { File archive = new File(url.toURI() + ".ERR"); ZipUtil.zip(archive, appDir); } catch (Exception e) { } } }
UTF-8
Java
1,444
java
ApplicationContainerUtils.java
Java
[]
null
[]
package com.esum.hotdeploy; import java.io.File; import java.net.URL; import com.esum.framework.common.util.ZipUtil; public class ApplicationContainerUtils { private static final int DEFAULT_DEPLOYER_MONITOR_INTERVAL_MS = 5000; private static final int DEFAULT_APPLICATION_MONITOR_INTERVAL_MS = 3000; public static File getXtrusHome() { String home = System.getProperty("xtrus.home", null); if(home!=null) return new File(home); return null; } public static File getAppsDir() { return new File(getXtrusHome(), "apps"); } public static File getHodeployTempDir() { return new File(getXtrusHome(), "deploy/temp"); } public static File getHodeployWorkDir() { return new File(getXtrusHome(), "deploy/works"); } public static int getAppConfigChangeMonitorInterval() { return DEFAULT_APPLICATION_MONITOR_INTERVAL_MS; } public static int getDeployerMonitorInterval() { return DEFAULT_DEPLOYER_MONITOR_INTERVAL_MS; } public static String getAnchorFileMessage() { return "anchor"; } public static void backup(String appName) { try { File appDir = new File(getAppsDir(), appName); File errorArchive = new File(appDir + ".zip.ERR"); ZipUtil.zip(errorArchive, appDir); } catch (Exception ex) { } } public static void backup(URL url, File appDir) { try { File archive = new File(url.toURI() + ".ERR"); ZipUtil.zip(archive, appDir); } catch (Exception e) { } } }
1,444
0.708449
0.702909
62
22.290323
22.112898
73
false
false
0
0
0
0
0
0
1.629032
false
false
10
4d7937a0d202196267bc580f30cc052ded884d12
652,835,093,629
23046a5e56dfd6884d640334b360fd56cee79659
/Multiplayer/src/org/academiadecodigo/bootcamp/multiplayer/Game.java
823f688e26c4d982bf60e6ce8cdb91dca8241cc5
[]
no_license
Fiono11/hello-world
https://github.com/Fiono11/hello-world
328a8a93e937ded8de2ca369b946c0622340f0c6
5219ed75495dcc27614736ce60f37054de803555
refs/heads/master
2020-12-30T13:59:58.743000
2017-06-23T09:41:45
2017-06-23T09:41:45
91,270,148
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.academiadecodigo.bootcamp.multiplayer; /** * Created by codecadet on 20/06/17. */ public class Game implements Runnable { private Cat cat; private Mouse mouse; private Grid grid; public Game() { grid = new Grid(24,24); cat = new Cat(); mouse = new Mouse(); try { start(); } catch (InterruptedException e) { e.printStackTrace(); } } public void start() throws InterruptedException{ while (true) { Thread.sleep(500); cat.move(); mouse.move(); } } @Override public void run() { try { start(); } catch (InterruptedException e) { e.printStackTrace(); } } }
UTF-8
Java
783
java
Game.java
Java
[ { "context": "adecodigo.bootcamp.multiplayer;\n\n/**\n * Created by codecadet on 20/06/17.\n */\npublic class Game implements Run", "end": 79, "score": 0.9996368885040283, "start": 70, "tag": "USERNAME", "value": "codecadet" } ]
null
[]
package org.academiadecodigo.bootcamp.multiplayer; /** * Created by codecadet on 20/06/17. */ public class Game implements Runnable { private Cat cat; private Mouse mouse; private Grid grid; public Game() { grid = new Grid(24,24); cat = new Cat(); mouse = new Mouse(); try { start(); } catch (InterruptedException e) { e.printStackTrace(); } } public void start() throws InterruptedException{ while (true) { Thread.sleep(500); cat.move(); mouse.move(); } } @Override public void run() { try { start(); } catch (InterruptedException e) { e.printStackTrace(); } } }
783
0.507024
0.490421
39
19.076923
14.550327
52
false
false
0
0
0
0
0
0
0.384615
false
false
10
e8711413fa0cb76d87cb4ab87ea49633e39e91e4
17,540,646,449,022
dc2c1bb98b023b4cc6a2a56e9bdaf93c652d1482
/eframe-sb/src/main/java/com/module/employee/entity/ViewUserInfo.java
88e3d87774f1132a52c04824d017ff1e9ead2324
[]
no_license
emmerichLuang/eframe
https://github.com/emmerichLuang/eframe
d8691c440c6381d4aa9acd4839d302a8ed6d584e
bc8ef03a72fadde61a8bbf8c54e742d10f4da995
refs/heads/master
2022-09-27T01:21:19.964000
2019-07-24T10:16:13
2019-07-24T10:16:13
20,056,648
0
0
null
false
2022-09-01T22:44:13
2014-05-22T10:10:42
2019-07-24T10:16:26
2022-09-01T22:44:10
227
0
0
17
Java
false
false
package com.module.employee.entity; import java.io.Serializable; import java.util.Date; import com.base.entity.BaseEntity; import javax.persistence.Column; import javax.persistence.Id; import javax.persistence.Table; import org.springframework.stereotype.Component; /** * * @author liangrl * @date 2019-04-16 * */ @Component @Table(name = "view_user_info") public class ViewUserInfo extends BaseEntity implements Serializable { private static final long serialVersionUID = 1L; @Id @Column(name = "id") private String id; @Column(name = "user_name") private String userName; @Column(name = "state") private Integer state; @Column(name = "mobile") private String mobile; @Column(name = "email") private String email; @Column(name = "is_mobile_check") private Integer isMobileCheck; @Column(name = "is_email_check") private Integer isEmailCheck; @Column(name = "nick_name") private String nickName; @Column(name = "create_time") private Date createTime; /************ getter and setter **************/ public String getId() { return this.id; } public void setId(String id) { this.id = id; } public String getUserName() { return this.userName; } public void setUserName(String userName) { this.userName = userName; } public Integer getState() { return this.state; } public void setState(Integer state) { this.state = state; } public String getMobile() { return this.mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getEmail() { return this.email; } public void setEmail(String email) { this.email = email; } public Integer getIsMobileCheck() { return this.isMobileCheck; } public void setIsMobileCheck(Integer isMobileCheck) { this.isMobileCheck = isMobileCheck; } public Integer getIsEmailCheck() { return this.isEmailCheck; } public void setIsEmailCheck(Integer isEmailCheck) { this.isEmailCheck = isEmailCheck; } public String getNickName() { return this.nickName; } public void setNickName(String nickName) { this.nickName = nickName; } public Date getCreateTime() { return this.createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } }
UTF-8
Java
2,241
java
ViewUserInfo.java
Java
[ { "context": "ramework.stereotype.Component;\n\n/**\n * \n * @author liangrl\n * @date 2019-04-16\n *\n */\n@Component\n@Table(name", "end": 295, "score": 0.9996903538703918, "start": 288, "tag": "USERNAME", "value": "liangrl" } ]
null
[]
package com.module.employee.entity; import java.io.Serializable; import java.util.Date; import com.base.entity.BaseEntity; import javax.persistence.Column; import javax.persistence.Id; import javax.persistence.Table; import org.springframework.stereotype.Component; /** * * @author liangrl * @date 2019-04-16 * */ @Component @Table(name = "view_user_info") public class ViewUserInfo extends BaseEntity implements Serializable { private static final long serialVersionUID = 1L; @Id @Column(name = "id") private String id; @Column(name = "user_name") private String userName; @Column(name = "state") private Integer state; @Column(name = "mobile") private String mobile; @Column(name = "email") private String email; @Column(name = "is_mobile_check") private Integer isMobileCheck; @Column(name = "is_email_check") private Integer isEmailCheck; @Column(name = "nick_name") private String nickName; @Column(name = "create_time") private Date createTime; /************ getter and setter **************/ public String getId() { return this.id; } public void setId(String id) { this.id = id; } public String getUserName() { return this.userName; } public void setUserName(String userName) { this.userName = userName; } public Integer getState() { return this.state; } public void setState(Integer state) { this.state = state; } public String getMobile() { return this.mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getEmail() { return this.email; } public void setEmail(String email) { this.email = email; } public Integer getIsMobileCheck() { return this.isMobileCheck; } public void setIsMobileCheck(Integer isMobileCheck) { this.isMobileCheck = isMobileCheck; } public Integer getIsEmailCheck() { return this.isEmailCheck; } public void setIsEmailCheck(Integer isEmailCheck) { this.isEmailCheck = isEmailCheck; } public String getNickName() { return this.nickName; } public void setNickName(String nickName) { this.nickName = nickName; } public Date getCreateTime() { return this.createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } }
2,241
0.709951
0.705935
126
16.793652
16.265318
70
false
false
0
0
0
0
0
0
1.02381
false
false
10
370bbf4a2e90d0341dfa000852f1adbe921a423a
11,519,102,344,109
97e3f73ab62a7862f8e95fd89fc0ddca40a2d0a2
/app/src/main/java/com/phicomm/smartplug/modules/device/devicedetails/PowerStaticsContract.java
5de7e4012905a23b4085616236e23622330ad2c5
[]
no_license
telemansoft/SmatPlug
https://github.com/telemansoft/SmatPlug
b9b768d8c9dbfdb181ba90ce30832901e664ec00
a1bbdcc32a3833d6348b0fdcd6f011b6443c8914
refs/heads/master
2020-09-18T18:55:55.275000
2017-09-04T03:19:11
2017-09-04T03:19:11
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.phicomm.smartplug.modules.device.devicedetails; import com.phicomm.smartplug.base.BasePresenter; import com.phicomm.smartplug.base.BaseResponseBean; import com.phicomm.smartplug.base.BaseView; /** * Created by feilong.yang on 2017/7/13. */ public interface PowerStaticsContract { interface View extends BaseView { //解析月电量http response void analysisDayElectResponseBean(BaseResponseBean t); //解析年电量http response void analysisMonthElectResponseBean(BaseResponseBean t); } interface TotalElectView extends BaseView { //解析总电量http response void analysisTotalElectResponseBean(BaseResponseBean t); } interface Presenter extends BasePresenter { //control device void dayElect(String access_token, String deviceId, String day_end_hour, String day_start_hour, String end_day, String start_day); void monthElect(String access_token, String deviceId, String day_end_hour, String day_start_hour, String end_year_month, String start_year_month); void totalElect(String access_token, String deviceId); } }
UTF-8
Java
1,241
java
PowerStaticsContract.java
Java
[ { "context": "hicomm.smartplug.base.BaseView;\n\n/**\n * Created by feilong.yang on 2017/7/13.\n */\n\npublic interface PowerStaticsC", "end": 237, "score": 0.9986822009086609, "start": 225, "tag": "USERNAME", "value": "feilong.yang" } ]
null
[]
package com.phicomm.smartplug.modules.device.devicedetails; import com.phicomm.smartplug.base.BasePresenter; import com.phicomm.smartplug.base.BaseResponseBean; import com.phicomm.smartplug.base.BaseView; /** * Created by feilong.yang on 2017/7/13. */ public interface PowerStaticsContract { interface View extends BaseView { //解析月电量http response void analysisDayElectResponseBean(BaseResponseBean t); //解析年电量http response void analysisMonthElectResponseBean(BaseResponseBean t); } interface TotalElectView extends BaseView { //解析总电量http response void analysisTotalElectResponseBean(BaseResponseBean t); } interface Presenter extends BasePresenter { //control device void dayElect(String access_token, String deviceId, String day_end_hour, String day_start_hour, String end_day, String start_day); void monthElect(String access_token, String deviceId, String day_end_hour, String day_start_hour, String end_year_month, String start_year_month); void totalElect(String access_token, String deviceId); } }
1,241
0.680429
0.674649
38
30.868422
26.814342
82
false
false
0
0
0
0
0
0
0.552632
false
false
10
69309615ace9541bc644282859a95da6bdc511da
11,519,102,344,986
1132acaf8ca039b13a09276d5804d0b8a4bf57b6
/src/br/com/harpia/entities/Cidade.java
61cb3d77e15a04d5e2776fbc7c827054cc53f1ed
[]
no_license
ricgavira/desenvolvimento
https://github.com/ricgavira/desenvolvimento
aeb3f51bbbac06d522d8b4543abeda52a55cf4a4
a7384282627ed0b22cbf844b264a41c9b373113b
refs/heads/master
2018-01-07T08:07:56.913000
2015-07-03T07:41:45
2015-07-03T07:41:45
32,536,592
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.harpia.entities; import java.util.List; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.SequenceGenerator; @Entity public class Cidade { @Id @SequenceGenerator(name = "GEN_CIDADE", sequenceName = "GEN_CIDADE_ID") @GeneratedValue(generator = "GEN_CIDADE", strategy = GenerationType.AUTO) private Integer cdcidade; @OneToMany(mappedBy = "cidade") private List<Bairro> bairros; @ManyToOne(optional = false) @JoinColumn(name = "cdestado") private Estado estado; private String nmcidade; public Integer getCdcidade() { return this.cdcidade; } public void setCdcidade(Integer cdcidade) { this.cdcidade = cdcidade; } public List<Bairro> getBairros() { return this.bairros; } public void setBairros(List<Bairro> bairros) { this.bairros = bairros; } public Estado getEstado() { return this.estado; } public void setEstado(Estado estado) { this.estado = estado; } public String getNmcidade() { return this.nmcidade; } public void setNmcidade(String nmcidade) { this.nmcidade = nmcidade; } }
UTF-8
Java
1,343
java
Cidade.java
Java
[]
null
[]
package br.com.harpia.entities; import java.util.List; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.SequenceGenerator; @Entity public class Cidade { @Id @SequenceGenerator(name = "GEN_CIDADE", sequenceName = "GEN_CIDADE_ID") @GeneratedValue(generator = "GEN_CIDADE", strategy = GenerationType.AUTO) private Integer cdcidade; @OneToMany(mappedBy = "cidade") private List<Bairro> bairros; @ManyToOne(optional = false) @JoinColumn(name = "cdestado") private Estado estado; private String nmcidade; public Integer getCdcidade() { return this.cdcidade; } public void setCdcidade(Integer cdcidade) { this.cdcidade = cdcidade; } public List<Bairro> getBairros() { return this.bairros; } public void setBairros(List<Bairro> bairros) { this.bairros = bairros; } public Estado getEstado() { return this.estado; } public void setEstado(Estado estado) { this.estado = estado; } public String getNmcidade() { return this.nmcidade; } public void setNmcidade(String nmcidade) { this.nmcidade = nmcidade; } }
1,343
0.719285
0.719285
62
19.693548
18.288538
74
false
false
0
0
0
0
0
0
1.064516
false
false
10
2664369a3af961e355a41b7264815576992d007f
33,303,176,461,881
01130d0f1585fcd07def2ad71a97f8ef517141af
/member-data/src/com/wanda/ccs/model/TCampaign.java
155b55f9ed46c27a15a0630bd8184b53e948fbcb
[]
no_license
xiongshaogang/member
https://github.com/xiongshaogang/member
31534ec17ab4b2dbe6d4894c9d56e8860585ab77
6d99204f1b8449582e5f6c582fd681fb8906d4ca
refs/heads/master
2021-01-22T06:02:11.076000
2016-12-01T02:50:47
2016-12-01T02:50:47
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.wanda.ccs.model; // Generated 2013-5-21 18:55:28 by Hibernate Tools 3.4.0.CR1 import static javax.persistence.GenerationType.SEQUENCE; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.OrderBy; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.persistence.Transient; import com.xcesys.extras.core.dao.model.BlameableEntity; import com.xcesys.extras.core.util.StringUtil; /** * TCampaign generated by hbm2java * 活动 */ @Entity @Table(name = "T_CAMPAIGN") public class TCampaign extends BlameableEntity implements java.io.Serializable { private static final long serialVersionUID = -7682546835058562310L; private Long id; private String code;//编码 private String name;//名称 private Date startDate;//开始日期 private Date endDate;//结束日期 private String status;//活动状态-DIM1001 private String type;//活动类型-DIM1004 private String channel;//活动渠道-DIM1003 private String description;//描述 private Long creationCinemaId;//创建方-影城ID private TCinema tCinema; private String creationAreaId;//创建方-区域ID private boolean allCinema;//包含所有影城 private String creationLevel;//创建方级别-DIM1013 private String allowModifier;//授权修改人(用户名) private String settlementType;// 结算方式 10院线 20影城 private Set<TCmnPhase> tCmnPhases = new HashSet<TCmnPhase>(0); private Set<TCmnActivity> tCmnActivities = new HashSet<TCmnActivity>(0); private Set<TCampaignCinema> tCampaignCinemas = new HashSet<TCampaignCinema>( 0); private String strStartDate; private String strEndDate; private String cinemas; private String phaseAndActivitys; public TCampaign() { } @SequenceGenerator(name = "generator", sequenceName = "S_T_CAMPAIGN", allocationSize = 1) @Id @GeneratedValue(strategy = SEQUENCE, generator = "generator") @Column(name = "CAMPAIGN_ID", unique = true, nullable = false, precision = 22, scale = 0) public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } @Column(name = "CODE", nullable = false, length = 30) public String getCode() { return this.code; } public void setCode(String code) { this.code = code; } @Column(name = "NAME", nullable = false, length = 256) public String getName() { return this.name; } public void setName(String name) { this.name = name; } @Column(name = "START_DATE") public Date getStartDate() { return this.startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } @Column(name = "END_DATE") public Date getEndDate() { return this.endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } @Column(name = "STATUS", nullable = false, length = 20) public String getStatus() { return this.status; } public void setStatus(String status) { this.status = status; } @Column(name = "TYPE", nullable = false, length = 20) public String getType() { return this.type; } public void setType(String type) { this.type = type; } @Column(name = "CHANNEL", nullable = false, length = 20) public String getChannel() { return this.channel; } public void setChannel(String channel) { this.channel = channel; } @Column(name = "DESCRIPTION", length = 4000) public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } @Column(name = "CREATION_CINEMA_ID", precision = 22, scale = 0) public Long getCreationCinemaId() { return this.creationCinemaId; } public void setCreationCinemaId(Long creationCinemaId) { this.creationCinemaId = creationCinemaId; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "CREATION_CINEMA_ID", updatable = false, insertable = false) public TCinema gettCinema() { return tCinema; } public void settCinema(TCinema tCinema) { this.tCinema = tCinema; } @Column(name = "CREATION_AREA_ID", nullable = false, length = 20) public String getCreationAreaId() { return this.creationAreaId; } public void setCreationAreaId(String creationAreaId) { this.creationAreaId = creationAreaId; } @Column(name = "ALL_CINEMA", nullable = false, length = 1) public boolean getAllCinema() { return this.allCinema; } public void setAllCinema(boolean allCinema) { this.allCinema = allCinema; } @Column(name = "CREATION_LEVEL", length = 20) public String getCreationLevel() { return this.creationLevel; } public void setCreationLevel(String creationLevel) { this.creationLevel = creationLevel; } @Column(name = "ALLOW_MODIFIER", length = 40) public String getAllowModifier() { return this.allowModifier; } public void setAllowModifier(String allowModifier) { this.allowModifier = allowModifier; } @Column(name = "SETTLEMENT_TYPE") public String getSettlementType() { return settlementType; } public void setSettlementType(String settlementType) { this.settlementType = settlementType; } @OneToMany(fetch = FetchType.LAZY, mappedBy = "tCampaign") @OrderBy(value="startDate,name asc") public Set<TCmnPhase> gettCmnPhases() { return this.tCmnPhases; } public void settCmnPhases(Set<TCmnPhase> tCmnPhases) { this.tCmnPhases = tCmnPhases; } @OneToMany(fetch = FetchType.LAZY, mappedBy = "tCampaign") public Set<TCmnActivity> gettCmnActivities() { return this.tCmnActivities; } public void settCmnActivities(Set<TCmnActivity> tCmnActivities) { this.tCmnActivities = tCmnActivities; } @OneToMany(fetch = FetchType.LAZY, mappedBy = "tCampaign", cascade = CascadeType.ALL, orphanRemoval = true) public Set<TCampaignCinema> gettCampaignCinemas() { return this.tCampaignCinemas; } public void settCampaignCinemas(Set<TCampaignCinema> tCampaignCinemas) { this.tCampaignCinemas = tCampaignCinemas; } @Transient public String getStrStartDate() { if(startDate != null) strStartDate = new SimpleDateFormat("yyyy-MM-dd").format(startDate); return strStartDate; } public void setStrStartDate(String strStartDate) { try { if(!StringUtil.isNullOrBlank(strStartDate)) startDate = new SimpleDateFormat("yyyy-MM-dd").parse(strStartDate); else startDate = null; } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } this.strStartDate = strStartDate; } @Transient public String getStrEndDate() { if(endDate != null) strEndDate = new SimpleDateFormat("yyyy-MM-dd").format(endDate); return strEndDate; } public void setStrEndDate(String strEndDate) { try { if(!StringUtil.isNullOrBlank(strEndDate)) endDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(strEndDate+" 23:59:59"); else endDate = null; } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } this.strEndDate = strEndDate; } @Transient public String getCinemas() { return cinemas; } public void setCinemas(String cinemas) { this.cinemas = cinemas; } @Transient public String getPhaseAndActivitys() { return phaseAndActivitys; } public void setPhaseAndActivitys(String phaseAndActivitys) { this.phaseAndActivitys = phaseAndActivitys; } }
UTF-8
Java
7,954
java
TCampaign.java
Java
[ { "context": "级别-DIM1013\r\n\tprivate String allowModifier;//授权修改人(用户名)\r\n\tprivate String settlementType;// 结算方式 10院线 20影", "end": 1659, "score": 0.9719567894935608, "start": 1656, "tag": "USERNAME", "value": "用户名" } ]
null
[]
package com.wanda.ccs.model; // Generated 2013-5-21 18:55:28 by Hibernate Tools 3.4.0.CR1 import static javax.persistence.GenerationType.SEQUENCE; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.OrderBy; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.persistence.Transient; import com.xcesys.extras.core.dao.model.BlameableEntity; import com.xcesys.extras.core.util.StringUtil; /** * TCampaign generated by hbm2java * 活动 */ @Entity @Table(name = "T_CAMPAIGN") public class TCampaign extends BlameableEntity implements java.io.Serializable { private static final long serialVersionUID = -7682546835058562310L; private Long id; private String code;//编码 private String name;//名称 private Date startDate;//开始日期 private Date endDate;//结束日期 private String status;//活动状态-DIM1001 private String type;//活动类型-DIM1004 private String channel;//活动渠道-DIM1003 private String description;//描述 private Long creationCinemaId;//创建方-影城ID private TCinema tCinema; private String creationAreaId;//创建方-区域ID private boolean allCinema;//包含所有影城 private String creationLevel;//创建方级别-DIM1013 private String allowModifier;//授权修改人(用户名) private String settlementType;// 结算方式 10院线 20影城 private Set<TCmnPhase> tCmnPhases = new HashSet<TCmnPhase>(0); private Set<TCmnActivity> tCmnActivities = new HashSet<TCmnActivity>(0); private Set<TCampaignCinema> tCampaignCinemas = new HashSet<TCampaignCinema>( 0); private String strStartDate; private String strEndDate; private String cinemas; private String phaseAndActivitys; public TCampaign() { } @SequenceGenerator(name = "generator", sequenceName = "S_T_CAMPAIGN", allocationSize = 1) @Id @GeneratedValue(strategy = SEQUENCE, generator = "generator") @Column(name = "CAMPAIGN_ID", unique = true, nullable = false, precision = 22, scale = 0) public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } @Column(name = "CODE", nullable = false, length = 30) public String getCode() { return this.code; } public void setCode(String code) { this.code = code; } @Column(name = "NAME", nullable = false, length = 256) public String getName() { return this.name; } public void setName(String name) { this.name = name; } @Column(name = "START_DATE") public Date getStartDate() { return this.startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } @Column(name = "END_DATE") public Date getEndDate() { return this.endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } @Column(name = "STATUS", nullable = false, length = 20) public String getStatus() { return this.status; } public void setStatus(String status) { this.status = status; } @Column(name = "TYPE", nullable = false, length = 20) public String getType() { return this.type; } public void setType(String type) { this.type = type; } @Column(name = "CHANNEL", nullable = false, length = 20) public String getChannel() { return this.channel; } public void setChannel(String channel) { this.channel = channel; } @Column(name = "DESCRIPTION", length = 4000) public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } @Column(name = "CREATION_CINEMA_ID", precision = 22, scale = 0) public Long getCreationCinemaId() { return this.creationCinemaId; } public void setCreationCinemaId(Long creationCinemaId) { this.creationCinemaId = creationCinemaId; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "CREATION_CINEMA_ID", updatable = false, insertable = false) public TCinema gettCinema() { return tCinema; } public void settCinema(TCinema tCinema) { this.tCinema = tCinema; } @Column(name = "CREATION_AREA_ID", nullable = false, length = 20) public String getCreationAreaId() { return this.creationAreaId; } public void setCreationAreaId(String creationAreaId) { this.creationAreaId = creationAreaId; } @Column(name = "ALL_CINEMA", nullable = false, length = 1) public boolean getAllCinema() { return this.allCinema; } public void setAllCinema(boolean allCinema) { this.allCinema = allCinema; } @Column(name = "CREATION_LEVEL", length = 20) public String getCreationLevel() { return this.creationLevel; } public void setCreationLevel(String creationLevel) { this.creationLevel = creationLevel; } @Column(name = "ALLOW_MODIFIER", length = 40) public String getAllowModifier() { return this.allowModifier; } public void setAllowModifier(String allowModifier) { this.allowModifier = allowModifier; } @Column(name = "SETTLEMENT_TYPE") public String getSettlementType() { return settlementType; } public void setSettlementType(String settlementType) { this.settlementType = settlementType; } @OneToMany(fetch = FetchType.LAZY, mappedBy = "tCampaign") @OrderBy(value="startDate,name asc") public Set<TCmnPhase> gettCmnPhases() { return this.tCmnPhases; } public void settCmnPhases(Set<TCmnPhase> tCmnPhases) { this.tCmnPhases = tCmnPhases; } @OneToMany(fetch = FetchType.LAZY, mappedBy = "tCampaign") public Set<TCmnActivity> gettCmnActivities() { return this.tCmnActivities; } public void settCmnActivities(Set<TCmnActivity> tCmnActivities) { this.tCmnActivities = tCmnActivities; } @OneToMany(fetch = FetchType.LAZY, mappedBy = "tCampaign", cascade = CascadeType.ALL, orphanRemoval = true) public Set<TCampaignCinema> gettCampaignCinemas() { return this.tCampaignCinemas; } public void settCampaignCinemas(Set<TCampaignCinema> tCampaignCinemas) { this.tCampaignCinemas = tCampaignCinemas; } @Transient public String getStrStartDate() { if(startDate != null) strStartDate = new SimpleDateFormat("yyyy-MM-dd").format(startDate); return strStartDate; } public void setStrStartDate(String strStartDate) { try { if(!StringUtil.isNullOrBlank(strStartDate)) startDate = new SimpleDateFormat("yyyy-MM-dd").parse(strStartDate); else startDate = null; } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } this.strStartDate = strStartDate; } @Transient public String getStrEndDate() { if(endDate != null) strEndDate = new SimpleDateFormat("yyyy-MM-dd").format(endDate); return strEndDate; } public void setStrEndDate(String strEndDate) { try { if(!StringUtil.isNullOrBlank(strEndDate)) endDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(strEndDate+" 23:59:59"); else endDate = null; } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } this.strEndDate = strEndDate; } @Transient public String getCinemas() { return cinemas; } public void setCinemas(String cinemas) { this.cinemas = cinemas; } @Transient public String getPhaseAndActivitys() { return phaseAndActivitys; } public void setPhaseAndActivitys(String phaseAndActivitys) { this.phaseAndActivitys = phaseAndActivitys; } }
7,954
0.708972
0.69683
306
23.568628
22.170982
108
false
false
0
0
0
0
0
0
1.457516
false
false
10
2c8dba0d847bc7d864bea1a179dda46b023a3a24
29,566,554,918,633
db6297390cb5403a82e84bcfb58e4b294907e9bb
/prototype_pattern/src/MilkTea.java
144a435112435fb6cea00016c78b36f23e46f64c
[]
no_license
hauringu/DesignPatterns
https://github.com/hauringu/DesignPatterns
97bbf54bf3784290373da5bc016466c88dcbcc00
65d1b10b3915c0449a0163c22bac5e8a39205404
refs/heads/main
2023-07-08T18:43:33.700000
2021-08-16T09:23:10
2021-08-16T09:23:10
385,499,618
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class MilkTea { private String type; private Boolean ice; public String getType() { return type; } public void setType(String type) { this.type = type; } public Boolean getIce() { return ice; } public void setIce(Boolean ice) { this.ice = ice; } public MilkTea copy() { MilkTea mt = new MilkTea(); mt.type = this.type; mt.ice = this.ice; return mt; } }
UTF-8
Java
477
java
MilkTea.java
Java
[]
null
[]
public class MilkTea { private String type; private Boolean ice; public String getType() { return type; } public void setType(String type) { this.type = type; } public Boolean getIce() { return ice; } public void setIce(Boolean ice) { this.ice = ice; } public MilkTea copy() { MilkTea mt = new MilkTea(); mt.type = this.type; mt.ice = this.ice; return mt; } }
477
0.532495
0.532495
27
16.666666
12.780193
38
false
false
0
0
0
0
0
0
0.37037
false
false
10
23181b4e81bf8aee27db78d21ed38267a387f118
33,303,176,414,859
40222a7b422e4eacf58201dce227d18cbe2a0186
/strasser.cipher/ShiftCipher.java
ab88b23cabce91697c5ca5a5580751d56a60e71d
[]
no_license
DominikStrasser3CHIT/SEW
https://github.com/DominikStrasser3CHIT/SEW
741499bfbc65504f49803b3094d22db7ced701f9
a640360a481c3c34124dd7f13e60dc7674e5e675
refs/heads/master
2021-01-23T14:56:09.145000
2014-04-23T07:34:48
2014-04-23T07:34:48
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Write a description of class ShiftCipher here. * * @author Dominik Strasser * @version 23.4.14 */ public class ShiftCipher extends MonoAlphabeticCipher { public ShiftCipher (int value) { super(); this.setShiftAmount(value); } public void setShiftAmount(int shiftvalue) { if(shiftvalue > 30 || shiftvalue < 0) { return; } String key = MonoAlphabeticCipher.standardAlphabet.substring(shiftvalue) + MonoAlphabeticCipher.standardAlphabet.substring(0,shiftvalue); super.setSecretAlphabet(key); } public static void main(String[] args){ System.out.println(MonoAlphabeticCipher.standardAlphabet); } }
UTF-8
Java
738
java
ShiftCipher.java
Java
[ { "context": "cription of class ShiftCipher here.\n * \n * @author Dominik Strasser\n * @version 23.4.14\n */\npublic class ShiftCipher ", "end": 86, "score": 0.9998054504394531, "start": 70, "tag": "NAME", "value": "Dominik Strasser" } ]
null
[]
/** * Write a description of class ShiftCipher here. * * @author <NAME> * @version 23.4.14 */ public class ShiftCipher extends MonoAlphabeticCipher { public ShiftCipher (int value) { super(); this.setShiftAmount(value); } public void setShiftAmount(int shiftvalue) { if(shiftvalue > 30 || shiftvalue < 0) { return; } String key = MonoAlphabeticCipher.standardAlphabet.substring(shiftvalue) + MonoAlphabeticCipher.standardAlphabet.substring(0,shiftvalue); super.setSecretAlphabet(key); } public static void main(String[] args){ System.out.println(MonoAlphabeticCipher.standardAlphabet); } }
728
0.635501
0.623306
29
24.413794
23.424887
83
false
false
0
0
0
0
0
0
0.310345
false
false
10
f11735b848d6c7242a42b31fccb2daab5a065cf9
7,799,660,611,571
f6142f3c6c6ca977f101435c43491a953028a749
/ita-webapp-bkg/src/main/java/com/aquariuslt/restful/BookingRestfulAPI.java
b55d8ac844958a00bf13fc068319ae73f6b1acc9
[]
no_license
Aquariuslt/ExtJS-UI
https://github.com/Aquariuslt/ExtJS-UI
1f8687b0a57db589a3ecaedfd3c810f011087929
bf2710b90e9a8f32e45eedf2862c193da3a729f2
refs/heads/master
2015-09-26T06:48:19.763000
2015-09-14T13:35:42
2015-09-14T13:35:42
42,403,774
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.aquariuslt.restful; import com.aquariuslt.constants.BKGConstants; import com.aquariuslt.dto.*; import com.aquariuslt.service.BookingService; import com.aquariuslt.utils.criteria.BookingSearchCriteria; import com.aquariuslt.utils.mapper.JsonMapper; import com.aquariuslt.utils.criteria.SortCriteria; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpSession; import java.io.IOException; import java.util.List; /** * @author Jason Cui * @version 2015-09-05 */ @Controller @RequestMapping("/rest/booking") public class BookingRestfulAPI { @Autowired BookingService bookingService; @Autowired JsonMapper jsonMapper; @RequestMapping(value = "/list",produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public Page<BookingRequestDto> findBookingRequestByPage( @RequestParam(value = "page",defaultValue = "0")Integer page, @RequestParam(value = "limit",defaultValue = "25")Integer limit, @RequestParam(value = "sort",required = false)String sortString, HttpSession session) throws IOException { Pageable pageable; if(StringUtils.isNotEmpty(sortString)){ List<SortCriteria> sortList=jsonMapper.readValue(sortString, jsonMapper.getTypeFactory().constructCollectionType(List.class, SortCriteria.class)); Sort sort=sortList.get(0).toSort(); pageable=new PageRequest(page-1,limit,sort); } else{ pageable=new PageRequest(page-1,limit); } //Construct SearchCriteria if(null!=session.getAttribute(BKGConstants.SEARCH_CRITERIA)){ BookingSearchCriteria bookingSearchCriteria=(BookingSearchCriteria)session.getAttribute(BKGConstants.SEARCH_CRITERIA); return bookingService.findAll(bookingSearchCriteria,pageable); } else{ return bookingService.findAll(pageable); } } //Update and create SearchCriteria Session @RequestMapping(value = "/query/update",produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public String updateSearchCriteria(@RequestParam(value = "searchCriteria")String searchCriteria,HttpSession session) throws IOException { BookingSearchCriteria bookingSearchCriteria=jsonMapper.readValue(searchCriteria,BookingSearchCriteria.class); session.setAttribute(BKGConstants.SEARCH_CRITERIA,bookingSearchCriteria); return HttpStatus.OK.toString(); } @RequestMapping(value = "/save",method = RequestMethod.POST) @ResponseBody public String saveBookingRequest( @RequestParam("bookingRequest")String bookingRequestBaseInfo, @RequestParam("bookingPartyShipper")String bookingPartyShipper, @RequestParam("bookingPartyForwarder")String bookingPartyForwarder, @RequestParam("bookingPartyConsignee")String bookingPartyConsignee, @RequestParam("bookingRouteLegList")String bookingRouteLegList, @RequestParam("bookingContainerList")String bookingContainerList ) throws IOException { System.out.println("=====Get Booking RequestDTO:====="); BookingRequestDto bookingRequestDto=jsonMapper.readValue(bookingRequestBaseInfo,BookingRequestDto.class); BookingRequestPartyDto bookingRequestPartyShipper=jsonMapper.readValue(bookingPartyShipper,BookingRequestPartyDto.class); BookingRequestPartyDto bookingRequestPartyForwarder=jsonMapper.readValue(bookingPartyForwarder,BookingRequestPartyDto.class); BookingRequestPartyDto bookingRequestPartyConsignee=jsonMapper.readValue(bookingPartyConsignee,BookingRequestPartyDto.class); BookingRequestCargoDto bookingRequestCargoDto=jsonMapper.readValue(bookingRequestBaseInfo,BookingRequestCargoDto.class); List<BookingRequestRouteLegDto> bookingRequestRouteLegDtoList=jsonMapper.readValue(bookingRouteLegList,jsonMapper.getTypeFactory().constructCollectionType(List.class,BookingRequestRouteLegDto.class)); List<BookingRequestContainerDto> bookingRequestContainerDtoList=jsonMapper.readValue(bookingContainerList,jsonMapper.getTypeFactory().constructCollectionType(List.class,BookingRequestContainerDto.class)); System.out.println("=====Merge BookingRequest DTO====="); bookingRequestDto.getBookingRequestPartyList().add(bookingRequestPartyShipper); bookingRequestDto.getBookingRequestPartyList().add(bookingRequestPartyForwarder); bookingRequestDto.getBookingRequestPartyList().add(bookingRequestPartyConsignee); bookingRequestDto.getBookingRequestCargoList().add(bookingRequestCargoDto); BookingRequestRouteDto bookingRequestRouteDto=new BookingRequestRouteDto(); bookingRequestRouteDto.getBookingRequestRouteLegDtoList().addAll(bookingRequestRouteLegDtoList); bookingRequestDto.getBookingRequestRouteList().add(bookingRequestRouteDto); bookingRequestDto.getBookingRequestContainerList().addAll(bookingRequestContainerDtoList); String bookingNumber=bookingService.save(bookingRequestDto); return bookingNumber; } }
UTF-8
Java
5,791
java
BookingRestfulAPI.java
Java
[ { "context": "OException;\nimport java.util.List;\n\n/**\n * @author Jason Cui\n * @version 2015-09-05\n */\n@Controller\n@RequestMa", "end": 1111, "score": 0.9992830753326416, "start": 1102, "tag": "NAME", "value": "Jason Cui" } ]
null
[]
package com.aquariuslt.restful; import com.aquariuslt.constants.BKGConstants; import com.aquariuslt.dto.*; import com.aquariuslt.service.BookingService; import com.aquariuslt.utils.criteria.BookingSearchCriteria; import com.aquariuslt.utils.mapper.JsonMapper; import com.aquariuslt.utils.criteria.SortCriteria; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpSession; import java.io.IOException; import java.util.List; /** * @author <NAME> * @version 2015-09-05 */ @Controller @RequestMapping("/rest/booking") public class BookingRestfulAPI { @Autowired BookingService bookingService; @Autowired JsonMapper jsonMapper; @RequestMapping(value = "/list",produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public Page<BookingRequestDto> findBookingRequestByPage( @RequestParam(value = "page",defaultValue = "0")Integer page, @RequestParam(value = "limit",defaultValue = "25")Integer limit, @RequestParam(value = "sort",required = false)String sortString, HttpSession session) throws IOException { Pageable pageable; if(StringUtils.isNotEmpty(sortString)){ List<SortCriteria> sortList=jsonMapper.readValue(sortString, jsonMapper.getTypeFactory().constructCollectionType(List.class, SortCriteria.class)); Sort sort=sortList.get(0).toSort(); pageable=new PageRequest(page-1,limit,sort); } else{ pageable=new PageRequest(page-1,limit); } //Construct SearchCriteria if(null!=session.getAttribute(BKGConstants.SEARCH_CRITERIA)){ BookingSearchCriteria bookingSearchCriteria=(BookingSearchCriteria)session.getAttribute(BKGConstants.SEARCH_CRITERIA); return bookingService.findAll(bookingSearchCriteria,pageable); } else{ return bookingService.findAll(pageable); } } //Update and create SearchCriteria Session @RequestMapping(value = "/query/update",produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public String updateSearchCriteria(@RequestParam(value = "searchCriteria")String searchCriteria,HttpSession session) throws IOException { BookingSearchCriteria bookingSearchCriteria=jsonMapper.readValue(searchCriteria,BookingSearchCriteria.class); session.setAttribute(BKGConstants.SEARCH_CRITERIA,bookingSearchCriteria); return HttpStatus.OK.toString(); } @RequestMapping(value = "/save",method = RequestMethod.POST) @ResponseBody public String saveBookingRequest( @RequestParam("bookingRequest")String bookingRequestBaseInfo, @RequestParam("bookingPartyShipper")String bookingPartyShipper, @RequestParam("bookingPartyForwarder")String bookingPartyForwarder, @RequestParam("bookingPartyConsignee")String bookingPartyConsignee, @RequestParam("bookingRouteLegList")String bookingRouteLegList, @RequestParam("bookingContainerList")String bookingContainerList ) throws IOException { System.out.println("=====Get Booking RequestDTO:====="); BookingRequestDto bookingRequestDto=jsonMapper.readValue(bookingRequestBaseInfo,BookingRequestDto.class); BookingRequestPartyDto bookingRequestPartyShipper=jsonMapper.readValue(bookingPartyShipper,BookingRequestPartyDto.class); BookingRequestPartyDto bookingRequestPartyForwarder=jsonMapper.readValue(bookingPartyForwarder,BookingRequestPartyDto.class); BookingRequestPartyDto bookingRequestPartyConsignee=jsonMapper.readValue(bookingPartyConsignee,BookingRequestPartyDto.class); BookingRequestCargoDto bookingRequestCargoDto=jsonMapper.readValue(bookingRequestBaseInfo,BookingRequestCargoDto.class); List<BookingRequestRouteLegDto> bookingRequestRouteLegDtoList=jsonMapper.readValue(bookingRouteLegList,jsonMapper.getTypeFactory().constructCollectionType(List.class,BookingRequestRouteLegDto.class)); List<BookingRequestContainerDto> bookingRequestContainerDtoList=jsonMapper.readValue(bookingContainerList,jsonMapper.getTypeFactory().constructCollectionType(List.class,BookingRequestContainerDto.class)); System.out.println("=====Merge BookingRequest DTO====="); bookingRequestDto.getBookingRequestPartyList().add(bookingRequestPartyShipper); bookingRequestDto.getBookingRequestPartyList().add(bookingRequestPartyForwarder); bookingRequestDto.getBookingRequestPartyList().add(bookingRequestPartyConsignee); bookingRequestDto.getBookingRequestCargoList().add(bookingRequestCargoDto); BookingRequestRouteDto bookingRequestRouteDto=new BookingRequestRouteDto(); bookingRequestRouteDto.getBookingRequestRouteLegDtoList().addAll(bookingRequestRouteLegDtoList); bookingRequestDto.getBookingRequestRouteList().add(bookingRequestRouteDto); bookingRequestDto.getBookingRequestContainerList().addAll(bookingRequestContainerDtoList); String bookingNumber=bookingService.save(bookingRequestDto); return bookingNumber; } }
5,788
0.77396
0.771369
125
45.327999
43.740284
212
false
false
0
0
0
0
0
0
0.696
false
false
10
f954a430b831c3c6f3f032b7848870adec0687af
14,516,989,476,682
c6f2bc9b9796aa4755bc2cf3c4deca8fc016161a
/src/controler/Main.java
fe97b64a531247c3457995066bf48a7c02d9d841
[]
no_license
michalkrempasky/example_eshop_app
https://github.com/michalkrempasky/example_eshop_app
d6fe00af7ca5bc3a88dd7ee5191047186fc5b69e
d073d8d2201df65cb0e0a7fba6490829ef18b9fe
refs/heads/master
2021-01-22T21:58:55.479000
2017-03-19T17:52:28
2017-03-19T17:52:28
85,496,488
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package controler; import java.util.Scanner; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Scanner scanner = new Scanner(System.in); InventoryHandler inventoryHandler = new InventoryHandler(); ShoppingHandler shoppingHandler= new ShoppingHandler(); System.out.println("inventar (1) nakupovat(2)"); int pom = scanner.nextInt(); switch(pom){ case 1 : {inventoryHandler.launch(scanner); break; } case 2 : {shoppingHandler.launch(scanner); break; } } } }
UTF-8
Java
552
java
Main.java
Java
[]
null
[]
package controler; import java.util.Scanner; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Scanner scanner = new Scanner(System.in); InventoryHandler inventoryHandler = new InventoryHandler(); ShoppingHandler shoppingHandler= new ShoppingHandler(); System.out.println("inventar (1) nakupovat(2)"); int pom = scanner.nextInt(); switch(pom){ case 1 : {inventoryHandler.launch(scanner); break; } case 2 : {shoppingHandler.launch(scanner); break; } } } }
552
0.690217
0.682971
29
18.034483
20.055927
61
false
false
0
0
0
0
0
0
1.827586
false
false
10
35b112fe35299cde764231e5c661b0e3eaef9468
20,547,123,571,232
6d34cb3a0d331c361d6830ada468fc82b780f6af
/workspace/httpclientdemo/src/test/java/com/fhr/httpclientdemo/util/HttpUtilsTest.java
895c370da188953be518220ce359ed42d693b925
[ "MIT" ]
permissive
FanHuaRan/httpclientdemo
https://github.com/FanHuaRan/httpclientdemo
0b3ccc6f7350accc70d2e4724ab1f325ec0c78e5
4bb5ba22f6f1d3cf22146767f053e15ef4d874fb
refs/heads/master
2021-05-15T14:28:35.038000
2017-10-17T02:50:51
2017-10-17T02:50:51
107,208,639
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.fhr.httpclientdemo.util; import static org.junit.Assert.*; import java.io.IOException; import java.util.LinkedList; import java.util.List; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.message.BasicNameValuePair; import org.junit.Test; public class HttpUtilsTest { private static final String GET_URL="http://localhost:8080/HttpClientTest/get"; private static final String POST_JSON_URL="http://localhost:8080/HttpClientTest/postJson"; private static final String POST_FORM_URL="http://localhost:8080/HttpClientTest/postForm"; @Test public void testGet() throws ClientProtocolException, IOException { String response=HttpUtils.get(GET_URL); } @Test public void testPostForm() throws ClientProtocolException, IOException { List<NameValuePair> params=new LinkedList<>(); params.add(new BasicNameValuePair("id", "1")); params.add(new BasicNameValuePair("age", "2")); String response=HttpUtils.postForm(POST_FORM_URL, params); } @Test public void testPostJson() throws ClientProtocolException, IOException { String response=HttpUtils.postJson(POST_JSON_URL,"{\"id\":1,\"test\":1}"); } }
UTF-8
Java
1,198
java
HttpUtilsTest.java
Java
[]
null
[]
package com.fhr.httpclientdemo.util; import static org.junit.Assert.*; import java.io.IOException; import java.util.LinkedList; import java.util.List; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.message.BasicNameValuePair; import org.junit.Test; public class HttpUtilsTest { private static final String GET_URL="http://localhost:8080/HttpClientTest/get"; private static final String POST_JSON_URL="http://localhost:8080/HttpClientTest/postJson"; private static final String POST_FORM_URL="http://localhost:8080/HttpClientTest/postForm"; @Test public void testGet() throws ClientProtocolException, IOException { String response=HttpUtils.get(GET_URL); } @Test public void testPostForm() throws ClientProtocolException, IOException { List<NameValuePair> params=new LinkedList<>(); params.add(new BasicNameValuePair("id", "1")); params.add(new BasicNameValuePair("age", "2")); String response=HttpUtils.postForm(POST_FORM_URL, params); } @Test public void testPostJson() throws ClientProtocolException, IOException { String response=HttpUtils.postJson(POST_JSON_URL,"{\"id\":1,\"test\":1}"); } }
1,198
0.772955
0.759599
38
30.526316
29.671656
91
false
false
0
0
0
0
0
0
1.315789
false
false
10
07d5d69a176cf46cc4cc9c01fb2abd8364a2de81
22,153,441,319,366
6ce299125378e4de0c5413cad12633e9420a7a79
/Lesson3/Aplication.java
2396a4b03c5f8b35464eeff4118c0c2083458e1e
[]
no_license
MarkianPylat23/Petrol_Station
https://github.com/MarkianPylat23/Petrol_Station
8d923a1dae8dbd7d0fb1c8d0b893ff73dda32f6b
ab02fec8657c688e85b00e146dbb9c9866999879
refs/heads/master
2020-04-15T13:33:54.628000
2020-01-23T15:07:52
2020-01-23T15:07:52
164,722,177
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Lesson3; import java.time.Instant; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Set; public class Aplication { public static void main(String[] args) throws InterruptedException { Set<String> names = new HashSet<>(); names.add("Oleg"); names.add("Taras"); names.add("Oleg"); names.add("Vitali"); names.add("Oleg"); names.add("Vitali"); names.add("Oksana"); names.add("Viktoria"); System.out.println(names); Set<String> names1 = new HashSet<>(); names1.add("Oleg"); names1.add("Taras"); names1.add("Taras1"); names.retainAll(names1); System.out.println(names); // ========== Set<Person> people = new HashSet<>(); people.add(new Person("Oleg")); people.add(new Person("Taras")); people.add(new Person("Oleg")); people.add(new Person("Vitali")); people.add(new Person("Oleg")); people.add(new Person("Vitali")); people.add(new Person("Oksana")); people.add(new Person("Viktoria")); System.out.println(people); Thread.sleep(2000); long startTime = Instant.now().getEpochSecond(); // HashSet long endTime = Instant.now().getEpochSecond(); System.out.println("HashSet time: " + (endTime - startTime)); } }
UTF-8
Java
1,432
java
Aplication.java
Java
[ { "context": "ring> names = new HashSet<>();\n names.add(\"Oleg\");\n names.add(\"Taras\");\n names.add(", "end": 316, "score": 0.9997363686561584, "start": 312, "tag": "NAME", "value": "Oleg" }, { "context": "();\n names.add(\"Oleg\");\n names.add(\"Taras\");\n names.add(\"Oleg\");\n names.add(\"", "end": 344, "score": 0.9997937679290771, "start": 339, "tag": "NAME", "value": "Taras" }, { "context": ");\n names.add(\"Taras\");\n names.add(\"Oleg\");\n names.add(\"Vitali\");\n names.add", "end": 371, "score": 0.9997881650924683, "start": 367, "tag": "NAME", "value": "Oleg" }, { "context": "\");\n names.add(\"Oleg\");\n names.add(\"Vitali\");\n names.add(\"Oleg\");\n names.add(\"", "end": 400, "score": 0.9997777342796326, "start": 394, "tag": "NAME", "value": "Vitali" }, { "context": ";\n names.add(\"Vitali\");\n names.add(\"Oleg\");\n names.add(\"Vitali\");\n names.add", "end": 427, "score": 0.9997744560241699, "start": 423, "tag": "NAME", "value": "Oleg" }, { "context": "\");\n names.add(\"Oleg\");\n names.add(\"Vitali\");\n names.add(\"Oksana\");\n names.add", "end": 456, "score": 0.9997760653495789, "start": 450, "tag": "NAME", "value": "Vitali" }, { "context": ";\n names.add(\"Vitali\");\n names.add(\"Oksana\");\n names.add(\"Viktoria\");\n System.", "end": 485, "score": 0.9998264312744141, "start": 479, "tag": "NAME", "value": "Oksana" }, { "context": ";\n names.add(\"Oksana\");\n names.add(\"Viktoria\");\n System.out.println(names);\n\n Se", "end": 516, "score": 0.9998195767402649, "start": 508, "tag": "NAME", "value": "Viktoria" }, { "context": "ng> names1 = new HashSet<>();\n names1.add(\"Oleg\");\n names1.add(\"Taras\");\n names1.ad", "end": 626, "score": 0.9997330904006958, "start": 622, "tag": "NAME", "value": "Oleg" }, { "context": ";\n names1.add(\"Oleg\");\n names1.add(\"Taras\");\n names1.add(\"Taras1\");\n\n names.r", "end": 655, "score": 0.9997859001159668, "start": 650, "tag": "NAME", "value": "Taras" }, { "context": "\n names1.add(\"Taras\");\n names1.add(\"Taras1\");\n\n names.retainAll(names1);\n Syst", "end": 685, "score": 0.999798059463501, "start": 679, "tag": "NAME", "value": "Taras1" }, { "context": "= new HashSet<>();\n people.add(new Person(\"Oleg\"));\n people.add(new Person(\"Taras\"));\n ", "end": 863, "score": 0.9996116757392883, "start": 859, "tag": "NAME", "value": "Oleg" }, { "context": "w Person(\"Oleg\"));\n people.add(new Person(\"Taras\"));\n people.add(new Person(\"Oleg\"));\n ", "end": 904, "score": 0.999737024307251, "start": 899, "tag": "NAME", "value": "Taras" }, { "context": " Person(\"Taras\"));\n people.add(new Person(\"Oleg\"));\n people.add(new Person(\"Vitali\"));\n ", "end": 944, "score": 0.9996755123138428, "start": 940, "tag": "NAME", "value": "Oleg" }, { "context": "w Person(\"Oleg\"));\n people.add(new Person(\"Vitali\"));\n people.add(new Person(\"Oleg\"));\n ", "end": 986, "score": 0.9997033476829529, "start": 980, "tag": "NAME", "value": "Vitali" }, { "context": "Person(\"Vitali\"));\n people.add(new Person(\"Oleg\"));\n people.add(new Person(\"Vitali\"));\n ", "end": 1026, "score": 0.9997453689575195, "start": 1022, "tag": "NAME", "value": "Oleg" }, { "context": "w Person(\"Oleg\"));\n people.add(new Person(\"Vitali\"));\n people.add(new Person(\"Oksana\"));\n ", "end": 1068, "score": 0.999671459197998, "start": 1062, "tag": "NAME", "value": "Vitali" }, { "context": "Person(\"Vitali\"));\n people.add(new Person(\"Oksana\"));\n people.add(new Person(\"Viktoria\"));\n ", "end": 1110, "score": 0.999792754650116, "start": 1104, "tag": "NAME", "value": "Oksana" }, { "context": "Person(\"Oksana\"));\n people.add(new Person(\"Viktoria\"));\n System.out.println(people);\n T", "end": 1154, "score": 0.9997692108154297, "start": 1146, "tag": "NAME", "value": "Viktoria" } ]
null
[]
package Lesson3; import java.time.Instant; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Set; public class Aplication { public static void main(String[] args) throws InterruptedException { Set<String> names = new HashSet<>(); names.add("Oleg"); names.add("Taras"); names.add("Oleg"); names.add("Vitali"); names.add("Oleg"); names.add("Vitali"); names.add("Oksana"); names.add("Viktoria"); System.out.println(names); Set<String> names1 = new HashSet<>(); names1.add("Oleg"); names1.add("Taras"); names1.add("Taras1"); names.retainAll(names1); System.out.println(names); // ========== Set<Person> people = new HashSet<>(); people.add(new Person("Oleg")); people.add(new Person("Taras")); people.add(new Person("Oleg")); people.add(new Person("Vitali")); people.add(new Person("Oleg")); people.add(new Person("Vitali")); people.add(new Person("Oksana")); people.add(new Person("Viktoria")); System.out.println(people); Thread.sleep(2000); long startTime = Instant.now().getEpochSecond(); // HashSet long endTime = Instant.now().getEpochSecond(); System.out.println("HashSet time: " + (endTime - startTime)); } }
1,432
0.576816
0.569134
50
27.66
17.445469
72
false
false
0
0
0
0
0
0
0.72
false
false
10
8debc151ffa51b39b313ae9732c6177acb40eb80
12,463,995,109,302
e81189f6e457aa401405c5512ba36af28b5eb64a
/minion/src/main/java/net/objectof/actof/minion/MinionController.java
3ef791a2de47f8c17d49ea19ad6dd9a497c1025e
[]
no_license
mahmoud1041998/actof
https://github.com/mahmoud1041998/actof
154b0cb07e52b6e7cfeda8873378383648ab3d31
c687774491bd60b53f453710a9b9f1f01a6be3db
refs/heads/master
2021-05-29T17:40:24.895000
2015-09-24T19:27:28
2015-09-24T19:27:28
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.objectof.actof.minion; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; public class MinionController { @FXML private TabPane tabs; @FXML private void initialize() { } public void addTab(Node node, String title) { Tab tab = new Tab(title); tab.setContent(node); tabs.getTabs().add(tab); } public void selectNextTab() { tabs.getSelectionModel().selectNext(); } }
UTF-8
Java
526
java
MinionController.java
Java
[]
null
[]
package net.objectof.actof.minion; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; public class MinionController { @FXML private TabPane tabs; @FXML private void initialize() { } public void addTab(Node node, String title) { Tab tab = new Tab(title); tab.setContent(node); tabs.getTabs().add(tab); } public void selectNextTab() { tabs.getSelectionModel().selectNext(); } }
526
0.65019
0.65019
32
15.4375
16.197874
49
false
false
0
0
0
0
0
0
0.34375
false
false
10
81de19911eb2ae954a0e56ada7c40382d17c6172
31,293,131,744,832
7afdbdfb70c8ebeb6404fdbe7b0e9f9b2737b5b4
/RPS_JAVA/RPSfunction.java
2fe7baa28f35b42193d3f4d0d93754a56041c57d
[]
no_license
reshinto/Rock-Paper-Scissors
https://github.com/reshinto/Rock-Paper-Scissors
cb013fa03b10fceb2d44e901cf30600cc0dc1beb
043fab94a2e0ec7cccb3fbc0b472497d69515d47
refs/heads/master
2022-08-14T20:33:23.834000
2020-01-16T07:16:54
2022-07-24T15:32:21
128,206,483
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// required for user input function import java.util.Scanner; // required for random function import java.util.Random; //import java.util.ArrayList; import java.util.List; public class RPSfunction { public static void main(String[] args) { intro(); } public static String repeat(String str, int times) { return new String(new char[times]).replace("\0", str); } public static void intro() { String text = "Welcome to ROCK, PAPER, SCISSORS game!\n"; int txt_size = text.length(); System.out.println(repeat("#", txt_size)); System.out.println(text); continue_game(); } public static void continue_game() { String text = "Do you wish to play or continue playing (y/n)? "; Scanner choice = new Scanner(System.in); System.out.print(text); String choice_input = choice.nextLine().toLowerCase(); if (choice_input.equals("y")) { play_game(); } else if (choice_input.equals("n")) { System.out.println("\nThank you for playing!\n"); } else { invalid_input(); continue_game(); } } public static void invalid_input() { String text = "You can only input y or n"; int txt_size = text.length(); System.out.println("\n"+repeat("!", txt_size)); System.out.println(text); System.out.println(repeat("!", txt_size)+"\n"); } public static void play_game() { String text = "\nEnter (r)ock, (p)aper, (s)cissors: "; int txt_size = text.length(); System.out.println(repeat("=", txt_size)); System.out.print(text); Scanner choice = new Scanner(System.in); String player = choice.nextLine().toLowerCase(); Random rand = new Random(); List<String> valid_moves = List.of("r","p","s"); int randomIndex = rand.nextInt(valid_moves.size()); String computer = valid_moves.get(randomIndex); rps_winner(player, computer); } public static void rps_winner(String player, String computer) { if (player.equals(computer)) { System.out.println("\nIt was a tie! you both moved: " + computer + "\n"); continue_game(); } else if (((player.equals("r")) && (computer.equals("s"))) || ((player.equals("p")) && (computer.equals("r"))) || ((player.equals("s")) && (computer.equals("p")))) { System.out.println("\nYou won! You moved: " + player + " | The computer moved: " + computer + "\n"); continue_game(); } else { // TODO else if player not in valid_moves System.out.println("\nYou lost! You moved: " + player + " | The computer moved: " + computer + "\n"); continue_game(); } } }
UTF-8
Java
2,929
java
RPSfunction.java
Java
[]
null
[]
// required for user input function import java.util.Scanner; // required for random function import java.util.Random; //import java.util.ArrayList; import java.util.List; public class RPSfunction { public static void main(String[] args) { intro(); } public static String repeat(String str, int times) { return new String(new char[times]).replace("\0", str); } public static void intro() { String text = "Welcome to ROCK, PAPER, SCISSORS game!\n"; int txt_size = text.length(); System.out.println(repeat("#", txt_size)); System.out.println(text); continue_game(); } public static void continue_game() { String text = "Do you wish to play or continue playing (y/n)? "; Scanner choice = new Scanner(System.in); System.out.print(text); String choice_input = choice.nextLine().toLowerCase(); if (choice_input.equals("y")) { play_game(); } else if (choice_input.equals("n")) { System.out.println("\nThank you for playing!\n"); } else { invalid_input(); continue_game(); } } public static void invalid_input() { String text = "You can only input y or n"; int txt_size = text.length(); System.out.println("\n"+repeat("!", txt_size)); System.out.println(text); System.out.println(repeat("!", txt_size)+"\n"); } public static void play_game() { String text = "\nEnter (r)ock, (p)aper, (s)cissors: "; int txt_size = text.length(); System.out.println(repeat("=", txt_size)); System.out.print(text); Scanner choice = new Scanner(System.in); String player = choice.nextLine().toLowerCase(); Random rand = new Random(); List<String> valid_moves = List.of("r","p","s"); int randomIndex = rand.nextInt(valid_moves.size()); String computer = valid_moves.get(randomIndex); rps_winner(player, computer); } public static void rps_winner(String player, String computer) { if (player.equals(computer)) { System.out.println("\nIt was a tie! you both moved: " + computer + "\n"); continue_game(); } else if (((player.equals("r")) && (computer.equals("s"))) || ((player.equals("p")) && (computer.equals("r"))) || ((player.equals("s")) && (computer.equals("p")))) { System.out.println("\nYou won! You moved: " + player + " | The computer moved: " + computer + "\n"); continue_game(); } else { // TODO else if player not in valid_moves System.out.println("\nYou lost! You moved: " + player + " | The computer moved: " + computer + "\n"); continue_game(); } } }
2,929
0.544896
0.544554
83
34.289158
23.618723
85
false
false
0
0
0
0
0
0
0.73494
false
false
10
6be42dcf92f732a1c9e0faae489f68d344a39d41
3,985,729,676,305
60f22e82fce81a3fae4f5b8f67ff37e4a61d0fc3
/AllWidgetExample/app/src/main/java/agrawal/snehal/allwidgetexample/ViewAnimatorActivity.java
f4bac03be6b327649b8c77c8993a2c7873ff8798
[]
no_license
SnehalAgrawal/Java-N-Doid
https://github.com/SnehalAgrawal/Java-N-Doid
97488ac12893407f558a4d48ee6815316a20717b
bba0ba1934834b84935bd62213f5a527114bee27
refs/heads/master
2021-11-28T19:25:51.866000
2021-11-22T03:01:56
2021-11-22T03:01:56
98,222,441
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package agrawal.snehal.allwidgetexample; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.ViewAnimator; public class ViewAnimatorActivity extends AppCompatActivity { private ViewAnimator simpleViewAnimator; Button btnNext; int[] images = {R.drawable.jellybean, R.drawable.kitkat, R.drawable.lollipop, R.drawable.marshmellow, R.drawable.nougat}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_viewanimator); btnNext = (Button) findViewById(R.id.buttonNext); simpleViewAnimator = (ViewAnimator) findViewById(R.id.simpleViewAnimator); // get the reference of ViewAnimator for (int i = 0; i < images.length; i++) { ImageView imageView = new ImageView(getApplicationContext()); // create a new object for ImageView imageView.setImageResource(images[i]); // set image resource for ImageView simpleViewAnimator.addView(imageView); // add child view in ViewAnimator } Animation in = AnimationUtils.loadAnimation(this, android.R.anim.slide_in_left); Animation out = AnimationUtils.loadAnimation(this, android.R.anim.slide_out_right); simpleViewAnimator.setInAnimation(in); simpleViewAnimator.setOutAnimation(out); simpleViewAnimator.setAnimateFirstView(false); // set false value for setAnimateFirstView btnNext.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub simpleViewAnimator.showNext(); } }); } }
UTF-8
Java
1,924
java
ViewAnimatorActivity.java
Java
[]
null
[]
package agrawal.snehal.allwidgetexample; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.ViewAnimator; public class ViewAnimatorActivity extends AppCompatActivity { private ViewAnimator simpleViewAnimator; Button btnNext; int[] images = {R.drawable.jellybean, R.drawable.kitkat, R.drawable.lollipop, R.drawable.marshmellow, R.drawable.nougat}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_viewanimator); btnNext = (Button) findViewById(R.id.buttonNext); simpleViewAnimator = (ViewAnimator) findViewById(R.id.simpleViewAnimator); // get the reference of ViewAnimator for (int i = 0; i < images.length; i++) { ImageView imageView = new ImageView(getApplicationContext()); // create a new object for ImageView imageView.setImageResource(images[i]); // set image resource for ImageView simpleViewAnimator.addView(imageView); // add child view in ViewAnimator } Animation in = AnimationUtils.loadAnimation(this, android.R.anim.slide_in_left); Animation out = AnimationUtils.loadAnimation(this, android.R.anim.slide_out_right); simpleViewAnimator.setInAnimation(in); simpleViewAnimator.setOutAnimation(out); simpleViewAnimator.setAnimateFirstView(false); // set false value for setAnimateFirstView btnNext.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub simpleViewAnimator.showNext(); } }); } }
1,924
0.718815
0.717775
43
43.744186
33.225861
125
false
false
0
0
0
0
0
0
0.813953
false
false
10
f4cb2d28ac46bdf5f04b1268cac9c55c3ad061e2
24,266,565,249,641
44a495cf3d818b874f8a59d13f320c6687cde1d4
/flashsale-service/src/main/java/com/le/flashsale/common/Constant.java
e5271ee3f4f4ba0f221a5a9fb950ec602a397718
[]
no_license
happy-lele/flashsale
https://github.com/happy-lele/flashsale
20dd06b5bf07efd29e16cbc4562e61d462a1e4f0
dfde750994d70f001b3fbbf52f0359baaabe5be1
refs/heads/main
2023-03-08T21:30:10.344000
2021-02-25T14:21:54
2021-02-25T14:21:54
342,266,378
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.le.flashsale.common; /** * Date 2020/11/16 7:54 下午 * Author le */ public class Constant { /** * 返回结果 */ public static final String SUCCESS = "success"; public static final String FAIL = "fail"; /** * 请求相关 */ public static final String HTTP_PREFIX = "flashsale"; // 请求前缀 /** * Redis 相关 */ public static final String REDIS_PREFIX_ADD_ORDER = "FLASH_SALE_ADD_ORDER_"; // 用户针对某个商品是否执行过下单操作 public static final String REDIS_PREFIX_ACTIVITY_STOCK_NUMS = "FLASH_SALE_ACTIVITY_STOCK_NUMS_"; // 活动涉及的库存量 public static final String REDIS_PREFIX_ACTIVITY_STOCK_STARTTIME = "FLASH_SALE_ACTIVITY_STOCK_STARTTIME_"; // 活动涉及的开始时间 public static final String REDIS_PREFIX_STOCK_ = "FLASH_SALE_STOCK_"; // 库存锁前缀 /** * 提示语句相关 */ public static final String MESSAGE_STOCK_BASE_PARAM_NULL = "接口入参不能为空"; public static final String MESSAGE_ORDER_SUBMITED = "请稍等,您的订单已在排队中,中签会收到邮件通知,请点击邮件中的链接查看具体详情"; public static final String MESSAGE_ORDER_FAILED_1 = "您已提交过订单,无须再次提交"; public static final String MESSAGE_ORDER_FAILED_2 = "实在抱歉,商品已售空,请15分钟之后再次尝试,抢购未支付的订单"; public static final String MESSAGE_ORDER_FAILED_3 = "该活动不存在,请稍后再试"; public static final String MESSAGE_STOCK_FAILED_STOCKID_NULL = "库存id不能为空"; public static final String MESSAGE_STOCK_FAILED_USERID_NULL = "用户id不能为空"; public static final String MESSAGE_STOCK_FAILED_NUMS_NULL = "扣减库存数量不能为空"; public static final String MESSAGE_STOCK_FAILED_NUMS_ERROR = "扣减库存数量只能为正整数"; public static final String MESSAGE_STOCK_FAILED_STOCK_NULL = "库存商品不存在"; public static final String MESSAGE_STOCK_FAILED_NUMS_NOT_ENOUGH = "需要扣减的数量大于库存商品数量"; public static final String MESSAGE_USER_FAILED_STOCKID_NULL = "用户id不能为空"; public static final String MESSAGE_USER_FAILED_USER_NULL = "不保存空的用户数据"; /** * 服务资源 */ public static final Long DATA_CENTER_ID = 3L; public static final Long MACHINE_ID = 10L; /** * 邮件服务 */ public static final String EMAIL_SUBJECT = "恭喜您!商品抢购成功!"; public static final String EMAIL_CONTANT = "您抢购的商品详情为:http://127.0.0.1:8080/flashsale/order/query/%s " + ",请在15分钟内点击该链接进行支付。如未支付,则视为放弃购买。"; }
UTF-8
Java
2,823
java
Constant.java
Java
[ { "context": ".common;\n\n/**\n * Date 2020/11/16 7:54 下午\n * Author le\n */\npublic class Constant {\n\n /**\n * 返回结果\n", "end": 78, "score": 0.6621218323707581, "start": 76, "tag": "USERNAME", "value": "le" }, { "context": "ic final String EMAIL_CONTANT = \"您抢购的商品详情为:http://127.0.0.1:8080/flashsale/order/query/%s \"\n + \",请", "end": 2154, "score": 0.944203794002533, "start": 2145, "tag": "IP_ADDRESS", "value": "127.0.0.1" } ]
null
[]
package com.le.flashsale.common; /** * Date 2020/11/16 7:54 下午 * Author le */ public class Constant { /** * 返回结果 */ public static final String SUCCESS = "success"; public static final String FAIL = "fail"; /** * 请求相关 */ public static final String HTTP_PREFIX = "flashsale"; // 请求前缀 /** * Redis 相关 */ public static final String REDIS_PREFIX_ADD_ORDER = "FLASH_SALE_ADD_ORDER_"; // 用户针对某个商品是否执行过下单操作 public static final String REDIS_PREFIX_ACTIVITY_STOCK_NUMS = "FLASH_SALE_ACTIVITY_STOCK_NUMS_"; // 活动涉及的库存量 public static final String REDIS_PREFIX_ACTIVITY_STOCK_STARTTIME = "FLASH_SALE_ACTIVITY_STOCK_STARTTIME_"; // 活动涉及的开始时间 public static final String REDIS_PREFIX_STOCK_ = "FLASH_SALE_STOCK_"; // 库存锁前缀 /** * 提示语句相关 */ public static final String MESSAGE_STOCK_BASE_PARAM_NULL = "接口入参不能为空"; public static final String MESSAGE_ORDER_SUBMITED = "请稍等,您的订单已在排队中,中签会收到邮件通知,请点击邮件中的链接查看具体详情"; public static final String MESSAGE_ORDER_FAILED_1 = "您已提交过订单,无须再次提交"; public static final String MESSAGE_ORDER_FAILED_2 = "实在抱歉,商品已售空,请15分钟之后再次尝试,抢购未支付的订单"; public static final String MESSAGE_ORDER_FAILED_3 = "该活动不存在,请稍后再试"; public static final String MESSAGE_STOCK_FAILED_STOCKID_NULL = "库存id不能为空"; public static final String MESSAGE_STOCK_FAILED_USERID_NULL = "用户id不能为空"; public static final String MESSAGE_STOCK_FAILED_NUMS_NULL = "扣减库存数量不能为空"; public static final String MESSAGE_STOCK_FAILED_NUMS_ERROR = "扣减库存数量只能为正整数"; public static final String MESSAGE_STOCK_FAILED_STOCK_NULL = "库存商品不存在"; public static final String MESSAGE_STOCK_FAILED_NUMS_NOT_ENOUGH = "需要扣减的数量大于库存商品数量"; public static final String MESSAGE_USER_FAILED_STOCKID_NULL = "用户id不能为空"; public static final String MESSAGE_USER_FAILED_USER_NULL = "不保存空的用户数据"; /** * 服务资源 */ public static final Long DATA_CENTER_ID = 3L; public static final Long MACHINE_ID = 10L; /** * 邮件服务 */ public static final String EMAIL_SUBJECT = "恭喜您!商品抢购成功!"; public static final String EMAIL_CONTANT = "您抢购的商品详情为:http://127.0.0.1:8080/flashsale/order/query/%s " + ",请在15分钟内点击该链接进行支付。如未支付,则视为放弃购买。"; }
2,823
0.688254
0.674408
60
36.299999
37.157009
123
false
false
0
0
0
0
0
0
0.416667
false
false
10
f6ae91c21e7627d41569922c59e37f8533de7749
19,018,115,247,155
a3ae982e7129859c0646f156f0c09801b751b62b
/src/main/java/com/devspecops/vsts/VstsHttp.java
663747e542d1ce5e21443a6f8dea676a668c5453
[]
no_license
testep02/buster
https://github.com/testep02/buster
a4c6bcf311216686c033deb045f7ce79e8d93794
8f7e31a815dc8cba9b5995165ecfd7bf09e5bdf3
refs/heads/master
2020-03-13T03:48:58.855000
2018-05-15T18:54:39
2018-05-15T18:54:39
130,857,038
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.devspecops.vsts; import com.amazonaws.util.IOUtils; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import org.apache.commons.codec.binary.Base64; import org.apache.http.HttpEntity; import org.apache.http.HttpHeaders; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * * @author EstepTravis */ @Component public class VstsHttp { private VstsConfig vstsConfig; private String vstsCollectionUrl; public VstsHttp() { vstsConfig = new VstsConfig(); vstsConfig.setAuthToken("oggrxnghhk5xqfap3ioqlgvfitzx54ze7ukledugzkvitijr6cxa"); vstsConfig.setOrgName("getbeyond"); vstsConfig.setCollection("DefaultCollection"); } public VstsCollection getCollection() { VstsCollection collection = null; System.out.println("CONFIG VALUE: "); System.out.println(vstsConfig.getOrgName()); try { ObjectMapper objMapper = new ObjectMapper(); collection = objMapper.readValue( getVstsProjectsJson(), VstsCollection.class); } catch (IOException | NullPointerException ioe) { System.out.println("There was an error getting collection data:"); System.out.println(ioe.getMessage()); } return collection; } public /*VstsRepositoryCollection*/ void getRepoCollection() { } private byte[] getVstsProjectsJson() { int statusCode = 0; byte[] jsonData = null; HttpGet request = new HttpGet(getProjectsUrl()); String authHeader = getAuthHeader(); request.setHeader(HttpHeaders.AUTHORIZATION, authHeader); HttpClient client = HttpClientBuilder.create().build(); try { HttpResponse response = client.execute(request); statusCode = response.getStatusLine().getStatusCode(); if(statusCode == 200) { HttpEntity entity = response.getEntity(); if(null != entity) { InputStream ios = entity.getContent(); String content = IOUtils.toString(ios); jsonData = content.getBytes(); } } } catch( IOException | UnsupportedOperationException ioe) { System.out.println("There was an error getting VSTS Projects."); System.out.println(ioe.getMessage()); } return jsonData; } private String getProjectsUrl() { StringBuilder sb = new StringBuilder(); sb.append("https://") .append(vstsConfig.getOrgName()) .append(".visualstudio.com/") .append(vstsConfig.getCollection()) .append("/_apis/projects"); System.out.println("Collection URL: "); System.out.println(sb.toString()); return sb.toString(); } private String getAuthHeader() { StringBuilder sb = new StringBuilder(); sb.append(vstsConfig.getUsername()) .append(":") .append(vstsConfig.getAuthToken()); byte[] encodedAuth = Base64.encodeBase64( sb.toString().getBytes( Charset.forName("US-ASCII"))); String authHeader = "Basic " + new String(encodedAuth); return authHeader; } }
UTF-8
Java
4,106
java
VstsHttp.java
Java
[ { "context": "ework.stereotype.Component;\r\n\r\n/**\r\n *\r\n * @author EstepTravis\r\n */\r\n\r\n@Component\r\npublic class VstsHttp {\r\n ", "end": 855, "score": 0.9926299452781677, "start": 844, "tag": "USERNAME", "value": "EstepTravis" }, { "context": "w VstsConfig();\r\n vstsConfig.setAuthToken(\"oggrxnghhk5xqfap3ioqlgvfitzx54ze7ukledugzkvitijr6cxa\");\r\n vstsConfig.setOrgName(\"getbeyond\");\r\n", "end": 1144, "score": 0.995007336139679, "start": 1092, "tag": "KEY", "value": "oggrxnghhk5xqfap3ioqlgvfitzx54ze7ukledugzkvitijr6cxa" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.devspecops.vsts; import com.amazonaws.util.IOUtils; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import org.apache.commons.codec.binary.Base64; import org.apache.http.HttpEntity; import org.apache.http.HttpHeaders; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * * @author EstepTravis */ @Component public class VstsHttp { private VstsConfig vstsConfig; private String vstsCollectionUrl; public VstsHttp() { vstsConfig = new VstsConfig(); vstsConfig.setAuthToken("<KEY>"); vstsConfig.setOrgName("getbeyond"); vstsConfig.setCollection("DefaultCollection"); } public VstsCollection getCollection() { VstsCollection collection = null; System.out.println("CONFIG VALUE: "); System.out.println(vstsConfig.getOrgName()); try { ObjectMapper objMapper = new ObjectMapper(); collection = objMapper.readValue( getVstsProjectsJson(), VstsCollection.class); } catch (IOException | NullPointerException ioe) { System.out.println("There was an error getting collection data:"); System.out.println(ioe.getMessage()); } return collection; } public /*VstsRepositoryCollection*/ void getRepoCollection() { } private byte[] getVstsProjectsJson() { int statusCode = 0; byte[] jsonData = null; HttpGet request = new HttpGet(getProjectsUrl()); String authHeader = getAuthHeader(); request.setHeader(HttpHeaders.AUTHORIZATION, authHeader); HttpClient client = HttpClientBuilder.create().build(); try { HttpResponse response = client.execute(request); statusCode = response.getStatusLine().getStatusCode(); if(statusCode == 200) { HttpEntity entity = response.getEntity(); if(null != entity) { InputStream ios = entity.getContent(); String content = IOUtils.toString(ios); jsonData = content.getBytes(); } } } catch( IOException | UnsupportedOperationException ioe) { System.out.println("There was an error getting VSTS Projects."); System.out.println(ioe.getMessage()); } return jsonData; } private String getProjectsUrl() { StringBuilder sb = new StringBuilder(); sb.append("https://") .append(vstsConfig.getOrgName()) .append(".visualstudio.com/") .append(vstsConfig.getCollection()) .append("/_apis/projects"); System.out.println("Collection URL: "); System.out.println(sb.toString()); return sb.toString(); } private String getAuthHeader() { StringBuilder sb = new StringBuilder(); sb.append(vstsConfig.getUsername()) .append(":") .append(vstsConfig.getAuthToken()); byte[] encodedAuth = Base64.encodeBase64( sb.toString().getBytes( Charset.forName("US-ASCII"))); String authHeader = "Basic " + new String(encodedAuth); return authHeader; } }
4,059
0.59206
0.588164
121
31.900826
22.339382
88
false
false
0
0
0
0
0
0
0.504132
false
false
10
7c38b91b5859341091a3e7d537e069b028e3c8c4
8,220,567,435,203
283c7b9fe12ef58fe389c6141f42fe8e7d6a0099
/SNS/src/main/java/org/kdea/mypage/BoardVO.java
18d0f3ce46615afc1a3bdbee0c32981fcccd9952
[]
no_license
lhgwoo2/MusicSNS
https://github.com/lhgwoo2/MusicSNS
e8785fe84767cd2b9532a402817d79dbde10fef7
bb2a19d5bea5a0852b38a47033cebde9cbbcc74b
refs/heads/master
2021-01-11T09:20:52.016000
2017-08-22T00:47:18
2017-08-22T00:47:18
77,001,596
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.kdea.mypage; public class BoardVO { private int num; private String title; private java.sql.Date regDate; private String author; private String genre; private int cnt; private int active; private int likes; private String contents; private String select; public int getNum() { return num; } public void setNum(int num) { this.num = num; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public java.sql.Date getRegDate() { return regDate; } public void setRegDate(java.sql.Date regDate) { this.regDate = regDate; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getGenre() { return genre; } public void setGenre(String genre) { this.genre = genre; } public int getCnt() { return cnt; } public void setCnt(int cnt) { this.cnt = cnt; } public int getActive() { return active; } public void setActive(int active) { this.active = active; } public int getLikes() { return likes; } public void setLikes(int likes) { this.likes = likes; } public String getContents() { return contents; } public void setContents(String contents) { this.contents = contents; } public String getSelect() { return select; } public void setSelect(String select) { this.select = select; } }
UTF-8
Java
1,479
java
BoardVO.java
Java
[]
null
[]
package org.kdea.mypage; public class BoardVO { private int num; private String title; private java.sql.Date regDate; private String author; private String genre; private int cnt; private int active; private int likes; private String contents; private String select; public int getNum() { return num; } public void setNum(int num) { this.num = num; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public java.sql.Date getRegDate() { return regDate; } public void setRegDate(java.sql.Date regDate) { this.regDate = regDate; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getGenre() { return genre; } public void setGenre(String genre) { this.genre = genre; } public int getCnt() { return cnt; } public void setCnt(int cnt) { this.cnt = cnt; } public int getActive() { return active; } public void setActive(int active) { this.active = active; } public int getLikes() { return likes; } public void setLikes(int likes) { this.likes = likes; } public String getContents() { return contents; } public void setContents(String contents) { this.contents = contents; } public String getSelect() { return select; } public void setSelect(String select) { this.select = select; } }
1,479
0.652468
0.652468
78
16.961538
12.642463
48
false
false
0
0
0
0
0
0
1.589744
false
false
10
b14650282d110616b484bb4f86c0e4f1b4ec7d37
10,196,252,365,101
78ae061b453e7cf80d55ce9359bb4708675963c7
/api/D8DateUtils.java
dccd092e9ffe91fd91102cd7d290d36072bcd15d
[ "Apache-2.0" ]
permissive
sylvainpennec/D8API
https://github.com/sylvainpennec/D8API
43298358d5f5c722317171c4661b73fd210346c8
5980216f3981cb4334ccc2d0c23a7dce8c42cc7d
refs/heads/master
2016-08-09T04:27:44.022000
2016-03-16T17:14:33
2016-03-16T17:14:33
54,051,470
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.dict8.api; import com.dict8.ohs.R; import java.text.DateFormat; import java.text.SimpleDateFormat; /** * Created by spennec on 09/12/2015. */ public class D8DateUtils { private static final String TAG = D8DateUtils.class.getSimpleName(); public static final DateFormat DATE_FORMAT = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); public static final String DF_yyyyMMdd = "yyyy/MM/dd"; public static final String DF_yyyyMMddHHmmss = "yyyyMMddHHmmss"; private static final int SECOND_MILLIS = 1000; private static final int MINUTE_MILLIS = 60 * SECOND_MILLIS; private static final int HOUR_MILLIS = 60 * MINUTE_MILLIS; private static final int DAY_MILLIS = 24 * HOUR_MILLIS; private static final int MONTH_MILLIS = 30 * DAY_MILLIS; private static final int YEAR_MILLIS = 365 * MONTH_MILLIS; public static String getTimeAgo(long time) { if (time < 1000000000000L) { // if timestamp given in seconds, convert to millis time *= 1000; } //long now = getCurrentTime(ctx); long now = System.currentTimeMillis(); if (time > now || time <= 0) { D8Log.w(TAG, "time=" + time + ", now=" + now + ", [time > now || time <= 0], [now - time = " + (now - time) + "]"); return ""; } else { D8Log.d(TAG, "time=" + time + ", now=" + now + ", [time > now || time <= 0], [now - time = " + (now - time) + "]"); } final long diff = Math.abs(now - time); double seconds = diff / 1000; double minutes = seconds / 60; double hours = minutes / 60; double days = hours / 24; double weeks = days / 7; double months = days / 30.5; // ??? double years = days / 365; if (diff < MINUTE_MILLIS) { return D8API.getContext().getString(R.string.just_now); //return "just now"; } else if (diff < 2 * MINUTE_MILLIS) { return D8API.getContext().getString(R.string.a_minute_ago); //return "a minute ago"; } else if (diff < 50 * MINUTE_MILLIS) { return String.format(D8API.getContext().getString(R.string.xxx_minutes_ago), diff / MINUTE_MILLIS); //return diff / MINUTE_MILLIS + " minutes ago"; } else if (diff < 90 * MINUTE_MILLIS) { return D8API.getContext().getString(R.string.an_hour_ago); //return "an hour ago"; } else if (diff < 24 * HOUR_MILLIS) { return String.format(D8API.getContext().getString(R.string.xxx_hours_ago), diff / HOUR_MILLIS); //return diff / HOUR_MILLIS + " hours ago"; } else if (diff < 48 * HOUR_MILLIS) { return D8API.getContext().getString(R.string.yesterday); //return "yesterday"; } // else // { // return diff / DAY_MILLIS + " days ago"; // } else if (days < 7) { return String.format(D8API.getContext().getString(R.string.xxx_days_ago), diff / DAY_MILLIS); //return diff / DAY_MILLIS + " days ago"; } else if (days < 15) { return D8API.getContext().getString(R.string.last_week); //return " last week"; } else if (days < 30) { return String.format(D8API.getContext().getString(R.string.xxx_days_ago), diff / DAY_MILLIS); //return diff / (DAY_MILLIS * 7) + " weeks ago"; } //else if (days < 45) else if (days < 60) { return D8API.getContext().getString(R.string.last_month); //return "last month"; } else if (days < 365) { return String.format(D8API.getContext().getString(R.string.xxx_months_ago), Math.abs(diff / MONTH_MILLIS)); //return diff / MONTH_MILLIS + " months ago"; } else if (years < 1.5) { return D8API.getContext().getString(R.string.last_year); //return "last year"; } else if (years < 6) { return String.format(D8API.getContext().getString(R.string.xxx_years_ago), diff / YEAR_MILLIS); //return diff / YEAR_MILLIS + " years ago"; } else { return String.format(D8API.getContext().getString(R.string.a_long_long_time_ago), diff / DAY_MILLIS); //return "a long long time ago (" + (diff / DAY_MILLIS) + " days)"; } } }
UTF-8
Java
4,621
java
D8DateUtils.java
Java
[ { "context": "ort java.text.SimpleDateFormat;\n\n/**\n * Created by spennec on 09/12/2015.\n */\npublic class D8DateUtils\n{\n\n ", "end": 139, "score": 0.9996523261070251, "start": 132, "tag": "USERNAME", "value": "spennec" } ]
null
[]
package com.dict8.api; import com.dict8.ohs.R; import java.text.DateFormat; import java.text.SimpleDateFormat; /** * Created by spennec on 09/12/2015. */ public class D8DateUtils { private static final String TAG = D8DateUtils.class.getSimpleName(); public static final DateFormat DATE_FORMAT = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); public static final String DF_yyyyMMdd = "yyyy/MM/dd"; public static final String DF_yyyyMMddHHmmss = "yyyyMMddHHmmss"; private static final int SECOND_MILLIS = 1000; private static final int MINUTE_MILLIS = 60 * SECOND_MILLIS; private static final int HOUR_MILLIS = 60 * MINUTE_MILLIS; private static final int DAY_MILLIS = 24 * HOUR_MILLIS; private static final int MONTH_MILLIS = 30 * DAY_MILLIS; private static final int YEAR_MILLIS = 365 * MONTH_MILLIS; public static String getTimeAgo(long time) { if (time < 1000000000000L) { // if timestamp given in seconds, convert to millis time *= 1000; } //long now = getCurrentTime(ctx); long now = System.currentTimeMillis(); if (time > now || time <= 0) { D8Log.w(TAG, "time=" + time + ", now=" + now + ", [time > now || time <= 0], [now - time = " + (now - time) + "]"); return ""; } else { D8Log.d(TAG, "time=" + time + ", now=" + now + ", [time > now || time <= 0], [now - time = " + (now - time) + "]"); } final long diff = Math.abs(now - time); double seconds = diff / 1000; double minutes = seconds / 60; double hours = minutes / 60; double days = hours / 24; double weeks = days / 7; double months = days / 30.5; // ??? double years = days / 365; if (diff < MINUTE_MILLIS) { return D8API.getContext().getString(R.string.just_now); //return "just now"; } else if (diff < 2 * MINUTE_MILLIS) { return D8API.getContext().getString(R.string.a_minute_ago); //return "a minute ago"; } else if (diff < 50 * MINUTE_MILLIS) { return String.format(D8API.getContext().getString(R.string.xxx_minutes_ago), diff / MINUTE_MILLIS); //return diff / MINUTE_MILLIS + " minutes ago"; } else if (diff < 90 * MINUTE_MILLIS) { return D8API.getContext().getString(R.string.an_hour_ago); //return "an hour ago"; } else if (diff < 24 * HOUR_MILLIS) { return String.format(D8API.getContext().getString(R.string.xxx_hours_ago), diff / HOUR_MILLIS); //return diff / HOUR_MILLIS + " hours ago"; } else if (diff < 48 * HOUR_MILLIS) { return D8API.getContext().getString(R.string.yesterday); //return "yesterday"; } // else // { // return diff / DAY_MILLIS + " days ago"; // } else if (days < 7) { return String.format(D8API.getContext().getString(R.string.xxx_days_ago), diff / DAY_MILLIS); //return diff / DAY_MILLIS + " days ago"; } else if (days < 15) { return D8API.getContext().getString(R.string.last_week); //return " last week"; } else if (days < 30) { return String.format(D8API.getContext().getString(R.string.xxx_days_ago), diff / DAY_MILLIS); //return diff / (DAY_MILLIS * 7) + " weeks ago"; } //else if (days < 45) else if (days < 60) { return D8API.getContext().getString(R.string.last_month); //return "last month"; } else if (days < 365) { return String.format(D8API.getContext().getString(R.string.xxx_months_ago), Math.abs(diff / MONTH_MILLIS)); //return diff / MONTH_MILLIS + " months ago"; } else if (years < 1.5) { return D8API.getContext().getString(R.string.last_year); //return "last year"; } else if (years < 6) { return String.format(D8API.getContext().getString(R.string.xxx_years_ago), diff / YEAR_MILLIS); //return diff / YEAR_MILLIS + " years ago"; } else { return String.format(D8API.getContext().getString(R.string.a_long_long_time_ago), diff / DAY_MILLIS); //return "a long long time ago (" + (diff / DAY_MILLIS) + " days)"; } } }
4,621
0.537546
0.514824
136
32.97794
30.952873
127
false
false
0
0
0
0
0
0
0.580882
false
false
10
743f50768bd97e698291ddbea33636531bf290b0
12,833,362,352,278
14caa603f6987f492dbc5d19f8f06822037d8c69
/src/main/java/common/SeleniumDriverHelper.java
44cc31e6be2c3102aced5a690f3f7b326faa311a
[]
no_license
dipjyotimetia/MA_IOS
https://github.com/dipjyotimetia/MA_IOS
92521922f7164ec8d3d1e5a0f9568a5b07862e9f
d20979f0f60bb87b60fb0424ad2c6c82e59f501c
refs/heads/master
2020-03-14T07:20:16.935000
2018-04-29T14:46:33
2018-04-29T14:46:33
131,502,731
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package common; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.FluentWait; import org.openqa.selenium.support.ui.WebDriverWait; import java.io.InputStream; import java.time.Duration; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.Function; public class SeleniumDriverHelper { protected MetDevice metDevice; protected final int DEFAULT_FLUENTWAIT_TIMEOUT = 20; private final int DEFAULT_THRESHOLD = 20; private InputStream inputStream = null; private Properties properties = null; static Dictionary<String, Dictionary<String, String>> testData = new Hashtable<String, Dictionary<String, String>>(); public final String CONFIG_FILE = "src/main/resources/config.properties"; public SeleniumDriverHelper(MetDevice metDevice) { this.metDevice = metDevice; } public final WebElement fluentWait(final By locator, long Timeout) { metDevice.getDriver().manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS); WebElement element = (WebElement) (new WebDriverWait(metDevice.getDriver(), Timeout)) .until(ExpectedConditions.presenceOfElementLocated(locator)); metDevice.getDriver().manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); return element; } protected List<WebElement> fluentWaitForXpath(final By locator,long Timeout){ metDevice.getDriver().manage().timeouts().implicitlyWait(0,TimeUnit.SECONDS); FluentWait<WebDriver> wait = new FluentWait<WebDriver>( metDevice.getDriver()) .withTimeout(Duration.ofSeconds(Timeout)) .pollingEvery(Duration.ofMillis(500)) .ignoring(NoSuchElementException.class); List<WebElement> webElement = wait.until(new Function<WebDriver, List<WebElement>>() { @Override public List<WebElement> apply(WebDriver webDriver) { return webDriver.findElement(locator); } }); metDevice.getDriver().manage().timeouts().implicitlyWait(5,TimeUnit.SECONDS); return webElement; } protected final WebElement getElement(By object) throws Exception{ try { return fluentWait(object,DEFAULT_FLUENTWAIT_TIMEOUT); } catch (Exception e){ e.printStackTrace(); throw new Exception("Element not found"); } } protected List<WebElement> getElements(By object) throws Exception{ try { return fluentWaitForXpath(object,DEFAULT_FLUENTWAIT_TIMEOUT); } catch (Exception e){ e.printStackTrace(); throw new Exception("Element not found"); } } protected final WebElement getElement(By object,long elementWaitTime) throws Exception{ try { return fluentWait(object,elementWaitTime); } catch (Exception e){ e.printStackTrace(); throw new Exception("Element not found"); } } public boolean checkElementExists(By fieldValue) throws Exception{ WebElement elementName = getElement(fieldValue,DEFAULT_FLUENTWAIT_TIMEOUT); if (elementName == null){ return false; } else { return true; } } public void swipeScreen(String startXY,String endXY){ String startX =(startXY.replace(",",",").split("%"))[0]; String startY = (startXY.replace(",",",").split("%"))[1]; String endX =(endXY.replace(",",",").split("%"))[0]; String endY = (endXY.replace(",",",").split("%"))[1]; } private int getX(int x){ return (int) ((metDevice.getDriver().manage().window().getSize().height*x)/100); } private int getY(int y){ return (int) ((metDevice.getDriver().manage().window().getSize().height*y)/100); } public void populatePasscodeFiled(String data) throws Exception{ Thread.sleep(2000); metDevice.getDriver().getKeyboard().sendKeys(data); Thread.sleep(2000); } public void dragUpFivePercent(){ final Map<String,Object> params = new HashMap<>(); params.put("location","20%,61%,20%,50%,80%,50%,80%,54%"); params.put("duration","1"); metDevice.getDriver().executeScript("mobile:touch:drag",params); } }
UTF-8
Java
4,543
java
SeleniumDriverHelper.java
Java
[]
null
[]
package common; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.FluentWait; import org.openqa.selenium.support.ui.WebDriverWait; import java.io.InputStream; import java.time.Duration; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.Function; public class SeleniumDriverHelper { protected MetDevice metDevice; protected final int DEFAULT_FLUENTWAIT_TIMEOUT = 20; private final int DEFAULT_THRESHOLD = 20; private InputStream inputStream = null; private Properties properties = null; static Dictionary<String, Dictionary<String, String>> testData = new Hashtable<String, Dictionary<String, String>>(); public final String CONFIG_FILE = "src/main/resources/config.properties"; public SeleniumDriverHelper(MetDevice metDevice) { this.metDevice = metDevice; } public final WebElement fluentWait(final By locator, long Timeout) { metDevice.getDriver().manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS); WebElement element = (WebElement) (new WebDriverWait(metDevice.getDriver(), Timeout)) .until(ExpectedConditions.presenceOfElementLocated(locator)); metDevice.getDriver().manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); return element; } protected List<WebElement> fluentWaitForXpath(final By locator,long Timeout){ metDevice.getDriver().manage().timeouts().implicitlyWait(0,TimeUnit.SECONDS); FluentWait<WebDriver> wait = new FluentWait<WebDriver>( metDevice.getDriver()) .withTimeout(Duration.ofSeconds(Timeout)) .pollingEvery(Duration.ofMillis(500)) .ignoring(NoSuchElementException.class); List<WebElement> webElement = wait.until(new Function<WebDriver, List<WebElement>>() { @Override public List<WebElement> apply(WebDriver webDriver) { return webDriver.findElement(locator); } }); metDevice.getDriver().manage().timeouts().implicitlyWait(5,TimeUnit.SECONDS); return webElement; } protected final WebElement getElement(By object) throws Exception{ try { return fluentWait(object,DEFAULT_FLUENTWAIT_TIMEOUT); } catch (Exception e){ e.printStackTrace(); throw new Exception("Element not found"); } } protected List<WebElement> getElements(By object) throws Exception{ try { return fluentWaitForXpath(object,DEFAULT_FLUENTWAIT_TIMEOUT); } catch (Exception e){ e.printStackTrace(); throw new Exception("Element not found"); } } protected final WebElement getElement(By object,long elementWaitTime) throws Exception{ try { return fluentWait(object,elementWaitTime); } catch (Exception e){ e.printStackTrace(); throw new Exception("Element not found"); } } public boolean checkElementExists(By fieldValue) throws Exception{ WebElement elementName = getElement(fieldValue,DEFAULT_FLUENTWAIT_TIMEOUT); if (elementName == null){ return false; } else { return true; } } public void swipeScreen(String startXY,String endXY){ String startX =(startXY.replace(",",",").split("%"))[0]; String startY = (startXY.replace(",",",").split("%"))[1]; String endX =(endXY.replace(",",",").split("%"))[0]; String endY = (endXY.replace(",",",").split("%"))[1]; } private int getX(int x){ return (int) ((metDevice.getDriver().manage().window().getSize().height*x)/100); } private int getY(int y){ return (int) ((metDevice.getDriver().manage().window().getSize().height*y)/100); } public void populatePasscodeFiled(String data) throws Exception{ Thread.sleep(2000); metDevice.getDriver().getKeyboard().sendKeys(data); Thread.sleep(2000); } public void dragUpFivePercent(){ final Map<String,Object> params = new HashMap<>(); params.put("location","20%,61%,20%,50%,80%,50%,80%,54%"); params.put("duration","1"); metDevice.getDriver().executeScript("mobile:touch:drag",params); } }
4,543
0.64891
0.638785
127
34.771652
29.422577
121
false
false
0
0
0
0
0
0
0.76378
false
false
10
cbe83b629ff932b895e7fcb60b07cd9970585479
4,612,794,893,839
8cfdb1d078cffa5e41387d711e4513afc0cb983b
/app/src/main/java/com/sunnyweather/fsystem/activity/ui/notifications/Project.java
453813d9eb0b5800d5bc8262df19b384c91601fd
[ "Apache-2.0" ]
permissive
feige011/FanluSystem
https://github.com/feige011/FanluSystem
6887cd8f1e4ca7c6116d531561621841654033e5
937ece664d1f9b2007ea3b061e37af261825c495
refs/heads/master
2022-11-24T12:40:24.860000
2020-07-31T00:45:34
2020-07-31T00:45:34
283,906,514
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sunnyweather.fsystem.activity.ui.notifications; public class Project { private String projectName; private String sketchProject; private String mainProject; public Project(String projectName, String sketchProject, String mainProject) { this.projectName = projectName; this.sketchProject = sketchProject; this.mainProject = mainProject; } public String getSketchProject() { return sketchProject; } public void setSketchProject(String sketchProject) { this.sketchProject = sketchProject; } public String getMainProject() { return mainProject; } public void setMainProject(String mainProject) { this.mainProject = mainProject; } public String getProjectName() { return projectName; } public void setProjectName(String projectName) { this.projectName = projectName; } }
UTF-8
Java
926
java
Project.java
Java
[]
null
[]
package com.sunnyweather.fsystem.activity.ui.notifications; public class Project { private String projectName; private String sketchProject; private String mainProject; public Project(String projectName, String sketchProject, String mainProject) { this.projectName = projectName; this.sketchProject = sketchProject; this.mainProject = mainProject; } public String getSketchProject() { return sketchProject; } public void setSketchProject(String sketchProject) { this.sketchProject = sketchProject; } public String getMainProject() { return mainProject; } public void setMainProject(String mainProject) { this.mainProject = mainProject; } public String getProjectName() { return projectName; } public void setProjectName(String projectName) { this.projectName = projectName; } }
926
0.684665
0.684665
37
24.027027
21.546288
82
false
false
0
0
0
0
0
0
0.405405
false
false
10
e8f5933736fc94be2dc9e4ee8dab26ba1014cc49
28,793,460,765,975
d0ff4bb30c88b71666cd891271cea3393715fd25
/base-web/src/main/java/com/example/base/utils/RedisUtils.java
1462ec1f43aae72467d2dc6965cd1c6d022f305b
[]
no_license
javaleekoy/base-demo
https://github.com/javaleekoy/base-demo
89a9127a2dd9e19ed5654d484cb4271f185f9546
07ce85f701dbb5968cde4be4aab17da8df0f18db
refs/heads/master
2020-03-28T17:23:10.095000
2018-10-22T07:32:00
2018-10-22T07:32:00
148,784,072
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.base.utils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import redis.clients.jedis.*; import redis.clients.jedis.params.geo.GeoRadiusParam; import java.util.List; import java.util.Map; import java.util.Set; /** * @author peramdy on 2018/10/19. */ @Component public class RedisUtils { @Autowired private JedisPool jedisPool; public String set(String key, String value) { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.set(key, value); } catch (Exception e) { e.printStackTrace(); } return result; } public String set(byte[] key, byte[] value) { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.set(key, value); } catch (Exception e) { e.printStackTrace(); } return result; } public String set(String key, String value, String nxxx, String expx, long time) { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.set(key, value, nxxx, expx, time); } catch (Exception e) { e.printStackTrace(); } return result; } public String get(String key) { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.get(key); } catch (Exception e) { e.printStackTrace(); } return result; } public byte[] get(byte[] key) { byte[] result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.get(key); } catch (Exception e) { e.printStackTrace(); } return result; } public Long exists(String... keys) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.exists(keys); } catch (Exception e) { e.printStackTrace(); } return result; } public Boolean exists(String key) { Boolean result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.exists(key); } catch (Exception e) { e.printStackTrace(); } return result; } public Long del(String... keys) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.del(keys); } catch (Exception e) { e.printStackTrace(); } return result; } public Long del(String key) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.del(key); } catch (Exception e) { e.printStackTrace(); } return result; } public String type(String key) { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.type(key); } catch (Exception e) { e.printStackTrace(); } return result; } public Set<String> keys(String pattern) { Set<String> results = null; try (Jedis jedis = jedisPool.getResource()) { results = jedis.keys(pattern); } catch (Exception e) { e.printStackTrace(); } return results; } public String randomKey() { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.randomKey(); } catch (Exception e) { e.printStackTrace(); } return result; } public String rename(String oldkey, String newkey) { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.rename(oldkey, newkey); } catch (Exception e) { e.printStackTrace(); } return result; } public Long renamenx(String oldkey, String newkey) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.renamenx(oldkey, newkey); } catch (Exception e) { e.printStackTrace(); } return result; } public Long expire(String key, int seconds) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.expire(key, seconds); } catch (Exception e) { e.printStackTrace(); } return result; } public Long expireAt(String key, long unixTime) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.expireAt(key, unixTime); } catch (Exception e) { e.printStackTrace(); } return result; } public Long ttl(String key) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.ttl(key); } catch (Exception e) { e.printStackTrace(); } return result; } public Long move(String key, int dbIndex) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.move(key, dbIndex); } catch (Exception e) { e.printStackTrace(); } return result; } public String getSet(String key, String value) { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.getSet(key, value); } catch (Exception e) { e.printStackTrace(); } return result; } public List<String> mget(String... keys) { List<String> result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.mget(keys); } catch (Exception e) { e.printStackTrace(); } return result; } public Long setnx(String key, String value) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.setnx(key, value); } catch (Exception e) { e.printStackTrace(); } return result; } public String setex(String key, int seconds, String value) { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.setex(key, seconds, value); } catch (Exception e) { e.printStackTrace(); } return result; } public String mset(String... keysvalues) { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.mset(keysvalues); } catch (Exception e) { e.printStackTrace(); } return result; } public Long msetnx(String... keysvalues) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.msetnx(keysvalues); } catch (Exception e) { e.printStackTrace(); } return result; } public Long decrBy(String key, long integer) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.decrBy(key, integer); } catch (Exception e) { e.printStackTrace(); } return result; } public Long decr(String key) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.decr(key); } catch (Exception e) { e.printStackTrace(); } return result; } public Long incrBy(String key, long integer) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.incrBy(key, integer); } catch (Exception e) { e.printStackTrace(); } return result; } public Double incrByFloat(String key, double value) { Double result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.incrByFloat(key, value); } catch (Exception e) { e.printStackTrace(); } return result; } public Long incr(String key) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.incr(key); } catch (Exception e) { e.printStackTrace(); } return result; } public Long append(String key, String value) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.append(key, value); } catch (Exception e) { e.printStackTrace(); } return result; } public String substr(String key, int start, int end) { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.substr(key, start, end); } catch (Exception e) { e.printStackTrace(); } return result; } public Long hset(String key, String field, String value) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.hset(key, field, value); } catch (Exception e) { e.printStackTrace(); } return result; } public String hget(String key, String field) { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.hget(key, field); } catch (Exception e) { e.printStackTrace(); } return result; } public Long hsetnx(String key, String field, String value) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.hsetnx(key, field, value); } catch (Exception e) { e.printStackTrace(); } return result; } public String hmset(String key, Map<String, String> hash) { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.hmset(key, hash); } catch (Exception e) { e.printStackTrace(); } return result; } public List<String> hmget(String key, String... fields) { List<String> result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.hmget(key, fields); } catch (Exception e) { e.printStackTrace(); } return result; } public Long hincrBy(String key, String field, long value) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.hincrBy(key, field, value); } catch (Exception e) { e.printStackTrace(); } return result; } public Double hincrByFloat(String key, String field, double value) { Double result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.hincrByFloat(key, field, value); } catch (Exception e) { e.printStackTrace(); } return result; } public Boolean hexists(String key, String field) { Boolean result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.hexists(key, field); } catch (Exception e) { e.printStackTrace(); } return result; } public Long hdel(String key, String... fields) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.hdel(key, fields); } catch (Exception e) { e.printStackTrace(); } return result; } public Long hlen(String key) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.hlen(key); } catch (Exception e) { e.printStackTrace(); } return result; } public Set<String> hkeys(String key) { Set<String> result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.hkeys(key); } catch (Exception e) { e.printStackTrace(); } return result; } public List<String> hvals(String key) { List<String> result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.hvals(key); } catch (Exception e) { e.printStackTrace(); } return result; } public Map<String, String> hgetAll(String key) { Map<String, String> result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.hgetAll(key); } catch (Exception e) { e.printStackTrace(); } return result; } public Long rpush(String key, String... strings) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.rpush(key, strings); } catch (Exception e) { e.printStackTrace(); } return result; } public Long lpush(String key, String... strings) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.lpush(key, strings); } catch (Exception e) { e.printStackTrace(); } return result; } public Long llen(String key) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.llen(key); } catch (Exception e) { e.printStackTrace(); } return result; } public List<String> lrange(String key, long start, long end) { List<String> result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.lrange(key, start, end); } catch (Exception e) { e.printStackTrace(); } return result; } public String ltrim(String key, long start, long end) { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.ltrim(key, start, end); } catch (Exception e) { e.printStackTrace(); } return result; } public String lindex(String key, long index) { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.lindex(key, index); } catch (Exception e) { e.printStackTrace(); } return result; } public String lset(String key, long index, String value) { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.lset(key, index, value); } catch (Exception e) { e.printStackTrace(); } return result; } public Long lrem(String key, long count, String value) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.lrem(key, count, value); } catch (Exception e) { e.printStackTrace(); } return result; } public String lpop(String key) { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.lpop(key); } catch (Exception e) { e.printStackTrace(); } return result; } public String rpop(String key) { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.rpop(key); } catch (Exception e) { e.printStackTrace(); } return result; } public String rpoplpush(String srckey, String dstkey) { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.rpoplpush(srckey, dstkey); } catch (Exception e) { e.printStackTrace(); } return result; } public Long sadd(String key, String... members) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.sadd(key, members); } catch (Exception e) { e.printStackTrace(); } return result; } public Set<String> smembers(String key) { Set<String> result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.smembers(key); } catch (Exception e) { e.printStackTrace(); } return result; } public Long srem(String key, String... members) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.srem(key, members); } catch (Exception e) { e.printStackTrace(); } return result; } public String spop(String key) { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.spop(key); } catch (Exception e) { e.printStackTrace(); } return result; } public Set<String> spop(String key, long count) { Set<String> result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.spop(key, count); } catch (Exception e) { e.printStackTrace(); } return result; } public Long smove(String srckey, String dstkey, String member) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.smove(srckey, dstkey, member); } catch (Exception e) { e.printStackTrace(); } return result; } public Long scard(String key) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.scard(key); } catch (Exception e) { e.printStackTrace(); } return result; } public Boolean sismember(String key, String member) { Boolean result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.sismember(key, member); } catch (Exception e) { e.printStackTrace(); } return result; } public Set<String> sinter(String... keys) { Set<String> result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.sinter(keys); } catch (Exception e) { e.printStackTrace(); } return result; } public Long sinterstore(String dstkey, String... keys) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.sinterstore(dstkey, keys); } catch (Exception e) { e.printStackTrace(); } return result; } public Set<String> sunion(String... keys) { Set<String> result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.sunion(keys); } catch (Exception e) { e.printStackTrace(); } return result; } public Set<Tuple> zrevrangeByScoreWithScores(String key, String max, String min) { Set<Tuple> result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.zrevrangeByScoreWithScores(key, max, min); } catch (Exception e) { e.printStackTrace(); } return result; } public Long zremrangeByRank(String key, long start, long end) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.zremrangeByRank(key, start, end); } catch (Exception e) { e.printStackTrace(); } return result; } public Long zremrangeByScore(String key, double start, double end) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.zremrangeByScore(key, start, end); } catch (Exception e) { e.printStackTrace(); } return result; } public Long zremrangeByScore(String key, String start, String end) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.zremrangeByScore(key, start, end); } catch (Exception e) { e.printStackTrace(); } return result; } public Long zunionstore(String dstkey, String... sets) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.zunionstore(dstkey, sets); } catch (Exception e) { e.printStackTrace(); } return result; } public Long zunionstore(String dstkey, ZParams params, String... sets) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.zunionstore(dstkey, params, sets); } catch (Exception e) { e.printStackTrace(); } return result; } public Long zinterstore(String dstkey, String... sets) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.zinterstore(dstkey, sets); } catch (Exception e) { e.printStackTrace(); } return result; } public Long zinterstore(String dstkey, ZParams params, String... sets) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.zinterstore(dstkey, params, sets); } catch (Exception e) { e.printStackTrace(); } return result; } public Long zlexcount(String key, String min, String max) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.zlexcount(key, min, max); } catch (Exception e) { e.printStackTrace(); } return result; } public Set<String> zrangeByLex(String key, String min, String max) { Set<String> result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.zrangeByLex(key, min, max); } catch (Exception e) { e.printStackTrace(); } return result; } public Set<String> zrangeByLex(String key, String min, String max, int offset, int count) { Set<String> result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.zrangeByLex(key, min, max, offset, count); } catch (Exception e) { e.printStackTrace(); } return result; } public Set<String> zrevrangeByLex(String key, String max, String min) { Set<String> result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.zrevrangeByLex(key, max, min); } catch (Exception e) { e.printStackTrace(); } return result; } public Set<String> zrevrangeByLex(String key, String max, String min, int offset, int count) { Set<String> result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.zrevrangeByLex(key, max, min, offset, count); } catch (Exception e) { e.printStackTrace(); } return result; } public Long zremrangeByLex(String key, String min, String max) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.zremrangeByLex(key, min, max); } catch (Exception e) { e.printStackTrace(); } return result; } public Long strlen(String key) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.strlen(key); } catch (Exception e) { e.printStackTrace(); } return result; } public Long lpushx(String key, String... string) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.lpushx(key, string); } catch (Exception e) { e.printStackTrace(); } return result; } public Long persist(String key) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.persist(key); } catch (Exception e) { e.printStackTrace(); } return result; } public Long rpushx(String key, String... string) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.rpushx(key, string); } catch (Exception e) { e.printStackTrace(); } return result; } public String echo(String string) { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.echo(string); } catch (Exception e) { e.printStackTrace(); } return result; } public Long linsert(String key, BinaryClient.LIST_POSITION where, String pivot, String value) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.linsert(key, where, pivot, value); } catch (Exception e) { e.printStackTrace(); } return result; } public String brpoplpush(String source, String destination, int timeout) { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.brpoplpush(source, destination, timeout); } catch (Exception e) { e.printStackTrace(); } return result; } public Boolean setbit(String key, long offset, boolean value) { Boolean result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.setbit(key, offset, value); } catch (Exception e) { e.printStackTrace(); } return result; } public Boolean setbit(String key, long offset, String value) { Boolean result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.setbit(key, offset, value); } catch (Exception e) { e.printStackTrace(); } return result; } public Boolean getbit(String key, long offset) { Boolean result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.getbit(key, offset); } catch (Exception e) { e.printStackTrace(); } return result; } public Long setrange(String key, long offset, String value) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.setrange(key, offset, value); } catch (Exception e) { e.printStackTrace(); } return result; } public String getrange(String key, long startOffset, long endOffset) { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.getrange(key, startOffset, endOffset); } catch (Exception e) { e.printStackTrace(); } return result; } public Long bitpos(String key, boolean value) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.bitpos(key, value); } catch (Exception e) { e.printStackTrace(); } return result; } public Long bitpos(String key, boolean value, BitPosParams params) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.bitpos(key, value, params); } catch (Exception e) { e.printStackTrace(); } return result; } public List<String> configGet(String pattern) { List<String> result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.configGet(pattern); } catch (Exception e) { e.printStackTrace(); } return result; } public String configSet(String parameter, String value) { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.configSet(parameter, value); } catch (Exception e) { e.printStackTrace(); } return result; } public Object eval(String script, int keyCount, String... params) { Object result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.eval(script, keyCount, params); } catch (Exception e) { e.printStackTrace(); } return result; } public void subscribe(JedisPubSub jedisPubSub, String... channels) { try (Jedis jedis = jedisPool.getResource()) { jedis.subscribe(jedisPubSub, channels); } catch (Exception e) { e.printStackTrace(); } } public Long publish(String channel, String message) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.publish(channel, message); } catch (Exception e) { e.printStackTrace(); } return result; } public void psubscribe(JedisPubSub jedisPubSub, String... patterns) { try (Jedis jedis = jedisPool.getResource()) { psubscribe(jedisPubSub, patterns); } catch (Exception e) { e.printStackTrace(); } } public Object eval(String script, List<String> keys, List<String> args) { Object result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.eval(script, keys, args); } catch (Exception e) { e.printStackTrace(); } return result; } public Object eval(String script) { Object result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.eval(script); } catch (Exception e) { e.printStackTrace(); } return result; } public Object evalsha(String script) { Object result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.evalsha(script); } catch (Exception e) { e.printStackTrace(); } return result; } public Object evalsha(String sha1, List<String> keys, List<String> args) { Object result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.evalsha(sha1, keys, args); } catch (Exception e) { e.printStackTrace(); } return result; } public Object evalsha(String sha1, int keyCount, String... params) { Object result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.evalsha(sha1, keyCount, params); } catch (Exception e) { e.printStackTrace(); } return result; } public List<GeoRadiusResponse> georadiusByMember(byte[] key, byte[] member, double radius, GeoUnit unit) { List<GeoRadiusResponse> result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.georadiusByMember(key, member, radius, unit); } catch (Exception e) { e.printStackTrace(); } return result; } public List<GeoRadiusResponse> georadiusByMember(byte[] key, byte[] member, double radius, GeoUnit unit, GeoRadiusParam param) { List<GeoRadiusResponse> result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.georadiusByMember(key, member, radius, unit, param); } catch (Exception e) { e.printStackTrace(); } return result; } public List<byte[]> bitfield(byte[] key, byte[]... arguments) { List<byte[]> result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.bitfield(key, arguments); } catch (Exception e) { e.printStackTrace(); } return result; } public int hashCode() { int result = 0; try (Jedis jedis = jedisPool.getResource()) { result = jedis.hashCode(); } catch (Exception e) { e.printStackTrace(); } return result; } public boolean equals(Object obj) { boolean result = false; try (Jedis jedis = jedisPool.getResource()) { result = jedis.equals(obj); } catch (Exception e) { e.printStackTrace(); } return result; } }
UTF-8
Java
33,076
java
RedisUtils.java
Java
[ { "context": "va.util.Map;\nimport java.util.Set;\n\n/**\n * @author peramdy on 2018/10/19.\n */\n@Component\npublic class RedisU", "end": 320, "score": 0.9995798468589783, "start": 313, "tag": "USERNAME", "value": "peramdy" } ]
null
[]
package com.example.base.utils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import redis.clients.jedis.*; import redis.clients.jedis.params.geo.GeoRadiusParam; import java.util.List; import java.util.Map; import java.util.Set; /** * @author peramdy on 2018/10/19. */ @Component public class RedisUtils { @Autowired private JedisPool jedisPool; public String set(String key, String value) { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.set(key, value); } catch (Exception e) { e.printStackTrace(); } return result; } public String set(byte[] key, byte[] value) { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.set(key, value); } catch (Exception e) { e.printStackTrace(); } return result; } public String set(String key, String value, String nxxx, String expx, long time) { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.set(key, value, nxxx, expx, time); } catch (Exception e) { e.printStackTrace(); } return result; } public String get(String key) { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.get(key); } catch (Exception e) { e.printStackTrace(); } return result; } public byte[] get(byte[] key) { byte[] result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.get(key); } catch (Exception e) { e.printStackTrace(); } return result; } public Long exists(String... keys) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.exists(keys); } catch (Exception e) { e.printStackTrace(); } return result; } public Boolean exists(String key) { Boolean result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.exists(key); } catch (Exception e) { e.printStackTrace(); } return result; } public Long del(String... keys) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.del(keys); } catch (Exception e) { e.printStackTrace(); } return result; } public Long del(String key) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.del(key); } catch (Exception e) { e.printStackTrace(); } return result; } public String type(String key) { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.type(key); } catch (Exception e) { e.printStackTrace(); } return result; } public Set<String> keys(String pattern) { Set<String> results = null; try (Jedis jedis = jedisPool.getResource()) { results = jedis.keys(pattern); } catch (Exception e) { e.printStackTrace(); } return results; } public String randomKey() { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.randomKey(); } catch (Exception e) { e.printStackTrace(); } return result; } public String rename(String oldkey, String newkey) { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.rename(oldkey, newkey); } catch (Exception e) { e.printStackTrace(); } return result; } public Long renamenx(String oldkey, String newkey) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.renamenx(oldkey, newkey); } catch (Exception e) { e.printStackTrace(); } return result; } public Long expire(String key, int seconds) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.expire(key, seconds); } catch (Exception e) { e.printStackTrace(); } return result; } public Long expireAt(String key, long unixTime) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.expireAt(key, unixTime); } catch (Exception e) { e.printStackTrace(); } return result; } public Long ttl(String key) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.ttl(key); } catch (Exception e) { e.printStackTrace(); } return result; } public Long move(String key, int dbIndex) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.move(key, dbIndex); } catch (Exception e) { e.printStackTrace(); } return result; } public String getSet(String key, String value) { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.getSet(key, value); } catch (Exception e) { e.printStackTrace(); } return result; } public List<String> mget(String... keys) { List<String> result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.mget(keys); } catch (Exception e) { e.printStackTrace(); } return result; } public Long setnx(String key, String value) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.setnx(key, value); } catch (Exception e) { e.printStackTrace(); } return result; } public String setex(String key, int seconds, String value) { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.setex(key, seconds, value); } catch (Exception e) { e.printStackTrace(); } return result; } public String mset(String... keysvalues) { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.mset(keysvalues); } catch (Exception e) { e.printStackTrace(); } return result; } public Long msetnx(String... keysvalues) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.msetnx(keysvalues); } catch (Exception e) { e.printStackTrace(); } return result; } public Long decrBy(String key, long integer) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.decrBy(key, integer); } catch (Exception e) { e.printStackTrace(); } return result; } public Long decr(String key) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.decr(key); } catch (Exception e) { e.printStackTrace(); } return result; } public Long incrBy(String key, long integer) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.incrBy(key, integer); } catch (Exception e) { e.printStackTrace(); } return result; } public Double incrByFloat(String key, double value) { Double result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.incrByFloat(key, value); } catch (Exception e) { e.printStackTrace(); } return result; } public Long incr(String key) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.incr(key); } catch (Exception e) { e.printStackTrace(); } return result; } public Long append(String key, String value) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.append(key, value); } catch (Exception e) { e.printStackTrace(); } return result; } public String substr(String key, int start, int end) { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.substr(key, start, end); } catch (Exception e) { e.printStackTrace(); } return result; } public Long hset(String key, String field, String value) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.hset(key, field, value); } catch (Exception e) { e.printStackTrace(); } return result; } public String hget(String key, String field) { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.hget(key, field); } catch (Exception e) { e.printStackTrace(); } return result; } public Long hsetnx(String key, String field, String value) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.hsetnx(key, field, value); } catch (Exception e) { e.printStackTrace(); } return result; } public String hmset(String key, Map<String, String> hash) { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.hmset(key, hash); } catch (Exception e) { e.printStackTrace(); } return result; } public List<String> hmget(String key, String... fields) { List<String> result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.hmget(key, fields); } catch (Exception e) { e.printStackTrace(); } return result; } public Long hincrBy(String key, String field, long value) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.hincrBy(key, field, value); } catch (Exception e) { e.printStackTrace(); } return result; } public Double hincrByFloat(String key, String field, double value) { Double result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.hincrByFloat(key, field, value); } catch (Exception e) { e.printStackTrace(); } return result; } public Boolean hexists(String key, String field) { Boolean result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.hexists(key, field); } catch (Exception e) { e.printStackTrace(); } return result; } public Long hdel(String key, String... fields) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.hdel(key, fields); } catch (Exception e) { e.printStackTrace(); } return result; } public Long hlen(String key) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.hlen(key); } catch (Exception e) { e.printStackTrace(); } return result; } public Set<String> hkeys(String key) { Set<String> result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.hkeys(key); } catch (Exception e) { e.printStackTrace(); } return result; } public List<String> hvals(String key) { List<String> result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.hvals(key); } catch (Exception e) { e.printStackTrace(); } return result; } public Map<String, String> hgetAll(String key) { Map<String, String> result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.hgetAll(key); } catch (Exception e) { e.printStackTrace(); } return result; } public Long rpush(String key, String... strings) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.rpush(key, strings); } catch (Exception e) { e.printStackTrace(); } return result; } public Long lpush(String key, String... strings) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.lpush(key, strings); } catch (Exception e) { e.printStackTrace(); } return result; } public Long llen(String key) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.llen(key); } catch (Exception e) { e.printStackTrace(); } return result; } public List<String> lrange(String key, long start, long end) { List<String> result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.lrange(key, start, end); } catch (Exception e) { e.printStackTrace(); } return result; } public String ltrim(String key, long start, long end) { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.ltrim(key, start, end); } catch (Exception e) { e.printStackTrace(); } return result; } public String lindex(String key, long index) { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.lindex(key, index); } catch (Exception e) { e.printStackTrace(); } return result; } public String lset(String key, long index, String value) { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.lset(key, index, value); } catch (Exception e) { e.printStackTrace(); } return result; } public Long lrem(String key, long count, String value) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.lrem(key, count, value); } catch (Exception e) { e.printStackTrace(); } return result; } public String lpop(String key) { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.lpop(key); } catch (Exception e) { e.printStackTrace(); } return result; } public String rpop(String key) { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.rpop(key); } catch (Exception e) { e.printStackTrace(); } return result; } public String rpoplpush(String srckey, String dstkey) { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.rpoplpush(srckey, dstkey); } catch (Exception e) { e.printStackTrace(); } return result; } public Long sadd(String key, String... members) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.sadd(key, members); } catch (Exception e) { e.printStackTrace(); } return result; } public Set<String> smembers(String key) { Set<String> result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.smembers(key); } catch (Exception e) { e.printStackTrace(); } return result; } public Long srem(String key, String... members) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.srem(key, members); } catch (Exception e) { e.printStackTrace(); } return result; } public String spop(String key) { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.spop(key); } catch (Exception e) { e.printStackTrace(); } return result; } public Set<String> spop(String key, long count) { Set<String> result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.spop(key, count); } catch (Exception e) { e.printStackTrace(); } return result; } public Long smove(String srckey, String dstkey, String member) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.smove(srckey, dstkey, member); } catch (Exception e) { e.printStackTrace(); } return result; } public Long scard(String key) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.scard(key); } catch (Exception e) { e.printStackTrace(); } return result; } public Boolean sismember(String key, String member) { Boolean result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.sismember(key, member); } catch (Exception e) { e.printStackTrace(); } return result; } public Set<String> sinter(String... keys) { Set<String> result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.sinter(keys); } catch (Exception e) { e.printStackTrace(); } return result; } public Long sinterstore(String dstkey, String... keys) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.sinterstore(dstkey, keys); } catch (Exception e) { e.printStackTrace(); } return result; } public Set<String> sunion(String... keys) { Set<String> result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.sunion(keys); } catch (Exception e) { e.printStackTrace(); } return result; } public Set<Tuple> zrevrangeByScoreWithScores(String key, String max, String min) { Set<Tuple> result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.zrevrangeByScoreWithScores(key, max, min); } catch (Exception e) { e.printStackTrace(); } return result; } public Long zremrangeByRank(String key, long start, long end) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.zremrangeByRank(key, start, end); } catch (Exception e) { e.printStackTrace(); } return result; } public Long zremrangeByScore(String key, double start, double end) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.zremrangeByScore(key, start, end); } catch (Exception e) { e.printStackTrace(); } return result; } public Long zremrangeByScore(String key, String start, String end) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.zremrangeByScore(key, start, end); } catch (Exception e) { e.printStackTrace(); } return result; } public Long zunionstore(String dstkey, String... sets) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.zunionstore(dstkey, sets); } catch (Exception e) { e.printStackTrace(); } return result; } public Long zunionstore(String dstkey, ZParams params, String... sets) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.zunionstore(dstkey, params, sets); } catch (Exception e) { e.printStackTrace(); } return result; } public Long zinterstore(String dstkey, String... sets) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.zinterstore(dstkey, sets); } catch (Exception e) { e.printStackTrace(); } return result; } public Long zinterstore(String dstkey, ZParams params, String... sets) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.zinterstore(dstkey, params, sets); } catch (Exception e) { e.printStackTrace(); } return result; } public Long zlexcount(String key, String min, String max) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.zlexcount(key, min, max); } catch (Exception e) { e.printStackTrace(); } return result; } public Set<String> zrangeByLex(String key, String min, String max) { Set<String> result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.zrangeByLex(key, min, max); } catch (Exception e) { e.printStackTrace(); } return result; } public Set<String> zrangeByLex(String key, String min, String max, int offset, int count) { Set<String> result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.zrangeByLex(key, min, max, offset, count); } catch (Exception e) { e.printStackTrace(); } return result; } public Set<String> zrevrangeByLex(String key, String max, String min) { Set<String> result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.zrevrangeByLex(key, max, min); } catch (Exception e) { e.printStackTrace(); } return result; } public Set<String> zrevrangeByLex(String key, String max, String min, int offset, int count) { Set<String> result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.zrevrangeByLex(key, max, min, offset, count); } catch (Exception e) { e.printStackTrace(); } return result; } public Long zremrangeByLex(String key, String min, String max) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.zremrangeByLex(key, min, max); } catch (Exception e) { e.printStackTrace(); } return result; } public Long strlen(String key) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.strlen(key); } catch (Exception e) { e.printStackTrace(); } return result; } public Long lpushx(String key, String... string) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.lpushx(key, string); } catch (Exception e) { e.printStackTrace(); } return result; } public Long persist(String key) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.persist(key); } catch (Exception e) { e.printStackTrace(); } return result; } public Long rpushx(String key, String... string) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.rpushx(key, string); } catch (Exception e) { e.printStackTrace(); } return result; } public String echo(String string) { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.echo(string); } catch (Exception e) { e.printStackTrace(); } return result; } public Long linsert(String key, BinaryClient.LIST_POSITION where, String pivot, String value) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.linsert(key, where, pivot, value); } catch (Exception e) { e.printStackTrace(); } return result; } public String brpoplpush(String source, String destination, int timeout) { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.brpoplpush(source, destination, timeout); } catch (Exception e) { e.printStackTrace(); } return result; } public Boolean setbit(String key, long offset, boolean value) { Boolean result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.setbit(key, offset, value); } catch (Exception e) { e.printStackTrace(); } return result; } public Boolean setbit(String key, long offset, String value) { Boolean result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.setbit(key, offset, value); } catch (Exception e) { e.printStackTrace(); } return result; } public Boolean getbit(String key, long offset) { Boolean result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.getbit(key, offset); } catch (Exception e) { e.printStackTrace(); } return result; } public Long setrange(String key, long offset, String value) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.setrange(key, offset, value); } catch (Exception e) { e.printStackTrace(); } return result; } public String getrange(String key, long startOffset, long endOffset) { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.getrange(key, startOffset, endOffset); } catch (Exception e) { e.printStackTrace(); } return result; } public Long bitpos(String key, boolean value) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.bitpos(key, value); } catch (Exception e) { e.printStackTrace(); } return result; } public Long bitpos(String key, boolean value, BitPosParams params) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.bitpos(key, value, params); } catch (Exception e) { e.printStackTrace(); } return result; } public List<String> configGet(String pattern) { List<String> result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.configGet(pattern); } catch (Exception e) { e.printStackTrace(); } return result; } public String configSet(String parameter, String value) { String result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.configSet(parameter, value); } catch (Exception e) { e.printStackTrace(); } return result; } public Object eval(String script, int keyCount, String... params) { Object result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.eval(script, keyCount, params); } catch (Exception e) { e.printStackTrace(); } return result; } public void subscribe(JedisPubSub jedisPubSub, String... channels) { try (Jedis jedis = jedisPool.getResource()) { jedis.subscribe(jedisPubSub, channels); } catch (Exception e) { e.printStackTrace(); } } public Long publish(String channel, String message) { Long result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.publish(channel, message); } catch (Exception e) { e.printStackTrace(); } return result; } public void psubscribe(JedisPubSub jedisPubSub, String... patterns) { try (Jedis jedis = jedisPool.getResource()) { psubscribe(jedisPubSub, patterns); } catch (Exception e) { e.printStackTrace(); } } public Object eval(String script, List<String> keys, List<String> args) { Object result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.eval(script, keys, args); } catch (Exception e) { e.printStackTrace(); } return result; } public Object eval(String script) { Object result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.eval(script); } catch (Exception e) { e.printStackTrace(); } return result; } public Object evalsha(String script) { Object result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.evalsha(script); } catch (Exception e) { e.printStackTrace(); } return result; } public Object evalsha(String sha1, List<String> keys, List<String> args) { Object result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.evalsha(sha1, keys, args); } catch (Exception e) { e.printStackTrace(); } return result; } public Object evalsha(String sha1, int keyCount, String... params) { Object result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.evalsha(sha1, keyCount, params); } catch (Exception e) { e.printStackTrace(); } return result; } public List<GeoRadiusResponse> georadiusByMember(byte[] key, byte[] member, double radius, GeoUnit unit) { List<GeoRadiusResponse> result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.georadiusByMember(key, member, radius, unit); } catch (Exception e) { e.printStackTrace(); } return result; } public List<GeoRadiusResponse> georadiusByMember(byte[] key, byte[] member, double radius, GeoUnit unit, GeoRadiusParam param) { List<GeoRadiusResponse> result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.georadiusByMember(key, member, radius, unit, param); } catch (Exception e) { e.printStackTrace(); } return result; } public List<byte[]> bitfield(byte[] key, byte[]... arguments) { List<byte[]> result = null; try (Jedis jedis = jedisPool.getResource()) { result = jedis.bitfield(key, arguments); } catch (Exception e) { e.printStackTrace(); } return result; } public int hashCode() { int result = 0; try (Jedis jedis = jedisPool.getResource()) { result = jedis.hashCode(); } catch (Exception e) { e.printStackTrace(); } return result; } public boolean equals(Object obj) { boolean result = false; try (Jedis jedis = jedisPool.getResource()) { result = jedis.equals(obj); } catch (Exception e) { e.printStackTrace(); } return result; } }
33,076
0.542024
0.541631
1,228
25.934853
20.820717
132
false
false
0
0
0
0
0
0
0.563518
false
false
10
952815ff56b13a7139e22884f080b0882e8ef957
12,970,801,250,831
261354cfb9111edd9a78b5cabaca64af9687628c
/src/main/java/replayTheSpire/replayxover/downfallbs.java
23b37a165e4750ae16c304d2566e9b7aee15037c
[]
no_license
The-Evil-Pickle/Replay-the-Spire
https://github.com/The-Evil-Pickle/Replay-the-Spire
1c9258bd664ba0ff41f79d57180a090c502cdca3
1fcb4cedafa61f32b3d9c3bab2d6a687f9cbe718
refs/heads/master
2022-11-14T15:56:19.255000
2022-11-01T13:30:14
2022-11-01T13:30:14
122,853,479
39
19
null
false
2022-11-01T13:30:15
2018-02-25T16:26:38
2022-11-01T13:28:26
2022-11-01T13:30:14
129,771
49
21
36
Java
false
false
package replayTheSpire.replayxover; import java.util.ArrayList; import com.evacipated.cardcrawl.modthespire.lib.ByRef; import com.evacipated.cardcrawl.modthespire.lib.SpireEnum; import com.evacipated.cardcrawl.modthespire.lib.SpireInsertPatch; import com.evacipated.cardcrawl.modthespire.lib.SpirePatch; import com.evacipated.cardcrawl.modthespire.lib.SpireReturn; import com.megacrit.cardcrawl.actions.common.HealAction; import com.megacrit.cardcrawl.actions.common.MakeTempCardInHandAction; import com.megacrit.cardcrawl.cards.AbstractCard; import com.megacrit.cardcrawl.cards.DamageInfo; import com.megacrit.cardcrawl.core.CardCrawlGame; import com.megacrit.cardcrawl.dungeons.AbstractDungeon; import com.megacrit.cardcrawl.mod.replay.cards.replayxover.curses.UnknownCurse; import com.megacrit.cardcrawl.mod.replay.cards.replayxover.curses.WhispersOfEvil; import com.megacrit.cardcrawl.mod.replay.cards.replayxover.downfall.M_BronzeAgony; import com.megacrit.cardcrawl.mod.replay.cards.replayxover.downfall.M_BronzeBash; import com.megacrit.cardcrawl.mod.replay.cards.replayxover.downfall.M_BronzeSurvivor; import com.megacrit.cardcrawl.mod.replay.cards.replayxover.downfall.M_GremlinBash; import com.megacrit.cardcrawl.mod.replay.cards.replayxover.downfall.ResoundingBlow; import com.megacrit.cardcrawl.mod.replay.cards.replayxover.spireboss.*; import com.megacrit.cardcrawl.mod.replay.monsters.replay.FadingForestBoss; import com.megacrit.cardcrawl.mod.replay.monsters.replay.PondfishBoss; import com.megacrit.cardcrawl.mod.replay.monsters.replay.hec.HellsEngine; import com.megacrit.cardcrawl.mod.replay.relics.CursedDEight; import com.megacrit.cardcrawl.mod.replay.relics.M_BronzeBlood; import com.megacrit.cardcrawl.mod.replay.relics.M_DevilBlood; import com.megacrit.cardcrawl.mod.replay.relics.M_Hexaring; import com.megacrit.cardcrawl.mod.replay.relics.M_HornedRing; import com.megacrit.cardcrawl.mod.replay.relics.M_IronCrown; import com.megacrit.cardcrawl.mod.replay.relics.M_NobBlood; import automaton.AutomatonChar; import basemod.BaseMod; import basemod.helpers.RelicType; import champ.ChampChar; import downfall.cards.OctoChoiceCard; import downfall.patches.EvilModeCharacterSelect; import expansioncontent.expansionContentMod; import expansioncontent.cards.QuickStudy; import slimebound.powers.SlimedPower; import theHexaghost.TheHexaghost; public class downfallbs { public static void addBossCards() { /** Bosses each only have one card now, to avoid thickening the pool too much. Feel free to add this back in as desired. Boss cards need to have a template override assigned, which each of the three uncommented ones do. **/ BaseMod.addCard(new SS_Fish_DragToHell()); //BaseMod.addCard(new SS_Fish_LivingLantern()); //BaseMod.addCard(new SS_Fish_SixFeetUnder()); BaseMod.addCard(new SS_Forest_Treasure()); //BaseMod.addCard(new SS_Forest_LostForever()); //BaseMod.addCard(new SS_Forest_Fishers()); BaseMod.addCard(new SS_Hec_ForgedInHellfire()); //BaseMod.addCard(new SS_Hec_SteelHeart()); //BaseMod.addCard(new SS_Hec_Dynamite()); /** Unknowns are VERY different now and would probably tough to make a new one. I didn't see this hooked up to anything, so I didn't worry about it right now. But we'll probably need to do some support on our end to allow modded Unknowns. Unknown Curse is set up to be basically what Unknowns are now, but there's a lot of hooks elsewhere. **/ //BaseMod.addCard(new UnknownCurse()); } public static void addMistCards() { BaseMod.addCard(new M_BronzeBash()); BaseMod.addCard(new M_BronzeSurvivor()); BaseMod.addCard(new M_BronzeAgony()); BaseMod.addCard(new M_GremlinBash()); } public static void addMistRelics() { BaseMod.addRelicToCustomPool(new M_DevilBlood(), TheHexaghost.Enums.GHOST_GREEN); BaseMod.addRelicToCustomPool(new M_Hexaring(), TheHexaghost.Enums.GHOST_GREEN); BaseMod.addRelicToCustomPool(new M_IronCrown(), ChampChar.Enums.CHAMP_GRAY); BaseMod.addRelicToCustomPool(new M_BronzeBlood(), AutomatonChar.Enums.BRONZE_AUTOMATON); BaseMod.addRelicToCustomPool(new M_HornedRing(), gremlin.patches.AbstractCardEnum.GREMLIN); BaseMod.addRelicToCustomPool(new M_NobBlood(), gremlin.patches.AbstractCardEnum.GREMLIN); } public static void addMiscRelics() { BaseMod.addRelic(new CursedDEight(), RelicType.SHARED); } public static void addMiscCards() { BaseMod.addCard(new ResoundingBlow()); BaseMod.addCard(new WhispersOfEvil()); } /* public static boolean inEvilMode() { try { return EvilModeCharacterSelect.evilMode; } catch (NoClassDefFoundError e) { return false; } }*/ /** Quick Study and the like are now fully tag-driven, so no patches are needed any more. **/ /*@SpirePatch(cls = "expansioncontent.cards.StudyTheSpire", method = "use", optional = true) public static class StudyTheSpirePatch { @SpireInsertPatch(rloc = 3, localvars = { "powers" }) public static void Insert(final StudyTheSpire __instance, final AbstractPlayer p, final AbstractMonster m, ArrayList<AbstractPower> powers) { powers.add(new StudyPondfishPower(p, p, __instance.magicNumber, __instance.upgraded)); powers.add(new StudyFableSpinnerPower(p, p, __instance.magicNumber, __instance.upgraded)); powers.add(new StudyHecPower(p, p, __instance.magicNumber, __instance.upgraded)); } }*/ /* @SpirePatch(cls = "slimebound.powers.SlimedPower", method = "onAttacked", optional = true) public static class SlimedRelicPatch { public static void Prefix(final SlimedPower __instance, final DamageInfo info, final int damageAmount) { if (info.type == DamageInfo.DamageType.NORMAL) { if (AbstractDungeon.player.hasRelic("Slimebound:AbsorbEndCombat")) { AbstractDungeon.actionManager.addToBottom(new HealAction(AbstractDungeon.player, AbstractDungeon.player, 2)); AbstractDungeon.player.getRelic("Slimebound:AbsorbEndCombat").flash(); } } } } @SpirePatch(cls = "expansioncontent.cards.QuickStudy", method = "choiceList", optional = true) public static class QuickStudyPatch { @SpireInsertPatch(rloc = 12, localvars = { "cardList" }) public static void Insert(final QuickStudy __instance, ArrayList<OctoChoiceCard> cardList) { String NAMESTRING = CardCrawlGame.languagePack.getCharacterString("downfall:OctoChoiceCards").NAMES[3]; String TEXTSTRING = CardCrawlGame.languagePack.getCharacterString("downfall:OctoChoiceCards").TEXT[3]; cardList.add(new OctoChoiceCard(expansionContentMod.makeID("9r"), FadingForestBoss.NAME, "cards/replay/ss_forest_skill.png", TEXTSTRING.replace(NAMESTRING, FadingForestBoss.NAME), new SS_Forest_Fishers(), new SS_Forest_LostForever(), new SS_Forest_Treasure())); cardList.add(new OctoChoiceCard(expansionContentMod.makeID("10r"), PondfishBoss.NAME, "cards/replay/ss_fish_light.png", TEXTSTRING.replace(NAMESTRING, PondfishBoss.NAME), new SS_Fish_DragToHell(), new SS_Fish_LivingLantern(), new SS_Fish_SixFeetUnder())); cardList.add(new OctoChoiceCard(expansionContentMod.makeID("11r"), HellsEngine.NAME, "cards/replay/ss_train.png", TEXTSTRING.replace(NAMESTRING, HellsEngine.NAME), new SS_Hec_Dynamite(), new SS_Hec_ForgedInHellfire(), new SS_Hec_SteelHeart())); } } @SpirePatch(cls = "expansioncontent.cards.QuickStudy", method = "doChoiceStuff", optional = true) public static class QuickStudyChoicePatch { public static SpireReturn Prefix(final QuickStudy __instance, final OctoChoiceCard card) { if (card.cardID.equals("expansioncontent:9r")) { AbstractCard q = new SS_Forest_Fishers(); AbstractCard r = new SS_Forest_LostForever(); AbstractCard z = new SS_Forest_Treasure(); q.freeToPlayOnce = true; r.freeToPlayOnce = true; z.freeToPlayOnce = true; AbstractDungeon.actionManager.addToBottom(new MakeTempCardInHandAction(q)); AbstractDungeon.actionManager.addToBottom(new MakeTempCardInHandAction(r)); AbstractDungeon.actionManager.addToBottom(new MakeTempCardInHandAction(z)); return SpireReturn.Return(null); } else if (card.cardID.equals("expansioncontent:10r")) { AbstractCard q = new SS_Fish_DragToHell(); AbstractCard r = new SS_Fish_LivingLantern(); AbstractCard z = new SS_Fish_SixFeetUnder(); q.freeToPlayOnce = true; r.freeToPlayOnce = true; z.freeToPlayOnce = true; AbstractDungeon.actionManager.addToBottom(new MakeTempCardInHandAction(q)); AbstractDungeon.actionManager.addToBottom(new MakeTempCardInHandAction(r)); AbstractDungeon.actionManager.addToBottom(new MakeTempCardInHandAction(z)); return SpireReturn.Return(null); } else if (card.cardID.equals("expansioncontent:11r")) { AbstractCard q = new SS_Hec_Dynamite(); AbstractCard r = new SS_Hec_ForgedInHellfire(); AbstractCard z = new SS_Hec_SteelHeart(); q.freeToPlayOnce = true; r.freeToPlayOnce = true; z.freeToPlayOnce = true; AbstractDungeon.actionManager.addToBottom(new MakeTempCardInHandAction(q)); AbstractDungeon.actionManager.addToBottom(new MakeTempCardInHandAction(r)); AbstractDungeon.actionManager.addToBottom(new MakeTempCardInHandAction(z)); return SpireReturn.Return(null); } return SpireReturn.Continue(); } } */ @SpirePatch(cls = "sneckomod.cards.AbstractSneckoCard", method = "getCorrectPlaceholderImage", optional = true) public static class SnekboiPatch { public static SpireReturn<String> Prefix(final String img) { if (img == "cards/replay/betaCurse.png") return SpireReturn.Return(img); return SpireReturn.Continue(); } } @SpirePatch(cls = "automaton.cards.AbstractBronzeCard", method = "getCorrectPlaceholderImage", optional = true) public static class AutocardPatch { public static SpireReturn<String> Prefix(final AbstractCard.CardType type, final String id) { if (id == M_BronzeAgony.ID) return SpireReturn.Return("cards/replay/agony.png"); if (id == M_BronzeBash.ID) return SpireReturn.Return("cards/replay/bash.png"); if (id == M_BronzeSurvivor.ID) return SpireReturn.Return("cards/replay/survivalism.png"); return SpireReturn.Continue(); } } }
UTF-8
Java
10,421
java
downfallbs.java
Java
[]
null
[]
package replayTheSpire.replayxover; import java.util.ArrayList; import com.evacipated.cardcrawl.modthespire.lib.ByRef; import com.evacipated.cardcrawl.modthespire.lib.SpireEnum; import com.evacipated.cardcrawl.modthespire.lib.SpireInsertPatch; import com.evacipated.cardcrawl.modthespire.lib.SpirePatch; import com.evacipated.cardcrawl.modthespire.lib.SpireReturn; import com.megacrit.cardcrawl.actions.common.HealAction; import com.megacrit.cardcrawl.actions.common.MakeTempCardInHandAction; import com.megacrit.cardcrawl.cards.AbstractCard; import com.megacrit.cardcrawl.cards.DamageInfo; import com.megacrit.cardcrawl.core.CardCrawlGame; import com.megacrit.cardcrawl.dungeons.AbstractDungeon; import com.megacrit.cardcrawl.mod.replay.cards.replayxover.curses.UnknownCurse; import com.megacrit.cardcrawl.mod.replay.cards.replayxover.curses.WhispersOfEvil; import com.megacrit.cardcrawl.mod.replay.cards.replayxover.downfall.M_BronzeAgony; import com.megacrit.cardcrawl.mod.replay.cards.replayxover.downfall.M_BronzeBash; import com.megacrit.cardcrawl.mod.replay.cards.replayxover.downfall.M_BronzeSurvivor; import com.megacrit.cardcrawl.mod.replay.cards.replayxover.downfall.M_GremlinBash; import com.megacrit.cardcrawl.mod.replay.cards.replayxover.downfall.ResoundingBlow; import com.megacrit.cardcrawl.mod.replay.cards.replayxover.spireboss.*; import com.megacrit.cardcrawl.mod.replay.monsters.replay.FadingForestBoss; import com.megacrit.cardcrawl.mod.replay.monsters.replay.PondfishBoss; import com.megacrit.cardcrawl.mod.replay.monsters.replay.hec.HellsEngine; import com.megacrit.cardcrawl.mod.replay.relics.CursedDEight; import com.megacrit.cardcrawl.mod.replay.relics.M_BronzeBlood; import com.megacrit.cardcrawl.mod.replay.relics.M_DevilBlood; import com.megacrit.cardcrawl.mod.replay.relics.M_Hexaring; import com.megacrit.cardcrawl.mod.replay.relics.M_HornedRing; import com.megacrit.cardcrawl.mod.replay.relics.M_IronCrown; import com.megacrit.cardcrawl.mod.replay.relics.M_NobBlood; import automaton.AutomatonChar; import basemod.BaseMod; import basemod.helpers.RelicType; import champ.ChampChar; import downfall.cards.OctoChoiceCard; import downfall.patches.EvilModeCharacterSelect; import expansioncontent.expansionContentMod; import expansioncontent.cards.QuickStudy; import slimebound.powers.SlimedPower; import theHexaghost.TheHexaghost; public class downfallbs { public static void addBossCards() { /** Bosses each only have one card now, to avoid thickening the pool too much. Feel free to add this back in as desired. Boss cards need to have a template override assigned, which each of the three uncommented ones do. **/ BaseMod.addCard(new SS_Fish_DragToHell()); //BaseMod.addCard(new SS_Fish_LivingLantern()); //BaseMod.addCard(new SS_Fish_SixFeetUnder()); BaseMod.addCard(new SS_Forest_Treasure()); //BaseMod.addCard(new SS_Forest_LostForever()); //BaseMod.addCard(new SS_Forest_Fishers()); BaseMod.addCard(new SS_Hec_ForgedInHellfire()); //BaseMod.addCard(new SS_Hec_SteelHeart()); //BaseMod.addCard(new SS_Hec_Dynamite()); /** Unknowns are VERY different now and would probably tough to make a new one. I didn't see this hooked up to anything, so I didn't worry about it right now. But we'll probably need to do some support on our end to allow modded Unknowns. Unknown Curse is set up to be basically what Unknowns are now, but there's a lot of hooks elsewhere. **/ //BaseMod.addCard(new UnknownCurse()); } public static void addMistCards() { BaseMod.addCard(new M_BronzeBash()); BaseMod.addCard(new M_BronzeSurvivor()); BaseMod.addCard(new M_BronzeAgony()); BaseMod.addCard(new M_GremlinBash()); } public static void addMistRelics() { BaseMod.addRelicToCustomPool(new M_DevilBlood(), TheHexaghost.Enums.GHOST_GREEN); BaseMod.addRelicToCustomPool(new M_Hexaring(), TheHexaghost.Enums.GHOST_GREEN); BaseMod.addRelicToCustomPool(new M_IronCrown(), ChampChar.Enums.CHAMP_GRAY); BaseMod.addRelicToCustomPool(new M_BronzeBlood(), AutomatonChar.Enums.BRONZE_AUTOMATON); BaseMod.addRelicToCustomPool(new M_HornedRing(), gremlin.patches.AbstractCardEnum.GREMLIN); BaseMod.addRelicToCustomPool(new M_NobBlood(), gremlin.patches.AbstractCardEnum.GREMLIN); } public static void addMiscRelics() { BaseMod.addRelic(new CursedDEight(), RelicType.SHARED); } public static void addMiscCards() { BaseMod.addCard(new ResoundingBlow()); BaseMod.addCard(new WhispersOfEvil()); } /* public static boolean inEvilMode() { try { return EvilModeCharacterSelect.evilMode; } catch (NoClassDefFoundError e) { return false; } }*/ /** Quick Study and the like are now fully tag-driven, so no patches are needed any more. **/ /*@SpirePatch(cls = "expansioncontent.cards.StudyTheSpire", method = "use", optional = true) public static class StudyTheSpirePatch { @SpireInsertPatch(rloc = 3, localvars = { "powers" }) public static void Insert(final StudyTheSpire __instance, final AbstractPlayer p, final AbstractMonster m, ArrayList<AbstractPower> powers) { powers.add(new StudyPondfishPower(p, p, __instance.magicNumber, __instance.upgraded)); powers.add(new StudyFableSpinnerPower(p, p, __instance.magicNumber, __instance.upgraded)); powers.add(new StudyHecPower(p, p, __instance.magicNumber, __instance.upgraded)); } }*/ /* @SpirePatch(cls = "slimebound.powers.SlimedPower", method = "onAttacked", optional = true) public static class SlimedRelicPatch { public static void Prefix(final SlimedPower __instance, final DamageInfo info, final int damageAmount) { if (info.type == DamageInfo.DamageType.NORMAL) { if (AbstractDungeon.player.hasRelic("Slimebound:AbsorbEndCombat")) { AbstractDungeon.actionManager.addToBottom(new HealAction(AbstractDungeon.player, AbstractDungeon.player, 2)); AbstractDungeon.player.getRelic("Slimebound:AbsorbEndCombat").flash(); } } } } @SpirePatch(cls = "expansioncontent.cards.QuickStudy", method = "choiceList", optional = true) public static class QuickStudyPatch { @SpireInsertPatch(rloc = 12, localvars = { "cardList" }) public static void Insert(final QuickStudy __instance, ArrayList<OctoChoiceCard> cardList) { String NAMESTRING = CardCrawlGame.languagePack.getCharacterString("downfall:OctoChoiceCards").NAMES[3]; String TEXTSTRING = CardCrawlGame.languagePack.getCharacterString("downfall:OctoChoiceCards").TEXT[3]; cardList.add(new OctoChoiceCard(expansionContentMod.makeID("9r"), FadingForestBoss.NAME, "cards/replay/ss_forest_skill.png", TEXTSTRING.replace(NAMESTRING, FadingForestBoss.NAME), new SS_Forest_Fishers(), new SS_Forest_LostForever(), new SS_Forest_Treasure())); cardList.add(new OctoChoiceCard(expansionContentMod.makeID("10r"), PondfishBoss.NAME, "cards/replay/ss_fish_light.png", TEXTSTRING.replace(NAMESTRING, PondfishBoss.NAME), new SS_Fish_DragToHell(), new SS_Fish_LivingLantern(), new SS_Fish_SixFeetUnder())); cardList.add(new OctoChoiceCard(expansionContentMod.makeID("11r"), HellsEngine.NAME, "cards/replay/ss_train.png", TEXTSTRING.replace(NAMESTRING, HellsEngine.NAME), new SS_Hec_Dynamite(), new SS_Hec_ForgedInHellfire(), new SS_Hec_SteelHeart())); } } @SpirePatch(cls = "expansioncontent.cards.QuickStudy", method = "doChoiceStuff", optional = true) public static class QuickStudyChoicePatch { public static SpireReturn Prefix(final QuickStudy __instance, final OctoChoiceCard card) { if (card.cardID.equals("expansioncontent:9r")) { AbstractCard q = new SS_Forest_Fishers(); AbstractCard r = new SS_Forest_LostForever(); AbstractCard z = new SS_Forest_Treasure(); q.freeToPlayOnce = true; r.freeToPlayOnce = true; z.freeToPlayOnce = true; AbstractDungeon.actionManager.addToBottom(new MakeTempCardInHandAction(q)); AbstractDungeon.actionManager.addToBottom(new MakeTempCardInHandAction(r)); AbstractDungeon.actionManager.addToBottom(new MakeTempCardInHandAction(z)); return SpireReturn.Return(null); } else if (card.cardID.equals("expansioncontent:10r")) { AbstractCard q = new SS_Fish_DragToHell(); AbstractCard r = new SS_Fish_LivingLantern(); AbstractCard z = new SS_Fish_SixFeetUnder(); q.freeToPlayOnce = true; r.freeToPlayOnce = true; z.freeToPlayOnce = true; AbstractDungeon.actionManager.addToBottom(new MakeTempCardInHandAction(q)); AbstractDungeon.actionManager.addToBottom(new MakeTempCardInHandAction(r)); AbstractDungeon.actionManager.addToBottom(new MakeTempCardInHandAction(z)); return SpireReturn.Return(null); } else if (card.cardID.equals("expansioncontent:11r")) { AbstractCard q = new SS_Hec_Dynamite(); AbstractCard r = new SS_Hec_ForgedInHellfire(); AbstractCard z = new SS_Hec_SteelHeart(); q.freeToPlayOnce = true; r.freeToPlayOnce = true; z.freeToPlayOnce = true; AbstractDungeon.actionManager.addToBottom(new MakeTempCardInHandAction(q)); AbstractDungeon.actionManager.addToBottom(new MakeTempCardInHandAction(r)); AbstractDungeon.actionManager.addToBottom(new MakeTempCardInHandAction(z)); return SpireReturn.Return(null); } return SpireReturn.Continue(); } } */ @SpirePatch(cls = "sneckomod.cards.AbstractSneckoCard", method = "getCorrectPlaceholderImage", optional = true) public static class SnekboiPatch { public static SpireReturn<String> Prefix(final String img) { if (img == "cards/replay/betaCurse.png") return SpireReturn.Return(img); return SpireReturn.Continue(); } } @SpirePatch(cls = "automaton.cards.AbstractBronzeCard", method = "getCorrectPlaceholderImage", optional = true) public static class AutocardPatch { public static SpireReturn<String> Prefix(final AbstractCard.CardType type, final String id) { if (id == M_BronzeAgony.ID) return SpireReturn.Return("cards/replay/agony.png"); if (id == M_BronzeBash.ID) return SpireReturn.Return("cards/replay/bash.png"); if (id == M_BronzeSurvivor.ID) return SpireReturn.Return("cards/replay/survivalism.png"); return SpireReturn.Continue(); } } }
10,421
0.748681
0.747145
214
47.696262
42.064327
264
false
false
0
0
0
0
0
0
2.042056
false
false
10
fc9ce3e5c2d386f87143acc3de08d24724700377
12,970,801,252,765
01ff007a1a504f0bc13030438f75bbc9b06e2585
/core/spoofax.core/src/main/java/mb/spoofax/core/language/command/CommandContextType.java
2e68fe2cbdf5740660a6fddfbfb5cdbb3e6e5b9f
[ "Apache-2.0" ]
permissive
AZWN/spoofax-pie
https://github.com/AZWN/spoofax-pie
48eac24f0ae3cd29895d6c1b7bf4134e69d81537
3428621fc7fe6d21d8b6889ef37cde8c41f9add2
refs/heads/master
2023-03-03T08:17:50.802000
2020-05-18T12:48:45
2020-05-18T12:48:45
267,873,687
0
0
Apache-2.0
true
2020-05-29T14:08:58
2020-05-29T14:08:58
2020-05-26T08:11:29
2020-05-26T08:11:27
3,510
0
0
0
null
false
false
package mb.spoofax.core.language.command; import java.io.Serializable; public enum CommandContextType implements Serializable { Project, Directory, File, ResourcePath, ResourceKey, Region, Offset }
UTF-8
Java
228
java
CommandContextType.java
Java
[]
null
[]
package mb.spoofax.core.language.command; import java.io.Serializable; public enum CommandContextType implements Serializable { Project, Directory, File, ResourcePath, ResourceKey, Region, Offset }
228
0.719298
0.719298
13
16.538462
15.770544
56
false
false
0
0
0
0
0
0
0.615385
false
false
10
e857bf43d3f94b23f6f28b533f1ce407baf02a03
24,524,263,278,301
b95377974726e11506ce8becbf19cce8cada6ff9
/src/main/java/com/nugrohosamiyono/springregion/Routes/Rule.java
173c0e7fdb15d34de4b12d1acfa2a7fa3b7a02ac
[]
no_license
nugrohosam/springregion
https://github.com/nugrohosam/springregion
f5ae86794d2caafb09d5b0ee8e34c225c419b48f
7d544c1e3618a7a1cde7f58d72c92d57b4ab8f31
refs/heads/master
2023-05-23T00:37:31.685000
2021-06-07T23:33:14
2021-06-07T23:33:14
358,998,686
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.nugrohosamiyono.springregion.Routes; public class Rule { public String auth[]; public String roles[]; public String permissions[]; public Rule(String auth[]) { this.auth = auth; } public Rule(String auth[], String roles[], String permissions[]) { this.auth = auth; this.roles = roles; this.permissions = permissions; } public Rule(String auth[], String roles[]) { this.auth = auth; this.roles = roles; } }
UTF-8
Java
512
java
Rule.java
Java
[]
null
[]
package com.nugrohosamiyono.springregion.Routes; public class Rule { public String auth[]; public String roles[]; public String permissions[]; public Rule(String auth[]) { this.auth = auth; } public Rule(String auth[], String roles[], String permissions[]) { this.auth = auth; this.roles = roles; this.permissions = permissions; } public Rule(String auth[], String roles[]) { this.auth = auth; this.roles = roles; } }
512
0.591797
0.591797
24
20.333334
18.530756
70
false
false
0
0
0
0
0
0
0.541667
false
false
10
6cb7a275dec153f5765e6c0f1388063f75101bcc
24,524,263,276,030
08cc124e65dd516ac44fbb80809a1b959690e954
/src/com/zjg/factoryMethodPattern/Product.java
0b9845fa6b3713fdfbf00bd1500a217d26d08fd1
[]
no_license
zhang2/JavaDesignPattern
https://github.com/zhang2/JavaDesignPattern
2b074ef66dd27a45cb02cbb3d49f1ad8fffe1bff
5b6da6f36801fafff895ac76ef49aa2b8b200688
refs/heads/master
2021-07-24T11:41:52.801000
2020-09-21T08:36:23
2020-09-21T08:36:23
218,234,225
0
0
null
false
2019-10-29T09:32:48
2019-10-29T08:04:37
2019-10-29T08:54:40
2019-10-29T09:32:47
49
0
0
0
Java
false
false
/** * */ package com.zjg.factoryMethodPattern; /** * @author apple * */ public abstract class Product { }
UTF-8
Java
115
java
Product.java
Java
[ { "context": "kage com.zjg.factoryMethodPattern;\n\n/**\n * @author apple\n *\n */\npublic abstract class Product {\n\t\n}\n", "end": 71, "score": 0.9939822554588318, "start": 66, "tag": "USERNAME", "value": "apple" } ]
null
[]
/** * */ package com.zjg.factoryMethodPattern; /** * @author apple * */ public abstract class Product { }
115
0.608696
0.608696
12
8.583333
12.086206
37
false
false
0
0
0
0
0
0
0.166667
false
false
10
93d1ca063cece7a1ba803fdda5780c96e2abd8f8
17,892,833,772,028
90d3bcfb1c44ef121da126036b42da0cdc00d159
/src/main/java/Account.java
99986bd7fa7ebcb169acd265c0556933a1e73da0
[]
no_license
rajithavk/Accouting
https://github.com/rajithavk/Accouting
02c8323ff16543e3f50f598a23b15d4ab30f129e
8434e1c98122a2323617fbb2f9c3d8dea8cae4b9
refs/heads/master
2016-09-05T11:29:36.231000
2015-05-18T17:02:22
2015-05-18T17:02:22
35,345,978
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package accountingsample; /** * * @author UDARA */ import java.util.List; import org.hibernate.HibernateException; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.classic.Session; import javax.persistence.*; @Entity //@Table(name="account") public class Account{ @Id @GeneratedValue private int accNo = -1; @Column(name="balance") private double balance; @Column(name="owner_type") private String ownerType; // @Column(name="credit_account") // private String accType; // // @Column(name="credit_account") // private String status; @Column(name="acc_name") private String accName; public Account() { } public Account( double amount, String ownerType, String accName){ this.balance = amount; this.ownerType = ownerType; this.accName = accName; } public double getBalance(){ return balance; } public void setBalance(double amount){ this.balance = amount; } public String getOwnerType(){ return ownerType; } public void setOwnerType(String ownerType){ this.ownerType = ownerType; } public int save(){ return saveAccount(this); } public int delete(){ return deleteAccount(this); } public int getId(){ return this.accNo; } public void setId(int accNo){ this.accNo = accNo; } public String getName(){ return accName; } private static int saveAccount(Account account){ SessionFactory factory = HibernateUtil.getSessionFactory(); Session session = factory.openSession(); Transaction tx = null; Integer bid = null; try{ tx = session.beginTransaction(); if(account.getId() == -1) { bid = (Integer) session.save(account); account.setId(bid); }else{ session.merge(account); bid = account.getId(); } tx.commit(); }catch (HibernateException e){ if(tx!=null) tx.rollback(); e.printStackTrace(); }finally { session.close(); } return bid; } private static int deleteAccount(Account account){ SessionFactory factory = HibernateUtil.getSessionFactory(); Session session = factory.openSession(); Transaction tx = null; Integer bid = null; try{ bid = account.getId(); if(bid != -1) { tx = session.beginTransaction(); session.delete(account); tx.commit(); } }catch (HibernateException e){ if(tx!=null) tx.rollback(); e.printStackTrace(); }finally { session.close(); } return bid; } }
UTF-8
Java
3,223
java
Account.java
Java
[ { "context": "\r\npackage accountingsample;\r\n\r\n/**\r\n *\r\n * @author UDARA\r\n */\r\nimport java.util.List;\r\nimport org.hibernat", "end": 158, "score": 0.9929449558258057, "start": 153, "tag": "NAME", "value": "UDARA" } ]
null
[]
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package accountingsample; /** * * @author UDARA */ import java.util.List; import org.hibernate.HibernateException; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.classic.Session; import javax.persistence.*; @Entity //@Table(name="account") public class Account{ @Id @GeneratedValue private int accNo = -1; @Column(name="balance") private double balance; @Column(name="owner_type") private String ownerType; // @Column(name="credit_account") // private String accType; // // @Column(name="credit_account") // private String status; @Column(name="acc_name") private String accName; public Account() { } public Account( double amount, String ownerType, String accName){ this.balance = amount; this.ownerType = ownerType; this.accName = accName; } public double getBalance(){ return balance; } public void setBalance(double amount){ this.balance = amount; } public String getOwnerType(){ return ownerType; } public void setOwnerType(String ownerType){ this.ownerType = ownerType; } public int save(){ return saveAccount(this); } public int delete(){ return deleteAccount(this); } public int getId(){ return this.accNo; } public void setId(int accNo){ this.accNo = accNo; } public String getName(){ return accName; } private static int saveAccount(Account account){ SessionFactory factory = HibernateUtil.getSessionFactory(); Session session = factory.openSession(); Transaction tx = null; Integer bid = null; try{ tx = session.beginTransaction(); if(account.getId() == -1) { bid = (Integer) session.save(account); account.setId(bid); }else{ session.merge(account); bid = account.getId(); } tx.commit(); }catch (HibernateException e){ if(tx!=null) tx.rollback(); e.printStackTrace(); }finally { session.close(); } return bid; } private static int deleteAccount(Account account){ SessionFactory factory = HibernateUtil.getSessionFactory(); Session session = factory.openSession(); Transaction tx = null; Integer bid = null; try{ bid = account.getId(); if(bid != -1) { tx = session.beginTransaction(); session.delete(account); tx.commit(); } }catch (HibernateException e){ if(tx!=null) tx.rollback(); e.printStackTrace(); }finally { session.close(); } return bid; } }
3,223
0.531182
0.530251
139
21.201439
16.759912
69
false
false
0
0
0
0
0
0
0.395683
false
false
10
3a826911f8cc16d892560fdbbfeab551dacc1687
17,892,833,770,453
48d8b9f807c61973ea9a22b47cc5a5b5dbbd5cef
/src/com/rgirish2/piece/KadabraPiece.java
cbb43b0a2ff92ea57ec691abd215dbfd1b131310
[]
no_license
rgirish2/AbstractChessGame
https://github.com/rgirish2/AbstractChessGame
1da6f2d6aa8dddce225944d798548a65e8ba7e19
3698a8ba2e7e90d7b7f780e2aa5b974a86c30251
refs/heads/master
2020-09-13T07:05:56.245000
2014-09-29T07:12:19
2014-09-29T07:12:19
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.rgirish2.piece; import com.rgirish2.assignment1.board.AbstractTwoDimensionalBoard; /** * A hypothetical piece created just to explain the process of creating new * pieces in this project structure. * @author Rishi Girish(rgirish2ATillinoisDOTedu) * */ public class KadabraPiece extends AbstractTwoDimensionalPiece { public KadabraPiece(String playerName, int posX, int posY, NormalPlayerOrdinal ordinal) { super(playerName, posX, posY, PieceType.KADABRA, ordinal, "KADABRA"); } /** * This method verifies whether the move being request is valid or not. * @param board The board on which this movement is being requested. * @param newPosX The new X dimensional position of this piece in a 2-D board. * @param newPosY The new Y dimensional position of this piece in a 2-D board. * @return True if this move valid, False otherwise. */ @Override public boolean isValidMove(AbstractTwoDimensionalBoard board, int newPosX, int newPosY) { if (board.getDimensionCount() != 2) { return false; } else if (newPosX < 0 || newPosX > board.getDimensionOne() || newPosY < 0 || newPosY > board.getDimensionTwo()){ return false; } else if (newPosX == this.getPosX() && newPosY == this.getPosY()) { return false; } else { if (board.getBoard()[newPosX][newPosY] != null) { AbstractTwoDimensionalPiece piece = board.getBoard()[newPosX][newPosY].getPiece(); if (piece.getPieceType().equals(PieceType.KING) && piece.getOrdinal().equals(this.getOrdinal())) { return true; } } } return false; } }
UTF-8
Java
1,558
java
KadabraPiece.java
Java
[ { "context": "ew\n * pieces in this project structure.\n * @author Rishi Girish(rgirish2ATillinoisDOTedu)\n *\n */\npublic class Kad", "end": 237, "score": 0.9998974800109863, "start": 225, "tag": "NAME", "value": "Rishi Girish" }, { "context": "this project structure.\n * @author Rishi Girish(rgirish2ATillinoisDOTedu)\n *\n */\npublic class KadabraPiece extends Abstrac", "end": 262, "score": 0.797966718673706, "start": 240, "tag": "EMAIL", "value": "irish2ATillinoisDOTedu" } ]
null
[]
package com.rgirish2.piece; import com.rgirish2.assignment1.board.AbstractTwoDimensionalBoard; /** * A hypothetical piece created just to explain the process of creating new * pieces in this project structure. * @author <NAME>(rg<EMAIL>) * */ public class KadabraPiece extends AbstractTwoDimensionalPiece { public KadabraPiece(String playerName, int posX, int posY, NormalPlayerOrdinal ordinal) { super(playerName, posX, posY, PieceType.KADABRA, ordinal, "KADABRA"); } /** * This method verifies whether the move being request is valid or not. * @param board The board on which this movement is being requested. * @param newPosX The new X dimensional position of this piece in a 2-D board. * @param newPosY The new Y dimensional position of this piece in a 2-D board. * @return True if this move valid, False otherwise. */ @Override public boolean isValidMove(AbstractTwoDimensionalBoard board, int newPosX, int newPosY) { if (board.getDimensionCount() != 2) { return false; } else if (newPosX < 0 || newPosX > board.getDimensionOne() || newPosY < 0 || newPosY > board.getDimensionTwo()){ return false; } else if (newPosX == this.getPosX() && newPosY == this.getPosY()) { return false; } else { if (board.getBoard()[newPosX][newPosY] != null) { AbstractTwoDimensionalPiece piece = board.getBoard()[newPosX][newPosY].getPiece(); if (piece.getPieceType().equals(PieceType.KING) && piece.getOrdinal().equals(this.getOrdinal())) { return true; } } } return false; } }
1,537
0.719512
0.713736
42
36.095238
35.145149
115
false
false
0
0
0
0
0
0
2
false
false
10
18f67be7757d4a71793139e375816cc6cd4ed5a3
24,850,680,793,794
375450244d99b8f4b1ef91b613f21d8961177d67
/demo-test/src/main/java/com/ruzhi/demo/test/self/validation/DemoForSelfValidation.java
4824977774faa033155561b911ab57f4ced2178f
[]
no_license
sailor0508/ruzhi_artifact
https://github.com/sailor0508/ruzhi_artifact
a70268d0d6212389ff19f1be162e359cbfad098d
8ef786c307a1ae1e26308b1c8ca36dcc945eed90
refs/heads/master
2020-06-10T16:21:55.374000
2017-11-08T10:32:33
2017-11-08T10:32:33
75,937,779
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ruzhi.demo.test.self.validation; import javax.validation.Valid; import javax.validation.constraints.NotNull; /** * Created by chunlong.wchl on 2015/6/3. */ public class DemoForSelfValidation { @SelfNotEmpty(message = "company is blank")//java有自带的NotEmpty,这里只是实验一下自定义注解,实验的时候最好不要和自带的重名 private String company=""; @MyPatternOfString.List({ @MyPatternOfString(mustContainLetter = "CH", message = "It does not belong toChina"), @MyPatternOfString(mustContainLetter = "MainLand", message = "It does not belong toMainLand") }) private String place = ""; @NotNull @Valid private Person person; //级联验证的方式(首先需要保证对象不会空,否则在级联验证是会异常,可能不会输出验证信息) public String getCompany() { return company; } public void setCompany(String company) { this.company = company; } public String getPlace() { return place; } public void setPlace(String place) { this.place = place; } public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } }
UTF-8
Java
1,336
java
DemoForSelfValidation.java
Java
[ { "context": "idation.constraints.NotNull;\r\n\r\n/**\r\n * Created by chunlong.wchl on 2015/6/3.\r\n */\r\npublic class DemoForSelfValida", "end": 162, "score": 0.9989586472511292, "start": 149, "tag": "USERNAME", "value": "chunlong.wchl" } ]
null
[]
package com.ruzhi.demo.test.self.validation; import javax.validation.Valid; import javax.validation.constraints.NotNull; /** * Created by chunlong.wchl on 2015/6/3. */ public class DemoForSelfValidation { @SelfNotEmpty(message = "company is blank")//java有自带的NotEmpty,这里只是实验一下自定义注解,实验的时候最好不要和自带的重名 private String company=""; @MyPatternOfString.List({ @MyPatternOfString(mustContainLetter = "CH", message = "It does not belong toChina"), @MyPatternOfString(mustContainLetter = "MainLand", message = "It does not belong toMainLand") }) private String place = ""; @NotNull @Valid private Person person; //级联验证的方式(首先需要保证对象不会空,否则在级联验证是会异常,可能不会输出验证信息) public String getCompany() { return company; } public void setCompany(String company) { this.company = company; } public String getPlace() { return place; } public void setPlace(String place) { this.place = place; } public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } }
1,336
0.630691
0.625632
48
22.708334
26.205883
105
false
false
0
0
0
0
0
0
0.3125
false
false
10
8410f7b949afdff8e0fec7789624de75f9f142c1
2,370,821,964,066
c398c220f54b9d5a090eda7ebc7e6f99347ccc9b
/src/ListCreator.java
7769a5882a32548ceb9a0a7631ca57fd540cd347
[ "Apache-2.0" ]
permissive
maliknsj/Coding-Guru
https://github.com/maliknsj/Coding-Guru
0a674736b07958278495ffbd31ea774ef7ae7481
f9898f41e9d0c7595b902515ef3c4be1ae239883
refs/heads/master
2020-06-11T22:22:23.970000
2016-12-05T11:19:54
2016-12-05T11:19:54
75,617,120
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.apache.commons.collections4.iterators.IteratorChain; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.HorizontalAlignment; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.VerticalAlignment; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xssf.usermodel.helpers.XSSFXmlColumnPr; public class ListCreator { /* * output.xlsx and input.xlsx should in same directory of running jar */ public class RowData { public int sentenceId; public int rowId; public String sentence; public RowData(int sentenceId, int rowId, String sentence) { this.sentenceId = sentenceId; this.rowId = rowId; this.sentence = sentence; } } public void LoadAndCreatLists(String filePath){ File f=new File("output.xlsx"); if(!f.exists()){ try { ArrayList<RowData> mydata=new ArrayList<>(); FileInputStream file=new FileInputStream(new File("input.xlsx")); XSSFWorkbook input=new XSSFWorkbook(file); XSSFSheet datasheet=input.getSheetAt(0); Iterator<Row> rowIterator = datasheet.iterator(); rowIterator.next(); int sentence=1; int rowid=-1; while(rowIterator.hasNext()){ Row row=rowIterator.next(); Iterator<Cell> cellIterator=row.cellIterator(); while(cellIterator.hasNext()){ Cell cell = cellIterator.next(); //Check the cell type and format accordingly switch (cell.getCellType()) { case Cell.CELL_TYPE_NUMERIC: rowid=(int) cell.getNumericCellValue(); break; case Cell.CELL_TYPE_STRING: String str=cell.getStringCellValue(); String[] tok=str.split("[.?]"); for(int i=0;i<tok.length;i++){ if(!(tok[i].trim().equals("") || (tok[i].length()<5))){ //System.out.println(sentence+" "+rowid+": "+tok[i]); mydata.add(new RowData(sentence, rowid, tok[i].trim())); sentence++; } } break; } } } file.close(); createLists(mydata); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } private void createLists(ArrayList<RowData> data){ XSSFWorkbook workbook=new XSSFWorkbook(); XSSFSheet sheet=workbook.createSheet("Task 1"); XSSFSheet sheet2=workbook.createSheet("Task 2"); XSSFSheet sheet3=workbook.createSheet("Task 3"); //Task_1 Header XSSFRow row=sheet.createRow(0); XSSFCell c1=row.createCell(0); c1.getCellStyle().setWrapText(true); c1.setCellValue("sentence_id"); XSSFCell c2=row.createCell(1); c2.setCellValue((String) "row id"); XSSFCell c3=row.createCell(2); c3.setCellValue((String)"Sentence"); //Task_2 Header Row row2=sheet2.createRow(0); row2.createCell(0).setCellValue("ID"); row2.createCell(1).setCellValue("Sentence_ID"); row2.createCell(2).setCellValue("Sentence"); row2.createCell(3).setCellValue("CheckBox 1"); row2.createCell(4).setCellValue("CheckBox 2"); row2.createCell(5).setCellValue("CheckBox 3"); row2.createCell(6).setCellValue("CheckBox 4"); row2.createCell(7).setCellValue("CheckBox 5"); row2.createCell(8).setCellValue("CheckBox 6"); row2.createCell(9).setCellValue("CheckBox 7"); row2.createCell(10).setCellValue("Skip Count"); row2.createCell(11).setCellValue("Submit Count"); int rownum = 1; for(RowData r:data){ row=sheet.createRow(rownum); row2=sheet2.createRow(rownum); System.out.println(r.sentenceId+" "+r.rowId+" "+r.sentence); c1=row.createCell(0); c1.setCellValue((Integer) r.sentenceId); c2=row.createCell(1); c2.setCellValue((Integer) r.rowId); c3=row.createCell(2); c3.setCellValue((String)r.sentence); row2.createCell(0).setCellValue(r.sentenceId); row2.createCell(1).setCellValue(r.sentenceId); row2.createCell(2).setCellValue(r.sentence); row2.createCell(3).setCellValue(0); row2.createCell(4).setCellValue(0); row2.createCell(5).setCellValue(0); row2.createCell(6).setCellValue(0); row2.createCell(7).setCellValue(0); row2.createCell(8).setCellValue(0); row2.createCell(9).setCellValue(0); row2.createCell(10).setCellValue(0); row2.createCell(11).setCellValue(0); rownum++; } try { //Write the workbook in file system FileOutputStream out = new FileOutputStream(new File("Output.xlsx")); workbook.write(out); out.close(); System.out.println("howtodoinjava_demo.xlsx written successfully on disk."); } catch (Exception e) { } } }
UTF-8
Java
5,354
java
ListCreator.java
Java
[]
null
[]
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.apache.commons.collections4.iterators.IteratorChain; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.HorizontalAlignment; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.VerticalAlignment; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xssf.usermodel.helpers.XSSFXmlColumnPr; public class ListCreator { /* * output.xlsx and input.xlsx should in same directory of running jar */ public class RowData { public int sentenceId; public int rowId; public String sentence; public RowData(int sentenceId, int rowId, String sentence) { this.sentenceId = sentenceId; this.rowId = rowId; this.sentence = sentence; } } public void LoadAndCreatLists(String filePath){ File f=new File("output.xlsx"); if(!f.exists()){ try { ArrayList<RowData> mydata=new ArrayList<>(); FileInputStream file=new FileInputStream(new File("input.xlsx")); XSSFWorkbook input=new XSSFWorkbook(file); XSSFSheet datasheet=input.getSheetAt(0); Iterator<Row> rowIterator = datasheet.iterator(); rowIterator.next(); int sentence=1; int rowid=-1; while(rowIterator.hasNext()){ Row row=rowIterator.next(); Iterator<Cell> cellIterator=row.cellIterator(); while(cellIterator.hasNext()){ Cell cell = cellIterator.next(); //Check the cell type and format accordingly switch (cell.getCellType()) { case Cell.CELL_TYPE_NUMERIC: rowid=(int) cell.getNumericCellValue(); break; case Cell.CELL_TYPE_STRING: String str=cell.getStringCellValue(); String[] tok=str.split("[.?]"); for(int i=0;i<tok.length;i++){ if(!(tok[i].trim().equals("") || (tok[i].length()<5))){ //System.out.println(sentence+" "+rowid+": "+tok[i]); mydata.add(new RowData(sentence, rowid, tok[i].trim())); sentence++; } } break; } } } file.close(); createLists(mydata); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } private void createLists(ArrayList<RowData> data){ XSSFWorkbook workbook=new XSSFWorkbook(); XSSFSheet sheet=workbook.createSheet("Task 1"); XSSFSheet sheet2=workbook.createSheet("Task 2"); XSSFSheet sheet3=workbook.createSheet("Task 3"); //Task_1 Header XSSFRow row=sheet.createRow(0); XSSFCell c1=row.createCell(0); c1.getCellStyle().setWrapText(true); c1.setCellValue("sentence_id"); XSSFCell c2=row.createCell(1); c2.setCellValue((String) "row id"); XSSFCell c3=row.createCell(2); c3.setCellValue((String)"Sentence"); //Task_2 Header Row row2=sheet2.createRow(0); row2.createCell(0).setCellValue("ID"); row2.createCell(1).setCellValue("Sentence_ID"); row2.createCell(2).setCellValue("Sentence"); row2.createCell(3).setCellValue("CheckBox 1"); row2.createCell(4).setCellValue("CheckBox 2"); row2.createCell(5).setCellValue("CheckBox 3"); row2.createCell(6).setCellValue("CheckBox 4"); row2.createCell(7).setCellValue("CheckBox 5"); row2.createCell(8).setCellValue("CheckBox 6"); row2.createCell(9).setCellValue("CheckBox 7"); row2.createCell(10).setCellValue("Skip Count"); row2.createCell(11).setCellValue("Submit Count"); int rownum = 1; for(RowData r:data){ row=sheet.createRow(rownum); row2=sheet2.createRow(rownum); System.out.println(r.sentenceId+" "+r.rowId+" "+r.sentence); c1=row.createCell(0); c1.setCellValue((Integer) r.sentenceId); c2=row.createCell(1); c2.setCellValue((Integer) r.rowId); c3=row.createCell(2); c3.setCellValue((String)r.sentence); row2.createCell(0).setCellValue(r.sentenceId); row2.createCell(1).setCellValue(r.sentenceId); row2.createCell(2).setCellValue(r.sentence); row2.createCell(3).setCellValue(0); row2.createCell(4).setCellValue(0); row2.createCell(5).setCellValue(0); row2.createCell(6).setCellValue(0); row2.createCell(7).setCellValue(0); row2.createCell(8).setCellValue(0); row2.createCell(9).setCellValue(0); row2.createCell(10).setCellValue(0); row2.createCell(11).setCellValue(0); rownum++; } try { //Write the workbook in file system FileOutputStream out = new FileOutputStream(new File("Output.xlsx")); workbook.write(out); out.close(); System.out.println("howtodoinjava_demo.xlsx written successfully on disk."); } catch (Exception e) { } } }
5,354
0.683975
0.66399
160
31.4625
18.524944
79
false
false
0
0
0
0
0
0
3.31875
false
false
10
72908e4269614cb14d4cb621e33b7f795c9e04fe
17,832,704,229,365
63508e9c11f08eb22807fc498107a69aefb8dc47
/src/tuto/FirstExtraction.java
1093d7b3733fd56da2dffb74d563773b43a2d90d
[]
no_license
ZacharieALES/viesa
https://github.com/ZacharieALES/viesa
ff5378294f9b988ba910aa001048567096b34f8b
f34b9619dacd244a702274e11f206ab5dae46908
refs/heads/master
2021-01-23T23:03:05.106000
2018-05-29T10:05:55
2018-05-29T10:05:55
102,952,711
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package tuto; public class FirstExtraction extends AbstractTutoStep { @Override public void stepInitialization() { getSelectionPanel().jb_process_extraction.setEnabled(true); } @Override public void stepFinalization() { getSelectionPanel().jb_process_extraction.setEnabled(false); } @Override public String description() { return "The aim of this software is to extract regularities in <i>annotation arrays</i>.<br>" + "An annotation array is a data structure in which: <br>" + "- the order of the lines is important (it usually represent temporality);<br>" + "- the order of the columns is irrelevant (they could be exchanged without altering the meaning of the data).<br><br>" + "In this tutorial we consider two very simple arrays named \"Tuto file 1.csv\" and \"Tuto file 2.csv\".<br>" + "One of them is currently displayed in the above overview and you can click on the name of the other in the list located<br>" + "in the area labeled \"Corpus\" to visualize it.<br><br>" + "You are currently in the tab which enables to modify the extraction parameters. <br>" + "Before explaining how these parameters work, we will perform a first extraction to see the regularities obtained with the <br>" + "default values."; } @Override public String instructions() { return "Start the extraction by pressing the button named \"Extract\""; } @Override public String resultsComment() { return "You are now in the visualization tab which is automatically displayed at the end of each extraction.<br><br>" + "This tab enables to display the obtained <i>alignments</i>.<br>" + "The term \"alignment\" characterizes two subparts of two different arrays which are similar.<br>" + "You can see four tables (2 on the left, 2 on the right). <br>" + "The two tables on the right represent the two arrays involved in the <b>first</b> alignment. <br>" + "The two tables on the left represent the two arrays involved in the <b>second</b> alignment. <br>" + "The annotations which are part of an alignment are displayed in red."; } @Override public String gotoName() { return "Extract patterns"; } @Override public void actionsIfSkipped() {} }
UTF-8
Java
2,225
java
FirstExtraction.java
Java
[]
null
[]
package tuto; public class FirstExtraction extends AbstractTutoStep { @Override public void stepInitialization() { getSelectionPanel().jb_process_extraction.setEnabled(true); } @Override public void stepFinalization() { getSelectionPanel().jb_process_extraction.setEnabled(false); } @Override public String description() { return "The aim of this software is to extract regularities in <i>annotation arrays</i>.<br>" + "An annotation array is a data structure in which: <br>" + "- the order of the lines is important (it usually represent temporality);<br>" + "- the order of the columns is irrelevant (they could be exchanged without altering the meaning of the data).<br><br>" + "In this tutorial we consider two very simple arrays named \"Tuto file 1.csv\" and \"Tuto file 2.csv\".<br>" + "One of them is currently displayed in the above overview and you can click on the name of the other in the list located<br>" + "in the area labeled \"Corpus\" to visualize it.<br><br>" + "You are currently in the tab which enables to modify the extraction parameters. <br>" + "Before explaining how these parameters work, we will perform a first extraction to see the regularities obtained with the <br>" + "default values."; } @Override public String instructions() { return "Start the extraction by pressing the button named \"Extract\""; } @Override public String resultsComment() { return "You are now in the visualization tab which is automatically displayed at the end of each extraction.<br><br>" + "This tab enables to display the obtained <i>alignments</i>.<br>" + "The term \"alignment\" characterizes two subparts of two different arrays which are similar.<br>" + "You can see four tables (2 on the left, 2 on the right). <br>" + "The two tables on the right represent the two arrays involved in the <b>first</b> alignment. <br>" + "The two tables on the left represent the two arrays involved in the <b>second</b> alignment. <br>" + "The annotations which are part of an alignment are displayed in red."; } @Override public String gotoName() { return "Extract patterns"; } @Override public void actionsIfSkipped() {} }
2,225
0.715506
0.713708
53
40.981133
42.3563
134
false
false
0
0
0
0
0
0
1.924528
false
false
10
d8c8a463e67cd9dfd71221b8e0bb25a2080dcd19
31,009,663,946,318
722b98fd4b9e973cb4952693bdde0d5550f5cf9a
/src/MergeSortPerformance.java
30178720568914058681f966016a93c94bd06f03
[]
no_license
cartersa79/MergeSortPerformance
https://github.com/cartersa79/MergeSortPerformance
0066318ab94a8134211d07a078704e7343f6b5df
9e95ee10a02922be5e8b499395e16666a85718d8
refs/heads/master
2020-08-08T06:56:21.889000
2019-10-08T22:29:46
2019-10-08T22:29:46
213,768,069
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.lang.management.ManagementFactory; import java.lang.management.ThreadMXBean; import java.io.*; import java.lang.reflect.Array; import java.util.Arrays; import java.util.function.Function; public class MergeSortPerformance { static ThreadMXBean bean = ManagementFactory.getThreadMXBean(); /* define constants */ static long MAXVALUE = 2000000000; static long MINVALUE = -2000000000; static int numberOfTrials = 50; // adjust numberOfTrials and MAXINPUTSIZE based on available static int MAXINPUTSIZE = (int) Math.pow(2, 20); // time, processor speed, and available memory static int MININPUTSIZE = 1; static String ResultsFolderPath = "/home/steve/Results/"; // pathname to results folder static FileWriter resultsFile; static PrintWriter resultsWriter; public static void main(String[] args) { // run the whole experiment at least twice, and expect to throw away the data from the earlier runs, before java has fully optimized System.out.println("Running first full experiment..."); runFullExperiment("MergeSort-Exp1-ThrowAway.txt"); System.out.println("Running second full experiment..."); runFullExperiment("MergeSort-Exp2.txt"); System.out.println("Running third full experiment..."); runFullExperiment("MergeSort-Exp3.txt"); // verify that the algorithm works System.out.println(""); System.out.println("----Verification Test----"); checkSortCorrectness(); long[] verificationList = createRandomIntegerList(1000); long[] verificationList2 = createRandomIntegerList(10000); System.out.println("-------------------------"); System.out.println("Array of 1000 sorted?: " + verifySorted(verificationList)); System.out.println("Array of 10000 sorted?: " + verifySorted(verificationList2)); System.out.println("Sorting..."); mergeSort(verificationList); mergeSort(verificationList2); System.out.println("Array of 1000 sorted?: " + verifySorted(verificationList)); System.out.println("Array of 10000 sorted?: " + verifySorted(verificationList2)); } static void runFullExperiment(String resultsFileName) { try { resultsFile = new FileWriter(ResultsFolderPath + resultsFileName); resultsWriter = new PrintWriter(resultsFile); } catch (Exception e) { System.out.println("*****!!!!! Had a problem opening the results file " + ResultsFolderPath + resultsFileName); return; // not very foolproof... but we do expect to be able to create/open the file... } ThreadCpuStopWatch BatchStopwatch = new ThreadCpuStopWatch(); // for timing an entire set of trials ThreadCpuStopWatch TrialStopwatch = new ThreadCpuStopWatch(); // for timing an individual trial resultsWriter.println("#InputSize AverageTime"); // # marks a comment in gnuplot data resultsWriter.flush(); /* for each size of input we want to test: in this case starting small and doubling the size each time */ for (int inputSize = MININPUTSIZE; inputSize <= MAXINPUTSIZE; inputSize *= 2) { // progress message... System.out.println("Running test for input size " + inputSize + " ... "); /* repeat for desired number of trials (for a specific size of input)... */ long batchElapsedTime = 0; // generate a list of random integers in random order to use as test input // In this case we're generating one list to use for the entire set of trials (of a given input size) //System.out.print(" Generating test data..."); //long[] testList = createRandomIntegerList(inputSize); //System.out.println("...done."); //System.out.print(" Running trial batch..."); /* force garbage collection before each batch of trials run so it is not included in the time */ System.gc(); // instead of timing each individual trial, we will time the entire set of trials (for a given input size) // and divide by the number of trials -- this reduces the impact of the amount of time it takes to call the // stopWatch methods themselves //BatchStopwatch.start(); // comment this line if timing trials individually // run the trials for (long trial = 0; trial < numberOfTrials; trial++) { // generate a random list of integers each trial long[] testList = createRandomIntegerList(inputSize); // generate a random key to search in the range of a the min/max numbers in the list // long testSearchKey = (long) (0 + Math.random() * (testList[testList.length - 1])); /* force garbage collection before each trial run so it is not included in the time */ // System.gc(); TrialStopwatch.start(); // *** uncomment this line if timing trials individually /* run the function we're testing on the trial input */ mergeSort(testList); batchElapsedTime = batchElapsedTime + TrialStopwatch.elapsedTime(); // *** uncomment this line if timing trials individually } //batchElapsedTime = BatchStopwatch.elapsedTime(); // *** comment this line if timing trials individually double averageTimePerTrialInBatch = (double) batchElapsedTime / (double) numberOfTrials; // calculate the average time per trial in this batch /* print data for this size of input */ resultsWriter.printf("%12d %15.2f \n", inputSize, averageTimePerTrialInBatch); // might as well make the columns look nice resultsWriter.flush(); System.out.println(" ....done."); } } // the algorithm from www.java67.com was used as a starting point but was modified // to suit the needs of the assignment public static void mergeSort(long[] input) { mergeSort(input, 0, input.length - 1); } private static void mergeSort(long[] input, int start, int end) { // break problem into smaller structurally identical problems int mid = (start + end) / 2; // get midpoint if (start < end) { mergeSort(input, start, mid); mergeSort(input, mid + 1, end); } // merge solved pieces to get solution to original problem int i = 0, first = start, last = mid + 1; long[] tmp = new long[end - start + 1]; while (first <= mid && last <= end) { tmp[i++] = input[first] < input[last] ? input[first++] : input[last++]; } while (first <= mid) { tmp[i++] = input[first++]; } while (last <= end) { tmp[i++] = input[last++]; } i = 0; while (start <= end) { input[start++] = tmp[i++]; } } // generate a random list of values to test against public static long[] createRandomIntegerList(int size) { long[] newList = new long[size]; // randomly picks a value between -1000000000 and 1000000000 for (int i = 0; i < size; i++) { newList[i] = (long) ((2000000000 * Math.random()) - 1000000000); } return newList; // return the list to caller } // verifies that an array is sorted in ascending (low to high) order private static boolean verifySorted(long[] list) { for (int i = 0; i < list.length - 1; i++){ if (list[i] > list[i+1]) return false; } return true; } // verifies that an array is sorted in ascending (low to high) order private static void checkSortCorrectness(){ long[] testArray = createRandomIntegerList(10); System.out.print("Unsorted Small Random Test Array: "); System.out.println(Arrays.toString(testArray)); System.out.println("The array is sorted: " + verifySorted(testArray)); System.out.println("Sorting..."); mergeSort(testArray); System.out.print("Small Random Test Array After Sort: "); System.out.println(Arrays.toString(testArray)); System.out.println("The array is sorted: " + verifySorted(testArray)); } }
UTF-8
Java
8,387
java
MergeSortPerformance.java
Java
[]
null
[]
import java.lang.management.ManagementFactory; import java.lang.management.ThreadMXBean; import java.io.*; import java.lang.reflect.Array; import java.util.Arrays; import java.util.function.Function; public class MergeSortPerformance { static ThreadMXBean bean = ManagementFactory.getThreadMXBean(); /* define constants */ static long MAXVALUE = 2000000000; static long MINVALUE = -2000000000; static int numberOfTrials = 50; // adjust numberOfTrials and MAXINPUTSIZE based on available static int MAXINPUTSIZE = (int) Math.pow(2, 20); // time, processor speed, and available memory static int MININPUTSIZE = 1; static String ResultsFolderPath = "/home/steve/Results/"; // pathname to results folder static FileWriter resultsFile; static PrintWriter resultsWriter; public static void main(String[] args) { // run the whole experiment at least twice, and expect to throw away the data from the earlier runs, before java has fully optimized System.out.println("Running first full experiment..."); runFullExperiment("MergeSort-Exp1-ThrowAway.txt"); System.out.println("Running second full experiment..."); runFullExperiment("MergeSort-Exp2.txt"); System.out.println("Running third full experiment..."); runFullExperiment("MergeSort-Exp3.txt"); // verify that the algorithm works System.out.println(""); System.out.println("----Verification Test----"); checkSortCorrectness(); long[] verificationList = createRandomIntegerList(1000); long[] verificationList2 = createRandomIntegerList(10000); System.out.println("-------------------------"); System.out.println("Array of 1000 sorted?: " + verifySorted(verificationList)); System.out.println("Array of 10000 sorted?: " + verifySorted(verificationList2)); System.out.println("Sorting..."); mergeSort(verificationList); mergeSort(verificationList2); System.out.println("Array of 1000 sorted?: " + verifySorted(verificationList)); System.out.println("Array of 10000 sorted?: " + verifySorted(verificationList2)); } static void runFullExperiment(String resultsFileName) { try { resultsFile = new FileWriter(ResultsFolderPath + resultsFileName); resultsWriter = new PrintWriter(resultsFile); } catch (Exception e) { System.out.println("*****!!!!! Had a problem opening the results file " + ResultsFolderPath + resultsFileName); return; // not very foolproof... but we do expect to be able to create/open the file... } ThreadCpuStopWatch BatchStopwatch = new ThreadCpuStopWatch(); // for timing an entire set of trials ThreadCpuStopWatch TrialStopwatch = new ThreadCpuStopWatch(); // for timing an individual trial resultsWriter.println("#InputSize AverageTime"); // # marks a comment in gnuplot data resultsWriter.flush(); /* for each size of input we want to test: in this case starting small and doubling the size each time */ for (int inputSize = MININPUTSIZE; inputSize <= MAXINPUTSIZE; inputSize *= 2) { // progress message... System.out.println("Running test for input size " + inputSize + " ... "); /* repeat for desired number of trials (for a specific size of input)... */ long batchElapsedTime = 0; // generate a list of random integers in random order to use as test input // In this case we're generating one list to use for the entire set of trials (of a given input size) //System.out.print(" Generating test data..."); //long[] testList = createRandomIntegerList(inputSize); //System.out.println("...done."); //System.out.print(" Running trial batch..."); /* force garbage collection before each batch of trials run so it is not included in the time */ System.gc(); // instead of timing each individual trial, we will time the entire set of trials (for a given input size) // and divide by the number of trials -- this reduces the impact of the amount of time it takes to call the // stopWatch methods themselves //BatchStopwatch.start(); // comment this line if timing trials individually // run the trials for (long trial = 0; trial < numberOfTrials; trial++) { // generate a random list of integers each trial long[] testList = createRandomIntegerList(inputSize); // generate a random key to search in the range of a the min/max numbers in the list // long testSearchKey = (long) (0 + Math.random() * (testList[testList.length - 1])); /* force garbage collection before each trial run so it is not included in the time */ // System.gc(); TrialStopwatch.start(); // *** uncomment this line if timing trials individually /* run the function we're testing on the trial input */ mergeSort(testList); batchElapsedTime = batchElapsedTime + TrialStopwatch.elapsedTime(); // *** uncomment this line if timing trials individually } //batchElapsedTime = BatchStopwatch.elapsedTime(); // *** comment this line if timing trials individually double averageTimePerTrialInBatch = (double) batchElapsedTime / (double) numberOfTrials; // calculate the average time per trial in this batch /* print data for this size of input */ resultsWriter.printf("%12d %15.2f \n", inputSize, averageTimePerTrialInBatch); // might as well make the columns look nice resultsWriter.flush(); System.out.println(" ....done."); } } // the algorithm from www.java67.com was used as a starting point but was modified // to suit the needs of the assignment public static void mergeSort(long[] input) { mergeSort(input, 0, input.length - 1); } private static void mergeSort(long[] input, int start, int end) { // break problem into smaller structurally identical problems int mid = (start + end) / 2; // get midpoint if (start < end) { mergeSort(input, start, mid); mergeSort(input, mid + 1, end); } // merge solved pieces to get solution to original problem int i = 0, first = start, last = mid + 1; long[] tmp = new long[end - start + 1]; while (first <= mid && last <= end) { tmp[i++] = input[first] < input[last] ? input[first++] : input[last++]; } while (first <= mid) { tmp[i++] = input[first++]; } while (last <= end) { tmp[i++] = input[last++]; } i = 0; while (start <= end) { input[start++] = tmp[i++]; } } // generate a random list of values to test against public static long[] createRandomIntegerList(int size) { long[] newList = new long[size]; // randomly picks a value between -1000000000 and 1000000000 for (int i = 0; i < size; i++) { newList[i] = (long) ((2000000000 * Math.random()) - 1000000000); } return newList; // return the list to caller } // verifies that an array is sorted in ascending (low to high) order private static boolean verifySorted(long[] list) { for (int i = 0; i < list.length - 1; i++){ if (list[i] > list[i+1]) return false; } return true; } // verifies that an array is sorted in ascending (low to high) order private static void checkSortCorrectness(){ long[] testArray = createRandomIntegerList(10); System.out.print("Unsorted Small Random Test Array: "); System.out.println(Arrays.toString(testArray)); System.out.println("The array is sorted: " + verifySorted(testArray)); System.out.println("Sorting..."); mergeSort(testArray); System.out.print("Small Random Test Array After Sort: "); System.out.println(Arrays.toString(testArray)); System.out.println("The array is sorted: " + verifySorted(testArray)); } }
8,387
0.623346
0.608322
174
47.206898
36.019196
154
false
false
0
0
0
0
0
0
0.643678
false
false
10
113b2afdb7e9013d5fe2a888177db755bc680e31
10,797,547,792,662
9f0282d22c65e19e2cc230fed9ae3851e6c5ff5a
/mvcUsuarios/mvnUsuarios/src/main/java/es/iesptocruz/victor/vista/AppVista.java
c163614e5bf70bb81b3f95c62db1f4f8192f0b50
[]
no_license
Kratossore069/java-repaso
https://github.com/Kratossore069/java-repaso
9438fe88747b50b3167d1389a8533e3ac30a5bcb
07fb53fbad08b6004a2758f366c0b74b8a0fe7dd
refs/heads/master
2023-05-30T21:36:30.818000
2021-06-13T22:42:28
2021-06-13T22:42:28
348,502,039
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package es.iesptocruz.victor.vista; import java.util.InputMismatchException; import java.util.Scanner; import es.iesptocruz.victor.api.Usuario; import es.iesptocruz.victor.controlador.UsuarioControlador; import es.iesptocruz.victor.exceptions.UsuarioException; public class AppVista { /** * Atributos que utilizara la clase main */ static UsuarioControlador usuarioControlador; static Usuario nuevoUsuario; static String nombre = null; static String apellido = null; static int edad = 0; static String identificador = null; static Scanner sn; /** * Constructor por defecto de la clase */ public AppVista() { usuarioControlador = new UsuarioControlador(); sn = new Scanner(System.in); } public static void main(String[] args) throws UsuarioException { System.out.println("Introduzca una opcion para trabajar: "); sn = new Scanner(System.in); boolean salir = false; int opcion; while (!salir) { System.out.println("1. Crear un usuario"); System.out.println("2. Eliminar usuario"); System.out.println("3. Buscar usuario"); System.out.println("4. Mostrar usuario"); try { System.out.println("Escribe una de las opciones"); opcion = sn.nextInt(); switch (opcion) { case 1: introducirDatos(); usuarioControlador.insertar(introducirDatos()); break; case 2: introducirDatos(); usuarioControlador.eliminar(introducirDatos()); break; case 3: introducirDatos(); usuarioControlador.buscar(introducirDatos()); break; case 4: System.out.println("Introduzca el identificador del usuario: "); String id = sn.nextLine(); usuarioControlador.mostrar(id); break; default: System.out.println("Solo números entre 1 y 4"); } } catch (InputMismatchException e) { System.out.println("Debes insertar un número"); sn.next(); } } } /** * Funcion que retorna un usuario creado * * @return usuario creado */ public static Usuario introducirDatos() { System.out.println("Nombre: "); nombre = sn.nextLine();sn.nextInt(); System.out.println("Apellido: "); apellido = sn.nextLine();sn.nextInt(); System.out.println("Edad: "); edad = sn.nextInt(); System.out.println("Identificador: (texto)"); identificador = sn.nextLine();sn.nextInt(); return new Usuario(nombre, apellido, edad, identificador); } }
UTF-8
Java
3,048
java
AppVista.java
Java
[]
null
[]
package es.iesptocruz.victor.vista; import java.util.InputMismatchException; import java.util.Scanner; import es.iesptocruz.victor.api.Usuario; import es.iesptocruz.victor.controlador.UsuarioControlador; import es.iesptocruz.victor.exceptions.UsuarioException; public class AppVista { /** * Atributos que utilizara la clase main */ static UsuarioControlador usuarioControlador; static Usuario nuevoUsuario; static String nombre = null; static String apellido = null; static int edad = 0; static String identificador = null; static Scanner sn; /** * Constructor por defecto de la clase */ public AppVista() { usuarioControlador = new UsuarioControlador(); sn = new Scanner(System.in); } public static void main(String[] args) throws UsuarioException { System.out.println("Introduzca una opcion para trabajar: "); sn = new Scanner(System.in); boolean salir = false; int opcion; while (!salir) { System.out.println("1. Crear un usuario"); System.out.println("2. Eliminar usuario"); System.out.println("3. Buscar usuario"); System.out.println("4. Mostrar usuario"); try { System.out.println("Escribe una de las opciones"); opcion = sn.nextInt(); switch (opcion) { case 1: introducirDatos(); usuarioControlador.insertar(introducirDatos()); break; case 2: introducirDatos(); usuarioControlador.eliminar(introducirDatos()); break; case 3: introducirDatos(); usuarioControlador.buscar(introducirDatos()); break; case 4: System.out.println("Introduzca el identificador del usuario: "); String id = sn.nextLine(); usuarioControlador.mostrar(id); break; default: System.out.println("Solo números entre 1 y 4"); } } catch (InputMismatchException e) { System.out.println("Debes insertar un número"); sn.next(); } } } /** * Funcion que retorna un usuario creado * * @return usuario creado */ public static Usuario introducirDatos() { System.out.println("Nombre: "); nombre = sn.nextLine();sn.nextInt(); System.out.println("Apellido: "); apellido = sn.nextLine();sn.nextInt(); System.out.println("Edad: "); edad = sn.nextInt(); System.out.println("Identificador: (texto)"); identificador = sn.nextLine();sn.nextInt(); return new Usuario(nombre, apellido, edad, identificador); } }
3,048
0.538739
0.535128
96
30.729166
22.071606
88
false
false
0
0
0
0
0
0
0.583333
false
false
10
cdaff44651b1fe89640b2efe33eb0acc327c3a9b
446,676,663,445
296fed4280fbed4669978598e47e3bedb88da558
/src/main/java/core/commands/ProfileInfoCommand.java
72294974090c62b9929ac0c7c3c1e1560b3f9e84
[ "MIT" ]
permissive
ishwi/discordBot
https://github.com/ishwi/discordBot
3cb8d4c52843f5190815633db09d8fd94d87beb5
ac3a4be9c89994d75bccacf2cedce1bb8d405f8e
refs/heads/master
2020-04-20T07:46:11.165000
2020-04-17T17:59:24
2020-04-17T17:59:24
168,719,188
34
7
null
null
null
null
null
null
null
null
null
null
null
null
null
package core.commands; import core.apis.discogs.DiscogsApi; import core.apis.discogs.DiscogsSingleton; import core.apis.spotify.Spotify; import core.apis.spotify.SpotifySingleton; import core.exceptions.InstanceNotFoundException; import core.exceptions.LastFmException; import core.imagerenderer.ProfileMaker; import core.parsers.OnlyUsernameParser; import core.parsers.OptionalEntity; import core.parsers.Parser; import core.parsers.params.ChuuDataParams; import dao.ChuuService; import dao.entities.*; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.MessageBuilder; import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.Collections; import java.util.List; public class ProfileInfoCommand extends ConcurrentCommand<ChuuDataParams> { private final Spotify spotify; private final DiscogsApi discogsApi; public ProfileInfoCommand(ChuuService dao) { super(dao); this.discogsApi = DiscogsSingleton.getInstanceUsingDoubleLocking(); this.spotify = SpotifySingleton.getInstance(); this.respondInPrivate = false; } @Override public Parser<ChuuDataParams> getParser() { return new OnlyUsernameParser(getService(), new OptionalEntity("--image", "display in list format")); } @Override public String getDescription() { return "Brief description of an user profile"; } @Override public List<String> getAliases() { return Collections.singletonList("profile"); } @Override protected void onCommand(MessageReceivedEvent e) throws LastFmException, InstanceNotFoundException { ChuuDataParams params = parser.parse(e); String lastFmName = params.getLastFMData().getName(); boolean isList = !params.hasOptional("--image"); UserInfo userInfo; int albumCount; userInfo = lastFM.getUserInfo(Collections.singletonList(lastFmName)).get(0); albumCount = lastFM.getTotalAlbumCount(lastFmName); long guildId = e.getGuild().getIdLong(); int guildCrownThreshold = getService().getGuildCrownThreshold(guildId); UniqueWrapper<ArtistPlays> crowns = getService().getCrowns(lastFmName, guildId, guildCrownThreshold); UniqueWrapper<ArtistPlays> unique = getService().getUniqueArtist(guildId, lastFmName); int totalUnique = unique.getRows(); int totalCrowns = crowns.getRows(); int totalArtist = getService().getUserArtistCount(lastFmName); String crownRepresentative = !crowns.getUniqueData().isEmpty() ? crowns.getUniqueData().get(0) .getArtistName() : "no crowns"; String uniqueRepresentative = !unique.getUniqueData().isEmpty() ? unique.getUniqueData().get(0) .getArtistName() : "no unique artists"; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); String date = LocalDateTime.ofEpochSecond(userInfo.getUnixtimestamp(), 0, ZoneOffset.UTC) .format(formatter); if (isList) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("Total number of scrobbles: ").append(userInfo.getPlayCount()).append("\n") .append("Total number of albums: ").append(albumCount).append("\n") .append("Total number of artists: ").append(totalArtist).append("\n") .append("Total number of crowns: ").append(totalCrowns).append("\n") .append("Top crown: ").append(CommandUtil.cleanMarkdownCharacter(crownRepresentative)).append("\n") .append("Total number of unique artist: ").append(totalUnique).append("\n") .append("Top unique: ").append(CommandUtil.cleanMarkdownCharacter(uniqueRepresentative)).append("\n"); String name = getUserString(e, unique.getDiscordId(), lastFmName); EmbedBuilder embedBuilder = new EmbedBuilder() .setTitle(name + "'s profile", CommandUtil.getLastFmUser(lastFmName)) .setColor(CommandUtil.randomColor()) .setThumbnail(userInfo.getImage().isEmpty() ? null : userInfo.getImage()) .setDescription(stringBuilder) .setFooter("Account created on " + date); MessageBuilder mes = new MessageBuilder(); mes.setEmbed(embedBuilder.build()).sendTo(e.getChannel()).queue(); } else { ObscuritySummary summary = getService().getObscuritySummary(lastFmName); String crownImage = !crowns.getUniqueData().isEmpty() ? CommandUtil .getArtistImageUrl(getService(), crownRepresentative, lastFM, discogsApi, spotify) : null; String uniqueImage = !unique.getUniqueData().isEmpty() ? CommandUtil .getArtistImageUrl(getService(), uniqueRepresentative, lastFM, discogsApi, spotify) : null; ProfileEntity entity = new ProfileEntity(lastFmName, "", crownRepresentative, uniqueRepresentative, uniqueImage, crownImage, userInfo .getImage(), "", userInfo .getPlayCount(), albumCount, totalArtist, totalCrowns, totalUnique, summary.getTotal(), date); sendImage(ProfileMaker.makeProfile(entity), e); } } @Override public String getName() { return "Profile"; } }
UTF-8
Java
5,558
java
ProfileInfoCommand.java
Java
[]
null
[]
package core.commands; import core.apis.discogs.DiscogsApi; import core.apis.discogs.DiscogsSingleton; import core.apis.spotify.Spotify; import core.apis.spotify.SpotifySingleton; import core.exceptions.InstanceNotFoundException; import core.exceptions.LastFmException; import core.imagerenderer.ProfileMaker; import core.parsers.OnlyUsernameParser; import core.parsers.OptionalEntity; import core.parsers.Parser; import core.parsers.params.ChuuDataParams; import dao.ChuuService; import dao.entities.*; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.MessageBuilder; import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.Collections; import java.util.List; public class ProfileInfoCommand extends ConcurrentCommand<ChuuDataParams> { private final Spotify spotify; private final DiscogsApi discogsApi; public ProfileInfoCommand(ChuuService dao) { super(dao); this.discogsApi = DiscogsSingleton.getInstanceUsingDoubleLocking(); this.spotify = SpotifySingleton.getInstance(); this.respondInPrivate = false; } @Override public Parser<ChuuDataParams> getParser() { return new OnlyUsernameParser(getService(), new OptionalEntity("--image", "display in list format")); } @Override public String getDescription() { return "Brief description of an user profile"; } @Override public List<String> getAliases() { return Collections.singletonList("profile"); } @Override protected void onCommand(MessageReceivedEvent e) throws LastFmException, InstanceNotFoundException { ChuuDataParams params = parser.parse(e); String lastFmName = params.getLastFMData().getName(); boolean isList = !params.hasOptional("--image"); UserInfo userInfo; int albumCount; userInfo = lastFM.getUserInfo(Collections.singletonList(lastFmName)).get(0); albumCount = lastFM.getTotalAlbumCount(lastFmName); long guildId = e.getGuild().getIdLong(); int guildCrownThreshold = getService().getGuildCrownThreshold(guildId); UniqueWrapper<ArtistPlays> crowns = getService().getCrowns(lastFmName, guildId, guildCrownThreshold); UniqueWrapper<ArtistPlays> unique = getService().getUniqueArtist(guildId, lastFmName); int totalUnique = unique.getRows(); int totalCrowns = crowns.getRows(); int totalArtist = getService().getUserArtistCount(lastFmName); String crownRepresentative = !crowns.getUniqueData().isEmpty() ? crowns.getUniqueData().get(0) .getArtistName() : "no crowns"; String uniqueRepresentative = !unique.getUniqueData().isEmpty() ? unique.getUniqueData().get(0) .getArtistName() : "no unique artists"; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); String date = LocalDateTime.ofEpochSecond(userInfo.getUnixtimestamp(), 0, ZoneOffset.UTC) .format(formatter); if (isList) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("Total number of scrobbles: ").append(userInfo.getPlayCount()).append("\n") .append("Total number of albums: ").append(albumCount).append("\n") .append("Total number of artists: ").append(totalArtist).append("\n") .append("Total number of crowns: ").append(totalCrowns).append("\n") .append("Top crown: ").append(CommandUtil.cleanMarkdownCharacter(crownRepresentative)).append("\n") .append("Total number of unique artist: ").append(totalUnique).append("\n") .append("Top unique: ").append(CommandUtil.cleanMarkdownCharacter(uniqueRepresentative)).append("\n"); String name = getUserString(e, unique.getDiscordId(), lastFmName); EmbedBuilder embedBuilder = new EmbedBuilder() .setTitle(name + "'s profile", CommandUtil.getLastFmUser(lastFmName)) .setColor(CommandUtil.randomColor()) .setThumbnail(userInfo.getImage().isEmpty() ? null : userInfo.getImage()) .setDescription(stringBuilder) .setFooter("Account created on " + date); MessageBuilder mes = new MessageBuilder(); mes.setEmbed(embedBuilder.build()).sendTo(e.getChannel()).queue(); } else { ObscuritySummary summary = getService().getObscuritySummary(lastFmName); String crownImage = !crowns.getUniqueData().isEmpty() ? CommandUtil .getArtistImageUrl(getService(), crownRepresentative, lastFM, discogsApi, spotify) : null; String uniqueImage = !unique.getUniqueData().isEmpty() ? CommandUtil .getArtistImageUrl(getService(), uniqueRepresentative, lastFM, discogsApi, spotify) : null; ProfileEntity entity = new ProfileEntity(lastFmName, "", crownRepresentative, uniqueRepresentative, uniqueImage, crownImage, userInfo .getImage(), "", userInfo .getPlayCount(), albumCount, totalArtist, totalCrowns, totalUnique, summary.getTotal(), date); sendImage(ProfileMaker.makeProfile(entity), e); } } @Override public String getName() { return "Profile"; } }
5,558
0.673983
0.672724
124
43.822582
35.636391
145
false
false
0
0
0
0
0
0
0.766129
false
false
10
67e1ff72a57f8e430e36911b955a368308d2fd87
24,421,184,067,117
7ad89c1231a61df3e7a44b557138a793fa2fc035
/mas-workspace/lab01/src/lab03/Agent.java
9586caf4a1e4b7890220daab1e3f2617891e0eb6
[]
no_license
vladpaunescu/college
https://github.com/vladpaunescu/college
d7d8423c8708046ca14ec7fbad4733ab77325b22
e18c9983815603828d63addf5e495754d1bf08bd
refs/heads/master
2021-01-23T13:54:44.256000
2014-06-01T19:24:49
2014-06-01T19:24:49
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package lab03; import java.awt.Color; public abstract class Agent { public Coordinates position; public Orientation orientation; public Board board; public int totalScore; public Agent(Board b, Coordinates coord, Orientation orient){ board = b; position = coord; orientation = orient; } public abstract Action play(); public abstract Color getColor(); }
UTF-8
Java
380
java
Agent.java
Java
[]
null
[]
package lab03; import java.awt.Color; public abstract class Agent { public Coordinates position; public Orientation orientation; public Board board; public int totalScore; public Agent(Board b, Coordinates coord, Orientation orient){ board = b; position = coord; orientation = orient; } public abstract Action play(); public abstract Color getColor(); }
380
0.734211
0.728947
23
15.521739
15.849481
62
false
false
0
0
0
0
0
0
1.347826
false
false
10
353ab346c7a732f9185f978bee231c086974c78a
26,250,840,128,197
49c0623dce7e9e416de31aebc79c49e39620fda2
/world-bank-impl/src/main/java/com/example/webapp/service/RegistrationService.java
ce608729e940d26122902244ff3666c0b6fec0ea
[]
no_license
git-sergBond/WorldBank.Bank
https://github.com/git-sergBond/WorldBank.Bank
ef6a6d4638a1438f74c8d24037e5bc744e140973
ed34f12a4f50760b67628b234f4503c989651773
refs/heads/master
2023-06-02T01:51:27.734000
2021-06-20T22:22:35
2021-06-20T22:22:35
359,305,023
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.webapp.service; import com.example.webapp.mappper.ClientMapper; import com.example.webapp.openapi.model.ClientDto; import com.example.webapp.repository.ClientRepository; import io.micrometer.core.instrument.util.StringUtils; import lombok.AllArgsConstructor; import org.springframework.stereotype.Service; @Service @AllArgsConstructor public class RegistrationService { private final ClientRepository clientRepository; public ClientDto register(ClientDto clientDto) { if (clientDto == null || StringUtils.isBlank(clientDto.getEmail()) || StringUtils.isBlank(clientDto.getPasswd())) { throw new IllegalArgumentException("Wrong arguments"); } if(clientRepository.findByEmail(clientDto.getEmail()).isPresent()) { throw new IllegalArgumentException("This email already registered"); } var client = ClientMapper.INSTANCE.toModel(clientDto); var saved = clientRepository.save(client); return ClientMapper.INSTANCE.toDto(saved); } }
UTF-8
Java
1,078
java
RegistrationService.java
Java
[]
null
[]
package com.example.webapp.service; import com.example.webapp.mappper.ClientMapper; import com.example.webapp.openapi.model.ClientDto; import com.example.webapp.repository.ClientRepository; import io.micrometer.core.instrument.util.StringUtils; import lombok.AllArgsConstructor; import org.springframework.stereotype.Service; @Service @AllArgsConstructor public class RegistrationService { private final ClientRepository clientRepository; public ClientDto register(ClientDto clientDto) { if (clientDto == null || StringUtils.isBlank(clientDto.getEmail()) || StringUtils.isBlank(clientDto.getPasswd())) { throw new IllegalArgumentException("Wrong arguments"); } if(clientRepository.findByEmail(clientDto.getEmail()).isPresent()) { throw new IllegalArgumentException("This email already registered"); } var client = ClientMapper.INSTANCE.toModel(clientDto); var saved = clientRepository.save(client); return ClientMapper.INSTANCE.toDto(saved); } }
1,078
0.723562
0.723562
33
31.666666
26.382578
80
false
false
0
0
0
0
0
0
0.515152
false
false
10
3533e1f6db99b14216b2ad22c6ceb5695b0180f4
18,339,510,382,335
9ee8f67786243c126639a07c83e30de789d20b72
/src/minecraft/net/tntchina/client/module/modules/combat/AutoClicker.java
5623411c857ab1975dcaf1434f3cdf51d2a2d22b
[]
no_license
TNTChinaAAA/TNT-MCPVersion
https://github.com/TNTChinaAAA/TNT-MCPVersion
ded78b45fbfe3584f18b5adb1577d0fa66819989
dd2fb5cab020c74008a05627e1795b8d2d700944
refs/heads/master
2020-04-27T20:46:20.299000
2019-03-16T02:01:29
2019-03-16T02:01:29
174,670,255
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.tntchina.client.module.modules.combat; import org.lwjgl.input.Mouse; import net.tntchina.client.module.Module; import net.tntchina.client.module.ModuleCategory; import net.tntchina.client.util.MathHelper; import net.tntchina.client.value.values.NumberValue; public class AutoClicker extends Module { private NumberValue CPS = new NumberValue(10.0D, "CPS", 20.0D, 1.0D); public AutoClicker(String name, ModuleCategory categorys) { super(name, categorys); } public void onUpdate() { if (!this.getState()) { return; } if (this.timeUtil.hasTimeReached(MathHelper.div(1000, this.CPS.getObject().doubleValue()))) { this.mc.gameSettings.keyBindAttack.pressed = true; this.timeUtil.setLastMS(); } else { if (Mouse.getEventButtonState()) { this.mc.gameSettings.keyBindAttack.pressed = Mouse.isButtonDown(1); } } } }
UTF-8
Java
865
java
AutoClicker.java
Java
[]
null
[]
package net.tntchina.client.module.modules.combat; import org.lwjgl.input.Mouse; import net.tntchina.client.module.Module; import net.tntchina.client.module.ModuleCategory; import net.tntchina.client.util.MathHelper; import net.tntchina.client.value.values.NumberValue; public class AutoClicker extends Module { private NumberValue CPS = new NumberValue(10.0D, "CPS", 20.0D, 1.0D); public AutoClicker(String name, ModuleCategory categorys) { super(name, categorys); } public void onUpdate() { if (!this.getState()) { return; } if (this.timeUtil.hasTimeReached(MathHelper.div(1000, this.CPS.getObject().doubleValue()))) { this.mc.gameSettings.keyBindAttack.pressed = true; this.timeUtil.setLastMS(); } else { if (Mouse.getEventButtonState()) { this.mc.gameSettings.keyBindAttack.pressed = Mouse.isButtonDown(1); } } } }
865
0.737572
0.722543
31
26.903225
25.983065
95
false
false
0
0
0
0
0
0
1.870968
false
false
10
4ad242a25549f47d1aefbf3a83f6d89a0a87f73d
19,628,000,573,231
89dc09a70e2d745e2e79529e190c4ca862199b6c
/Workspace/Snake/src/Coord.java
361b0167ceb467ae42debae04d22ff8c7cf36f6f
[]
no_license
barthinator/SchoolProjects
https://github.com/barthinator/SchoolProjects
cdf9984801837810b85f06a451016d6e06c33b44
d2f040e4e7231ce7012b43fc41fbf8fd51bd5d53
refs/heads/master
2020-08-30T14:32:11.692000
2016-08-31T06:41:02
2016-08-31T06:41:02
67,010,076
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Coord { private int s_x, s_y; Coord next, previous; public Coord(int x, int y){ s_x = x; s_y = y; } public int getX(){ return s_x; } public int getY(){ return s_y; } public void setX(int s_x) { this.s_x = s_x; } public void setY(int s_y) { this.s_y = s_y; } public void setNext(Coord newNode) { next = newNode; } public Coord getNext(){ return next; } public void setPrevious(Coord newNode){ previous = newNode; } public Coord getPrevious(){ return previous; } //Added this just to make debugging easier public String toString() { return "Coord [x=" + s_x + ", y=" + s_y + "]"; } }
UTF-8
Java
646
java
Coord.java
Java
[]
null
[]
public class Coord { private int s_x, s_y; Coord next, previous; public Coord(int x, int y){ s_x = x; s_y = y; } public int getX(){ return s_x; } public int getY(){ return s_y; } public void setX(int s_x) { this.s_x = s_x; } public void setY(int s_y) { this.s_y = s_y; } public void setNext(Coord newNode) { next = newNode; } public Coord getNext(){ return next; } public void setPrevious(Coord newNode){ previous = newNode; } public Coord getPrevious(){ return previous; } //Added this just to make debugging easier public String toString() { return "Coord [x=" + s_x + ", y=" + s_y + "]"; } }
646
0.605263
0.605263
40
15.175
12.953547
48
false
false
0
0
0
0
0
0
1.65
false
false
10
f1ba0a1a636913eb730763216eeb30e19bca294e
7,533,372,678,457
0b1a7607118903d1a5c8ef9308cf620691b134b2
/src/main/java/com/example/marketmaker/common/MarketMakerServer.java
dd319c7396db781df281efb53bbc5941b463c808
[]
no_license
SatendraSingh2016/Learning
https://github.com/SatendraSingh2016/Learning
589361ac5a32c53dbe26369bb3eaf7c300ba225c
b22d26020c02eedf13a6b5fda58c44cf495ab41c
refs/heads/master
2021-01-13T16:45:49.546000
2016-12-24T16:48:39
2016-12-24T16:48:39
76,917,916
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.marketmaker.common; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import com.example.marketmaker.ReferencePriceSource; /** * this class is used to create the server connection and able to handle * the multiple client connect at the moment. * * @author Satendra * */ public class MarketMakerServer{ private ServerSocket serverSocket; private final BlockingQueue<QuoteRequest> quoteReqQ; private volatile ServerStatus serverStatus; private final Thread quotePriceProcessor; public MarketMakerServer(int port, int maxConn, ReferencePriceSource referencePriceSource) { this.quoteReqQ = new LinkedBlockingQueue<>(); serverStatus = ServerStatus.RUNNING; this.quotePriceProcessor = new Thread(new QuotePriceProcessor(quoteReqQ, serverStatus, referencePriceSource)); try { serverSocket = new ServerSocket(port, maxConn); serverSocket.setReuseAddress(true); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); System.exit(-1); //exit if server is not able to bind service } } /** * this method is used to accept the client connection and handling the * each client with different thread */ public void startServer(){ new Thread(){ @Override public void run(){ quotePriceProcessor.start(); while(serverStatus.isRunning()){ try { System.out.println("Waiting for client..."); final Socket client = serverSocket.accept(); if(client!= null && client.isConnected()) new Thread(new QuoteRequestHandler(serverStatus, client, quoteReqQ)).start(); } catch (IOException e) { e.printStackTrace(); } } } }.start(); } public void stopServer(){ serverStatus.setRunning(false); try { quotePriceProcessor.interrupt(); serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } }
UTF-8
Java
2,153
java
MarketMakerServer.java
Java
[ { "context": "le client connect at the moment. \r\n * \r\n * @author Satendra\r\n *\r\n */\r\npublic class MarketMakerServer{\r\n\t\r\n\tpr", "end": 465, "score": 0.9996758103370667, "start": 457, "tag": "NAME", "value": "Satendra" } ]
null
[]
package com.example.marketmaker.common; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import com.example.marketmaker.ReferencePriceSource; /** * this class is used to create the server connection and able to handle * the multiple client connect at the moment. * * @author Satendra * */ public class MarketMakerServer{ private ServerSocket serverSocket; private final BlockingQueue<QuoteRequest> quoteReqQ; private volatile ServerStatus serverStatus; private final Thread quotePriceProcessor; public MarketMakerServer(int port, int maxConn, ReferencePriceSource referencePriceSource) { this.quoteReqQ = new LinkedBlockingQueue<>(); serverStatus = ServerStatus.RUNNING; this.quotePriceProcessor = new Thread(new QuotePriceProcessor(quoteReqQ, serverStatus, referencePriceSource)); try { serverSocket = new ServerSocket(port, maxConn); serverSocket.setReuseAddress(true); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); System.exit(-1); //exit if server is not able to bind service } } /** * this method is used to accept the client connection and handling the * each client with different thread */ public void startServer(){ new Thread(){ @Override public void run(){ quotePriceProcessor.start(); while(serverStatus.isRunning()){ try { System.out.println("Waiting for client..."); final Socket client = serverSocket.accept(); if(client!= null && client.isConnected()) new Thread(new QuoteRequestHandler(serverStatus, client, quoteReqQ)).start(); } catch (IOException e) { e.printStackTrace(); } } } }.start(); } public void stopServer(){ serverStatus.setRunning(false); try { quotePriceProcessor.interrupt(); serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } }
2,153
0.6902
0.689735
78
25.602564
20.729231
83
false
false
0
0
0
0
0
0
2.461539
false
false
10