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
69817fcb57d0226e08213f2e1d2f07bf2e533737
13,589,276,544,366
28e5e71cba1d020e08f93ee7eef47cb769f42b9f
/src/Arrays/StudentManagerment.java
7df696be9ebdbb24213a6cbd176b4341cde2c742
[]
no_license
vunguyenuk/java-pf1-nguyenvanvu
https://github.com/vunguyenuk/java-pf1-nguyenvanvu
3afe4f40546a7607d2639d6a5a066a97b5213a46
23907bcbcf07f25292d245be0e37a23bf2559f19
refs/heads/master
2020-03-29T22:01:54.047000
2018-12-13T11:47:57
2018-12-13T11:47:57
150,399,562
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Arrays; import java.util.Scanner; public class StudentManagerment { public static void main(String[] args) { int[] scoreStudent = new int[3]; for(int i = 0; i < scoreStudent.length; i++){ Scanner sc = new Scanner(System.in); System.out.println("Enter student score of turn " + i + ": "); scoreStudent[i] = sc.nextInt(); } for(int i = 0; i < scoreStudent.length; i++ ){ System.out.println("Enter student score of turn " + i + " is: " + scoreStudent[i]); } } }
UTF-8
Java
570
java
StudentManagerment.java
Java
[]
null
[]
package Arrays; import java.util.Scanner; public class StudentManagerment { public static void main(String[] args) { int[] scoreStudent = new int[3]; for(int i = 0; i < scoreStudent.length; i++){ Scanner sc = new Scanner(System.in); System.out.println("Enter student score of turn " + i + ": "); scoreStudent[i] = sc.nextInt(); } for(int i = 0; i < scoreStudent.length; i++ ){ System.out.println("Enter student score of turn " + i + " is: " + scoreStudent[i]); } } }
570
0.552632
0.547368
22
24.90909
27.296202
95
false
false
0
0
0
0
0
0
0.5
false
false
10
6edf9a46bb6c5431c81f53846261989ce9071655
17,789,754,593,163
775a0cb250df17adff7f51543e5cb95b761fecaf
/Videoplaza/src/tests/StreamHandlerTest.java
09946a749a452937d326e7f38c23e660c3f84e85
[]
no_license
oalsing/Videoplaza
https://github.com/oalsing/Videoplaza
a41fe0844cd2706e765226b6a0f5c6a9980f651d
4e5e57d0e4402f0e696d20543af508ac1e0b66ac
refs/heads/master
2016-08-06T23:23:32.920000
2013-10-27T17:52:37
2013-10-27T17:52:37
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package tests; import static org.junit.Assert.*; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import main.StreamHandler; import org.junit.After; import org.junit.Before; import org.junit.Test; public class StreamHandlerTest { StreamHandler sh; File destFile; BufferedWriter fileWriter; @Before public void setUp() throws IOException{ sh = new StreamHandler("customers.txt"); destFile = new File("optimizedRevenueTest.txt"); fileWriter = new BufferedWriter(new FileWriter(destFile)); } @After public void tearDown(){ destFile.delete(); } @Test public void setFileWriterTest(){ sh.setFileWriter(fileWriter); assertEquals(sh.getFileWriter(), fileWriter); } @Test public void writeResultToFileTest() throws IOException { sh.setFileWriter(fileWriter); sh.writeResultToFile("Hej!"); assertTrue(destFile.canRead()); } }
UTF-8
Java
918
java
StreamHandlerTest.java
Java
[]
null
[]
package tests; import static org.junit.Assert.*; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import main.StreamHandler; import org.junit.After; import org.junit.Before; import org.junit.Test; public class StreamHandlerTest { StreamHandler sh; File destFile; BufferedWriter fileWriter; @Before public void setUp() throws IOException{ sh = new StreamHandler("customers.txt"); destFile = new File("optimizedRevenueTest.txt"); fileWriter = new BufferedWriter(new FileWriter(destFile)); } @After public void tearDown(){ destFile.delete(); } @Test public void setFileWriterTest(){ sh.setFileWriter(fileWriter); assertEquals(sh.getFileWriter(), fileWriter); } @Test public void writeResultToFileTest() throws IOException { sh.setFileWriter(fileWriter); sh.writeResultToFile("Hej!"); assertTrue(destFile.canRead()); } }
918
0.753813
0.753813
44
19.863636
16.759789
60
false
false
0
0
0
0
0
0
1.318182
false
false
10
03b5f7c30f303f88cf210fd021725b6ae5378072
24,429,774,004,494
11ce4e48bc643b48ea29f5f4073a6c91e6a261af
/GAlactic Weight/src/prog432aPaldino.java
d897951cf170b7cca88f878ca84686d4a1980c24
[]
no_license
tesla232/APComputerScience
https://github.com/tesla232/APComputerScience
386e5288696f8163dc0f3d3c4f2e33cb18f12d56
783638f5a274aaa1775992f648fe636186f8ff98
refs/heads/master
2016-08-17T00:09:03.806000
2016-05-18T05:10:05
2016-05-18T05:10:05
45,654,456
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class prog432aPaldino { public static void main(String[] args) { /** * Jordan Paldino * 3/11/16s * AP Computer Science * Prog415hPaldino * Windows 10/ JDK 8 * Description: Removes duplicate numbers * Difficulties: I had difficulties making it loop properly * What I learned: I learned how loop arrays */ Converter convert = new Converter(); while(convert.getDestination() != 9){ convert.input(); System.out.println(convert); System.out.println(); } //Sample Output /* Convert your weight on earth to: 1. Mercury 2. Venus 3. Mars 4. Jupiter 5. Saturn 6. Uranus 7. Neptune 8. Pluto 9. Quit Select a destination by number (or 9 to quit) 2 Enter weight: 132 Your weight on Venus would be 112.2 Convert your weight on earth to: 1. Mercury 2. Venus 3. Mars 4. Jupiter 5. Saturn 6. Uranus 7. Neptune 8. Pluto 9. Quit Select a destination by number (or 9 to quit) 3 Enter weight: 423 Your weight on Mars would be 67.68 Convert your weight on earth to: 1. Mercury 2. Venus 3. Mars 4. Jupiter 5. Saturn 6. Uranus 7. Neptune 8. Pluto 9. Quit Select a destination by number (or 9 to quit) 8 Enter weight: 3200 Your weight on Pluto would be 800.0 Convert your weight on earth to: 1. Mercury 2. Venus 3. Mars 4. Jupiter 5. Saturn 6. Uranus 7. Neptune 8. Pluto 9. Quit Select a destination by number (or 9 to quit) 10 Enter weight: 89 Error--Invalid destination Convert your weight on earth to: 1. Mercury 2. Venus 3. Mars 4. Jupiter 5. Saturn 6. Uranus 7. Neptune 8. Pluto 9. Quit Select a destination by number (or 9 to quit) 9 */ } }
UTF-8
Java
1,746
java
prog432aPaldino.java
Java
[ { "context": "lic static void main(String[] args) {\r\n\t\t/**\r\n\t\t * Jordan Paldino\r\n\t\t * 3/11/16s\r\n\t\t * AP Computer Science\r\n\t\t * Pr", "end": 105, "score": 0.9998855590820312, "start": 91, "tag": "NAME", "value": "Jordan Paldino" } ]
null
[]
public class prog432aPaldino { public static void main(String[] args) { /** * <NAME> * 3/11/16s * AP Computer Science * Prog415hPaldino * Windows 10/ JDK 8 * Description: Removes duplicate numbers * Difficulties: I had difficulties making it loop properly * What I learned: I learned how loop arrays */ Converter convert = new Converter(); while(convert.getDestination() != 9){ convert.input(); System.out.println(convert); System.out.println(); } //Sample Output /* Convert your weight on earth to: 1. Mercury 2. Venus 3. Mars 4. Jupiter 5. Saturn 6. Uranus 7. Neptune 8. Pluto 9. Quit Select a destination by number (or 9 to quit) 2 Enter weight: 132 Your weight on Venus would be 112.2 Convert your weight on earth to: 1. Mercury 2. Venus 3. Mars 4. Jupiter 5. Saturn 6. Uranus 7. Neptune 8. Pluto 9. Quit Select a destination by number (or 9 to quit) 3 Enter weight: 423 Your weight on Mars would be 67.68 Convert your weight on earth to: 1. Mercury 2. Venus 3. Mars 4. Jupiter 5. Saturn 6. Uranus 7. Neptune 8. Pluto 9. Quit Select a destination by number (or 9 to quit) 8 Enter weight: 3200 Your weight on Pluto would be 800.0 Convert your weight on earth to: 1. Mercury 2. Venus 3. Mars 4. Jupiter 5. Saturn 6. Uranus 7. Neptune 8. Pluto 9. Quit Select a destination by number (or 9 to quit) 10 Enter weight: 89 Error--Invalid destination Convert your weight on earth to: 1. Mercury 2. Venus 3. Mars 4. Jupiter 5. Saturn 6. Uranus 7. Neptune 8. Pluto 9. Quit Select a destination by number (or 9 to quit) 9 */ } }
1,738
0.644903
0.590493
94
16.553192
13.936495
61
false
false
0
0
0
0
0
0
0.5
false
false
10
a3445e28f3a0b753215525508644d94808c7a4c6
23,622,320,154,309
23b6d6971a66cf057d1846e3b9523f2ad4e05f61
/MLMN-Statistics/src/vn/com/vhc/vmsc2/statistics/dao/DyBscGprsDAOImpl.java
3625212dc86dc9597ab34563ab12257f1452dca6
[]
no_license
vhctrungnq/mlmn
https://github.com/vhctrungnq/mlmn
943f5a44f24625cfac0edc06a0d1b114f808dfb8
d3ba1f6eebe2e38cdc8053f470f0b99931085629
refs/heads/master
2020-03-22T13:48:30.767000
2018-07-08T05:14:12
2018-07-08T05:14:12
140,132,808
0
1
null
false
2018-07-08T05:29:27
2018-07-08T02:57:06
2018-07-08T05:14:14
2018-07-08T05:29:26
84,136
0
1
0
Java
false
null
package vn.com.vhc.vmsc2.statistics.dao; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport; import vn.com.vhc.vmsc2.statistics.domain.DyBscGprs; public class DyBscGprsDAOImpl extends SqlMapClientDaoSupport implements DyBscGprsDAO { /** * This method was generated by Apache iBATIS ibator. * This method corresponds to the database table DY_BSC_GPRS * * @ibatorgenerated Tue Jul 23 17:54:00 ICT 2013 */ public DyBscGprsDAOImpl() { super(); } /** * This method was generated by Apache iBATIS ibator. * This method corresponds to the database table DY_BSC_GPRS * * @ibatorgenerated Tue Jul 23 17:54:00 ICT 2013 */ public int deleteByPrimaryKey(String bscid, Date day) { DyBscGprs key = new DyBscGprs(); key.setBscid(bscid); key.setDay(day); int rows = getSqlMapClientTemplate().delete("DY_BSC_GPRS.ibatorgenerated_deleteByPrimaryKey", key); return rows; } /** * This method was generated by Apache iBATIS ibator. * This method corresponds to the database table DY_BSC_GPRS * * @ibatorgenerated Tue Jul 23 17:54:00 ICT 2013 */ public void insert(DyBscGprs record) { getSqlMapClientTemplate().insert("DY_BSC_GPRS.ibatorgenerated_insert", record); } /** * This method was generated by Apache iBATIS ibator. * This method corresponds to the database table DY_BSC_GPRS * * @ibatorgenerated Tue Jul 23 17:54:00 ICT 2013 */ public void insertSelective(DyBscGprs record) { getSqlMapClientTemplate().insert("DY_BSC_GPRS.ibatorgenerated_insertSelective", record); } /** * This method was generated by Apache iBATIS ibator. * This method corresponds to the database table DY_BSC_GPRS * * @ibatorgenerated Tue Jul 23 17:54:00 ICT 2013 */ public DyBscGprs selectByPrimaryKey(String bscid, Date day) { DyBscGprs key = new DyBscGprs(); key.setBscid(bscid); key.setDay(day); DyBscGprs record = (DyBscGprs) getSqlMapClientTemplate().queryForObject("DY_BSC_GPRS.ibatorgenerated_selectByPrimaryKey", key); return record; } /** * This method was generated by Apache iBATIS ibator. * This method corresponds to the database table DY_BSC_GPRS * * @ibatorgenerated Tue Jul 23 17:54:00 ICT 2013 */ public int updateByPrimaryKeySelective(DyBscGprs record) { int rows = getSqlMapClientTemplate().update("DY_BSC_GPRS.ibatorgenerated_updateByPrimaryKeySelective", record); return rows; } /** * This method was generated by Apache iBATIS ibator. * This method corresponds to the database table DY_BSC_GPRS * * @ibatorgenerated Tue Jul 23 17:54:00 ICT 2013 */ public int updateByPrimaryKey(DyBscGprs record) { int rows = getSqlMapClientTemplate().update("DY_BSC_GPRS.ibatorgenerated_updateByPrimaryKey", record); return rows; } @SuppressWarnings("unchecked") public List<DyBscGprs> getDyBscGprsFilter(String bscid, String startDate, String endDate, String column, String order) { Map<String, Object> map = new HashMap<String, Object>(); map.put("P_BSCID", bscid); map.put("P_START_DATE", startDate); map.put("P_END_DATE", endDate); map.put("P_COLUMN", column); map.put("P_ORDER", order); map.put("P_DATA", null); return getSqlMapClientTemplate().queryForList("DY_BSC_GPRS.getDyBscGprsFilter", map); } @SuppressWarnings("unchecked") public List<DyBscGprs> getDyDayBscGprs(String endDate) { Map<String, Object> map = new HashMap<String, Object>(); map.put("P_END_DATE", endDate); map.put("P_DATA", null); return getSqlMapClientTemplate().queryForList("DY_BSC_GPRS.getDyDayBscGprs", map); } @SuppressWarnings("unchecked") public List<DyBscGprs> getPcuCongRateByBscid(String bscid, String endDate) { Map<String, Object> map = new HashMap<String, Object>(); map.put("P_BSCID", bscid); map.put("P_END_DATE", endDate); map.put("P_DATA", null); return getSqlMapClientTemplate().queryForList("DY_BSC_GPRS.getPcuCongRateByBscid", map); } @SuppressWarnings("unchecked") public List<DyBscGprs> getGslutilRateByBscid(String bscid, String endDate) { Map<String, Object> map = new HashMap<String, Object>(); map.put("P_BSCID", bscid); map.put("P_END_DATE", endDate); map.put("P_DATA", null); return getSqlMapClientTemplate().queryForList("DY_BSC_GPRS.getGslutilRateByBscid", map); } }
UTF-8
Java
4,855
java
DyBscGprsDAOImpl.java
Java
[]
null
[]
package vn.com.vhc.vmsc2.statistics.dao; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport; import vn.com.vhc.vmsc2.statistics.domain.DyBscGprs; public class DyBscGprsDAOImpl extends SqlMapClientDaoSupport implements DyBscGprsDAO { /** * This method was generated by Apache iBATIS ibator. * This method corresponds to the database table DY_BSC_GPRS * * @ibatorgenerated Tue Jul 23 17:54:00 ICT 2013 */ public DyBscGprsDAOImpl() { super(); } /** * This method was generated by Apache iBATIS ibator. * This method corresponds to the database table DY_BSC_GPRS * * @ibatorgenerated Tue Jul 23 17:54:00 ICT 2013 */ public int deleteByPrimaryKey(String bscid, Date day) { DyBscGprs key = new DyBscGprs(); key.setBscid(bscid); key.setDay(day); int rows = getSqlMapClientTemplate().delete("DY_BSC_GPRS.ibatorgenerated_deleteByPrimaryKey", key); return rows; } /** * This method was generated by Apache iBATIS ibator. * This method corresponds to the database table DY_BSC_GPRS * * @ibatorgenerated Tue Jul 23 17:54:00 ICT 2013 */ public void insert(DyBscGprs record) { getSqlMapClientTemplate().insert("DY_BSC_GPRS.ibatorgenerated_insert", record); } /** * This method was generated by Apache iBATIS ibator. * This method corresponds to the database table DY_BSC_GPRS * * @ibatorgenerated Tue Jul 23 17:54:00 ICT 2013 */ public void insertSelective(DyBscGprs record) { getSqlMapClientTemplate().insert("DY_BSC_GPRS.ibatorgenerated_insertSelective", record); } /** * This method was generated by Apache iBATIS ibator. * This method corresponds to the database table DY_BSC_GPRS * * @ibatorgenerated Tue Jul 23 17:54:00 ICT 2013 */ public DyBscGprs selectByPrimaryKey(String bscid, Date day) { DyBscGprs key = new DyBscGprs(); key.setBscid(bscid); key.setDay(day); DyBscGprs record = (DyBscGprs) getSqlMapClientTemplate().queryForObject("DY_BSC_GPRS.ibatorgenerated_selectByPrimaryKey", key); return record; } /** * This method was generated by Apache iBATIS ibator. * This method corresponds to the database table DY_BSC_GPRS * * @ibatorgenerated Tue Jul 23 17:54:00 ICT 2013 */ public int updateByPrimaryKeySelective(DyBscGprs record) { int rows = getSqlMapClientTemplate().update("DY_BSC_GPRS.ibatorgenerated_updateByPrimaryKeySelective", record); return rows; } /** * This method was generated by Apache iBATIS ibator. * This method corresponds to the database table DY_BSC_GPRS * * @ibatorgenerated Tue Jul 23 17:54:00 ICT 2013 */ public int updateByPrimaryKey(DyBscGprs record) { int rows = getSqlMapClientTemplate().update("DY_BSC_GPRS.ibatorgenerated_updateByPrimaryKey", record); return rows; } @SuppressWarnings("unchecked") public List<DyBscGprs> getDyBscGprsFilter(String bscid, String startDate, String endDate, String column, String order) { Map<String, Object> map = new HashMap<String, Object>(); map.put("P_BSCID", bscid); map.put("P_START_DATE", startDate); map.put("P_END_DATE", endDate); map.put("P_COLUMN", column); map.put("P_ORDER", order); map.put("P_DATA", null); return getSqlMapClientTemplate().queryForList("DY_BSC_GPRS.getDyBscGprsFilter", map); } @SuppressWarnings("unchecked") public List<DyBscGprs> getDyDayBscGprs(String endDate) { Map<String, Object> map = new HashMap<String, Object>(); map.put("P_END_DATE", endDate); map.put("P_DATA", null); return getSqlMapClientTemplate().queryForList("DY_BSC_GPRS.getDyDayBscGprs", map); } @SuppressWarnings("unchecked") public List<DyBscGprs> getPcuCongRateByBscid(String bscid, String endDate) { Map<String, Object> map = new HashMap<String, Object>(); map.put("P_BSCID", bscid); map.put("P_END_DATE", endDate); map.put("P_DATA", null); return getSqlMapClientTemplate().queryForList("DY_BSC_GPRS.getPcuCongRateByBscid", map); } @SuppressWarnings("unchecked") public List<DyBscGprs> getGslutilRateByBscid(String bscid, String endDate) { Map<String, Object> map = new HashMap<String, Object>(); map.put("P_BSCID", bscid); map.put("P_END_DATE", endDate); map.put("P_DATA", null); return getSqlMapClientTemplate().queryForList("DY_BSC_GPRS.getGslutilRateByBscid", map); } }
4,855
0.656231
0.638517
135
33.977779
31.159201
135
false
false
0
0
0
0
0
0
0.918519
false
false
10
dee9b22dd2cac86c228413e77605e7b69a29c75f
24,618,752,563,067
9dc3ad1fa74346c1604491ff0677173835eb43f9
/app/src/main/java/demo/kolorob/kolorobdemoversion/model/SubCategoryItemNew.java
0fe3df4b3cffb8809b48697f07aa0400eb55dd13
[]
no_license
Kolorob/Kolorob
https://github.com/Kolorob/Kolorob
cc8ea81e7443ea19756fe08d5395c03f9739b332
77d6f4970fbe62175dc8c91ee0ef1420d1073179
refs/heads/master
2020-04-04T07:13:54.673000
2018-07-07T10:18:39
2018-07-07T10:18:39
49,218,529
3
5
null
null
null
null
null
null
null
null
null
null
null
null
null
package demo.kolorob.kolorobdemoversion.model; import org.json.JSONException; import org.json.JSONObject; import java.io.Serializable; /** * Created by Israt Jahan on 26-Dec-15. */ public class SubCategoryItemNew extends BaseModel <SubCategoryItemNew> implements Serializable { private int id; private int catId; private String CatLabel; private int subCatId; private String subCatLabel; private String subCatLabelBn; private int refId; private String refLabel; private String refLabelBn; public SubCategoryItemNew(int id, int catId, String catLabel, int subCatId, String subCatLabel, String subCatLabelBn, int refId, String refLabel, String refLabelBn) { this.id = id; this.catId = catId; CatLabel = catLabel; this.subCatId = subCatId; this.subCatLabel = subCatLabel; this.subCatLabelBn = subCatLabelBn; this.refId = refId; this.refLabel = refLabel; this.refLabelBn = refLabelBn; } public SubCategoryItemNew() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getCatId() { return catId; } public void setCatId(int catId) { this.catId = catId; } public String getCatLabel() { return CatLabel; } public void setCatLabel(String catLabel) { CatLabel = catLabel; } public int getSubCatId() { return subCatId; } public void setSubCatId(int subCatId) { this.subCatId = subCatId; } public String getSubCatLabel() { return subCatLabel; } public void setSubCatLabel(String subCatLabel) { this.subCatLabel = subCatLabel; } public String getSubCatLabelBn() { return subCatLabelBn; } public void setSubCatLabelBn(String subCatLabelBn) { this.subCatLabelBn = subCatLabelBn; } public int getRefId() { return refId; } public void setRefId(int refId) { this.refId = refId; } public String getRefLabel() { return refLabel; } public void setRefLabel(String refLabel) { this.refLabel = refLabel; } public String getRefLabelBn() { return refLabelBn; } public void setRefLabelBn(String refLabelBn) { this.refLabelBn = refLabelBn; } public SubCategoryItemNew parse(JSONObject jo) throws JSONException { int _id = jo.getInt("ref_id"); int cat_id = jo.getInt("cat_id"); String catname = jo.getString("cat_label"); int subcatid = jo.getInt("sub_cat_id"); String subcatLabele = jo.getString("sub_cat_label"); String subcatLabelB = jo.getString("sub_cat_label_bn"); int refId = jo.getInt("ref_id"); String refname = jo.getString("ref_label"); String refnamebn = jo.getString("ref_label_bn"); return new SubCategoryItemNew(_id, cat_id,catname,subcatid, subcatLabele,subcatLabelB,refId,refname,refnamebn); } }
UTF-8
Java
3,055
java
SubCategoryItemNew.java
Java
[ { "context": ";\n\nimport java.io.Serializable;\n\n/**\n * Created by Israt Jahan on 26-Dec-15.\n */\n\npublic class SubCategoryItemNe", "end": 167, "score": 0.9998466968536377, "start": 156, "tag": "NAME", "value": "Israt Jahan" } ]
null
[]
package demo.kolorob.kolorobdemoversion.model; import org.json.JSONException; import org.json.JSONObject; import java.io.Serializable; /** * Created by <NAME> on 26-Dec-15. */ public class SubCategoryItemNew extends BaseModel <SubCategoryItemNew> implements Serializable { private int id; private int catId; private String CatLabel; private int subCatId; private String subCatLabel; private String subCatLabelBn; private int refId; private String refLabel; private String refLabelBn; public SubCategoryItemNew(int id, int catId, String catLabel, int subCatId, String subCatLabel, String subCatLabelBn, int refId, String refLabel, String refLabelBn) { this.id = id; this.catId = catId; CatLabel = catLabel; this.subCatId = subCatId; this.subCatLabel = subCatLabel; this.subCatLabelBn = subCatLabelBn; this.refId = refId; this.refLabel = refLabel; this.refLabelBn = refLabelBn; } public SubCategoryItemNew() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getCatId() { return catId; } public void setCatId(int catId) { this.catId = catId; } public String getCatLabel() { return CatLabel; } public void setCatLabel(String catLabel) { CatLabel = catLabel; } public int getSubCatId() { return subCatId; } public void setSubCatId(int subCatId) { this.subCatId = subCatId; } public String getSubCatLabel() { return subCatLabel; } public void setSubCatLabel(String subCatLabel) { this.subCatLabel = subCatLabel; } public String getSubCatLabelBn() { return subCatLabelBn; } public void setSubCatLabelBn(String subCatLabelBn) { this.subCatLabelBn = subCatLabelBn; } public int getRefId() { return refId; } public void setRefId(int refId) { this.refId = refId; } public String getRefLabel() { return refLabel; } public void setRefLabel(String refLabel) { this.refLabel = refLabel; } public String getRefLabelBn() { return refLabelBn; } public void setRefLabelBn(String refLabelBn) { this.refLabelBn = refLabelBn; } public SubCategoryItemNew parse(JSONObject jo) throws JSONException { int _id = jo.getInt("ref_id"); int cat_id = jo.getInt("cat_id"); String catname = jo.getString("cat_label"); int subcatid = jo.getInt("sub_cat_id"); String subcatLabele = jo.getString("sub_cat_label"); String subcatLabelB = jo.getString("sub_cat_label_bn"); int refId = jo.getInt("ref_id"); String refname = jo.getString("ref_label"); String refnamebn = jo.getString("ref_label_bn"); return new SubCategoryItemNew(_id, cat_id,catname,subcatid, subcatLabele,subcatLabelB,refId,refname,refnamebn); } }
3,050
0.636661
0.635352
126
23.246031
24.895237
170
false
false
0
0
0
0
0
0
0.52381
false
false
10
fca40375569de0cf643d96ba94d565ade352776d
33,560,874,507,511
fc044b821e3133e0ea83a26933b986c7a34e24c7
/src/main/java/annotation/Scope.java
53474ec3dea47c9f79589ec31e8dddc8d2a39a94
[]
no_license
liweiwei0/spring
https://github.com/liweiwei0/spring
2de200843b2e7b36095f91aeb1caafadaef78fff
3cd7f432fa4776fa5c54277fee9170d1a86dfdd2
refs/heads/master
2021-09-24T11:34:46.015000
2018-10-09T06:31:47
2018-10-09T06:31:47
119,356,253
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package annotation; public interface Scope<T> { public void test(); }
UTF-8
Java
73
java
Scope.java
Java
[]
null
[]
package annotation; public interface Scope<T> { public void test(); }
73
0.712329
0.712329
6
11.166667
11.126795
27
false
false
0
0
0
0
0
0
0.5
false
false
10
623c598be72379482f9f34afd628e9f7c793c421
30,657,476,607,794
4b41ef7236087641b4edc23ffaa9198e392b1d90
/src/presentation/objects/Orientation.java
d399f9db9b9f7d2f026d2c04e58c25385de3b3aa
[]
no_license
Breina/MC-ticker
https://github.com/Breina/MC-ticker
e4b5147771f6500fd482ef396d88461c5b9123db
06f16490ce5b113dd9a58a580da2a404d395d8b1
refs/heads/master
2021-05-31T20:57:47.265000
2015-09-29T22:47:38
2015-09-29T22:47:38
21,747,731
4
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package presentation.objects; public enum Orientation { TOP, RIGHT, FRONT }
UTF-8
Java
81
java
Orientation.java
Java
[]
null
[]
package presentation.objects; public enum Orientation { TOP, RIGHT, FRONT }
81
0.740741
0.740741
8
9.125
10.670491
29
false
false
0
0
0
0
0
0
0.75
false
false
10
63930644ab303cd9979ee4c22d74e221248d69c7
7,559,142,490,051
183bec6dac50da4b8bf0150d0c5cd9775cdd2554
/src/test/java/MultiThreading_2/SquareSumTest.java
d35cc87b4682fca6152e8a6f1ef52eee12d8461c
[]
no_license
EgorSalenko/JavaEnterpriseEdition
https://github.com/EgorSalenko/JavaEnterpriseEdition
b331cbdafc798be392293485773ab902ee58babe
b419e4db232d2ef32d33e7d637b8e6dc099b1606
refs/heads/master
2017-06-18T03:55:44.421000
2016-06-27T10:14:45
2016-06-27T10:14:45
53,699,657
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package MultiThreading_2; import static org.junit.Assert.*; /** * Created by Wrong on 12.05.2016. * */ public class SquareSumTest { @org.junit.Test public void getSquareSum() throws Exception { SquareSum squareSum = new SquareSum(); int[] items = {1, 2, 3, 4, 5, 6, 7, 8, 9}; long expected = 285; long actual = squareSum.getSquareSum(items, 10); assertEquals(expected, actual); } }
UTF-8
Java
443
java
SquareSumTest.java
Java
[ { "context": "port static org.junit.Assert.*;\n\n/**\n * Created by Wrong on 12.05.2016.\n *\n */\npublic class SquareSumTest ", "end": 85, "score": 0.6279197335243225, "start": 80, "tag": "USERNAME", "value": "Wrong" } ]
null
[]
package MultiThreading_2; import static org.junit.Assert.*; /** * Created by Wrong on 12.05.2016. * */ public class SquareSumTest { @org.junit.Test public void getSquareSum() throws Exception { SquareSum squareSum = new SquareSum(); int[] items = {1, 2, 3, 4, 5, 6, 7, 8, 9}; long expected = 285; long actual = squareSum.getSquareSum(items, 10); assertEquals(expected, actual); } }
443
0.611738
0.559819
23
18.304348
19.576904
56
false
false
0
0
0
0
0
0
0.73913
false
false
10
9cf8d362504c7d131fb7655d9453a8f7b9247fbb
11,991,548,744,847
dbe8b018e57694aa8392a05a1893d8b2de5f7a85
/src/main/java/br/edu/ufcg/computacao/si1/controller/ErrorPagesController.java
c0fdb92adc58b540013ac59053fb94b26d94531d
[ "MIT" ]
permissive
matheusfreitaas/SI-Project
https://github.com/matheusfreitaas/SI-Project
aee9b525f5efaa67d5b0ac08d5a4e619c53967d6
1b136414eccfe10c8c24c44d7160ece851b32813
refs/heads/master
2021-01-17T15:50:23.096000
2017-03-28T20:18:22
2017-03-28T20:18:22
84,113,386
0
0
null
false
2017-03-24T21:44:57
2017-03-06T19:40:39
2017-03-08T13:35:55
2017-03-24T21:35:10
2,293
0
0
0
Java
null
null
package br.edu.ufcg.computacao.si1.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import br.edu.ufcg.computacao.si1.util.Constantes; /** * Responsável pelo redirecionamento para páginas de erro * @author Rafael * */ @Controller public class ErrorPagesController { /** * Redireciona para a página de erro 404 * @return Página 404 */ @RequestMapping(Constantes.ROTA_404) public String notFound() { return Constantes.ERRO_404; } /** * Redireciona para a página de erro 403 * @return Página 403 */ @RequestMapping(Constantes.ROTA_403) public String forbidden() { return Constantes.ERRO_403; } /** * Redireciona para a página de erro 500 * @return Página 500 */ @RequestMapping(Constantes.ROTA_500) public String internalServerError() { return Constantes.ERRO_500; } }
UTF-8
Java
946
java
ErrorPagesController.java
Java
[ { "context": "o redirecionamento para páginas de erro\n * @author Rafael\n *\n */\n@Controller\npublic class ErrorPagesControl", "end": 292, "score": 0.9998412132263184, "start": 286, "tag": "NAME", "value": "Rafael" } ]
null
[]
package br.edu.ufcg.computacao.si1.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import br.edu.ufcg.computacao.si1.util.Constantes; /** * Responsável pelo redirecionamento para páginas de erro * @author Rafael * */ @Controller public class ErrorPagesController { /** * Redireciona para a página de erro 404 * @return Página 404 */ @RequestMapping(Constantes.ROTA_404) public String notFound() { return Constantes.ERRO_404; } /** * Redireciona para a página de erro 403 * @return Página 403 */ @RequestMapping(Constantes.ROTA_403) public String forbidden() { return Constantes.ERRO_403; } /** * Redireciona para a página de erro 500 * @return Página 500 */ @RequestMapping(Constantes.ROTA_500) public String internalServerError() { return Constantes.ERRO_500; } }
946
0.696162
0.65565
41
21.878048
19.058569
62
false
false
0
0
0
0
0
0
0.414634
false
false
10
bf7f035b1d77976ab66e599359ce8d212be55b20
1,606,317,824,125
94d4e47e332b14f4a02eca769dd0daf3c090df47
/app/src/main/java/com/example/reto1appsmoviles/CreatePotHoleDialogFragment.java
19cf26ab6240c7cac55e24f63b12f6159706a6ef
[]
no_license
juan-carvajal/Reto1Appsmoviles
https://github.com/juan-carvajal/Reto1Appsmoviles
a4a6acb2b7c1f2a60f3ebe8f3fcb2725c24acb7b
1d6433c06f37f645360036baa9af33958ad1fcd5
refs/heads/master
2022-12-30T21:57:19.900000
2020-10-25T17:35:20
2020-10-25T17:35:20
307,155,182
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.reto1appsmoviles; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import androidx.fragment.app.DialogFragment; import com.example.reto1appsmoviles.comm.HTTPSWebUtilDomi; import com.example.reto1appsmoviles.models.PotHole; import com.google.gson.Gson; import java.util.UUID; public class CreatePotHoleDialogFragment extends DialogFragment { private PotHole potHole; Activity activity; private HTTPSWebUtilDomi https; private Gson gson; public CreatePotHoleDialogFragment(PotHole potHole, Activity activity){ this.potHole =potHole; this.activity = activity; https = new HTTPSWebUtilDomi(); gson = new Gson(); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Use the Builder class for convenient dialog construction AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setMessage("Coordenada:\n"+this.potHole.latitude+", "+this.potHole.longitude+"\n\nDirección:\n"+this.potHole.streetAddress).setTitle("Agregar un hueco") .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { new Thread( ()->{ String url = "https://appmoviles-47f25.firebaseio.com/potholes/"+ UUID.randomUUID().toString() +".json"; https.PUTrequest(url,gson.toJson(potHole)); } ).start(); } }); // Create the AlertDialog object and return it return builder.create(); } }
UTF-8
Java
1,851
java
CreatePotHoleDialogFragment.java
Java
[]
null
[]
package com.example.reto1appsmoviles; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import androidx.fragment.app.DialogFragment; import com.example.reto1appsmoviles.comm.HTTPSWebUtilDomi; import com.example.reto1appsmoviles.models.PotHole; import com.google.gson.Gson; import java.util.UUID; public class CreatePotHoleDialogFragment extends DialogFragment { private PotHole potHole; Activity activity; private HTTPSWebUtilDomi https; private Gson gson; public CreatePotHoleDialogFragment(PotHole potHole, Activity activity){ this.potHole =potHole; this.activity = activity; https = new HTTPSWebUtilDomi(); gson = new Gson(); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Use the Builder class for convenient dialog construction AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setMessage("Coordenada:\n"+this.potHole.latitude+", "+this.potHole.longitude+"\n\nDirección:\n"+this.potHole.streetAddress).setTitle("Agregar un hueco") .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { new Thread( ()->{ String url = "https://appmoviles-47f25.firebaseio.com/potholes/"+ UUID.randomUUID().toString() +".json"; https.PUTrequest(url,gson.toJson(potHole)); } ).start(); } }); // Create the AlertDialog object and return it return builder.create(); } }
1,851
0.637297
0.633514
50
36
33.892181
169
false
false
0
0
0
0
0
0
0.6
false
false
10
e970096ee94407da3d595018722a00897ae26cdd
32,538,672,290,663
701b7ce70f7972124df907b0096a00020954ecce
/src/com/jetbrains/Main.java
fe97bc49f75d6449ec443f20ba2a4c6e265b88d6
[]
no_license
Dunbun/InnovaticxTest
https://github.com/Dunbun/InnovaticxTest
2befaf11c220e5b3e3143c2c61a23d2f8cbf5a97
82129bc16ee3a3127e5a1d789ca52e1c74c64386
refs/heads/master
2020-09-09T18:45:49.810000
2019-11-13T19:53:56
2019-11-13T19:53:56
221,532,260
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jetbrains; public class Main { public static void main(String[] args) { CycleList testCycleList = new CycleList(); testCycleList.addElement(0,2); testCycleList.addElement(1,3); testCycleList.addElement(2,4); testCycleList.addElement(3,5); testCycleList.addElement(-4,20); testCycleList.printCycleList(); System.out.println("____________"); testCycleList.deleteElement(-5); testCycleList.printCycleList(); System.out.println("______reverse______"); testCycleList.reverse(testCycleList); testCycleList.printCycleList(); } }
UTF-8
Java
649
java
Main.java
Java
[]
null
[]
package com.jetbrains; public class Main { public static void main(String[] args) { CycleList testCycleList = new CycleList(); testCycleList.addElement(0,2); testCycleList.addElement(1,3); testCycleList.addElement(2,4); testCycleList.addElement(3,5); testCycleList.addElement(-4,20); testCycleList.printCycleList(); System.out.println("____________"); testCycleList.deleteElement(-5); testCycleList.printCycleList(); System.out.println("______reverse______"); testCycleList.reverse(testCycleList); testCycleList.printCycleList(); } }
649
0.622496
0.604006
21
29.904762
17.511642
50
false
false
0
0
0
0
0
0
0.904762
false
false
10
e9d4bcba4b9c69a7b95ce4f9b2ce7a9b3c4f5492
28,217,935,181,409
9515cd5c6b9927992fc3b9fc2542dc272fbf8485
/src/main/java/br/com/marceloazvedo/model/Movie.java
f9ea7f1114557a053a9958d2c57835d8fa9fee26
[]
no_license
marceloazvedo/using-java-8
https://github.com/marceloazvedo/using-java-8
3c3fd9b823b3bdee0353001efb110f4e33ff264a
5bb4907455ad290fe4db7cafff3152fd347a74c0
refs/heads/master
2022-05-28T10:43:56.486000
2020-05-05T20:00:56
2020-05-05T20:00:56
254,930,172
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.marceloazvedo.model; public class Movie { private Long movieId; private String title; private String genres; public Movie(Long movieId, String title, String genres) { this.movieId = movieId; this.title = title; this.genres = genres; } public Movie() { } public Long getMovieId() { return movieId; } public void setMovieId(Long movieId) { this.movieId = movieId; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getGenres() { return genres; } public void setGenres(String genres) { this.genres = genres; } public String[] getGenresAsArray() { return genres.split("\\|"); } @Override public String toString() { return "Movie{" + "movieId=" + movieId + ", title='" + title + '\'' + ", genres='" + genres + '\'' + '}'; } }
UTF-8
Java
1,063
java
Movie.java
Java
[]
null
[]
package br.com.marceloazvedo.model; public class Movie { private Long movieId; private String title; private String genres; public Movie(Long movieId, String title, String genres) { this.movieId = movieId; this.title = title; this.genres = genres; } public Movie() { } public Long getMovieId() { return movieId; } public void setMovieId(Long movieId) { this.movieId = movieId; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getGenres() { return genres; } public void setGenres(String genres) { this.genres = genres; } public String[] getGenresAsArray() { return genres.split("\\|"); } @Override public String toString() { return "Movie{" + "movieId=" + movieId + ", title='" + title + '\'' + ", genres='" + genres + '\'' + '}'; } }
1,063
0.527752
0.527752
54
18.685184
16.037947
61
false
false
0
0
0
0
0
0
0.37037
false
false
10
d923d9d545805f688bd9b20eb76c6fcd74d9631c
16,269,336,168,748
98d354b02719933a104aa96a689fa0963a2218d1
/app/src/main/java/ca/ualberta/CMPUT3012019T02/alexandria/activity/ChatRoomActivity.java
a3444c32ad92e5394479835b0b94f71ed18f9050
[ "Apache-2.0" ]
permissive
cmput301w19t02/Alexandria
https://github.com/cmput301w19t02/Alexandria
fbbc1cf26ad3a18d7a5baecc582418d49bf83546
1e66077a3661ef6f8c72d414117b5512c59f9d8a
refs/heads/master
2023-01-28T11:39:01.320000
2019-04-01T21:57:49
2019-04-01T21:57:49
169,452,637
2
6
Apache-2.0
false
2023-01-09T11:35:24
2019-02-06T18:12:07
2021-04-22T02:55:39
2023-01-09T11:35:22
18,970
2
4
15
Java
false
false
package ca.ualberta.CMPUT3012019T02.alexandria.activity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.annotation.NonNull; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.Date; import java.util.List; import ca.ualberta.CMPUT3012019T02.alexandria.R; import ca.ualberta.CMPUT3012019T02.alexandria.controller.ChatController; import ca.ualberta.CMPUT3012019T02.alexandria.controller.NotificationController; import ca.ualberta.CMPUT3012019T02.alexandria.controller.UserController; import ca.ualberta.CMPUT3012019T02.alexandria.adapter.MessageRecyclerViewAdapter; import ca.ualberta.CMPUT3012019T02.alexandria.model.Location; import ca.ualberta.CMPUT3012019T02.alexandria.model.message.LocationMessage; import ca.ualberta.CMPUT3012019T02.alexandria.model.message.Message; import ca.ualberta.CMPUT3012019T02.alexandria.model.message.TextMessage; /** * This activity is solely for user to user messaging. */ public class ChatRoomActivity extends AppCompatActivity { static final int MEET_LOCATION_REQUEST = 1; private ChatController chatController = ChatController.getInstance(); private UserController userController = UserController.getInstance(); private NotificationController notificationController = NotificationController.getInstance(); private DatabaseReference messagesRef; private ValueEventListener messagesListener; private List<Message> messageList = new ArrayList<>(); private String chatId; private String receiverId; private String senderId; private String receiverName; private MessageRecyclerViewAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_chat_room); Intent intent = getIntent(); chatId = intent.getStringExtra("chatId"); receiverId = intent.getStringExtra("receiverId"); receiverName = intent.getStringExtra("receiverName"); senderId = UserController.getInstance().getMyId(); TextView receiverUserName = findViewById(R.id.receiver_username); receiverUserName.setText(receiverName); // toolbar Toolbar toolbar = findViewById(R.id.ChatRoom_toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayShowTitleEnabled(false); // remove default title toolbar.setNavigationIcon(R.drawable.ic_arrow_back); toolbar.setNavigationOnClickListener((View v) -> finish()); //edit text focus EditText editText = findViewById(R.id.edit_message); editText.requestFocus(); // messages messagesRef = FirebaseDatabase.getInstance().getReference().child("chatMessages").child(chatId); messagesListener = new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.exists()) { messageList.clear(); for (DataSnapshot childSnapshot : dataSnapshot.getChildren()){ TextMessage message = childSnapshot.getValue(TextMessage.class); messageList.add(message); } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { throw new RuntimeException("Could not load data from database " + databaseError); } }; messagesRef.addValueEventListener(messagesListener); ImageView sendButton = findViewById(R.id.image_send); sendButton.setOnClickListener((View v) -> { EditText input = findViewById(R.id.edit_message); String inputText = input.getText().toString(); if (!inputText.matches("")) { onSendMessageClick(inputText, senderId); input.setText(""); } }); } @Override public void onResume(){ super.onResume(); RecyclerView mRecyclerView = findViewById(R.id.message_recycler); adapter = new MessageRecyclerViewAdapter(this, messageList); mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); mRecyclerView.setAdapter(adapter); //runs once to get scroll to bottom final Handler onceHandler = new Handler(); onceHandler.postDelayed(() -> { adapter.updateMessageList(messageList); adapter.notifyDataSetChanged(); if (messageList.size() != 0) { mRecyclerView.scrollToPosition(messageList.size()-1); } }, 500); final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { adapter.updateMessageList(messageList); adapter.notifyDataSetChanged(); handler.postDelayed(this, 500); } }, 500); } @Override protected void onStop(){ super.onStop(); messagesRef.removeEventListener(messagesListener); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.message_settings, menu); return super.onCreateOptionsMenu(menu); } /** * Block the user you are messaging. * * @param item * @return */ @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.view_profile: Intent startViewProfile = new Intent(this, ViewUserProfileActivity.class); startViewProfile.putExtra("USER_ID",receiverId); startActivity(startViewProfile); case R.id.messaging_setting: // open menu break; default: throw new RuntimeException("Unknown option"); } return super.onOptionsItemSelected(item); } /** * On add location message to database. * */ public void onAddLocationClick() { Intent intent = new Intent(this, LocationActivity.class); startActivityForResult(intent, MEET_LOCATION_REQUEST); } /** * On send message click. * * @param inputText the input text * @param senderId the sender id */ public void onSendMessageClick(String inputText, String senderId) { Date date = new Date(); TextMessage message = new TextMessage(inputText, "unread", date.getTime(), senderId); chatController.addTextMessage(chatId, message); chatController.setUserChatRoomReadStatus(chatId, receiverId, false); } @Override protected void onActivityResult(int requestCode,int resultCode, Intent returnIntent) { if (requestCode == MEET_LOCATION_REQUEST){ if (resultCode == Activity.RESULT_OK){ double lat = returnIntent.getExtras().getDouble("lat"); double lng = returnIntent.getExtras().getDouble("lng"); String imageId = returnIntent.getStringExtra("imageId"); Location location = new Location(lat, lng); Date date = new Date(); LocationMessage message = new LocationMessage(location, "unread", date.getTime(), senderId, imageId); //setting content for RecyclerAdapter use String content = imageId + "," + lat + "," + lng; message.setContent(content); chatController.addLocationMessage(chatId, message); chatController.setUserChatRoomReadStatus(chatId, receiverId, false); messageList.add(message); adapter.updateMessageList(messageList); adapter.notifyDataSetChanged(); userController.getMyProfile().handleAsync((result, error) -> { if (error == null) { notificationController.sendNotification(receiverId, "New Meet up Location from " + result.getUsername(), "Go to your messages to see the new place to meet"); } else { //handle error } return null; }); } if (resultCode == Activity.RESULT_CANCELED){ Toast.makeText(this , "No Location Added", Toast.LENGTH_LONG).show(); } } } }
UTF-8
Java
9,425
java
ChatRoomActivity.java
Java
[]
null
[]
package ca.ualberta.CMPUT3012019T02.alexandria.activity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.annotation.NonNull; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.Date; import java.util.List; import ca.ualberta.CMPUT3012019T02.alexandria.R; import ca.ualberta.CMPUT3012019T02.alexandria.controller.ChatController; import ca.ualberta.CMPUT3012019T02.alexandria.controller.NotificationController; import ca.ualberta.CMPUT3012019T02.alexandria.controller.UserController; import ca.ualberta.CMPUT3012019T02.alexandria.adapter.MessageRecyclerViewAdapter; import ca.ualberta.CMPUT3012019T02.alexandria.model.Location; import ca.ualberta.CMPUT3012019T02.alexandria.model.message.LocationMessage; import ca.ualberta.CMPUT3012019T02.alexandria.model.message.Message; import ca.ualberta.CMPUT3012019T02.alexandria.model.message.TextMessage; /** * This activity is solely for user to user messaging. */ public class ChatRoomActivity extends AppCompatActivity { static final int MEET_LOCATION_REQUEST = 1; private ChatController chatController = ChatController.getInstance(); private UserController userController = UserController.getInstance(); private NotificationController notificationController = NotificationController.getInstance(); private DatabaseReference messagesRef; private ValueEventListener messagesListener; private List<Message> messageList = new ArrayList<>(); private String chatId; private String receiverId; private String senderId; private String receiverName; private MessageRecyclerViewAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_chat_room); Intent intent = getIntent(); chatId = intent.getStringExtra("chatId"); receiverId = intent.getStringExtra("receiverId"); receiverName = intent.getStringExtra("receiverName"); senderId = UserController.getInstance().getMyId(); TextView receiverUserName = findViewById(R.id.receiver_username); receiverUserName.setText(receiverName); // toolbar Toolbar toolbar = findViewById(R.id.ChatRoom_toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayShowTitleEnabled(false); // remove default title toolbar.setNavigationIcon(R.drawable.ic_arrow_back); toolbar.setNavigationOnClickListener((View v) -> finish()); //edit text focus EditText editText = findViewById(R.id.edit_message); editText.requestFocus(); // messages messagesRef = FirebaseDatabase.getInstance().getReference().child("chatMessages").child(chatId); messagesListener = new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.exists()) { messageList.clear(); for (DataSnapshot childSnapshot : dataSnapshot.getChildren()){ TextMessage message = childSnapshot.getValue(TextMessage.class); messageList.add(message); } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { throw new RuntimeException("Could not load data from database " + databaseError); } }; messagesRef.addValueEventListener(messagesListener); ImageView sendButton = findViewById(R.id.image_send); sendButton.setOnClickListener((View v) -> { EditText input = findViewById(R.id.edit_message); String inputText = input.getText().toString(); if (!inputText.matches("")) { onSendMessageClick(inputText, senderId); input.setText(""); } }); } @Override public void onResume(){ super.onResume(); RecyclerView mRecyclerView = findViewById(R.id.message_recycler); adapter = new MessageRecyclerViewAdapter(this, messageList); mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); mRecyclerView.setAdapter(adapter); //runs once to get scroll to bottom final Handler onceHandler = new Handler(); onceHandler.postDelayed(() -> { adapter.updateMessageList(messageList); adapter.notifyDataSetChanged(); if (messageList.size() != 0) { mRecyclerView.scrollToPosition(messageList.size()-1); } }, 500); final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { adapter.updateMessageList(messageList); adapter.notifyDataSetChanged(); handler.postDelayed(this, 500); } }, 500); } @Override protected void onStop(){ super.onStop(); messagesRef.removeEventListener(messagesListener); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.message_settings, menu); return super.onCreateOptionsMenu(menu); } /** * Block the user you are messaging. * * @param item * @return */ @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.view_profile: Intent startViewProfile = new Intent(this, ViewUserProfileActivity.class); startViewProfile.putExtra("USER_ID",receiverId); startActivity(startViewProfile); case R.id.messaging_setting: // open menu break; default: throw new RuntimeException("Unknown option"); } return super.onOptionsItemSelected(item); } /** * On add location message to database. * */ public void onAddLocationClick() { Intent intent = new Intent(this, LocationActivity.class); startActivityForResult(intent, MEET_LOCATION_REQUEST); } /** * On send message click. * * @param inputText the input text * @param senderId the sender id */ public void onSendMessageClick(String inputText, String senderId) { Date date = new Date(); TextMessage message = new TextMessage(inputText, "unread", date.getTime(), senderId); chatController.addTextMessage(chatId, message); chatController.setUserChatRoomReadStatus(chatId, receiverId, false); } @Override protected void onActivityResult(int requestCode,int resultCode, Intent returnIntent) { if (requestCode == MEET_LOCATION_REQUEST){ if (resultCode == Activity.RESULT_OK){ double lat = returnIntent.getExtras().getDouble("lat"); double lng = returnIntent.getExtras().getDouble("lng"); String imageId = returnIntent.getStringExtra("imageId"); Location location = new Location(lat, lng); Date date = new Date(); LocationMessage message = new LocationMessage(location, "unread", date.getTime(), senderId, imageId); //setting content for RecyclerAdapter use String content = imageId + "," + lat + "," + lng; message.setContent(content); chatController.addLocationMessage(chatId, message); chatController.setUserChatRoomReadStatus(chatId, receiverId, false); messageList.add(message); adapter.updateMessageList(messageList); adapter.notifyDataSetChanged(); userController.getMyProfile().handleAsync((result, error) -> { if (error == null) { notificationController.sendNotification(receiverId, "New Meet up Location from " + result.getUsername(), "Go to your messages to see the new place to meet"); } else { //handle error } return null; }); } if (resultCode == Activity.RESULT_CANCELED){ Toast.makeText(this , "No Location Added", Toast.LENGTH_LONG).show(); } } } }
9,425
0.649655
0.638302
250
36.700001
26.598684
104
false
false
0
0
0
0
0
0
0.644
false
false
10
ec1488247c7188936dd82bb032e4bac06310672c
24,962,349,976,027
250581cbc64651a0a5cc3eda255766b77e9d3b3a
/2016.05.02/Fechas.java
f1622843e763a86f10957261e23a6bb1a67b2ca7
[]
no_license
JoanRq/CURSJAVA8
https://github.com/JoanRq/CURSJAVA8
789364ca32df4bd836a806d86fc2d7450d49a2e9
aa5fb6fd2d6a3554eee64601b72c9eb69f427640
refs/heads/master
2021-01-18T22:33:09.170000
2016-06-14T06:07:40
2016-06-14T06:07:40
55,094,688
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.time.*; import java.time.format.*; public class Fechas { public static void main(String[] args) { System.out.println(LocalDate.now()); System.out.println(LocalTime.now()); System.out.println(LocalDateTime.now()); LocalDate ld = LocalDate.of(2015, 2, 28); System.out.println(ld); LocalTime lt = LocalTime.of(2, 15, 59, 200000000); System.out.println(lt); LocalDateTime ldt = LocalDateTime.of(2016, 1, 20, 2, 15, 59); LocalDateTime ldt2 = LocalDateTime.of(ld, lt); ld = ld.plusDays(2); System.out.println(ld); ld = ld.plusWeeks(1); ld = ld.plusMonths(3); ld = ld.plusYears(4); System.out.println(ld); ld = ld.minusYears(3).minusWeeks(3).minusMonths(4); System.out.println(ld); lt = lt.plusHours(2).minusMinutes(4).plusSeconds(3); System.out.println(lt); ldt = ldt.plusMinutes(4); System.out.println(ldt); System.out.println(ldt.isAfter(ldt2)); System.out.println(ld.toEpochDay()); // FECHA UNIX Period p = Period.ofMonths(1); Period anualmente = Period.ofYears(1); ld = ld.plus(p); // lt = lt.plus(p); NO se puede sumar un mes a una hora System.out.println(ld.getYear()); System.out.println(ld.getMonth()); System.out.println(ld.getDayOfWeek()); System.out.println(ld.getDayOfYear()); System.out.println(ld.getDayOfMonth()); System.out.println(ld.format(DateTimeFormatter.BASIC_ISO_DATE)); System.out.println(ldt.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)); // Imprimimos fecha y hora segun formato local (España) DateTimeFormatter dtf = DateTimeFormatter .ofLocalizedDateTime(FormatStyle.SHORT); DateTimeFormatter dd = DateTimeFormatter .ofLocalizedDate(FormatStyle.SHORT); System.out.println(ldt.format(dtf)); System.out.println(ld.format(dd)); // Formateador personalizado DateTimeFormatter dtfp = DateTimeFormatter.ofPattern( "dd, yyyy, hh:mm"); System.out.println(ldt.format(dtfp)); // AL REVES String hora = "12:59"; DateTimeFormatter dtfp2 = DateTimeFormatter.ofPattern( "hh:mm"); LocalTime ldt3 = LocalTime.parse(hora); System.out.println(ldt3); } }
UTF-8
Java
2,290
java
Fechas.java
Java
[]
null
[]
import java.time.*; import java.time.format.*; public class Fechas { public static void main(String[] args) { System.out.println(LocalDate.now()); System.out.println(LocalTime.now()); System.out.println(LocalDateTime.now()); LocalDate ld = LocalDate.of(2015, 2, 28); System.out.println(ld); LocalTime lt = LocalTime.of(2, 15, 59, 200000000); System.out.println(lt); LocalDateTime ldt = LocalDateTime.of(2016, 1, 20, 2, 15, 59); LocalDateTime ldt2 = LocalDateTime.of(ld, lt); ld = ld.plusDays(2); System.out.println(ld); ld = ld.plusWeeks(1); ld = ld.plusMonths(3); ld = ld.plusYears(4); System.out.println(ld); ld = ld.minusYears(3).minusWeeks(3).minusMonths(4); System.out.println(ld); lt = lt.plusHours(2).minusMinutes(4).plusSeconds(3); System.out.println(lt); ldt = ldt.plusMinutes(4); System.out.println(ldt); System.out.println(ldt.isAfter(ldt2)); System.out.println(ld.toEpochDay()); // FECHA UNIX Period p = Period.ofMonths(1); Period anualmente = Period.ofYears(1); ld = ld.plus(p); // lt = lt.plus(p); NO se puede sumar un mes a una hora System.out.println(ld.getYear()); System.out.println(ld.getMonth()); System.out.println(ld.getDayOfWeek()); System.out.println(ld.getDayOfYear()); System.out.println(ld.getDayOfMonth()); System.out.println(ld.format(DateTimeFormatter.BASIC_ISO_DATE)); System.out.println(ldt.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)); // Imprimimos fecha y hora segun formato local (España) DateTimeFormatter dtf = DateTimeFormatter .ofLocalizedDateTime(FormatStyle.SHORT); DateTimeFormatter dd = DateTimeFormatter .ofLocalizedDate(FormatStyle.SHORT); System.out.println(ldt.format(dtf)); System.out.println(ld.format(dd)); // Formateador personalizado DateTimeFormatter dtfp = DateTimeFormatter.ofPattern( "dd, yyyy, hh:mm"); System.out.println(ldt.format(dtfp)); // AL REVES String hora = "12:59"; DateTimeFormatter dtfp2 = DateTimeFormatter.ofPattern( "hh:mm"); LocalTime ldt3 = LocalTime.parse(hora); System.out.println(ldt3); } }
2,290
0.645697
0.621669
75
29.533333
19.604988
74
false
false
0
0
0
0
0
0
0.786667
false
false
10
cbda5ebb75e39095edc32d5338080ac535b8b597
16,088,947,546,767
ef44d044ff58ebc6c0052962b04b0130025a102b
/com.freevisiontech.fvmobile_source_from_JADX/sources/org/opencv/xfeatures2d/PCTSignatures.java
d37cfaf84e89f22a29351e31eb68b440d05b15bf
[]
no_license
thedemoncat/FVShare
https://github.com/thedemoncat/FVShare
e610bac0f2dc394534ac0ccec86941ff523e2dfd
bd1e52defaec868f0d1f9b4f2039625c8ff3ee4a
refs/heads/master
2023-08-06T04:11:16.403000
2021-09-25T10:11:13
2021-09-25T10:11:13
410,232,121
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.opencv.xfeatures2d; import java.util.List; import org.opencv.core.Algorithm; import org.opencv.core.Mat; import org.opencv.core.MatOfFloat; import org.opencv.core.MatOfInt; import org.opencv.core.MatOfPoint2f; import org.opencv.utils.Converters; public class PCTSignatures extends Algorithm { public static final int GAUSSIAN = 1; public static final int HEURISTIC = 2; public static final int L0_25 = 0; public static final int L0_5 = 1; /* renamed from: L1 */ public static final int f1135L1 = 2; /* renamed from: L2 */ public static final int f1136L2 = 3; public static final int L2SQUARED = 4; /* renamed from: L5 */ public static final int f1137L5 = 5; public static final int L_INFINITY = 6; public static final int MINUS = 0; public static final int NORMAL = 2; public static final int REGULAR = 1; public static final int UNIFORM = 0; private static native void computeSignature_0(long j, long j2, long j3); private static native void computeSignatures_0(long j, long j2, long j3); private static native long create_0(int i, int i2, int i3); private static native long create_1(); private static native long create_2(long j, int i); private static native long create_3(long j, long j2); private static native void delete(long j); private static native void drawSignature_0(long j, long j2, long j3, float f, int i); private static native void drawSignature_1(long j, long j2, long j3); private static native void generateInitPoints_0(long j, int i, int i2); private static native int getClusterMinSize_0(long j); private static native int getDistanceFunction_0(long j); private static native float getDropThreshold_0(long j); private static native int getGrayscaleBits_0(long j); private static native int getInitSeedCount_0(long j); private static native long getInitSeedIndexes_0(long j); private static native int getIterationCount_0(long j); private static native float getJoiningDistance_0(long j); private static native int getMaxClustersCount_0(long j); private static native int getSampleCount_0(long j); private static native long getSamplingPoints_0(long j); private static native float getWeightA_0(long j); private static native float getWeightB_0(long j); private static native float getWeightConstrast_0(long j); private static native float getWeightEntropy_0(long j); private static native float getWeightL_0(long j); private static native float getWeightX_0(long j); private static native float getWeightY_0(long j); private static native int getWindowRadius_0(long j); private static native void setClusterMinSize_0(long j, int i); private static native void setDistanceFunction_0(long j, int i); private static native void setDropThreshold_0(long j, float f); private static native void setGrayscaleBits_0(long j, int i); private static native void setInitSeedIndexes_0(long j, long j2); private static native void setIterationCount_0(long j, int i); private static native void setJoiningDistance_0(long j, float f); private static native void setMaxClustersCount_0(long j, int i); private static native void setSamplingPoints_0(long j, long j2); private static native void setTranslation_0(long j, int i, float f); private static native void setTranslations_0(long j, long j2); private static native void setWeightA_0(long j, float f); private static native void setWeightB_0(long j, float f); private static native void setWeightContrast_0(long j, float f); private static native void setWeightEntropy_0(long j, float f); private static native void setWeightL_0(long j, float f); private static native void setWeightX_0(long j, float f); private static native void setWeightY_0(long j, float f); private static native void setWeight_0(long j, int i, float f); private static native void setWeights_0(long j, long j2); private static native void setWindowRadius_0(long j, int i); protected PCTSignatures(long addr) { super(addr); } public static PCTSignatures create(int initSampleCount, int initSeedCount, int pointDistribution) { return new PCTSignatures(create_0(initSampleCount, initSeedCount, pointDistribution)); } public static PCTSignatures create() { return new PCTSignatures(create_1()); } public static PCTSignatures create(MatOfPoint2f initSamplingPoints, int initSeedCount) { return new PCTSignatures(create_2(initSamplingPoints.nativeObj, initSeedCount)); } public static PCTSignatures create(MatOfPoint2f initSamplingPoints, MatOfInt initClusterSeedIndexes) { return new PCTSignatures(create_3(initSamplingPoints.nativeObj, initClusterSeedIndexes.nativeObj)); } public float getDropThreshold() { return getDropThreshold_0(this.nativeObj); } public float getJoiningDistance() { return getJoiningDistance_0(this.nativeObj); } public float getWeightA() { return getWeightA_0(this.nativeObj); } public float getWeightB() { return getWeightB_0(this.nativeObj); } public float getWeightConstrast() { return getWeightConstrast_0(this.nativeObj); } public float getWeightEntropy() { return getWeightEntropy_0(this.nativeObj); } public float getWeightL() { return getWeightL_0(this.nativeObj); } public float getWeightX() { return getWeightX_0(this.nativeObj); } public float getWeightY() { return getWeightY_0(this.nativeObj); } public int getClusterMinSize() { return getClusterMinSize_0(this.nativeObj); } public int getDistanceFunction() { return getDistanceFunction_0(this.nativeObj); } public int getGrayscaleBits() { return getGrayscaleBits_0(this.nativeObj); } public int getInitSeedCount() { return getInitSeedCount_0(this.nativeObj); } public int getIterationCount() { return getIterationCount_0(this.nativeObj); } public int getMaxClustersCount() { return getMaxClustersCount_0(this.nativeObj); } public int getSampleCount() { return getSampleCount_0(this.nativeObj); } public int getWindowRadius() { return getWindowRadius_0(this.nativeObj); } public MatOfPoint2f getSamplingPoints() { return MatOfPoint2f.fromNativeAddr(getSamplingPoints_0(this.nativeObj)); } public MatOfInt getInitSeedIndexes() { return MatOfInt.fromNativeAddr(getInitSeedIndexes_0(this.nativeObj)); } public void computeSignature(Mat image, Mat signature) { computeSignature_0(this.nativeObj, image.nativeObj, signature.nativeObj); } public void computeSignatures(List<Mat> images, List<Mat> signatures) { computeSignatures_0(this.nativeObj, Converters.vector_Mat_to_Mat(images).nativeObj, Converters.vector_Mat_to_Mat(signatures).nativeObj); } public static void drawSignature(Mat source, Mat signature, Mat result, float radiusToShorterSideRatio, int borderThickness) { drawSignature_0(source.nativeObj, signature.nativeObj, result.nativeObj, radiusToShorterSideRatio, borderThickness); } public static void drawSignature(Mat source, Mat signature, Mat result) { drawSignature_1(source.nativeObj, signature.nativeObj, result.nativeObj); } public static void generateInitPoints(MatOfPoint2f initPoints, int count, int pointDistribution) { generateInitPoints_0(initPoints.nativeObj, count, pointDistribution); } public void setClusterMinSize(int clusterMinSize) { setClusterMinSize_0(this.nativeObj, clusterMinSize); } public void setDistanceFunction(int distanceFunction) { setDistanceFunction_0(this.nativeObj, distanceFunction); } public void setDropThreshold(float dropThreshold) { setDropThreshold_0(this.nativeObj, dropThreshold); } public void setGrayscaleBits(int grayscaleBits) { setGrayscaleBits_0(this.nativeObj, grayscaleBits); } public void setInitSeedIndexes(MatOfInt initSeedIndexes) { setInitSeedIndexes_0(this.nativeObj, initSeedIndexes.nativeObj); } public void setIterationCount(int iterationCount) { setIterationCount_0(this.nativeObj, iterationCount); } public void setJoiningDistance(float joiningDistance) { setJoiningDistance_0(this.nativeObj, joiningDistance); } public void setMaxClustersCount(int maxClustersCount) { setMaxClustersCount_0(this.nativeObj, maxClustersCount); } public void setSamplingPoints(MatOfPoint2f samplingPoints) { setSamplingPoints_0(this.nativeObj, samplingPoints.nativeObj); } public void setTranslation(int idx, float value) { setTranslation_0(this.nativeObj, idx, value); } public void setTranslations(MatOfFloat translations) { setTranslations_0(this.nativeObj, translations.nativeObj); } public void setWeight(int idx, float value) { setWeight_0(this.nativeObj, idx, value); } public void setWeightA(float weight) { setWeightA_0(this.nativeObj, weight); } public void setWeightB(float weight) { setWeightB_0(this.nativeObj, weight); } public void setWeightContrast(float weight) { setWeightContrast_0(this.nativeObj, weight); } public void setWeightEntropy(float weight) { setWeightEntropy_0(this.nativeObj, weight); } public void setWeightL(float weight) { setWeightL_0(this.nativeObj, weight); } public void setWeightX(float weight) { setWeightX_0(this.nativeObj, weight); } public void setWeightY(float weight) { setWeightY_0(this.nativeObj, weight); } public void setWeights(MatOfFloat weights) { setWeights_0(this.nativeObj, weights.nativeObj); } public void setWindowRadius(int radius) { setWindowRadius_0(this.nativeObj, radius); } /* access modifiers changed from: protected */ public void finalize() throws Throwable { delete(this.nativeObj); } }
UTF-8
Java
10,330
java
PCTSignatures.java
Java
[]
null
[]
package org.opencv.xfeatures2d; import java.util.List; import org.opencv.core.Algorithm; import org.opencv.core.Mat; import org.opencv.core.MatOfFloat; import org.opencv.core.MatOfInt; import org.opencv.core.MatOfPoint2f; import org.opencv.utils.Converters; public class PCTSignatures extends Algorithm { public static final int GAUSSIAN = 1; public static final int HEURISTIC = 2; public static final int L0_25 = 0; public static final int L0_5 = 1; /* renamed from: L1 */ public static final int f1135L1 = 2; /* renamed from: L2 */ public static final int f1136L2 = 3; public static final int L2SQUARED = 4; /* renamed from: L5 */ public static final int f1137L5 = 5; public static final int L_INFINITY = 6; public static final int MINUS = 0; public static final int NORMAL = 2; public static final int REGULAR = 1; public static final int UNIFORM = 0; private static native void computeSignature_0(long j, long j2, long j3); private static native void computeSignatures_0(long j, long j2, long j3); private static native long create_0(int i, int i2, int i3); private static native long create_1(); private static native long create_2(long j, int i); private static native long create_3(long j, long j2); private static native void delete(long j); private static native void drawSignature_0(long j, long j2, long j3, float f, int i); private static native void drawSignature_1(long j, long j2, long j3); private static native void generateInitPoints_0(long j, int i, int i2); private static native int getClusterMinSize_0(long j); private static native int getDistanceFunction_0(long j); private static native float getDropThreshold_0(long j); private static native int getGrayscaleBits_0(long j); private static native int getInitSeedCount_0(long j); private static native long getInitSeedIndexes_0(long j); private static native int getIterationCount_0(long j); private static native float getJoiningDistance_0(long j); private static native int getMaxClustersCount_0(long j); private static native int getSampleCount_0(long j); private static native long getSamplingPoints_0(long j); private static native float getWeightA_0(long j); private static native float getWeightB_0(long j); private static native float getWeightConstrast_0(long j); private static native float getWeightEntropy_0(long j); private static native float getWeightL_0(long j); private static native float getWeightX_0(long j); private static native float getWeightY_0(long j); private static native int getWindowRadius_0(long j); private static native void setClusterMinSize_0(long j, int i); private static native void setDistanceFunction_0(long j, int i); private static native void setDropThreshold_0(long j, float f); private static native void setGrayscaleBits_0(long j, int i); private static native void setInitSeedIndexes_0(long j, long j2); private static native void setIterationCount_0(long j, int i); private static native void setJoiningDistance_0(long j, float f); private static native void setMaxClustersCount_0(long j, int i); private static native void setSamplingPoints_0(long j, long j2); private static native void setTranslation_0(long j, int i, float f); private static native void setTranslations_0(long j, long j2); private static native void setWeightA_0(long j, float f); private static native void setWeightB_0(long j, float f); private static native void setWeightContrast_0(long j, float f); private static native void setWeightEntropy_0(long j, float f); private static native void setWeightL_0(long j, float f); private static native void setWeightX_0(long j, float f); private static native void setWeightY_0(long j, float f); private static native void setWeight_0(long j, int i, float f); private static native void setWeights_0(long j, long j2); private static native void setWindowRadius_0(long j, int i); protected PCTSignatures(long addr) { super(addr); } public static PCTSignatures create(int initSampleCount, int initSeedCount, int pointDistribution) { return new PCTSignatures(create_0(initSampleCount, initSeedCount, pointDistribution)); } public static PCTSignatures create() { return new PCTSignatures(create_1()); } public static PCTSignatures create(MatOfPoint2f initSamplingPoints, int initSeedCount) { return new PCTSignatures(create_2(initSamplingPoints.nativeObj, initSeedCount)); } public static PCTSignatures create(MatOfPoint2f initSamplingPoints, MatOfInt initClusterSeedIndexes) { return new PCTSignatures(create_3(initSamplingPoints.nativeObj, initClusterSeedIndexes.nativeObj)); } public float getDropThreshold() { return getDropThreshold_0(this.nativeObj); } public float getJoiningDistance() { return getJoiningDistance_0(this.nativeObj); } public float getWeightA() { return getWeightA_0(this.nativeObj); } public float getWeightB() { return getWeightB_0(this.nativeObj); } public float getWeightConstrast() { return getWeightConstrast_0(this.nativeObj); } public float getWeightEntropy() { return getWeightEntropy_0(this.nativeObj); } public float getWeightL() { return getWeightL_0(this.nativeObj); } public float getWeightX() { return getWeightX_0(this.nativeObj); } public float getWeightY() { return getWeightY_0(this.nativeObj); } public int getClusterMinSize() { return getClusterMinSize_0(this.nativeObj); } public int getDistanceFunction() { return getDistanceFunction_0(this.nativeObj); } public int getGrayscaleBits() { return getGrayscaleBits_0(this.nativeObj); } public int getInitSeedCount() { return getInitSeedCount_0(this.nativeObj); } public int getIterationCount() { return getIterationCount_0(this.nativeObj); } public int getMaxClustersCount() { return getMaxClustersCount_0(this.nativeObj); } public int getSampleCount() { return getSampleCount_0(this.nativeObj); } public int getWindowRadius() { return getWindowRadius_0(this.nativeObj); } public MatOfPoint2f getSamplingPoints() { return MatOfPoint2f.fromNativeAddr(getSamplingPoints_0(this.nativeObj)); } public MatOfInt getInitSeedIndexes() { return MatOfInt.fromNativeAddr(getInitSeedIndexes_0(this.nativeObj)); } public void computeSignature(Mat image, Mat signature) { computeSignature_0(this.nativeObj, image.nativeObj, signature.nativeObj); } public void computeSignatures(List<Mat> images, List<Mat> signatures) { computeSignatures_0(this.nativeObj, Converters.vector_Mat_to_Mat(images).nativeObj, Converters.vector_Mat_to_Mat(signatures).nativeObj); } public static void drawSignature(Mat source, Mat signature, Mat result, float radiusToShorterSideRatio, int borderThickness) { drawSignature_0(source.nativeObj, signature.nativeObj, result.nativeObj, radiusToShorterSideRatio, borderThickness); } public static void drawSignature(Mat source, Mat signature, Mat result) { drawSignature_1(source.nativeObj, signature.nativeObj, result.nativeObj); } public static void generateInitPoints(MatOfPoint2f initPoints, int count, int pointDistribution) { generateInitPoints_0(initPoints.nativeObj, count, pointDistribution); } public void setClusterMinSize(int clusterMinSize) { setClusterMinSize_0(this.nativeObj, clusterMinSize); } public void setDistanceFunction(int distanceFunction) { setDistanceFunction_0(this.nativeObj, distanceFunction); } public void setDropThreshold(float dropThreshold) { setDropThreshold_0(this.nativeObj, dropThreshold); } public void setGrayscaleBits(int grayscaleBits) { setGrayscaleBits_0(this.nativeObj, grayscaleBits); } public void setInitSeedIndexes(MatOfInt initSeedIndexes) { setInitSeedIndexes_0(this.nativeObj, initSeedIndexes.nativeObj); } public void setIterationCount(int iterationCount) { setIterationCount_0(this.nativeObj, iterationCount); } public void setJoiningDistance(float joiningDistance) { setJoiningDistance_0(this.nativeObj, joiningDistance); } public void setMaxClustersCount(int maxClustersCount) { setMaxClustersCount_0(this.nativeObj, maxClustersCount); } public void setSamplingPoints(MatOfPoint2f samplingPoints) { setSamplingPoints_0(this.nativeObj, samplingPoints.nativeObj); } public void setTranslation(int idx, float value) { setTranslation_0(this.nativeObj, idx, value); } public void setTranslations(MatOfFloat translations) { setTranslations_0(this.nativeObj, translations.nativeObj); } public void setWeight(int idx, float value) { setWeight_0(this.nativeObj, idx, value); } public void setWeightA(float weight) { setWeightA_0(this.nativeObj, weight); } public void setWeightB(float weight) { setWeightB_0(this.nativeObj, weight); } public void setWeightContrast(float weight) { setWeightContrast_0(this.nativeObj, weight); } public void setWeightEntropy(float weight) { setWeightEntropy_0(this.nativeObj, weight); } public void setWeightL(float weight) { setWeightL_0(this.nativeObj, weight); } public void setWeightX(float weight) { setWeightX_0(this.nativeObj, weight); } public void setWeightY(float weight) { setWeightY_0(this.nativeObj, weight); } public void setWeights(MatOfFloat weights) { setWeights_0(this.nativeObj, weights.nativeObj); } public void setWindowRadius(int radius) { setWindowRadius_0(this.nativeObj, radius); } /* access modifiers changed from: protected */ public void finalize() throws Throwable { delete(this.nativeObj); } }
10,330
0.708035
0.692643
336
29.744047
29.99365
144
false
false
0
0
0
0
0
0
0.642857
false
false
10
4c86603a48f6484b44e11e72d83ef4e4620c5e0e
5,660,766,949,186
f6731a653b613f79f7cfffbd998d4508ea063f66
/src/praktek02/tanahaksi.java
9b6a54fd7072b5fb7381fc059f2892eee9b182a4
[]
no_license
bestiyusna/praktek02
https://github.com/bestiyusna/praktek02
e7c2eb69883f2a6681a268f875f19dbf463295e8
cedc679cd82655340a46d18bcf854960087db2fc
refs/heads/master
2020-03-07T03:36:50.236000
2018-03-29T06:06:28
2018-03-29T06:06:28
127,241,465
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 praktek02; /** * * @author BESTI */ public class tanahaksi { public static void main(String[] args) { tanah A1 = new tanah(); A1.lebar = 90; A1.panjang = 80; A1.cetakInfo(); System.out.println("luas nya adalah : "+A1.hitungLuas()); A1.cetakLuasTanah(); tanah A2 = new tanah(); A2.cetakInfo(); tanah A3 = new tanah(50,90); A.cetakInfo(); } }
UTF-8
Java
662
java
tanahaksi.java
Java
[ { "context": " editor.\n */\npackage praktek02;\n\n/**\n *\n * @author BESTI\n */\npublic class tanahaksi {\n public static vo", "end": 228, "score": 0.9001144766807556, "start": 223, "tag": "NAME", "value": "BESTI" } ]
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 praktek02; /** * * @author BESTI */ public class tanahaksi { public static void main(String[] args) { tanah A1 = new tanah(); A1.lebar = 90; A1.panjang = 80; A1.cetakInfo(); System.out.println("luas nya adalah : "+A1.hitungLuas()); A1.cetakLuasTanah(); tanah A2 = new tanah(); A2.cetakInfo(); tanah A3 = new tanah(50,90); A.cetakInfo(); } }
662
0.561934
0.533233
29
21.827587
19.854763
79
false
false
0
0
0
0
0
0
0.517241
false
false
10
2d567e1537e4af1d83780c08d8fe19f07567efc6
34,162,169,888,195
06bb7c19925df53ee4d23a4c531da4350bbfdf5a
/Serveur/src/serveur/communication/Connexion.java
22055deb022c4d8e5865346aa6937074cc60dc7e
[]
no_license
kaldoran/Projet_GL_Code
https://github.com/kaldoran/Projet_GL_Code
d729fa2ee5db95b5435790b08996cb5a2491643a
d82d432131fdc2f63db3b5cc9ea26f7eb5593ea4
refs/heads/master
2016-09-06T04:47:13.349000
2015-01-08T21:24:20
2015-01-08T21:24:20
27,834,218
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 serveur.communication; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; import java.net.Socket; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author kaldoran */ class Connexion { public static String login = null, pass = null, message1 = null, message2 = null, message3 = null; private Scanner sc = null; private Boolean connect = false; public Connexion(Socket socket, PrintWriter out, BufferedReader in) { try { String s; sc = new Scanner(System.in); System.out.println(in.readLine()); while(!connect) { System.out.println("Verification de login"); System.out.println(in.readLine()); login = sc.nextLine(); out.println(login); out.flush(); System.out.println(in.readLine()); pass = sc.nextLine(); out.println(pass); out.flush(); if(in.readLine().equalsIgnoreCase("connect")){ System.out.println("Vous etes connecté"); connect = true; } else { System.out.println("Erreur de password ou login"); } } } catch (IOException ex) { Logger.getLogger(Connexion.class.getName()).log(Level.SEVERE, null, ex); } } }
UTF-8
Java
1,740
java
Connexion.java
Java
[ { "context": "mport java.util.logging.Logger;\n\n/**\n *\n * @author kaldoran\n */\nclass Connexion {\n public static String lo", "end": 446, "score": 0.9995512962341309, "start": 438, "tag": "USERNAME", "value": "kaldoran" } ]
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 serveur.communication; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; import java.net.Socket; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author kaldoran */ class Connexion { public static String login = null, pass = null, message1 = null, message2 = null, message3 = null; private Scanner sc = null; private Boolean connect = false; public Connexion(Socket socket, PrintWriter out, BufferedReader in) { try { String s; sc = new Scanner(System.in); System.out.println(in.readLine()); while(!connect) { System.out.println("Verification de login"); System.out.println(in.readLine()); login = sc.nextLine(); out.println(login); out.flush(); System.out.println(in.readLine()); pass = sc.nextLine(); out.println(pass); out.flush(); if(in.readLine().equalsIgnoreCase("connect")){ System.out.println("Vous etes connecté"); connect = true; } else { System.out.println("Erreur de password ou login"); } } } catch (IOException ex) { Logger.getLogger(Connexion.class.getName()).log(Level.SEVERE, null, ex); } } }
1,740
0.549166
0.547441
61
27.508196
23.679295
102
false
false
0
0
0
0
0
0
0.622951
false
false
10
79e6dc88ecc5ee5e77cc8debd8b567d4013fea66
12,996,571,098,879
59d0601f10c0af84168f09447ebef24041140b04
/Movie/app/src/main/java/com/example/minhnguyen/movie/listMovie/ComplexMovie.java
24acdc77c75d47d9b3555bc544a9022640353d6c
[ "Apache-2.0" ]
permissive
minhnguyen10397/week1
https://github.com/minhnguyen10397/week1
14363706483788693ee2716baef7475ab74c3bc2
cd270d39edd7d86dee2e459fe32bbbf179d5b029
refs/heads/master
2020-03-19T19:36:26.488000
2018-06-18T03:42:46
2018-06-18T03:42:46
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.minhnguyen.movie.listMovie; import android.app.ActivityOptions; import android.content.Context; import android.content.Intent; import android.content.res.Configuration; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.bumptech.glide.Glide; import com.bumptech.glide.load.MultiTransformation; import com.bumptech.glide.request.RequestOptions; import com.example.minhnguyen.movie.R; import com.example.minhnguyen.movie.VideoActivity; import com.example.minhnguyen.movie.ViewDetail.Movie; import com.example.minhnguyen.movie.ViewDetail.MovieDetailActivity; import com.example.minhnguyen.movie.retrofit.Result; import java.util.Collections; import java.util.List; import jp.wasabeef.glide.transformations.RoundedCornersTransformation; import static com.bumptech.glide.request.RequestOptions.bitmapTransform; public class ComplexMovie extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private MultiTransformation cornor = new MultiTransformation(new RoundedCornersTransformation(10, 0)); // The items to display in your RecyclerView private Context context; private List<Result> movieList = Collections.emptyList(); private final int type1 = 0, type2 = 1; public void clear() { movieList.clear(); notifyDataSetChanged(); } // Add a list of items -- change to type used public void addAll(List<Result> list) { movieList.addAll(list); notifyDataSetChanged(); } // Provide a suitable constructor (depends on the kind of dataset) public ComplexMovie(Context context,List<Result> movieList) { this.context = context; this.movieList = movieList; } // Return the size of your dataset (invoked by the layout manager) @Override public int getItemCount() { return movieList.size(); } @Override public int getItemViewType(int position) { if (movieList.get(position).getVoteAverage() > 7.5 && context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { return type2; } else if (movieList.get(position).getVoteAverage() > 7.5 && context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { return -1; } else return type1; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) { RecyclerView.ViewHolder viewHolder; LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext()); switch (viewType) { case type1: View v1 = inflater.inflate(R.layout.layout_viewholder1, viewGroup, false); viewHolder = new ViewHolder1(v1); break; case type2: View v2 = inflater.inflate(R.layout.layout_viewholder2, viewGroup, false); viewHolder = new ViewHolder2(v2); break; default: View v3 = inflater.inflate(R.layout.layout_viewholder3, viewGroup, false); viewHolder = new ViewHolder3(v3); } return viewHolder; } @Override public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, final int position) { switch (viewHolder.getItemViewType()) { case type1: ViewHolder1 vh1 = (ViewHolder1) viewHolder; configureViewHolder1(vh1, position); vh1.layout.setOnClickListener(new View.OnClickListener() { @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) @Override public void onClick(View v) { Intent intent = new Intent(context, MovieDetailActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); float vote = movieList.get(position).getVoteAverage().floatValue(); Movie movie = new Movie(movieList.get(position).getId(),movieList.get(position).getTitle(), movieList.get(position).getOverview(), "https://image.tmdb.org/t/p/original" + movieList.get(position).getPosterPath(), vote,movieList.get(position).getReleaseDate()); Bundle b = new Bundle(); b.putSerializable("movie", movie); intent.putExtra("MOVIE", b); ActivityOptions options = ActivityOptions.makeCustomAnimation(context,R.anim.right_to_left,0); context.startActivity(intent,options.toBundle()); } }); break; case type2: ViewHolder2 vh2 = (ViewHolder2) viewHolder; configureViewHolder2(vh2, position); vh2.getOverlayType2().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, VideoActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); int movieID = movieList.get(position).getId(); intent.putExtra("MOVIE_ID", movieID); context.startActivity(intent); } }); break; default: ViewHolder3 vh3 = (ViewHolder3) viewHolder; configureViewHolder3(vh3, position); configureViewHolder3(vh3, position); vh3.getOverlayType3().setOnClickListener(new View.OnClickListener() { @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) @Override public void onClick(View v) { Intent intent = new Intent(context, VideoActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); int movieID = movieList.get(position).getId(); intent.putExtra("MOVIE_ID", movieID); context.startActivity(intent); } }); } } private void configureViewHolder1(ViewHolder1 vh1, int position) { if (movieList != null) { vh1.getTitleType1().setText(movieList.get(position).getTitle()); vh1.getOverviewType1().setText(movieList.get(position).getOverview()); RequestOptions optionsType = new RequestOptions() .centerCrop().placeholder(R.drawable.loading_spinner) .error(R.drawable.loading_spinner) .apply(bitmapTransform(cornor)); Glide.with(context) .load("https://image.tmdb.org/t/p/original" + movieList.get(position).getPosterPath()) .apply(optionsType) //.apply(bitmapTransform(cornorPoster)) .into(vh1.getImgType1()); /*if (context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { Glide.with(context) .load("https://image.tmdb.org/t/p/original" + movieList.get(position).getBackdropPath()) .apply(bitmapTransform(cornorPoster)) .into(vh1.getImgType1()); } else { //Picasso.get().load("https://image.tmdb.org/t/p/original" + movieList.get(position).getPosterPath()).transform(new RoundedTransformation(50, 0)).into(vh1.getImgType1()); Glide.with(context) .load("https://image.tmdb.org/t/p/original" + movieList.get(position).getPosterPath()) .apply(bitmapTransform(cornorPoster)) .into(vh1.getImgType1()); }*/ } } private void configureViewHolder2(ViewHolder2 vh2, int position) { if (movieList != null) { RequestOptions optionsType = new RequestOptions() .placeholder(R.drawable.loading_spinner) .error(R.drawable.loading_spinner); Glide.with(context) .load("https://image.tmdb.org/t/p/original" + movieList.get(position).getBackdropPath()) .apply(bitmapTransform(cornor)) .apply(optionsType) .into(vh2.getImg()); Glide.with(context) .load(R.drawable.icon) .apply(bitmapTransform(cornor)) .into(vh2.getOverlayType2()); } } private void configureViewHolder3(ViewHolder3 vh3, int position) { if (movieList != null) { vh3.getTitleType3().setText(movieList.get(position).getTitle()); vh3.getOverviewType3().setText(movieList.get(position).getOverview()); //Picasso.get().load("https://image.tmdb.org/t/p/original" + movieList.get(position).getBackdropPath()).transform(new RoundedTransformation(50, 0)).into(vh3.getImgType3()); RequestOptions optionsType = new RequestOptions() .placeholder(R.drawable.loading_spinner) .error(R.drawable.loading_spinner); Glide.with(context) .load("https://image.tmdb.org/t/p/original" + movieList.get(position).getBackdropPath()) .apply(bitmapTransform(cornor)) .apply(optionsType) .into(vh3.getImgType3()); if (movieList.get(position).getVoteAverage()>7.5) { Glide.with(context) .load(R.drawable.icon) .apply(bitmapTransform(cornor)) .into(vh3.getOverlayType3()); } } } }
UTF-8
Java
10,127
java
ComplexMovie.java
Java
[]
null
[]
package com.example.minhnguyen.movie.listMovie; import android.app.ActivityOptions; import android.content.Context; import android.content.Intent; import android.content.res.Configuration; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.bumptech.glide.Glide; import com.bumptech.glide.load.MultiTransformation; import com.bumptech.glide.request.RequestOptions; import com.example.minhnguyen.movie.R; import com.example.minhnguyen.movie.VideoActivity; import com.example.minhnguyen.movie.ViewDetail.Movie; import com.example.minhnguyen.movie.ViewDetail.MovieDetailActivity; import com.example.minhnguyen.movie.retrofit.Result; import java.util.Collections; import java.util.List; import jp.wasabeef.glide.transformations.RoundedCornersTransformation; import static com.bumptech.glide.request.RequestOptions.bitmapTransform; public class ComplexMovie extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private MultiTransformation cornor = new MultiTransformation(new RoundedCornersTransformation(10, 0)); // The items to display in your RecyclerView private Context context; private List<Result> movieList = Collections.emptyList(); private final int type1 = 0, type2 = 1; public void clear() { movieList.clear(); notifyDataSetChanged(); } // Add a list of items -- change to type used public void addAll(List<Result> list) { movieList.addAll(list); notifyDataSetChanged(); } // Provide a suitable constructor (depends on the kind of dataset) public ComplexMovie(Context context,List<Result> movieList) { this.context = context; this.movieList = movieList; } // Return the size of your dataset (invoked by the layout manager) @Override public int getItemCount() { return movieList.size(); } @Override public int getItemViewType(int position) { if (movieList.get(position).getVoteAverage() > 7.5 && context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { return type2; } else if (movieList.get(position).getVoteAverage() > 7.5 && context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { return -1; } else return type1; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) { RecyclerView.ViewHolder viewHolder; LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext()); switch (viewType) { case type1: View v1 = inflater.inflate(R.layout.layout_viewholder1, viewGroup, false); viewHolder = new ViewHolder1(v1); break; case type2: View v2 = inflater.inflate(R.layout.layout_viewholder2, viewGroup, false); viewHolder = new ViewHolder2(v2); break; default: View v3 = inflater.inflate(R.layout.layout_viewholder3, viewGroup, false); viewHolder = new ViewHolder3(v3); } return viewHolder; } @Override public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, final int position) { switch (viewHolder.getItemViewType()) { case type1: ViewHolder1 vh1 = (ViewHolder1) viewHolder; configureViewHolder1(vh1, position); vh1.layout.setOnClickListener(new View.OnClickListener() { @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) @Override public void onClick(View v) { Intent intent = new Intent(context, MovieDetailActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); float vote = movieList.get(position).getVoteAverage().floatValue(); Movie movie = new Movie(movieList.get(position).getId(),movieList.get(position).getTitle(), movieList.get(position).getOverview(), "https://image.tmdb.org/t/p/original" + movieList.get(position).getPosterPath(), vote,movieList.get(position).getReleaseDate()); Bundle b = new Bundle(); b.putSerializable("movie", movie); intent.putExtra("MOVIE", b); ActivityOptions options = ActivityOptions.makeCustomAnimation(context,R.anim.right_to_left,0); context.startActivity(intent,options.toBundle()); } }); break; case type2: ViewHolder2 vh2 = (ViewHolder2) viewHolder; configureViewHolder2(vh2, position); vh2.getOverlayType2().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, VideoActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); int movieID = movieList.get(position).getId(); intent.putExtra("MOVIE_ID", movieID); context.startActivity(intent); } }); break; default: ViewHolder3 vh3 = (ViewHolder3) viewHolder; configureViewHolder3(vh3, position); configureViewHolder3(vh3, position); vh3.getOverlayType3().setOnClickListener(new View.OnClickListener() { @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) @Override public void onClick(View v) { Intent intent = new Intent(context, VideoActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); int movieID = movieList.get(position).getId(); intent.putExtra("MOVIE_ID", movieID); context.startActivity(intent); } }); } } private void configureViewHolder1(ViewHolder1 vh1, int position) { if (movieList != null) { vh1.getTitleType1().setText(movieList.get(position).getTitle()); vh1.getOverviewType1().setText(movieList.get(position).getOverview()); RequestOptions optionsType = new RequestOptions() .centerCrop().placeholder(R.drawable.loading_spinner) .error(R.drawable.loading_spinner) .apply(bitmapTransform(cornor)); Glide.with(context) .load("https://image.tmdb.org/t/p/original" + movieList.get(position).getPosterPath()) .apply(optionsType) //.apply(bitmapTransform(cornorPoster)) .into(vh1.getImgType1()); /*if (context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { Glide.with(context) .load("https://image.tmdb.org/t/p/original" + movieList.get(position).getBackdropPath()) .apply(bitmapTransform(cornorPoster)) .into(vh1.getImgType1()); } else { //Picasso.get().load("https://image.tmdb.org/t/p/original" + movieList.get(position).getPosterPath()).transform(new RoundedTransformation(50, 0)).into(vh1.getImgType1()); Glide.with(context) .load("https://image.tmdb.org/t/p/original" + movieList.get(position).getPosterPath()) .apply(bitmapTransform(cornorPoster)) .into(vh1.getImgType1()); }*/ } } private void configureViewHolder2(ViewHolder2 vh2, int position) { if (movieList != null) { RequestOptions optionsType = new RequestOptions() .placeholder(R.drawable.loading_spinner) .error(R.drawable.loading_spinner); Glide.with(context) .load("https://image.tmdb.org/t/p/original" + movieList.get(position).getBackdropPath()) .apply(bitmapTransform(cornor)) .apply(optionsType) .into(vh2.getImg()); Glide.with(context) .load(R.drawable.icon) .apply(bitmapTransform(cornor)) .into(vh2.getOverlayType2()); } } private void configureViewHolder3(ViewHolder3 vh3, int position) { if (movieList != null) { vh3.getTitleType3().setText(movieList.get(position).getTitle()); vh3.getOverviewType3().setText(movieList.get(position).getOverview()); //Picasso.get().load("https://image.tmdb.org/t/p/original" + movieList.get(position).getBackdropPath()).transform(new RoundedTransformation(50, 0)).into(vh3.getImgType3()); RequestOptions optionsType = new RequestOptions() .placeholder(R.drawable.loading_spinner) .error(R.drawable.loading_spinner); Glide.with(context) .load("https://image.tmdb.org/t/p/original" + movieList.get(position).getBackdropPath()) .apply(bitmapTransform(cornor)) .apply(optionsType) .into(vh3.getImgType3()); if (movieList.get(position).getVoteAverage()>7.5) { Glide.with(context) .load(R.drawable.icon) .apply(bitmapTransform(cornor)) .into(vh3.getOverlayType3()); } } } }
10,127
0.587933
0.578454
217
45.67281
33.110329
186
false
false
0
0
0
0
0
0
0.603687
false
false
10
683c87d16f8aec83448894011330e1402f99431e
26,680,336,911,290
9f8a2aaaec5cc50da4c9850f255268d0f513f0a1
/app/src/main/java/com/dazone/crewchat/ViewHolders/ListGroupViewHolder.java
d225d53c76c0a45e7389a92a7194752d21c1f606
[]
no_license
TungLam9101/crewchat
https://github.com/TungLam9101/crewchat
0f05648e0f4adb826270c431d0f0eb609fab6f50
87e95c7ea297a2fd34b1af4b7ae2212eea0f0e9a
refs/heads/master
2020-06-27T08:42:45.468000
2016-12-07T07:17:21
2016-12-07T07:17:21
74,530,460
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.dazone.crewchat.ViewHolders; import android.view.View; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.dazone.crewchat.R; import com.dazone.crewchat.dto.TreeUserDTOTemp; import com.dazone.crewchat.utils.DialogUtils; import com.dazone.crewchat.utils.ImageUtils; import com.dazone.crewchat.utils.Prefs; import com.dazone.crewchat.utils.Utils; /** * Created by THANHTUNG on 04/03/2016. */ public class ListGroupViewHolder extends ItemViewHolder<TreeUserDTOTemp> { private RelativeLayout layoutMain; private TextView tvUserName, tvPosition; private ImageView ivAvatar; public ListGroupViewHolder(View v) { super(v); } @Override protected void setup(View v) { layoutMain = (RelativeLayout) v.findViewById(R.id.layout_main); tvUserName = (TextView) v.findViewById(R.id.tv_username); ivAvatar = (ImageView) v.findViewById(R.id.iv_avatar); tvPosition = (TextView) v.findViewById(R.id.tv_position); } @Override public void bindData(TreeUserDTOTemp treeUserDTOTemp) { if (treeUserDTOTemp != null) { tvUserName.setText(treeUserDTOTemp.getName()); tvPosition.setText(treeUserDTOTemp.getPosition()); //ImageLoader.getInstance().displayImage(new Prefs().getServerSite() + treeUserDTOTemp.getAvatarUrl(), ivAvatar, Statics.options2); ImageUtils.showCycleImageFromLink(new Prefs().getServerSite() + treeUserDTOTemp.getAvatarUrl(), ivAvatar, R.dimen.button_height); layoutMain.setTag(treeUserDTOTemp); layoutMain.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { TreeUserDTOTemp user = (TreeUserDTOTemp) v.getTag(); String strName = user.getName(); String strPhoneNumber = user.getCellPhone(); String strCompanyNumber = user.getCompanyPhone(); int userNo = user.getUserNo(); Utils.printLogs(user.getName() + " " + user.getCellPhone() + " " + user.getCompanyPhone()); DialogUtils.showDialogUser(strName, strPhoneNumber, strCompanyNumber, userNo); return false; } }); } } }
UTF-8
Java
2,388
java
ListGroupViewHolder.java
Java
[ { "context": "om.dazone.crewchat.utils.Utils;\n\n/**\n * Created by THANHTUNG on 04/03/2016.\n */\npublic class ListGroupViewHold", "end": 448, "score": 0.9950278997421265, "start": 439, "tag": "USERNAME", "value": "THANHTUNG" } ]
null
[]
package com.dazone.crewchat.ViewHolders; import android.view.View; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.dazone.crewchat.R; import com.dazone.crewchat.dto.TreeUserDTOTemp; import com.dazone.crewchat.utils.DialogUtils; import com.dazone.crewchat.utils.ImageUtils; import com.dazone.crewchat.utils.Prefs; import com.dazone.crewchat.utils.Utils; /** * Created by THANHTUNG on 04/03/2016. */ public class ListGroupViewHolder extends ItemViewHolder<TreeUserDTOTemp> { private RelativeLayout layoutMain; private TextView tvUserName, tvPosition; private ImageView ivAvatar; public ListGroupViewHolder(View v) { super(v); } @Override protected void setup(View v) { layoutMain = (RelativeLayout) v.findViewById(R.id.layout_main); tvUserName = (TextView) v.findViewById(R.id.tv_username); ivAvatar = (ImageView) v.findViewById(R.id.iv_avatar); tvPosition = (TextView) v.findViewById(R.id.tv_position); } @Override public void bindData(TreeUserDTOTemp treeUserDTOTemp) { if (treeUserDTOTemp != null) { tvUserName.setText(treeUserDTOTemp.getName()); tvPosition.setText(treeUserDTOTemp.getPosition()); //ImageLoader.getInstance().displayImage(new Prefs().getServerSite() + treeUserDTOTemp.getAvatarUrl(), ivAvatar, Statics.options2); ImageUtils.showCycleImageFromLink(new Prefs().getServerSite() + treeUserDTOTemp.getAvatarUrl(), ivAvatar, R.dimen.button_height); layoutMain.setTag(treeUserDTOTemp); layoutMain.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { TreeUserDTOTemp user = (TreeUserDTOTemp) v.getTag(); String strName = user.getName(); String strPhoneNumber = user.getCellPhone(); String strCompanyNumber = user.getCompanyPhone(); int userNo = user.getUserNo(); Utils.printLogs(user.getName() + " " + user.getCellPhone() + " " + user.getCompanyPhone()); DialogUtils.showDialogUser(strName, strPhoneNumber, strCompanyNumber, userNo); return false; } }); } } }
2,388
0.66206
0.658291
60
38.799999
32.740799
143
false
false
0
0
0
0
0
0
0.683333
false
false
10
a3a3d202028b777245adfb95ffc6d4708885babc
5,188,320,518,207
f89223660be3f79c47ee2690cc4a00337485bcec
/app/src/main/java/com/example/andrescabal/musicapp/domain/usecase/LastFmAuthUseCase.java
4ec68074e412b3d3852723e24697f732a8eef5f6
[]
no_license
maurocabor521/Musicapp
https://github.com/maurocabor521/Musicapp
2222e54f85bf2f3fab3447f9b112fe5d7c50eea1
0d2e18481f274c0b6f5e37297104fc7deab52255
refs/heads/master
2020-03-12T11:03:55.459000
2018-04-25T23:29:13
2018-04-25T23:29:13
130,587,681
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.andrescabal.musicapp.domain.usecase; import com.example.andrescabal.musicapp.domain.model.MobileSessionResponse; import com.example.andrescabal.musicapp.helpers.Callback; /** * Created by krlosf on 14/04/18. */ public interface LastFmAuthUseCase { void getMobileSession(String username, String password, Callback<MobileSessionResponse> callback); }
UTF-8
Java
382
java
LastFmAuthUseCase.java
Java
[ { "context": "al.musicapp.helpers.Callback;\n\n\n\n/**\n * Created by krlosf on 14/04/18.\n */\n\npublic interface LastFmAuthUseC", "end": 219, "score": 0.9996476173400879, "start": 213, "tag": "USERNAME", "value": "krlosf" } ]
null
[]
package com.example.andrescabal.musicapp.domain.usecase; import com.example.andrescabal.musicapp.domain.model.MobileSessionResponse; import com.example.andrescabal.musicapp.helpers.Callback; /** * Created by krlosf on 14/04/18. */ public interface LastFmAuthUseCase { void getMobileSession(String username, String password, Callback<MobileSessionResponse> callback); }
382
0.801047
0.78534
16
22.875
32.060246
102
false
false
0
0
0
0
0
0
0.375
false
false
10
ba4efbb0d6375ccfee23f20505999e80bdb64533
3,616,362,512,534
1e30906b00806084e9b7640f1704ee09cb14bb20
/src/main/java/com/birdsnail/flink/stream/StreamJoinTest.java
01dfa2f7a2d7ab36b6ff3af810e51c743a87a3b3
[]
no_license
BirdSnail/flink-training
https://github.com/BirdSnail/flink-training
ce7db8be828a225a5858a0d13a39f603622d23f1
84d8b5786c8b30d9632c822c72e338e06b660486
refs/heads/master
2021-07-03T13:57:11.361000
2020-01-16T07:46:29
2020-01-16T07:46:29
230,219,418
0
0
null
false
2021-04-26T19:49:27
2019-12-26T07:44:40
2020-01-16T07:46:53
2021-04-26T19:49:27
26
0
0
1
Java
false
false
package com.birdsnail.flink.stream; import org.apache.flink.streaming.api.datastream.DataStreamSource; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; /** * @author BirdSnail * @date 2020/1/14 */ public class StreamJoinTest { public static void main(String[] args) { StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); DataStreamSource<Integer> intSource = env.fromElements(1, 2, 3); DataStreamSource<String> stringSource = env.fromElements("1", "2", "3"); // intSource.keyBy(1) // .join(stringSource) // .where().equalTo(0) // .window() // . } }
UTF-8
Java
720
java
StreamJoinTest.java
Java
[ { "context": "onment.StreamExecutionEnvironment;\n\n/**\n * @author BirdSnail\n * @date 2020/1/14\n */\npublic class StreamJoinTes", "end": 207, "score": 0.9967833161354065, "start": 198, "tag": "USERNAME", "value": "BirdSnail" } ]
null
[]
package com.birdsnail.flink.stream; import org.apache.flink.streaming.api.datastream.DataStreamSource; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; /** * @author BirdSnail * @date 2020/1/14 */ public class StreamJoinTest { public static void main(String[] args) { StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); DataStreamSource<Integer> intSource = env.fromElements(1, 2, 3); DataStreamSource<String> stringSource = env.fromElements("1", "2", "3"); // intSource.keyBy(1) // .join(stringSource) // .where().equalTo(0) // .window() // . } }
720
0.65
0.629167
25
27.799999
28.820826
94
false
false
0
0
0
0
0
0
0.4
false
false
10
645cb358e12ed74a850cb8574c09710b5247d1ee
34,720,515,649,111
e514832bca77d1d45e725fee4b5eac8a23dc4d53
/rpc-commons/src/main/java/com/earlyrpc/commons/protocol/handler/RpcDecodeHandler.java
b1dfaf3eceff972925e25e42a3c52d62f7ce353a
[]
no_license
solthx/early-RPC
https://github.com/solthx/early-RPC
c9fa7b5d53abbc7bab4d22ef3e3a5e3bed8e7eb3
75d1b519937a158c15f939de35a0896144ab63e2
refs/heads/master
2022-12-30T21:44:55.310000
2020-10-20T05:19:39
2020-10-20T05:19:39
287,712,575
7
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.earlyrpc.commons.protocol.handler; import com.earlyrpc.commons.protocol.EarlyRpcProtocol; import com.earlyrpc.commons.serializer.Serializer; import com.earlyrpc.commons.serializer.SerializerChooser; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ByteToMessageDecoder; import lombok.extern.slf4j.Slf4j; import java.util.List; /** * @author czf * @Date 2020/9/23 11:10 下午 */ @Slf4j public class RpcDecodeHandler extends ByteToMessageDecoder { /** * 协议体的类对象 */ private Class<?> protocolBodyClass; public RpcDecodeHandler(Class<?> protocolBodyClass) { this.protocolBodyClass = protocolBodyClass; } /** * 协议解码: * 1. 消息包的总长度(4字节) * 2. 协议头: * a. 协议头长度(2字节) short * b. 协议版本号(1字节) * c. 消息类型(1字节) * d. 序列化方式(1字节) * 3. 协议体: * a. 协议体的序列化内容(序列化为protocolBodyClass类型的对象) * * @param channelHandlerContext * @param byteBuf * @param list * @throws Exception */ @Override protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception { if (byteBuf.readableBytes() < 4) { // byteBuf.markReaderIndex(); // log.info("{}<4 返回, 数据为:\n", byteBuf.readableBytes()); // char[] ch = byteBuf.readBytes(byteBuf.readableBytes()).toString().toCharArray(); // for( int i=0; i<ch.length; ++i ){ // System.out.print(ch[i]); // } // System.out.println(); // byteBuf.resetReaderIndex(); return; } byteBuf.markReaderIndex(); // 消息总长度 int messageLength = byteBuf.readInt(); // if ( byteBuf.readableBytes()<messageLength ){ // log.info("{}<messageLength={} 返回", byteBuf.readableBytes(), messageLength); // byteBuf.resetReaderIndex(); // return ; // } // 魔数 byte magicCode = byteBuf.readByte(); if ( magicCode != EarlyRpcProtocol.MAGIC_CODE ){ // 如果不是earlyRpc协议,则不处理 byteBuf.resetReaderIndex(); return ; } // 协议头长度 short protocolHeaderLength = byteBuf.readShort(); // 协议头 ByteBuf protocolHeaderByteBuf = byteBuf.readBytes(protocolHeaderLength); // 协议版本号 Byte version = protocolHeaderByteBuf.readByte(); // 消息类型 Byte messageType = protocolHeaderByteBuf.readByte(); // 序列化方式 Byte serializeType = protocolHeaderByteBuf.readByte(); Serializer serializer = SerializerChooser.choose(serializeType); // 获取协议体 = 总长度 - 协议头长度(protocolHeaderLength) - 协议头长度的长度(short=2字节) - 魔数长度(1字节) // = 总长度 - 协议头长度(protocolHeaderLength) - 3 byte [] protocolBodyBytes = new byte[(messageLength-protocolHeaderLength-3)]; byteBuf.readBytes(protocolBodyBytes); Object protocolBody = serializer.deserialize(protocolBodyBytes, protocolBodyClass); list.add(protocolBody); log.debug("received a message : \n" +"\tmessageLength:{},\n" +"\tprotocolHeaderLength:{}\n" +"\tversion:{},\n" +"\tmessageType:{},\n" +"\tserializeType:{},\n" +"\tprotocolBody:{}", messageLength, protocolHeaderLength,version,messageType, serializeType,protocolBody); } }
UTF-8
Java
3,845
java
RpcDecodeHandler.java
Java
[ { "context": "f4j.Slf4j;\n\nimport java.util.List;\n\n/**\n * @author czf\n * @Date 2020/9/23 11:10 下午\n */\n@Slf4j\npublic cla", "end": 420, "score": 0.9996284246444702, "start": 417, "tag": "USERNAME", "value": "czf" } ]
null
[]
package com.earlyrpc.commons.protocol.handler; import com.earlyrpc.commons.protocol.EarlyRpcProtocol; import com.earlyrpc.commons.serializer.Serializer; import com.earlyrpc.commons.serializer.SerializerChooser; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ByteToMessageDecoder; import lombok.extern.slf4j.Slf4j; import java.util.List; /** * @author czf * @Date 2020/9/23 11:10 下午 */ @Slf4j public class RpcDecodeHandler extends ByteToMessageDecoder { /** * 协议体的类对象 */ private Class<?> protocolBodyClass; public RpcDecodeHandler(Class<?> protocolBodyClass) { this.protocolBodyClass = protocolBodyClass; } /** * 协议解码: * 1. 消息包的总长度(4字节) * 2. 协议头: * a. 协议头长度(2字节) short * b. 协议版本号(1字节) * c. 消息类型(1字节) * d. 序列化方式(1字节) * 3. 协议体: * a. 协议体的序列化内容(序列化为protocolBodyClass类型的对象) * * @param channelHandlerContext * @param byteBuf * @param list * @throws Exception */ @Override protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception { if (byteBuf.readableBytes() < 4) { // byteBuf.markReaderIndex(); // log.info("{}<4 返回, 数据为:\n", byteBuf.readableBytes()); // char[] ch = byteBuf.readBytes(byteBuf.readableBytes()).toString().toCharArray(); // for( int i=0; i<ch.length; ++i ){ // System.out.print(ch[i]); // } // System.out.println(); // byteBuf.resetReaderIndex(); return; } byteBuf.markReaderIndex(); // 消息总长度 int messageLength = byteBuf.readInt(); // if ( byteBuf.readableBytes()<messageLength ){ // log.info("{}<messageLength={} 返回", byteBuf.readableBytes(), messageLength); // byteBuf.resetReaderIndex(); // return ; // } // 魔数 byte magicCode = byteBuf.readByte(); if ( magicCode != EarlyRpcProtocol.MAGIC_CODE ){ // 如果不是earlyRpc协议,则不处理 byteBuf.resetReaderIndex(); return ; } // 协议头长度 short protocolHeaderLength = byteBuf.readShort(); // 协议头 ByteBuf protocolHeaderByteBuf = byteBuf.readBytes(protocolHeaderLength); // 协议版本号 Byte version = protocolHeaderByteBuf.readByte(); // 消息类型 Byte messageType = protocolHeaderByteBuf.readByte(); // 序列化方式 Byte serializeType = protocolHeaderByteBuf.readByte(); Serializer serializer = SerializerChooser.choose(serializeType); // 获取协议体 = 总长度 - 协议头长度(protocolHeaderLength) - 协议头长度的长度(short=2字节) - 魔数长度(1字节) // = 总长度 - 协议头长度(protocolHeaderLength) - 3 byte [] protocolBodyBytes = new byte[(messageLength-protocolHeaderLength-3)]; byteBuf.readBytes(protocolBodyBytes); Object protocolBody = serializer.deserialize(protocolBodyBytes, protocolBodyClass); list.add(protocolBody); log.debug("received a message : \n" +"\tmessageLength:{},\n" +"\tprotocolHeaderLength:{}\n" +"\tversion:{},\n" +"\tmessageType:{},\n" +"\tserializeType:{},\n" +"\tprotocolBody:{}", messageLength, protocolHeaderLength,version,messageType, serializeType,protocolBody); } }
3,845
0.596815
0.58857
112
30.401785
27.402901
125
false
false
0
0
0
0
0
0
0.5
false
false
10
f461ade80e85d5d07815def318ecddd0b50ea9e4
24,292,335,042,491
b7d16e7cb9c917ec218a101f395e188fc3b3ed5f
/tests/scripts/UseHref.java
2905ade57aa0c95da9bf772303fb0e29520f2c79
[]
no_license
deadpool1418/Selenium_Webdriver
https://github.com/deadpool1418/Selenium_Webdriver
83b51424debcc1da19b311b0d5e3a09eb9a05717
7f2cf98edc8eaa730f8e090456b03e448371c319
refs/heads/master
2023-07-16T09:12:31.359000
2021-08-31T08:59:36
2021-08-31T08:59:36
394,561,898
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package scripts; import static scripts.PropertyReader.getProperty; import static utilities.Driver.setup; import java.io.FileNotFoundException; import java.io.IOException; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; public class UseHref { public static void main(String[] args) throws FileNotFoundException, IOException { WebDriver driver = setup("CH"); String urlString = getProperty("baseUrl"); driver.get(urlString); List<WebElement> list = driver.findElements(By.tagName("a")); for(WebElement element: list) { if (element.isDisplayed()) System.out.println(element.getText() + " " + element.getAttribute("href")); } } }
UTF-8
Java
740
java
UseHref.java
Java
[]
null
[]
package scripts; import static scripts.PropertyReader.getProperty; import static utilities.Driver.setup; import java.io.FileNotFoundException; import java.io.IOException; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; public class UseHref { public static void main(String[] args) throws FileNotFoundException, IOException { WebDriver driver = setup("CH"); String urlString = getProperty("baseUrl"); driver.get(urlString); List<WebElement> list = driver.findElements(By.tagName("a")); for(WebElement element: list) { if (element.isDisplayed()) System.out.println(element.getText() + " " + element.getAttribute("href")); } } }
740
0.751351
0.751351
27
26.407408
23.373392
83
false
false
0
0
0
0
0
0
1.407407
false
false
10
2c56691995105a90d3ea03b8c3f87c682284ca50
24,292,335,038,822
5d26c0ca60f5a37cb0d7344724800eca65f4a312
/src/main/java/cn/aethli/thoth/controller/LotteryController.java
d9d8c81d7fdbf9e34236df5cdeed87ee5b0d7a8e
[ "Apache-2.0" ]
permissive
AethLi/thoth_data
https://github.com/AethLi/thoth_data
37a96a7ae81a7da578416d5c99514724bb9f0eea
8340795ff6e4c9c45519851e44e8bee72ef9a734
refs/heads/master
2022-09-22T19:45:51.888000
2022-09-02T01:06:00
2022-09-02T01:06:00
203,950,463
0
0
Apache-2.0
false
2022-09-02T01:06:01
2019-08-23T07:47:43
2021-08-24T01:20:26
2022-09-02T01:06:00
150
0
0
0
Java
false
false
package cn.aethli.thoth.controller; import cn.aethli.thoth.common.enums.LotteryType; import cn.aethli.thoth.common.exception.LotteryException; import cn.aethli.thoth.common.utils.LotteryUtils; import cn.aethli.thoth.service.LotteryService; import java.util.List; import java.util.Map; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestControllerAdvice; /** * @author Termite */ @Slf4j @RestControllerAdvice @RequestMapping("lottery") public class LotteryController { @Autowired private LotteryService lotteryService; @GetMapping public Object doGet(@RequestBody Map<String, String> params) { LotteryType type = LotteryType.get(Integer.parseInt(params.get("type"))); lotteryService.getNewest(type); switch (type) { case QXC: break; } return null; } @GetMapping(value = "compare") public Object compare(@RequestParam int typeValue, @RequestParam String lotteryValue) { LotteryType type = LotteryType.get(typeValue); switch (type) { case QXC: try { List<String> lotteryValues = LotteryUtils.resolve(LotteryType.QXC, lotteryValue); lotteryService.compare(type, lotteryValues); } catch (LotteryException e) { log.error(e.getMessage(), e); } break; } return null; } }
UTF-8
Java
1,643
java
LotteryController.java
Java
[ { "context": "d.annotation.RestControllerAdvice;\n\n/**\n * @author Termite\n */\n@Slf4j\n@RestControllerAdvice\n@RequestMapping(", "end": 718, "score": 0.9994773864746094, "start": 711, "tag": "USERNAME", "value": "Termite" } ]
null
[]
package cn.aethli.thoth.controller; import cn.aethli.thoth.common.enums.LotteryType; import cn.aethli.thoth.common.exception.LotteryException; import cn.aethli.thoth.common.utils.LotteryUtils; import cn.aethli.thoth.service.LotteryService; import java.util.List; import java.util.Map; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestControllerAdvice; /** * @author Termite */ @Slf4j @RestControllerAdvice @RequestMapping("lottery") public class LotteryController { @Autowired private LotteryService lotteryService; @GetMapping public Object doGet(@RequestBody Map<String, String> params) { LotteryType type = LotteryType.get(Integer.parseInt(params.get("type"))); lotteryService.getNewest(type); switch (type) { case QXC: break; } return null; } @GetMapping(value = "compare") public Object compare(@RequestParam int typeValue, @RequestParam String lotteryValue) { LotteryType type = LotteryType.get(typeValue); switch (type) { case QXC: try { List<String> lotteryValues = LotteryUtils.resolve(LotteryType.QXC, lotteryValue); lotteryService.compare(type, lotteryValues); } catch (LotteryException e) { log.error(e.getMessage(), e); } break; } return null; } }
1,643
0.739501
0.737675
54
29.425926
25.036715
91
false
false
0
0
0
0
0
0
0.555556
false
false
10
5516ad945ab52fcfdf6ab5c15ff9fb4743fb72a2
6,201,932,799,268
4d55e56525007d6beac1bc6c157b6c9c023b26a9
/Forte/java/src/edu/virginia/lab1test/LevelThreeEvent.java
2b22b5da6700979f3167141b7e36600a85238ea5
[]
no_license
wzy810103882/Forte2
https://github.com/wzy810103882/Forte2
fa6fe7a22dba837a73866c505aa8774fcc4729da
53ed64f7915660a245ac9c173a5c6368fb4882d4
refs/heads/master
2021-01-19T22:21:25.579000
2017-05-01T05:41:35
2017-05-01T05:41:35
88,799,382
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.virginia.lab1test; import edu.virginia.engine.events.Event; import edu.virginia.engine.events.IEventDispatcher; public class LevelThreeEvent extends Event { static final String LevelThreeEvent = "LevelThree"; public LevelThreeEvent(String eventType, IEventDispatcher source) { super(eventType, source); } }
UTF-8
Java
345
java
LevelThreeEvent.java
Java
[]
null
[]
package edu.virginia.lab1test; import edu.virginia.engine.events.Event; import edu.virginia.engine.events.IEventDispatcher; public class LevelThreeEvent extends Event { static final String LevelThreeEvent = "LevelThree"; public LevelThreeEvent(String eventType, IEventDispatcher source) { super(eventType, source); } }
345
0.762319
0.75942
15
22
24.437675
71
false
false
0
0
0
0
0
0
0.466667
false
false
10
52d5fc6b623d5a43100977657be9b9b6d6092fb2
2,018,634,698,037
55f576da1f9b4d79d1e4802f5617050a1605694b
/src/cfh/tcpscript/command/WaitCommand.java
1831063f91c06a48cb9ea3cfd202365b243e66bb
[ "MIT" ]
permissive
CHeuberger/TCPscript
https://github.com/CHeuberger/TCPscript
2addaf204c8bdd39d5867345e047a2a96429e976
799fc21f5bb206f5b10fe5dc23db47972e67af5c
refs/heads/master
2021-01-19T01:03:01.907000
2020-08-17T22:01:08
2020-08-17T22:58:33
61,931,614
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cfh.tcpscript.command; import java.text.ParseException; import javax.naming.NameNotFoundException; import cfh.tcpscript.Channel; import cfh.tcpscript.ScriptEngine; /** * TODO * * @author Carlos Heuberger * $Revision: 1.8 $ */ class WaitCommand extends Command { WaitCommand() { super("wait", "<name> [<pattern>]", "wait till connected (server) or message received (client)"); } @Override public void run(ScriptEngine executor, String arg) throws Exception { boolean debug = arg.startsWith("-d "); String[] words = arg.substring(debug?3:0).split("\\s++", 2); if (words.length < 1) { throw new ParseException(createUsageMesssage("missing argument"), 0); } String name = words[0]; Channel channel = Channel.get(name); if (channel == null) { throw new NameNotFoundException(name); } if (words.length == 1) { channel.waitConnect(debug?executor.getOutput():null); } else { String regex = words[1]; channel.waitPattern(regex, debug?executor.getOutput():null); } } }
UTF-8
Java
1,159
java
WaitCommand.java
Java
[ { "context": "cpscript.ScriptEngine;\n\n/**\n * TODO\n * \n * @author Carlos Heuberger\n * $Revision: 1.8 $\n */\nclass WaitCommand extends", "end": 219, "score": 0.9998928904533386, "start": 203, "tag": "NAME", "value": "Carlos Heuberger" } ]
null
[]
package cfh.tcpscript.command; import java.text.ParseException; import javax.naming.NameNotFoundException; import cfh.tcpscript.Channel; import cfh.tcpscript.ScriptEngine; /** * TODO * * @author <NAME> * $Revision: 1.8 $ */ class WaitCommand extends Command { WaitCommand() { super("wait", "<name> [<pattern>]", "wait till connected (server) or message received (client)"); } @Override public void run(ScriptEngine executor, String arg) throws Exception { boolean debug = arg.startsWith("-d "); String[] words = arg.substring(debug?3:0).split("\\s++", 2); if (words.length < 1) { throw new ParseException(createUsageMesssage("missing argument"), 0); } String name = words[0]; Channel channel = Channel.get(name); if (channel == null) { throw new NameNotFoundException(name); } if (words.length == 1) { channel.waitConnect(debug?executor.getOutput():null); } else { String regex = words[1]; channel.waitPattern(regex, debug?executor.getOutput():null); } } }
1,149
0.609146
0.600518
41
27.268293
25.817392
105
false
false
0
0
0
0
0
0
0.512195
false
false
10
4d170ce143d4fa77f52e90566d8a3d0c5b84974e
18,313,740,567,457
f5f69e74b1f6f72479e1f1caed241397ef026ef1
/src/exceptions/RegisterPropertyValidationError.java
fd1de1da4e54f2424e86fe1c66d5d31b227f03f5
[]
no_license
jclarke001/RuralHouses
https://github.com/jclarke001/RuralHouses
869adf3d42d62308592bdf3278a5a010305fdd60
a50e652d3398862cab4a2dd8b3a9ca0d941f1d64
refs/heads/master
2016-09-06T21:45:25.024000
2015-09-17T15:03:49
2015-09-17T15:03:49
42,663,123
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package exceptions; public class RegisterPropertyValidationError extends Exception { private static final long serialVersionUID = 1L; public RegisterPropertyValidationError() { super(); } /**This exception is triggered if there exists an overlapping offer *@param String *@return None */ public RegisterPropertyValidationError(String s) { super(s); } }
UTF-8
Java
377
java
RegisterPropertyValidationError.java
Java
[]
null
[]
package exceptions; public class RegisterPropertyValidationError extends Exception { private static final long serialVersionUID = 1L; public RegisterPropertyValidationError() { super(); } /**This exception is triggered if there exists an overlapping offer *@param String *@return None */ public RegisterPropertyValidationError(String s) { super(s); } }
377
0.750663
0.748011
16
22.5625
23.262011
68
false
false
0
0
0
0
0
0
0.9375
false
false
10
9a6168715808aa9075c84f17d562c658452e657d
10,118,942,993,600
428f20d0ff18dd845c01d36839a5effd75ebbeca
/ComputacaoII/src/aula2/exercicios/parte1/Limite.java
43d5b68e8f9436525ffeaacd53645027750a295c
[]
no_license
rmirandarj/ufrrj
https://github.com/rmirandarj/ufrrj
e3ceb88ea8a19ca33d8350c51ea4a1abd89d4058
d4ebb594d16f7b0e7b68dc601b15fe1df3285cac
refs/heads/master
2021-05-29T06:35:16.682000
2015-11-17T23:12:41
2015-11-17T23:12:41
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package aula2.exercicios.parte1; public class Limite{ public static void main(String []args){ double n = 1, lim = 0; while (n > 0){ lim = Math.pow (1 + (1/n), n); n++; System.out.println (lim); } } }
UTF-8
Java
298
java
Limite.java
Java
[]
null
[]
package aula2.exercicios.parte1; public class Limite{ public static void main(String []args){ double n = 1, lim = 0; while (n > 0){ lim = Math.pow (1 + (1/n), n); n++; System.out.println (lim); } } }
298
0.42953
0.40604
13
21.076923
14.871043
44
false
false
0
0
0
0
0
0
0.538462
false
false
10
1b962eb71f74d861b21069423182e646d97a2a6e
14,568,529,107,454
b226ab20232e4cb5beff34f9a2c1f083ffa13243
/src/main/java/jdbc/lesson4/ex2/DemoFile.java
7280b9ba5dc21af441dd6d639130581a834f00ad
[]
no_license
Bdvoga/java-jdbc-grom
https://github.com/Bdvoga/java-jdbc-grom
00690519263d4b597d831e02703878ed2ff9631a
41700287d1f269f72a4a8fa632076dd2da00628e
refs/heads/master
2023-03-02T20:15:22.947000
2021-02-15T21:38:12
2021-02-15T21:38:12
322,681,662
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package jdbc.lesson4.ex2; public class DemoFile { public static void main(String[] args) throws Exception { FileDAO fileDAO = new FileDAO(); Storage storage1 = new Storage(4L, new String[]{"txt", "jpg"}, "UA", 1000L); Storage storage2 = new Storage(1L, new String[]{"txt", "jpg"}, "UA", 1000L); Storage storage3 = new Storage(2L, new String[]{"txt", "jpg"}, "UA", 1000L); File file1 = new File(1L, "test1", "txt", 10L, storage1); File file2 = new File(2L, "test2", "txt", 15L, storage2); File file3 = new File(3L, "test3", "txt", 25L, storage3); File file5 = new File(5L, "test5", "rar", 2000L, storage3); File file6 = new File(6L, "test6", "jpg", 100L, storage3); // fileDAO.save(file6); // fileDAO.delete(5); // fileDAO.update(file3); } }
UTF-8
Java
851
java
DemoFile.java
Java
[]
null
[]
package jdbc.lesson4.ex2; public class DemoFile { public static void main(String[] args) throws Exception { FileDAO fileDAO = new FileDAO(); Storage storage1 = new Storage(4L, new String[]{"txt", "jpg"}, "UA", 1000L); Storage storage2 = new Storage(1L, new String[]{"txt", "jpg"}, "UA", 1000L); Storage storage3 = new Storage(2L, new String[]{"txt", "jpg"}, "UA", 1000L); File file1 = new File(1L, "test1", "txt", 10L, storage1); File file2 = new File(2L, "test2", "txt", 15L, storage2); File file3 = new File(3L, "test3", "txt", 25L, storage3); File file5 = new File(5L, "test5", "rar", 2000L, storage3); File file6 = new File(6L, "test6", "jpg", 100L, storage3); // fileDAO.save(file6); // fileDAO.delete(5); // fileDAO.update(file3); } }
851
0.578143
0.512338
26
31.73077
31.451498
84
false
false
0
0
0
0
0
0
1.730769
false
false
10
7c4bcff40ead640458677334b3b871327c90f8ca
28,192,165,377,526
25e5f041dc759814a8a783d3abfbe09467c66d2b
/src/main/java/com/alinso/stock/dao/CategoryDao.java
f0cfd27713b9afd0d122d5e9840a0c602d30296f
[]
no_license
alinso/stock
https://github.com/alinso/stock
8bc54b6bd5ffdcc1f84e1e564fcc162026ab8b76
05358d12fea8d27382d16733b1ea8c148416135c
refs/heads/master
2021-09-06T21:28:59.445000
2018-02-11T19:06:47
2018-02-11T19:06:47
119,935,424
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.alinso.stock.dao; import com.alinso.stock.dao.BaseDAO; import com.alinso.stock.entity.Category; import org.springframework.stereotype.Repository; /** * Created by KHAN on 2.02.2018. */ @Repository public class CategoryDao extends BaseDAO<Category> { public CategoryDao(){ super.setTheClass(Category.class); } // TODO: AbstractDao Dışında Kullanılacaklar }
UTF-8
Java
396
java
CategoryDao.java
Java
[ { "context": "ramework.stereotype.Repository;\n\n/**\n * Created by KHAN on 2.02.2018.\n */\n@Repository\npublic class Catego", "end": 182, "score": 0.9944159388542175, "start": 178, "tag": "USERNAME", "value": "KHAN" } ]
null
[]
package com.alinso.stock.dao; import com.alinso.stock.dao.BaseDAO; import com.alinso.stock.entity.Category; import org.springframework.stereotype.Repository; /** * Created by KHAN on 2.02.2018. */ @Repository public class CategoryDao extends BaseDAO<Category> { public CategoryDao(){ super.setTheClass(Category.class); } // TODO: AbstractDao Dışında Kullanılacaklar }
396
0.742347
0.72449
17
22.058823
19.337469
52
false
false
0
0
0
0
0
0
0.294118
false
false
10
79f479de52211db1f328c949804f469bc6bba7b1
26,903,675,159,186
4e5a45a95f381b802c0664fc1b7b136c065027aa
/src/main/java/boosterm/backend/domain/Term.java
38cd95775f7680854270513e96b88a2695a52e33
[]
no_license
braianhal/boosterm-backend
https://github.com/braianhal/boosterm-backend
5b79cdcdca4e1c5250b8970adfb077cc207085f0
486e6ca8f72ddb0815833aee6be80f0e7e6fee3f
refs/heads/master
2021-08-17T11:37:53.139000
2018-11-09T02:09:27
2018-11-09T02:09:27
144,166,528
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package boosterm.backend.domain; import java.time.LocalDateTime; import java.util.Map; import static boosterm.backend.config.SystemConfig.now; public class Term { private String code; private String name; private String type; private String description; private LocalDateTime lastUpdated; private Map<String, Boolean> graphsConfig; public Term(String code, String name, String type, String description, LocalDateTime lastUpdated, Map<String, Boolean> graphsConfig) { this.code = code; this.name = name; this.type = type; this.description = description; this.lastUpdated = lastUpdated; this.graphsConfig = graphsConfig; } public String getCode() { return code; } public String getName() { return name; } public String getType() { return type; } public String getDescription() { return description; } public LocalDateTime getLastUpdated() { return lastUpdated; } public Map<String, Boolean> getGraphsConfig() { return graphsConfig; } public Term update(String newDescription, Map<String, Boolean> newGraphsConfig, LocalDateTime now) { String description = newDescription == null ? this.description : newDescription; Map<String, Boolean> graphsConfig = this.graphsConfig; if (newGraphsConfig != null) { newGraphsConfig.forEach(graphsConfig::put); } LocalDateTime lastUpdated = (newDescription != null || newGraphsConfig != null) ? now() : this.lastUpdated; return new Term(this.code, this.name, this.type, description, lastUpdated, graphsConfig); } }
UTF-8
Java
1,713
java
Term.java
Java
[]
null
[]
package boosterm.backend.domain; import java.time.LocalDateTime; import java.util.Map; import static boosterm.backend.config.SystemConfig.now; public class Term { private String code; private String name; private String type; private String description; private LocalDateTime lastUpdated; private Map<String, Boolean> graphsConfig; public Term(String code, String name, String type, String description, LocalDateTime lastUpdated, Map<String, Boolean> graphsConfig) { this.code = code; this.name = name; this.type = type; this.description = description; this.lastUpdated = lastUpdated; this.graphsConfig = graphsConfig; } public String getCode() { return code; } public String getName() { return name; } public String getType() { return type; } public String getDescription() { return description; } public LocalDateTime getLastUpdated() { return lastUpdated; } public Map<String, Boolean> getGraphsConfig() { return graphsConfig; } public Term update(String newDescription, Map<String, Boolean> newGraphsConfig, LocalDateTime now) { String description = newDescription == null ? this.description : newDescription; Map<String, Boolean> graphsConfig = this.graphsConfig; if (newGraphsConfig != null) { newGraphsConfig.forEach(graphsConfig::put); } LocalDateTime lastUpdated = (newDescription != null || newGraphsConfig != null) ? now() : this.lastUpdated; return new Term(this.code, this.name, this.type, description, lastUpdated, graphsConfig); } }
1,713
0.66258
0.66258
68
24.191177
29.55765
138
false
false
0
0
0
0
0
0
0.676471
false
false
10
fad213da00b4fcf778d8d7c5399358a7bbd5d7cb
29,403,346,159,421
b24f2fa49a6b9417b9737604e5f3fe92147228db
/src/main/java/com/crm/miniCRM/model/PersonAddress.java
2da2258dbfdb76808ad1252dc352e679a49541ba
[]
no_license
mpaesen/miniCRM-starter
https://github.com/mpaesen/miniCRM-starter
c1d832be11928d023aa2d13702ecaa31d600af5e
29392fda47d5e18fdf1b1537a370c08e842e2994
refs/heads/master
2023-04-21T05:54:41.770000
2021-05-10T15:53:47
2021-05-10T15:53:47
364,696,384
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.crm.miniCRM.model; import com.crm.miniCRM.model.persistence.PersonAddressID; import javax.persistence.*; import java.io.Serializable; @Entity @Table(name="person_address") public class PersonAddress implements Serializable { @EmbeddedId private PersonAddressID Id; private String email; private String phone; private String mobile; private char type; public PersonAddress(){} public PersonAddress(PersonAddressID Id, String email, String phone, String mobile, char type) { this.Id = Id; this.email = email; this.phone = phone; this.mobile = mobile; this.type = type; } public PersonAddressID getId() { return Id; } public void setId(PersonAddressID personAddressID) { this.Id = personAddressID; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public char getType() { return type; } public void setType(char type) { this.type = type; } @Override public String toString() { return "PersonAddress{" + "personAddressID=" + Id + ", email='" + email + '\'' + ", phone='" + phone + '\'' + ", mobile='" + mobile + '\'' + ", type=" + type + '}'; } }
UTF-8
Java
1,692
java
PersonAddress.java
Java
[]
null
[]
package com.crm.miniCRM.model; import com.crm.miniCRM.model.persistence.PersonAddressID; import javax.persistence.*; import java.io.Serializable; @Entity @Table(name="person_address") public class PersonAddress implements Serializable { @EmbeddedId private PersonAddressID Id; private String email; private String phone; private String mobile; private char type; public PersonAddress(){} public PersonAddress(PersonAddressID Id, String email, String phone, String mobile, char type) { this.Id = Id; this.email = email; this.phone = phone; this.mobile = mobile; this.type = type; } public PersonAddressID getId() { return Id; } public void setId(PersonAddressID personAddressID) { this.Id = personAddressID; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public char getType() { return type; } public void setType(char type) { this.type = type; } @Override public String toString() { return "PersonAddress{" + "personAddressID=" + Id + ", email='" + email + '\'' + ", phone='" + phone + '\'' + ", mobile='" + mobile + '\'' + ", type=" + type + '}'; } }
1,692
0.565012
0.565012
80
20.15
18.267527
100
false
false
0
0
0
0
0
0
0.4125
false
false
10
11498e93fe9899af184e5eae2b9a03dd604f1c44
1,949,915,191,756
309f852a152a35285c4eb6aa9d8c75b90212bb1a
/leetcode/medium/PathSum2.java
44c22f457e0c8f9bafc62e7d7c12925bb53afe52
[]
no_license
ashwin244/Leetcode
https://github.com/ashwin244/Leetcode
94efca3709c1a0888f447c617a4d966f821d0370
e171f835cf8cacdcb221f5b2f18c2f0d67cb6c87
refs/heads/master
2020-04-16T02:12:06.268000
2016-09-26T05:35:32
2016-09-26T05:35:32
64,622,316
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package leetcode.medium; /* Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. For example: Given the below binary tree and sum = 22, 5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1 return [ [5,4,11,2], [5,8,4,5] ] */ import java.util.*; public class PathSum2 { public List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer>> result = new ArrayList<>(); List<Integer> list = new ArrayList<>(); path(result, list, root, sum); return result; } public void path(List<List<Integer>> result, List<Integer> list, TreeNode root, int sum) { if(root == null) { return; } list.add(root.val); if(root.left == null && root.right == null && sum == root.val) { result.add(new ArrayList<>(list)); } else { path(result, list, root.left, sum - root.val); path(result, list, root.right, sum - root.val); } list.remove(list.size() - 1); } }
UTF-8
Java
1,148
java
PathSum2.java
Java
[]
null
[]
package leetcode.medium; /* Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. For example: Given the below binary tree and sum = 22, 5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1 return [ [5,4,11,2], [5,8,4,5] ] */ import java.util.*; public class PathSum2 { public List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer>> result = new ArrayList<>(); List<Integer> list = new ArrayList<>(); path(result, list, root, sum); return result; } public void path(List<List<Integer>> result, List<Integer> list, TreeNode root, int sum) { if(root == null) { return; } list.add(root.val); if(root.left == null && root.right == null && sum == root.val) { result.add(new ArrayList<>(list)); } else { path(result, list, root.left, sum - root.val); path(result, list, root.right, sum - root.val); } list.remove(list.size() - 1); } }
1,148
0.512195
0.490418
49
21.428572
22.566004
94
false
false
0
0
0
0
0
0
1.081633
false
false
10
b6f6657501b72addd8735759e0d0b6a63b34bea5
5,145,370,853,030
29b42fa0c872616802b66b941f7478fe67a2ab69
/IntegerToRoman12/Solution.java
4c43ce2ef4d5d38a58c37ac8a416a63f14a207d6
[]
no_license
ppulse/LeetcodeWithJava
https://github.com/ppulse/LeetcodeWithJava
f316968d96e388edfcb73c9e9c42ee6810ce771a
ce72c93b2891362402299bb492a43c1d059b72e3
refs/heads/master
2021-01-17T18:01:55.263000
2016-12-02T16:21:37
2016-12-02T16:21:37
70,925,278
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Solution { public String intToRoman(int num) { if (num < 1 || num > 3999) return ""; String[] map = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; StringBuilder sb = new StringBuilder(); int[] divisor = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; int idx = 0; int mapSize = map.length; while (idx < mapSize) { int cnt = num / divisor[idx]; num %= divisor[idx]; for (int i = 0; i < cnt; i++) sb.append(map[idx]); idx++; } return sb.toString(); } }
UTF-8
Java
706
java
Solution.java
Java
[]
null
[]
public class Solution { public String intToRoman(int num) { if (num < 1 || num > 3999) return ""; String[] map = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; StringBuilder sb = new StringBuilder(); int[] divisor = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; int idx = 0; int mapSize = map.length; while (idx < mapSize) { int cnt = num / divisor[idx]; num %= divisor[idx]; for (int i = 0; i < cnt; i++) sb.append(map[idx]); idx++; } return sb.toString(); } }
706
0.399433
0.349858
24
28.458334
21.996172
95
false
false
0
0
0
0
0
0
1.625
false
false
10
38343e44fa420137fc9a1a2a838026a0077b0b60
15,384,572,903,085
fb91e9f09b631ad18f8785c6481039f6a9083e1d
/src/main/java/cn/smallyoung/oa/entity/SysOperationLog.java
96d39e5e6a0be9280c459f1e9274594d224de2d5
[]
no_license
yjiace/oa
https://github.com/yjiace/oa
49a5b345b68f13d5b92915d55df025e30ca7d3eb
f65a77128bc3c491ebfb930d065d77e56b5f4fcf
refs/heads/master
2023-04-05T01:45:10.894000
2021-04-13T12:42:14
2021-04-13T12:42:14
307,349,371
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.smallyoung.oa.entity; import com.fasterxml.jackson.annotation.JsonFormat; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Getter; import lombok.Setter; import org.springframework.data.annotation.CreatedBy; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import javax.persistence.*; import java.io.Serializable; import java.time.LocalDateTime; /** * 系统操作日志 * * @author smallyoung * @data 2020/11/4 */ @Getter @Setter @Entity @ApiModel("系统操作日志") @Table(name = "t_sys_operation_log") @EntityListeners({AuditingEntityListener.class}) public class SysOperationLog implements Serializable { private static final long serialVersionUID = 2415594410963135575L; @Id @Column(name = "id" ) @ApiModelProperty(notes = "主键ID") @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; /** * 操作人 */ @CreatedBy @Column(name = "username" ) @ApiModelProperty(notes = "操作人") private String username; /** * 操作模块 */ @Column(name = "module" ) @ApiModelProperty(notes = "操作模块") private String module; /** * 操作类型 */ @Column(name = "method" ) @ApiModelProperty(notes = "操作类型") private String method; /** * 请求参数 */ @Column(name = "params" ) @ApiModelProperty(notes = "请求参数") private String params; @Column(name = "package_and_method" ) @ApiModelProperty(notes = "包路径和方法名") private String packageAndMethod; /** * 操作前的数据 */ @Column(name = "before_data" ) @ApiModelProperty(notes = "操作前的数据") private String beforeData; /** * 操作后的数据 */ @Column(name = "after_data" ) @ApiModelProperty(notes = "操作后的数据") private String afterData; /** * 说明 */ @Column(name = "content" ) @ApiModelProperty(notes = "说明") private String content; /** * 开始时间 */ @Column(name = "start_time" ) @ApiModelProperty(notes = "开始时间") private LocalDateTime startTime; /** * 结束时间 */ @Column(name = "end_time" ) @ApiModelProperty(notes = "结束时间") private LocalDateTime endTime; /** * 操作状态 */ @Column(name = "result_status" ) @ApiModelProperty(notes = "操作状态") private String resultStatus; /** * 操作结果 */ @Column(name = "result_msg" ) @ApiModelProperty(notes = "操作结果") private String resultMsg; }
UTF-8
Java
2,702
java
SysOperationLog.java
Java
[ { "context": "a.time.LocalDateTime;\n\n/**\n * 系统操作日志\n *\n * @author smallyoung\n * @data 2020/11/4\n */\n@Getter\n@Setter\n@Entity\n@A", "end": 476, "score": 0.9996949434280396, "start": 466, "tag": "USERNAME", "value": "smallyoung" } ]
null
[]
package cn.smallyoung.oa.entity; import com.fasterxml.jackson.annotation.JsonFormat; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Getter; import lombok.Setter; import org.springframework.data.annotation.CreatedBy; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import javax.persistence.*; import java.io.Serializable; import java.time.LocalDateTime; /** * 系统操作日志 * * @author smallyoung * @data 2020/11/4 */ @Getter @Setter @Entity @ApiModel("系统操作日志") @Table(name = "t_sys_operation_log") @EntityListeners({AuditingEntityListener.class}) public class SysOperationLog implements Serializable { private static final long serialVersionUID = 2415594410963135575L; @Id @Column(name = "id" ) @ApiModelProperty(notes = "主键ID") @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; /** * 操作人 */ @CreatedBy @Column(name = "username" ) @ApiModelProperty(notes = "操作人") private String username; /** * 操作模块 */ @Column(name = "module" ) @ApiModelProperty(notes = "操作模块") private String module; /** * 操作类型 */ @Column(name = "method" ) @ApiModelProperty(notes = "操作类型") private String method; /** * 请求参数 */ @Column(name = "params" ) @ApiModelProperty(notes = "请求参数") private String params; @Column(name = "package_and_method" ) @ApiModelProperty(notes = "包路径和方法名") private String packageAndMethod; /** * 操作前的数据 */ @Column(name = "before_data" ) @ApiModelProperty(notes = "操作前的数据") private String beforeData; /** * 操作后的数据 */ @Column(name = "after_data" ) @ApiModelProperty(notes = "操作后的数据") private String afterData; /** * 说明 */ @Column(name = "content" ) @ApiModelProperty(notes = "说明") private String content; /** * 开始时间 */ @Column(name = "start_time" ) @ApiModelProperty(notes = "开始时间") private LocalDateTime startTime; /** * 结束时间 */ @Column(name = "end_time" ) @ApiModelProperty(notes = "结束时间") private LocalDateTime endTime; /** * 操作状态 */ @Column(name = "result_status" ) @ApiModelProperty(notes = "操作状态") private String resultStatus; /** * 操作结果 */ @Column(name = "result_msg" ) @ApiModelProperty(notes = "操作结果") private String resultMsg; }
2,702
0.629839
0.619355
119
19.82353
16.783169
74
false
false
0
0
0
0
0
0
0.210084
false
false
10
62fd5f56b8cdcbbd19ed5db6498c0ddfcbc12507
8,899,172,288,177
c77a385be624f8913a4824d0d0714aff7e182e93
/tt/DS_practice/src/array/UserNameAssignmentEX_ArrayList.java
e08233b08f48864ea99aa0be463a4545efa4e0f5
[]
no_license
Roushan45/pythontask
https://github.com/Roushan45/pythontask
f5a4fe32715335a3edc425ffce27d13229ed73cc
8a45f5a33583ac5e1f49a2d960123647dd6c2aa6
refs/heads/master
2021-09-12T18:11:02.163000
2018-04-19T15:39:18
2018-04-19T15:39:18
116,141,378
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package array; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Scanner; public class UserNameAssignmentEX_ArrayList { public static void main(String[] args) throws FileNotFoundException { //ArrayList that will contains student object ArrayList<Student> stuList = new ArrayList<>(); int id ; String name; int age=0; Scanner scan = new Scanner(new File("C:/Users/Ashmit/student.txt")); while(scan.hasNext()){ //reading attribute from file one by one id=scan.nextInt(); name=scan.next(); age = scan.nextInt(); //creating bew student Student newStudent = new Student(); //assigning the attribute id, name, age newStudent.id=id; newStudent.name=name; newStudent.age=age; //adding student to arraylist stuList.add(newStudent); } //closing the scanner resource scan.close(); //reading stored student from array list for(Student stu : stuList){ //validating stu age // less than 20 if(stu.age<20){ System.out.println("Student ID = "+stu.id); System.out.println("Student Name = "+stu.name); System.out.println("--------------------------"); } } } }
UTF-8
Java
1,231
java
UserNameAssignmentEX_ArrayList.java
Java
[ { "context": "\r\n\t\tScanner scan = new Scanner(new File(\"C:/Users/Ashmit/student.txt\"));\r\n\t\twhile(scan.hasNext()){\r\n\t\t\t//r", "end": 454, "score": 0.6912066340446472, "start": 448, "tag": "NAME", "value": "Ashmit" }, { "context": "me, age\r\n\t\t\tnewStudent.id=id;\r\n\t\t\tnewStudent.name=name;\r\n\t\t\tnewStudent.age=age;\r\n\t\t\t//adding student to ", "end": 770, "score": 0.5120775699615479, "start": 766, "tag": "NAME", "value": "name" } ]
null
[]
package array; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Scanner; public class UserNameAssignmentEX_ArrayList { public static void main(String[] args) throws FileNotFoundException { //ArrayList that will contains student object ArrayList<Student> stuList = new ArrayList<>(); int id ; String name; int age=0; Scanner scan = new Scanner(new File("C:/Users/Ashmit/student.txt")); while(scan.hasNext()){ //reading attribute from file one by one id=scan.nextInt(); name=scan.next(); age = scan.nextInt(); //creating bew student Student newStudent = new Student(); //assigning the attribute id, name, age newStudent.id=id; newStudent.name=name; newStudent.age=age; //adding student to arraylist stuList.add(newStudent); } //closing the scanner resource scan.close(); //reading stored student from array list for(Student stu : stuList){ //validating stu age // less than 20 if(stu.age<20){ System.out.println("Student ID = "+stu.id); System.out.println("Student Name = "+stu.name); System.out.println("--------------------------"); } } } }
1,231
0.653128
0.649066
45
25.355556
18.56419
70
false
false
0
0
0
0
0
0
2.422222
false
false
10
e01adb911d2c1d7360045eddeb332ea57a059f68
8,899,172,290,475
06b51f67a5a040c8d5dcb48662b6cc2099d0a39e
/backends/Springboot/src/main/java/org/arlevin/metrix/MetrixApplication.java
fc6b11c607b1fd805e2d4548d4df93ced53c26aa
[]
no_license
arl505/metrix
https://github.com/arl505/metrix
2cd1721f908bd2369429739bd97c459777c612c1
208fa75cff8bfa7d5bb267207b015bf08dcc508a
refs/heads/master
2020-06-14T22:06:32.792000
2019-09-04T02:22:51
2019-09-04T02:22:51
195,138,552
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.arlevin.metrix; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MetrixApplication { public static void main(String[] args) { SpringApplication.run(MetrixApplication.class, args); } }
UTF-8
Java
313
java
MetrixApplication.java
Java
[]
null
[]
package org.arlevin.metrix; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MetrixApplication { public static void main(String[] args) { SpringApplication.run(MetrixApplication.class, args); } }
313
0.814696
0.814696
12
25.166666
23.776155
68
false
false
0
0
0
0
0
0
0.416667
false
false
10
8c39a1b0fd2ed33fd74faf7df3b2655d5f05da8b
11,948,599,029,423
3813ad7ebbb49ccc089a7b7631eb6ada84c880e7
/src/Schedule/Interface/InterfaceGraphique.java
fb94247678288aad0a710dec00285b1b6eefe36b
[]
no_license
apozel/Schedule-Management
https://github.com/apozel/Schedule-Management
f83f9d40ba1beb3116b633d08b888d1787ca08e4
93597cd5802423aa3480a021a07004c99fa24385
refs/heads/master
2022-12-28T15:37:10.947000
2020-04-03T17:00:08
2020-04-03T17:00:08
208,753,357
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Schedule.Interface; import static javax.swing.BoxLayout.X_AXIS; import static javax.swing.BoxLayout.Y_AXIS; import java.awt.BorderLayout; import java.awt.Choice; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.Random; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.border.TitledBorder; import Schedule.moteur.Simulation; import Schedule.utilities.Docteur; import Schedule.utilities.Patient; import Schedule.utilities.Position; /** * InterfaceGraphique */ public class InterfaceGraphique extends JFrame { /** * */ private static final long serialVersionUID = 1L; private Simulation resteDuProjet = new Simulation(); private optionJpanelDroite optionDroite = new optionJpanelDroite(); private affichageMap map = new affichageMap(); private Docteur docteurChoisit; public InterfaceGraphique() { // initialisation fenetre this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setLocationRelativeTo(null); this.setResizable(false); this.setSize(800, 800); this.setTitle("interface graphique"); this.setFocusable(true); this.setVisible(true); // mise en forme fenetre this.setLayout(new BorderLayout()); this.getContentPane().add(map, BorderLayout.CENTER); this.getContentPane().add(optionDroite, BorderLayout.EAST); } public static void main(String[] args) { new InterfaceGraphique(); } /** * affichageMap */ public class affichageMap extends JPanel { /** * */ private LocalDate jourChoisit = LocalDate.now(); private static final long serialVersionUID = 1L; public void paintComponent(Graphics g) { System.out.println("interfacegraphique : affichagemap : paintComponent()"); g.setColor(Color.BLACK); // On le dessine de sorte qu'il occupe toute la surface g.fillRect(0, 0, this.getWidth(), this.getHeight()); Graphics2D g2d = (Graphics2D) g; g2d.translate(0, this.getHeight() / 2); if (resteDuProjet.retourPositionRdvSelonDateDocteur(docteurChoisit, jourChoisit) != null) { g.setColor(Color.BLUE); // point de depart du docteur Position precedentPosition = docteurChoisit.getLieuDeDepart(); g.fillOval((int) precedentPosition.getX(), (int) precedentPosition.getY(), 10, 10); g.setColor(Color.WHITE);// affichage des points du trajets for (Position positionRdv : resteDuProjet.retourPositionRdvSelonDateDocteur(docteurChoisit,jourChoisit)) { System.out.println("interfaceGraphique : affichageMap : paintComponent() : " + positionRdv); g.fillOval((int) positionRdv.getX(), (int) positionRdv.getY(), 10, 10); if (precedentPosition != null) { g.drawLine((int) precedentPosition.getX(), (int) precedentPosition.getY(), (int) positionRdv.getX(), (int) positionRdv.getY()); } precedentPosition = positionRdv; } } } public void MAJdeLaMap() { this.repaint(); } public LocalDate getJourChoisit() { return jourChoisit; } public void setJourChoisit(LocalDate jourChoisit) { this.jourChoisit = jourChoisit; } } private class optionJpanelDroite extends JPanel implements ActionListener { /** * */ private static final long serialVersionUID = 1L; private int criticiteMax = 10; private JTabbedPane tabbedPane = new JTabbedPane(); private JComboBox<Docteur> choixDocteurBox = new JComboBox<Docteur>(); private JComboBox<Patient> creationNouvelleDemandePatientComboBox = new JComboBox<Patient>(); private JTextArea affichageDonnees = new JTextArea(); private JScrollPane affichageDonneesJScrollPane = new JScrollPane(affichageDonnees); private JButton selectionDateDocteurButton = new JButton("selection Date"); private JPanel affichageJPanel = new JPanel(); private LocalDate jourChoisit = LocalDate.now(); private JTextField affichageDateJLabel = new JTextField(); private JButton affichageDateJButton = new JButton("Date"); private JPanel affichageDateJPanel = new JPanel(); private JPanel ajoutJPanel = new JPanel(); private TitledBorder titreAjoutDemande; private JPanel ajoutDemandeJPanel = new JPanel(); private JLabel ajoutCriticiteDemandLabel = new JLabel("Criticite :"); private Choice ajoutCriticiteDemande = new Choice(); private JLabel ajoutDescriptionJLabel = new JLabel("Description :"); private JTextField ajoutDescriptionJTexteField = new JTextField(); private JButton confirmationCreationDemandeButton = new JButton("confirmer"); private TitledBorder titreAjoutPatient; private JPanel ajoutPatientJPanel = new JPanel(); private JLabel ajoutPatientNomJLabel = new JLabel("nom :"); private JTextField ajoutPatientNomJTextField = new JTextField(); private JLabel ajoutPatientPrenomJLabel = new JLabel("prenom :"); private JTextField ajoutPatientPrenomJTextField = new JTextField(); private JLabel ajoutPatientPositionJLabel = new JLabel("position :"); private JTextField ajoutPatientPositionJTextField = new JTextField(); private JButton confirmationCreationPatientJButton = new JButton("confirmer"); private JPanel testJPanel = new JPanel(); private TitledBorder titreTest; private JButton testPatientJButton = new JButton("Creer Patient"); private JButton testDemandeJButton = new JButton("Creer Demande"); optionJpanelDroite() { creerInterfaceGraphique(); } public void creerInterfaceGraphique() { BoxLayout boxlayout = new BoxLayout(this, BoxLayout.Y_AXIS); this.setLayout(boxlayout); BoxLayout affichageLayout = new BoxLayout(affichageJPanel, BoxLayout.Y_AXIS); affichageJPanel.setLayout(affichageLayout); BoxLayout ajoutLayout = new BoxLayout(ajoutJPanel, BoxLayout.Y_AXIS); ajoutJPanel.setLayout(ajoutLayout); titreAjoutDemande = BorderFactory.createTitledBorder("Ajout Demande"); BoxLayout ajoutLayoutDemande = new BoxLayout(ajoutDemandeJPanel, Y_AXIS); ajoutDemandeJPanel.setLayout(ajoutLayoutDemande); ajoutDemandeJPanel.setBorder(titreAjoutDemande); titreAjoutPatient = BorderFactory.createTitledBorder("Ajout Patient"); BoxLayout ajoutLayoutPatient = new BoxLayout(ajoutPatientJPanel, Y_AXIS); ajoutPatientJPanel.setLayout(ajoutLayoutPatient); ajoutPatientJPanel.setBorder(titreAjoutPatient); BoxLayout affichageDateLayout = new BoxLayout(affichageDateJPanel, X_AXIS); affichageDateJPanel.setLayout(affichageDateLayout); titreTest = BorderFactory.createTitledBorder("Test"); BoxLayout testLayout = new BoxLayout(testJPanel, Y_AXIS); testJPanel.setLayout(testLayout); testJPanel.setBorder(titreTest); MAJdesBarres(); for (int i = 0; i < criticiteMax; i++) { ajoutCriticiteDemande.add(Integer.toString(i)); } choixDocteurBox.addActionListener(this); tabbedPane.addTab("Affichage", affichageJPanel); tabbedPane.addTab("Patient", ajoutJPanel); tabbedPane.addTab("Test", testJPanel); //affichageDateJPanel.setPreferredSize(new Dimension(203,150)); affichageDateJLabel.setMaximumSize(new Dimension(340, 50)); affichageDateJPanel.add(affichageDateJLabel); affichageDateJPanel.add(affichageDateJButton); affichageDateJButton.addActionListener(this); choixDocteurBox.setMaximumSize(new Dimension(340, 50)); affichageJPanel.add(choixDocteurBox); affichageJPanel.add(affichageDateJPanel); affichageDonneesJScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); affichageJPanel.add(affichageDonneesJScrollPane); affichageJPanel.add(selectionDateDocteurButton); selectionDateDocteurButton.addActionListener(this); ajoutJPanel.add(ajoutDemandeJPanel); ajoutJPanel.add(ajoutPatientJPanel); ajoutDemandeJPanel.add(creationNouvelleDemandePatientComboBox); ajoutDemandeJPanel.add(ajoutCriticiteDemandLabel); ajoutDemandeJPanel.add(ajoutCriticiteDemande); ajoutDemandeJPanel.add(ajoutDescriptionJLabel); ajoutDemandeJPanel.add(ajoutDescriptionJTexteField); ajoutDemandeJPanel.add(confirmationCreationDemandeButton); confirmationCreationDemandeButton.addActionListener(this); ajoutPatientJPanel.add(ajoutPatientNomJLabel); ajoutPatientJPanel.add(ajoutPatientNomJTextField); ajoutPatientJPanel.add(ajoutPatientPrenomJLabel); ajoutPatientJPanel.add(ajoutPatientPrenomJTextField); ajoutPatientJPanel.add(ajoutPatientPositionJLabel); ajoutPatientJPanel.add(ajoutPatientPositionJTextField); ajoutPatientJPanel.add(confirmationCreationPatientJButton); confirmationCreationPatientJButton.addActionListener(this); testJPanel.add(testPatientJButton); testJPanel.add(testDemandeJButton); testPatientJButton.addActionListener(this); testDemandeJButton.addActionListener(this); this.add(tabbedPane); } public void MAJdesBarres() { choixDocteurBox.removeAllItems(); creationNouvelleDemandePatientComboBox.removeAllItems(); affichageDateJLabel.setText(jourChoisit.toString()); for (Docteur var : resteDuProjet.getDoc()) { choixDocteurBox.addItem(var); } for (Patient Pati : resteDuProjet.getMalades()) { creationNouvelleDemandePatientComboBox.addItem(Pati); } } public void recuperationPourDemande() { resteDuProjet.nouveauDiagnostic(Integer.parseInt(ajoutCriticiteDemande.getSelectedItem()), ajoutDescriptionJTexteField.getText(), ((Patient) creationNouvelleDemandePatientComboBox.getSelectedItem()).getIDPatient()); ajoutCriticiteDemande.select(0); ajoutDescriptionJTexteField.setText(""); MAJdesBarres(); } public void recuperationPourPatient() { try { if (ajoutPatientNomJTextField.getText() != "" && ajoutPatientPrenomJTextField.getText() != "") { int positionCarre = Integer.parseInt(ajoutPatientPositionJTextField.getText()); Position prochainePositionPatient = new Position(positionCarre, positionCarre); resteDuProjet.addPatient(new Patient(prochainePositionPatient, ajoutPatientNomJTextField.getText(), ajoutPatientPrenomJTextField.getText())); MAJdesBarres(); } else { System.out.println( "interfaceGraphique : optionJpanelDroite : recuperationPourPatient() mauvaise saisie patient"); } } catch (NumberFormatException e) { System.out.println( "interfaceGraphique : optionJpanelDroite : recuperationPourPatient() (erreur) : la position du patient entree est pas correcte"); } ajoutPatientNomJTextField.setText(""); ajoutPatientPrenomJTextField.setText(""); ajoutPatientPositionJTextField.setText(""); } public void changementDateAffichage() { DateTimeFormatter formatDate = DateTimeFormatter.ofPattern("yyyy-MM-dd"); LocalDate date = LocalDate.parse(new DatePicker().setPickedDate(), formatDate); this.jourChoisit = date; map.setJourChoisit(jourChoisit); MAJdesBarres(); } public void chargementInfoEnfonctionDateDocteur() { docteurChoisit = (Docteur) choixDocteurBox.getSelectedItem(); affichageDonnees.setText(resteDuProjet.retourStringRdvSelonDateDocteur(docteurChoisit, jourChoisit)); map.MAJdeLaMap(); System.out.println("interfaceGraphique : optionJpanelDroite : actionPerformed() : " + resteDuProjet.retourStringDesRdvSelonDocteur(docteurChoisit)); System.out.println("interfaceGraphique : optionJpanelDroite : actionPerformed() : debug : taille d'affichage Date docteur " + affichageDateJPanel.getSize() ); } public Patient nouveauxPatientAleatoire(){ String nomAleatoire = "patient " + new Random().nextInt(100); String prenomAleatoire = "test "; Position positionAleatoire = new Position(new Random().nextInt(250), new Random().nextInt(250)); return new Patient(positionAleatoire, nomAleatoire, prenomAleatoire); } public void testGraphique(ActionEvent e) { if (e.getSource() == testPatientJButton) { resteDuProjet.addPatient(nouveauxPatientAleatoire()); } else if (e.getSource() == testDemandeJButton) { Patient pat = nouveauxPatientAleatoire(); resteDuProjet.addPatient(pat); resteDuProjet.nouveauDiagnostic(new Random().nextInt(5), "maladie", pat.getIDPatient()); } MAJdesBarres(); } public void actionPerformed(ActionEvent e) { if (e.getSource() == confirmationCreationDemandeButton) { System.out.println("interfaceGraphique : optionJpanelDroite : actionPerformed() bouton demande"); recuperationPourDemande(); } else if (e.getSource() == selectionDateDocteurButton) { System.out.println( "interfaceGraphique : optionJpanelDroite : actionPerformed() : changement date ou docteur"); chargementInfoEnfonctionDateDocteur(); } else if (e.getSource() == confirmationCreationPatientJButton) { System.out.println("interfaceGraphique : optionJpanelDroite : actionPerformed() : bouton patient"); recuperationPourPatient(); } else if (e.getSource() == affichageDateJButton) { changementDateAffichage(); } else if (e.getSource() == testPatientJButton || e.getSource() == testDemandeJButton) { testGraphique(e); } } } }
UTF-8
Java
15,633
java
InterfaceGraphique.java
Java
[]
null
[]
package Schedule.Interface; import static javax.swing.BoxLayout.X_AXIS; import static javax.swing.BoxLayout.Y_AXIS; import java.awt.BorderLayout; import java.awt.Choice; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.Random; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.border.TitledBorder; import Schedule.moteur.Simulation; import Schedule.utilities.Docteur; import Schedule.utilities.Patient; import Schedule.utilities.Position; /** * InterfaceGraphique */ public class InterfaceGraphique extends JFrame { /** * */ private static final long serialVersionUID = 1L; private Simulation resteDuProjet = new Simulation(); private optionJpanelDroite optionDroite = new optionJpanelDroite(); private affichageMap map = new affichageMap(); private Docteur docteurChoisit; public InterfaceGraphique() { // initialisation fenetre this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setLocationRelativeTo(null); this.setResizable(false); this.setSize(800, 800); this.setTitle("interface graphique"); this.setFocusable(true); this.setVisible(true); // mise en forme fenetre this.setLayout(new BorderLayout()); this.getContentPane().add(map, BorderLayout.CENTER); this.getContentPane().add(optionDroite, BorderLayout.EAST); } public static void main(String[] args) { new InterfaceGraphique(); } /** * affichageMap */ public class affichageMap extends JPanel { /** * */ private LocalDate jourChoisit = LocalDate.now(); private static final long serialVersionUID = 1L; public void paintComponent(Graphics g) { System.out.println("interfacegraphique : affichagemap : paintComponent()"); g.setColor(Color.BLACK); // On le dessine de sorte qu'il occupe toute la surface g.fillRect(0, 0, this.getWidth(), this.getHeight()); Graphics2D g2d = (Graphics2D) g; g2d.translate(0, this.getHeight() / 2); if (resteDuProjet.retourPositionRdvSelonDateDocteur(docteurChoisit, jourChoisit) != null) { g.setColor(Color.BLUE); // point de depart du docteur Position precedentPosition = docteurChoisit.getLieuDeDepart(); g.fillOval((int) precedentPosition.getX(), (int) precedentPosition.getY(), 10, 10); g.setColor(Color.WHITE);// affichage des points du trajets for (Position positionRdv : resteDuProjet.retourPositionRdvSelonDateDocteur(docteurChoisit,jourChoisit)) { System.out.println("interfaceGraphique : affichageMap : paintComponent() : " + positionRdv); g.fillOval((int) positionRdv.getX(), (int) positionRdv.getY(), 10, 10); if (precedentPosition != null) { g.drawLine((int) precedentPosition.getX(), (int) precedentPosition.getY(), (int) positionRdv.getX(), (int) positionRdv.getY()); } precedentPosition = positionRdv; } } } public void MAJdeLaMap() { this.repaint(); } public LocalDate getJourChoisit() { return jourChoisit; } public void setJourChoisit(LocalDate jourChoisit) { this.jourChoisit = jourChoisit; } } private class optionJpanelDroite extends JPanel implements ActionListener { /** * */ private static final long serialVersionUID = 1L; private int criticiteMax = 10; private JTabbedPane tabbedPane = new JTabbedPane(); private JComboBox<Docteur> choixDocteurBox = new JComboBox<Docteur>(); private JComboBox<Patient> creationNouvelleDemandePatientComboBox = new JComboBox<Patient>(); private JTextArea affichageDonnees = new JTextArea(); private JScrollPane affichageDonneesJScrollPane = new JScrollPane(affichageDonnees); private JButton selectionDateDocteurButton = new JButton("selection Date"); private JPanel affichageJPanel = new JPanel(); private LocalDate jourChoisit = LocalDate.now(); private JTextField affichageDateJLabel = new JTextField(); private JButton affichageDateJButton = new JButton("Date"); private JPanel affichageDateJPanel = new JPanel(); private JPanel ajoutJPanel = new JPanel(); private TitledBorder titreAjoutDemande; private JPanel ajoutDemandeJPanel = new JPanel(); private JLabel ajoutCriticiteDemandLabel = new JLabel("Criticite :"); private Choice ajoutCriticiteDemande = new Choice(); private JLabel ajoutDescriptionJLabel = new JLabel("Description :"); private JTextField ajoutDescriptionJTexteField = new JTextField(); private JButton confirmationCreationDemandeButton = new JButton("confirmer"); private TitledBorder titreAjoutPatient; private JPanel ajoutPatientJPanel = new JPanel(); private JLabel ajoutPatientNomJLabel = new JLabel("nom :"); private JTextField ajoutPatientNomJTextField = new JTextField(); private JLabel ajoutPatientPrenomJLabel = new JLabel("prenom :"); private JTextField ajoutPatientPrenomJTextField = new JTextField(); private JLabel ajoutPatientPositionJLabel = new JLabel("position :"); private JTextField ajoutPatientPositionJTextField = new JTextField(); private JButton confirmationCreationPatientJButton = new JButton("confirmer"); private JPanel testJPanel = new JPanel(); private TitledBorder titreTest; private JButton testPatientJButton = new JButton("Creer Patient"); private JButton testDemandeJButton = new JButton("Creer Demande"); optionJpanelDroite() { creerInterfaceGraphique(); } public void creerInterfaceGraphique() { BoxLayout boxlayout = new BoxLayout(this, BoxLayout.Y_AXIS); this.setLayout(boxlayout); BoxLayout affichageLayout = new BoxLayout(affichageJPanel, BoxLayout.Y_AXIS); affichageJPanel.setLayout(affichageLayout); BoxLayout ajoutLayout = new BoxLayout(ajoutJPanel, BoxLayout.Y_AXIS); ajoutJPanel.setLayout(ajoutLayout); titreAjoutDemande = BorderFactory.createTitledBorder("Ajout Demande"); BoxLayout ajoutLayoutDemande = new BoxLayout(ajoutDemandeJPanel, Y_AXIS); ajoutDemandeJPanel.setLayout(ajoutLayoutDemande); ajoutDemandeJPanel.setBorder(titreAjoutDemande); titreAjoutPatient = BorderFactory.createTitledBorder("Ajout Patient"); BoxLayout ajoutLayoutPatient = new BoxLayout(ajoutPatientJPanel, Y_AXIS); ajoutPatientJPanel.setLayout(ajoutLayoutPatient); ajoutPatientJPanel.setBorder(titreAjoutPatient); BoxLayout affichageDateLayout = new BoxLayout(affichageDateJPanel, X_AXIS); affichageDateJPanel.setLayout(affichageDateLayout); titreTest = BorderFactory.createTitledBorder("Test"); BoxLayout testLayout = new BoxLayout(testJPanel, Y_AXIS); testJPanel.setLayout(testLayout); testJPanel.setBorder(titreTest); MAJdesBarres(); for (int i = 0; i < criticiteMax; i++) { ajoutCriticiteDemande.add(Integer.toString(i)); } choixDocteurBox.addActionListener(this); tabbedPane.addTab("Affichage", affichageJPanel); tabbedPane.addTab("Patient", ajoutJPanel); tabbedPane.addTab("Test", testJPanel); //affichageDateJPanel.setPreferredSize(new Dimension(203,150)); affichageDateJLabel.setMaximumSize(new Dimension(340, 50)); affichageDateJPanel.add(affichageDateJLabel); affichageDateJPanel.add(affichageDateJButton); affichageDateJButton.addActionListener(this); choixDocteurBox.setMaximumSize(new Dimension(340, 50)); affichageJPanel.add(choixDocteurBox); affichageJPanel.add(affichageDateJPanel); affichageDonneesJScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); affichageJPanel.add(affichageDonneesJScrollPane); affichageJPanel.add(selectionDateDocteurButton); selectionDateDocteurButton.addActionListener(this); ajoutJPanel.add(ajoutDemandeJPanel); ajoutJPanel.add(ajoutPatientJPanel); ajoutDemandeJPanel.add(creationNouvelleDemandePatientComboBox); ajoutDemandeJPanel.add(ajoutCriticiteDemandLabel); ajoutDemandeJPanel.add(ajoutCriticiteDemande); ajoutDemandeJPanel.add(ajoutDescriptionJLabel); ajoutDemandeJPanel.add(ajoutDescriptionJTexteField); ajoutDemandeJPanel.add(confirmationCreationDemandeButton); confirmationCreationDemandeButton.addActionListener(this); ajoutPatientJPanel.add(ajoutPatientNomJLabel); ajoutPatientJPanel.add(ajoutPatientNomJTextField); ajoutPatientJPanel.add(ajoutPatientPrenomJLabel); ajoutPatientJPanel.add(ajoutPatientPrenomJTextField); ajoutPatientJPanel.add(ajoutPatientPositionJLabel); ajoutPatientJPanel.add(ajoutPatientPositionJTextField); ajoutPatientJPanel.add(confirmationCreationPatientJButton); confirmationCreationPatientJButton.addActionListener(this); testJPanel.add(testPatientJButton); testJPanel.add(testDemandeJButton); testPatientJButton.addActionListener(this); testDemandeJButton.addActionListener(this); this.add(tabbedPane); } public void MAJdesBarres() { choixDocteurBox.removeAllItems(); creationNouvelleDemandePatientComboBox.removeAllItems(); affichageDateJLabel.setText(jourChoisit.toString()); for (Docteur var : resteDuProjet.getDoc()) { choixDocteurBox.addItem(var); } for (Patient Pati : resteDuProjet.getMalades()) { creationNouvelleDemandePatientComboBox.addItem(Pati); } } public void recuperationPourDemande() { resteDuProjet.nouveauDiagnostic(Integer.parseInt(ajoutCriticiteDemande.getSelectedItem()), ajoutDescriptionJTexteField.getText(), ((Patient) creationNouvelleDemandePatientComboBox.getSelectedItem()).getIDPatient()); ajoutCriticiteDemande.select(0); ajoutDescriptionJTexteField.setText(""); MAJdesBarres(); } public void recuperationPourPatient() { try { if (ajoutPatientNomJTextField.getText() != "" && ajoutPatientPrenomJTextField.getText() != "") { int positionCarre = Integer.parseInt(ajoutPatientPositionJTextField.getText()); Position prochainePositionPatient = new Position(positionCarre, positionCarre); resteDuProjet.addPatient(new Patient(prochainePositionPatient, ajoutPatientNomJTextField.getText(), ajoutPatientPrenomJTextField.getText())); MAJdesBarres(); } else { System.out.println( "interfaceGraphique : optionJpanelDroite : recuperationPourPatient() mauvaise saisie patient"); } } catch (NumberFormatException e) { System.out.println( "interfaceGraphique : optionJpanelDroite : recuperationPourPatient() (erreur) : la position du patient entree est pas correcte"); } ajoutPatientNomJTextField.setText(""); ajoutPatientPrenomJTextField.setText(""); ajoutPatientPositionJTextField.setText(""); } public void changementDateAffichage() { DateTimeFormatter formatDate = DateTimeFormatter.ofPattern("yyyy-MM-dd"); LocalDate date = LocalDate.parse(new DatePicker().setPickedDate(), formatDate); this.jourChoisit = date; map.setJourChoisit(jourChoisit); MAJdesBarres(); } public void chargementInfoEnfonctionDateDocteur() { docteurChoisit = (Docteur) choixDocteurBox.getSelectedItem(); affichageDonnees.setText(resteDuProjet.retourStringRdvSelonDateDocteur(docteurChoisit, jourChoisit)); map.MAJdeLaMap(); System.out.println("interfaceGraphique : optionJpanelDroite : actionPerformed() : " + resteDuProjet.retourStringDesRdvSelonDocteur(docteurChoisit)); System.out.println("interfaceGraphique : optionJpanelDroite : actionPerformed() : debug : taille d'affichage Date docteur " + affichageDateJPanel.getSize() ); } public Patient nouveauxPatientAleatoire(){ String nomAleatoire = "patient " + new Random().nextInt(100); String prenomAleatoire = "test "; Position positionAleatoire = new Position(new Random().nextInt(250), new Random().nextInt(250)); return new Patient(positionAleatoire, nomAleatoire, prenomAleatoire); } public void testGraphique(ActionEvent e) { if (e.getSource() == testPatientJButton) { resteDuProjet.addPatient(nouveauxPatientAleatoire()); } else if (e.getSource() == testDemandeJButton) { Patient pat = nouveauxPatientAleatoire(); resteDuProjet.addPatient(pat); resteDuProjet.nouveauDiagnostic(new Random().nextInt(5), "maladie", pat.getIDPatient()); } MAJdesBarres(); } public void actionPerformed(ActionEvent e) { if (e.getSource() == confirmationCreationDemandeButton) { System.out.println("interfaceGraphique : optionJpanelDroite : actionPerformed() bouton demande"); recuperationPourDemande(); } else if (e.getSource() == selectionDateDocteurButton) { System.out.println( "interfaceGraphique : optionJpanelDroite : actionPerformed() : changement date ou docteur"); chargementInfoEnfonctionDateDocteur(); } else if (e.getSource() == confirmationCreationPatientJButton) { System.out.println("interfaceGraphique : optionJpanelDroite : actionPerformed() : bouton patient"); recuperationPourPatient(); } else if (e.getSource() == affichageDateJButton) { changementDateAffichage(); } else if (e.getSource() == testPatientJButton || e.getSource() == testDemandeJButton) { testGraphique(e); } } } }
15,633
0.655792
0.65221
372
41.026882
32.709694
171
false
false
0
0
0
0
0
0
0.674731
false
false
10
dafafbde8e7dd5f7deac5e35863416abbed9800e
2,860,448,286,422
02b7fafb7ff9ea986ef67498c783b5d279b46a5b
/spring-boot-quartz/src/main/java/com/example/domain/QuartzEntity.java
77d68f6f5974a7ffdeccfffe409faff4969bd574
[]
no_license
sz-liuxiang/microservice
https://github.com/sz-liuxiang/microservice
59a9b93e0fba0c625a3fb650437ba158ed8b4f14
73e287357e70828c16e69f7123e2e91369202a37
refs/heads/master
2018-10-20T12:28:49.822000
2018-10-12T14:49:28
2018-10-12T14:49:28
135,397,851
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.domain; import lombok.Data; @Data public class QuartzEntity{ private String jobName;//任务名称 private String jobGroup;//任务分组 private String description;//任务描述 private String jobClassName;//执行类 private String cronExpression;//执行时间 private String triggerName;//执行时间 private String triggerState;//任务状态 }
UTF-8
Java
381
java
QuartzEntity.java
Java
[]
null
[]
package com.example.domain; import lombok.Data; @Data public class QuartzEntity{ private String jobName;//任务名称 private String jobGroup;//任务分组 private String description;//任务描述 private String jobClassName;//执行类 private String cronExpression;//执行时间 private String triggerName;//执行时间 private String triggerState;//任务状态 }
381
0.792049
0.792049
14
22.357143
13.931501
37
false
false
0
0
0
0
0
0
1.142857
false
false
10
31c23e4531c1a72e5cec3a56d5beb80454a84d7f
9,560,597,247,661
a45549d83cdae282e87993f5afba1ad9737af18e
/src/test/java/tests/day15/C01_DriverClassKullanımı.java
f8b65bdacf05e9eb98e4c6a7d706228240e8b736
[]
no_license
SedaDemirhan/POM
https://github.com/SedaDemirhan/POM
48749102067967df08131a676ed8b83df88eefff
bad704e66639f2cb3a2fcf8de193cdbc8074f71e
refs/heads/master
2023-09-04T17:00:35.310000
2021-11-16T18:31:20
2021-11-16T18:31:20
428,771,435
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package tests.day15; import org.testng.annotations.Test; import utilities.ConfigReader; import utilities.Driver; public class C01_DriverClassKullanımı { @Test public void test(){ Driver.getDriver().get(ConfigReader.getProperty("amazonUrl")); Driver.getDriver().get(ConfigReader.getProperty("facebookUrl")); Driver.getDriver().get(ConfigReader.getProperty("CHUrl")); // Driver driver=new Driver(); //driver class'ından obje üretilmesin istediğimiz için driver class'ı SINGELTON yapıyoruz //bunun için default constructor yerine parametresiz bir constructor oluşturup access modifer'ı //private seciyoruz Driver.closeDriver(); } }
UTF-8
Java
721
java
C01_DriverClassKullanımı.java
Java
[]
null
[]
package tests.day15; import org.testng.annotations.Test; import utilities.ConfigReader; import utilities.Driver; public class C01_DriverClassKullanımı { @Test public void test(){ Driver.getDriver().get(ConfigReader.getProperty("amazonUrl")); Driver.getDriver().get(ConfigReader.getProperty("facebookUrl")); Driver.getDriver().get(ConfigReader.getProperty("CHUrl")); // Driver driver=new Driver(); //driver class'ından obje üretilmesin istediğimiz için driver class'ı SINGELTON yapıyoruz //bunun için default constructor yerine parametresiz bir constructor oluşturup access modifer'ı //private seciyoruz Driver.closeDriver(); } }
721
0.714085
0.708451
23
29.869566
31.022158
103
false
false
0
0
0
0
0
0
0.391304
false
false
10
95b9aa966ff55747815efaf6fd84560d2691c62a
31,061,203,550,232
6f00dfad74aab3b249b16824ec71a380c5e77796
/product/src/main/java/pl/trosko/product/service/ProductService.java
52afa8e6a5bdd45e8a81f4264ab23da1ff6d8436
[]
no_license
DanielTrosko/test
https://github.com/DanielTrosko/test
af9d567a1c7fe2ea79248c605e2a548e4d8ab34d
d3fc1a689c3b671ed7906240f82564c25ea1b81b
refs/heads/master
2023-08-27T06:16:20.563000
2021-11-07T22:19:12
2021-11-07T22:19:12
425,629,240
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pl.trosko.product.service; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import pl.trosko.product.entity.Product; import pl.trosko.product.respository.ProductRepository; import java.util.List; @Service @RequiredArgsConstructor public class ProductService { private final ProductRepository productRepository; public List<Product> getAll(List<Long> ids) { return productRepository.findByIds(ids); } public Product createProduct(Long creditId, Product product) { product.setCreditId(creditId); return productRepository.save(product); } }
UTF-8
Java
633
java
ProductService.java
Java
[]
null
[]
package pl.trosko.product.service; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import pl.trosko.product.entity.Product; import pl.trosko.product.respository.ProductRepository; import java.util.List; @Service @RequiredArgsConstructor public class ProductService { private final ProductRepository productRepository; public List<Product> getAll(List<Long> ids) { return productRepository.findByIds(ids); } public Product createProduct(Long creditId, Product product) { product.setCreditId(creditId); return productRepository.save(product); } }
633
0.770932
0.770932
24
25.375
21.921854
66
false
false
0
0
0
0
0
0
0.458333
false
false
10
0d6843928de28d279b0cd9614c7f6abd79f0a252
24,721,831,771,961
54a9b4168ae3f40e39b0d7c4ef9a0c8fca86fcc4
/src/main/SerializeAndDeserializeBinaryTree.java
95025a093e4258d6009c4201aecb30ed3bf92338
[]
no_license
SicongLiu/JavaCodingPractice
https://github.com/SicongLiu/JavaCodingPractice
3178efe6991475a948a606735eeb90f2761b5288
f9eaba4c5274217751c64527a68c541ac1bffbec
refs/heads/master
2020-02-25T23:46:14.302000
2019-10-26T18:18:50
2019-10-26T18:18:50
100,679,149
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package main; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Queue; import javax.swing.tree.TreeNode; /** LeetCode 297, Level Hard Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment. Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure. Example: You may serialize the following tree: 1 / \ 2 3 / \ 4 5 as "[1,2,3,null,null,4,5]" Clarification: The above format is the same as how LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself. * */ /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ //Your Codec object will be instantiated and called as such: //Codec codec = new Codec(); //codec.deserialize(codec.serialize(root)); // Reference: https://www.cnblogs.com/yrbbest/p/5047035.html // use recursion public class SerializeAndDeserializeBinaryTree { private final String delimiter = ","; private final String nullnode = "null"; // Encodes a tree to a single string. // recursion public String serialize(TreeNode root) { if(root == null) return null; StringBuilder sb = new StringBuilder(); serialize(root, sb); return sb.toString(); } public void serialize(TreeNode node, StringBuilder sb) { if(node == null) { sb.append(nullnode).append(delimiter); } else { sb.append(node.val).append(delimiter); serialize(node.left, sb); serialize(node.right, sb); } } // Decodes your encoded data to tree. // recursion public TreeNode deserialize(String data) { if(data == null) return null; String[] str = data.split(delimiter); Queue<String> q = new LinkedList<String>(); Collections.addAll(q, str); return deserialize(q); } public TreeNode deserialize(Queue<String> q) { if(q.isEmpty()) return null; String cur = q.poll(); if(cur.equals(nullnode)) return null; TreeNode node = new TreeNode(Integer.valueOf(cur)); node.left = deserialize(q); node.right = deserialize(q); return node; } }
UTF-8
Java
2,843
java
SerializeAndDeserializeBinaryTree.java
Java
[ { "context": "e(root));\n\n\n// Reference: https://www.cnblogs.com/yrbbest/p/5047035.html\n// use recursion\npublic class Seri", "end": 1473, "score": 0.9996928572654724, "start": 1466, "tag": "USERNAME", "value": "yrbbest" } ]
null
[]
package main; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Queue; import javax.swing.tree.TreeNode; /** LeetCode 297, Level Hard Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment. Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure. Example: You may serialize the following tree: 1 / \ 2 3 / \ 4 5 as "[1,2,3,null,null,4,5]" Clarification: The above format is the same as how LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself. * */ /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ //Your Codec object will be instantiated and called as such: //Codec codec = new Codec(); //codec.deserialize(codec.serialize(root)); // Reference: https://www.cnblogs.com/yrbbest/p/5047035.html // use recursion public class SerializeAndDeserializeBinaryTree { private final String delimiter = ","; private final String nullnode = "null"; // Encodes a tree to a single string. // recursion public String serialize(TreeNode root) { if(root == null) return null; StringBuilder sb = new StringBuilder(); serialize(root, sb); return sb.toString(); } public void serialize(TreeNode node, StringBuilder sb) { if(node == null) { sb.append(nullnode).append(delimiter); } else { sb.append(node.val).append(delimiter); serialize(node.left, sb); serialize(node.right, sb); } } // Decodes your encoded data to tree. // recursion public TreeNode deserialize(String data) { if(data == null) return null; String[] str = data.split(delimiter); Queue<String> q = new LinkedList<String>(); Collections.addAll(q, str); return deserialize(q); } public TreeNode deserialize(Queue<String> q) { if(q.isEmpty()) return null; String cur = q.poll(); if(cur.equals(nullnode)) return null; TreeNode node = new TreeNode(Integer.valueOf(cur)); node.left = deserialize(q); node.right = deserialize(q); return node; } }
2,843
0.668308
0.661273
110
24.845455
25.976278
120
false
false
0
0
0
0
0
0
1.127273
false
false
10
61d2b894762fc02f1e1dc5f8f42d3fa02219e6e8
21,955,872,848,858
a208762ff7f139a822409885e980e03e39517ecb
/src/_03_array_method/excercise/Bt5FindMinElement.java
499989877881eac1ea0b7ac3917d83a75d3f0ca7
[]
no_license
Hanguyen2332/C0421G1_NguyenThiThanhHa_Module2
https://github.com/Hanguyen2332/C0421G1_NguyenThiThanhHa_Module2
539c211c9c4a6c06aabad415e862596261f93b5c
4d7e0f1308c7ef14e334c7fc399bfc2833b619a0
refs/heads/master
2023-06-12T07:38:36.023000
2021-07-09T09:16:45
2021-07-09T09:16:45
372,703,828
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package _03_array_method.excercise; import java.util.Arrays; import java.util.Scanner; public class Bt5FindMinElement { static Scanner input = new Scanner(System.in); public static void main(String[] args) { findMinElement(); } private static void findMinElement() { System.out.println("Enter length of array: "); int length = input.nextInt(); int[] arr = new int[length]; int minElement = arr[0]; int indexMin = 0; for (int i = 0; i < arr.length; i++) { System.out.printf("Enter element %d ", i); arr[i] = input.nextInt(); if (arr[i] < minElement) { minElement = arr[i]; indexMin = i; } } System.out.println("arr = " + Arrays.toString(arr)); System.out.printf("MIN element is %d at index %d ", minElement, indexMin); } }
UTF-8
Java
906
java
Bt5FindMinElement.java
Java
[]
null
[]
package _03_array_method.excercise; import java.util.Arrays; import java.util.Scanner; public class Bt5FindMinElement { static Scanner input = new Scanner(System.in); public static void main(String[] args) { findMinElement(); } private static void findMinElement() { System.out.println("Enter length of array: "); int length = input.nextInt(); int[] arr = new int[length]; int minElement = arr[0]; int indexMin = 0; for (int i = 0; i < arr.length; i++) { System.out.printf("Enter element %d ", i); arr[i] = input.nextInt(); if (arr[i] < minElement) { minElement = arr[i]; indexMin = i; } } System.out.println("arr = " + Arrays.toString(arr)); System.out.printf("MIN element is %d at index %d ", minElement, indexMin); } }
906
0.556291
0.549669
30
29.200001
20.439178
82
false
false
0
0
0
0
0
0
0.7
false
false
10
989f6f3d4ee20a45717bce0f05783093794f901f
17,540,646,471,148
eb9f655206c43c12b497c667ba56a0d358b6bc3a
/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createGetterOrSetter/beforeNoSetterForStaticFinal.java
02799cea8b86e76da231d8f55b28a9cb0b54e86d
[ "Apache-2.0" ]
permissive
JetBrains/intellij-community
https://github.com/JetBrains/intellij-community
2ed226e200ecc17c037dcddd4a006de56cd43941
05dbd4575d01a213f3f4d69aa4968473f2536142
refs/heads/master
2023-09-03T17:06:37.560000
2023-09-03T11:51:00
2023-09-03T12:12:27
2,489,216
16,288
6,635
Apache-2.0
false
2023-09-12T07:41:58
2011-09-30T13:33:05
2023-09-12T03:37:30
2023-09-12T06:46:46
4,523,919
15,754
4,972
237
null
false
false
// "Create setter for 's'" "false" class A { private final static String <caret>s; }
UTF-8
Java
86
java
beforeNoSetterForStaticFinal.java
Java
[]
null
[]
// "Create setter for 's'" "false" class A { private final static String <caret>s; }
86
0.662791
0.662791
4
20.75
16.0993
39
false
false
0
0
0
0
0
0
0.25
false
false
10
c1430304ed3fd2c4db729cd457250e16c5f925ee
29,386,166,277,102
c71af56951d1c661a5819db72da1caccd9130df2
/java/BigNumbers2/src/token/TokenTypeConverter.java
0b4008eba233f4ed251e33d8d73d89b19de1c093
[]
no_license
adrianpoplesanu/personal-work
https://github.com/adrianpoplesanu/personal-work
2940a0dc4e4e27e0cc467875bae3fdea27dd0d31
adc289ecb72c1c6f98582f3ea9ad4bf2e8e08d29
refs/heads/master
2023-08-23T06:56:49.363000
2023-08-21T17:20:51
2023-08-21T17:20:51
109,451,981
0
1
null
false
2022-10-07T04:53:24
2017-11-03T23:36:21
2022-01-10T23:21:52
2022-10-07T04:53:24
314,531
0
1
1
Python
false
false
package token; import java.util.HashMap; public class TokenTypeConverter { private static HashMap<TokenType, String> tokenTypeMap = new HashMap<TokenType, String>() { { put(TokenType.UNDEFINED, "UNDEFINED"); put(TokenType.SUM, "SUM"); put(TokenType.MINUS, "MINUS"); put(TokenType.MULTIPLY, "MULTIPLY"); put(TokenType.DIVIDE, "DIVIDE"); put(TokenType.BIG_NUMBER, "BIG_NUMBER"); put(TokenType.ASSIGN, "ASSIGN"); put(TokenType.LPAREN, "LPAREN"); put(TokenType.RPAREN, "RPAREN"); put(TokenType.SEMICOLON, "SEMICOLON"); put(TokenType.IF, "IF"); put(TokenType.TRUE, "IF"); put(TokenType.FALSE, "IF"); put(TokenType.LET, "LET"); put(TokenType.DOT, "DOT"); put(TokenType.GT, "GT"); put(TokenType.LT, "LT"); put(TokenType.GTE, "GTE"); put(TokenType.LTE, "LTE"); put(TokenType.EOF, "EOF"); put(TokenType.ELSE, "ELSE"); put(TokenType.LBRACKET, "LBRACKET"); put(TokenType.RBRACKET, "RBRACKET"); put(TokenType.EQ, "EQ"); put(TokenType.NON_EQ, "NON_EQ"); put(TokenType.AND, "AND"); put(TokenType.OR, "OR"); put(TokenType.IDENT, "IDENT"); } }; public static String convertTokenType(TokenType key) { return tokenTypeMap.get(key); } }
UTF-8
Java
1,497
java
TokenTypeConverter.java
Java
[]
null
[]
package token; import java.util.HashMap; public class TokenTypeConverter { private static HashMap<TokenType, String> tokenTypeMap = new HashMap<TokenType, String>() { { put(TokenType.UNDEFINED, "UNDEFINED"); put(TokenType.SUM, "SUM"); put(TokenType.MINUS, "MINUS"); put(TokenType.MULTIPLY, "MULTIPLY"); put(TokenType.DIVIDE, "DIVIDE"); put(TokenType.BIG_NUMBER, "BIG_NUMBER"); put(TokenType.ASSIGN, "ASSIGN"); put(TokenType.LPAREN, "LPAREN"); put(TokenType.RPAREN, "RPAREN"); put(TokenType.SEMICOLON, "SEMICOLON"); put(TokenType.IF, "IF"); put(TokenType.TRUE, "IF"); put(TokenType.FALSE, "IF"); put(TokenType.LET, "LET"); put(TokenType.DOT, "DOT"); put(TokenType.GT, "GT"); put(TokenType.LT, "LT"); put(TokenType.GTE, "GTE"); put(TokenType.LTE, "LTE"); put(TokenType.EOF, "EOF"); put(TokenType.ELSE, "ELSE"); put(TokenType.LBRACKET, "LBRACKET"); put(TokenType.RBRACKET, "RBRACKET"); put(TokenType.EQ, "EQ"); put(TokenType.NON_EQ, "NON_EQ"); put(TokenType.AND, "AND"); put(TokenType.OR, "OR"); put(TokenType.IDENT, "IDENT"); } }; public static String convertTokenType(TokenType key) { return tokenTypeMap.get(key); } }
1,497
0.536406
0.536406
42
34.642857
18.557276
95
false
false
0
0
0
0
0
0
1.47619
false
false
10
c0c8e1c3c1b62197f2c95d44c8b7f2421e9838a2
16,080,357,593,128
20dd475455cdfc1bef94366f79fbcbffb2a63169
/Collection/src/com/usingMap/BloodDonorService.java
b8673a088a9ec70f8e4c4520c7513b3a3c0400e6
[]
no_license
abhineet-singh/java_assignment
https://github.com/abhineet-singh/java_assignment
bf68c30f72f148b0c88386ed5caba5d4c1266365
7763dfa3092ea5e091b2e1ad3e65c484699fbc99
refs/heads/master
2023-02-10T01:00:00.267000
2021-01-08T09:14:50
2021-01-08T09:14:50
319,296,581
0
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.usingMap; import java.util.*; public class BloodDonorService { private HashMap<String,ArrayList<BloodDonor>> bloodDonorMap; public BloodDonorService() { this.bloodDonorMap = new HashMap<>(); } public boolean addDonorToGroup(BloodDonor donor) { ArrayList<BloodDonor> donorList = bloodDonorMap.get(donor.getBloodGroup()); if(donorList == null) { donorList = new ArrayList<BloodDonor>(); donorList.add(donor); this.bloodDonorMap.put(donor.getBloodGroup(), donorList); } else { if(!donorList.contains(donor)) { donorList.add(donor); } else { return false; } } return true; } public List<BloodDonor> printDonorOfGroup(String bloodGroup) { ArrayList<BloodDonor> list = this.bloodDonorMap.get(bloodGroup); return list; } }
UTF-8
Java
943
java
BloodDonorService.java
Java
[]
null
[]
package com.usingMap; import java.util.*; public class BloodDonorService { private HashMap<String,ArrayList<BloodDonor>> bloodDonorMap; public BloodDonorService() { this.bloodDonorMap = new HashMap<>(); } public boolean addDonorToGroup(BloodDonor donor) { ArrayList<BloodDonor> donorList = bloodDonorMap.get(donor.getBloodGroup()); if(donorList == null) { donorList = new ArrayList<BloodDonor>(); donorList.add(donor); this.bloodDonorMap.put(donor.getBloodGroup(), donorList); } else { if(!donorList.contains(donor)) { donorList.add(donor); } else { return false; } } return true; } public List<BloodDonor> printDonorOfGroup(String bloodGroup) { ArrayList<BloodDonor> list = this.bloodDonorMap.get(bloodGroup); return list; } }
943
0.597031
0.597031
46
18.5
21.416927
77
false
false
0
0
0
0
0
0
1.434783
false
false
10
282605e49aa67788850aefc1179a3b6466d2b964
8,083,128,475,890
5c1856f6419369e57426e83f788fd4a28cdd9107
/meme-im/src/main/java/com/meme/im/pojo/MemeMusic.java
1c29f26f55404414cbd98b5a5fd39ab5d7ff76ad
[]
no_license
cherish-wwl/meme-branch
https://github.com/cherish-wwl/meme-branch
c5072572df7dfa57a32ce1fb28819da8cbf1dceb
250d6f6a2ddbac1fa1a688873de58a53ee580aee
refs/heads/master
2020-04-09T05:03:08.138000
2018-12-02T13:16:47
2018-12-02T13:16:47
160,049,156
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.meme.im.pojo; public class MemeMusic { }
UTF-8
Java
55
java
MemeMusic.java
Java
[]
null
[]
package com.meme.im.pojo; public class MemeMusic { }
55
0.727273
0.727273
5
10
11.849051
25
false
false
0
0
0
0
0
0
0.2
false
false
10
e204ef14133dc13d112c154e892e120c7134706b
6,502,580,539,293
2a39c350ac5b0832069c6f930ff42473f9a53bec
/app/src/main/java/yotatest/ru/rssswidget/XMLParser.java
284385ae2d292183e0589efa08f53210efda24bf
[]
no_license
Gaikanomer9/yota_test_rss
https://github.com/Gaikanomer9/yota_test_rss
15618b5d8ed195722bf314030a6fa28b1bb758ba
f9cfbf6d62a87f220c5404dde73bac94d953218c
refs/heads/master
2017-12-01T09:01:47.457000
2016-06-09T18:28:42
2016-06-09T18:28:42
60,493,418
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package yotatest.ru.rssswidget; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserFactory; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; /** * Created by Nikita on 05.06.2016. */ public class XMLParser { private String title = "title"; private String description = "description"; private static String urlString = null; private XmlPullParserFactory xmlFactoryObject; public volatile boolean parsingComplete = true; private ArrayList<ParsedObject> parsedObjects; private static XMLParser xmlParser; private static Thread thread; public int getNewsCount(){ return parsedObjects.size(); } public String getNewsTitleAt(int i){ return parsedObjects.get(i).title; } public String getNewsDescrAt(int i){ return parsedObjects.get(i).description; } public static XMLParser initiate(String url){ if (xmlParser == null){ xmlParser = new XMLParser(url); } if (!urlString.equals(url)){ xmlParser = new XMLParser(url); } return xmlParser; } private XMLParser(String url){ urlString = url; parsedObjects = new ArrayList<>(); } public void parseXMLAndStoreIt(XmlPullParser myParser) { int event; String text=null; parsedObjects = new ArrayList<>(); try { event = myParser.getEventType(); while (event != XmlPullParser.END_DOCUMENT) { String name=myParser.getName(); if (name == null){ event = myParser.next(); continue; } if (!name.equals("item")){ event = myParser.next(); continue; } else { event = myParser.next(); name = myParser.getName()==null?"":myParser.getName(); ParsedObject parsedObject = new ParsedObject(); while(!name.equals("item")){ name = myParser.getName()==null?"":myParser.getName(); switch (event){ case XmlPullParser.START_TAG: break; case XmlPullParser.TEXT: text = myParser.getText(); break; case XmlPullParser.END_TAG: if(name.equals("title")){ title = text; parsedObject.title = title; } else if(name.equals("description")){ description = text; parsedObject.description = description; } break; } event = myParser.next(); } if (!parsedObjects.contains(parsedObject)){ parsedObjects.add(parsedObject); } } } parsingComplete = false; } catch (Exception e) { e.printStackTrace(); } } public void fetchXML(){ thread = new Thread(new Runnable(){ @Override public void run() { try { URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("GET"); conn.setDoInput(true); // Starts the query conn.connect(); InputStream stream = conn.getInputStream(); xmlFactoryObject = XmlPullParserFactory.newInstance(); XmlPullParser myparser = xmlFactoryObject.newPullParser(); myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false); myparser.setInput(stream, null); parseXMLAndStoreIt(myparser); stream.close(); } catch (Exception e) { } } }); thread.start(); try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } private class ParsedObject{ private String title; private String description; @Override public boolean equals(Object object) { boolean sameSame = false; if (object != null && object instanceof ParsedObject) { sameSame = this.title.equals(((ParsedObject) object).title) & this.description.equals(((ParsedObject) object).description); } return sameSame; } } }
UTF-8
Java
5,183
java
XMLParser.java
Java
[ { "context": "RL;\nimport java.util.ArrayList;\n\n/**\n * Created by Nikita on 05.06.2016.\n */\npublic class XMLParser {\n p", "end": 252, "score": 0.9980892539024353, "start": 246, "tag": "NAME", "value": "Nikita" } ]
null
[]
package yotatest.ru.rssswidget; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserFactory; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; /** * Created by Nikita on 05.06.2016. */ public class XMLParser { private String title = "title"; private String description = "description"; private static String urlString = null; private XmlPullParserFactory xmlFactoryObject; public volatile boolean parsingComplete = true; private ArrayList<ParsedObject> parsedObjects; private static XMLParser xmlParser; private static Thread thread; public int getNewsCount(){ return parsedObjects.size(); } public String getNewsTitleAt(int i){ return parsedObjects.get(i).title; } public String getNewsDescrAt(int i){ return parsedObjects.get(i).description; } public static XMLParser initiate(String url){ if (xmlParser == null){ xmlParser = new XMLParser(url); } if (!urlString.equals(url)){ xmlParser = new XMLParser(url); } return xmlParser; } private XMLParser(String url){ urlString = url; parsedObjects = new ArrayList<>(); } public void parseXMLAndStoreIt(XmlPullParser myParser) { int event; String text=null; parsedObjects = new ArrayList<>(); try { event = myParser.getEventType(); while (event != XmlPullParser.END_DOCUMENT) { String name=myParser.getName(); if (name == null){ event = myParser.next(); continue; } if (!name.equals("item")){ event = myParser.next(); continue; } else { event = myParser.next(); name = myParser.getName()==null?"":myParser.getName(); ParsedObject parsedObject = new ParsedObject(); while(!name.equals("item")){ name = myParser.getName()==null?"":myParser.getName(); switch (event){ case XmlPullParser.START_TAG: break; case XmlPullParser.TEXT: text = myParser.getText(); break; case XmlPullParser.END_TAG: if(name.equals("title")){ title = text; parsedObject.title = title; } else if(name.equals("description")){ description = text; parsedObject.description = description; } break; } event = myParser.next(); } if (!parsedObjects.contains(parsedObject)){ parsedObjects.add(parsedObject); } } } parsingComplete = false; } catch (Exception e) { e.printStackTrace(); } } public void fetchXML(){ thread = new Thread(new Runnable(){ @Override public void run() { try { URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("GET"); conn.setDoInput(true); // Starts the query conn.connect(); InputStream stream = conn.getInputStream(); xmlFactoryObject = XmlPullParserFactory.newInstance(); XmlPullParser myparser = xmlFactoryObject.newPullParser(); myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false); myparser.setInput(stream, null); parseXMLAndStoreIt(myparser); stream.close(); } catch (Exception e) { } } }); thread.start(); try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } private class ParsedObject{ private String title; private String description; @Override public boolean equals(Object object) { boolean sameSame = false; if (object != null && object instanceof ParsedObject) { sameSame = this.title.equals(((ParsedObject) object).title) & this.description.equals(((ParsedObject) object).description); } return sameSame; } } }
5,183
0.490835
0.486977
168
29.857143
23.852795
139
false
false
0
0
0
0
0
0
0.434524
false
false
10
aa07d4b954dbefc2faad3c6d706fe245221fa787
22,187,801,092,826
2e17f9bab427647bd7ad5b6a07544d21e16b11e3
/Chapter24/BankServerElegant_kiv/AdminData.java
7f9f265869fc0516573fa4ce310dc7fc910a8576
[ "MIT" ]
permissive
freakygeeks/BigJavaCodeSolution
https://github.com/freakygeeks/BigJavaCodeSolution
42918111d8efb7bcb88616b256e44894c6433ed1
ed02f808cf61a1bf0f3af8bd5fb891d10229e3f3
refs/heads/master
2021-07-11T13:15:00.466000
2021-04-02T14:49:48
2021-04-02T14:49:48
52,708,407
3
0
null
false
2021-04-02T14:41:13
2016-02-28T06:35:46
2021-01-22T10:10:09
2021-04-02T14:41:12
26,044
1
0
0
Java
false
false
//Chapter 24 - Exercise 24.3 /** Contains bank administration data. */ public class AdminData { private int customerCount = 0; private String password = "secret"; private boolean shutdown; /** Increments the customer count. */ public synchronized void incrementCustomerCount() { customerCount++; } /** Gets the current customer count. */ public synchronized int getCustomerCount() { return customerCount; } /** Checks the password @param pw the password to check against @return true if this is the correct password */ public synchronized boolean checkPassword(String pw) { return password.equals(pw); } /** Changes the password. @param oldPassword the current password @param newPassword the new password */ public synchronized void changePassword(String oldPassword, String newPassword) { if (checkPassword(oldPassword)) password = newPassword; } }
UTF-8
Java
1,008
java
AdminData.java
Java
[ { "context": " customerCount = 0;\n private String password = \"secret\";\n private boolean shutdown;\n\n /**\n Incr", "end": 170, "score": 0.9995527863502502, "start": 164, "tag": "PASSWORD", "value": "secret" }, { "context": "f (checkPassword(oldPassword))\n password = newPassword;\n }\n}", "end": 1000, "score": 0.9808917045593262, "start": 989, "tag": "PASSWORD", "value": "newPassword" } ]
null
[]
//Chapter 24 - Exercise 24.3 /** Contains bank administration data. */ public class AdminData { private int customerCount = 0; private String password = "<PASSWORD>"; private boolean shutdown; /** Increments the customer count. */ public synchronized void incrementCustomerCount() { customerCount++; } /** Gets the current customer count. */ public synchronized int getCustomerCount() { return customerCount; } /** Checks the password @param pw the password to check against @return true if this is the correct password */ public synchronized boolean checkPassword(String pw) { return password.equals(pw); } /** Changes the password. @param oldPassword the current password @param newPassword the new password */ public synchronized void changePassword(String oldPassword, String newPassword) { if (checkPassword(oldPassword)) password = <PASSWORD>; } }
1,011
0.65377
0.647817
48
20.020834
19.684479
82
false
false
0
0
0
0
0
0
0.166667
false
false
10
b6d01c5ea4e8077f6804a1405b2f6c959d811bfa
22,187,801,093,059
dc1c1fdbf0e50aa420b22872e2455fe62b1f2103
/src/com/hxh19950701/action/TeacherManagerAction.java
32679490a7c7f0052f0677dd26872661895f8e3c
[]
no_license
hxh19950701/TeachingEvaluateServer
https://github.com/hxh19950701/TeachingEvaluateServer
bd323f5212bfc7a13faae40210599f102adbe247
ca8f794592c451264fe9d0faff056dd9318c48a7
refs/heads/master
2021-01-20T07:24:25.283000
2017-08-27T07:49:19
2017-08-27T07:53:46
101,537,788
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hxh19950701.action; import com.hxh19950701.comm.CheckUtils; import com.hxh19950701.comm.Constant; import com.hxh19950701.comm.CustomException; import com.hxh19950701.pojos.Code; import com.hxh19950701.pojos.Teacher; import com.hxh19950701.pojos.User; import com.hxh19950701.service.CodeService; import com.hxh19950701.service.TeacherService; public class TeacherManagerAction extends BaseAction { private static final long serialVersionUID = 1L; private int uid = -1; private String teacherId = null; private int sex = -1; private String name = null; private CodeService codeService; private TeacherService teacherService; public void setUid(int uid) { this.uid = uid; } public void setTeacherId(String teacherId) { this.teacherId = teacherId; } public void setSex(int sex) { this.sex = sex; } public void setName(String name) { this.name = name; } public void setTeacherService(TeacherService teacherService) { this.teacherService = teacherService; } public void setCodeService(CodeService codeService) { this.codeService = codeService; } public Object register() throws Exception { User user = getOnlineUser(); switch (user.getIdentity()) { case Constant.IDENTITY_STUDENT: throw new CustomException.PermissionDeniedException(); case Constant.IDENTITY_TEACHER: return teacherService.register(user.getId(), teacherId, name, sex); case Constant.IDENTITY_ADMINISTRATOR: return teacherService.register(uid, teacherId, name, sex); } return null; } public Object currentTeacher() throws Exception { User user = getOnlineUser(); Teacher teacher = teacherService.getTeacherByUid(user.getId()); return teacher; } public Teacher getTeacherByUid() throws CustomException.BaseCustomException { CheckUtils.checkUid(uid); return teacherService.getTeacherByUid(uid); } public Code createCode() throws CustomException.BaseCustomException { User user = getOnlineUser(); switch (user.getIdentity()) { case Constant.IDENTITY_STUDENT: throw new CustomException.PermissionDeniedException(); case Constant.IDENTITY_TEACHER: return codeService.create(); case Constant.IDENTITY_ADMINISTRATOR: throw new CustomException.PermissionDeniedException(); } return null; } }
UTF-8
Java
2,362
java
TeacherManagerAction.java
Java
[]
null
[]
package com.hxh19950701.action; import com.hxh19950701.comm.CheckUtils; import com.hxh19950701.comm.Constant; import com.hxh19950701.comm.CustomException; import com.hxh19950701.pojos.Code; import com.hxh19950701.pojos.Teacher; import com.hxh19950701.pojos.User; import com.hxh19950701.service.CodeService; import com.hxh19950701.service.TeacherService; public class TeacherManagerAction extends BaseAction { private static final long serialVersionUID = 1L; private int uid = -1; private String teacherId = null; private int sex = -1; private String name = null; private CodeService codeService; private TeacherService teacherService; public void setUid(int uid) { this.uid = uid; } public void setTeacherId(String teacherId) { this.teacherId = teacherId; } public void setSex(int sex) { this.sex = sex; } public void setName(String name) { this.name = name; } public void setTeacherService(TeacherService teacherService) { this.teacherService = teacherService; } public void setCodeService(CodeService codeService) { this.codeService = codeService; } public Object register() throws Exception { User user = getOnlineUser(); switch (user.getIdentity()) { case Constant.IDENTITY_STUDENT: throw new CustomException.PermissionDeniedException(); case Constant.IDENTITY_TEACHER: return teacherService.register(user.getId(), teacherId, name, sex); case Constant.IDENTITY_ADMINISTRATOR: return teacherService.register(uid, teacherId, name, sex); } return null; } public Object currentTeacher() throws Exception { User user = getOnlineUser(); Teacher teacher = teacherService.getTeacherByUid(user.getId()); return teacher; } public Teacher getTeacherByUid() throws CustomException.BaseCustomException { CheckUtils.checkUid(uid); return teacherService.getTeacherByUid(uid); } public Code createCode() throws CustomException.BaseCustomException { User user = getOnlineUser(); switch (user.getIdentity()) { case Constant.IDENTITY_STUDENT: throw new CustomException.PermissionDeniedException(); case Constant.IDENTITY_TEACHER: return codeService.create(); case Constant.IDENTITY_ADMINISTRATOR: throw new CustomException.PermissionDeniedException(); } return null; } }
2,362
0.737934
0.706181
84
26.142857
21.465445
78
false
false
0
0
0
0
0
0
1.809524
false
false
10
35e90a65db2c8b3fa811cfe90e877ab56d0f21c5
13,855,564,547,263
e1be07c04d74336448787700ff6eb16028f421fb
/src/ozlib/util/_Date_cl.java
dda031c28ca3366b8e6b1e999283535200173310
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
yoshiylife/OZonJava
https://github.com/yoshiylife/OZonJava
0e66a989556d359361d02d74641968c076b24565
b0d89353a8bf1224a9a8da490409c5f62dc2d017
refs/heads/master
2021-01-10T01:06:37.338000
2016-02-18T18:47:12
2016-02-18T18:47:12
52,029,219
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* Copyright(c) 1996-1998 IPA, ETL, AT21, FSIABC, FXIS, InArc, MRI, NUL, SBC, Sharp, TEC, TIS All rights reserved. No guarantee. This technology is a result of the Advanced Software Enrichment Project of Information-technology Promotion Agency, Japan (IPA). Permissions to use, copy, modify and distribute this software are governed by the terms and conditions set forth in the file COPYRIGHT, located on the top directory of this software. */ /* * $Id: _Date_cl.java,v 1.1 1997/08/19 09:52:12 hgoto Exp $ */ package JP.go.ipa.oz.lib.standard; public class _Date_cl extends JP.go.ipa.oz.lang._Root_cl implements _Date_if { java.util.Date _body; public Object _new_breed() throws Exception { _body = new java.util.Date(); return this; } public Object _new_breed(long arg_a) throws Exception { long var_a = arg_a; _body = new java.util.Date(var_a); return this; } public long getTime() throws Exception { checkSecureInvocation(); long work; long ret; work = ((java.util.Date)_body).getTime(); ret = work; return ret; } public void setTime(long arg_a) throws Exception { checkSecureInvocation(); long var_a = arg_a; ((java.util.Date)_body).setTime(var_a); } public boolean before(_Date_if arg_a) throws Exception { checkSecureInvocation(); _Date_cl var_a = (_Date_cl)arg_a; boolean work; boolean ret; work = ((java.util.Date)_body).before((java.util.Date)(var_a._body)); ret = work; return ret; } public boolean after(_Date_if arg_a) throws Exception { checkSecureInvocation(); _Date_cl var_a = (_Date_cl)arg_a; boolean work; boolean ret; work = ((java.util.Date)_body).after((java.util.Date)(var_a._body)); ret = work; return ret; } public boolean isEqualDate(_Date_if arg_a) throws Exception { checkSecureInvocation(); boolean ret; ret = _body.equals(((_Date_cl)arg_a)._body); return ret; } public _String_if asString() throws Exception { checkSecureInvocation(); java.lang.String work; _String_cl ret; work = ((java.util.Date)_body).toString(); ret = new _String_cl(work); return ret; } public _Date_cl() { } _Date_cl(java.util.Date arg_a) { _body = arg_a; } }
UTF-8
Java
2,269
java
_Date_cl.java
Java
[ { "context": "/*\n * $Id: _Date_cl.java,v 1.1 1997/08/19 09:52:12 hgoto Exp $\n */\n\npackage JP.go.ipa.oz.lib.standard;\n\npu", "end": 521, "score": 0.982286274433136, "start": 516, "tag": "USERNAME", "value": "hgoto" } ]
null
[]
/* Copyright(c) 1996-1998 IPA, ETL, AT21, FSIABC, FXIS, InArc, MRI, NUL, SBC, Sharp, TEC, TIS All rights reserved. No guarantee. This technology is a result of the Advanced Software Enrichment Project of Information-technology Promotion Agency, Japan (IPA). Permissions to use, copy, modify and distribute this software are governed by the terms and conditions set forth in the file COPYRIGHT, located on the top directory of this software. */ /* * $Id: _Date_cl.java,v 1.1 1997/08/19 09:52:12 hgoto Exp $ */ package JP.go.ipa.oz.lib.standard; public class _Date_cl extends JP.go.ipa.oz.lang._Root_cl implements _Date_if { java.util.Date _body; public Object _new_breed() throws Exception { _body = new java.util.Date(); return this; } public Object _new_breed(long arg_a) throws Exception { long var_a = arg_a; _body = new java.util.Date(var_a); return this; } public long getTime() throws Exception { checkSecureInvocation(); long work; long ret; work = ((java.util.Date)_body).getTime(); ret = work; return ret; } public void setTime(long arg_a) throws Exception { checkSecureInvocation(); long var_a = arg_a; ((java.util.Date)_body).setTime(var_a); } public boolean before(_Date_if arg_a) throws Exception { checkSecureInvocation(); _Date_cl var_a = (_Date_cl)arg_a; boolean work; boolean ret; work = ((java.util.Date)_body).before((java.util.Date)(var_a._body)); ret = work; return ret; } public boolean after(_Date_if arg_a) throws Exception { checkSecureInvocation(); _Date_cl var_a = (_Date_cl)arg_a; boolean work; boolean ret; work = ((java.util.Date)_body).after((java.util.Date)(var_a._body)); ret = work; return ret; } public boolean isEqualDate(_Date_if arg_a) throws Exception { checkSecureInvocation(); boolean ret; ret = _body.equals(((_Date_cl)arg_a)._body); return ret; } public _String_if asString() throws Exception { checkSecureInvocation(); java.lang.String work; _String_cl ret; work = ((java.util.Date)_body).toString(); ret = new _String_cl(work); return ret; } public _Date_cl() { } _Date_cl(java.util.Date arg_a) { _body = arg_a; } }
2,269
0.653592
0.642133
106
20.405661
20.794947
70
false
false
0
0
0
0
0
0
0.90566
false
false
10
cce9fdc6b5eee99edd025dc8201a42333a3d42fd
13,855,564,549,962
5b3967c0ba4503308ddc3c840bfa96c5f10665e1
/multiplicity3-parent/multiplicity3-contentsystem/src/main/java/multiplicity3/csys/items/border/IRoundedBorder.java
2134f96eb305b1e022696e61771423c29712e73c
[ "BSD-3-Clause" ]
permissive
jamcnaughton/synergynet3
https://github.com/jamcnaughton/synergynet3
ce549f841190fee4f9b39264a5b3df4aebad2b2b
8ef37a03253b39515c914efa021309428b63ef53
refs/heads/master
2020-04-18T22:41:47.206000
2017-07-07T15:21:20
2017-07-07T15:21:20
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package multiplicity3.csys.items.border; import multiplicity3.csys.items.item.IItem; import com.jme3.math.Vector2f; import com.jme3.math.ColorRGBA; public interface IRoundedBorder extends IItem { public Vector2f getSize(); public void setSize(Vector2f size); public void setSize(float width, float height); public void setBorderWidth(float borderSize); public void setColor(ColorRGBA color); public float getBorderWidth(); }
UTF-8
Java
434
java
IRoundedBorder.java
Java
[]
null
[]
package multiplicity3.csys.items.border; import multiplicity3.csys.items.item.IItem; import com.jme3.math.Vector2f; import com.jme3.math.ColorRGBA; public interface IRoundedBorder extends IItem { public Vector2f getSize(); public void setSize(Vector2f size); public void setSize(float width, float height); public void setBorderWidth(float borderSize); public void setColor(ColorRGBA color); public float getBorderWidth(); }
434
0.801843
0.785714
15
27.933332
17.781889
48
false
false
0
0
0
0
0
0
1.133333
false
false
10
0271889c55c65fe5e5b608c259b7839dd8f462d5
16,896,401,400,834
a8cfaf8af953248532b6a683915974ed9c6c9015
/app/src/main/java/com/example/timo/uebung2/MainActivity.java
0b275af5499243b55dbcce69c9dda4d561c003a7
[]
no_license
timokae/android-sensors
https://github.com/timokae/android-sensors
512af10fc4289d0c4a64a1da0e6ba642dd67f3f7
33ad7c2d14666df4c0ff2caabdb96ba109ea6778
refs/heads/master
2020-04-01T13:56:12.436000
2018-10-16T11:33:18
2018-10-16T11:33:18
153,273,459
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.timo.uebung2; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; public class MainActivity extends AppCompatActivity { SensorManager sensorManager; TextView textViewAccelerometer; TextView textViewProximity; TextView textViewLight; TextView textViewMagneticField; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textViewAccelerometer = findViewById(R.id.textViewAccelerometer); textViewProximity = findViewById(R.id.textViewProximity); textViewLight = findViewById(R.id.textViewLight); textViewMagneticField = findViewById(R.id.textViewMagneticField); sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE); SensorEventListener sensorEventListener = new SensorEventListener() { @Override public void onSensorChanged(SensorEvent event) { switch (event.sensor.getType()) { case Sensor.TYPE_ACCELEROMETER: textViewAccelerometer.setText("X: " + event.values[0] + "\n" + "Y: " + event.values[1] + "\n" + "Z: " + event.values[2]); break; case Sensor.TYPE_PROXIMITY: textViewProximity.setText("X: " + event.values[0] + " cm" + " [" + event.values[1] + "]"); break; case Sensor.TYPE_LIGHT: textViewLight.setText(event.values[0] + " lx"); break; case Sensor.TYPE_MAGNETIC_FIELD: textViewMagneticField.setText("X: " + event.values[0] + "\n" + "Y: " + event.values[1] + "\n" + "Z: " + event.values[2]); break; } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } }; sensorManager.registerListener(sensorEventListener, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), sensorManager.SENSOR_DELAY_NORMAL); sensorManager.registerListener(sensorEventListener, sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY), sensorManager.SENSOR_DELAY_NORMAL); sensorManager.registerListener(sensorEventListener, sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT), sensorManager.SENSOR_DELAY_NORMAL); sensorManager.registerListener(sensorEventListener, sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD), sensorManager.SENSOR_DELAY_NORMAL); } }
UTF-8
Java
2,812
java
MainActivity.java
Java
[ { "context": "package com.example.timo.uebung2;\n\nimport android.hardware.Sensor;\nimport ", "end": 24, "score": 0.5733141303062439, "start": 20, "tag": "USERNAME", "value": "timo" } ]
null
[]
package com.example.timo.uebung2; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; public class MainActivity extends AppCompatActivity { SensorManager sensorManager; TextView textViewAccelerometer; TextView textViewProximity; TextView textViewLight; TextView textViewMagneticField; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textViewAccelerometer = findViewById(R.id.textViewAccelerometer); textViewProximity = findViewById(R.id.textViewProximity); textViewLight = findViewById(R.id.textViewLight); textViewMagneticField = findViewById(R.id.textViewMagneticField); sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE); SensorEventListener sensorEventListener = new SensorEventListener() { @Override public void onSensorChanged(SensorEvent event) { switch (event.sensor.getType()) { case Sensor.TYPE_ACCELEROMETER: textViewAccelerometer.setText("X: " + event.values[0] + "\n" + "Y: " + event.values[1] + "\n" + "Z: " + event.values[2]); break; case Sensor.TYPE_PROXIMITY: textViewProximity.setText("X: " + event.values[0] + " cm" + " [" + event.values[1] + "]"); break; case Sensor.TYPE_LIGHT: textViewLight.setText(event.values[0] + " lx"); break; case Sensor.TYPE_MAGNETIC_FIELD: textViewMagneticField.setText("X: " + event.values[0] + "\n" + "Y: " + event.values[1] + "\n" + "Z: " + event.values[2]); break; } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } }; sensorManager.registerListener(sensorEventListener, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), sensorManager.SENSOR_DELAY_NORMAL); sensorManager.registerListener(sensorEventListener, sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY), sensorManager.SENSOR_DELAY_NORMAL); sensorManager.registerListener(sensorEventListener, sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT), sensorManager.SENSOR_DELAY_NORMAL); sensorManager.registerListener(sensorEventListener, sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD), sensorManager.SENSOR_DELAY_NORMAL); } }
2,812
0.65505
0.651138
62
44.354839
42.245098
155
false
false
0
0
0
0
0
0
0.677419
false
false
10
c7392539c35ec4a5c3fc593a6681fa894bfa49f3
30,391,188,590,212
87b1597b0213fe671d8a0f7037fcde89d3d28743
/CanchasPZ 27.8.2/build/generated-sources/jax-ws/ws/Cancha.java
b06899bc43e3be795e9115d477b1bf2a9f06daba
[]
no_license
mario2598/CanchasPZyWS
https://github.com/mario2598/CanchasPZyWS
3794a192021cccfe764c2dfda92df36ac390ecf1
84dbd343be52c79a561eea43372c05e635a0c29d
refs/heads/master
2020-03-31T23:25:08.941000
2018-10-20T15:57:23
2018-10-20T15:57:23
152,655,059
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ws; import java.math.BigDecimal; import java.math.BigInteger; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * <p>Clase Java para cancha complex type. * * <p>El siguiente fragmento de esquema especifica el contenido que se espera que haya en esta clase. * * <pre> * &lt;complexType name="cancha"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="admId" type="{http://ws/}administrador" minOccurs="0"/> * &lt;element name="canAbre" type="{http://www.w3.org/2001/XMLSchema}integer" minOccurs="0"/> * &lt;element name="canCantJugadores" type="{http://www.w3.org/2001/XMLSchema}integer" minOccurs="0"/> * &lt;element name="canCierra" type="{http://www.w3.org/2001/XMLSchema}integer" minOccurs="0"/> * &lt;element name="canDireccion" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="canId" type="{http://www.w3.org/2001/XMLSchema}decimal" minOccurs="0"/> * &lt;element name="canLatitud" type="{http://www.w3.org/2001/XMLSchema}integer" minOccurs="0"/> * &lt;element name="canLongitud" type="{http://www.w3.org/2001/XMLSchema}integer" minOccurs="0"/> * &lt;element name="canNombre" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="canPrecioDia" type="{http://www.w3.org/2001/XMLSchema}integer" minOccurs="0"/> * &lt;element name="canPrecioNoches" type="{http://www.w3.org/2001/XMLSchema}integer" minOccurs="0"/> * &lt;element name="canTel" type="{http://www.w3.org/2001/XMLSchema}integer" minOccurs="0"/> * &lt;element name="canUrl" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "cancha", propOrder = { "admId", "canAbre", "canCantJugadores", "canCierra", "canDireccion", "canId", "canLatitud", "canLongitud", "canNombre", "canPrecioDia", "canPrecioNoches", "canTel", "canUrl" }) public class Cancha { protected Administrador admId; protected BigInteger canAbre; protected BigInteger canCantJugadores; protected BigInteger canCierra; protected String canDireccion; protected BigDecimal canId; protected BigInteger canLatitud; protected BigInteger canLongitud; protected String canNombre; protected BigInteger canPrecioDia; protected BigInteger canPrecioNoches; protected BigInteger canTel; protected String canUrl; /** * Obtiene el valor de la propiedad admId. * * @return * possible object is * {@link Administrador } * */ public Administrador getAdmId() { return admId; } /** * Define el valor de la propiedad admId. * * @param value * allowed object is * {@link Administrador } * */ public void setAdmId(Administrador value) { this.admId = value; } /** * Obtiene el valor de la propiedad canAbre. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getCanAbre() { return canAbre; } /** * Define el valor de la propiedad canAbre. * * @param value * allowed object is * {@link BigInteger } * */ public void setCanAbre(BigInteger value) { this.canAbre = value; } /** * Obtiene el valor de la propiedad canCantJugadores. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getCanCantJugadores() { return canCantJugadores; } /** * Define el valor de la propiedad canCantJugadores. * * @param value * allowed object is * {@link BigInteger } * */ public void setCanCantJugadores(BigInteger value) { this.canCantJugadores = value; } /** * Obtiene el valor de la propiedad canCierra. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getCanCierra() { return canCierra; } /** * Define el valor de la propiedad canCierra. * * @param value * allowed object is * {@link BigInteger } * */ public void setCanCierra(BigInteger value) { this.canCierra = value; } /** * Obtiene el valor de la propiedad canDireccion. * * @return * possible object is * {@link String } * */ public String getCanDireccion() { return canDireccion; } /** * Define el valor de la propiedad canDireccion. * * @param value * allowed object is * {@link String } * */ public void setCanDireccion(String value) { this.canDireccion = value; } /** * Obtiene el valor de la propiedad canId. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getCanId() { return canId; } /** * Define el valor de la propiedad canId. * * @param value * allowed object is * {@link BigDecimal } * */ public void setCanId(BigDecimal value) { this.canId = value; } /** * Obtiene el valor de la propiedad canLatitud. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getCanLatitud() { return canLatitud; } /** * Define el valor de la propiedad canLatitud. * * @param value * allowed object is * {@link BigInteger } * */ public void setCanLatitud(BigInteger value) { this.canLatitud = value; } /** * Obtiene el valor de la propiedad canLongitud. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getCanLongitud() { return canLongitud; } /** * Define el valor de la propiedad canLongitud. * * @param value * allowed object is * {@link BigInteger } * */ public void setCanLongitud(BigInteger value) { this.canLongitud = value; } /** * Obtiene el valor de la propiedad canNombre. * * @return * possible object is * {@link String } * */ public String getCanNombre() { return canNombre; } /** * Define el valor de la propiedad canNombre. * * @param value * allowed object is * {@link String } * */ public void setCanNombre(String value) { this.canNombre = value; } /** * Obtiene el valor de la propiedad canPrecioDia. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getCanPrecioDia() { return canPrecioDia; } /** * Define el valor de la propiedad canPrecioDia. * * @param value * allowed object is * {@link BigInteger } * */ public void setCanPrecioDia(BigInteger value) { this.canPrecioDia = value; } /** * Obtiene el valor de la propiedad canPrecioNoches. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getCanPrecioNoches() { return canPrecioNoches; } /** * Define el valor de la propiedad canPrecioNoches. * * @param value * allowed object is * {@link BigInteger } * */ public void setCanPrecioNoches(BigInteger value) { this.canPrecioNoches = value; } /** * Obtiene el valor de la propiedad canTel. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getCanTel() { return canTel; } /** * Define el valor de la propiedad canTel. * * @param value * allowed object is * {@link BigInteger } * */ public void setCanTel(BigInteger value) { this.canTel = value; } /** * Obtiene el valor de la propiedad canUrl. * * @return * possible object is * {@link String } * */ public String getCanUrl() { return canUrl; } /** * Define el valor de la propiedad canUrl. * * @param value * allowed object is * {@link String } * */ public void setCanUrl(String value) { this.canUrl = value; } }
UTF-8
Java
9,160
java
Cancha.java
Java
[]
null
[]
package ws; import java.math.BigDecimal; import java.math.BigInteger; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * <p>Clase Java para cancha complex type. * * <p>El siguiente fragmento de esquema especifica el contenido que se espera que haya en esta clase. * * <pre> * &lt;complexType name="cancha"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="admId" type="{http://ws/}administrador" minOccurs="0"/> * &lt;element name="canAbre" type="{http://www.w3.org/2001/XMLSchema}integer" minOccurs="0"/> * &lt;element name="canCantJugadores" type="{http://www.w3.org/2001/XMLSchema}integer" minOccurs="0"/> * &lt;element name="canCierra" type="{http://www.w3.org/2001/XMLSchema}integer" minOccurs="0"/> * &lt;element name="canDireccion" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="canId" type="{http://www.w3.org/2001/XMLSchema}decimal" minOccurs="0"/> * &lt;element name="canLatitud" type="{http://www.w3.org/2001/XMLSchema}integer" minOccurs="0"/> * &lt;element name="canLongitud" type="{http://www.w3.org/2001/XMLSchema}integer" minOccurs="0"/> * &lt;element name="canNombre" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="canPrecioDia" type="{http://www.w3.org/2001/XMLSchema}integer" minOccurs="0"/> * &lt;element name="canPrecioNoches" type="{http://www.w3.org/2001/XMLSchema}integer" minOccurs="0"/> * &lt;element name="canTel" type="{http://www.w3.org/2001/XMLSchema}integer" minOccurs="0"/> * &lt;element name="canUrl" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "cancha", propOrder = { "admId", "canAbre", "canCantJugadores", "canCierra", "canDireccion", "canId", "canLatitud", "canLongitud", "canNombre", "canPrecioDia", "canPrecioNoches", "canTel", "canUrl" }) public class Cancha { protected Administrador admId; protected BigInteger canAbre; protected BigInteger canCantJugadores; protected BigInteger canCierra; protected String canDireccion; protected BigDecimal canId; protected BigInteger canLatitud; protected BigInteger canLongitud; protected String canNombre; protected BigInteger canPrecioDia; protected BigInteger canPrecioNoches; protected BigInteger canTel; protected String canUrl; /** * Obtiene el valor de la propiedad admId. * * @return * possible object is * {@link Administrador } * */ public Administrador getAdmId() { return admId; } /** * Define el valor de la propiedad admId. * * @param value * allowed object is * {@link Administrador } * */ public void setAdmId(Administrador value) { this.admId = value; } /** * Obtiene el valor de la propiedad canAbre. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getCanAbre() { return canAbre; } /** * Define el valor de la propiedad canAbre. * * @param value * allowed object is * {@link BigInteger } * */ public void setCanAbre(BigInteger value) { this.canAbre = value; } /** * Obtiene el valor de la propiedad canCantJugadores. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getCanCantJugadores() { return canCantJugadores; } /** * Define el valor de la propiedad canCantJugadores. * * @param value * allowed object is * {@link BigInteger } * */ public void setCanCantJugadores(BigInteger value) { this.canCantJugadores = value; } /** * Obtiene el valor de la propiedad canCierra. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getCanCierra() { return canCierra; } /** * Define el valor de la propiedad canCierra. * * @param value * allowed object is * {@link BigInteger } * */ public void setCanCierra(BigInteger value) { this.canCierra = value; } /** * Obtiene el valor de la propiedad canDireccion. * * @return * possible object is * {@link String } * */ public String getCanDireccion() { return canDireccion; } /** * Define el valor de la propiedad canDireccion. * * @param value * allowed object is * {@link String } * */ public void setCanDireccion(String value) { this.canDireccion = value; } /** * Obtiene el valor de la propiedad canId. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getCanId() { return canId; } /** * Define el valor de la propiedad canId. * * @param value * allowed object is * {@link BigDecimal } * */ public void setCanId(BigDecimal value) { this.canId = value; } /** * Obtiene el valor de la propiedad canLatitud. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getCanLatitud() { return canLatitud; } /** * Define el valor de la propiedad canLatitud. * * @param value * allowed object is * {@link BigInteger } * */ public void setCanLatitud(BigInteger value) { this.canLatitud = value; } /** * Obtiene el valor de la propiedad canLongitud. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getCanLongitud() { return canLongitud; } /** * Define el valor de la propiedad canLongitud. * * @param value * allowed object is * {@link BigInteger } * */ public void setCanLongitud(BigInteger value) { this.canLongitud = value; } /** * Obtiene el valor de la propiedad canNombre. * * @return * possible object is * {@link String } * */ public String getCanNombre() { return canNombre; } /** * Define el valor de la propiedad canNombre. * * @param value * allowed object is * {@link String } * */ public void setCanNombre(String value) { this.canNombre = value; } /** * Obtiene el valor de la propiedad canPrecioDia. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getCanPrecioDia() { return canPrecioDia; } /** * Define el valor de la propiedad canPrecioDia. * * @param value * allowed object is * {@link BigInteger } * */ public void setCanPrecioDia(BigInteger value) { this.canPrecioDia = value; } /** * Obtiene el valor de la propiedad canPrecioNoches. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getCanPrecioNoches() { return canPrecioNoches; } /** * Define el valor de la propiedad canPrecioNoches. * * @param value * allowed object is * {@link BigInteger } * */ public void setCanPrecioNoches(BigInteger value) { this.canPrecioNoches = value; } /** * Obtiene el valor de la propiedad canTel. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getCanTel() { return canTel; } /** * Define el valor de la propiedad canTel. * * @param value * allowed object is * {@link BigInteger } * */ public void setCanTel(BigInteger value) { this.canTel = value; } /** * Obtiene el valor de la propiedad canUrl. * * @return * possible object is * {@link String } * */ public String getCanUrl() { return canUrl; } /** * Define el valor de la propiedad canUrl. * * @param value * allowed object is * {@link String } * */ public void setCanUrl(String value) { this.canUrl = value; } }
9,160
0.551201
0.542686
385
22.78961
21.912575
111
false
false
0
0
0
0
0
0
0.205195
false
false
10
deacfbfb3971ab82a459c6415e86567155c3f6f4
2,774,548,922,500
f6f10e657bc3ab325b9d74761739c73149c2688d
/crypfy-elastic-trader/src/main/java/com/crypfy/elastic/trader/persistance/repository/StrategyRepository.java
32dced76a7a5b015a22c015f3806a20341b0f95d
[]
no_license
robertolima-dev/AI-Financial-Market
https://github.com/robertolima-dev/AI-Financial-Market
fb58f6454d04cd9a184368d77a412018943a39f7
1cdec7e4eb0b894df9d8e618d51049c3d4f32096
refs/heads/master
2021-10-21T21:48:01.197000
2019-03-06T18:48:08
2019-03-06T18:48:08
174,201,579
1
5
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.crypfy.elastic.trader.persistance.repository; import com.crypfy.elastic.trader.persistance.entity.Strategy; import com.crypfy.elastic.trader.persistance.enums.StrategyStatus; import org.springframework.data.mongodb.repository.MongoRepository; import java.util.List; public interface StrategyRepository extends MongoRepository<Strategy,String> { public Strategy findByName(String name); public List<Strategy> findByStrategyStatusNot(StrategyStatus strategyStatus); }
UTF-8
Java
505
java
StrategyRepository.java
Java
[]
null
[]
package com.crypfy.elastic.trader.persistance.repository; import com.crypfy.elastic.trader.persistance.entity.Strategy; import com.crypfy.elastic.trader.persistance.enums.StrategyStatus; import org.springframework.data.mongodb.repository.MongoRepository; import java.util.List; public interface StrategyRepository extends MongoRepository<Strategy,String> { public Strategy findByName(String name); public List<Strategy> findByStrategyStatusNot(StrategyStatus strategyStatus); }
505
0.813861
0.813861
14
34.07143
32.325275
81
false
false
0
0
0
0
0
0
0.571429
false
false
10
35e71a17c98bca88f58f8eb884461034b8def0bc
32,925,219,350,789
bb3c0bbbcd1ec992be242427e2d7deb76c125c9e
/Chapter 15/src/task_1/Holder3.java
227b58960111bcf76e14428f3d46db873997ab9c
[]
no_license
SergiyBiryuk/thinking-in-java
https://github.com/SergiyBiryuk/thinking-in-java
48545e08d9cba81c9e1fd548e87394d42ade76e2
ecebeb62a8043efc2f63089a54e5efba6aea1bbd
refs/heads/main
2023-04-10T11:04:45.794000
2021-04-14T19:48:22
2021-04-14T19:48:22
357,869,570
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package task_1; import typeinfo.pets.*; public class Holder3<T> { private T a; public Holder3(T a) { this.a = a; } public void set(T a) { this.a = a; } public T get() { return a; } public static void main(String [] args) { Holder3<Pet> h3 = new Holder3<Pet>(Pets.randomPet()); Pet p = h3.get(); System.out.println("0 " + p); for(int i = 0; i < 10; i++) { h3.set(Pets.randomPet()); System.out.println(i + 1 + " " + h3.get()); } } }
UTF-8
Java
521
java
Holder3.java
Java
[]
null
[]
package task_1; import typeinfo.pets.*; public class Holder3<T> { private T a; public Holder3(T a) { this.a = a; } public void set(T a) { this.a = a; } public T get() { return a; } public static void main(String [] args) { Holder3<Pet> h3 = new Holder3<Pet>(Pets.randomPet()); Pet p = h3.get(); System.out.println("0 " + p); for(int i = 0; i < 10; i++) { h3.set(Pets.randomPet()); System.out.println(i + 1 + " " + h3.get()); } } }
521
0.508637
0.481766
19
26.421053
17.957012
61
false
false
0
0
0
0
0
0
0.684211
false
false
10
f91b7e2d7924db63df1b977a5b4a3ec71712bce1
21,835,613,770,912
5336621f468044662f5db991e01b6a63d1747527
/JavaCourse/src/bmwMouloud/Car.java
63bb899544e13488b6c6ad0b9094c2c7d500cfd5
[]
no_license
mouloudwissam/firstPractice
https://github.com/mouloudwissam/firstPractice
fc5e357a2e9ad3c20733e7c538e70e52384f46bc
21efae7fd7a0b141c0cb6f8be5fbdfbed9ca4add
refs/heads/master
2020-07-13T11:12:10.270000
2019-08-29T03:21:09
2019-08-29T03:21:09
205,071,556
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package bmwMouloud; public class Car { public int model; public float price; public short max_speed; public int Sum(int a,int b) { int x =Sum(12,13); int y =Sum(13,14); System.out.print(x); System.out.print(x*y); return a*b; } }
UTF-8
Java
257
java
Car.java
Java
[]
null
[]
package bmwMouloud; public class Car { public int model; public float price; public short max_speed; public int Sum(int a,int b) { int x =Sum(12,13); int y =Sum(13,14); System.out.print(x); System.out.print(x*y); return a*b; } }
257
0.626459
0.595331
14
16.5
8.894219
30
false
false
0
0
0
0
0
0
1.928571
false
false
10
f23fb997b8e84bb9fadda766c6417a89f98df795
3,015,067,043,208
75962c018572404bba808afba3ff56a748436d4c
/Programming/Java/sem4/Lab11/src/bsu/fpmi/artsiushkevich/window/Sound.java
693daf26b980289d90968a49fd8befc8f91e1490
[]
no_license
thekirjava/BSU
https://github.com/thekirjava/BSU
0f313df3ff9dda3df37efeeee813fbfd466a977e
33d56c9adc9b6873f2bb360c0d7089dc458eb451
refs/heads/master
2021-11-20T14:07:55.287000
2021-10-17T19:37:07
2021-10-17T19:37:07
220,980,538
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package bsu.fpmi.artsiushkevich.window; import javax.sound.sampled.*; import java.io.File; import java.io.IOException; public class Sound { Clip nomNom; Clip newGame; Clip death; boolean stopped; public Sound() { stopped = true; AudioInputStream audioIn; try { audioIn = AudioSystem.getAudioInputStream(new File("sounds/nomnom.wav")); nomNom = AudioSystem.getClip(); nomNom.open(audioIn); audioIn = AudioSystem.getAudioInputStream(new File("sounds/newGame.wav")); newGame = AudioSystem.getClip(); newGame.open(audioIn); audioIn = AudioSystem.getAudioInputStream(new File("sounds/death.wav")); death = AudioSystem.getClip(); death.open(audioIn); } catch (LineUnavailableException | IOException | UnsupportedAudioFileException e) { e.printStackTrace(); } } public void nomNom() { if (!stopped) { return; } stopped = false; nomNom.stop(); nomNom.setFramePosition(0); nomNom.loop(Clip.LOOP_CONTINUOUSLY); } public void nomNomStop() { stopped = true; nomNom.stop(); nomNom.setFramePosition(0); } public void newGame() { newGame.stop(); newGame.setFramePosition(0); newGame.start(); } public void death() { death.stop(); death.setFramePosition(0); death.start(); } }
UTF-8
Java
1,514
java
Sound.java
Java
[]
null
[]
package bsu.fpmi.artsiushkevich.window; import javax.sound.sampled.*; import java.io.File; import java.io.IOException; public class Sound { Clip nomNom; Clip newGame; Clip death; boolean stopped; public Sound() { stopped = true; AudioInputStream audioIn; try { audioIn = AudioSystem.getAudioInputStream(new File("sounds/nomnom.wav")); nomNom = AudioSystem.getClip(); nomNom.open(audioIn); audioIn = AudioSystem.getAudioInputStream(new File("sounds/newGame.wav")); newGame = AudioSystem.getClip(); newGame.open(audioIn); audioIn = AudioSystem.getAudioInputStream(new File("sounds/death.wav")); death = AudioSystem.getClip(); death.open(audioIn); } catch (LineUnavailableException | IOException | UnsupportedAudioFileException e) { e.printStackTrace(); } } public void nomNom() { if (!stopped) { return; } stopped = false; nomNom.stop(); nomNom.setFramePosition(0); nomNom.loop(Clip.LOOP_CONTINUOUSLY); } public void nomNomStop() { stopped = true; nomNom.stop(); nomNom.setFramePosition(0); } public void newGame() { newGame.stop(); newGame.setFramePosition(0); newGame.start(); } public void death() { death.stop(); death.setFramePosition(0); death.start(); } }
1,514
0.581242
0.5786
56
26.035715
20.839493
92
false
false
0
0
0
0
0
0
0.642857
false
false
10
93fec4bbca5028c2c1bc0d9df29dd3f2a9dc679b
10,161,892,629,522
814f909c29d02de5fcd6142af2d1365a6d36f73e
/src/org/team3128/autonomous/programs/FarCanGrabAuto.java
a01471d749c08a9627e6421d54d3242a21dd206e
[]
no_license
Team3128/robot-TheClawwww
https://github.com/Team3128/robot-TheClawwww
d4257de712feb6290213e053b81b2c881cbd17e7
64a853d937cf5a8ed0788b905921fcf9d4667287
refs/heads/master
2020-04-06T07:12:45.242000
2016-10-02T23:27:47
2016-10-02T23:27:47
55,358,772
0
1
null
false
2016-09-02T22:57:01
2016-04-03T17:20:55
2016-04-03T17:25:14
2016-09-02T22:57:00
26
0
0
0
Java
null
null
package org.team3128.autonomous.programs; import org.team3128.autonomous.commands.CmdToteGrab; import org.team3128.common.autonomous.primitives.CmdDelay; import org.team3128.common.autonomous.primitives.CmdLog; import org.team3128.common.drive.TankDrive; import org.team3128.common.hardware.motor.MotorGroup; import org.team3128.mechanisms.ClawArm; import edu.wpi.first.wpilibj.command.CommandGroup; public class FarCanGrabAuto extends CommandGroup { public FarCanGrabAuto(TankDrive drive, ClawArm arm, MotorGroup frontHook, boolean grabTote) { addSequential(arm.new CmdArmAngles(46, 280, 11, 5000));//81 addSequential(arm.new CmdOpenClaw(1400)); addSequential(new CmdLog("Opening Claw")); addSequential(arm.new CmdArmAngles(46, 145, 10, 7500));//81 addSequential(new CmdDelay(4000)); addSequential(new CmdLog("Driving To Can")); addSequential(drive.new CmdMoveForward(27, 2000, true)); addSequential(new CmdLog("Closing Claw")); addSequential(arm.new CmdCloseClaw(2000)); if(grabTote) { addSequential(new CmdLog("Grabbing Tote")); addSequential(new CmdToteGrab(frontHook, 750)); } addSequential(arm.new CmdArmAngles(46, 230, 5, 2500));//85 addSequential(new CmdDelay(2000)); addSequential(new CmdLog("Backing Up")); addSequential(drive.new CmdMoveForward(-200, 10000, true)); } }
UTF-8
Java
1,434
java
FarCanGrabAuto.java
Java
[]
null
[]
package org.team3128.autonomous.programs; import org.team3128.autonomous.commands.CmdToteGrab; import org.team3128.common.autonomous.primitives.CmdDelay; import org.team3128.common.autonomous.primitives.CmdLog; import org.team3128.common.drive.TankDrive; import org.team3128.common.hardware.motor.MotorGroup; import org.team3128.mechanisms.ClawArm; import edu.wpi.first.wpilibj.command.CommandGroup; public class FarCanGrabAuto extends CommandGroup { public FarCanGrabAuto(TankDrive drive, ClawArm arm, MotorGroup frontHook, boolean grabTote) { addSequential(arm.new CmdArmAngles(46, 280, 11, 5000));//81 addSequential(arm.new CmdOpenClaw(1400)); addSequential(new CmdLog("Opening Claw")); addSequential(arm.new CmdArmAngles(46, 145, 10, 7500));//81 addSequential(new CmdDelay(4000)); addSequential(new CmdLog("Driving To Can")); addSequential(drive.new CmdMoveForward(27, 2000, true)); addSequential(new CmdLog("Closing Claw")); addSequential(arm.new CmdCloseClaw(2000)); if(grabTote) { addSequential(new CmdLog("Grabbing Tote")); addSequential(new CmdToteGrab(frontHook, 750)); } addSequential(arm.new CmdArmAngles(46, 230, 5, 2500));//85 addSequential(new CmdDelay(2000)); addSequential(new CmdLog("Backing Up")); addSequential(drive.new CmdMoveForward(-200, 10000, true)); } }
1,434
0.715481
0.646443
40
34.849998
25.191814
95
false
false
0
0
0
0
0
0
1.425
false
false
10
0d55770506b47b80608f2e6bcc4b7e1878b866cd
12,730,283,121,399
e9609cc67cf0388d342f30a6da855641fc9b22d3
/Employees/src/employee/Employee.java
19487296b6818f92be7b49b48843020534311dda
[]
no_license
MatJackson/COMP-249-Assignment-4
https://github.com/MatJackson/COMP-249-Assignment-4
d169ed928e43918cd65520da5d7cbee78312d83a
acb580e29a1dd3d9605b9856b4f73c3dea4b9348
refs/heads/master
2017-12-03T13:39:01.958000
2017-04-10T04:44:42
2017-04-10T04:44:42
85,981,983
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// ----------------------------------------------------- // Assignment #4 // // Written by: Mathew Jackson - 27709315, Kevin Luu - 40037514 // ----------------------------------------------------- package employee; /** * Base Employee Class */ public abstract class Employee implements Cloneable, Ordered { // Global Variables private int employeeID; private String firstName; private String familyName; private String cityOfResidence; private int hireYear; // Constructors public Employee() { employeeID = 0; firstName = "N/A"; familyName = "N/A"; cityOfResidence = "N/A"; hireYear = 0; } public Employee(int employeeID, String firstName, String familyName, String cityOfResidence, int hireYear) { // Invokes setting methods to ensure proper implementation setEmployeeID(employeeID); setFirstName(firstName); setFamilyName(familyName); setCityOfResidence(cityOfResidence); setHireYear(hireYear); } // Accessors public int getEmployeeID() { return employeeID; } public String getFirstName() { return firstName; } public String getFamilyName() { return familyName; } public String getCityOfResidence() { return cityOfResidence; } public int getHireYear() { return hireYear; } // Mutators *************** modify all setters ******************* public void setEmployeeID(int employeeID) { this.employeeID = employeeID; } public void setFirstName(String firstName) { this.firstName = firstName; } public void setFamilyName(String familyName) { this.familyName = familyName; } public void setCityOfResidence(String cityOfResidence) { this.cityOfResidence = cityOfResidence; } public void setHireYear(int hireYear) { this.hireYear = hireYear; } //From the ordered interface public boolean precedes(Object otherObject){ if (otherObject == null) //check if the type Object is null return false; else if (! (otherObject instanceof Employee)) //check if the type Object is an instance of the Employee class return false; else{ Employee otherEmployee = (Employee) otherObject; if(getHireYear() == otherEmployee.getHireYear()){ System.out.println("Both of them were hired during the same year"); return false; } return (getHireYear() < otherEmployee.getHireYear()); } } public boolean follows(Object otherObject){ if (otherObject == null) //check if the type Object is null return false; else if (! (otherObject instanceof Employee)) //check if the type Object is an instance of the Employee class return false; else{ Employee otherEmployee = (Employee) otherObject; if(getHireYear() == otherEmployee.getHireYear()){ System.out.println("Both of them were hired during the same year"); return false; } return (getHireYear() > otherEmployee.getHireYear()); } } // toString, equals, clone public abstract String toString(); public abstract boolean equals(Object otherObject); public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { return null; } } }
UTF-8
Java
3,064
java
Employee.java
Java
[ { "context": "---------------\n// Assignment #4\n//\n// Written by: Mathew Jackson - 27709315, Kevin Luu - 40037514\n// -------------", "end": 106, "score": 0.9998412132263184, "start": 92, "tag": "NAME", "value": "Mathew Jackson" }, { "context": "nt #4\n//\n// Written by: Mathew Jackson - 27709315, Kevin Luu - 40037514\n// -----------------------------------", "end": 128, "score": 0.9998309016227722, "start": 119, "tag": "NAME", "value": "Kevin Luu" }, { "context": "ation\n\t\tsetEmployeeID(employeeID);\n\t\tsetFirstName(firstName);\n\t\tsetFamilyName(familyName);\n\t\tsetCityOfResiden", "end": 838, "score": 0.8605717420578003, "start": 829, "tag": "NAME", "value": "firstName" } ]
null
[]
// ----------------------------------------------------- // Assignment #4 // // Written by: <NAME> - 27709315, <NAME> - 40037514 // ----------------------------------------------------- package employee; /** * Base Employee Class */ public abstract class Employee implements Cloneable, Ordered { // Global Variables private int employeeID; private String firstName; private String familyName; private String cityOfResidence; private int hireYear; // Constructors public Employee() { employeeID = 0; firstName = "N/A"; familyName = "N/A"; cityOfResidence = "N/A"; hireYear = 0; } public Employee(int employeeID, String firstName, String familyName, String cityOfResidence, int hireYear) { // Invokes setting methods to ensure proper implementation setEmployeeID(employeeID); setFirstName(firstName); setFamilyName(familyName); setCityOfResidence(cityOfResidence); setHireYear(hireYear); } // Accessors public int getEmployeeID() { return employeeID; } public String getFirstName() { return firstName; } public String getFamilyName() { return familyName; } public String getCityOfResidence() { return cityOfResidence; } public int getHireYear() { return hireYear; } // Mutators *************** modify all setters ******************* public void setEmployeeID(int employeeID) { this.employeeID = employeeID; } public void setFirstName(String firstName) { this.firstName = firstName; } public void setFamilyName(String familyName) { this.familyName = familyName; } public void setCityOfResidence(String cityOfResidence) { this.cityOfResidence = cityOfResidence; } public void setHireYear(int hireYear) { this.hireYear = hireYear; } //From the ordered interface public boolean precedes(Object otherObject){ if (otherObject == null) //check if the type Object is null return false; else if (! (otherObject instanceof Employee)) //check if the type Object is an instance of the Employee class return false; else{ Employee otherEmployee = (Employee) otherObject; if(getHireYear() == otherEmployee.getHireYear()){ System.out.println("Both of them were hired during the same year"); return false; } return (getHireYear() < otherEmployee.getHireYear()); } } public boolean follows(Object otherObject){ if (otherObject == null) //check if the type Object is null return false; else if (! (otherObject instanceof Employee)) //check if the type Object is an instance of the Employee class return false; else{ Employee otherEmployee = (Employee) otherObject; if(getHireYear() == otherEmployee.getHireYear()){ System.out.println("Both of them were hired during the same year"); return false; } return (getHireYear() > otherEmployee.getHireYear()); } } // toString, equals, clone public abstract String toString(); public abstract boolean equals(Object otherObject); public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { return null; } } }
3,053
0.686031
0.67983
123
23.910568
24.285233
111
false
false
0
0
0
0
0
0
1.788618
false
false
10
c13700f6079414e0adcab30b785edec3dc5bb2c1
30,605,937,019,855
579465554107f88cf67c2716168e30e766bd62eb
/chatchat/src/com/example/chatchat/Chatting_toast2.java
8bb0ac320802bc91f88e88535c4e451ae49363e3
[]
no_license
yulyulyul/chatchat
https://github.com/yulyulyul/chatchat
3a821b06f90e3d6a8662ad07db603e827fd36cc9
5143e0ac1731eade239e2e86d9de67f985d6934b
refs/heads/master
2020-03-20T12:25:35.850000
2018-06-15T02:14:13
2018-06-15T02:14:13
137,429,777
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.chatchat; //import com.facebook.drawee.backends.pipeline.Fresco; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; public class Chatting_toast2 extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Fresco.initialize(this); setContentView(R.layout.activity_chatting_toast); } }
UTF-8
Java
436
java
Chatting_toast2.java
Java
[]
null
[]
package com.example.chatchat; //import com.facebook.drawee.backends.pipeline.Fresco; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; public class Chatting_toast2 extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Fresco.initialize(this); setContentView(R.layout.activity_chatting_toast); } }
436
0.795872
0.793578
17
24.647058
19.069351
54
false
false
0
0
0
0
0
0
1.058824
false
false
10
a5d6cc686bdb83dc5a035624e0929cc8c1edf990
4,552,665,402,081
a3b3d58a55105af1b2c5277b1500ab316fb0de37
/multiThread/src/ProducerAndConsumer/Producer.java
9023a9a81f711f081705d9a742eb43363deda37c
[]
no_license
Danieladu/MultiThread
https://github.com/Danieladu/MultiThread
eba80db337018c6bda557c474d1a60a00ac1ad57
8af032005fa0dc74a573165e0d71536f00314c20
refs/heads/master
2016-07-26T12:10:55.038000
2015-03-26T12:54:34
2015-03-26T12:54:34
32,922,484
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ProducerAndConsumer; public class Producer implements Runnable{ private resource r; private int pnumber ; public Producer(int pnumber,resource r) { this.r = r; this.pnumber = pnumber; } @Override public void run() { // TODO Auto-generated method stub r.produce(pnumber); } }
UTF-8
Java
333
java
Producer.java
Java
[]
null
[]
package ProducerAndConsumer; public class Producer implements Runnable{ private resource r; private int pnumber ; public Producer(int pnumber,resource r) { this.r = r; this.pnumber = pnumber; } @Override public void run() { // TODO Auto-generated method stub r.produce(pnumber); } }
333
0.648649
0.648649
22
13.136364
13.955434
42
false
false
0
0
0
0
0
0
1.272727
false
false
10
e081fc85656ab691f5cbe6d62155049bbe8dea03
32,409,823,258,496
2ec3df122f778c9887967a13740c5b9e9e45d09d
/.svn/pristine/90/90d7cee7bdec7f5ec94d21d9115d7608259ee7ba.svn-base
9d4aaeedbb006f4e2b8ecf1dd7ddd17c2127a93e
[]
no_license
passionsteve/stevemanager
https://github.com/passionsteve/stevemanager
a9fe68c96af4596283e6d2c9415a971487d74d02
af000cb20a1b380d2df91c207179c0ceb3c12cc8
refs/heads/master
2016-06-05T00:06:27.482000
2016-03-17T14:06:55
2016-03-17T14:06:55
54,121,331
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * BigstarExtractRewardRecordInfo.java * com.enmoli.showluck.bigstar.domain * Function: TODO * * ver date author * ────────────────────────────────── * Mar 4, 2014 Administrator * * Copyright (c) 2014, TNT All Rights Reserved. */ package com.enmoli.showluck.bigstar.domain; import java.util.Date; /** * ClassName:BigstarExtractRewardRecordInfo * Function: TODO ADD FUNCTION * Reason: TODO ADD REASON * * @author Administrator * @version * @since Ver 1.1 * @Date 2014 Mar 4, 2014 6:13:27 PM * * @see */ public class BigstarExtractRewardRecordInfo { private Integer id; private Integer uid; private String nickname; private Integer extractType; private String extractTypeName; private Integer extractTime; private Date extractDate; private Integer isPay; private Integer rewardId; private String rewardJson; private Integer payDiamond; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getUid() { return uid; } public void setUid(Integer uid) { this.uid = uid; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public Integer getExtractType() { return extractType; } public void setExtractType(Integer extractType) { this.extractType = extractType; } public Integer getExtractTime() { return extractTime; } public void setExtractTime(Integer extractTime) { this.extractTime = extractTime; } public Date getExtractDate() { return extractDate; } public void setExtractDate(Date extractDate) { this.extractDate = extractDate; } public Integer getIsPay() { return isPay; } public void setIsPay(Integer isPay) { this.isPay = isPay; } public Integer getRewardId() { return rewardId; } public void setRewardId(Integer rewardId) { this.rewardId = rewardId; } public String getRewardJson() { return rewardJson; } public void setRewardJson(String rewardJson) { this.rewardJson = rewardJson; } public Integer getPayDiamond() { return payDiamond; } public void setPayDiamond(Integer payDiamond) { this.payDiamond = payDiamond; } public String getExtractTypeName() { return extractTypeName; } public void setExtractTypeName(String extractTypeName) { this.extractTypeName = extractTypeName; } }
UTF-8
Java
2,815
90d7cee7bdec7f5ec94d21d9115d7608259ee7ba.svn-base
Java
[ { "context": "NCTION\n * Reason:\t TODO ADD REASON\n *\n * @author Administrator\n * @version \n * @since Ver 1.1\n * @Date\t 2014", "end": 467, "score": 0.9166517853736877, "start": 454, "tag": "NAME", "value": "Administrator" } ]
null
[]
/** * BigstarExtractRewardRecordInfo.java * com.enmoli.showluck.bigstar.domain * Function: TODO * * ver date author * ────────────────────────────────── * Mar 4, 2014 Administrator * * Copyright (c) 2014, TNT All Rights Reserved. */ package com.enmoli.showluck.bigstar.domain; import java.util.Date; /** * ClassName:BigstarExtractRewardRecordInfo * Function: TODO ADD FUNCTION * Reason: TODO ADD REASON * * @author Administrator * @version * @since Ver 1.1 * @Date 2014 Mar 4, 2014 6:13:27 PM * * @see */ public class BigstarExtractRewardRecordInfo { private Integer id; private Integer uid; private String nickname; private Integer extractType; private String extractTypeName; private Integer extractTime; private Date extractDate; private Integer isPay; private Integer rewardId; private String rewardJson; private Integer payDiamond; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getUid() { return uid; } public void setUid(Integer uid) { this.uid = uid; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public Integer getExtractType() { return extractType; } public void setExtractType(Integer extractType) { this.extractType = extractType; } public Integer getExtractTime() { return extractTime; } public void setExtractTime(Integer extractTime) { this.extractTime = extractTime; } public Date getExtractDate() { return extractDate; } public void setExtractDate(Date extractDate) { this.extractDate = extractDate; } public Integer getIsPay() { return isPay; } public void setIsPay(Integer isPay) { this.isPay = isPay; } public Integer getRewardId() { return rewardId; } public void setRewardId(Integer rewardId) { this.rewardId = rewardId; } public String getRewardJson() { return rewardJson; } public void setRewardJson(String rewardJson) { this.rewardJson = rewardJson; } public Integer getPayDiamond() { return payDiamond; } public void setPayDiamond(Integer payDiamond) { this.payDiamond = payDiamond; } public String getExtractTypeName() { return extractTypeName; } public void setExtractTypeName(String extractTypeName) { this.extractTypeName = extractTypeName; } }
2,815
0.613115
0.604007
131
19.954199
15.75425
58
false
false
0
0
0
0
0
0
0.366412
false
false
10
7a486c6f235311d30fc9b7afeaac194c5a402a93
27,075,473,865,325
2c72764f1c55608944ca7c4e70d35face8fe43b1
/src/main/java/com/publicvm/siburarenda/rest/ManageRestController.java
44b91d16d86fadf9930fb05b9f5b81e4c5554295
[]
no_license
SiburArenda/backend
https://github.com/SiburArenda/backend
fc8c63345c37e1ddd28649bdc8689541db311c6c
871c1e2725cb119f8146297cfba87ba314bfa5b9
refs/heads/master
2023-04-28T06:02:07.542000
2020-08-04T16:20:16
2020-08-04T16:20:16
252,676,404
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.publicvm.siburarenda.rest; import com.publicvm.siburarenda.dto.EventDto; import com.publicvm.siburarenda.dto.UserDto; import com.publicvm.siburarenda.model.User; import com.publicvm.siburarenda.service.EventService; import com.publicvm.siburarenda.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; /** * REST controller user connected requestst. * * @author Valera * @version 1.0 */ @RestController @RequestMapping(value = "/api/manage/") public class ManageRestController { private final UserService userService; private final EventService eventService; @Autowired public ManageRestController(UserService userService, EventService eventService) { this.userService = userService; this.eventService = eventService; } @GetMapping(value = "events/accepted") public ResponseEntity<List<EventDto>> getAcceptedEvents() { return ResponseEntity.ok(eventService.getAcceptedEvents() .stream() .map(EventDto::toDto) .collect(Collectors.toList())); } @GetMapping(value = "events/acceptable") public ResponseEntity<List<EventDto>> getNotAcceptedEvents() { return ResponseEntity.ok(eventService.getNotAcceptedEvents() .stream() .map(EventDto::toDto) .collect(Collectors.toList())); } @GetMapping(value = "users") public ResponseEntity<List<UserDto>> getUsers() { List<User> users = userService.getAll(); users.sort(Comparator.comparing(User::eventsCount, Comparator.reverseOrder())); return ResponseEntity.ok(users .stream() .map(UserDto::fromUser) .collect(Collectors.toList())); } }
UTF-8
Java
1,974
java
ManageRestController.java
Java
[ { "context": "controller user connected requestst.\n *\n * @author Valera\n * @version 1.0\n */\n\n@RestController\n@RequestMapp", "end": 602, "score": 0.9995926022529602, "start": 596, "tag": "NAME", "value": "Valera" } ]
null
[]
package com.publicvm.siburarenda.rest; import com.publicvm.siburarenda.dto.EventDto; import com.publicvm.siburarenda.dto.UserDto; import com.publicvm.siburarenda.model.User; import com.publicvm.siburarenda.service.EventService; import com.publicvm.siburarenda.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; /** * REST controller user connected requestst. * * @author Valera * @version 1.0 */ @RestController @RequestMapping(value = "/api/manage/") public class ManageRestController { private final UserService userService; private final EventService eventService; @Autowired public ManageRestController(UserService userService, EventService eventService) { this.userService = userService; this.eventService = eventService; } @GetMapping(value = "events/accepted") public ResponseEntity<List<EventDto>> getAcceptedEvents() { return ResponseEntity.ok(eventService.getAcceptedEvents() .stream() .map(EventDto::toDto) .collect(Collectors.toList())); } @GetMapping(value = "events/acceptable") public ResponseEntity<List<EventDto>> getNotAcceptedEvents() { return ResponseEntity.ok(eventService.getNotAcceptedEvents() .stream() .map(EventDto::toDto) .collect(Collectors.toList())); } @GetMapping(value = "users") public ResponseEntity<List<UserDto>> getUsers() { List<User> users = userService.getAll(); users.sort(Comparator.comparing(User::eventsCount, Comparator.reverseOrder())); return ResponseEntity.ok(users .stream() .map(UserDto::fromUser) .collect(Collectors.toList())); } }
1,974
0.693516
0.692503
62
30.838709
23.210949
87
false
false
0
0
0
0
0
0
0.370968
false
false
10
d61dcf8aff134354099e524795ed640d7f8c0a40
3,083,786,527,734
60d3f34d3c79f720799d2ac7b6f3fa1b15b5344b
/src/oop/overloading/Calculation2.java
7264f28eedcaecd8ca43cbf2150d47ca50838006
[]
no_license
yrojha4ever/JavaStud
https://github.com/yrojha4ever/JavaStud
a0718ced013bb20bdead4b5f33af331523e5e6fe
8b38dd73eee9eddf0e6e8cb4ee03ea916013eef3
refs/heads/master
2023-04-13T05:43:32.014000
2023-04-04T09:29:56
2023-04-04T09:29:56
41,842,465
323
130
null
null
null
null
null
null
null
null
null
null
null
null
null
package oop.overloading; public class Calculation2 { int sum( int a, int b ) { return ( a + b ); } int sum( double a, double b ) { int r = ( int ) ( a + b ); return r; } int sum( String a, String b ) { int r = Integer.valueOf( a ) + Integer.valueOf( b ); return r; } public static void main( String args[] ) { Calculation2 obj = new Calculation2( ); int r = obj.sum( 10.5, 10.5 ); System.out.println( r ); System.out.println( obj.sum( 10.5, 10.5 ) ); System.out.println( obj.sum( "55", "44" ) ); System.out.println( obj.sum( 100, 100 ) ); } }
UTF-8
Java
615
java
Calculation2.java
Java
[]
null
[]
package oop.overloading; public class Calculation2 { int sum( int a, int b ) { return ( a + b ); } int sum( double a, double b ) { int r = ( int ) ( a + b ); return r; } int sum( String a, String b ) { int r = Integer.valueOf( a ) + Integer.valueOf( b ); return r; } public static void main( String args[] ) { Calculation2 obj = new Calculation2( ); int r = obj.sum( 10.5, 10.5 ); System.out.println( r ); System.out.println( obj.sum( 10.5, 10.5 ) ); System.out.println( obj.sum( "55", "44" ) ); System.out.println( obj.sum( 100, 100 ) ); } }
615
0.549594
0.508943
32
17.21875
17.90554
54
false
false
0
0
0
0
0
0
1.53125
false
false
10
7b9e825422d96eb3b715c7acc3e19130745fb2d5
18,992,345,435,909
7c24d65caa39969d1a8285d2ab3c040d290aa16c
/src/main/java/com/alibaba/jingxun/AutoHandler.java
dbf6d82687995291449cdc268fe68274c4aafa2f
[]
no_license
NiX-Team/autoMapping
https://github.com/NiX-Team/autoMapping
83c3c3d4575792d31eabc39aaaef60c9790223a8
b16a04f00e151621fba50ca002a98dbfc9a4809e
refs/heads/master
2020-03-19T14:11:47.266000
2018-06-11T03:56:23
2018-06-11T03:56:23
136,613,009
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.alibaba.jingxun; import freemaker.XmlService; import freemaker.util.FreemarkerRoot; import freemaker.util.log.LogKit; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.*; /** * @author Kiss * @date 2018/06/08 10:59 * 自动生成管理 */ public class AutoHandler { private final File configFile; private final ConfigurationFileHandler.FileType fileType; private final String ftl; private ConfigParse configParse; private final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(0, 20, 0, TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>(), new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setName("auto-mapping"); return t; } }); private CountDownLatch countDownLatch = null; /** * 需要自动生成mapping.xml的对象列表 * */ private List<Model> models = new ArrayList<Model>(); public AutoHandler(File configFile, ConfigurationFileHandler.FileType fileType,String ftl) { this.configFile = configFile; this.fileType = fileType; this.ftl = ftl; } public void start() throws Exception { switch (fileType) { case XML:configParse = new XmlConfigParse();break; case YML:configParse = new XmlConfigParse();break; case PROPERTIES:configParse = new XmlConfigParse();break; case OTHER:return; default:return; } models = configParse.parse(configFile); LogKit.info("需要自动生成的对象:"); LogKit.info(Arrays.toString(models.toArray())); countDownLatch = new CountDownLatch(models.size()); File ftlDir = new File("./.auto"); File file = new File("./.auto/mapping_have_header.ftl"); File file1 = new File("./.auto/mapping_no_header.ftl"); if (!ftlDir.mkdir() || !file.createNewFile() || !file1.createNewFile()) { return; } writeFile(file,haveHeaderFtl); writeFile(file1,noHaveHeaderFtl); try { final FreemarkerRoot freemakerRoot = new FreemarkerRoot(ftl,ftlDir); for (Model model:models) { autoOneModel(model,freemakerRoot); } countDownLatch.await(); }finally { file.delete(); file1.delete(); ftlDir.deleteOnExit(); } } private void writeFile(File file,String content) throws IOException { FileWriter writer = new FileWriter(file); writer.write(content); writer.flush(); writer.close(); } /** * 自动生成一个对象的mapping文件 * */ private void autoOneModel(final Model model,final FreemarkerRoot freemakerRoot) { LogKit.info("开始自动生成mapping:" + model); threadPoolExecutor.execute(new Runnable() { @Override public void run() { try { XmlService.startGenerateMappingXml(model.getClazz(), model.getMappingFileName(), model.getTable(), freemakerRoot); }catch (Exception e) { LogKit.error(e.getMessage(),e); } finally { countDownLatch.countDown(); } } }); } private final String haveHeaderFtl = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">\n" + "<mapper namespace=\"namespace\">\n" + " <resultMap id=\"BaseResultMap\" type=\"${oneself.type}\">\n" + " <#list oneself.params as param>\n" + " <#if param.property == \"id\" >\n" + " <id column=\"${param.column}\" property=\"${param.property}\" jdbcType=\"${param.jdbcType}\"/>\n" + " <#else >\n" + " <result column=\"${param.column}\" property=\"${param.property}\" jdbcType=\"${param.jdbcType}\"/>\n" + " </#if>\n" + " </#list>\n" + " <#if others?has_content>\n" + " <#list others as other>\n" + " <#--<#if other.columnType == 1>-->\n" + " <#--<association property=\"${other.name}\" javaType=\"${other.type}\" column=\"id\"/>-->\n" + " <#--</#if>-->\n" + " <#--<#if other.columnType == 2>-->\n" + " <#--<collection property=\"${other.name}\" ofType=\"${other.type}\" column=\"id\"/>-->\n" + " <#--</#if>-->\n" + " </#list>\n" + " </#if>\n" + " </resultMap>\n" + " <insert id=\"insert\" parameterType=\"${oneself.type}\">\n" + " insert into `${table}`\n" + " <trim prefix=\"(\" suffix=\")\" suffixOverrides=\",\">\n" + " <#list oneself.params as param>\n" + " <if test=\"${param.property} != null\">\n" + " `${param.column}`,\n" + " </if>\n" + " </#list>\n" + " </trim>\n" + " <trim prefix=\"values (\" suffix=\")\" suffixOverrides=\",\">\n" + " <#list oneself.params as param>\n" + " <if test=\"${param.property} != null\">\n" + " ${r\"#{\"}${param.column},jdbcType=${param.jdbcType}${r\"}\"},\n" + " </if>\n" + " </#list>\n" + " </trim>\n" + " </insert>\n" + " <delete id=\"delete\" parameterType=\"java.lang.Integer\">\n" + " delete from `${table}` where id = ${r\"#{\"}id,jdbcType=INTEGER${r\"}\"}\n" + " </delete>\n" + " <update id=\"update\" parameterType=\"${oneself.type}\">\n" + " update `${table}`\n" + " set\n" + " <trim prefix=\"\" suffix=\"\" suffixOverrides=\",\">\n" + " <#list oneself.params as param>\n" + " <if test=\"${param.property} != null\">\n" + " `${param.column}` = ${r\"#{\"}${param.property},jdbcType=${param.jdbcType}${r\"}\"},\n" + " </if>\n" + " </#list>\n" + " </trim>\n" + " where id = ${r\"#{\"}id,jdbcType=INTEGER${r\"}\"}\n" + " </update>\n" + " <select id=\"select\" parameterType=\"int\" resultMap=\"BaseResultMap\">\n" + " select * from `${table}` where id = ${r\"#{\"}id,jdbcType=INTEGER${r\"}\"}\n" + " </select>\n" + "\n" + " <select id=\"maxId\" resultType=\"Integer\">\n" + " select max(`id`) from `${table}`;\n" + " </select>\n" + "\n" + " <select id=\"count\" resultType=\"Long\">\n" + " select count(`id`) from `${table}`;\n" + " </select>\n" + "\n" + " <select id=\"findByOneField\" resultMap=\"BaseResultMap\">\n" + " select * from `${table}` where `@{field}` = ${r\"#{\"}value,jdbcType=INTEGER${r\"}\"}\n" + " </select>\n" + "\n" + " <select id=\"list\" resultMap=\"BaseResultMap\">\n" + " select `${table}`.* from @{tables}\n" + " <if test=\"conditions != null\">\n" + " where @{conditions}\n" + " </if>\n" + " <if test=\"order != null and sort != null\">\n" + " order by @{order} @{sort}\n" + " </if>\n" + " <if test=\"offset != null\">\n" + " limit ${r\"#{offset,jdbcType=INTEGER}\"},${r\"#{limit,jdbcType=INTEGER}\"}\n" + " </if>\n" + " </select>\n" + "\n" + " <select id=\"selectLazy\" resultMap=\"BaseResultMap\">\n" + " select * from `${table}` where id = ${r\"#{\"}${table},jdbcType=INTEGER${r\"}\"}\n" + " </select>\n" + "</mapper>"; private final String noHaveHeaderFtl = "<resultMap id=\"BaseResultMap\" type=\"${oneself.type}\">\n" + " <#list oneself.params as param>\n" + " <#if param.property == \"id\" >\n" + " <id column=\"${param.column}\" property=\"${param.property}\" jdbcType=\"${param.jdbcType}\"/>\n" + " <#else >\n" + " <result column=\"${param.column}\" property=\"${param.property}\" jdbcType=\"${param.jdbcType}\"/>\n" + " </#if>\n" + " </#list>\n" + " <#if others?has_content>\n" + " <#list others as other>\n" + " <#--<#if other.columnType == 1>-->\n" + " <#--<association property=\"${other.name}\" javaType=\"${other.type}\" column=\"id\"/>-->\n" + " <#--</#if>-->\n" + " <#--<#if other.columnType == 2>-->\n" + " <#--<collection property=\"${other.name}\" ofType=\"${other.type}\" column=\"id\"/>-->\n" + " <#--</#if>-->\n" + " </#list>\n" + " </#if>\n" + "</resultMap>\n" + " <insert id=\"insert\" parameterType=\"${oneself.type}\">\n" + " insert into `${table}`\n" + " <trim prefix=\"(\" suffix=\")\" suffixOverrides=\",\">\n" + " <#list oneself.params as param>\n" + " <if test=\"${param.property} != null\">\n" + " `${param.column}`,\n" + " </if>\n" + " </#list>\n" + " </trim>\n" + " <trim prefix=\"values (\" suffix=\")\" suffixOverrides=\",\">\n" + " <#list oneself.params as param>\n" + " <if test=\"${param.property} != null\">\n" + " ${r\"#{\"}${param.column},jdbcType=${param.jdbcType}${r\"}\"},\n" + " </if>\n" + " </#list>\n" + " </trim>\n" + " </insert>\n" + " <delete id=\"delete\" parameterType=\"java.lang.Integer\">\n" + " delete from `${table}` where id = ${r\"#{\"}id,jdbcType=INTEGER${r\"}\"}\n" + " </delete>\n" + " <update id=\"update\" parameterType=\"${oneself.type}\">\n" + " update `${table}`\n" + " set\n" + " <trim prefix=\"\" suffix=\"\" suffixOverrides=\",\">\n" + " <#list oneself.params as param>\n" + " <if test=\"${param.property} != null\">\n" + " `${param.column}` = ${r\"#{\"}${param.property},jdbcType=${param.jdbcType}${r\"}\"},\n" + " </if>\n" + " </#list>\n" + " </trim>\n" + " where id = ${r\"#{\"}id,jdbcType=INTEGER${r\"}\"}\n" + " </update>\n" + " <select id=\"select\" parameterType=\"int\" resultMap=\"BaseResultMap\">\n" + " select * from `${table}` where id = ${r\"#{\"}id,jdbcType=INTEGER${r\"}\"}\n" + " </select>\n" + " <select id=\"maxId\" resultType=\"Integer\">\n" + " select max(`id`) from `${table}`;\n" + " </select>\n" + "\n" + " <select id=\"count\" resultType=\"Long\">\n" + " select count(`id`) from `${table}`;\n" + " </select>\n" + " <select id=\"findByOneField\" resultMap=\"BaseResultMap\">\n" + " select * from `${table}` where `@{field}` = ${r\"#{\"}value,jdbcType=INTEGER${r\"}\"}\n" + " </select>\n" + " <select id=\"list\" resultMap=\"BaseResultMap\">\n" + " select `${table}`.* from @{tables}\n" + " <if test=\"conditions != null\">\n" + " where @{conditions}\n" + " </if>\n" + " <if test=\"order != null and sort != null\">\n" + " order by @{order} @{sort}\n" + " </if>\n" + " <if test=\"offset != null\">\n" + " limit ${r\"#{offset,jdbcType=INTEGER}\"},${r\"#{limit,jdbcType=INTEGER}\"}\n" + " </if>\n" + " </select>\n" + " <select id=\"selectLazy\" resultMap=\"BaseResultMap\">\n" + " select * from `${table}` where id = ${r\"#{\"}${table},jdbcType=INTEGER${r\"}\"}\n" + " </select>"; }
UTF-8
Java
13,224
java
AutoHandler.java
Java
[ { "context": "st;\nimport java.util.concurrent.*;\n\n/**\n * @author Kiss\n * @date 2018/06/08 10:59\n * 自动生成管理\n */\npublic cl", "end": 335, "score": 0.9988381862640381, "start": 331, "tag": "USERNAME", "value": "Kiss" } ]
null
[]
package com.alibaba.jingxun; import freemaker.XmlService; import freemaker.util.FreemarkerRoot; import freemaker.util.log.LogKit; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.*; /** * @author Kiss * @date 2018/06/08 10:59 * 自动生成管理 */ public class AutoHandler { private final File configFile; private final ConfigurationFileHandler.FileType fileType; private final String ftl; private ConfigParse configParse; private final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(0, 20, 0, TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>(), new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setName("auto-mapping"); return t; } }); private CountDownLatch countDownLatch = null; /** * 需要自动生成mapping.xml的对象列表 * */ private List<Model> models = new ArrayList<Model>(); public AutoHandler(File configFile, ConfigurationFileHandler.FileType fileType,String ftl) { this.configFile = configFile; this.fileType = fileType; this.ftl = ftl; } public void start() throws Exception { switch (fileType) { case XML:configParse = new XmlConfigParse();break; case YML:configParse = new XmlConfigParse();break; case PROPERTIES:configParse = new XmlConfigParse();break; case OTHER:return; default:return; } models = configParse.parse(configFile); LogKit.info("需要自动生成的对象:"); LogKit.info(Arrays.toString(models.toArray())); countDownLatch = new CountDownLatch(models.size()); File ftlDir = new File("./.auto"); File file = new File("./.auto/mapping_have_header.ftl"); File file1 = new File("./.auto/mapping_no_header.ftl"); if (!ftlDir.mkdir() || !file.createNewFile() || !file1.createNewFile()) { return; } writeFile(file,haveHeaderFtl); writeFile(file1,noHaveHeaderFtl); try { final FreemarkerRoot freemakerRoot = new FreemarkerRoot(ftl,ftlDir); for (Model model:models) { autoOneModel(model,freemakerRoot); } countDownLatch.await(); }finally { file.delete(); file1.delete(); ftlDir.deleteOnExit(); } } private void writeFile(File file,String content) throws IOException { FileWriter writer = new FileWriter(file); writer.write(content); writer.flush(); writer.close(); } /** * 自动生成一个对象的mapping文件 * */ private void autoOneModel(final Model model,final FreemarkerRoot freemakerRoot) { LogKit.info("开始自动生成mapping:" + model); threadPoolExecutor.execute(new Runnable() { @Override public void run() { try { XmlService.startGenerateMappingXml(model.getClazz(), model.getMappingFileName(), model.getTable(), freemakerRoot); }catch (Exception e) { LogKit.error(e.getMessage(),e); } finally { countDownLatch.countDown(); } } }); } private final String haveHeaderFtl = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">\n" + "<mapper namespace=\"namespace\">\n" + " <resultMap id=\"BaseResultMap\" type=\"${oneself.type}\">\n" + " <#list oneself.params as param>\n" + " <#if param.property == \"id\" >\n" + " <id column=\"${param.column}\" property=\"${param.property}\" jdbcType=\"${param.jdbcType}\"/>\n" + " <#else >\n" + " <result column=\"${param.column}\" property=\"${param.property}\" jdbcType=\"${param.jdbcType}\"/>\n" + " </#if>\n" + " </#list>\n" + " <#if others?has_content>\n" + " <#list others as other>\n" + " <#--<#if other.columnType == 1>-->\n" + " <#--<association property=\"${other.name}\" javaType=\"${other.type}\" column=\"id\"/>-->\n" + " <#--</#if>-->\n" + " <#--<#if other.columnType == 2>-->\n" + " <#--<collection property=\"${other.name}\" ofType=\"${other.type}\" column=\"id\"/>-->\n" + " <#--</#if>-->\n" + " </#list>\n" + " </#if>\n" + " </resultMap>\n" + " <insert id=\"insert\" parameterType=\"${oneself.type}\">\n" + " insert into `${table}`\n" + " <trim prefix=\"(\" suffix=\")\" suffixOverrides=\",\">\n" + " <#list oneself.params as param>\n" + " <if test=\"${param.property} != null\">\n" + " `${param.column}`,\n" + " </if>\n" + " </#list>\n" + " </trim>\n" + " <trim prefix=\"values (\" suffix=\")\" suffixOverrides=\",\">\n" + " <#list oneself.params as param>\n" + " <if test=\"${param.property} != null\">\n" + " ${r\"#{\"}${param.column},jdbcType=${param.jdbcType}${r\"}\"},\n" + " </if>\n" + " </#list>\n" + " </trim>\n" + " </insert>\n" + " <delete id=\"delete\" parameterType=\"java.lang.Integer\">\n" + " delete from `${table}` where id = ${r\"#{\"}id,jdbcType=INTEGER${r\"}\"}\n" + " </delete>\n" + " <update id=\"update\" parameterType=\"${oneself.type}\">\n" + " update `${table}`\n" + " set\n" + " <trim prefix=\"\" suffix=\"\" suffixOverrides=\",\">\n" + " <#list oneself.params as param>\n" + " <if test=\"${param.property} != null\">\n" + " `${param.column}` = ${r\"#{\"}${param.property},jdbcType=${param.jdbcType}${r\"}\"},\n" + " </if>\n" + " </#list>\n" + " </trim>\n" + " where id = ${r\"#{\"}id,jdbcType=INTEGER${r\"}\"}\n" + " </update>\n" + " <select id=\"select\" parameterType=\"int\" resultMap=\"BaseResultMap\">\n" + " select * from `${table}` where id = ${r\"#{\"}id,jdbcType=INTEGER${r\"}\"}\n" + " </select>\n" + "\n" + " <select id=\"maxId\" resultType=\"Integer\">\n" + " select max(`id`) from `${table}`;\n" + " </select>\n" + "\n" + " <select id=\"count\" resultType=\"Long\">\n" + " select count(`id`) from `${table}`;\n" + " </select>\n" + "\n" + " <select id=\"findByOneField\" resultMap=\"BaseResultMap\">\n" + " select * from `${table}` where `@{field}` = ${r\"#{\"}value,jdbcType=INTEGER${r\"}\"}\n" + " </select>\n" + "\n" + " <select id=\"list\" resultMap=\"BaseResultMap\">\n" + " select `${table}`.* from @{tables}\n" + " <if test=\"conditions != null\">\n" + " where @{conditions}\n" + " </if>\n" + " <if test=\"order != null and sort != null\">\n" + " order by @{order} @{sort}\n" + " </if>\n" + " <if test=\"offset != null\">\n" + " limit ${r\"#{offset,jdbcType=INTEGER}\"},${r\"#{limit,jdbcType=INTEGER}\"}\n" + " </if>\n" + " </select>\n" + "\n" + " <select id=\"selectLazy\" resultMap=\"BaseResultMap\">\n" + " select * from `${table}` where id = ${r\"#{\"}${table},jdbcType=INTEGER${r\"}\"}\n" + " </select>\n" + "</mapper>"; private final String noHaveHeaderFtl = "<resultMap id=\"BaseResultMap\" type=\"${oneself.type}\">\n" + " <#list oneself.params as param>\n" + " <#if param.property == \"id\" >\n" + " <id column=\"${param.column}\" property=\"${param.property}\" jdbcType=\"${param.jdbcType}\"/>\n" + " <#else >\n" + " <result column=\"${param.column}\" property=\"${param.property}\" jdbcType=\"${param.jdbcType}\"/>\n" + " </#if>\n" + " </#list>\n" + " <#if others?has_content>\n" + " <#list others as other>\n" + " <#--<#if other.columnType == 1>-->\n" + " <#--<association property=\"${other.name}\" javaType=\"${other.type}\" column=\"id\"/>-->\n" + " <#--</#if>-->\n" + " <#--<#if other.columnType == 2>-->\n" + " <#--<collection property=\"${other.name}\" ofType=\"${other.type}\" column=\"id\"/>-->\n" + " <#--</#if>-->\n" + " </#list>\n" + " </#if>\n" + "</resultMap>\n" + " <insert id=\"insert\" parameterType=\"${oneself.type}\">\n" + " insert into `${table}`\n" + " <trim prefix=\"(\" suffix=\")\" suffixOverrides=\",\">\n" + " <#list oneself.params as param>\n" + " <if test=\"${param.property} != null\">\n" + " `${param.column}`,\n" + " </if>\n" + " </#list>\n" + " </trim>\n" + " <trim prefix=\"values (\" suffix=\")\" suffixOverrides=\",\">\n" + " <#list oneself.params as param>\n" + " <if test=\"${param.property} != null\">\n" + " ${r\"#{\"}${param.column},jdbcType=${param.jdbcType}${r\"}\"},\n" + " </if>\n" + " </#list>\n" + " </trim>\n" + " </insert>\n" + " <delete id=\"delete\" parameterType=\"java.lang.Integer\">\n" + " delete from `${table}` where id = ${r\"#{\"}id,jdbcType=INTEGER${r\"}\"}\n" + " </delete>\n" + " <update id=\"update\" parameterType=\"${oneself.type}\">\n" + " update `${table}`\n" + " set\n" + " <trim prefix=\"\" suffix=\"\" suffixOverrides=\",\">\n" + " <#list oneself.params as param>\n" + " <if test=\"${param.property} != null\">\n" + " `${param.column}` = ${r\"#{\"}${param.property},jdbcType=${param.jdbcType}${r\"}\"},\n" + " </if>\n" + " </#list>\n" + " </trim>\n" + " where id = ${r\"#{\"}id,jdbcType=INTEGER${r\"}\"}\n" + " </update>\n" + " <select id=\"select\" parameterType=\"int\" resultMap=\"BaseResultMap\">\n" + " select * from `${table}` where id = ${r\"#{\"}id,jdbcType=INTEGER${r\"}\"}\n" + " </select>\n" + " <select id=\"maxId\" resultType=\"Integer\">\n" + " select max(`id`) from `${table}`;\n" + " </select>\n" + "\n" + " <select id=\"count\" resultType=\"Long\">\n" + " select count(`id`) from `${table}`;\n" + " </select>\n" + " <select id=\"findByOneField\" resultMap=\"BaseResultMap\">\n" + " select * from `${table}` where `@{field}` = ${r\"#{\"}value,jdbcType=INTEGER${r\"}\"}\n" + " </select>\n" + " <select id=\"list\" resultMap=\"BaseResultMap\">\n" + " select `${table}`.* from @{tables}\n" + " <if test=\"conditions != null\">\n" + " where @{conditions}\n" + " </if>\n" + " <if test=\"order != null and sort != null\">\n" + " order by @{order} @{sort}\n" + " </if>\n" + " <if test=\"offset != null\">\n" + " limit ${r\"#{offset,jdbcType=INTEGER}\"},${r\"#{limit,jdbcType=INTEGER}\"}\n" + " </if>\n" + " </select>\n" + " <select id=\"selectLazy\" resultMap=\"BaseResultMap\">\n" + " select * from `${table}` where id = ${r\"#{\"}${table},jdbcType=INTEGER${r\"}\"}\n" + " </select>"; }
13,224
0.42942
0.427136
273
47.10989
30.056156
134
false
false
0
0
0
0
0
0
0.424908
false
false
10
8f7c2e7288135364b7be6dd48890e13a2d79a697
34,445,637,738,073
aedb2bc9460163b7fa95a2d7ac404a2907adcca5
/src/test/java/sm/example/navigation/NavigationRunner.java
51e50e4e9c71e5c35c04484d39a192f01ba9e025
[]
no_license
oscarcenteno/sm.java.e2e.practices
https://github.com/oscarcenteno/sm.java.e2e.practices
50d47aa32179fd50f1b705cee903a411a9d65a69
4b09f1c87019109503feece3df6ebaa995ef7f0c
refs/heads/master
2020-04-06T16:25:01.456000
2018-11-14T22:22:17
2018-11-14T22:22:17
157,618,821
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package sm.example.navigation; import net.serenitybdd.jbehave.SerenityStories; import org.jbehave.core.io.StoryFinder; import org.jbehave.core.steps.InjectableStepsFactory; import org.jbehave.core.steps.InstanceStepsFactory; import java.util.Arrays; import java.util.List; import static org.jbehave.core.io.CodeLocations.codeLocationFromClass; public class NavigationRunner extends SerenityStories { @Override public List<String> storyPaths() { return Arrays.asList("stories/example/navigation/PageLoad.story"); } }
UTF-8
Java
541
java
NavigationRunner.java
Java
[]
null
[]
package sm.example.navigation; import net.serenitybdd.jbehave.SerenityStories; import org.jbehave.core.io.StoryFinder; import org.jbehave.core.steps.InjectableStepsFactory; import org.jbehave.core.steps.InstanceStepsFactory; import java.util.Arrays; import java.util.List; import static org.jbehave.core.io.CodeLocations.codeLocationFromClass; public class NavigationRunner extends SerenityStories { @Override public List<String> storyPaths() { return Arrays.asList("stories/example/navigation/PageLoad.story"); } }
541
0.796673
0.796673
20
26.1
25.015795
74
false
false
0
0
0
0
0
0
0.45
false
false
10
1b517ddc22dc224a107ae2ba03386062cb562ff9
15,522,011,847,831
f94065879d08b2956559ac16ffc621bf0f21d562
/LeetCode/LeetCode-Java/LeetCode0701_Insert_into_a_Binary_Search_Tree/TreeNode.java
8c03fc0ec23423e69979bc31e0dc4e6b10b4df39
[ "MIT" ]
permissive
chenshuaiyu/Algorithm
https://github.com/chenshuaiyu/Algorithm
ddf4dd4193770effa2ea717a1cac587795b32f7f
06a9cd3b32b15b276c8c048b23f297e80ed033ea
refs/heads/master
2020-06-18T05:30:58.192000
2020-03-26T07:13:30
2020-03-26T07:13:30
196,180,277
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package LeetCode0701_Insert_into_a_Binary_Search_Tree; /** * Coder : chenshuaiyu * Time : 2018/12/13 13:48 */ public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } }
UTF-8
Java
238
java
TreeNode.java
Java
[ { "context": "_Insert_into_a_Binary_Search_Tree;\n\n/**\n * Coder : chenshuaiyu\n * Time : 2018/12/13 13:48\n */\npublic class TreeN", "end": 82, "score": 0.9947509765625, "start": 71, "tag": "USERNAME", "value": "chenshuaiyu" } ]
null
[]
package LeetCode0701_Insert_into_a_Binary_Search_Tree; /** * Coder : chenshuaiyu * Time : 2018/12/13 13:48 */ public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } }
238
0.605042
0.537815
15
14.866667
13.807567
54
false
false
0
0
0
0
0
0
0.333333
false
false
10
1c1fdb4f29982129ab1f32bfd2fc9a3bf7c22616
30,150,670,485,890
cf64c5bb55bf989d33ec2a1f7371ffd93dd0b2e2
/patterns/hexagonal-architecture/src/test/java/com/baeldung/hexagonalarchitecture/liquiditytracker/domain/impl/LiquidityTrackerImplInternalMethodsUnitTest.java
5a56edc8dc10f002c337ddc9b520218f8c4874ed
[ "MIT" ]
permissive
VictorGil/tutorials
https://github.com/VictorGil/tutorials
0f6226ae4d2f7b197267d55b4b41487d805630b5
9fae72f323d4bd649f1b7a554b5a0186e7abe7cd
refs/heads/master
2020-05-01T11:51:24.632000
2019-04-07T09:04:42
2019-04-07T13:48:51
177,453,403
0
0
null
true
2019-03-24T18:31:49
2019-03-24T18:31:49
2019-03-24T15:42:23
2019-03-24T17:07:53
117,082
0
0
0
null
false
null
package com.baeldung.hexagonalarchitecture.liquiditytracker.domain.impl; import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.baeldung.hexagonalarchitecture.liquiditytracker.domain.NotEnoughAvailableLiquidityException; /** * @author Víctor Gil * * since March 2019 */ public class LiquidityTrackerImplInternalMethodsUnitTest { private static final Logger log = LoggerFactory.getLogger(LiquidityTrackerImplInternalMethodsUnitTest.class); private final LiquidityTrackerImpl trackerImpl; public LiquidityTrackerImplInternalMethodsUnitTest() { trackerImpl = new LiquidityTrackerImpl(); } @Test public void getAvailableLiquidityTest(){ long liquidityLimit = 600; long utilizedLiquidity = 100; long availableLiquidity = trackerImpl.getAvailableLiquidity(liquidityLimit, utilizedLiquidity); Assert.assertEquals(500, availableLiquidity); } @Test public void checkIfThereIsEnoughLiquidityAvailableTest1() { long newLiquidityLimit = 300; long utilizedLiquidity = 250; try { trackerImpl.checkIfThereIsEnoughLiquidityAvailable(newLiquidityLimit, utilizedLiquidity); } catch (NotEnoughAvailableLiquidityException ex) { Assert.fail(NotEnoughAvailableLiquidityException.class.getSimpleName() + " should not have been thrown."); } } @Test public void checkIfThereIsEnoughLiquidityAvailableTest2() { long newLiquidityLimit = 300; long utilizedLiquidity = 301; try { trackerImpl.checkIfThereIsEnoughLiquidityAvailable(newLiquidityLimit, utilizedLiquidity); } catch (NotEnoughAvailableLiquidityException ex) { log.trace("Exception was thown as expected: " + ex); return; } Assert.fail(NotEnoughAvailableLiquidityException.class.getSimpleName() + " should have been thrown."); } @Test public void increaseUtilizedLiquidityAmountTest1() { long currentUtilizedLiquidity = 400; long increasingUtilizedLiquidityAmount = 100; long liquidityLimit = 500; try { trackerImpl.increaseUtilizedLiquidityAmount(currentUtilizedLiquidity, increasingUtilizedLiquidityAmount, liquidityLimit); } catch (NotEnoughAvailableLiquidityException e) { Assert.fail(NotEnoughAvailableLiquidityException.class.getSimpleName() + " should not have been thrown."); } } @Test public void increaseUtilizedLiquidityAmountTest2() { long currentUtilizedLiquidity = 400; long increasingUtilizedLiquidityAmount = 100; long liquidityLimit = 499; try { trackerImpl.increaseUtilizedLiquidityAmount(currentUtilizedLiquidity, increasingUtilizedLiquidityAmount, liquidityLimit); } catch (NotEnoughAvailableLiquidityException ex) { log.trace("Exception was thown as expected: " + ex); return; } Assert.fail(NotEnoughAvailableLiquidityException.class.getSimpleName() + " should have been thrown."); } public void decreaseUtilizedLiquidityAmountTest() { long currentUtilizedLiquidity = 200; long decreasingAmount = 50; long newUtilizedLiquidityAmount = trackerImpl.decreaseUtilizedLiquidityAmount(currentUtilizedLiquidity, decreasingAmount); Assert.assertEquals(150, newUtilizedLiquidityAmount); } }
UTF-8
Java
3,766
java
LiquidityTrackerImplInternalMethodsUnitTest.java
Java
[ { "context": "ughAvailableLiquidityException;\r\n\r\n/**\r\n * @author Víctor Gil\r\n *\r\n * since March 2019\r\n */\r\npublic class Liqui", "end": 322, "score": 0.999843418598175, "start": 312, "tag": "NAME", "value": "Víctor Gil" } ]
null
[]
package com.baeldung.hexagonalarchitecture.liquiditytracker.domain.impl; import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.baeldung.hexagonalarchitecture.liquiditytracker.domain.NotEnoughAvailableLiquidityException; /** * @author <NAME> * * since March 2019 */ public class LiquidityTrackerImplInternalMethodsUnitTest { private static final Logger log = LoggerFactory.getLogger(LiquidityTrackerImplInternalMethodsUnitTest.class); private final LiquidityTrackerImpl trackerImpl; public LiquidityTrackerImplInternalMethodsUnitTest() { trackerImpl = new LiquidityTrackerImpl(); } @Test public void getAvailableLiquidityTest(){ long liquidityLimit = 600; long utilizedLiquidity = 100; long availableLiquidity = trackerImpl.getAvailableLiquidity(liquidityLimit, utilizedLiquidity); Assert.assertEquals(500, availableLiquidity); } @Test public void checkIfThereIsEnoughLiquidityAvailableTest1() { long newLiquidityLimit = 300; long utilizedLiquidity = 250; try { trackerImpl.checkIfThereIsEnoughLiquidityAvailable(newLiquidityLimit, utilizedLiquidity); } catch (NotEnoughAvailableLiquidityException ex) { Assert.fail(NotEnoughAvailableLiquidityException.class.getSimpleName() + " should not have been thrown."); } } @Test public void checkIfThereIsEnoughLiquidityAvailableTest2() { long newLiquidityLimit = 300; long utilizedLiquidity = 301; try { trackerImpl.checkIfThereIsEnoughLiquidityAvailable(newLiquidityLimit, utilizedLiquidity); } catch (NotEnoughAvailableLiquidityException ex) { log.trace("Exception was thown as expected: " + ex); return; } Assert.fail(NotEnoughAvailableLiquidityException.class.getSimpleName() + " should have been thrown."); } @Test public void increaseUtilizedLiquidityAmountTest1() { long currentUtilizedLiquidity = 400; long increasingUtilizedLiquidityAmount = 100; long liquidityLimit = 500; try { trackerImpl.increaseUtilizedLiquidityAmount(currentUtilizedLiquidity, increasingUtilizedLiquidityAmount, liquidityLimit); } catch (NotEnoughAvailableLiquidityException e) { Assert.fail(NotEnoughAvailableLiquidityException.class.getSimpleName() + " should not have been thrown."); } } @Test public void increaseUtilizedLiquidityAmountTest2() { long currentUtilizedLiquidity = 400; long increasingUtilizedLiquidityAmount = 100; long liquidityLimit = 499; try { trackerImpl.increaseUtilizedLiquidityAmount(currentUtilizedLiquidity, increasingUtilizedLiquidityAmount, liquidityLimit); } catch (NotEnoughAvailableLiquidityException ex) { log.trace("Exception was thown as expected: " + ex); return; } Assert.fail(NotEnoughAvailableLiquidityException.class.getSimpleName() + " should have been thrown."); } public void decreaseUtilizedLiquidityAmountTest() { long currentUtilizedLiquidity = 200; long decreasingAmount = 50; long newUtilizedLiquidityAmount = trackerImpl.decreaseUtilizedLiquidityAmount(currentUtilizedLiquidity, decreasingAmount); Assert.assertEquals(150, newUtilizedLiquidityAmount); } }
3,761
0.667729
0.65259
102
34.892159
34.411839
118
false
false
0
0
0
0
0
0
0.480392
false
false
10
011c3795913667d81db4f19024454f068323b899
6,768,868,481,164
22b2780b590c166fbc14b318aa04dace543e1350
/app/src/main/java/com/example/imageslider/ViewPagerAdapter.java
e93f0b48f749503c5f487a1449e99a91cbcd5708
[]
no_license
KapilYadava/AndroidImageSliderJava
https://github.com/KapilYadava/AndroidImageSliderJava
f12a200cf80e615123bb52bcceddc5dac5fb1212
4d9021ec3b3e4680fa6891ad51c6c56448bff72c
refs/heads/master
2020-05-30T20:45:25.271000
2019-06-03T07:24:45
2019-06-03T07:24:45
189,955,657
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.imageslider; import android.content.Context; import android.os.Handler; import android.support.annotation.NonNull; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.squareup.picasso.Picasso; import java.util.Timer; import java.util.TimerTask; public class ViewPagerAdapter extends PagerAdapter { int currentPage = 0; Timer timer; final long DELAY_MS = 500;//delay in milliseconds before task is to be executed final long PERIOD_MS = 3000; private Context context; private String[] imgURLs; public ViewPagerAdapter(Context context, String[] imgURLs){ this.context = context; this.imgURLs = imgURLs; } @Override public int getCount() { return imgURLs.length; } @Override public boolean isViewFromObject(@NonNull View view, @NonNull Object object) { return view == object; } @NonNull @Override public Object instantiateItem(@NonNull ViewGroup container, int position) { ImageView imageView = new ImageView(context); Picasso.get() .load(imgURLs[position]) .fit() .centerCrop() .into(imageView); container.addView(imageView); return imageView; } @Override public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { container.removeView((View) object); } public void startAutoScroll(final ViewPager pager){ final Handler handler = new Handler(); final Runnable Update = new Runnable() { public void run() { if (currentPage == imgURLs.length) { currentPage = 0; } pager.setCurrentItem(currentPage++, true); } }; timer = new Timer(); // This will create a new Thread timer.schedule(new TimerTask() { // task to be scheduled @Override public void run() { handler.post(Update); } }, DELAY_MS, PERIOD_MS); } public void stopAutoScroll(){ timer.cancel(); } }
UTF-8
Java
2,291
java
ViewPagerAdapter.java
Java
[]
null
[]
package com.example.imageslider; import android.content.Context; import android.os.Handler; import android.support.annotation.NonNull; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.squareup.picasso.Picasso; import java.util.Timer; import java.util.TimerTask; public class ViewPagerAdapter extends PagerAdapter { int currentPage = 0; Timer timer; final long DELAY_MS = 500;//delay in milliseconds before task is to be executed final long PERIOD_MS = 3000; private Context context; private String[] imgURLs; public ViewPagerAdapter(Context context, String[] imgURLs){ this.context = context; this.imgURLs = imgURLs; } @Override public int getCount() { return imgURLs.length; } @Override public boolean isViewFromObject(@NonNull View view, @NonNull Object object) { return view == object; } @NonNull @Override public Object instantiateItem(@NonNull ViewGroup container, int position) { ImageView imageView = new ImageView(context); Picasso.get() .load(imgURLs[position]) .fit() .centerCrop() .into(imageView); container.addView(imageView); return imageView; } @Override public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { container.removeView((View) object); } public void startAutoScroll(final ViewPager pager){ final Handler handler = new Handler(); final Runnable Update = new Runnable() { public void run() { if (currentPage == imgURLs.length) { currentPage = 0; } pager.setCurrentItem(currentPage++, true); } }; timer = new Timer(); // This will create a new Thread timer.schedule(new TimerTask() { // task to be scheduled @Override public void run() { handler.post(Update); } }, DELAY_MS, PERIOD_MS); } public void stopAutoScroll(){ timer.cancel(); } }
2,291
0.621563
0.616761
83
26.602409
21.97476
97
false
false
0
0
0
0
0
0
0.518072
false
false
10
7c44d1922e33e596114ffba72d401de515a4d706
15,831,249,499,914
8acc79821081bb1c93b58952fe952bc3695eaa3b
/osa05-Osa05_03.EuroShopper/src/main/java/euroshopper/ShoppingCart.java
6599e755b58a572cad54f37c09744c4e3b9be0a4
[]
no_license
sonkkeli/Web-palvelinohjelmointi-MOOC
https://github.com/sonkkeli/Web-palvelinohjelmointi-MOOC
5d6cd067d04361134ce69cc38babd5d66acc1b1d
2a53bf5c4e33fdc7e78728de70209169cc78d173
refs/heads/master
2020-04-27T22:32:19.623000
2019-04-27T19:46:09
2019-04-27T19:46:09
174,740,606
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package euroshopper; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import lombok.*; import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.ScopedProxyMode; import org.springframework.stereotype.Component; /** * * @author sonja */ @Data @Component @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) public class ShoppingCart implements Serializable { private Map<Item,Long> items; private int sum; public ShoppingCart(){ this.items = new HashMap<>(); this.sum = 0; } public void addToCart(Item item){ this.sum += item.getPrice(); if (items.containsKey(item)){ Long amount = this.items.get(item); this.items.replace(item, amount +1); } else { this.items.put(item, 1L); } } public void clearCart(){ this.items = new HashMap<>(); this.sum = 0; } }
UTF-8
Java
1,025
java
ShoppingCart.java
Java
[ { "context": "ework.stereotype.Component;\r\n\r\n/**\r\n *\r\n * @author sonja\r\n */\r\n\r\n@Data\r\n@Component\r\n@Scope(value = \"sessio", "end": 317, "score": 0.9991104602813721, "start": 312, "tag": "USERNAME", "value": "sonja" } ]
null
[]
package euroshopper; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import lombok.*; import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.ScopedProxyMode; import org.springframework.stereotype.Component; /** * * @author sonja */ @Data @Component @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) public class ShoppingCart implements Serializable { private Map<Item,Long> items; private int sum; public ShoppingCart(){ this.items = new HashMap<>(); this.sum = 0; } public void addToCart(Item item){ this.sum += item.getPrice(); if (items.containsKey(item)){ Long amount = this.items.get(item); this.items.replace(item, amount +1); } else { this.items.put(item, 1L); } } public void clearCart(){ this.items = new HashMap<>(); this.sum = 0; } }
1,025
0.612683
0.608781
41
23
18.539345
67
false
false
0
0
0
0
0
0
0.536585
false
false
10
56cd450a957011d05d5cdc1675f2f64d49b17115
15,453,292,376,933
4757a6c0f452f49968798aaeb0fc804bdf3d5ab5
/src/main/java/com/drivecure/ServletInitializer.java
49b0ed17cab624ea395188a2e946b5cb26002a59
[]
no_license
chetant1/drivercure
https://github.com/chetant1/drivercure
b0d0f34bfde424770295414384b3fa263e5c5488
53e891950e28329b77a884151d813baa1a65634c
refs/heads/master
2021-02-07T12:29:59.371000
2020-03-01T08:23:08
2020-03-01T08:23:08
244,024,477
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.drivecure; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; public class ServletInitializer extends SpringBootServletInitializer { //THis is my main class @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(DrivecureApplication.class); } }
UTF-8
Java
431
java
ServletInitializer.java
Java
[]
null
[]
package com.drivecure; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; public class ServletInitializer extends SpringBootServletInitializer { //THis is my main class @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(DrivecureApplication.class); } }
431
0.849188
0.849188
14
29.785715
32.628162
85
false
false
0
0
0
0
0
0
0.714286
false
false
10
4a518d1ca1138751e760f9654092aee05b206ba8
14,465,449,911,046
1435cbf198d4016b5c62aef47a6c84bbcc3a86a5
/cotizaciones_seditek/src/controllers/ControllerProductos.java
5d21519c06d2eabbef79a629da7882402bca2235
[]
no_license
JocelynFlores1/cotizaciones_seditek
https://github.com/JocelynFlores1/cotizaciones_seditek
3d6c16703fc54bab4424c306efe23c8b7c729b1c
b3ad80b339ddbafd26deb9b5106c77caa7e0065b
refs/heads/main
2023-04-08T21:17:48.824000
2021-04-18T22:19:45
2021-04-18T22:19:45
331,161,554
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package controllers; import models.ModelProductos; import models.ModelConexion; import models.ModelGenerarCodigos; import views.ViewProductos; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.ResultSetMetaData; import java.sql.SQLException; import javax.swing.JOptionPane; import javax.swing.JTable; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.DefaultTableModel; public class ControllerProductos { public ModelProductos model_productos; public ViewProductos view_productos; ModelConexion productoConexion = new ModelConexion(); ActionListener actionListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == view_productos.jBInsertarProducto) { Insertar_producto_actionPerformed(); } else if (e.getSource() == view_productos.jBModificarProducto) { Modificar_producto_actionPerformed(); } else if (e.getSource() == view_productos.jBEliminarProducto) { Borrar_producto_actionListener(); } else if (e.getSource() == view_productos.jBNuevoProducto) { Nuevo_producto_actionPerformed(); } } }; public ControllerProductos(ModelProductos model_productos,ViewProductos views_productos){ this.model_productos = model_productos; this.view_productos = views_productos; initComponents(); setActionListener(); } public void initComponents() { view_productos.setVisible(true); model_productos.conectarDB(productoConexion); CambiarCampos(); tablaConsulta(); System.out.println("Solo se inicia si se abre productos"); } /** * * * Metodo que cambia los campos de los jTextField en ViewProductos */ public void CambiarCampos() { view_productos.jTIdProducto.setText(""+model_productos.getId_producto()); view_productos.jTCodigoProducto.setText(""+model_productos.getCodigo_producto()); view_productos.jTNombreProducto.setText(""+model_productos.getNombre_producto()); view_productos.jTMarcaProducto.setText(""+model_productos.getMarca()); view_productos.jTModeloProducto.setText(""+model_productos.getModelo()); view_productos.jTDescripcionUsuarioProducto.setText(""+model_productos.getDescripcion_usuario()); view_productos.jTDescripcionClienteProducto.setText(""+model_productos.getDescripcion_cliente()); view_productos.jTAccesoriosProducto.setText(""+model_productos.getAccesorios()); view_productos.jTPrecioProducto.setText(""+model_productos.getPrecio_unitario()); view_productos.jTStockProducto.setText(""+model_productos.getStock()); view_productos.jTProveedorProducto.setText(""+model_productos.getId_proveedor()); } /** * Método para agregar el actionListener a cada boton de la vista */ public void setActionListener() { view_productos.jBNuevoProducto.addActionListener(actionListener); view_productos.jBInsertarProducto.addActionListener(actionListener); view_productos.jBModificarProducto.addActionListener(actionListener); view_productos.jBEliminarProducto.addActionListener(actionListener); view_productos.jTableProductos.getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { insertarCamposTabla(); } }); } /** * * * Modelo que permite insertar el texto obenido en los jTextField de * ViewProductos e inserta los valores en las variables de ModelProductos */ public void Insertar_producto_actionPerformed() { //JOptionPane.showConfirmDialog permite al usuario elegir si realizar la accion del boton solicitado o simplemente cancelarlo int cancelar = JOptionPane.showConfirmDialog(null, "¿Vas a guardar un nuevo producto?", "Guardar producto", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if(view_productos.jTCodigoProducto.getText().equals("") || view_productos.jTNombreProducto.getText().equals("") || view_productos.jTMarcaProducto.getText().equals("")|| view_productos.jTModeloProducto.getText().equals("") || view_productos.jTDescripcionUsuarioProducto.getText().equals("") || view_productos.jTDescripcionClienteProducto.getText().equals("") || view_productos.jTAccesoriosProducto.getText().equals("") || view_productos.jTPrecioProducto.getText().equals("") || view_productos.jTStockProducto.getText().equals("") || view_productos.jTProveedorProducto.getText().equals("") ){ JOptionPane.showMessageDialog(null,"Debes llenar todos los campos"); }else{ if (cancelar == 0) { model_productos.setId_producto(view_productos.jTIdProducto.getText()); model_productos.setCodigo_producto(view_productos.jTCodigoProducto.getText()); model_productos.setNombre_producto(view_productos.jTNombreProducto.getText()); model_productos.setMarca(view_productos.jTMarcaProducto.getText()); model_productos.setModelo(view_productos.jTModeloProducto.getText()); model_productos.setDescripcion_usuario(view_productos.jTDescripcionUsuarioProducto.getText()); model_productos.setDescripcion_cliente(view_productos.jTDescripcionClienteProducto.getText()); model_productos.setAccesorios(view_productos.jTAccesoriosProducto.getText()); if(!view_productos.jTPrecioProducto.getText().equals(" ")){ model_productos.setPrecio_unitario(Float.parseFloat(view_productos.jTPrecioProducto.getText())); } if(!view_productos.jTStockProducto.getText().equals(" ")){ model_productos.setStock(Integer.parseInt(view_productos.jTStockProducto.getText())); } model_productos.setId_proveedor(view_productos.jTProveedorProducto.getText()); model_productos.insertarNuevoProducto(productoConexion); tablaConsulta(); JOptionPane.showMessageDialog(null, "Registro almacenado correctamente"); } else { ///Respuesta que se obtiene cuando se cancela la accion del boton elegido JOptionPane.showMessageDialog(null, "No se guardo ningun producto"); } } } public void Modificar_producto_actionPerformed() { //JOptionPane.showConfirmDialog permite al usuario elegir si realizar la accion del boton solicitado o simplemente cancelarlo int cancelar = JOptionPane.showConfirmDialog(null, "¿Desea actualizar los datos del producto?", "Guardar cambios", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if (cancelar == 0) { //model_productos.setId_producto(view_productos.jTIdProducto.getText()); model_productos.setCodigo_producto(view_productos.jTCodigoProducto.getText()); model_productos.setNombre_producto(view_productos.jTNombreProducto.getText()); model_productos.setMarca(view_productos.jTMarcaProducto.getText()); model_productos.setModelo(view_productos.jTModeloProducto.getText()); model_productos.setDescripcion_usuario(view_productos.jTDescripcionUsuarioProducto.getText()); model_productos.setDescripcion_cliente(view_productos.jTDescripcionClienteProducto.getText()); model_productos.setAccesorios(view_productos.jTAccesoriosProducto.getText()); if(!view_productos.jTPrecioProducto.getText().equals(" ")){ model_productos.setPrecio_unitario(Float.parseFloat(view_productos.jTPrecioProducto.getText())); } if(!view_productos.jTStockProducto.getText().equals(" ")){ model_productos.setStock(Integer.parseInt(view_productos.jTStockProducto.getText())); } model_productos.setId_proveedor(view_productos.jTProveedorProducto.getText()); model_productos.modificarDatosProducto(productoConexion); //Este comando realiza la accion de utlilzar el metodo de modificarDatosUsuario usando el objeto construido en de modelClientes JOptionPane.showMessageDialog(null, "Datos del producto modificados correctamente"); tablaConsulta(); //Se usa el metodo tablaConsulta para actualizar los registros en jTableProducto } else { ///Respuesta que se obtiene cuando se cancela la accion del boton elegido JOptionPane.showMessageDialog(null, "No se guardo ningun cambio"); } } public void Borrar_producto_actionListener() { //JOptionPane.showConfirmDialog permite al usuario elegir si realizar la accion del boton solicitado o simplemente cancelarlo int cancelar = JOptionPane.showConfirmDialog(null, "¿Desea borrar los datos del producto?", "Borrar producto", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if (cancelar == 0) { model_productos.setId_producto(view_productos.jTIdProducto.getText()); model_productos.borrarDatosProducto(productoConexion); tablaConsulta(); JOptionPane.showMessageDialog(null, "Los datos del producto han sido eliminados"); } else { ///Respuesta que se obtiene cuando se cancela la accion del boton elegido JOptionPane.showMessageDialog(null, "No se borro ningun registro"); } } public void tablaConsulta() { try { DefaultTableModel modelo = new DefaultTableModel(); view_productos.jTableProductos.setModel(modelo); view_productos.jTableProductos.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); model_productos.consultajTableProducto(productoConexion); ResultSetMetaData rsMd = model_productos.getRs().getMetaData(); int cantidadColumnas = rsMd.getColumnCount(); modelo.addColumn("ID"); modelo.addColumn("Codigo"); modelo.addColumn("Nombre"); modelo.addColumn("Marca"); modelo.addColumn("Modelo"); modelo.addColumn("Descripción Usuario"); modelo.addColumn("Descripción Cliente"); modelo.addColumn("Accesorios"); modelo.addColumn("Precio Unitario"); modelo.addColumn("Stock"); modelo.addColumn("Proveedor"); while (model_productos.getRs().next()) { Object[] filas = new Object[cantidadColumnas]; for (int i = 0; i < cantidadColumnas; i++) { filas[i] = model_productos.getRs().getObject(i + 1); } modelo.addRow(filas); } } catch (SQLException ex) { System.out.println("Error" + ex); } } public void insertarCamposTabla() { try { if (view_productos.jTableProductos.getSelectedRow() != -1) { int fila = view_productos.jTableProductos.getSelectedRow(); view_productos.jTIdProducto.setText(view_productos.jTableProductos.getValueAt(fila, 0).toString()); view_productos.jTCodigoProducto.setText(view_productos.jTableProductos.getValueAt(fila, 1).toString()); view_productos.jTNombreProducto.setText(view_productos.jTableProductos.getValueAt(fila, 2).toString()); view_productos.jTMarcaProducto.setText(view_productos.jTableProductos.getValueAt(fila, 3).toString()); view_productos.jTModeloProducto.setText(view_productos.jTableProductos.getValueAt(fila, 4).toString()); view_productos.jTDescripcionUsuarioProducto.setText(view_productos.jTableProductos.getValueAt(fila, 5).toString()); view_productos.jTDescripcionClienteProducto.setText(view_productos.jTableProductos.getValueAt(fila, 6).toString()); view_productos.jTAccesoriosProducto.setText(view_productos.jTableProductos.getValueAt(fila, 7).toString()); view_productos.jTPrecioProducto.setText(view_productos.jTableProductos.getValueAt(fila, 8).toString()); view_productos.jTStockProducto.setText(view_productos.jTableProductos.getValueAt(fila, 9).toString()); view_productos.jTProveedorProducto.setText(view_productos.jTableProductos.getValueAt(fila, 10).toString()); } } catch (Exception err) { JOptionPane.showMessageDialog(null, "Error:\nSelecciona un registro"); } } public void Nuevo_producto_actionPerformed() { //view_productos.jTIdProducto.setText(""); view_productos.jTCodigoProducto.setText(""); view_productos.jTNombreProducto.setText(""); view_productos.jTMarcaProducto.setText(""); view_productos.jTModeloProducto.setText(""); view_productos.jTDescripcionUsuarioProducto.setText(""); view_productos.jTDescripcionClienteProducto.setText(""); view_productos.jTAccesoriosProducto.setText(""); view_productos.jTPrecioProducto.setText(""); view_productos.jTStockProducto.setText(""); view_productos.jTProveedorProducto.setText(""); } /** * Este metodo permite generar codigos automaticamente con una consulta en * la base de datos desde models.ModelProductos.GenerarCodigos */ public void codigos() { int j; int cont = 1; String num = ""; model_productos.consultaGenerarCodigos(productoConexion); if (model_productos.getU() == null) { view_productos.jTIdProducto.setText("SEDITEK-P0000001"); } else { char r1 = model_productos.getU().charAt(6); char r2 = model_productos.getU().charAt(7); char r3 = model_productos.getU().charAt(8); char r4 = model_productos.getU().charAt(9); char r5 = model_productos.getU().charAt(10); char r6 = model_productos.getU().charAt(11); char r7 = model_productos.getU().charAt(12); String r = ""; r = "" + r1 + r2 + r3 + r4 + r5 + r6 + r7; j = Integer.parseInt(r); System.out.println(j); ModelGenerarCodigos gen = new ModelGenerarCodigos(); gen.generar(j); view_productos.jTIdProducto.setText("SEDITEK-P" + gen.serie()); System.out.println("SEDITEK-P" + gen.serie()); } } }
UTF-8
Java
15,116
java
ControllerProductos.java
Java
[]
null
[]
package controllers; import models.ModelProductos; import models.ModelConexion; import models.ModelGenerarCodigos; import views.ViewProductos; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.ResultSetMetaData; import java.sql.SQLException; import javax.swing.JOptionPane; import javax.swing.JTable; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.DefaultTableModel; public class ControllerProductos { public ModelProductos model_productos; public ViewProductos view_productos; ModelConexion productoConexion = new ModelConexion(); ActionListener actionListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == view_productos.jBInsertarProducto) { Insertar_producto_actionPerformed(); } else if (e.getSource() == view_productos.jBModificarProducto) { Modificar_producto_actionPerformed(); } else if (e.getSource() == view_productos.jBEliminarProducto) { Borrar_producto_actionListener(); } else if (e.getSource() == view_productos.jBNuevoProducto) { Nuevo_producto_actionPerformed(); } } }; public ControllerProductos(ModelProductos model_productos,ViewProductos views_productos){ this.model_productos = model_productos; this.view_productos = views_productos; initComponents(); setActionListener(); } public void initComponents() { view_productos.setVisible(true); model_productos.conectarDB(productoConexion); CambiarCampos(); tablaConsulta(); System.out.println("Solo se inicia si se abre productos"); } /** * * * Metodo que cambia los campos de los jTextField en ViewProductos */ public void CambiarCampos() { view_productos.jTIdProducto.setText(""+model_productos.getId_producto()); view_productos.jTCodigoProducto.setText(""+model_productos.getCodigo_producto()); view_productos.jTNombreProducto.setText(""+model_productos.getNombre_producto()); view_productos.jTMarcaProducto.setText(""+model_productos.getMarca()); view_productos.jTModeloProducto.setText(""+model_productos.getModelo()); view_productos.jTDescripcionUsuarioProducto.setText(""+model_productos.getDescripcion_usuario()); view_productos.jTDescripcionClienteProducto.setText(""+model_productos.getDescripcion_cliente()); view_productos.jTAccesoriosProducto.setText(""+model_productos.getAccesorios()); view_productos.jTPrecioProducto.setText(""+model_productos.getPrecio_unitario()); view_productos.jTStockProducto.setText(""+model_productos.getStock()); view_productos.jTProveedorProducto.setText(""+model_productos.getId_proveedor()); } /** * Método para agregar el actionListener a cada boton de la vista */ public void setActionListener() { view_productos.jBNuevoProducto.addActionListener(actionListener); view_productos.jBInsertarProducto.addActionListener(actionListener); view_productos.jBModificarProducto.addActionListener(actionListener); view_productos.jBEliminarProducto.addActionListener(actionListener); view_productos.jTableProductos.getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { insertarCamposTabla(); } }); } /** * * * Modelo que permite insertar el texto obenido en los jTextField de * ViewProductos e inserta los valores en las variables de ModelProductos */ public void Insertar_producto_actionPerformed() { //JOptionPane.showConfirmDialog permite al usuario elegir si realizar la accion del boton solicitado o simplemente cancelarlo int cancelar = JOptionPane.showConfirmDialog(null, "¿Vas a guardar un nuevo producto?", "Guardar producto", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if(view_productos.jTCodigoProducto.getText().equals("") || view_productos.jTNombreProducto.getText().equals("") || view_productos.jTMarcaProducto.getText().equals("")|| view_productos.jTModeloProducto.getText().equals("") || view_productos.jTDescripcionUsuarioProducto.getText().equals("") || view_productos.jTDescripcionClienteProducto.getText().equals("") || view_productos.jTAccesoriosProducto.getText().equals("") || view_productos.jTPrecioProducto.getText().equals("") || view_productos.jTStockProducto.getText().equals("") || view_productos.jTProveedorProducto.getText().equals("") ){ JOptionPane.showMessageDialog(null,"Debes llenar todos los campos"); }else{ if (cancelar == 0) { model_productos.setId_producto(view_productos.jTIdProducto.getText()); model_productos.setCodigo_producto(view_productos.jTCodigoProducto.getText()); model_productos.setNombre_producto(view_productos.jTNombreProducto.getText()); model_productos.setMarca(view_productos.jTMarcaProducto.getText()); model_productos.setModelo(view_productos.jTModeloProducto.getText()); model_productos.setDescripcion_usuario(view_productos.jTDescripcionUsuarioProducto.getText()); model_productos.setDescripcion_cliente(view_productos.jTDescripcionClienteProducto.getText()); model_productos.setAccesorios(view_productos.jTAccesoriosProducto.getText()); if(!view_productos.jTPrecioProducto.getText().equals(" ")){ model_productos.setPrecio_unitario(Float.parseFloat(view_productos.jTPrecioProducto.getText())); } if(!view_productos.jTStockProducto.getText().equals(" ")){ model_productos.setStock(Integer.parseInt(view_productos.jTStockProducto.getText())); } model_productos.setId_proveedor(view_productos.jTProveedorProducto.getText()); model_productos.insertarNuevoProducto(productoConexion); tablaConsulta(); JOptionPane.showMessageDialog(null, "Registro almacenado correctamente"); } else { ///Respuesta que se obtiene cuando se cancela la accion del boton elegido JOptionPane.showMessageDialog(null, "No se guardo ningun producto"); } } } public void Modificar_producto_actionPerformed() { //JOptionPane.showConfirmDialog permite al usuario elegir si realizar la accion del boton solicitado o simplemente cancelarlo int cancelar = JOptionPane.showConfirmDialog(null, "¿Desea actualizar los datos del producto?", "Guardar cambios", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if (cancelar == 0) { //model_productos.setId_producto(view_productos.jTIdProducto.getText()); model_productos.setCodigo_producto(view_productos.jTCodigoProducto.getText()); model_productos.setNombre_producto(view_productos.jTNombreProducto.getText()); model_productos.setMarca(view_productos.jTMarcaProducto.getText()); model_productos.setModelo(view_productos.jTModeloProducto.getText()); model_productos.setDescripcion_usuario(view_productos.jTDescripcionUsuarioProducto.getText()); model_productos.setDescripcion_cliente(view_productos.jTDescripcionClienteProducto.getText()); model_productos.setAccesorios(view_productos.jTAccesoriosProducto.getText()); if(!view_productos.jTPrecioProducto.getText().equals(" ")){ model_productos.setPrecio_unitario(Float.parseFloat(view_productos.jTPrecioProducto.getText())); } if(!view_productos.jTStockProducto.getText().equals(" ")){ model_productos.setStock(Integer.parseInt(view_productos.jTStockProducto.getText())); } model_productos.setId_proveedor(view_productos.jTProveedorProducto.getText()); model_productos.modificarDatosProducto(productoConexion); //Este comando realiza la accion de utlilzar el metodo de modificarDatosUsuario usando el objeto construido en de modelClientes JOptionPane.showMessageDialog(null, "Datos del producto modificados correctamente"); tablaConsulta(); //Se usa el metodo tablaConsulta para actualizar los registros en jTableProducto } else { ///Respuesta que se obtiene cuando se cancela la accion del boton elegido JOptionPane.showMessageDialog(null, "No se guardo ningun cambio"); } } public void Borrar_producto_actionListener() { //JOptionPane.showConfirmDialog permite al usuario elegir si realizar la accion del boton solicitado o simplemente cancelarlo int cancelar = JOptionPane.showConfirmDialog(null, "¿Desea borrar los datos del producto?", "Borrar producto", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if (cancelar == 0) { model_productos.setId_producto(view_productos.jTIdProducto.getText()); model_productos.borrarDatosProducto(productoConexion); tablaConsulta(); JOptionPane.showMessageDialog(null, "Los datos del producto han sido eliminados"); } else { ///Respuesta que se obtiene cuando se cancela la accion del boton elegido JOptionPane.showMessageDialog(null, "No se borro ningun registro"); } } public void tablaConsulta() { try { DefaultTableModel modelo = new DefaultTableModel(); view_productos.jTableProductos.setModel(modelo); view_productos.jTableProductos.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); model_productos.consultajTableProducto(productoConexion); ResultSetMetaData rsMd = model_productos.getRs().getMetaData(); int cantidadColumnas = rsMd.getColumnCount(); modelo.addColumn("ID"); modelo.addColumn("Codigo"); modelo.addColumn("Nombre"); modelo.addColumn("Marca"); modelo.addColumn("Modelo"); modelo.addColumn("Descripción Usuario"); modelo.addColumn("Descripción Cliente"); modelo.addColumn("Accesorios"); modelo.addColumn("Precio Unitario"); modelo.addColumn("Stock"); modelo.addColumn("Proveedor"); while (model_productos.getRs().next()) { Object[] filas = new Object[cantidadColumnas]; for (int i = 0; i < cantidadColumnas; i++) { filas[i] = model_productos.getRs().getObject(i + 1); } modelo.addRow(filas); } } catch (SQLException ex) { System.out.println("Error" + ex); } } public void insertarCamposTabla() { try { if (view_productos.jTableProductos.getSelectedRow() != -1) { int fila = view_productos.jTableProductos.getSelectedRow(); view_productos.jTIdProducto.setText(view_productos.jTableProductos.getValueAt(fila, 0).toString()); view_productos.jTCodigoProducto.setText(view_productos.jTableProductos.getValueAt(fila, 1).toString()); view_productos.jTNombreProducto.setText(view_productos.jTableProductos.getValueAt(fila, 2).toString()); view_productos.jTMarcaProducto.setText(view_productos.jTableProductos.getValueAt(fila, 3).toString()); view_productos.jTModeloProducto.setText(view_productos.jTableProductos.getValueAt(fila, 4).toString()); view_productos.jTDescripcionUsuarioProducto.setText(view_productos.jTableProductos.getValueAt(fila, 5).toString()); view_productos.jTDescripcionClienteProducto.setText(view_productos.jTableProductos.getValueAt(fila, 6).toString()); view_productos.jTAccesoriosProducto.setText(view_productos.jTableProductos.getValueAt(fila, 7).toString()); view_productos.jTPrecioProducto.setText(view_productos.jTableProductos.getValueAt(fila, 8).toString()); view_productos.jTStockProducto.setText(view_productos.jTableProductos.getValueAt(fila, 9).toString()); view_productos.jTProveedorProducto.setText(view_productos.jTableProductos.getValueAt(fila, 10).toString()); } } catch (Exception err) { JOptionPane.showMessageDialog(null, "Error:\nSelecciona un registro"); } } public void Nuevo_producto_actionPerformed() { //view_productos.jTIdProducto.setText(""); view_productos.jTCodigoProducto.setText(""); view_productos.jTNombreProducto.setText(""); view_productos.jTMarcaProducto.setText(""); view_productos.jTModeloProducto.setText(""); view_productos.jTDescripcionUsuarioProducto.setText(""); view_productos.jTDescripcionClienteProducto.setText(""); view_productos.jTAccesoriosProducto.setText(""); view_productos.jTPrecioProducto.setText(""); view_productos.jTStockProducto.setText(""); view_productos.jTProveedorProducto.setText(""); } /** * Este metodo permite generar codigos automaticamente con una consulta en * la base de datos desde models.ModelProductos.GenerarCodigos */ public void codigos() { int j; int cont = 1; String num = ""; model_productos.consultaGenerarCodigos(productoConexion); if (model_productos.getU() == null) { view_productos.jTIdProducto.setText("SEDITEK-P0000001"); } else { char r1 = model_productos.getU().charAt(6); char r2 = model_productos.getU().charAt(7); char r3 = model_productos.getU().charAt(8); char r4 = model_productos.getU().charAt(9); char r5 = model_productos.getU().charAt(10); char r6 = model_productos.getU().charAt(11); char r7 = model_productos.getU().charAt(12); String r = ""; r = "" + r1 + r2 + r3 + r4 + r5 + r6 + r7; j = Integer.parseInt(r); System.out.println(j); ModelGenerarCodigos gen = new ModelGenerarCodigos(); gen.generar(j); view_productos.jTIdProducto.setText("SEDITEK-P" + gen.serie()); System.out.println("SEDITEK-P" + gen.serie()); } } }
15,116
0.653408
0.650099
322
45.925465
39.195171
183
false
false
0
0
0
0
0
0
0.63354
false
false
12
e0e71612416f6a312da4de67db79934a01277b19
31,430,570,732,950
b1397836e374d33844323b183ec87fe85a59c05f
/Apps/WaiterApp/app/src/main/java/com/Lieyang/waiter/Network/PersistentCookieJar.java
38df764311ed2bedf4aed8d4cc0047d25062f84a
[]
no_license
sa2423/SE-2019
https://github.com/sa2423/SE-2019
4c06e81e02cb452112fa93e538235e429e998481
9b5c43c56a713a1f47fde28e8bd6ff1781f77eb8
refs/heads/master
2020-04-20T10:18:37.259000
2019-05-08T03:54:47
2019-05-08T03:54:47
168,787,302
1
4
null
false
2019-04-19T14:49:16
2019-02-02T02:50:06
2019-04-19T13:34:22
2019-04-19T13:34:19
19,039
1
3
0
CSS
false
false
/** * Created by Taras Tysovskyi * Class to save cookies in network manager to storage and retrieving them from storage when the app is loaded * This allows us to keep the user logged in between the app restarts */ package com.Lieyang.waiter.Network; import android.content.Context; import android.content.SharedPreferences; import android.util.Log; import com.Lieyang.waiter.GlobalApplication; import com.Lieyang.waiter.MainActivity; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.List; import java.util.Map; import okhttp3.Cookie; import okhttp3.CookieJar; import okhttp3.HttpUrl; public class PersistentCookieJar implements CookieJar { public static final String TAG = "PersistentCookieJar"; private List<Cookie> cookies; private SharedPreferences sharedPreferences; public PersistentCookieJar(){ sharedPreferences = GlobalApplication.getAppContext().getSharedPreferences("cookies", Context.MODE_PRIVATE); cookies = readCookiesFromSharedPreferences(); } @Override public void saveFromResponse(HttpUrl url, List<Cookie> cookies) { saveCookiesToSharedPreferences(cookies); this.cookies = cookies; } @Override public List<Cookie> loadForRequest(HttpUrl url) { if (cookies != null) return cookies; return new ArrayList<Cookie>(); } public void saveCookiesToSharedPreferences(List<Cookie> cookies){ SharedPreferences.Editor editor = sharedPreferences.edit(); for (Cookie cookie : cookies) { editor.putString(createCookieKey(cookie), new SerializableCookie().encode(cookie)); } editor.commit(); } public List<Cookie> readCookiesFromSharedPreferences(){ List<Cookie> cookies = new ArrayList<>(sharedPreferences.getAll().size()); for (Map.Entry<String, ?> entry : sharedPreferences.getAll().entrySet()) { String serializedCookie = (String) entry.getValue(); Cookie cookie = new SerializableCookie().decode(serializedCookie); if (cookie != null) { cookies.add(cookie); } } return cookies; } public void clearAllCookies(){ SharedPreferences.Editor editor = sharedPreferences.edit(); for (Cookie cookie : cookies) { editor.remove(createCookieKey(cookie)); } editor.commit(); } private static String createCookieKey(Cookie cookie) { return (cookie.secure() ? "https" : "http") + "://" + cookie.domain() + cookie.path() + "|" + cookie.name(); } }
UTF-8
Java
2,756
java
PersistentCookieJar.java
Java
[ { "context": "/**\n * Created by Taras Tysovskyi\n * Class to save cookies in network manager to st", "end": 33, "score": 0.9998770356178284, "start": 18, "tag": "NAME", "value": "Taras Tysovskyi" } ]
null
[]
/** * Created by <NAME> * Class to save cookies in network manager to storage and retrieving them from storage when the app is loaded * This allows us to keep the user logged in between the app restarts */ package com.Lieyang.waiter.Network; import android.content.Context; import android.content.SharedPreferences; import android.util.Log; import com.Lieyang.waiter.GlobalApplication; import com.Lieyang.waiter.MainActivity; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.List; import java.util.Map; import okhttp3.Cookie; import okhttp3.CookieJar; import okhttp3.HttpUrl; public class PersistentCookieJar implements CookieJar { public static final String TAG = "PersistentCookieJar"; private List<Cookie> cookies; private SharedPreferences sharedPreferences; public PersistentCookieJar(){ sharedPreferences = GlobalApplication.getAppContext().getSharedPreferences("cookies", Context.MODE_PRIVATE); cookies = readCookiesFromSharedPreferences(); } @Override public void saveFromResponse(HttpUrl url, List<Cookie> cookies) { saveCookiesToSharedPreferences(cookies); this.cookies = cookies; } @Override public List<Cookie> loadForRequest(HttpUrl url) { if (cookies != null) return cookies; return new ArrayList<Cookie>(); } public void saveCookiesToSharedPreferences(List<Cookie> cookies){ SharedPreferences.Editor editor = sharedPreferences.edit(); for (Cookie cookie : cookies) { editor.putString(createCookieKey(cookie), new SerializableCookie().encode(cookie)); } editor.commit(); } public List<Cookie> readCookiesFromSharedPreferences(){ List<Cookie> cookies = new ArrayList<>(sharedPreferences.getAll().size()); for (Map.Entry<String, ?> entry : sharedPreferences.getAll().entrySet()) { String serializedCookie = (String) entry.getValue(); Cookie cookie = new SerializableCookie().decode(serializedCookie); if (cookie != null) { cookies.add(cookie); } } return cookies; } public void clearAllCookies(){ SharedPreferences.Editor editor = sharedPreferences.edit(); for (Cookie cookie : cookies) { editor.remove(createCookieKey(cookie)); } editor.commit(); } private static String createCookieKey(Cookie cookie) { return (cookie.secure() ? "https" : "http") + "://" + cookie.domain() + cookie.path() + "|" + cookie.name(); } }
2,747
0.689042
0.687954
87
30.678162
28.82308
116
false
false
0
0
0
0
0
0
0.494253
false
false
12
3fc2d48c123cd2a8ff2ac7a3173855b4b0824b7a
27,290,222,202,028
b7ade44f74fc949604704a7c07004470cfbc5710
/car-service/src/main/java/com/epam/vvmikhalevich/carservice/CarService.java
54b3582171a417468b4751f44778504b00059cf9
[]
no_license
vvmikhalevich/usersReserve
https://github.com/vvmikhalevich/usersReserve
73951176a9acf270aaf208dac22ca09e05bebc37
e31a0a49062d600872f414f82d3260ca9033af5f
refs/heads/master
2021-03-08T15:12:50.001000
2020-03-23T20:23:15
2020-03-23T20:23:15
246,354,315
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.epam.vvmikhalevich.carservice; import java.util.List; public interface CarService { List<Car> list(); void reserve(Integer id); void cancel(Integer id); void commit(Integer id); }
UTF-8
Java
216
java
CarService.java
Java
[]
null
[]
package com.epam.vvmikhalevich.carservice; import java.util.List; public interface CarService { List<Car> list(); void reserve(Integer id); void cancel(Integer id); void commit(Integer id); }
216
0.689815
0.689815
16
12.5
14.662878
42
false
false
0
0
0
0
0
0
0.375
false
false
12
ad2bea9fdab8c6886a4d5f1aa65562bd66a96b56
22,007,412,474,900
b7c72bf108c0aa6d3a165229b38727fe3dd103d4
/Doctor 24-7/MyApplication/app/src/main/java/com/example/mayur/doctor24_7/Diabeties/frag_effect.java
20bcd57bc62c5476b21f035b0c0fe86f13ef0835
[]
no_license
ahermayur/MAHealth
https://github.com/ahermayur/MAHealth
b82735b0cd899d569e4c9ce8d35b6ca7bbd43198
84bf003d1f54c9233b3a34b4e9ca0a27814403ef
refs/heads/master
2021-01-17T14:23:53.576000
2017-03-07T15:38:55
2017-03-07T15:38:55
84,086,196
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.mayur.doctor24_7.Diabeties; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.codesgood.views.JustifiedTextView; import com.example.mayur.doctor24_7.R; public class frag_effect extends Fragment { JustifiedTextView tv1,tv2,tv3,tv4,tv5,tv6; JustifiedTextView tv11,tv12,tv13,tv14,tv15,tv16; String s1,s2,s3,s4,s5,s6; String s11,s12,s13,s14,s15,s16; public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_frag_effect, container, false); Toast.makeText(getContext(),"effects",Toast.LENGTH_LONG).show(); tv1=(JustifiedTextView)view.findViewById(R.id.txt2); tv2=(JustifiedTextView)view.findViewById(R.id.txt4); tv3=(JustifiedTextView)view.findViewById(R.id.txt6); tv4=(JustifiedTextView)view.findViewById(R.id.txt8); tv5=(JustifiedTextView)view.findViewById(R.id.txt10); tv6=(JustifiedTextView)view.findViewById(R.id.txt12); tv11=(JustifiedTextView)view.findViewById(R.id.txt1); tv12=(JustifiedTextView)view.findViewById(R.id.txt3); tv13=(JustifiedTextView)view.findViewById(R.id.txt5); tv14=(JustifiedTextView)view.findViewById(R.id.txt7); tv15=(JustifiedTextView)view.findViewById(R.id.txt9); tv16=(JustifiedTextView)view.findViewById(R.id.txt11); s1="\n\t\tDiabetes dramatically increases your risk of various cardiovascular problems, including coronary artery disease with chest pain (angina), heart attack, stroke, narrowing of the arteries (atherosclerosis) and high blood pressure."; s2="\n\t\tExcess sugar can injure the walls of the tiny blood vessels (capillaries) that nourish your nerves, especially in the legs. This can cause tingling, numbness, burning or pain that usually begins at the tips of the toes or fingers and gradually spreads upward. Poorly controlled blood sugar could cause you to eventually lose all sense of feeling in the affected limbs."; s3="\n\t\tDiabetes can damage the blood vessels of the retina (diabetic retinopathy), potentially leading to blindness. Diabetes also increases the risk of other serious vision conditions, such as cataracts and glaucoma."; s4="\n\t\tNerve damage in the feet or poor blood flow to the feet increases the risk of various foot complications. Left untreated, cuts and blisters can become serious infections, which often heal poorly and may ultimately require toe, foot or leg amputation."; s5="\n\t\tDiabetes may leave you more susceptible to skin problems, including bacterial and fungal infections."; s6="\n\t\tHigh blood sugar levels can be dangerous for both the mother and the baby. The risk of miscarriage, stillbirth and birth defects are increased when diabetes isn't well-controlled. For the mother, diabetes increases the risk of diabetic ketoacidosis, diabetic eye problems (retinopathy), pregnancy-induced high blood pressure and preeclampsia."; s11="Heart and blood vessel disease"; s12="Nerve damage (neuropathy)"; s13="Eye damage"; s14="Foot damage"; s15="Skin and mouth conditions"; s16="Pregnancy complications"; /* tv1.setText("\n"+s1); tv2.setText("\n"+s2); tv3.setText("\n"+s3); tv4.setText("\n"+s4); tv5.setText("\n"+s5); tv6.setText("\n"+s6);*/ tv11.setText(""+s11); tv12.setText(""+s12); tv13.setText(""+s13); tv14.setText(""+s14); tv15.setText(""+s15); tv16.setText(""+s16); tv11.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(tv1.getText().toString().equals("")) { tv1.setText("\n\n" + s1); tv2.setText(""); tv3.setText(""); tv4.setText(""); tv5.setText(""); tv6.setText(""); tv11.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.up,0); tv12.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv13.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv14.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv15.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv16.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); } else { tv1.setText(""); tv11.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); } } }); tv12.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(tv2.getText().toString().equals("")) { tv1.setText(""); tv2.setText("\n" + s2); tv3.setText(""); tv4.setText(""); tv5.setText(""); tv6.setText(""); tv12.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.up,0); tv11.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv13.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv14.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv15.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv16.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); } else { tv2.setText(""); tv12.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); } } }); tv13.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(tv3.getText().toString().equals("")) { tv1.setText(""); tv2.setText(""); tv3.setText("\n" + s3); tv4.setText(""); tv5.setText(""); tv6.setText(""); tv13.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.up,0); tv11.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv12.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv14.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv15.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv16.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); } else { tv3.setText(""); tv13.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); } } }); tv14.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (tv4.getText().toString().equals("")) { tv1.setText(""); tv2.setText(""); tv3.setText(""); tv4.setText("\n" + s4); tv5.setText(""); tv6.setText(""); tv14.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.up,0); tv11.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv12.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv13.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv15.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv16.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); } else { tv4.setText(""); tv14.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); } } }); tv15.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(tv5.getText().toString().equals("")) { tv1.setText(""); tv2.setText(""); tv3.setText(""); tv4.setText(""); tv5.setText("\n" + s5); tv6.setText(""); tv15.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.up,0); tv11.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv12.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv13.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv14.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv16.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); } else { tv5.setText(""); tv15.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); } } }); tv16.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (tv6.getText().toString().equals("")){ tv1.setText(""); tv2.setText(""); tv3.setText(""); tv4.setText(""); tv5.setText(""); tv6.setText("\n" + s6); tv16.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.up,0); tv11.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv12.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv13.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv14.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv15.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); } else { tv6.setText(""); tv16.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); } } }); return view; } }
UTF-8
Java
11,150
java
frag_effect.java
Java
[]
null
[]
package com.example.mayur.doctor24_7.Diabeties; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.codesgood.views.JustifiedTextView; import com.example.mayur.doctor24_7.R; public class frag_effect extends Fragment { JustifiedTextView tv1,tv2,tv3,tv4,tv5,tv6; JustifiedTextView tv11,tv12,tv13,tv14,tv15,tv16; String s1,s2,s3,s4,s5,s6; String s11,s12,s13,s14,s15,s16; public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_frag_effect, container, false); Toast.makeText(getContext(),"effects",Toast.LENGTH_LONG).show(); tv1=(JustifiedTextView)view.findViewById(R.id.txt2); tv2=(JustifiedTextView)view.findViewById(R.id.txt4); tv3=(JustifiedTextView)view.findViewById(R.id.txt6); tv4=(JustifiedTextView)view.findViewById(R.id.txt8); tv5=(JustifiedTextView)view.findViewById(R.id.txt10); tv6=(JustifiedTextView)view.findViewById(R.id.txt12); tv11=(JustifiedTextView)view.findViewById(R.id.txt1); tv12=(JustifiedTextView)view.findViewById(R.id.txt3); tv13=(JustifiedTextView)view.findViewById(R.id.txt5); tv14=(JustifiedTextView)view.findViewById(R.id.txt7); tv15=(JustifiedTextView)view.findViewById(R.id.txt9); tv16=(JustifiedTextView)view.findViewById(R.id.txt11); s1="\n\t\tDiabetes dramatically increases your risk of various cardiovascular problems, including coronary artery disease with chest pain (angina), heart attack, stroke, narrowing of the arteries (atherosclerosis) and high blood pressure."; s2="\n\t\tExcess sugar can injure the walls of the tiny blood vessels (capillaries) that nourish your nerves, especially in the legs. This can cause tingling, numbness, burning or pain that usually begins at the tips of the toes or fingers and gradually spreads upward. Poorly controlled blood sugar could cause you to eventually lose all sense of feeling in the affected limbs."; s3="\n\t\tDiabetes can damage the blood vessels of the retina (diabetic retinopathy), potentially leading to blindness. Diabetes also increases the risk of other serious vision conditions, such as cataracts and glaucoma."; s4="\n\t\tNerve damage in the feet or poor blood flow to the feet increases the risk of various foot complications. Left untreated, cuts and blisters can become serious infections, which often heal poorly and may ultimately require toe, foot or leg amputation."; s5="\n\t\tDiabetes may leave you more susceptible to skin problems, including bacterial and fungal infections."; s6="\n\t\tHigh blood sugar levels can be dangerous for both the mother and the baby. The risk of miscarriage, stillbirth and birth defects are increased when diabetes isn't well-controlled. For the mother, diabetes increases the risk of diabetic ketoacidosis, diabetic eye problems (retinopathy), pregnancy-induced high blood pressure and preeclampsia."; s11="Heart and blood vessel disease"; s12="Nerve damage (neuropathy)"; s13="Eye damage"; s14="Foot damage"; s15="Skin and mouth conditions"; s16="Pregnancy complications"; /* tv1.setText("\n"+s1); tv2.setText("\n"+s2); tv3.setText("\n"+s3); tv4.setText("\n"+s4); tv5.setText("\n"+s5); tv6.setText("\n"+s6);*/ tv11.setText(""+s11); tv12.setText(""+s12); tv13.setText(""+s13); tv14.setText(""+s14); tv15.setText(""+s15); tv16.setText(""+s16); tv11.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(tv1.getText().toString().equals("")) { tv1.setText("\n\n" + s1); tv2.setText(""); tv3.setText(""); tv4.setText(""); tv5.setText(""); tv6.setText(""); tv11.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.up,0); tv12.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv13.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv14.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv15.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv16.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); } else { tv1.setText(""); tv11.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); } } }); tv12.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(tv2.getText().toString().equals("")) { tv1.setText(""); tv2.setText("\n" + s2); tv3.setText(""); tv4.setText(""); tv5.setText(""); tv6.setText(""); tv12.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.up,0); tv11.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv13.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv14.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv15.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv16.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); } else { tv2.setText(""); tv12.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); } } }); tv13.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(tv3.getText().toString().equals("")) { tv1.setText(""); tv2.setText(""); tv3.setText("\n" + s3); tv4.setText(""); tv5.setText(""); tv6.setText(""); tv13.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.up,0); tv11.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv12.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv14.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv15.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv16.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); } else { tv3.setText(""); tv13.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); } } }); tv14.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (tv4.getText().toString().equals("")) { tv1.setText(""); tv2.setText(""); tv3.setText(""); tv4.setText("\n" + s4); tv5.setText(""); tv6.setText(""); tv14.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.up,0); tv11.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv12.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv13.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv15.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv16.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); } else { tv4.setText(""); tv14.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); } } }); tv15.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(tv5.getText().toString().equals("")) { tv1.setText(""); tv2.setText(""); tv3.setText(""); tv4.setText(""); tv5.setText("\n" + s5); tv6.setText(""); tv15.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.up,0); tv11.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv12.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv13.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv14.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv16.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); } else { tv5.setText(""); tv15.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); } } }); tv16.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (tv6.getText().toString().equals("")){ tv1.setText(""); tv2.setText(""); tv3.setText(""); tv4.setText(""); tv5.setText(""); tv6.setText("\n" + s6); tv16.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.up,0); tv11.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv12.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv13.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv14.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); tv15.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); } else { tv6.setText(""); tv16.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.down,0); } } }); return view; } }
11,150
0.589865
0.553453
238
45.84874
49.936539
388
false
false
0
0
0
0
0
0
1.306723
false
false
12
4007d4b1163b17cafd5df5eb9beb843dc7d2ffbe
27,573,690,093,849
5bb2ec198da055148f6181474cfd5688baec96a6
/src/test/java/com/martinywwan/FlinkTwitterLauncherTest.java
233ac737eb33e68028563a40dd7392b3025aae52
[]
no_license
martinywwan/flink-twitter-streaming
https://github.com/martinywwan/flink-twitter-streaming
05cec5e57dab1a780d40197ee24125b7948bc938
b08b95ab86395c7ae5cb9ada48fb01dae60cf340
refs/heads/master
2020-03-31T15:02:57.111000
2018-10-11T20:10:44
2018-10-11T20:10:44
152,321,596
1
0
null
false
2018-10-11T20:05:53
2018-10-09T21:08:02
2018-10-09T21:30:09
2018-10-11T20:05:53
5
1
0
0
Java
false
null
package com.martinywwan; import com.martinywwan.configuration.TestConfiguration; import com.martinywwan.model.Tweet; import com.martinywwan.runner.FlinkTwitterLauncher; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Description; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.List; import static org.assertj.core.api.Java6Assertions.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = { Application.class, TestConfiguration.class}) @ActiveProfiles("test") public class FlinkTwitterLauncherTest { @Autowired private FlinkTwitterLauncher flinkTwitterLauncher; @Autowired private JpaRepository<Tweet, Long> tweetRepo; @Description("Dummy test source writes JSON test file into the Flink stream. " + "The JSON is mapped to a POJO and persisted to H2 database") @Test public void endToEndDataIngestion() throws Exception { Thread.sleep(200); List<Tweet> tweets = tweetRepo.findAll(); assertThat(tweets.size()).isEqualTo(1); Tweet tweet = tweets.get(0); assertThat(tweet.getTweetId()).isEqualTo(850006245121695744L); assertThat(tweet.getText()).isEqualTo("Example Tweet :) .. www.github.com/martinywwan"); } }
UTF-8
Java
1,573
java
FlinkTwitterLauncherTest.java
Java
[ { "context": "()).isEqualTo(\"Example Tweet :) .. www.github.com/martinywwan\");\n }\n}\n", "end": 1561, "score": 0.9996711015701294, "start": 1550, "tag": "USERNAME", "value": "martinywwan" } ]
null
[]
package com.martinywwan; import com.martinywwan.configuration.TestConfiguration; import com.martinywwan.model.Tweet; import com.martinywwan.runner.FlinkTwitterLauncher; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Description; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.List; import static org.assertj.core.api.Java6Assertions.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = { Application.class, TestConfiguration.class}) @ActiveProfiles("test") public class FlinkTwitterLauncherTest { @Autowired private FlinkTwitterLauncher flinkTwitterLauncher; @Autowired private JpaRepository<Tweet, Long> tweetRepo; @Description("Dummy test source writes JSON test file into the Flink stream. " + "The JSON is mapped to a POJO and persisted to H2 database") @Test public void endToEndDataIngestion() throws Exception { Thread.sleep(200); List<Tweet> tweets = tweetRepo.findAll(); assertThat(tweets.size()).isEqualTo(1); Tweet tweet = tweets.get(0); assertThat(tweet.getTweetId()).isEqualTo(850006245121695744L); assertThat(tweet.getText()).isEqualTo("Example Tweet :) .. www.github.com/martinywwan"); } }
1,573
0.771138
0.753338
41
37.365852
27.154263
96
false
false
0
0
0
0
0
0
0.585366
false
false
12
4fcf521c48b69d3c449fbe8ac12b474f7dc2bbf4
21,930,103,016,500
8fc1bc983dca9e5de34ea699e290f788538927c0
/app/src/main/java/com/coderockets/referandumproject/model/ModelUserQuestions.java
c8549cfafb963f0d3744ce460305c3f2f7b6d4f1
[]
no_license
CodeRockets/ReferandumProject
https://github.com/CodeRockets/ReferandumProject
b989c7101ae16b3ef10f7fc3f9baeebfa4fdc569
bf22dc7f4a2d4a24f27bd430892841aed12a2d38
refs/heads/master
2020-05-22T04:10:14.576000
2017-06-10T22:59:17
2017-06-10T22:59:17
60,269,489
4
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.coderockets.referandumproject.model; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.List; /** * Created by aykutasil on 6.09.2016. */ public class ModelUserQuestions { @SerializedName("questions") @Expose private Questions Questions; @SerializedName("favorites") @Expose private Favorites Favorites; public ModelUserQuestions.Questions getQuestions() { return Questions; } public void setQuestions(ModelUserQuestions.Questions questions) { Questions = questions; } public ModelUserQuestions.Favorites getFavorites() { return Favorites; } public void setFavorites(ModelUserQuestions.Favorites favorites) { Favorites = favorites; } public class Questions { @Expose @SerializedName("count") private int Count; @Expose @SerializedName("rows") private List<ModelQuestionInformation> Rows; public int getCount() { return Count; } public void setCount(int count) { Count = count; } public List<ModelQuestionInformation> getRows() { return Rows; } public void setRows(List<ModelQuestionInformation> rows) { Rows = rows; } } public class Favorites { @Expose @SerializedName("count") private int Count; @Expose @SerializedName("rows") private List<ModelQuestionInformation> Rows; public int getCount() { return Count; } public void setCount(int count) { Count = count; } public List<ModelQuestionInformation> getRows() { return Rows; } public void setRows(List<ModelQuestionInformation> rows) { Rows = rows; } } }
UTF-8
Java
1,931
java
ModelUserQuestions.java
Java
[ { "context": "edName;\n\nimport java.util.List;\n\n/**\n * Created by aykutasil on 6.09.2016.\n */\npublic class ModelUserQuestions", "end": 196, "score": 0.9996331930160522, "start": 187, "tag": "USERNAME", "value": "aykutasil" } ]
null
[]
package com.coderockets.referandumproject.model; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.List; /** * Created by aykutasil on 6.09.2016. */ public class ModelUserQuestions { @SerializedName("questions") @Expose private Questions Questions; @SerializedName("favorites") @Expose private Favorites Favorites; public ModelUserQuestions.Questions getQuestions() { return Questions; } public void setQuestions(ModelUserQuestions.Questions questions) { Questions = questions; } public ModelUserQuestions.Favorites getFavorites() { return Favorites; } public void setFavorites(ModelUserQuestions.Favorites favorites) { Favorites = favorites; } public class Questions { @Expose @SerializedName("count") private int Count; @Expose @SerializedName("rows") private List<ModelQuestionInformation> Rows; public int getCount() { return Count; } public void setCount(int count) { Count = count; } public List<ModelQuestionInformation> getRows() { return Rows; } public void setRows(List<ModelQuestionInformation> rows) { Rows = rows; } } public class Favorites { @Expose @SerializedName("count") private int Count; @Expose @SerializedName("rows") private List<ModelQuestionInformation> Rows; public int getCount() { return Count; } public void setCount(int count) { Count = count; } public List<ModelQuestionInformation> getRows() { return Rows; } public void setRows(List<ModelQuestionInformation> rows) { Rows = rows; } } }
1,931
0.60435
0.600725
92
19.98913
19.678114
70
false
false
0
0
0
0
0
0
0.23913
false
false
12
da3a631b9eb0a54bd824cea3b3705512e990d43d
32,323,923,930,222
c1a29ab2da713dea9f2aa5f439368ba179a9d321
/spring-boot-module/src/main/java/ru/mail/krivonos/al/controller/config/security/EncryptionConfig.java
936740e4052d19560666e5862bb21f083b1fd89e
[]
no_license
krivonos-alex/online_market_akrivonos
https://github.com/krivonos-alex/online_market_akrivonos
f14620e1545c099cd2051ec12e7e9f0c3772928d
93576775571f349745bb15818398f6c573092932
refs/heads/master
2020-05-18T07:00:12.828000
2019-06-10T06:34:32
2019-06-10T06:34:32
184,251,558
0
1
null
false
2019-06-10T06:34:57
2019-04-30T11:39:44
2019-06-10T06:34:36
2019-06-10T06:34:33
364
0
0
0
Java
false
false
package ru.mail.krivonos.al.controller.config.security; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; @Configuration public class EncryptionConfig { @Bean("passwordEncoder") public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(9); } }
UTF-8
Java
490
java
EncryptionConfig.java
Java
[]
null
[]
package ru.mail.krivonos.al.controller.config.security; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; @Configuration public class EncryptionConfig { @Bean("passwordEncoder") public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(9); } }
490
0.812245
0.810204
15
31.666666
25.834517
72
false
false
0
0
0
0
0
0
0.4
false
false
12
d2e250a1117be8a08d6ab8ea72182f289405b8ac
15,401,752,793,907
ca957060b411c88be41dfbf5dffa1fea2744f4a5
/src/org/sosy_lab/cpachecker/cpa/policyiteration/PolicyCPA.java
4c8eccf2865b0c7dc3afdfed246f9e91bc72d60e
[ "Apache-2.0" ]
permissive
45258E9F/IntPTI
https://github.com/45258E9F/IntPTI
62f705f539038f9457c818d515c81bf4621d7c85
e5dda55aafa2da3d977a9a62ad0857746dae3fe1
refs/heads/master
2020-12-30T14:34:30.174000
2018-06-01T07:32:07
2018-06-01T07:32:07
91,068,091
4
6
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * IntPTI: integer error fixing by proper-type inference * Copyright (c) 2017. * * Open-source component: * * CPAchecker * Copyright (C) 2007-2014 Dirk Beyer * * Guava: Google Core Libraries for Java * Copyright (C) 2010-2006 Google * * */ package org.sosy_lab.cpachecker.cpa.policyiteration; import com.google.common.base.Function; import com.google.common.base.Optional; import org.sosy_lab.common.ShutdownManager; import org.sosy_lab.common.ShutdownNotifier; import org.sosy_lab.common.configuration.Configuration; import org.sosy_lab.common.configuration.InvalidConfigurationException; import org.sosy_lab.common.configuration.Option; import org.sosy_lab.common.configuration.Options; import org.sosy_lab.common.log.LogManager; import org.sosy_lab.cpachecker.cfa.CFA; import org.sosy_lab.cpachecker.cfa.model.CFAEdge; import org.sosy_lab.cpachecker.cfa.model.CFANode; import org.sosy_lab.cpachecker.core.AnalysisDirection; import org.sosy_lab.cpachecker.core.algorithm.invariants.CPAInvariantGenerator; import org.sosy_lab.cpachecker.core.algorithm.invariants.DoNothingInvariantGenerator; import org.sosy_lab.cpachecker.core.algorithm.invariants.InvariantGenerator; import org.sosy_lab.cpachecker.core.defaults.AutomaticCPAFactory; import org.sosy_lab.cpachecker.core.defaults.SingleEdgeTransferRelation; import org.sosy_lab.cpachecker.core.defaults.StopSepOperator; import org.sosy_lab.cpachecker.core.interfaces.AbstractDomain; import org.sosy_lab.cpachecker.core.interfaces.AbstractState; import org.sosy_lab.cpachecker.core.interfaces.CPAFactory; import org.sosy_lab.cpachecker.core.interfaces.ConfigurableProgramAnalysis; import org.sosy_lab.cpachecker.core.interfaces.MergeOperator; import org.sosy_lab.cpachecker.core.interfaces.Precision; import org.sosy_lab.cpachecker.core.interfaces.PrecisionAdjustment; import org.sosy_lab.cpachecker.core.interfaces.PrecisionAdjustmentResult; import org.sosy_lab.cpachecker.core.interfaces.StateSpacePartition; import org.sosy_lab.cpachecker.core.interfaces.Statistics; import org.sosy_lab.cpachecker.core.interfaces.StatisticsProvider; import org.sosy_lab.cpachecker.core.interfaces.StopOperator; import org.sosy_lab.cpachecker.core.interfaces.TransferRelation; import org.sosy_lab.cpachecker.core.interfaces.conditions.AdjustableConditionCPA; import org.sosy_lab.cpachecker.core.interfaces.conditions.ReachedSetAdjustingCPA; import org.sosy_lab.cpachecker.core.reachedset.ReachedSet; import org.sosy_lab.cpachecker.core.reachedset.UnmodifiableReachedSet; import org.sosy_lab.cpachecker.cpa.policyiteration.congruence.CongruenceManager; import org.sosy_lab.cpachecker.cpa.policyiteration.polyhedra.PolyhedraWideningManager; import org.sosy_lab.cpachecker.exceptions.CPAException; import org.sosy_lab.cpachecker.exceptions.CPATransferException; import org.sosy_lab.cpachecker.util.predicates.pathformula.CachingPathFormulaManager; import org.sosy_lab.cpachecker.util.predicates.pathformula.PathFormulaManager; import org.sosy_lab.cpachecker.util.predicates.pathformula.PathFormulaManagerImpl; import org.sosy_lab.cpachecker.util.predicates.smt.FormulaManagerView; import org.sosy_lab.cpachecker.util.predicates.smt.Solver; import java.util.Collection; import java.util.List; import javax.annotation.Nullable; /** * Policy iteration CPA. */ @Options(prefix = "cpa.stator.policy") public class PolicyCPA extends SingleEdgeTransferRelation implements ConfigurableProgramAnalysis, StatisticsProvider, AbstractDomain, PrecisionAdjustment, AdjustableConditionCPA, ReachedSetAdjustingCPA, MergeOperator { @Option(secure = true, description = "Generate invariants and strengthen the formulas during abstraction with them.") private boolean useInvariantsForAbstraction = false; @Option(secure = true, description = "Cache formulas produced by path formula manager") private boolean useCachingPathFormulaManager = true; private final Configuration config; private final IPolicyIterationManager policyIterationManager; private final LogManager logger; private final PolicyIterationStatistics statistics; private final StopOperator stopOperator; public static CPAFactory factory() { return AutomaticCPAFactory.forType(PolicyCPA.class); } @SuppressWarnings("unused") private PolicyCPA( Configuration pConfig, LogManager pLogger, ShutdownNotifier shutdownNotifier, CFA cfa ) throws InvalidConfigurationException, CPAException { pConfig.inject(this); logger = pLogger; config = pConfig; Solver solver = Solver.create(config, pLogger, shutdownNotifier); FormulaManagerView formulaManager = solver.getFormulaManager(); PathFormulaManager pathFormulaManager = new PathFormulaManagerImpl( formulaManager, pConfig, pLogger, shutdownNotifier, cfa, AnalysisDirection.FORWARD); if (useCachingPathFormulaManager) { pathFormulaManager = new CachingPathFormulaManager(pathFormulaManager); } InvariantGenerator invariantGenerator; if (useInvariantsForAbstraction) { ShutdownManager invariantShutdown = ShutdownManager.createWithParent(shutdownNotifier); invariantGenerator = CPAInvariantGenerator.create( config, logger, invariantShutdown, Optional.<ShutdownManager>absent(), cfa); } else { invariantGenerator = new DoNothingInvariantGenerator(); } statistics = new PolicyIterationStatistics(cfa); TemplateManager templateManager = new TemplateManager(pLogger, pConfig, cfa, statistics); CongruenceManager pCongruenceManager = new CongruenceManager( pConfig, solver, templateManager, formulaManager, statistics, pathFormulaManager); StateFormulaConversionManager stateFormulaConversionManager = new StateFormulaConversionManager( formulaManager, pathFormulaManager, pCongruenceManager, templateManager, invariantGenerator); ValueDeterminationManager valueDeterminationFormulaManager = new ValueDeterminationManager( formulaManager, pLogger, templateManager, pathFormulaManager, stateFormulaConversionManager); FormulaLinearizationManager formulaLinearizationManager = new FormulaLinearizationManager( formulaManager.getBooleanFormulaManager(), formulaManager, formulaManager.getIntegerFormulaManager(), statistics); PolyhedraWideningManager pPwm = new PolyhedraWideningManager( statistics, logger); policyIterationManager = new PolicyIterationManager( pConfig, formulaManager, cfa, pathFormulaManager, solver, pLogger, shutdownNotifier, templateManager, valueDeterminationFormulaManager, statistics, formulaLinearizationManager, pCongruenceManager, pPwm, invariantGenerator, stateFormulaConversionManager); stopOperator = new StopSepOperator(this); } @Override public AbstractState getInitialState(CFANode node, StateSpacePartition pPartition) { return policyIterationManager.getInitialState(node); } @Override public AbstractState join(AbstractState state1, AbstractState state2) throws CPAException, InterruptedException { throw new UnsupportedOperationException("PolicyCPA should be used with its" + " own merge operator"); } /** * We only keep one abstract state per node. * {@code #isLessOrEqual} is called after the merge, but as our * merge is always joining two states {@code #isLessOrEqual} should * always return {@code true}. */ @Override public boolean isLessOrEqual(AbstractState state1, AbstractState state2) throws CPAException, InterruptedException { return policyIterationManager.isLessOrEqual( (PolicyState) state1, (PolicyState) state2 ); } @Override public Collection<? extends AbstractState> getAbstractSuccessorsForEdge( AbstractState pState, List<AbstractState> otherStates, Precision pPrecision, CFAEdge pEdge ) throws CPATransferException, InterruptedException { return policyIterationManager.getAbstractSuccessors( (PolicyState) pState, pEdge ); } @Override public Collection<? extends AbstractState> strengthen( AbstractState state, List<AbstractState> otherStates, @Nullable CFAEdge cfaEdge, Precision precision) throws CPATransferException, InterruptedException { // We perform strengthening in precision adjustment. return null; } @Override public AbstractDomain getAbstractDomain() { return this; } @Override public TransferRelation getTransferRelation() { return this; } @Override public MergeOperator getMergeOperator() { return this; } @Override public StopOperator getStopOperator() { return stopOperator; } @Override public PrecisionAdjustment getPrecisionAdjustment() { return this; } @Override public PolicyPrecision getInitialPrecision( CFANode node, StateSpacePartition pPartition) { return PolicyPrecision.empty(); } @Override public void collectStatistics(Collection<Statistics> statsCollection) { statsCollection.add(statistics); } @Override public Optional<PrecisionAdjustmentResult> prec( AbstractState state, Precision precision, UnmodifiableReachedSet states, Function<AbstractState, AbstractState> projection, AbstractState fullState) throws CPAException, InterruptedException { return policyIterationManager.precisionAdjustment( (PolicyState) state, (PolicyPrecision) precision, states, fullState); } @Override public boolean adjustPrecision() { return policyIterationManager.adjustPrecision(); } @Override public void adjustReachedSet(ReachedSet pReachedSet) { policyIterationManager.adjustReachedSet(pReachedSet); } public LogManager getLogger() { return logger; } public Configuration getConfig() { return config; } @Override public AbstractState merge( AbstractState state1, AbstractState state2, Precision precision) throws CPAException, InterruptedException { return policyIterationManager.merge( (PolicyState) state1, (PolicyState) state2, (PolicyPrecision) precision ); } }
UTF-8
Java
10,420
java
PolicyCPA.java
Java
[ { "context": "nent:\n *\n * CPAchecker\n * Copyright (C) 2007-2014 Dirk Beyer\n *\n * Guava: Google Core Libraries for Java\n * Co", "end": 167, "score": 0.9997316598892212, "start": 157, "tag": "NAME", "value": "Dirk Beyer" } ]
null
[]
/* * IntPTI: integer error fixing by proper-type inference * Copyright (c) 2017. * * Open-source component: * * CPAchecker * Copyright (C) 2007-2014 <NAME> * * Guava: Google Core Libraries for Java * Copyright (C) 2010-2006 Google * * */ package org.sosy_lab.cpachecker.cpa.policyiteration; import com.google.common.base.Function; import com.google.common.base.Optional; import org.sosy_lab.common.ShutdownManager; import org.sosy_lab.common.ShutdownNotifier; import org.sosy_lab.common.configuration.Configuration; import org.sosy_lab.common.configuration.InvalidConfigurationException; import org.sosy_lab.common.configuration.Option; import org.sosy_lab.common.configuration.Options; import org.sosy_lab.common.log.LogManager; import org.sosy_lab.cpachecker.cfa.CFA; import org.sosy_lab.cpachecker.cfa.model.CFAEdge; import org.sosy_lab.cpachecker.cfa.model.CFANode; import org.sosy_lab.cpachecker.core.AnalysisDirection; import org.sosy_lab.cpachecker.core.algorithm.invariants.CPAInvariantGenerator; import org.sosy_lab.cpachecker.core.algorithm.invariants.DoNothingInvariantGenerator; import org.sosy_lab.cpachecker.core.algorithm.invariants.InvariantGenerator; import org.sosy_lab.cpachecker.core.defaults.AutomaticCPAFactory; import org.sosy_lab.cpachecker.core.defaults.SingleEdgeTransferRelation; import org.sosy_lab.cpachecker.core.defaults.StopSepOperator; import org.sosy_lab.cpachecker.core.interfaces.AbstractDomain; import org.sosy_lab.cpachecker.core.interfaces.AbstractState; import org.sosy_lab.cpachecker.core.interfaces.CPAFactory; import org.sosy_lab.cpachecker.core.interfaces.ConfigurableProgramAnalysis; import org.sosy_lab.cpachecker.core.interfaces.MergeOperator; import org.sosy_lab.cpachecker.core.interfaces.Precision; import org.sosy_lab.cpachecker.core.interfaces.PrecisionAdjustment; import org.sosy_lab.cpachecker.core.interfaces.PrecisionAdjustmentResult; import org.sosy_lab.cpachecker.core.interfaces.StateSpacePartition; import org.sosy_lab.cpachecker.core.interfaces.Statistics; import org.sosy_lab.cpachecker.core.interfaces.StatisticsProvider; import org.sosy_lab.cpachecker.core.interfaces.StopOperator; import org.sosy_lab.cpachecker.core.interfaces.TransferRelation; import org.sosy_lab.cpachecker.core.interfaces.conditions.AdjustableConditionCPA; import org.sosy_lab.cpachecker.core.interfaces.conditions.ReachedSetAdjustingCPA; import org.sosy_lab.cpachecker.core.reachedset.ReachedSet; import org.sosy_lab.cpachecker.core.reachedset.UnmodifiableReachedSet; import org.sosy_lab.cpachecker.cpa.policyiteration.congruence.CongruenceManager; import org.sosy_lab.cpachecker.cpa.policyiteration.polyhedra.PolyhedraWideningManager; import org.sosy_lab.cpachecker.exceptions.CPAException; import org.sosy_lab.cpachecker.exceptions.CPATransferException; import org.sosy_lab.cpachecker.util.predicates.pathformula.CachingPathFormulaManager; import org.sosy_lab.cpachecker.util.predicates.pathformula.PathFormulaManager; import org.sosy_lab.cpachecker.util.predicates.pathformula.PathFormulaManagerImpl; import org.sosy_lab.cpachecker.util.predicates.smt.FormulaManagerView; import org.sosy_lab.cpachecker.util.predicates.smt.Solver; import java.util.Collection; import java.util.List; import javax.annotation.Nullable; /** * Policy iteration CPA. */ @Options(prefix = "cpa.stator.policy") public class PolicyCPA extends SingleEdgeTransferRelation implements ConfigurableProgramAnalysis, StatisticsProvider, AbstractDomain, PrecisionAdjustment, AdjustableConditionCPA, ReachedSetAdjustingCPA, MergeOperator { @Option(secure = true, description = "Generate invariants and strengthen the formulas during abstraction with them.") private boolean useInvariantsForAbstraction = false; @Option(secure = true, description = "Cache formulas produced by path formula manager") private boolean useCachingPathFormulaManager = true; private final Configuration config; private final IPolicyIterationManager policyIterationManager; private final LogManager logger; private final PolicyIterationStatistics statistics; private final StopOperator stopOperator; public static CPAFactory factory() { return AutomaticCPAFactory.forType(PolicyCPA.class); } @SuppressWarnings("unused") private PolicyCPA( Configuration pConfig, LogManager pLogger, ShutdownNotifier shutdownNotifier, CFA cfa ) throws InvalidConfigurationException, CPAException { pConfig.inject(this); logger = pLogger; config = pConfig; Solver solver = Solver.create(config, pLogger, shutdownNotifier); FormulaManagerView formulaManager = solver.getFormulaManager(); PathFormulaManager pathFormulaManager = new PathFormulaManagerImpl( formulaManager, pConfig, pLogger, shutdownNotifier, cfa, AnalysisDirection.FORWARD); if (useCachingPathFormulaManager) { pathFormulaManager = new CachingPathFormulaManager(pathFormulaManager); } InvariantGenerator invariantGenerator; if (useInvariantsForAbstraction) { ShutdownManager invariantShutdown = ShutdownManager.createWithParent(shutdownNotifier); invariantGenerator = CPAInvariantGenerator.create( config, logger, invariantShutdown, Optional.<ShutdownManager>absent(), cfa); } else { invariantGenerator = new DoNothingInvariantGenerator(); } statistics = new PolicyIterationStatistics(cfa); TemplateManager templateManager = new TemplateManager(pLogger, pConfig, cfa, statistics); CongruenceManager pCongruenceManager = new CongruenceManager( pConfig, solver, templateManager, formulaManager, statistics, pathFormulaManager); StateFormulaConversionManager stateFormulaConversionManager = new StateFormulaConversionManager( formulaManager, pathFormulaManager, pCongruenceManager, templateManager, invariantGenerator); ValueDeterminationManager valueDeterminationFormulaManager = new ValueDeterminationManager( formulaManager, pLogger, templateManager, pathFormulaManager, stateFormulaConversionManager); FormulaLinearizationManager formulaLinearizationManager = new FormulaLinearizationManager( formulaManager.getBooleanFormulaManager(), formulaManager, formulaManager.getIntegerFormulaManager(), statistics); PolyhedraWideningManager pPwm = new PolyhedraWideningManager( statistics, logger); policyIterationManager = new PolicyIterationManager( pConfig, formulaManager, cfa, pathFormulaManager, solver, pLogger, shutdownNotifier, templateManager, valueDeterminationFormulaManager, statistics, formulaLinearizationManager, pCongruenceManager, pPwm, invariantGenerator, stateFormulaConversionManager); stopOperator = new StopSepOperator(this); } @Override public AbstractState getInitialState(CFANode node, StateSpacePartition pPartition) { return policyIterationManager.getInitialState(node); } @Override public AbstractState join(AbstractState state1, AbstractState state2) throws CPAException, InterruptedException { throw new UnsupportedOperationException("PolicyCPA should be used with its" + " own merge operator"); } /** * We only keep one abstract state per node. * {@code #isLessOrEqual} is called after the merge, but as our * merge is always joining two states {@code #isLessOrEqual} should * always return {@code true}. */ @Override public boolean isLessOrEqual(AbstractState state1, AbstractState state2) throws CPAException, InterruptedException { return policyIterationManager.isLessOrEqual( (PolicyState) state1, (PolicyState) state2 ); } @Override public Collection<? extends AbstractState> getAbstractSuccessorsForEdge( AbstractState pState, List<AbstractState> otherStates, Precision pPrecision, CFAEdge pEdge ) throws CPATransferException, InterruptedException { return policyIterationManager.getAbstractSuccessors( (PolicyState) pState, pEdge ); } @Override public Collection<? extends AbstractState> strengthen( AbstractState state, List<AbstractState> otherStates, @Nullable CFAEdge cfaEdge, Precision precision) throws CPATransferException, InterruptedException { // We perform strengthening in precision adjustment. return null; } @Override public AbstractDomain getAbstractDomain() { return this; } @Override public TransferRelation getTransferRelation() { return this; } @Override public MergeOperator getMergeOperator() { return this; } @Override public StopOperator getStopOperator() { return stopOperator; } @Override public PrecisionAdjustment getPrecisionAdjustment() { return this; } @Override public PolicyPrecision getInitialPrecision( CFANode node, StateSpacePartition pPartition) { return PolicyPrecision.empty(); } @Override public void collectStatistics(Collection<Statistics> statsCollection) { statsCollection.add(statistics); } @Override public Optional<PrecisionAdjustmentResult> prec( AbstractState state, Precision precision, UnmodifiableReachedSet states, Function<AbstractState, AbstractState> projection, AbstractState fullState) throws CPAException, InterruptedException { return policyIterationManager.precisionAdjustment( (PolicyState) state, (PolicyPrecision) precision, states, fullState); } @Override public boolean adjustPrecision() { return policyIterationManager.adjustPrecision(); } @Override public void adjustReachedSet(ReachedSet pReachedSet) { policyIterationManager.adjustReachedSet(pReachedSet); } public LogManager getLogger() { return logger; } public Configuration getConfig() { return config; } @Override public AbstractState merge( AbstractState state1, AbstractState state2, Precision precision) throws CPAException, InterruptedException { return policyIterationManager.merge( (PolicyState) state1, (PolicyState) state2, (PolicyPrecision) precision ); } }
10,416
0.765739
0.76286
293
34.559727
26.566563
119
false
false
0
0
0
0
0
0
0.624573
false
false
12
616d8b5111f3c461683c9b53de159aabf4360d50
23,063,974,391,386
44653d1b2dc395309fe504148dcd19d884db50b4
/org.neuro4j.studio.core.diagram/src/org/neuro4j/studio/core/diagram/edit/shapes/FixedConnectionAnchor.java
000fb591c2982c0c4fe7453a22d51745f1824262
[ "Apache-2.0" ]
permissive
eternita/studio
https://github.com/eternita/studio
14e84b2cc3b78ac93c0abca16695b5d954821225
d5317386af66542c51880ac7d06176aee89b0d55
refs/heads/master
2021-06-17T02:23:24.712000
2017-05-17T04:43:07
2017-05-17T04:43:07
10,698,953
2
5
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright (c) 2013-2014, Neuro4j.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.neuro4j.studio.core.diagram.edit.shapes; import org.eclipse.draw2d.AbstractConnectionAnchor; import org.eclipse.draw2d.IFigure; import org.eclipse.draw2d.geometry.Point; import org.eclipse.draw2d.geometry.PrecisionPoint; import org.eclipse.draw2d.geometry.Rectangle; import org.neuro4j.studio.core.ActionNode; import org.neuro4j.studio.core.diagram.edit.shapes.anchors.NorthEastSouthFixedAnchors; public class FixedConnectionAnchor extends AbstractConnectionAnchor { private double xOffset; private double yOffset; private String type; public FixedConnectionAnchor(IFigure owner, PrecisionPoint offset) { this(owner, offset.preciseX, offset.preciseY); } public FixedConnectionAnchor(IFigure owner, double xOffset, double yOffset) { super(owner); this.xOffset = xOffset; this.yOffset = yOffset; } @Override public Point getLocation(Point point) { return getLocation(); } public Point getLocation() { Rectangle r = getOwner().getBounds(); Point p = new PrecisionPoint(r.x + r.width * xOffset, r.y + r.height * yOffset); getOwner().translateToAbsolute(p); return p; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Point getReferencePoint() { if (getOwner() == null) return null; else { Point ref = getOwner().getBounds().getCenter(); getOwner().translateToAbsolute(ref); return ref; } } }
UTF-8
Java
2,223
java
FixedConnectionAnchor.java
Java
[]
null
[]
/* * Copyright (c) 2013-2014, Neuro4j.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.neuro4j.studio.core.diagram.edit.shapes; import org.eclipse.draw2d.AbstractConnectionAnchor; import org.eclipse.draw2d.IFigure; import org.eclipse.draw2d.geometry.Point; import org.eclipse.draw2d.geometry.PrecisionPoint; import org.eclipse.draw2d.geometry.Rectangle; import org.neuro4j.studio.core.ActionNode; import org.neuro4j.studio.core.diagram.edit.shapes.anchors.NorthEastSouthFixedAnchors; public class FixedConnectionAnchor extends AbstractConnectionAnchor { private double xOffset; private double yOffset; private String type; public FixedConnectionAnchor(IFigure owner, PrecisionPoint offset) { this(owner, offset.preciseX, offset.preciseY); } public FixedConnectionAnchor(IFigure owner, double xOffset, double yOffset) { super(owner); this.xOffset = xOffset; this.yOffset = yOffset; } @Override public Point getLocation(Point point) { return getLocation(); } public Point getLocation() { Rectangle r = getOwner().getBounds(); Point p = new PrecisionPoint(r.x + r.width * xOffset, r.y + r.height * yOffset); getOwner().translateToAbsolute(p); return p; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Point getReferencePoint() { if (getOwner() == null) return null; else { Point ref = getOwner().getBounds().getCenter(); getOwner().translateToAbsolute(ref); return ref; } } }
2,223
0.680162
0.670715
75
28.653334
25.604424
88
false
false
0
0
0
0
0
0
0.506667
false
false
12
5594c55eb8660260d9b29e047883504475c59635
14,302,241,107,011
d74ee1d0fa564d37255a3bf310dce1cd48abf651
/management_bank/src/management_bank/Main.java
3d8971b7ef7c0ee2af44cb3fae0f8d343284f3d9
[]
no_license
long-joecoffee/Javacore
https://github.com/long-joecoffee/Javacore
50be26cd84a56c9ffd06e4e32b344a4963916985
a4663fb0bda8d01b1a4ea31ecb292fdc6adb33c4
refs/heads/main
2023-03-07T00:14:39.670000
2021-02-23T03:34:56
2021-02-23T03:34:56
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package management_bank; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Account[] accounts = null; boolean run = true; do { menu(); int option = Integer.parseInt(scanner.nextLine()); switch (option) { case 1: { System.out.println("How many accounts do you want ?"); accounts = new Account[Integer.parseInt(scanner.nextLine())]; for (int index = 0; index < accounts.length; index++) { System.out.println("Account " + (index + 1)); accounts[index] = new Account(); accounts[index].inputInfoAccount(scanner); } break; } case 2: { if (accounts != null) { for (Account account : accounts) { account.outInfoAccount(); } } else { System.out.println("Accounts are empty"); } break; } case 3: { if (accounts == null) { System.out.println("Accounts are empty"); break; } int checkIndex = -1; System.out.println("Please enter your account number"); int accountNumber = Integer.parseInt(scanner.nextLine()); for (int index = 0; index < accounts.length; index++) { if (accounts[index].getAccountNumber() == accountNumber) { checkIndex = index; break; } } if (checkIndex < 0) { System.out.println("Please try again"); break; } System.out.println("How much money do you want to add ?"); double money = Double.parseDouble(scanner.nextLine()); accounts[checkIndex].inputMoneyToCard(money, accountNumber); break; } case 4: { if (accounts == null) { System.out.println("Accounts are empty"); break; } int checkIndex = -1; System.out.println("Please enter your account number"); int accountNumber = Integer.parseInt(scanner.nextLine()); for (int index = 0; index < accounts.length; index++) { if (accounts[index].getAccountNumber() == accountNumber) { checkIndex = index; break; } } if (checkIndex < 0) { System.out.println("Please try again"); break; } System.out.println("How much money do you want to withdrawn ?"); double money = Double.parseDouble(scanner.nextLine()); accounts[checkIndex].withdrawMoneyFromCard(money, accountNumber); break; } case 5: { if (accounts == null) { System.out.println("Accounts are empty"); break; } int checkIndex = -1; System.out.println("Please enter your account number"); int accountNumber = Integer.parseInt(scanner.nextLine()); for (int index = 0; index < accounts.length; index++) { if (accounts[index].getAccountNumber() == accountNumber) { checkIndex = index; break; } } if (checkIndex < 0) { System.out.println("Please try again"); break; } accounts[checkIndex].expiratedDateMoney(); break; } case 6: { if (accounts == null) { System.out.println("Accounts are empty"); break; } // Person Transfers Money int indexOfPersonTransferMoney = -1; System.out.println("Please enter your account number"); int accountTransferNumber = Integer.parseInt(scanner.nextLine()); for (int index = 0; index < accounts.length; index++) { if (accounts[index].getAccountNumber() == accountTransferNumber) { indexOfPersonTransferMoney = index; break; } } if (indexOfPersonTransferMoney < 0) { System.out.println("Person transfer is invalid"); break; } // Person Received Money int indexOfPersonReceivedMoney = -1; System.out.println("Please enter your account received number"); int accountReceivedNumber = Integer.parseInt(scanner.nextLine()); if (accountTransferNumber == accountReceivedNumber) { System.out.println("Person transfer and person received are invalid"); break; } for (int index = 0; index < accounts.length; index++) { if (accounts[index].getAccountNumber() == accountReceivedNumber) { indexOfPersonReceivedMoney = index; break; } } if (indexOfPersonReceivedMoney < 0) { System.out.println("Person received is invalid"); break; } // Process Transfer Money And Received Money System.out.println("How much money do you want to transfer ?"); double transferMoney = Double.parseDouble(scanner.nextLine()); accounts[indexOfPersonReceivedMoney].inputMoneyToCard(transferMoney, accountReceivedNumber); accounts[indexOfPersonTransferMoney].withdrawMoneyFromCard(transferMoney, accountTransferNumber); break; } default: run = false; System.out.println("===============End==============="); break; } } while (run); } public static void menu() { System.out.println("What do you want ?"); System.out.println("1. Enter info for client"); System.out.println("2. Show all info of client"); System.out.println("3. Input money to card"); System.out.println("4. With drawn money from card"); System.out.println("5. Expire date money of client"); System.out.println("6. Transfer money to another card"); System.out.println("7. Tap others number to stop program"); } }
UTF-8
Java
5,223
java
Main.java
Java
[]
null
[]
package management_bank; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Account[] accounts = null; boolean run = true; do { menu(); int option = Integer.parseInt(scanner.nextLine()); switch (option) { case 1: { System.out.println("How many accounts do you want ?"); accounts = new Account[Integer.parseInt(scanner.nextLine())]; for (int index = 0; index < accounts.length; index++) { System.out.println("Account " + (index + 1)); accounts[index] = new Account(); accounts[index].inputInfoAccount(scanner); } break; } case 2: { if (accounts != null) { for (Account account : accounts) { account.outInfoAccount(); } } else { System.out.println("Accounts are empty"); } break; } case 3: { if (accounts == null) { System.out.println("Accounts are empty"); break; } int checkIndex = -1; System.out.println("Please enter your account number"); int accountNumber = Integer.parseInt(scanner.nextLine()); for (int index = 0; index < accounts.length; index++) { if (accounts[index].getAccountNumber() == accountNumber) { checkIndex = index; break; } } if (checkIndex < 0) { System.out.println("Please try again"); break; } System.out.println("How much money do you want to add ?"); double money = Double.parseDouble(scanner.nextLine()); accounts[checkIndex].inputMoneyToCard(money, accountNumber); break; } case 4: { if (accounts == null) { System.out.println("Accounts are empty"); break; } int checkIndex = -1; System.out.println("Please enter your account number"); int accountNumber = Integer.parseInt(scanner.nextLine()); for (int index = 0; index < accounts.length; index++) { if (accounts[index].getAccountNumber() == accountNumber) { checkIndex = index; break; } } if (checkIndex < 0) { System.out.println("Please try again"); break; } System.out.println("How much money do you want to withdrawn ?"); double money = Double.parseDouble(scanner.nextLine()); accounts[checkIndex].withdrawMoneyFromCard(money, accountNumber); break; } case 5: { if (accounts == null) { System.out.println("Accounts are empty"); break; } int checkIndex = -1; System.out.println("Please enter your account number"); int accountNumber = Integer.parseInt(scanner.nextLine()); for (int index = 0; index < accounts.length; index++) { if (accounts[index].getAccountNumber() == accountNumber) { checkIndex = index; break; } } if (checkIndex < 0) { System.out.println("Please try again"); break; } accounts[checkIndex].expiratedDateMoney(); break; } case 6: { if (accounts == null) { System.out.println("Accounts are empty"); break; } // Person Transfers Money int indexOfPersonTransferMoney = -1; System.out.println("Please enter your account number"); int accountTransferNumber = Integer.parseInt(scanner.nextLine()); for (int index = 0; index < accounts.length; index++) { if (accounts[index].getAccountNumber() == accountTransferNumber) { indexOfPersonTransferMoney = index; break; } } if (indexOfPersonTransferMoney < 0) { System.out.println("Person transfer is invalid"); break; } // Person Received Money int indexOfPersonReceivedMoney = -1; System.out.println("Please enter your account received number"); int accountReceivedNumber = Integer.parseInt(scanner.nextLine()); if (accountTransferNumber == accountReceivedNumber) { System.out.println("Person transfer and person received are invalid"); break; } for (int index = 0; index < accounts.length; index++) { if (accounts[index].getAccountNumber() == accountReceivedNumber) { indexOfPersonReceivedMoney = index; break; } } if (indexOfPersonReceivedMoney < 0) { System.out.println("Person received is invalid"); break; } // Process Transfer Money And Received Money System.out.println("How much money do you want to transfer ?"); double transferMoney = Double.parseDouble(scanner.nextLine()); accounts[indexOfPersonReceivedMoney].inputMoneyToCard(transferMoney, accountReceivedNumber); accounts[indexOfPersonTransferMoney].withdrawMoneyFromCard(transferMoney, accountTransferNumber); break; } default: run = false; System.out.println("===============End==============="); break; } } while (run); } public static void menu() { System.out.println("What do you want ?"); System.out.println("1. Enter info for client"); System.out.println("2. Show all info of client"); System.out.println("3. Input money to card"); System.out.println("4. With drawn money from card"); System.out.println("5. Expire date money of client"); System.out.println("6. Transfer money to another card"); System.out.println("7. Tap others number to stop program"); } }
5,223
0.638522
0.632778
206
24.354368
24.705757
101
false
false
0
0
0
0
0
0
3.548544
false
false
12
e27d7c98f0c025c2b354d67abc471f7f033b9230
13,915,694,043,750
fc85f14f2979ba1a31f2f99a2de463dfb14fe3e5
/statistics/src/main/java/com/statistics/service/CommentService.java
1f0e606f5a0b3f54c4f5f8114d338d83fd0f921f
[]
no_license
petarcurcin/Rent-a-Car-MicroservicesApp
https://github.com/petarcurcin/Rent-a-Car-MicroservicesApp
0220d2a43c12dc6040379c6296abd1b30df87ff1
cfe492db8248cc48a5bb5c54519b5c745b30b51f
refs/heads/master
2022-11-09T12:22:20.648000
2020-06-30T16:55:40
2020-06-30T16:55:40
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.statistics.service; import com.statistics.dto.CommentDTO; import java.util.List; public interface CommentService { List<CommentDTO> findUnprocessed(); void changeStatus(CommentDTO comment); Long addComment(CommentDTO dto); Long addCommentOwner(CommentDTO dto); List<CommentDTO> findProcessedAdvertisementComments(long id); }
UTF-8
Java
361
java
CommentService.java
Java
[]
null
[]
package com.statistics.service; import com.statistics.dto.CommentDTO; import java.util.List; public interface CommentService { List<CommentDTO> findUnprocessed(); void changeStatus(CommentDTO comment); Long addComment(CommentDTO dto); Long addCommentOwner(CommentDTO dto); List<CommentDTO> findProcessedAdvertisementComments(long id); }
361
0.778393
0.778393
14
24.785715
20.337082
65
false
false
0
0
0
0
0
0
0.571429
false
false
12
2e367866b35f3f07a6f684c9cd67a94046f4cb35
2,765,958,947,679
e694a0823c3c915f65a8a25e104866ed916b9193
/src/Dynamic/기타리스트.java
2168389b5527462ba64f7f01bb96af43399d97a0
[]
no_license
chd830/Algorithm
https://github.com/chd830/Algorithm
2f1f61b8af94bfe02d4b9953ca52d2ebe1963c9f
1bfe2cce65d993ab91a705b518e573875359c384
refs/heads/master
2022-08-18T04:23:06.435000
2022-08-05T03:44:25
2022-08-05T03:44:25
214,943,907
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Dynamic; import java.util.*; import java.io.*; // https://www.acmicpc.net/problem/1495 public class 기타리스트 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer token = new StringTokenizer(br.readLine()); int N = Integer.parseInt(token.nextToken()); int start = Integer.parseInt(token.nextToken()); int limit = Integer.parseInt(token.nextToken()); token = new StringTokenizer(br.readLine()); int[] arr = new int[N+1]; for(int i = 1; i <= N; i++) arr[i] = Integer.parseInt(token.nextToken()); boolean[][] dp = new boolean[N+1][limit+1]; dp[0][start] = true; for(int i = 1; i <= N; i++) { for(int j = 0; j <= limit; j++) { if(!dp[i-1][j]) continue; if(j-arr[i] >= 0) dp[i][j-arr[i]] = true; if(j+arr[i] <= limit) dp[i][j+arr[i]] = true; } } int result = -1; for (int j = limit; j >= 0; j--) { if (dp[N][j]) { result = j; break; } } System.out.println(result); } }
UTF-8
Java
1,315
java
기타리스트.java
Java
[]
null
[]
package Dynamic; import java.util.*; import java.io.*; // https://www.acmicpc.net/problem/1495 public class 기타리스트 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer token = new StringTokenizer(br.readLine()); int N = Integer.parseInt(token.nextToken()); int start = Integer.parseInt(token.nextToken()); int limit = Integer.parseInt(token.nextToken()); token = new StringTokenizer(br.readLine()); int[] arr = new int[N+1]; for(int i = 1; i <= N; i++) arr[i] = Integer.parseInt(token.nextToken()); boolean[][] dp = new boolean[N+1][limit+1]; dp[0][start] = true; for(int i = 1; i <= N; i++) { for(int j = 0; j <= limit; j++) { if(!dp[i-1][j]) continue; if(j-arr[i] >= 0) dp[i][j-arr[i]] = true; if(j+arr[i] <= limit) dp[i][j+arr[i]] = true; } } int result = -1; for (int j = limit; j >= 0; j--) { if (dp[N][j]) { result = j; break; } } System.out.println(result); } }
1,315
0.481226
0.469732
39
32.46154
19.387871
81
false
false
0
0
0
0
0
0
0.717949
false
false
12
68de7d9cd573f011a28cc0dc49e19d347118bf81
30,056,181,202,669
41648f15cf0cfce8f69e6d5fb1e1536dfd3cfd93
/app/src/main/java/com/app24announce/dupat/id/DetailTugasPage.java
79482e884701fd53faeb6682157eec2540dd90ce
[]
no_license
dinopriyano/Dupat-Smart-School
https://github.com/dinopriyano/Dupat-Smart-School
4871883aac7ad3a275a4a641c5e3e80d77436f7c
cab2c5e80e535c651653a34b3b10c5a0780e0a43
refs/heads/master
2021-03-03T03:50:28.323000
2020-03-10T10:04:56
2020-03-10T10:04:56
245,929,688
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.app24announce.dupat.id; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.app.DownloadManager; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.firebase.ui.database.FirebaseRecyclerAdapter; import com.firebase.ui.database.FirebaseRecyclerOptions; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import org.w3c.dom.Text; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; public class DetailTugasPage extends AppCompatActivity { String month[] = {"Januari","Februari","Maret","April","Mei","Juni","Juli","Agustus","September","Oktober","November","Desember"}; String hari[] = {"Minggu","Senin","Selasa","Rabu","Kamis","Jumat","Sabtu"}; GregorianCalendar gc = new GregorianCalendar(); String bln = month[gc.get(Calendar.MONTH)]; String hri = hari[(gc.get(Calendar.DAY_OF_WEEK))-1]; int tgl = gc.get(Calendar.DATE); int year = gc.get(Calendar.YEAR); int jam = gc.get(Calendar.HOUR); int mnt = gc.get(Calendar.MINUTE); int dt = gc.get(Calendar.SECOND); int pmam = gc.get(Calendar.AM_PM); String hariIni = hri+", "+tgl+" "+bln+" "+year; long Kb = 1 * 1024; long Mb = Kb * 1024; long Gb = Mb * 1024; long Tb = Gb * 1024; Toolbar toolbar; TextView mapelDetil,namaGuruTanggalTulis,kelasDetil,descDetil; RecyclerView rvLampiranDetail; String adalampiran,id,kelastujuan,keterangan,mapel,namaguru,tanggal,uid; DatabaseReference refTugas; FirebaseAuth myAuth; private ArrayList<SetGetDetailTugasPage> arrayList; private FirebaseRecyclerOptions<SetGetDetailTugasPage> options; private FirebaseRecyclerAdapter<SetGetDetailTugasPage, AdapterDetailTugasPage> adapter; @Override protected void onStart() { super.onStart(); adapter.startListening(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail_tugas_page); adalampiran = getIntent().getStringExtra("adalampiran"); id = getIntent().getStringExtra("id"); kelastujuan = getIntent().getStringExtra("kelastujuan"); keterangan = getIntent().getStringExtra("keterangan"); mapel = getIntent().getStringExtra("mapel"); namaguru = getIntent().getStringExtra("namaguru"); tanggal = getIntent().getStringExtra("tanggal"); uid = getIntent().getStringExtra("uid"); //Toast.makeText(this, id, Toast.LENGTH_SHORT).show(); myAuth = FirebaseAuth.getInstance(); refTugas = FirebaseDatabase.getInstance().getReference().child("tugas").child(id).child("lampiran"); refTugas.keepSynced(true); arrayList = new ArrayList<SetGetDetailTugasPage>(); options = new FirebaseRecyclerOptions.Builder<SetGetDetailTugasPage>().setQuery(refTugas,SetGetDetailTugasPage.class).build(); rvLampiranDetail = (RecyclerView) findViewById(R.id.rvLampiranDetail); //rvLampiranDetail.setHasFixedSize(true); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this); linearLayoutManager.setReverseLayout(true); linearLayoutManager.setStackFromEnd(true); rvLampiranDetail.setLayoutManager(linearLayoutManager); mapelDetil = (TextView) findViewById(R.id.mapelDetil); namaGuruTanggalTulis = (TextView) findViewById(R.id.namaGuruTanggalTulis); //kelasDetil = (TextView) findViewById(R.id.kelasDetil); descDetil = (TextView) findViewById(R.id.descDetil); toolbar = findViewById(R.id.tb); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); mapelDetil.setText(mapel); namaGuruTanggalTulis.setText("oleh "+namaguru+". "+tanggal); //kelasDetil.setText("untuk "+kelastujuan); descDetil.setText(keterangan); adapter = new FirebaseRecyclerAdapter<SetGetDetailTugasPage, AdapterDetailTugasPage>(options) { @Override protected void onBindViewHolder(@NonNull AdapterDetailTugasPage adapterDetailTugasPage, int i, @NonNull final SetGetDetailTugasPage setGetDetailTugasPage) { adapterDetailTugasPage.namaFile.setText(setGetDetailTugasPage.getNamafile()); String ukuranString= null; long uk = setGetDetailTugasPage.getUkuranfile(); if(uk < Kb) { ukuranString = String.valueOf(uk)+" bytes"; } else if(uk >= Kb && uk < Mb) { ukuranString = String.valueOf(uk/Kb)+" Kb"; } else if(uk >= Mb && uk < Gb) { ukuranString = String.valueOf(uk/Mb)+" Mb"; } else if(uk >= Gb && uk <Tb) { ukuranString = String.valueOf(uk/Gb)+" Gb"; } adapterDetailTugasPage.ukuranFile.setText(ukuranString); adapterDetailTugasPage.ivDownloadFile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String url = setGetDetailTugasPage.getUrl(); DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)); request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE); request.setTitle(setGetDetailTugasPage.getNamafile()); request.setDescription("Downloading "+setGetDetailTugasPage.getNamafile()); request.allowScanningByMediaScanner(); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,setGetDetailTugasPage.getNamafile()); DownloadManager manager = (DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE); manager.enqueue(request); } }); } @NonNull @Override public AdapterDetailTugasPage onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { return new AdapterDetailTugasPage(LayoutInflater.from(DetailTugasPage.this).inflate(R.layout.row_recyclerview_attachment_detail_tugas,parent,false)); } }; rvLampiranDetail.setAdapter(adapter); } }
UTF-8
Java
7,226
java
DetailTugasPage.java
Java
[]
null
[]
package com.app24announce.dupat.id; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.app.DownloadManager; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.firebase.ui.database.FirebaseRecyclerAdapter; import com.firebase.ui.database.FirebaseRecyclerOptions; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import org.w3c.dom.Text; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; public class DetailTugasPage extends AppCompatActivity { String month[] = {"Januari","Februari","Maret","April","Mei","Juni","Juli","Agustus","September","Oktober","November","Desember"}; String hari[] = {"Minggu","Senin","Selasa","Rabu","Kamis","Jumat","Sabtu"}; GregorianCalendar gc = new GregorianCalendar(); String bln = month[gc.get(Calendar.MONTH)]; String hri = hari[(gc.get(Calendar.DAY_OF_WEEK))-1]; int tgl = gc.get(Calendar.DATE); int year = gc.get(Calendar.YEAR); int jam = gc.get(Calendar.HOUR); int mnt = gc.get(Calendar.MINUTE); int dt = gc.get(Calendar.SECOND); int pmam = gc.get(Calendar.AM_PM); String hariIni = hri+", "+tgl+" "+bln+" "+year; long Kb = 1 * 1024; long Mb = Kb * 1024; long Gb = Mb * 1024; long Tb = Gb * 1024; Toolbar toolbar; TextView mapelDetil,namaGuruTanggalTulis,kelasDetil,descDetil; RecyclerView rvLampiranDetail; String adalampiran,id,kelastujuan,keterangan,mapel,namaguru,tanggal,uid; DatabaseReference refTugas; FirebaseAuth myAuth; private ArrayList<SetGetDetailTugasPage> arrayList; private FirebaseRecyclerOptions<SetGetDetailTugasPage> options; private FirebaseRecyclerAdapter<SetGetDetailTugasPage, AdapterDetailTugasPage> adapter; @Override protected void onStart() { super.onStart(); adapter.startListening(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail_tugas_page); adalampiran = getIntent().getStringExtra("adalampiran"); id = getIntent().getStringExtra("id"); kelastujuan = getIntent().getStringExtra("kelastujuan"); keterangan = getIntent().getStringExtra("keterangan"); mapel = getIntent().getStringExtra("mapel"); namaguru = getIntent().getStringExtra("namaguru"); tanggal = getIntent().getStringExtra("tanggal"); uid = getIntent().getStringExtra("uid"); //Toast.makeText(this, id, Toast.LENGTH_SHORT).show(); myAuth = FirebaseAuth.getInstance(); refTugas = FirebaseDatabase.getInstance().getReference().child("tugas").child(id).child("lampiran"); refTugas.keepSynced(true); arrayList = new ArrayList<SetGetDetailTugasPage>(); options = new FirebaseRecyclerOptions.Builder<SetGetDetailTugasPage>().setQuery(refTugas,SetGetDetailTugasPage.class).build(); rvLampiranDetail = (RecyclerView) findViewById(R.id.rvLampiranDetail); //rvLampiranDetail.setHasFixedSize(true); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this); linearLayoutManager.setReverseLayout(true); linearLayoutManager.setStackFromEnd(true); rvLampiranDetail.setLayoutManager(linearLayoutManager); mapelDetil = (TextView) findViewById(R.id.mapelDetil); namaGuruTanggalTulis = (TextView) findViewById(R.id.namaGuruTanggalTulis); //kelasDetil = (TextView) findViewById(R.id.kelasDetil); descDetil = (TextView) findViewById(R.id.descDetil); toolbar = findViewById(R.id.tb); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); mapelDetil.setText(mapel); namaGuruTanggalTulis.setText("oleh "+namaguru+". "+tanggal); //kelasDetil.setText("untuk "+kelastujuan); descDetil.setText(keterangan); adapter = new FirebaseRecyclerAdapter<SetGetDetailTugasPage, AdapterDetailTugasPage>(options) { @Override protected void onBindViewHolder(@NonNull AdapterDetailTugasPage adapterDetailTugasPage, int i, @NonNull final SetGetDetailTugasPage setGetDetailTugasPage) { adapterDetailTugasPage.namaFile.setText(setGetDetailTugasPage.getNamafile()); String ukuranString= null; long uk = setGetDetailTugasPage.getUkuranfile(); if(uk < Kb) { ukuranString = String.valueOf(uk)+" bytes"; } else if(uk >= Kb && uk < Mb) { ukuranString = String.valueOf(uk/Kb)+" Kb"; } else if(uk >= Mb && uk < Gb) { ukuranString = String.valueOf(uk/Mb)+" Mb"; } else if(uk >= Gb && uk <Tb) { ukuranString = String.valueOf(uk/Gb)+" Gb"; } adapterDetailTugasPage.ukuranFile.setText(ukuranString); adapterDetailTugasPage.ivDownloadFile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String url = setGetDetailTugasPage.getUrl(); DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)); request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE); request.setTitle(setGetDetailTugasPage.getNamafile()); request.setDescription("Downloading "+setGetDetailTugasPage.getNamafile()); request.allowScanningByMediaScanner(); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,setGetDetailTugasPage.getNamafile()); DownloadManager manager = (DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE); manager.enqueue(request); } }); } @NonNull @Override public AdapterDetailTugasPage onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { return new AdapterDetailTugasPage(LayoutInflater.from(DetailTugasPage.this).inflate(R.layout.row_recyclerview_attachment_detail_tugas,parent,false)); } }; rvLampiranDetail.setAdapter(adapter); } }
7,226
0.667589
0.664683
181
38.922653
34.661179
168
false
false
0
0
0
0
0
0
0.81768
false
false
12
9e2108b8b49f5e18f57504c93ecaa6dc89ccc75a
33,913,061,817,875
bb6e348668892727dda0bc4efb904f03733d0335
/app/src/main/java/pl/xsteam/santacruz/activities/IMainActivity.java
82df2d191655a73d16401aea33054c1073c4090b
[]
no_license
Santacruzzz/XSTtest1
https://github.com/Santacruzzz/XSTtest1
8952bad21484ef7b701891d26ff3d56e04ef78d3
1e114c7d232af4a1dbbccce6de8336723acd92bb
refs/heads/master
2021-05-08T17:04:29.891000
2019-03-20T21:41:01
2019-03-20T21:41:01
120,184,875
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pl.xsteam.santacruz.activities; import android.content.Intent; /** * Created by Tomek on 2017-10-19. */ public interface IMainActivity { void broadcastReceived(String intent); void nowa_wiadomosc(Intent i); void zalogowano(); void odswiezWiadomosci(); int getThemeColor(int[] arr); int getThemeRecourceId(int[] arr); void sendMessage(String wiadomosc); void polajkowanoWiadomosc(int msgid); void lajkujWiadomosc(int id, int position); Integer getKeyboardSize(); int getState(); }
UTF-8
Java
537
java
IMainActivity.java
Java
[ { "context": "\nimport android.content.Intent;\n\n/**\n * Created by Tomek on 2017-10-19.\n */\n\npublic interface IMainActivit", "end": 96, "score": 0.9955937266349792, "start": 91, "tag": "NAME", "value": "Tomek" } ]
null
[]
package pl.xsteam.santacruz.activities; import android.content.Intent; /** * Created by Tomek on 2017-10-19. */ public interface IMainActivity { void broadcastReceived(String intent); void nowa_wiadomosc(Intent i); void zalogowano(); void odswiezWiadomosci(); int getThemeColor(int[] arr); int getThemeRecourceId(int[] arr); void sendMessage(String wiadomosc); void polajkowanoWiadomosc(int msgid); void lajkujWiadomosc(int id, int position); Integer getKeyboardSize(); int getState(); }
537
0.713222
0.698324
21
24.571428
16.022518
47
false
false
0
0
0
0
0
0
0.666667
false
false
12
90138926f40fd8e1491fc519f49b549133c51fcd
37,099,927,526,886
b8b9e7308fda7248af0aeedcd7857dd91c5514dc
/src/main/java/coe/neu/edu/UploadController.java
169c8eb1d5e2e836fff09f87b53a736302f2adb0
[]
no_license
iamaayush/E-Commerce-beatport
https://github.com/iamaayush/E-Commerce-beatport
65d72c9550aaf371c3ab67dbe5a2e4e1e9286368
0ecb0a219436fb85c6deec2a1c17fae0cbcb458b
refs/heads/master
2021-01-14T07:55:43.584000
2017-02-14T02:24:25
2017-02-14T02:24:25
81,892,190
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package coe.neu.edu; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import coe.neu.edu.DAO.MusicDao; import coe.neu.edu.DAO.SupplierDao; //import coe.neu.edu.model.FileUpload; import coe.neu.edu.model.Genre; import coe.neu.edu.model.Music; import coe.neu.edu.model.UserAccount; @Controller public class UploadController{ // @Autowired // @Qualifier("musicValidator") // private Validator validator2; @Autowired private SupplierDao supplierDao; @Autowired private MusicDao musicDao; // @InitBinder // private void initBinder (WebDataBinder binder){ // binder.setValidator(validator2); // } //// // /*//// @RequestMapping(value="addMusicToCategory.do", method=RequestMethod.POST) //// protected ModelAndView doSubmitAction(Model model, Object command, HttpServletRequest request) throws Exception { //// Music music = (Music) command; //// ////// CommonsMultipartFile commonsFile = music.getImage(); ////// CommonsMultipartFile commonsFile2 = music.getSampleMusic(); //// ////// File destFileImage = new File("E:\\uploads\\images\\", commonsFile.getOriginalFilename()); ////// File destFileSampleMusic = new File("E:\\uploads\\sample\\", commonsFile2.getOriginalFilename()); //// ////// music.getImage().transferTo(destFileImage); ////// music.getSampleMusic().transferTo(destFileSampleMusic); //// ////// String imagePath = "E:\\uploads\\images\\"+commonsFile.getOriginalFilename(); ////// String samplePath = "E:\\uploads\\sample\\"+commonsFile2.getOriginalFilename(); //// ////// music.setImagePath(imagePath); ////// music.setSamplePath(samplePath); //// //// //hibernateSession.save(user); //// String selectedGenre = request.getParameter("selectedGenre"); //// //// model.addAttribute("music", music); //// //// supplierDao.addMusicToDb(music, selectedGenre); //// //// return new ModelAndView(getSuccessView(), "music", music); // return "musicAdded"; } // //Use onSubmit instead of doSubmitAction // //when you need access to the Request, Response, or BindException objects // /* // * @Override protected ModelAndView onSubmit( HttpServletRequest request, // * HttpServletResponse response, Object command, BindException errors) // * throws Exception { ModelAndView mv = new ModelAndView(getSuccessView()); // * //Do something... return mv; } // */ // // // // @RequestMapping(value="addMusicToCategory.do", method=RequestMethod.POST) protected String doSubmitAction(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception { UserAccount user = (UserAccount)session.getAttribute("user"); if(user==null){ return "403"; } if(!user.getRole().equals("supplier")){ return "403"; } //hibernateSession.save(user); Music music = new Music(); String selectedGenre = request.getParameter("selectedGenre"); music.setDescription(request.getParameter("description")); music.setName(request.getParameter("name")); music.setSupplierName(request.getParameter("supplierName")); music.setPrice(Float.parseFloat(request.getParameter("price"))); music.setQuantity(Integer.parseInt(request.getParameter("quantity"))); music.setImagePath(request.getParameter("putImage")); music.setSamplePath(request.getParameter("putSample")); // music.setSupplierName(request.getParameter("supplierName")); Genre genre = musicDao.getGenreObj(selectedGenre); music.setGenre(genre); supplierDao.addMusicToDb(music); return "musicAdded"; } // @RequestMapping(value="addMusicToCategory.do", method = RequestMethod.POST) //// public @ResponseBody // public String uploadMultipleFileHandler(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception { // //// if (files.length != names.length) //// return "Mandatory information missing"; // //// String message = ""; // // // Music music = new Music(); // // String selectedGenre = request.getParameter("selectedGenre"); // music.setDescription(request.getParameter("description")); // music.setName(request.getParameter("name")); // music.setPrice(Float.parseFloat(request.getParameter("price"))); // music.setQuantity(Integer.parseInt(request.getParameter("quantity"))); // // music.setImagePath("imagePath"); //// music.setImagePath(request.getParameter("image")); //// music.setSamplePath(request.getParameter("sample")); // // Genre genre = musicDao.getGenreObj(selectedGenre); // music.setGenre(genre); // // // //// for (int i = 0; i < files.length; i++) { //// MultipartFile file = files[i]; //// String name = names[i]; // try { // byte[] bytes = file.getBytes(); // // // Creating the directory to store file // String rootPath = System.getProperty("catalina.home"); // File dir = new File(rootPath + File.separator + "tmpFiles"); // if (!dir.exists()) // { // dir.mkdirs(); // } // // // Create the file on server // File serverFile = new File(dir.getAbsolutePath()); // BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile)); // stream.write(bytes); // stream.close(); // // // // // // String fileLocation = serverFile.getAbsolutePath(); // //// if(file.getName().equals("*.img")) // music.setImagePath(fileLocation); //// music.setSamplePath(request.getParameter("sample")); // // // logger.info("Server File Location=" // + serverFile.getAbsolutePath()); // // // //// message = message + "You successfully uploaded file=" + name //// + "<br />"; // } catch (Exception e) { // return "You failed to upload "+ e.getMessage(); // } // // // // // // supplierDao.addMusicToDb(music); // //// return new ModelAndView(getSuccessView(), "music", music); // //// return "musicAdded"; // // // // return "musicAdded"; // } // @RequestMapping(value="aMTC.do", method=RequestMethod.POST) // protected ModelAndView onSubmit(HttpServletRequest request, // HttpServletResponse response, @Validated FileUpload fileUpload,BindingResult result, BindException errors, Object command) // throws Exception { // // // // // MultipartFile multipartFile = fileUpload.getImage(); // // String fileName=""; // // if(multipartFile!=null){ // fileName = multipartFile.getOriginalFilename(); // //// BufferedImage src = ImageIO.read(new ByteArrayInputStream(file.getBytes())); //// File destination = new File("File directory with file name") // something like C:/Users/tom/Documents/nameBasedOnSomeId.png //// ImageIO.write(src, "png", destination); // // // byte[] bytes = multipartFile.getBytes(); // // String rootPath = System.getProperty("catalina.home"); // File dir = new File(rootPath + File.separator + "tmpFiles"); // if (!dir.exists()) // dir.mkdirs(); // // // Create the file on server // File serverFile = new File(dir.getAbsolutePath() // + File.separator + fileName); // BufferedOutputStream stream = new BufferedOutputStream( // new FileOutputStream(serverFile)); // stream.write(bytes); // stream.close(); // //// logger.info("Server File Location=" //// + serverFile.getAbsolutePath()); // // // //do whatever you want // } // // ModelAndView mv = new ModelAndView(); //// mv.addObject("music", music); // mv.addObject("fileName", fileName); // // mv.setViewName("musicAdded"); // return mv; //// return new ModelAndView("musicAdded","fileName",fileName); // } }
UTF-8
Java
8,868
java
UploadController.java
Java
[]
null
[]
package coe.neu.edu; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import coe.neu.edu.DAO.MusicDao; import coe.neu.edu.DAO.SupplierDao; //import coe.neu.edu.model.FileUpload; import coe.neu.edu.model.Genre; import coe.neu.edu.model.Music; import coe.neu.edu.model.UserAccount; @Controller public class UploadController{ // @Autowired // @Qualifier("musicValidator") // private Validator validator2; @Autowired private SupplierDao supplierDao; @Autowired private MusicDao musicDao; // @InitBinder // private void initBinder (WebDataBinder binder){ // binder.setValidator(validator2); // } //// // /*//// @RequestMapping(value="addMusicToCategory.do", method=RequestMethod.POST) //// protected ModelAndView doSubmitAction(Model model, Object command, HttpServletRequest request) throws Exception { //// Music music = (Music) command; //// ////// CommonsMultipartFile commonsFile = music.getImage(); ////// CommonsMultipartFile commonsFile2 = music.getSampleMusic(); //// ////// File destFileImage = new File("E:\\uploads\\images\\", commonsFile.getOriginalFilename()); ////// File destFileSampleMusic = new File("E:\\uploads\\sample\\", commonsFile2.getOriginalFilename()); //// ////// music.getImage().transferTo(destFileImage); ////// music.getSampleMusic().transferTo(destFileSampleMusic); //// ////// String imagePath = "E:\\uploads\\images\\"+commonsFile.getOriginalFilename(); ////// String samplePath = "E:\\uploads\\sample\\"+commonsFile2.getOriginalFilename(); //// ////// music.setImagePath(imagePath); ////// music.setSamplePath(samplePath); //// //// //hibernateSession.save(user); //// String selectedGenre = request.getParameter("selectedGenre"); //// //// model.addAttribute("music", music); //// //// supplierDao.addMusicToDb(music, selectedGenre); //// //// return new ModelAndView(getSuccessView(), "music", music); // return "musicAdded"; } // //Use onSubmit instead of doSubmitAction // //when you need access to the Request, Response, or BindException objects // /* // * @Override protected ModelAndView onSubmit( HttpServletRequest request, // * HttpServletResponse response, Object command, BindException errors) // * throws Exception { ModelAndView mv = new ModelAndView(getSuccessView()); // * //Do something... return mv; } // */ // // // // @RequestMapping(value="addMusicToCategory.do", method=RequestMethod.POST) protected String doSubmitAction(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception { UserAccount user = (UserAccount)session.getAttribute("user"); if(user==null){ return "403"; } if(!user.getRole().equals("supplier")){ return "403"; } //hibernateSession.save(user); Music music = new Music(); String selectedGenre = request.getParameter("selectedGenre"); music.setDescription(request.getParameter("description")); music.setName(request.getParameter("name")); music.setSupplierName(request.getParameter("supplierName")); music.setPrice(Float.parseFloat(request.getParameter("price"))); music.setQuantity(Integer.parseInt(request.getParameter("quantity"))); music.setImagePath(request.getParameter("putImage")); music.setSamplePath(request.getParameter("putSample")); // music.setSupplierName(request.getParameter("supplierName")); Genre genre = musicDao.getGenreObj(selectedGenre); music.setGenre(genre); supplierDao.addMusicToDb(music); return "musicAdded"; } // @RequestMapping(value="addMusicToCategory.do", method = RequestMethod.POST) //// public @ResponseBody // public String uploadMultipleFileHandler(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception { // //// if (files.length != names.length) //// return "Mandatory information missing"; // //// String message = ""; // // // Music music = new Music(); // // String selectedGenre = request.getParameter("selectedGenre"); // music.setDescription(request.getParameter("description")); // music.setName(request.getParameter("name")); // music.setPrice(Float.parseFloat(request.getParameter("price"))); // music.setQuantity(Integer.parseInt(request.getParameter("quantity"))); // // music.setImagePath("imagePath"); //// music.setImagePath(request.getParameter("image")); //// music.setSamplePath(request.getParameter("sample")); // // Genre genre = musicDao.getGenreObj(selectedGenre); // music.setGenre(genre); // // // //// for (int i = 0; i < files.length; i++) { //// MultipartFile file = files[i]; //// String name = names[i]; // try { // byte[] bytes = file.getBytes(); // // // Creating the directory to store file // String rootPath = System.getProperty("catalina.home"); // File dir = new File(rootPath + File.separator + "tmpFiles"); // if (!dir.exists()) // { // dir.mkdirs(); // } // // // Create the file on server // File serverFile = new File(dir.getAbsolutePath()); // BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile)); // stream.write(bytes); // stream.close(); // // // // // // String fileLocation = serverFile.getAbsolutePath(); // //// if(file.getName().equals("*.img")) // music.setImagePath(fileLocation); //// music.setSamplePath(request.getParameter("sample")); // // // logger.info("Server File Location=" // + serverFile.getAbsolutePath()); // // // //// message = message + "You successfully uploaded file=" + name //// + "<br />"; // } catch (Exception e) { // return "You failed to upload "+ e.getMessage(); // } // // // // // // supplierDao.addMusicToDb(music); // //// return new ModelAndView(getSuccessView(), "music", music); // //// return "musicAdded"; // // // // return "musicAdded"; // } // @RequestMapping(value="aMTC.do", method=RequestMethod.POST) // protected ModelAndView onSubmit(HttpServletRequest request, // HttpServletResponse response, @Validated FileUpload fileUpload,BindingResult result, BindException errors, Object command) // throws Exception { // // // // // MultipartFile multipartFile = fileUpload.getImage(); // // String fileName=""; // // if(multipartFile!=null){ // fileName = multipartFile.getOriginalFilename(); // //// BufferedImage src = ImageIO.read(new ByteArrayInputStream(file.getBytes())); //// File destination = new File("File directory with file name") // something like C:/Users/tom/Documents/nameBasedOnSomeId.png //// ImageIO.write(src, "png", destination); // // // byte[] bytes = multipartFile.getBytes(); // // String rootPath = System.getProperty("catalina.home"); // File dir = new File(rootPath + File.separator + "tmpFiles"); // if (!dir.exists()) // dir.mkdirs(); // // // Create the file on server // File serverFile = new File(dir.getAbsolutePath() // + File.separator + fileName); // BufferedOutputStream stream = new BufferedOutputStream( // new FileOutputStream(serverFile)); // stream.write(bytes); // stream.close(); // //// logger.info("Server File Location=" //// + serverFile.getAbsolutePath()); // // // //do whatever you want // } // // ModelAndView mv = new ModelAndView(); //// mv.addObject("music", music); // mv.addObject("fileName", fileName); // // mv.setViewName("musicAdded"); // return mv; //// return new ModelAndView("musicAdded","fileName",fileName); // } }
8,868
0.601037
0.599684
257
33.501945
29.874201
134
false
false
0
0
0
0
0
0
1.136187
false
false
12
7fd4903d8996e0d08aa3e402439cda4ad1ea8ab6
35,854,387,012,925
c2105820952fd8730b01bdcd4596b8b2d803b6cf
/test.shaadi.com/src/main/java/stepDefinitions/SignupStepDefinition.java
dd91639e4f343bd6d2af1e090cb3e63913dbc9fb
[]
no_license
mksingh8/cucumberSelenium.BDDFrameWork
https://github.com/mksingh8/cucumberSelenium.BDDFrameWork
0f6ed86a5624a60d64c21604ca8b926c9287ab08
a0b5408bcede4e01733e8017e5119c94be73b4ed
refs/heads/master
2021-07-01T00:27:29.325000
2019-06-18T03:32:00
2019-06-18T03:32:00
169,948,266
0
0
null
false
2020-10-13T11:56:39
2019-02-10T06:02:40
2019-06-18T03:32:31
2020-10-13T11:56:38
57
0
0
1
Java
false
false
package stepDefinitions; import java.util.concurrent.TimeUnit; import org.junit.Assert; import org.openqa.selenium.By; import org.openqa.selenium.ElementNotInteractableException; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.Keys; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; public class SignupStepDefinition { WebDriver driver; @Given("user is already on shaadiDotcom website") public void user_is_already_on_shaadiDotcom_website() { System.setProperty("webdriver.gecko.driver", "/home/manish/Downloads/Selenium/Lib/Browser/geckodriver-v0.23.0-linux64/geckodriver"); driver = new FirefoxDriver(); driver.manage().deleteAllCookies(); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); driver.get("https://www.shaadi.com/"); } @When("user clicks on the SignUp button") public void user_clicks_on_the_SignUp_button() { driver.findElement(By.xpath("//a[text()='Sign up']")).click(); } @Then("user provides \"(.*)\" and \"(.*)\" and OnBehalf details as \"(.*)\"") public void user_provides_email_address_andpassword_and_OnBehalf_details_as_daughter(String emailAdd, String password, String profilfor) { WebElement email = driver.findElement(By.xpath("//input[@name='email']")); new WebDriverWait(driver, 20).ignoring(ElementNotInteractableException.class) .until(ExpectedConditions.elementToBeClickable(email)); email.sendKeys(emailAdd); driver.findElement(By.xpath("//input[@name='password1']")).sendKeys(password); driver.findElement(By.xpath("//*[@id='s2id_layer_postedby']/a/span[1]")).click(); String befoe_Xpath = "//*[@id='select2-drop']/ul/li["; for (int i = 2; i <= 6; i++) { WebElement ele = driver.findElement(By.xpath(befoe_Xpath + i + "]")); String dropDown = ele.getText(); System.out.println(dropDown); if (profilfor.equalsIgnoreCase(dropDown)) { ele.click(); break; } } } @Then("user clicks on the Next button") public void user_clicks_on_the_Next_button() { driver.findElement(By.xpath("//a[text()='Next']")).click(); } @Then("Great! Now some basic details are displayed") public void great_Now_some_basic_details_are_displayed() { WebElement basicDetailsScreen = driver.findElement(By.xpath("//*[text()='Great! Now some basic details']")); new WebDriverWait(driver, 20).ignoring(NoSuchElementException.class). until(ExpectedConditions.elementToBeClickable(basicDetailsScreen)); //until(ExpectedConditions.elementSelectionStateToBe(basicDetailsScreen, true)); //until(ExpectedConditions.invisibilityOf(basicDetailsScreen)); //Assert.assertEquals("Great! Now some basic details", basicDetailsScreen); } @Then("user provides daughters \"(.*)\" and \"(.*)\" and other details") public void user_provides_daughter_details(String firstname, String lastname) throws InterruptedException { Thread.sleep(500); driver.findElement(By.xpath("//input[@name='first_name']")).sendKeys(firstname); driver.findElement(By.xpath("//input[@name='last_name']")).sendKeys(lastname); driver.findElement(By.xpath("//*[@id='s2id_layer_day']")).click(); driver.findElement(By.xpath("//*[@id='select2-drop']/ul/li[2]")).click(); /* WebElement monthSelection = driver.findElement(By.xpath("//*[@id='select2-drop']/ul/li[2]")); JavascriptExecutor js = ((JavascriptExecutor)driver); js.executeScript("arguments[0].click", monthSelection); */ driver.findElement(By.xpath("//*[@id='select2-drop']/ul/li[2]")).click(); driver.findElement(By.xpath("//*[@id='select2-drop']/ul/li[7]")).click(); driver.findElement(By.xpath("//*[@id='s2id_layer_community']/a/span[1]")).click(); driver.findElement(By.xpath("//*[@id='select2-drop']/ul/li[2]")).click(); driver.findElement(By.xpath("//*[@id='s2id_layer_mother_tongue']/a/span[1]")).click(); driver.findElement(By.xpath("//*[@id='select2-drop']/ul/li[2]/ul/li[5]")).click(); } @Then("clciks on the SignUp button") public void clciks_on_the_SignUp_button() { driver.findElement(By.xpath("//a[text()='Sign Up' and @id='btnSubmit']")).click(); } @Then("user close the browser") public void user_close_the_browser() { driver.quit(); } /* @Then("Welcome to Shaadi.com displayed") public void welcome_to_Shaadi_com_displayed() throws InterruptedException { Thread.sleep(5000); WebElement newWindow = driver.findElement(By.xpath("//div[@class='sc-bsbRJL fxQkgV']")); //WebElement welcomeMessage = driver.findElement(By.xpath("//h1[text()='Welcome to Shaadi.com!']")); JavascriptExecutor js = (JavascriptExecutor)driver; js.executeScript("arguments[0].scrollIntoView()", newWindow); //new WebDriverWait(driver, 10).ignoring(ElementNotInteractableException.class). // until(ExpectedConditions.visibilityOf(welcomeMessage)); //Assert.assertTrue(welcomeMessage.isDisplayed()); } @Then("user provide information some demographic and marital status of daughter") public void user_provide_information_some_demographic_and_marital_status_of_daughter() { WebElement state = driver.findElement(By.xpath("//input[@name='state']")); state.click(); state.sendKeys("andhra"); state.sendKeys(Keys.RETURN); WebElement city = driver.findElement(By.xpath("//input[@name='city']")); new WebDriverWait(driver, 5).until(ExpectedConditions.elementToBeClickable(city)); city.click(); city.sendKeys("Eluru"); //WebElement maritalStatus = driver.findElement(By.xpath("//input[@name='maritalStatus']")); JavascriptExecutor js = ((JavascriptExecutor)driver); js.executeScript("document.getElemenetByname('maritalStatus').value='Never Married'"); } @Then("user clicks on the Continue button") public void user_clicks_on_the_Continue_button() { // Write code here that turns the phrase above into concrete actions throw new cucumber.api.PendingException(); } */ }
UTF-8
Java
6,226
java
SignupStepDefinition.java
Java
[ { "context": "d);\n\t\tdriver.findElement(By.xpath(\"//input[@name='password1']\")).sendKeys(password);\n\n\t\tdriver.findElement(By", "end": 1864, "score": 0.9978154897689819, "start": 1855, "tag": "PASSWORD", "value": "password1" }, { "context": "eep(500);\n\t\tdriver.findElement(By.xpath(\"//input[@name='first_name']\")).sendKeys(firstname);\n\t\tdriver.fi", "end": 3298, "score": 0.5582962036132812, "start": 3294, "tag": "EMAIL", "value": "name" }, { "context": "driver.findElement(By.xpath(\"//input[@name='first_name']\")).sendKeys(firstname);\n\t\tdriver.findElement(By", "end": 3310, "score": 0.6208056211471558, "start": 3306, "tag": "EMAIL", "value": "name" }, { "context": "state']\"));\n\t\tstate.click();\n\t\tstate.sendKeys(\"andhra\");\n\t\tstate.sendKeys(Keys.RETURN);\n\t\t\n\t\tWebElement", "end": 5507, "score": 0.6726201772689819, "start": 5504, "tag": "NAME", "value": "hra" }, { "context": "ckable(city));\n\t\tcity.click();\n\t\tcity.sendKeys(\"Eluru\");\n\t\t\n\t\t//WebElement maritalStatus = driver.findE", "end": 5743, "score": 0.7638372778892517, "start": 5740, "tag": "NAME", "value": "uru" } ]
null
[]
package stepDefinitions; import java.util.concurrent.TimeUnit; import org.junit.Assert; import org.openqa.selenium.By; import org.openqa.selenium.ElementNotInteractableException; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.Keys; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; public class SignupStepDefinition { WebDriver driver; @Given("user is already on shaadiDotcom website") public void user_is_already_on_shaadiDotcom_website() { System.setProperty("webdriver.gecko.driver", "/home/manish/Downloads/Selenium/Lib/Browser/geckodriver-v0.23.0-linux64/geckodriver"); driver = new FirefoxDriver(); driver.manage().deleteAllCookies(); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); driver.get("https://www.shaadi.com/"); } @When("user clicks on the SignUp button") public void user_clicks_on_the_SignUp_button() { driver.findElement(By.xpath("//a[text()='Sign up']")).click(); } @Then("user provides \"(.*)\" and \"(.*)\" and OnBehalf details as \"(.*)\"") public void user_provides_email_address_andpassword_and_OnBehalf_details_as_daughter(String emailAdd, String password, String profilfor) { WebElement email = driver.findElement(By.xpath("//input[@name='email']")); new WebDriverWait(driver, 20).ignoring(ElementNotInteractableException.class) .until(ExpectedConditions.elementToBeClickable(email)); email.sendKeys(emailAdd); driver.findElement(By.xpath("//input[@name='<PASSWORD>']")).sendKeys(password); driver.findElement(By.xpath("//*[@id='s2id_layer_postedby']/a/span[1]")).click(); String befoe_Xpath = "//*[@id='select2-drop']/ul/li["; for (int i = 2; i <= 6; i++) { WebElement ele = driver.findElement(By.xpath(befoe_Xpath + i + "]")); String dropDown = ele.getText(); System.out.println(dropDown); if (profilfor.equalsIgnoreCase(dropDown)) { ele.click(); break; } } } @Then("user clicks on the Next button") public void user_clicks_on_the_Next_button() { driver.findElement(By.xpath("//a[text()='Next']")).click(); } @Then("Great! Now some basic details are displayed") public void great_Now_some_basic_details_are_displayed() { WebElement basicDetailsScreen = driver.findElement(By.xpath("//*[text()='Great! Now some basic details']")); new WebDriverWait(driver, 20).ignoring(NoSuchElementException.class). until(ExpectedConditions.elementToBeClickable(basicDetailsScreen)); //until(ExpectedConditions.elementSelectionStateToBe(basicDetailsScreen, true)); //until(ExpectedConditions.invisibilityOf(basicDetailsScreen)); //Assert.assertEquals("Great! Now some basic details", basicDetailsScreen); } @Then("user provides daughters \"(.*)\" and \"(.*)\" and other details") public void user_provides_daughter_details(String firstname, String lastname) throws InterruptedException { Thread.sleep(500); driver.findElement(By.xpath("//input[@<EMAIL>='first_<EMAIL>']")).sendKeys(firstname); driver.findElement(By.xpath("//input[@name='last_name']")).sendKeys(lastname); driver.findElement(By.xpath("//*[@id='s2id_layer_day']")).click(); driver.findElement(By.xpath("//*[@id='select2-drop']/ul/li[2]")).click(); /* WebElement monthSelection = driver.findElement(By.xpath("//*[@id='select2-drop']/ul/li[2]")); JavascriptExecutor js = ((JavascriptExecutor)driver); js.executeScript("arguments[0].click", monthSelection); */ driver.findElement(By.xpath("//*[@id='select2-drop']/ul/li[2]")).click(); driver.findElement(By.xpath("//*[@id='select2-drop']/ul/li[7]")).click(); driver.findElement(By.xpath("//*[@id='s2id_layer_community']/a/span[1]")).click(); driver.findElement(By.xpath("//*[@id='select2-drop']/ul/li[2]")).click(); driver.findElement(By.xpath("//*[@id='s2id_layer_mother_tongue']/a/span[1]")).click(); driver.findElement(By.xpath("//*[@id='select2-drop']/ul/li[2]/ul/li[5]")).click(); } @Then("clciks on the SignUp button") public void clciks_on_the_SignUp_button() { driver.findElement(By.xpath("//a[text()='Sign Up' and @id='btnSubmit']")).click(); } @Then("user close the browser") public void user_close_the_browser() { driver.quit(); } /* @Then("Welcome to Shaadi.com displayed") public void welcome_to_Shaadi_com_displayed() throws InterruptedException { Thread.sleep(5000); WebElement newWindow = driver.findElement(By.xpath("//div[@class='sc-bsbRJL fxQkgV']")); //WebElement welcomeMessage = driver.findElement(By.xpath("//h1[text()='Welcome to Shaadi.com!']")); JavascriptExecutor js = (JavascriptExecutor)driver; js.executeScript("arguments[0].scrollIntoView()", newWindow); //new WebDriverWait(driver, 10).ignoring(ElementNotInteractableException.class). // until(ExpectedConditions.visibilityOf(welcomeMessage)); //Assert.assertTrue(welcomeMessage.isDisplayed()); } @Then("user provide information some demographic and marital status of daughter") public void user_provide_information_some_demographic_and_marital_status_of_daughter() { WebElement state = driver.findElement(By.xpath("//input[@name='state']")); state.click(); state.sendKeys("andhra"); state.sendKeys(Keys.RETURN); WebElement city = driver.findElement(By.xpath("//input[@name='city']")); new WebDriverWait(driver, 5).until(ExpectedConditions.elementToBeClickable(city)); city.click(); city.sendKeys("Eluru"); //WebElement maritalStatus = driver.findElement(By.xpath("//input[@name='maritalStatus']")); JavascriptExecutor js = ((JavascriptExecutor)driver); js.executeScript("document.getElemenetByname('maritalStatus').value='Never Married'"); } @Then("user clicks on the Continue button") public void user_clicks_on_the_Continue_button() { // Write code here that turns the phrase above into concrete actions throw new cucumber.api.PendingException(); } */ }
6,233
0.72133
0.71346
157
38.656052
32.952911
139
false
false
0
0
0
0
0
0
1.936306
false
false
12
ac03db64c05e6618f5ca2159faa7ad41391ce67f
38,568,806,337,750
24ad2dc00687f44623256cc1b270101866143e43
/Algo/src/순열조합/Maaaaaaaaze.java
0a67d5d9b871e27a405ecd5d135394ae4b68390d
[]
no_license
Jangsukwoo/Algorithm
https://github.com/Jangsukwoo/Algorithm
9a1e7234749768bdf05550f38c63b8d809ef065f
570fefe5b7f42b729e6701664094c2e95340e63e
refs/heads/master
2022-12-10T23:49:26.114000
2022-12-09T02:37:41
2022-12-09T02:37:41
206,563,752
5
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package 순열조합; import java.util.Arrays; import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; /* * 3:44~ * 25X25 정육면체 * 각 판을 쌓는 순서는 임의로 정할 수 있고 * 각 판은 시계방향으로 회전할 수 있다. * 판을 쌓는 경우의수 5! = 120 * 각 판 시계방향에 대해 4개씩의 경우의수가 존재하고 * 각 층별로 가능한 경우의 수는 4^5 * 120 x 4^2 = 122280 * 최단경로를 구하는것이므로 각 판에 대해서 bfs 수행 * 적절한 미로 정육면체를 먼저 만드는게 우선 * boolean 4차원 맵을 생각했다. * 첫번째 인덱스는 층 * 두번째 인덱스는 각 회전 경우의 수 * 세번재,네번째 인덱스는 row,col * * 코드는 2시간정도만에 나왔으나 * 답이 이상하게 나와서 계속 디버깅하다가 * 결국 찾은 문제점이 q.clear()를 안해준것이였다.. * 맞왜틀만 계속하다가 큐를 초기화하지 않은 문제점 찾고 너무 속상했다 ㅠ 하아 */ public class Maaaaaaaaze { static int[][][][] mazeCase = new int[5][4][5][5];//모든 가능한 판의 집합 static int[][][] maze = new int[5][5][5]; static boolean[][][] mazeVisit = new boolean[5][5][5]; static int[] floor = new int[5]; static int[] spin = new int[5]; static boolean[] visit = new boolean[5]; static int[] dr = {-1,0,1,0}; static int[] dc = {0,1,0,-1};//상우하좌 static int[] dz = {-1,1}; static int distance = Integer.MAX_VALUE; static Queue<int[]> q = new LinkedList<int[]>(); public static void main(String[] args) { Scanner sc = new Scanner(System.in); for(int board =0;board<5;board++) { for(int row=0;row<5;row++) for(int col=0;col<5;col++) mazeCase[board][0][row][col] = sc.nextInt(); } setRotationBoard();//모든 가능한 정육면체 세팅 entireFloorDFS(0);//5! if(distance==Integer.MAX_VALUE) System.out.println("-1"); else System.out.println(distance); } private static void entireFloorDFS(int cnt) {//5! if(cnt==5){ //판을 쌓는 한 경우의 수. 5!중에 한 경우 entireRotateDFS(0); return; } for(int i=0;i<5;i++){ if(visit[i]==false) { visit[i] = true; floor[cnt] = i; entireFloorDFS(cnt+1); visit[i] = false; } } } private static void entireRotateDFS(int cnt) {//4^2 = 1024 if(cnt==5){ //각 판 층에 대해 회전에 대한 경우의수 1024개 중에 한 경우 setMaze(); escapeBFS(); return ; } for(int i=0;i<4;i++){ spin[cnt] = i; entireRotateDFS(cnt+1); } } private static void escapeBFS() { if(maze[0][0][0]!=1) return; mazeVisit = new boolean[5][5][5]; int cnt=0; q.clear(); q.add(new int[]{0,0,0});//z,row,col mazeVisit[0][0][0] = true; while(!q.isEmpty()){ int size = q.size(); for(int i=0;i<size;i++){ int[] curZRC = q.poll(); if((curZRC[0]==4&&curZRC[1]==4&&curZRC[2]==4)){//도착했으면 distance = Math.min(cnt,distance); return ; } for(int dir=0;dir<4;dir++){//현재 판에서 상우하좌 int nr = curZRC[1]+dr[dir]; int nc = curZRC[2]+dc[dir]; if(rangeCheck(nr,nc)){ if(mazeVisit[curZRC[0]][nr][nc]==false && maze[curZRC[0]][nr][nc]==1){//안가봤고 갈 수 있으면 mazeVisit[curZRC[0]][nr][nc] = true; q.add(new int[] {curZRC[0],nr,nc}); } } } for(int dir=0;dir<2;dir++){//Z축 2방향 int nz = curZRC[0]+dz[dir]; if(nz>=0 && nz<5){//영역 만족 if(mazeVisit[nz][curZRC[1]][curZRC[2]]==false && maze[nz][curZRC[1]][curZRC[2]]==1){//안가봤고 갈 수 있으면 mazeVisit[nz][curZRC[1]][curZRC[2]]=true; q.add(new int[] {nz,curZRC[1],curZRC[2]}); } } } } cnt++; } } private static boolean rangeCheck(int nr, int nc) { if(nr>=0 && nr<5 && nc>=0 && nc<5) return true; return false; } private static void setMaze() { for(int i=0;i<5;i++){ for(int row=0;row<5;row++) { for(int col=0;col<5;col++){ maze[i][row][col] = mazeCase[floor[i]][spin[i]][row][col]; } } } } private static void setRotationBoard() { for(int board=0;board<5;board++){//각 판에대해서 for(int spin=1;spin<4;spin++){//시계방향 회전을 한다. rotate(board,spin); } } } private static void rotate(int board,int spin) { for(int idx=0;idx<2;idx++){ for(int col=idx;col<(5-idx);col++){ mazeCase[board][spin][col][4-idx] = mazeCase[board][spin-1][idx][col];//상변이 우변으로 mazeCase[board][spin][col][idx] = mazeCase[board][spin-1][4-idx][col];//하변이 좌변으로 } for(int row=idx;row<(5-idx);row++){ mazeCase[board][spin][4-idx][4-row] = mazeCase[board][spin-1][row][4-idx];//우변이 하변으로 mazeCase[board][spin][idx][4-row] = mazeCase[board][spin-1][row][idx];//좌변이 상변으로 } } mazeCase[board][spin][2][2] = mazeCase[board][spin-1][2][2]; } private static void view() { for(int spin=0;spin<4;spin++) { for(int row=0;row<5;row++) { for(int col=0;col<5;col++) { System.out.print(mazeCase[0][spin][row][col]); } System.out.println(); } System.out.println(); } } }
UTF-8
Java
5,169
java
Maaaaaaaaze.java
Java
[]
null
[]
package 순열조합; import java.util.Arrays; import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; /* * 3:44~ * 25X25 정육면체 * 각 판을 쌓는 순서는 임의로 정할 수 있고 * 각 판은 시계방향으로 회전할 수 있다. * 판을 쌓는 경우의수 5! = 120 * 각 판 시계방향에 대해 4개씩의 경우의수가 존재하고 * 각 층별로 가능한 경우의 수는 4^5 * 120 x 4^2 = 122280 * 최단경로를 구하는것이므로 각 판에 대해서 bfs 수행 * 적절한 미로 정육면체를 먼저 만드는게 우선 * boolean 4차원 맵을 생각했다. * 첫번째 인덱스는 층 * 두번째 인덱스는 각 회전 경우의 수 * 세번재,네번째 인덱스는 row,col * * 코드는 2시간정도만에 나왔으나 * 답이 이상하게 나와서 계속 디버깅하다가 * 결국 찾은 문제점이 q.clear()를 안해준것이였다.. * 맞왜틀만 계속하다가 큐를 초기화하지 않은 문제점 찾고 너무 속상했다 ㅠ 하아 */ public class Maaaaaaaaze { static int[][][][] mazeCase = new int[5][4][5][5];//모든 가능한 판의 집합 static int[][][] maze = new int[5][5][5]; static boolean[][][] mazeVisit = new boolean[5][5][5]; static int[] floor = new int[5]; static int[] spin = new int[5]; static boolean[] visit = new boolean[5]; static int[] dr = {-1,0,1,0}; static int[] dc = {0,1,0,-1};//상우하좌 static int[] dz = {-1,1}; static int distance = Integer.MAX_VALUE; static Queue<int[]> q = new LinkedList<int[]>(); public static void main(String[] args) { Scanner sc = new Scanner(System.in); for(int board =0;board<5;board++) { for(int row=0;row<5;row++) for(int col=0;col<5;col++) mazeCase[board][0][row][col] = sc.nextInt(); } setRotationBoard();//모든 가능한 정육면체 세팅 entireFloorDFS(0);//5! if(distance==Integer.MAX_VALUE) System.out.println("-1"); else System.out.println(distance); } private static void entireFloorDFS(int cnt) {//5! if(cnt==5){ //판을 쌓는 한 경우의 수. 5!중에 한 경우 entireRotateDFS(0); return; } for(int i=0;i<5;i++){ if(visit[i]==false) { visit[i] = true; floor[cnt] = i; entireFloorDFS(cnt+1); visit[i] = false; } } } private static void entireRotateDFS(int cnt) {//4^2 = 1024 if(cnt==5){ //각 판 층에 대해 회전에 대한 경우의수 1024개 중에 한 경우 setMaze(); escapeBFS(); return ; } for(int i=0;i<4;i++){ spin[cnt] = i; entireRotateDFS(cnt+1); } } private static void escapeBFS() { if(maze[0][0][0]!=1) return; mazeVisit = new boolean[5][5][5]; int cnt=0; q.clear(); q.add(new int[]{0,0,0});//z,row,col mazeVisit[0][0][0] = true; while(!q.isEmpty()){ int size = q.size(); for(int i=0;i<size;i++){ int[] curZRC = q.poll(); if((curZRC[0]==4&&curZRC[1]==4&&curZRC[2]==4)){//도착했으면 distance = Math.min(cnt,distance); return ; } for(int dir=0;dir<4;dir++){//현재 판에서 상우하좌 int nr = curZRC[1]+dr[dir]; int nc = curZRC[2]+dc[dir]; if(rangeCheck(nr,nc)){ if(mazeVisit[curZRC[0]][nr][nc]==false && maze[curZRC[0]][nr][nc]==1){//안가봤고 갈 수 있으면 mazeVisit[curZRC[0]][nr][nc] = true; q.add(new int[] {curZRC[0],nr,nc}); } } } for(int dir=0;dir<2;dir++){//Z축 2방향 int nz = curZRC[0]+dz[dir]; if(nz>=0 && nz<5){//영역 만족 if(mazeVisit[nz][curZRC[1]][curZRC[2]]==false && maze[nz][curZRC[1]][curZRC[2]]==1){//안가봤고 갈 수 있으면 mazeVisit[nz][curZRC[1]][curZRC[2]]=true; q.add(new int[] {nz,curZRC[1],curZRC[2]}); } } } } cnt++; } } private static boolean rangeCheck(int nr, int nc) { if(nr>=0 && nr<5 && nc>=0 && nc<5) return true; return false; } private static void setMaze() { for(int i=0;i<5;i++){ for(int row=0;row<5;row++) { for(int col=0;col<5;col++){ maze[i][row][col] = mazeCase[floor[i]][spin[i]][row][col]; } } } } private static void setRotationBoard() { for(int board=0;board<5;board++){//각 판에대해서 for(int spin=1;spin<4;spin++){//시계방향 회전을 한다. rotate(board,spin); } } } private static void rotate(int board,int spin) { for(int idx=0;idx<2;idx++){ for(int col=idx;col<(5-idx);col++){ mazeCase[board][spin][col][4-idx] = mazeCase[board][spin-1][idx][col];//상변이 우변으로 mazeCase[board][spin][col][idx] = mazeCase[board][spin-1][4-idx][col];//하변이 좌변으로 } for(int row=idx;row<(5-idx);row++){ mazeCase[board][spin][4-idx][4-row] = mazeCase[board][spin-1][row][4-idx];//우변이 하변으로 mazeCase[board][spin][idx][4-row] = mazeCase[board][spin-1][row][idx];//좌변이 상변으로 } } mazeCase[board][spin][2][2] = mazeCase[board][spin-1][2][2]; } private static void view() { for(int spin=0;spin<4;spin++) { for(int row=0;row<5;row++) { for(int col=0;col<5;col++) { System.out.print(mazeCase[0][spin][row][col]); } System.out.println(); } System.out.println(); } } }
5,169
0.583465
0.545866
159
26.767296
20.896328
104
false
false
0
0
0
0
0
0
3.08805
false
false
12
1219ecae2ef2a9274b8b22e7f6309bf1d86b60bd
38,053,410,252,479
7b09dcc14b89ec403e4b1f77848bf3b04176d72a
/Samsung_past/boj_19236_final.java
9d1b32e0cf18473422ea52c1f45bc94ee5865828
[]
no_license
kkh8676/Baekjoon
https://github.com/kkh8676/Baekjoon
af438f26cc0160825198bac240c699adc8d197b8
ae2a12425f4a8f857f90ed2dd03cf7f1a313e2c0
refs/heads/master
2023-03-10T14:00:36.270000
2021-02-26T13:06:36
2021-02-26T13:06:36
287,746,526
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// Took 1hr 55 min......... // Already solved Problem import java.io.*; import java.util.Arrays; class boj_19236_final{ static int[][] board; // first mean fish index // 0 : row // 1 : column // 2 : direction // 3 : dead or not static int[][] fish; static final int SHARK = 0; static int[] dr = {0,-1,-1,0,1,1,1,0,-1}; static int[] dc = {0,0,-1,-1,-1,0,1,1,1}; static int ANSWER; static int SCORE; public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); board = new int[4][4]; fish = new int[17][4]; for (int r=0; r<4; r++) { String[] curRow = br.readLine().split(" "); for(int c=0; c<4; c++){ int fish_num = Integer.parseInt(curRow[2*c]); // 0,2,4,6 int fish_dir = Integer.parseInt(curRow[2*c+1]); // 1,3,5,7 board[r][c] = fish_num; fish[fish_num][0] = r; fish[fish_num][1] = c; fish[fish_num][2] = fish_dir; fish[fish_num][3] = 0; } }// end of getting board....... SCORE = 0; ANSWER = Integer.MIN_VALUE; DFS(0,0); System.out.println(ANSWER); }// end of main method public static void DFS(int r, int c){ // 상어가 r,c로 이동 fish[SHARK][0] = r ; fish[SHARK][1] = c; int eaten_f = board[r][c]; fish[SHARK][2] = fish[ eaten_f ][2]; // 점수 변화 SCORE = SCORE + eaten_f; // 해당 위치의 물고기 변화, 즉 물고기는 죽는다. fish[ eaten_f ][3] = 1; // 3 dead fish[ eaten_f ][0] = -1; // 0 row fish[ eaten_f ][1] = -1; // 1 col fish[ eaten_f ][2] = -1; // 2 dir // board에서 해당 위치는 0이 된다!! // board에서 상어는 0 나머지는 자연수, 빈칸은 -1로 처리 board[r][c] = 0; // 물고기 이동 update(); //System.out.println("After fishes moves are done!\n"); //print_board(); // 상어가 갈 수 있는 위치가 있는 지 확인, 갈 데가 없다면 DFS 종료 // 최대 3번 상어가 갈 수 있는 지 아닌 지 확인. 갈 수 있다면 해당 위치로 ㄱㄱ int cSR = fish[SHARK][0]; // current Shark Row int cSC = fish[SHARK][1]; // current Shark Column int cSD = fish[SHARK][2]; // current Shark direction for (int p=0; p<3; p++) { // 상어 DFS ㄱㄱ // 해당 위치에 물고기가 있따면 ㄱㄱ int nSR = cSR + dr[cSD]*(p+1); int nSC = cSC + dc[cSD]*(p+1); // 범위를 넘어선다면 그냥 contunue; if(nSR < 0 || nSR >= 4 || nSC < 0 || nSC >= 4) continue; if(board[nSR][nSC] > 0) { // Saving State int prevScore = SCORE; int[][] prevBoard = new int[4][4]; int[][] prevFish = new int[17][4]; copyAry(prevBoard, board); copyAry(prevFish, fish); board[cSR][cSC] = -1; //System.out.println("DFS at "+nSR + " "+nSC); DFS(nSR,nSC); copyAry(fish, prevFish); copyAry(board,prevBoard); SCORE = prevScore; // Loading STate } }// end of for loop ANSWER = SCORE > ANSWER? SCORE : ANSWER; }// end of DFS method // fish location updating!! public static void update(){ // 작은 물고기부터 순서대로 움직인다. for (int num=1; num<=16; num++) { // 물고기가 이미 죽었다면 그냥 coninue; // 내가 빈 칸인 경우는 없다. if(fish[num][3] == 1) continue; // 현재 방향 먼저 살피고 총 여덟번 살펴야한다. int cfr = fish[num][0]; int cfc = fish[num][1]; int cfd = fish[num][2]; int nfd = cfd; for (int i=0; i<8; i++) { if(i!=0) nfd = nfd%8 + 1; //System.out.println("cfd " + cfd+ " nfd "+nfd); int nfr = cfr + dr[nfd]; int nfc = cfc + dc[nfd]; // 범위를 넘어선다면 다음으로 ㄱㄱ; if(nfr < 0 || nfr >= 4 || nfc <0 || nfc >= 4) continue; // 다음 위치에 물고기가 있거나 빈칸이라면 위치 바꾼다.! if(board[nfr][nfc] == -1 || board[nfr][nfc] > 0 ){ // 해당 위치와 change!! fish[num][2] = nfd; change(cfr,cfc,nfr,nfc); //System.out.print("Updating proces "+ num +" fish \n"); //print_board(); break; } // end of change possible if condition }// end of for loop for next 8 direction }//end of fish number } // end of update method // changing the location of two fishes......... // fish가 없을 수도 있는데 이건 어떻게 처리를 하지? public static void change(int r1, int c1, int r2, int c2){ // fish num 1 : alive fish _num int fish1 = board[r1][c1]; int fish2 = board[r2][c2]; board[r1][c1] = fish2; board[r2][c2] = fish1; fish[fish1][0] = r2; fish[fish1][1] = c2; if(fish2 != -1){ fish[fish2][0] = r1; fish[fish2][1] = c1; } // fish num 2: changing, but 살았는 지 죽었는 지 모른다. } public static void copyAry(int[][] cAry, int[][] oAry){ for (int r=0; r<cAry.length; r++) { for (int c=0; c<cAry[0].length; c++) { cAry[r][c] = oAry[r][c]; } } } public static void print_board(){ for (int i=0; i<4; i++) { for (int c=0; c<4; c++) { System.out.print(board[i][c] + " " ); } System.out.println(); } } }// end of class
UTF-8
Java
5,285
java
boj_19236_final.java
Java
[]
null
[]
// Took 1hr 55 min......... // Already solved Problem import java.io.*; import java.util.Arrays; class boj_19236_final{ static int[][] board; // first mean fish index // 0 : row // 1 : column // 2 : direction // 3 : dead or not static int[][] fish; static final int SHARK = 0; static int[] dr = {0,-1,-1,0,1,1,1,0,-1}; static int[] dc = {0,0,-1,-1,-1,0,1,1,1}; static int ANSWER; static int SCORE; public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); board = new int[4][4]; fish = new int[17][4]; for (int r=0; r<4; r++) { String[] curRow = br.readLine().split(" "); for(int c=0; c<4; c++){ int fish_num = Integer.parseInt(curRow[2*c]); // 0,2,4,6 int fish_dir = Integer.parseInt(curRow[2*c+1]); // 1,3,5,7 board[r][c] = fish_num; fish[fish_num][0] = r; fish[fish_num][1] = c; fish[fish_num][2] = fish_dir; fish[fish_num][3] = 0; } }// end of getting board....... SCORE = 0; ANSWER = Integer.MIN_VALUE; DFS(0,0); System.out.println(ANSWER); }// end of main method public static void DFS(int r, int c){ // 상어가 r,c로 이동 fish[SHARK][0] = r ; fish[SHARK][1] = c; int eaten_f = board[r][c]; fish[SHARK][2] = fish[ eaten_f ][2]; // 점수 변화 SCORE = SCORE + eaten_f; // 해당 위치의 물고기 변화, 즉 물고기는 죽는다. fish[ eaten_f ][3] = 1; // 3 dead fish[ eaten_f ][0] = -1; // 0 row fish[ eaten_f ][1] = -1; // 1 col fish[ eaten_f ][2] = -1; // 2 dir // board에서 해당 위치는 0이 된다!! // board에서 상어는 0 나머지는 자연수, 빈칸은 -1로 처리 board[r][c] = 0; // 물고기 이동 update(); //System.out.println("After fishes moves are done!\n"); //print_board(); // 상어가 갈 수 있는 위치가 있는 지 확인, 갈 데가 없다면 DFS 종료 // 최대 3번 상어가 갈 수 있는 지 아닌 지 확인. 갈 수 있다면 해당 위치로 ㄱㄱ int cSR = fish[SHARK][0]; // current Shark Row int cSC = fish[SHARK][1]; // current Shark Column int cSD = fish[SHARK][2]; // current Shark direction for (int p=0; p<3; p++) { // 상어 DFS ㄱㄱ // 해당 위치에 물고기가 있따면 ㄱㄱ int nSR = cSR + dr[cSD]*(p+1); int nSC = cSC + dc[cSD]*(p+1); // 범위를 넘어선다면 그냥 contunue; if(nSR < 0 || nSR >= 4 || nSC < 0 || nSC >= 4) continue; if(board[nSR][nSC] > 0) { // Saving State int prevScore = SCORE; int[][] prevBoard = new int[4][4]; int[][] prevFish = new int[17][4]; copyAry(prevBoard, board); copyAry(prevFish, fish); board[cSR][cSC] = -1; //System.out.println("DFS at "+nSR + " "+nSC); DFS(nSR,nSC); copyAry(fish, prevFish); copyAry(board,prevBoard); SCORE = prevScore; // Loading STate } }// end of for loop ANSWER = SCORE > ANSWER? SCORE : ANSWER; }// end of DFS method // fish location updating!! public static void update(){ // 작은 물고기부터 순서대로 움직인다. for (int num=1; num<=16; num++) { // 물고기가 이미 죽었다면 그냥 coninue; // 내가 빈 칸인 경우는 없다. if(fish[num][3] == 1) continue; // 현재 방향 먼저 살피고 총 여덟번 살펴야한다. int cfr = fish[num][0]; int cfc = fish[num][1]; int cfd = fish[num][2]; int nfd = cfd; for (int i=0; i<8; i++) { if(i!=0) nfd = nfd%8 + 1; //System.out.println("cfd " + cfd+ " nfd "+nfd); int nfr = cfr + dr[nfd]; int nfc = cfc + dc[nfd]; // 범위를 넘어선다면 다음으로 ㄱㄱ; if(nfr < 0 || nfr >= 4 || nfc <0 || nfc >= 4) continue; // 다음 위치에 물고기가 있거나 빈칸이라면 위치 바꾼다.! if(board[nfr][nfc] == -1 || board[nfr][nfc] > 0 ){ // 해당 위치와 change!! fish[num][2] = nfd; change(cfr,cfc,nfr,nfc); //System.out.print("Updating proces "+ num +" fish \n"); //print_board(); break; } // end of change possible if condition }// end of for loop for next 8 direction }//end of fish number } // end of update method // changing the location of two fishes......... // fish가 없을 수도 있는데 이건 어떻게 처리를 하지? public static void change(int r1, int c1, int r2, int c2){ // fish num 1 : alive fish _num int fish1 = board[r1][c1]; int fish2 = board[r2][c2]; board[r1][c1] = fish2; board[r2][c2] = fish1; fish[fish1][0] = r2; fish[fish1][1] = c2; if(fish2 != -1){ fish[fish2][0] = r1; fish[fish2][1] = c1; } // fish num 2: changing, but 살았는 지 죽었는 지 모른다. } public static void copyAry(int[][] cAry, int[][] oAry){ for (int r=0; r<cAry.length; r++) { for (int c=0; c<cAry[0].length; c++) { cAry[r][c] = oAry[r][c]; } } } public static void print_board(){ for (int i=0; i<4; i++) { for (int c=0; c<4; c++) { System.out.print(board[i][c] + " " ); } System.out.println(); } } }// end of class
5,285
0.528496
0.495268
198
22.025253
17.161572
75
false
false
0
0
0
0
0
0
2.762626
false
false
12
29a347a7c7c823d20eb1f706bdac44586a19c3c6
10,505,490,060,209
9e755285782704775d7a1943338625db78c2fe2c
/com.star.mobile.video_ppv_20160115/src/com/star/mobile/video/fragment/ChannelGuideFragment.java
a8cf734b8dd950b5510089a91079dbd13df2c490
[]
no_license
XueBaoPeng/ppv_android
https://github.com/XueBaoPeng/ppv_android
a3ba3038568134d8173ded828a41a92c9fefd26a
7fde328847c250c4937e603179326d5976051113
refs/heads/master
2021-01-10T14:35:48.242000
2016-03-10T08:39:38
2016-03-10T08:39:38
53,650,310
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.star.mobile.video.fragment; import java.util.List; import android.os.Bundle; import android.os.Handler; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import com.star.cms.model.Channel; import com.star.cms.model.enm.OrderType; import com.star.cms.model.vo.ChannelVO; import com.star.mobile.video.R; import com.star.mobile.video.base.BaseFragment; import com.star.mobile.video.base.BaseFragmentActivity; import com.star.mobile.video.util.LoadingDataTask; import com.star.mobile.video.util.MaskUtil; import com.star.mobile.video.view.ChannelGuideChannel; import com.star.mobile.video.view.ChannelGuideVideo; public class ChannelGuideFragment extends BaseFragment { private ViewGroup mView; private BaseFragmentActivity channelGuideActivity; private ChannelVO mChannel; private AllChannelFragment mChildFragment; private ChannelGuideChannel channelLayout; private ChannelGuideVideo videoLayout; private Long channelID; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if(mView != null){ ViewGroup parent = (ViewGroup) mView.getParent(); if(parent != null) { parent.removeView(mView); } return mView; } channelGuideActivity = (BaseFragmentActivity) getActivity(); mView = new LinearLayout(channelGuideActivity); mView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); mChildFragment = new AllChannelFragment(this, channelGuideActivity); channelGuideActivity.mAllChannelFragment = mChildFragment; if(mChannel!=null&&mChannel.getType()!=null){ if(mChannel.getType()==Channel.LIVE_TYPE){ mView.addView(getChannelLayout()); }else{ mView.addView(getVideoLayout()); } }else if(mChannel==null && channelID==null){ executeFavTask(); } return mView; } @Override public void onStart() { if(mChannel!=null){ setCurrentChannel(mChannel.getId()); } if(mChildFragment!=null){ mChildFragment.loadingData(); } super.onStart(); } public void setCurrentChannel(final Long channelID){ this.channelID = channelID; handler.sendEmptyMessage(0); } private Handler handler = new Handler(){ public void handleMessage(android.os.Message msg) { new LoadingDataTask() { private ChannelVO ch; @Override public void onPreExecute() { } @Override public void onPostExecute() { setCurrentChannel(ch); } @Override public void doInBackground() { ch = getChannelService().getChannelById(channelID); } }.execute(); }; }; private void executeFavTask(){ new LoadingDataTask() { private List<ChannelVO> chns; @Override public void onPreExecute() { } @Override public void onPostExecute() { if(chns != null && chns.size()>0){ ChannelVO vo = chns.get(0); setCurrentChannel(vo); } new Handler().postDelayed(new Runnable() { @Override public void run() { if(channelGuideActivity!=null && !channelGuideActivity.isFromTask()) channelGuideActivity.showAllchannelFragment(); } }, 300); } @Override public void doInBackground() { chns = getChannelService().getChannels(OrderType.FAVORITE, 0, 1); } }.execute(); } public void setCurrentChannel(ChannelVO channel){ if(channel!=null && channel.equals(mChannel)){ return; } Integer pageType = Channel.LIVE_TYPE; if(channel!=null) pageType = channel.getType()==null?0:channel.getType(); if(mView != null){ if(pageType == Channel.LIVE_TYPE){ if(mChannel==null || (mChannel!=null&&!pageType.equals(mChannel.getType()))){ mView.removeAllViews(); mView.addView(getChannelLayout()); } setChannelGuideChannel(channel); }else{ if(mChannel==null || (mChannel!=null&&!pageType.equals(mChannel.getType()))){ mView.removeAllViews(); mView.addView(getVideoLayout()); } channelGuideVideoSet(channel); } } mChannel = channel; } private void setChannelGuideChannel(ChannelVO channel){ getChannelLayout().setCurrentChannel(channel); new Handler().postDelayed(new Runnable() { @Override public void run() { if(!mChildFragment.isShown()&&channelGuideActivity!=null&&!channelGuideActivity.isFromTask()) MaskUtil.showChatroomOnTVGuideFrame(channelGuideActivity); } }, 500); } /** * channelGuideVideo的设置 * @param channel */ private void channelGuideVideoSet(ChannelVO channel) { getVideoLayout().setCurrentChannel(channel); } public ChannelGuideChannel getChannelLayout() { channelGuideActivity.setCurrentFragmentTag(channelGuideActivity.getResources().getString(R.string.fragment_tag_channelGuide)); if(channelLayout==null){ channelLayout = new ChannelGuideChannel(channelGuideActivity, this); } return channelLayout; } public ChannelGuideVideo getVideoLayout() { channelGuideActivity.setCurrentFragmentTag(channelGuideActivity.getResources().getString(R.string.tag_video_list)); if(videoLayout==null){ videoLayout = new ChannelGuideVideo(channelGuideActivity); } return videoLayout; } }
UTF-8
Java
5,444
java
ChannelGuideFragment.java
Java
[]
null
[]
package com.star.mobile.video.fragment; import java.util.List; import android.os.Bundle; import android.os.Handler; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import com.star.cms.model.Channel; import com.star.cms.model.enm.OrderType; import com.star.cms.model.vo.ChannelVO; import com.star.mobile.video.R; import com.star.mobile.video.base.BaseFragment; import com.star.mobile.video.base.BaseFragmentActivity; import com.star.mobile.video.util.LoadingDataTask; import com.star.mobile.video.util.MaskUtil; import com.star.mobile.video.view.ChannelGuideChannel; import com.star.mobile.video.view.ChannelGuideVideo; public class ChannelGuideFragment extends BaseFragment { private ViewGroup mView; private BaseFragmentActivity channelGuideActivity; private ChannelVO mChannel; private AllChannelFragment mChildFragment; private ChannelGuideChannel channelLayout; private ChannelGuideVideo videoLayout; private Long channelID; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if(mView != null){ ViewGroup parent = (ViewGroup) mView.getParent(); if(parent != null) { parent.removeView(mView); } return mView; } channelGuideActivity = (BaseFragmentActivity) getActivity(); mView = new LinearLayout(channelGuideActivity); mView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); mChildFragment = new AllChannelFragment(this, channelGuideActivity); channelGuideActivity.mAllChannelFragment = mChildFragment; if(mChannel!=null&&mChannel.getType()!=null){ if(mChannel.getType()==Channel.LIVE_TYPE){ mView.addView(getChannelLayout()); }else{ mView.addView(getVideoLayout()); } }else if(mChannel==null && channelID==null){ executeFavTask(); } return mView; } @Override public void onStart() { if(mChannel!=null){ setCurrentChannel(mChannel.getId()); } if(mChildFragment!=null){ mChildFragment.loadingData(); } super.onStart(); } public void setCurrentChannel(final Long channelID){ this.channelID = channelID; handler.sendEmptyMessage(0); } private Handler handler = new Handler(){ public void handleMessage(android.os.Message msg) { new LoadingDataTask() { private ChannelVO ch; @Override public void onPreExecute() { } @Override public void onPostExecute() { setCurrentChannel(ch); } @Override public void doInBackground() { ch = getChannelService().getChannelById(channelID); } }.execute(); }; }; private void executeFavTask(){ new LoadingDataTask() { private List<ChannelVO> chns; @Override public void onPreExecute() { } @Override public void onPostExecute() { if(chns != null && chns.size()>0){ ChannelVO vo = chns.get(0); setCurrentChannel(vo); } new Handler().postDelayed(new Runnable() { @Override public void run() { if(channelGuideActivity!=null && !channelGuideActivity.isFromTask()) channelGuideActivity.showAllchannelFragment(); } }, 300); } @Override public void doInBackground() { chns = getChannelService().getChannels(OrderType.FAVORITE, 0, 1); } }.execute(); } public void setCurrentChannel(ChannelVO channel){ if(channel!=null && channel.equals(mChannel)){ return; } Integer pageType = Channel.LIVE_TYPE; if(channel!=null) pageType = channel.getType()==null?0:channel.getType(); if(mView != null){ if(pageType == Channel.LIVE_TYPE){ if(mChannel==null || (mChannel!=null&&!pageType.equals(mChannel.getType()))){ mView.removeAllViews(); mView.addView(getChannelLayout()); } setChannelGuideChannel(channel); }else{ if(mChannel==null || (mChannel!=null&&!pageType.equals(mChannel.getType()))){ mView.removeAllViews(); mView.addView(getVideoLayout()); } channelGuideVideoSet(channel); } } mChannel = channel; } private void setChannelGuideChannel(ChannelVO channel){ getChannelLayout().setCurrentChannel(channel); new Handler().postDelayed(new Runnable() { @Override public void run() { if(!mChildFragment.isShown()&&channelGuideActivity!=null&&!channelGuideActivity.isFromTask()) MaskUtil.showChatroomOnTVGuideFrame(channelGuideActivity); } }, 500); } /** * channelGuideVideo的设置 * @param channel */ private void channelGuideVideoSet(ChannelVO channel) { getVideoLayout().setCurrentChannel(channel); } public ChannelGuideChannel getChannelLayout() { channelGuideActivity.setCurrentFragmentTag(channelGuideActivity.getResources().getString(R.string.fragment_tag_channelGuide)); if(channelLayout==null){ channelLayout = new ChannelGuideChannel(channelGuideActivity, this); } return channelLayout; } public ChannelGuideVideo getVideoLayout() { channelGuideActivity.setCurrentFragmentTag(channelGuideActivity.getResources().getString(R.string.tag_video_list)); if(videoLayout==null){ videoLayout = new ChannelGuideVideo(channelGuideActivity); } return videoLayout; } }
5,444
0.702832
0.700625
187
27.080214
24.465385
128
false
false
0
0
0
0
0
0
2.625669
false
false
12
9c586e7f07b372df3fb6489434ba06f4eb96a9b5
36,593,121,392,579
badf3b50c949c683999d223ad6989093e9d1ab97
/src/vimath/mathparser/exception/UndefinedValueException.java
325dd9f5229e36e38da4cdcbb1396c9c82998eca
[]
no_license
01885404983/vimath
https://github.com/01885404983/vimath
ba581b072c4b638890c8f4c7baac0b4cf0d96ab2
7cd694fa7d0ad3ec73b74cdd57116b7254895f6c
refs/heads/master
2017-12-22T10:40:05.547000
2016-05-16T10:37:57
2016-05-16T10:37:57
55,128,654
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package vimath.mathparser.exception; public class UndefinedValueException extends EvaluationException { public UndefinedValueException() {super();} public UndefinedValueException(String s) {super(s);} public UndefinedValueException(Throwable cause) { super(cause); } public UndefinedValueException(String msg, Throwable cause) { super(msg, cause); } }
UTF-8
Java
366
java
UndefinedValueException.java
Java
[]
null
[]
package vimath.mathparser.exception; public class UndefinedValueException extends EvaluationException { public UndefinedValueException() {super();} public UndefinedValueException(String s) {super(s);} public UndefinedValueException(Throwable cause) { super(cause); } public UndefinedValueException(String msg, Throwable cause) { super(msg, cause); } }
366
0.781421
0.781421
10
35.700001
26.077002
67
false
false
0
0
0
0
0
0
0.7
false
false
12
a0b4642d34f1abeb7e35087d0b5e910a9702bed0
39,058,432,617,949
f9bc5195ae8feb013821d0a0cffc9e2eb12f54b4
/src/main/java/com/cf/dto/InvoiceDTO.java
bee807e64509bbf48b88941f7740756a396855b4
[]
no_license
Jeffer23/OpenShiftCentraForklifts
https://github.com/Jeffer23/OpenShiftCentraForklifts
2943563320301ab09054ee2b84ae998ccc089a58
6c8034ac1a158550b8e82123ff90314ff27cd53f
refs/heads/master
2022-12-03T16:46:48.299000
2019-12-22T20:15:18
2019-12-22T20:15:18
220,217,227
0
0
null
false
2022-11-24T10:01:35
2019-11-07T11:06:43
2019-12-22T20:15:21
2022-11-24T10:01:31
7,767
0
0
2
CSS
false
false
package com.cf.dto; import java.util.ArrayList; import java.util.Calendar; import java.util.List; public class InvoiceDTO { private int invoiceId; private Calendar invoiceDate; private Calendar dueDate; private float subTotal; private float discount; private float subTotalLessDiscount; private float taxRate; private float totalTax; private float shippingFee; private float balanceDue; public int getInvoiceId() { return invoiceId; } public void setInvoiceId(int invoiceId) { this.invoiceId = invoiceId; } public Calendar getInvoiceDate() { return invoiceDate; } public void setInvoiceDate(Calendar invoiceDate) { this.invoiceDate = invoiceDate; } public Calendar getDueDate() { return dueDate; } public void setDueDate(Calendar dueDate) { this.dueDate = dueDate; } public float getSubTotal() { return subTotal; } public void setSubTotal(float subTotal) { this.subTotal = subTotal; } public float getDiscount() { return discount; } public void setDiscount(float discount) { this.discount = discount; } public float getSubTotalLessDiscount() { return subTotalLessDiscount; } public void setSubTotalLessDiscount(float subTotalLessDiscount) { this.subTotalLessDiscount = subTotalLessDiscount; } public float getTotalTax() { return totalTax; } public void setTotalTax(float totalTax) { this.totalTax = totalTax; } public float getShippingFee() { return shippingFee; } public void setShippingFee(float shippingFee) { this.shippingFee = shippingFee; } public float getBalanceDue() { return balanceDue; } public void setBalanceDue(float balanceDue) { this.balanceDue = balanceDue; } public float getTaxRate() { return taxRate; } public void setTaxRate(float taxRate) { this.taxRate = taxRate; } @Override public String toString() { return "InvoiceDTO [invoiceId=" + invoiceId + ", invoiceDate=" + invoiceDate + ", dueDate=" + dueDate + ", subTotal=" + subTotal + ", discount=" + discount + ", subTotalLessDiscount=" + subTotalLessDiscount + ", taxRate=" + taxRate + ", totalTax=" + totalTax + ", shippingFee=" + shippingFee + ", balanceDue=" + balanceDue + "]"; } }
UTF-8
Java
2,222
java
InvoiceDTO.java
Java
[]
null
[]
package com.cf.dto; import java.util.ArrayList; import java.util.Calendar; import java.util.List; public class InvoiceDTO { private int invoiceId; private Calendar invoiceDate; private Calendar dueDate; private float subTotal; private float discount; private float subTotalLessDiscount; private float taxRate; private float totalTax; private float shippingFee; private float balanceDue; public int getInvoiceId() { return invoiceId; } public void setInvoiceId(int invoiceId) { this.invoiceId = invoiceId; } public Calendar getInvoiceDate() { return invoiceDate; } public void setInvoiceDate(Calendar invoiceDate) { this.invoiceDate = invoiceDate; } public Calendar getDueDate() { return dueDate; } public void setDueDate(Calendar dueDate) { this.dueDate = dueDate; } public float getSubTotal() { return subTotal; } public void setSubTotal(float subTotal) { this.subTotal = subTotal; } public float getDiscount() { return discount; } public void setDiscount(float discount) { this.discount = discount; } public float getSubTotalLessDiscount() { return subTotalLessDiscount; } public void setSubTotalLessDiscount(float subTotalLessDiscount) { this.subTotalLessDiscount = subTotalLessDiscount; } public float getTotalTax() { return totalTax; } public void setTotalTax(float totalTax) { this.totalTax = totalTax; } public float getShippingFee() { return shippingFee; } public void setShippingFee(float shippingFee) { this.shippingFee = shippingFee; } public float getBalanceDue() { return balanceDue; } public void setBalanceDue(float balanceDue) { this.balanceDue = balanceDue; } public float getTaxRate() { return taxRate; } public void setTaxRate(float taxRate) { this.taxRate = taxRate; } @Override public String toString() { return "InvoiceDTO [invoiceId=" + invoiceId + ", invoiceDate=" + invoiceDate + ", dueDate=" + dueDate + ", subTotal=" + subTotal + ", discount=" + discount + ", subTotalLessDiscount=" + subTotalLessDiscount + ", taxRate=" + taxRate + ", totalTax=" + totalTax + ", shippingFee=" + shippingFee + ", balanceDue=" + balanceDue + "]"; } }
2,222
0.713771
0.713771
132
15.833333
20.914749
108
false
false
0
0
0
0
0
0
1.189394
false
false
12
c674fb9da27e28bb8099e1bfeb6ad76191533116
38,749,194,961,727
8052e551630ad6aa62036f19eb9e7255f456bdaa
/src/com/kzw/system/web/DictionaryAction.java
2665d1982e2e69018a0e11913b1601359dabe4fe
[]
no_license
phoebemoon16/MoBook
https://github.com/phoebemoon16/MoBook
45e2b35904fc369c32f36d0f6b8b82149ead86c4
e6fd1b64fc5834b4322d3e67f5e06e37a7bdf223
refs/heads/master
2020-03-21T22:43:13.727000
2018-06-29T11:57:44
2018-06-29T11:57:44
139,143,078
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.kzw.system.web; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.kzw.comm.vo.Msg; import com.kzw.core.orm.Page; import com.kzw.core.orm.PageRequest; import com.kzw.core.orm.StringPropertyFilter; import com.kzw.core.util.JSON; import com.kzw.core.util.web.ResponseUtils; import com.kzw.system.entity.Dictionary; import com.kzw.system.service.DictionaryService; @Controller @RequestMapping("/dict") public class DictionaryAction { @Autowired private DictionaryService dictionaryService; @RequestMapping("view") public String view() { return "system/dictionary_view"; } @RequestMapping("save") public String save(Dictionary dict) { dictionaryService.saveOrUpdate(dict); return "redirect:/dict/list"; } @RequestMapping("list") public void list(PageRequest pageRequest, HttpServletRequest request, HttpServletResponse response) { List<StringPropertyFilter> filters = StringPropertyFilter.buildFromHttpRequest(request); Page<Dictionary> page = dictionaryService.search2(pageRequest, filters); String json = new JSON(page).buildWithFilters(3); ResponseUtils.renderJson(response, json); } @RequestMapping("get/{id}") public String get(@PathVariable("id")int id, Model model) { Dictionary dict = dictionaryService.get(id); model.addAttribute("dict", dict); return "system/dictionary_form"; } @ResponseBody @RequestMapping("delete") public Msg delete(String ids) { dictionaryService.remove(ids); return new Msg(true); } }
UTF-8
Java
1,895
java
DictionaryAction.java
Java
[]
null
[]
package com.kzw.system.web; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.kzw.comm.vo.Msg; import com.kzw.core.orm.Page; import com.kzw.core.orm.PageRequest; import com.kzw.core.orm.StringPropertyFilter; import com.kzw.core.util.JSON; import com.kzw.core.util.web.ResponseUtils; import com.kzw.system.entity.Dictionary; import com.kzw.system.service.DictionaryService; @Controller @RequestMapping("/dict") public class DictionaryAction { @Autowired private DictionaryService dictionaryService; @RequestMapping("view") public String view() { return "system/dictionary_view"; } @RequestMapping("save") public String save(Dictionary dict) { dictionaryService.saveOrUpdate(dict); return "redirect:/dict/list"; } @RequestMapping("list") public void list(PageRequest pageRequest, HttpServletRequest request, HttpServletResponse response) { List<StringPropertyFilter> filters = StringPropertyFilter.buildFromHttpRequest(request); Page<Dictionary> page = dictionaryService.search2(pageRequest, filters); String json = new JSON(page).buildWithFilters(3); ResponseUtils.renderJson(response, json); } @RequestMapping("get/{id}") public String get(@PathVariable("id")int id, Model model) { Dictionary dict = dictionaryService.get(id); model.addAttribute("dict", dict); return "system/dictionary_form"; } @ResponseBody @RequestMapping("delete") public Msg delete(String ids) { dictionaryService.remove(ids); return new Msg(true); } }
1,895
0.788391
0.787335
63
29.079365
23.278372
102
false
false
0
0
0
0
0
0
1.333333
false
false
12
953b727ab1b378b0ee24cb877ef387b45cf5defb
29,755,533,475,858
ca95f11f172474efdf8c9860153f158d235c1601
/arsenal-java/arsenal-design/src/main/java/com/yanxml/design/book/design/factory/simple/Human.java
586166e57d9832ca94a7b11ca7ecd96c7f30e19c
[ "Apache-2.0" ]
permissive
SeanYanxml/arsenal
https://github.com/SeanYanxml/arsenal
2bbf1ec430c952dc30cb174ea62b11d7ab7d78d6
d13b9b327111f36b1c46d9d3ec00305aebdc93e4
refs/heads/master
2018-12-06T00:03:49.647000
2018-12-02T19:04:30
2018-12-02T19:04:30
135,309,475
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yanxml.design.book.design.factory.simple; public interface Human { // 每个人种的皮肤有相应的颜色 public void getColor(); // 人类会说话 public void talk(); }
UTF-8
Java
193
java
Human.java
Java
[]
null
[]
package com.yanxml.design.book.design.factory.simple; public interface Human { // 每个人种的皮肤有相应的颜色 public void getColor(); // 人类会说话 public void talk(); }
193
0.732484
0.732484
9
16.444445
15.979926
53
false
false
0
0
0
0
0
0
0.777778
false
false
12
cded2c8cd45a811cf70f436b4fa2d466346017e8
18,648,748,046,088
27cf821c5ea90b2bf29fa038edfe17fc27b24367
/Day08/src/middle_test/test04.java
2785b806b47c50e3dcf50e487100e5737cab2b6a
[]
no_license
noarcho/Java
https://github.com/noarcho/Java
0a128bbcff0294f4b9e52fbfb913e788203ef5c6
303b7cc18c5629417bb6ec034b597499ffc4295d
refs/heads/master
2021-01-11T00:52:52.572000
2016-10-11T08:01:53
2016-10-11T08:01:53
70,456,664
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package middle_test; import java.lang.reflect.Array; import java.util.Scanner; public class test04 { public static void main(String[] args) { int[] array1 = {10, 20, 30, 40}; int[] array2 = new int[array1.length]; //얕은 복사 : 둘다 같은 주소값을 가르킨다 int[] array3 = array1; //깊은 복사 : 두개가 다른 주소값을 가르킨다. for(int i = 0; i<array1.length;i++) array2[i] = array1[i]; array2 = new int[array1.length]; for(int n:array2){ array1[n] = array2[n]; } // 전통적인 for 루프는 3항(초기화; 조건; 증감)을 쓰는 대신 for each는 두항(변수:배열)만을 쓴다. // 일반 for 루프는 조건을 지정해줘야하지만 for each는 배열의 끝까지 자동으로 계속 돌아가게 된다. } }
UHC
Java
839
java
test04.java
Java
[]
null
[]
package middle_test; import java.lang.reflect.Array; import java.util.Scanner; public class test04 { public static void main(String[] args) { int[] array1 = {10, 20, 30, 40}; int[] array2 = new int[array1.length]; //얕은 복사 : 둘다 같은 주소값을 가르킨다 int[] array3 = array1; //깊은 복사 : 두개가 다른 주소값을 가르킨다. for(int i = 0; i<array1.length;i++) array2[i] = array1[i]; array2 = new int[array1.length]; for(int n:array2){ array1[n] = array2[n]; } // 전통적인 for 루프는 3항(초기화; 조건; 증감)을 쓰는 대신 for each는 두항(변수:배열)만을 쓴다. // 일반 for 루프는 조건을 지정해줘야하지만 for each는 배열의 끝까지 자동으로 계속 돌아가게 된다. } }
839
0.588144
0.549142
30
19.433332
18.465614
66
false
false
0
0
0
0
0
0
2.033333
false
false
12
e17457634daf158ab8239921ace8d046069ca62a
9,921,374,509,513
02333c980524dc474dc4659f1411b0f89efad4eb
/src/main/java/com/bi/corelog/format/AppPlayFormatMR.java
51460c010e444cacb8afb6c1e9610d172a1d1979
[]
no_license
jeremy0822/cloud-platform-corelog
https://github.com/jeremy0822/cloud-platform-corelog
fcc6e20a912c482c4d085b2a0b4083d518deaf5b
7c4fbc43ff2a6eac5da72725442c17bb6bf23ecc
refs/heads/master
2016-08-10T18:15:03.114000
2016-04-01T10:58:18
2016-04-01T10:58:18
55,140,006
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bi.corelog.format; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.MultipleOutputs; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import com.bi.corelog.util.CommonConstant; import com.bi.corelog.util.CoreLogFormatUtil; import com.bi.corelog.util.PlatFormatUtil; import com.funshion.dc.cloud.common.constant.DefaultFieldValueEnum; import com.funshion.dc.cloud.common.dao.AbstractDMDAO; import com.funshion.dc.cloud.common.dao.DMIPRuleDAOImpl; import com.funshion.dc.cloud.common.dao.DMPlatyRuleDAOImpl; import com.funshion.dc.cloud.common.dao.DMQuDaoRuleDAOImpl; import com.funshion.dc.cloud.common.enums.AppPlayEnum; import com.funshion.dc.cloud.common.enums.ConstantEnum; import com.funshion.dc.cloud.common.pojo.DevInfo; import com.funshion.dc.cloud.common.util.FormatFunctionUtil; import com.funshion.dc.cloud.common.util.TimeFormat; public class AppPlayFormatMR extends Configured implements Tool { public static void main(String[] args) throws Exception { int nRet = ToolRunner.run(new Configuration(), new AppPlayFormatMR(), args); System.out.println(nRet); } @Override public int run(String[] args) throws Exception { Configuration conf = getConf(); Job job = Job.getInstance(conf); job.setJarByClass(AppPlayFormatMR.class); String jobName = conf.get("jobName", "AppPlayFormat"); job.setJobName(jobName); job.setMapperClass(AppPlayMapper.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(NullWritable.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(NullWritable.class); String inputPathStr = conf.get(CommonConstant.INPUT_PATH); for (int i = 0; i < 24; i++) { if (i < 10) FileInputFormat.addInputPaths(job, inputPathStr + "/0" + i+"/"); else FileInputFormat.addInputPaths(job, inputPathStr +"/"+ i+"/"); } String outputPathStr = conf.get(CommonConstant.OUTPUT_PATH); FileOutputFormat.setOutputPath(job, new Path(outputPathStr)); int reduceNum = conf.getInt(CommonConstant.REDUCE_NUM, 8); job.setNumReduceTasks(reduceNum); int isInputLZOCompress = conf.getInt(CommonConstant.IS_INPUTFORMATLZOCOMPRESS, 1); if (1 == isInputLZOCompress) { job.setInputFormatClass(com.hadoop.mapreduce.LzoTextInputFormat.class); } int result = job.waitForCompletion(true) ? 0 : 1; return result; } public static class AppPlayMapper extends Mapper<LongWritable, Text, Text, NullWritable> { private AbstractDMDAO<String, Integer> dmPlatRuleDAO = null; private AbstractDMDAO<Long, Map<ConstantEnum, String>> dmIPRuleDAO = null; private AbstractDMDAO<Integer, Integer> dmQuDaoRuleDAO = null; private MultipleOutputs<Text, NullWritable> multipleOutputs; @Override protected void setup(Context context) throws IOException, InterruptedException { super.setup(context); dmPlatRuleDAO = new DMPlatyRuleDAOImpl<String, Integer>(); dmPlatRuleDAO.parseDMObj(new File(ConstantEnum.DM_MOBILE_PLAT.name().toLowerCase())); dmIPRuleDAO = new DMIPRuleDAOImpl<Long, Map<ConstantEnum, String>>(); dmIPRuleDAO.parseDMObj(new File(ConstantEnum.IP_TABLE.name().toLowerCase())); dmQuDaoRuleDAO = new DMQuDaoRuleDAOImpl<Integer, Integer>(); dmQuDaoRuleDAO.parseDMObj(new File(ConstantEnum.DM_MOBILE_QUDAO.name().toLowerCase())); multipleOutputs = new MultipleOutputs<Text, NullWritable>(context); } public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { try { Map<String,String> map=new HashMap<>(); CoreLogFormatUtil.coverStringToMap(value.toString(), map,CommonConstant.FIELD_COMMA_SEPARATOR); String formatLogStr = formatLog(map); context.write(new Text(formatLogStr), NullWritable.get()); }catch(Exception e) { multipleOutputs.write(new Text(e.getMessage() + "\t" + value.toString()), NullWritable.get(), "_error/part"); return; } } @Override protected void cleanup(Context context) throws IOException, InterruptedException { multipleOutputs.close(); } public String formatLog(Map<String,String> map) throws Exception { try { //如果不包括媒体id或视频id的过滤 if(!map.containsKey(AppPlayEnum.VID.name().toLowerCase())&&!map.containsKey(AppPlayEnum.MID.name().toLowerCase())){ throw new Exception("Fields is not need"); } setDefaultFields(map); String timeStamp = map.get(AppPlayEnum.TIMESTAMP.name().toLowerCase()); Map<ConstantEnum, String> timeStampMap = TimeFormat.formatTimestamp2(timeStamp); String dateId = timeStampMap.get(ConstantEnum.DATE_ID); String hourId = timeStampMap.get(ConstantEnum.HOUR_ID); // ip_format, province_id, city_id, isp_id String ipFormat = FormatFunctionUtil.ipFormat(map.get("mr_ip")); long ipLong = FormatFunctionUtil.ip2long(ipFormat); Map<ConstantEnum, String> ipRuleMap = dmIPRuleDAO.getDMOjb(ipLong); String provinceId = ipRuleMap.get(ConstantEnum.PROVINCE_ID); String cityId = ipRuleMap.get(ConstantEnum.CITY_ID); String ispId = ipRuleMap.get(ConstantEnum.ISP_ID); // plat_id // platid,devinfo String platOrigin = ""; DevInfo devInfo = PlatFormatUtil.getDevInfoPrefix(map.get("dev")); if(map.containsKey("apptype")){ platOrigin=PlatFormatUtil.getFormatPlatTypePrefix(map.get("apptype")); } else { platOrigin = devInfo.getPlatType(); } int platId = 0; platId = dmPlatRuleDAO.getDMOjb(platOrigin); // versionId String versionOrigin = map.get(AppPlayEnum.VER.name().toLowerCase()); String versionFormat = FormatFunctionUtil.versionFormat(versionOrigin); long versionId = 0L; versionId = FormatFunctionUtil.version2long(versionFormat); // infohash String infohash = FormatFunctionUtil.InfohashFormat(map.get(AppPlayEnum.IH.name().toLowerCase())); // media_type_id, media_id, video_id int media_type_id = FormatFunctionUtil.getIntValueOfField(map.get(AppPlayEnum.VT.name().toLowerCase()), DefaultFieldValueEnum.mediaTypeIdDefault.getValueInt()); long video_id = FormatFunctionUtil.getLongValueOfField(map.get(AppPlayEnum.VID.name().toLowerCase()),DefaultFieldValueEnum.mediaIdDefault.getValueInt()); long media_id = FormatFunctionUtil.getLongValueOfField(map.get(AppPlayEnum.MID.name().toLowerCase()),DefaultFieldValueEnum.mediaIdDefault.getValueInt()); if(media_type_id != 1 && media_type_id != 2){ media_type_id = -999; } if(media_type_id == -999){ if(media_id != DefaultFieldValueEnum.mediaIdDefault.getValueInt()){ media_type_id = Integer.parseInt(CommonConstant.LONG_VIDEO_FLAG); }else if(video_id != DefaultFieldValueEnum.mediaIdDefault.getValueInt()){ media_type_id = Integer.parseInt(CommonConstant.SMALL_VIDEO_FLAG); } } // netTypeId int netTypeId = FormatFunctionUtil.getIntValueOfField(map.get(AppPlayEnum.NT.name().toLowerCase()), DefaultFieldValueEnum.netTypeDefault.getValueInt()); if (netTypeId > 3 || netTypeId < -1) netTypeId = DefaultFieldValueEnum.netTypeDefault.getValueInt(); // qudaoId int qudaoId = FormatFunctionUtil.getIntValueOfField(map.get(AppPlayEnum.SID.name().toLowerCase()), DefaultFieldValueEnum.qudaoIdDefault.getValueInt()); if(qudaoId==0){ qudaoId=1; } //qudaoId = dmQuDaoRuleDAO.getDMOjb(qudaoId); // mac String mac = FormatFunctionUtil.macFormat(map.get(AppPlayEnum.MAC.name().toLowerCase())); // fudid String fudid = FormatFunctionUtil.fudidFormat(map.get(AppPlayEnum.FUDID.name().toLowerCase())); //根据fudid计算hash值 int hash=CoreLogFormatUtil.hashFudid(mac); // action String action = map.get(AppPlayEnum.ACTION.name().toLowerCase()); int fr = FormatFunctionUtil.getIntValueOfField(map.get("fr"), -999); StringBuilder formatLog = new StringBuilder(); formatLog.append(dateId); formatLog.append(CommonConstant.FIELD_TAB_SEPARATOR); formatLog.append(hourId); formatLog.append(CommonConstant.FIELD_TAB_SEPARATOR); formatLog.append(provinceId); formatLog.append(CommonConstant.FIELD_TAB_SEPARATOR); formatLog.append(cityId); formatLog.append(CommonConstant.FIELD_TAB_SEPARATOR); formatLog.append(ispId); formatLog.append(CommonConstant.FIELD_TAB_SEPARATOR); formatLog.append(platId); formatLog.append(CommonConstant.FIELD_TAB_SEPARATOR); formatLog.append(qudaoId); formatLog.append(CommonConstant.FIELD_TAB_SEPARATOR); formatLog.append(versionId); formatLog.append(CommonConstant.FIELD_TAB_SEPARATOR); formatLog.append(mac); formatLog.append(CommonConstant.FIELD_TAB_SEPARATOR); formatLog.append(fudid); formatLog.append(CommonConstant.FIELD_TAB_SEPARATOR); formatLog.append(infohash); formatLog.append(CommonConstant.FIELD_TAB_SEPARATOR); formatLog.append(media_id); formatLog.append(CommonConstant.FIELD_TAB_SEPARATOR); formatLog.append(video_id); formatLog.append(CommonConstant.FIELD_TAB_SEPARATOR); formatLog.append(media_type_id); formatLog.append(CommonConstant.FIELD_TAB_SEPARATOR); formatLog.append(netTypeId); formatLog.append(CommonConstant.FIELD_TAB_SEPARATOR); formatLog.append(action); formatLog.append(CommonConstant.FIELD_TAB_SEPARATOR); formatLog.append(fr); formatLog.append(CommonConstant.FIELD_TAB_SEPARATOR); formatLog.append(hash); return formatLog.toString(); }catch(Exception e) { throw e; } } private void setDefaultFields(Map<String,String> map) { String timestamp=AppPlayEnum.TIMESTAMP.name().toLowerCase(); if(!map.containsKey(timestamp)){ map.put(timestamp, DefaultFieldValueEnum.timeStampDefault.getValueStr()); } if(!map.containsKey("mr_ip")){ map.put("mr_ip", DefaultFieldValueEnum.IPDefault.getValueStr()); } String dev=AppPlayEnum.DEV.name().toLowerCase(); if(!map.containsKey(dev)){ map.put(dev, "other"); } String mac=AppPlayEnum.MAC.name().toLowerCase(); if(!map.containsKey(mac)){ map.put(mac, DefaultFieldValueEnum.macCodeDefault.getValueStr()); } String ver=AppPlayEnum.VER.name().toLowerCase(); if(!map.containsKey(ver)){ map.put(ver, DefaultFieldValueEnum.versionIdDefault.getValueStr()); } String nt=AppPlayEnum.NT.name().toLowerCase(); if(!map.containsKey(nt)){ map.put(nt, DefaultFieldValueEnum.netTypeDefault.getValueStr()); } String ih=AppPlayEnum.IH.name().toLowerCase(); if(!map.containsKey(ih)){ map.put(ih, "-999"); } String action=AppPlayEnum.ACTION.name().toLowerCase(); if(!map.containsKey(action)){ map.put(action, "0"); } String mid=AppPlayEnum.MID.name().toLowerCase(); if(!map.containsKey(mid)){ map.put(mid, DefaultFieldValueEnum.mediaIdDefault.getValueStr()); } String vt=AppPlayEnum.VT.name().toLowerCase(); if(!map.containsKey(vt)){ map.put(vt, "-999"); } String sid=AppPlayEnum.SID.name().toLowerCase(); if(!map.containsKey(sid)){ map.put(sid, "0"); } String rt=AppPlayEnum.NT.name().toLowerCase(); if(!map.containsKey(rt)){ map.put(rt, "0"); } String vid=AppPlayEnum.VID.name().toLowerCase(); if(!map.containsKey(vid)){ map.put(vid, "-999"); } String eid=AppPlayEnum.EID.name().toLowerCase(); if(!map.containsKey(eid)){ map.put(eid, "-999"); } String fudid=AppPlayEnum.FUDID.name().toLowerCase(); if(!map.containsKey(fudid)){ map.put(fudid, DefaultFieldValueEnum.fudidDefault.getValueStr()); } //新增字段fr if(!map.containsKey("fr")){ map.put("fr", "-999"); } } } }
UTF-8
Java
15,044
java
AppPlayFormatMR.java
Java
[]
null
[]
package com.bi.corelog.format; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.MultipleOutputs; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import com.bi.corelog.util.CommonConstant; import com.bi.corelog.util.CoreLogFormatUtil; import com.bi.corelog.util.PlatFormatUtil; import com.funshion.dc.cloud.common.constant.DefaultFieldValueEnum; import com.funshion.dc.cloud.common.dao.AbstractDMDAO; import com.funshion.dc.cloud.common.dao.DMIPRuleDAOImpl; import com.funshion.dc.cloud.common.dao.DMPlatyRuleDAOImpl; import com.funshion.dc.cloud.common.dao.DMQuDaoRuleDAOImpl; import com.funshion.dc.cloud.common.enums.AppPlayEnum; import com.funshion.dc.cloud.common.enums.ConstantEnum; import com.funshion.dc.cloud.common.pojo.DevInfo; import com.funshion.dc.cloud.common.util.FormatFunctionUtil; import com.funshion.dc.cloud.common.util.TimeFormat; public class AppPlayFormatMR extends Configured implements Tool { public static void main(String[] args) throws Exception { int nRet = ToolRunner.run(new Configuration(), new AppPlayFormatMR(), args); System.out.println(nRet); } @Override public int run(String[] args) throws Exception { Configuration conf = getConf(); Job job = Job.getInstance(conf); job.setJarByClass(AppPlayFormatMR.class); String jobName = conf.get("jobName", "AppPlayFormat"); job.setJobName(jobName); job.setMapperClass(AppPlayMapper.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(NullWritable.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(NullWritable.class); String inputPathStr = conf.get(CommonConstant.INPUT_PATH); for (int i = 0; i < 24; i++) { if (i < 10) FileInputFormat.addInputPaths(job, inputPathStr + "/0" + i+"/"); else FileInputFormat.addInputPaths(job, inputPathStr +"/"+ i+"/"); } String outputPathStr = conf.get(CommonConstant.OUTPUT_PATH); FileOutputFormat.setOutputPath(job, new Path(outputPathStr)); int reduceNum = conf.getInt(CommonConstant.REDUCE_NUM, 8); job.setNumReduceTasks(reduceNum); int isInputLZOCompress = conf.getInt(CommonConstant.IS_INPUTFORMATLZOCOMPRESS, 1); if (1 == isInputLZOCompress) { job.setInputFormatClass(com.hadoop.mapreduce.LzoTextInputFormat.class); } int result = job.waitForCompletion(true) ? 0 : 1; return result; } public static class AppPlayMapper extends Mapper<LongWritable, Text, Text, NullWritable> { private AbstractDMDAO<String, Integer> dmPlatRuleDAO = null; private AbstractDMDAO<Long, Map<ConstantEnum, String>> dmIPRuleDAO = null; private AbstractDMDAO<Integer, Integer> dmQuDaoRuleDAO = null; private MultipleOutputs<Text, NullWritable> multipleOutputs; @Override protected void setup(Context context) throws IOException, InterruptedException { super.setup(context); dmPlatRuleDAO = new DMPlatyRuleDAOImpl<String, Integer>(); dmPlatRuleDAO.parseDMObj(new File(ConstantEnum.DM_MOBILE_PLAT.name().toLowerCase())); dmIPRuleDAO = new DMIPRuleDAOImpl<Long, Map<ConstantEnum, String>>(); dmIPRuleDAO.parseDMObj(new File(ConstantEnum.IP_TABLE.name().toLowerCase())); dmQuDaoRuleDAO = new DMQuDaoRuleDAOImpl<Integer, Integer>(); dmQuDaoRuleDAO.parseDMObj(new File(ConstantEnum.DM_MOBILE_QUDAO.name().toLowerCase())); multipleOutputs = new MultipleOutputs<Text, NullWritable>(context); } public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { try { Map<String,String> map=new HashMap<>(); CoreLogFormatUtil.coverStringToMap(value.toString(), map,CommonConstant.FIELD_COMMA_SEPARATOR); String formatLogStr = formatLog(map); context.write(new Text(formatLogStr), NullWritable.get()); }catch(Exception e) { multipleOutputs.write(new Text(e.getMessage() + "\t" + value.toString()), NullWritable.get(), "_error/part"); return; } } @Override protected void cleanup(Context context) throws IOException, InterruptedException { multipleOutputs.close(); } public String formatLog(Map<String,String> map) throws Exception { try { //如果不包括媒体id或视频id的过滤 if(!map.containsKey(AppPlayEnum.VID.name().toLowerCase())&&!map.containsKey(AppPlayEnum.MID.name().toLowerCase())){ throw new Exception("Fields is not need"); } setDefaultFields(map); String timeStamp = map.get(AppPlayEnum.TIMESTAMP.name().toLowerCase()); Map<ConstantEnum, String> timeStampMap = TimeFormat.formatTimestamp2(timeStamp); String dateId = timeStampMap.get(ConstantEnum.DATE_ID); String hourId = timeStampMap.get(ConstantEnum.HOUR_ID); // ip_format, province_id, city_id, isp_id String ipFormat = FormatFunctionUtil.ipFormat(map.get("mr_ip")); long ipLong = FormatFunctionUtil.ip2long(ipFormat); Map<ConstantEnum, String> ipRuleMap = dmIPRuleDAO.getDMOjb(ipLong); String provinceId = ipRuleMap.get(ConstantEnum.PROVINCE_ID); String cityId = ipRuleMap.get(ConstantEnum.CITY_ID); String ispId = ipRuleMap.get(ConstantEnum.ISP_ID); // plat_id // platid,devinfo String platOrigin = ""; DevInfo devInfo = PlatFormatUtil.getDevInfoPrefix(map.get("dev")); if(map.containsKey("apptype")){ platOrigin=PlatFormatUtil.getFormatPlatTypePrefix(map.get("apptype")); } else { platOrigin = devInfo.getPlatType(); } int platId = 0; platId = dmPlatRuleDAO.getDMOjb(platOrigin); // versionId String versionOrigin = map.get(AppPlayEnum.VER.name().toLowerCase()); String versionFormat = FormatFunctionUtil.versionFormat(versionOrigin); long versionId = 0L; versionId = FormatFunctionUtil.version2long(versionFormat); // infohash String infohash = FormatFunctionUtil.InfohashFormat(map.get(AppPlayEnum.IH.name().toLowerCase())); // media_type_id, media_id, video_id int media_type_id = FormatFunctionUtil.getIntValueOfField(map.get(AppPlayEnum.VT.name().toLowerCase()), DefaultFieldValueEnum.mediaTypeIdDefault.getValueInt()); long video_id = FormatFunctionUtil.getLongValueOfField(map.get(AppPlayEnum.VID.name().toLowerCase()),DefaultFieldValueEnum.mediaIdDefault.getValueInt()); long media_id = FormatFunctionUtil.getLongValueOfField(map.get(AppPlayEnum.MID.name().toLowerCase()),DefaultFieldValueEnum.mediaIdDefault.getValueInt()); if(media_type_id != 1 && media_type_id != 2){ media_type_id = -999; } if(media_type_id == -999){ if(media_id != DefaultFieldValueEnum.mediaIdDefault.getValueInt()){ media_type_id = Integer.parseInt(CommonConstant.LONG_VIDEO_FLAG); }else if(video_id != DefaultFieldValueEnum.mediaIdDefault.getValueInt()){ media_type_id = Integer.parseInt(CommonConstant.SMALL_VIDEO_FLAG); } } // netTypeId int netTypeId = FormatFunctionUtil.getIntValueOfField(map.get(AppPlayEnum.NT.name().toLowerCase()), DefaultFieldValueEnum.netTypeDefault.getValueInt()); if (netTypeId > 3 || netTypeId < -1) netTypeId = DefaultFieldValueEnum.netTypeDefault.getValueInt(); // qudaoId int qudaoId = FormatFunctionUtil.getIntValueOfField(map.get(AppPlayEnum.SID.name().toLowerCase()), DefaultFieldValueEnum.qudaoIdDefault.getValueInt()); if(qudaoId==0){ qudaoId=1; } //qudaoId = dmQuDaoRuleDAO.getDMOjb(qudaoId); // mac String mac = FormatFunctionUtil.macFormat(map.get(AppPlayEnum.MAC.name().toLowerCase())); // fudid String fudid = FormatFunctionUtil.fudidFormat(map.get(AppPlayEnum.FUDID.name().toLowerCase())); //根据fudid计算hash值 int hash=CoreLogFormatUtil.hashFudid(mac); // action String action = map.get(AppPlayEnum.ACTION.name().toLowerCase()); int fr = FormatFunctionUtil.getIntValueOfField(map.get("fr"), -999); StringBuilder formatLog = new StringBuilder(); formatLog.append(dateId); formatLog.append(CommonConstant.FIELD_TAB_SEPARATOR); formatLog.append(hourId); formatLog.append(CommonConstant.FIELD_TAB_SEPARATOR); formatLog.append(provinceId); formatLog.append(CommonConstant.FIELD_TAB_SEPARATOR); formatLog.append(cityId); formatLog.append(CommonConstant.FIELD_TAB_SEPARATOR); formatLog.append(ispId); formatLog.append(CommonConstant.FIELD_TAB_SEPARATOR); formatLog.append(platId); formatLog.append(CommonConstant.FIELD_TAB_SEPARATOR); formatLog.append(qudaoId); formatLog.append(CommonConstant.FIELD_TAB_SEPARATOR); formatLog.append(versionId); formatLog.append(CommonConstant.FIELD_TAB_SEPARATOR); formatLog.append(mac); formatLog.append(CommonConstant.FIELD_TAB_SEPARATOR); formatLog.append(fudid); formatLog.append(CommonConstant.FIELD_TAB_SEPARATOR); formatLog.append(infohash); formatLog.append(CommonConstant.FIELD_TAB_SEPARATOR); formatLog.append(media_id); formatLog.append(CommonConstant.FIELD_TAB_SEPARATOR); formatLog.append(video_id); formatLog.append(CommonConstant.FIELD_TAB_SEPARATOR); formatLog.append(media_type_id); formatLog.append(CommonConstant.FIELD_TAB_SEPARATOR); formatLog.append(netTypeId); formatLog.append(CommonConstant.FIELD_TAB_SEPARATOR); formatLog.append(action); formatLog.append(CommonConstant.FIELD_TAB_SEPARATOR); formatLog.append(fr); formatLog.append(CommonConstant.FIELD_TAB_SEPARATOR); formatLog.append(hash); return formatLog.toString(); }catch(Exception e) { throw e; } } private void setDefaultFields(Map<String,String> map) { String timestamp=AppPlayEnum.TIMESTAMP.name().toLowerCase(); if(!map.containsKey(timestamp)){ map.put(timestamp, DefaultFieldValueEnum.timeStampDefault.getValueStr()); } if(!map.containsKey("mr_ip")){ map.put("mr_ip", DefaultFieldValueEnum.IPDefault.getValueStr()); } String dev=AppPlayEnum.DEV.name().toLowerCase(); if(!map.containsKey(dev)){ map.put(dev, "other"); } String mac=AppPlayEnum.MAC.name().toLowerCase(); if(!map.containsKey(mac)){ map.put(mac, DefaultFieldValueEnum.macCodeDefault.getValueStr()); } String ver=AppPlayEnum.VER.name().toLowerCase(); if(!map.containsKey(ver)){ map.put(ver, DefaultFieldValueEnum.versionIdDefault.getValueStr()); } String nt=AppPlayEnum.NT.name().toLowerCase(); if(!map.containsKey(nt)){ map.put(nt, DefaultFieldValueEnum.netTypeDefault.getValueStr()); } String ih=AppPlayEnum.IH.name().toLowerCase(); if(!map.containsKey(ih)){ map.put(ih, "-999"); } String action=AppPlayEnum.ACTION.name().toLowerCase(); if(!map.containsKey(action)){ map.put(action, "0"); } String mid=AppPlayEnum.MID.name().toLowerCase(); if(!map.containsKey(mid)){ map.put(mid, DefaultFieldValueEnum.mediaIdDefault.getValueStr()); } String vt=AppPlayEnum.VT.name().toLowerCase(); if(!map.containsKey(vt)){ map.put(vt, "-999"); } String sid=AppPlayEnum.SID.name().toLowerCase(); if(!map.containsKey(sid)){ map.put(sid, "0"); } String rt=AppPlayEnum.NT.name().toLowerCase(); if(!map.containsKey(rt)){ map.put(rt, "0"); } String vid=AppPlayEnum.VID.name().toLowerCase(); if(!map.containsKey(vid)){ map.put(vid, "-999"); } String eid=AppPlayEnum.EID.name().toLowerCase(); if(!map.containsKey(eid)){ map.put(eid, "-999"); } String fudid=AppPlayEnum.FUDID.name().toLowerCase(); if(!map.containsKey(fudid)){ map.put(fudid, DefaultFieldValueEnum.fudidDefault.getValueStr()); } //新增字段fr if(!map.containsKey("fr")){ map.put("fr", "-999"); } } } }
15,044
0.5932
0.589933
335
42.776119
31.041533
176
false
false
0
0
0
0
0
0
1.158209
false
false
12
cd93ea32404db27c107d325bbc130be1c8c98b1d
9,543,417,386,905
7fe78eafa4058d46d57c0522289528052a021637
/src/main/java/kochme/visualsorting/ui/MainWindow.java
bc5b064507a9a291db2441d10d48578d0fd94731
[ "MIT", "CC-BY-3.0" ]
permissive
Maurice189/VisualSorting
https://github.com/Maurice189/VisualSorting
2ff776767c5a478ea31a00d5044ac0a19b761111
3f597dec8daadde1964cc9d56a51f32e32e6467d
refs/heads/master
2021-06-15T17:37:01.615000
2021-05-01T21:00:23
2021-05-01T21:00:23
19,375,322
1
1
MIT
false
2021-04-29T15:27:47
2014-05-02T12:56:37
2021-04-29T15:27:32
2021-04-29T15:27:30
14,763
0
0
1
Java
false
false
package kochme.visualsorting.ui; /* * This software is licensed under the MIT License. * Copyright 2018, Maurice Koch * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and * to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED * TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH * THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import java.awt.*; import java.awt.event.KeyEvent; import java.io.IOException; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.*; import java.util.List; import javax.swing.*; import javax.swing.border.Border; import javax.swing.border.CompoundBorder; import javax.swing.border.EmptyBorder; import kochme.visualsorting.app.Constants; import kochme.visualsorting.app.Constants.SortAlgorithm; import kochme.visualsorting.app.Controller; import kochme.visualsorting.app.Configuration; public class MainWindow extends JFrame { private static Font componentFont = new Font("Monospace", Font.BOLD, 13); private static Font infoFont = new Font("Monospace", Font.BOLD, 43); public enum State {EMPTY, RUNNING, PAUSED, STOPPED} private JLabel algorithmInfo; private final String title; private JButton addAlgorithmBtn; private JButton nextInstructionBtn; private JButton resetBtn; private JButton listOfElementsBtn; private PlayPauseToggle playPauseToggle; private JPanel panelContainer; private final Controller controller; private JLabel centeredInfoLabel, executionTimeLabel, numberOfElementsLabel; private JComboBox<SortAlgorithm> algorithmSelection; private SimpleDateFormat dataFormat = new SimpleDateFormat("mm:ss:SSS"); private List<FramedElementsCanvas> vsPanel; public MainWindow(Controller controller, String title, int width, int height) { this.title = title; this.controller = controller; initComponents(width, height); } private void initComponents(int width, int height) { JMenuBar menuBar; centeredInfoLabel = new JLabel("Add some sort algorithm", JLabel.CENTER); centeredInfoLabel.setFont(infoFont); centeredInfoLabel.setForeground(Color.GRAY); executionTimeLabel = new JLabel(); executionTimeLabel.setToolTipText("Execution time [min:sec:msec]."); executionTimeLabel.setForeground(Color.black); executionTimeLabel.setIcon(new ImageIcon(this.getClass().getResource("/icons/timer-small.png"))); JCheckBoxMenuItem switchIntPause = new JCheckBoxMenuItem("Automatic pause enabled"); switchIntPause.addActionListener(controller); switchIntPause.setActionCommand(Constants.AUTO_PAUSE); switchIntPause.setState(Configuration.isAutoPauseEnabled()); numberOfElementsLabel = new JLabel(); numberOfElementsLabel.setToolTipText("Number of elements in list."); numberOfElementsLabel.setForeground(Color.black); setTitle(title); setSize(width, height); vsPanel = new ArrayList<>(); addWindowListener(controller); JToolBar toolBar = new JToolBar(); toolBar.setFloatable(false); toolBar.setRollover(true); menuBar = new JMenuBar(); Border border = BorderFactory.createEtchedBorder(); Border margin = new EmptyBorder(5, 1, 10, 1); toolBar.setBorder(new CompoundBorder(border, margin)); JPanel bottomBar = new JPanel(); bottomBar.setLayout(new BoxLayout(bottomBar, BoxLayout.X_AXIS)); bottomBar.setBackground(bottomBar.getBackground().darker()); bottomBar.setBorder(BorderFactory.createEtchedBorder()); bottomBar.add(executionTimeLabel); bottomBar.add(Box.createHorizontalGlue()); bottomBar.add(numberOfElementsLabel); JMenu help = new JMenu("Help"); JMenuItem about = new JMenuItem("About " + title); about.addActionListener(controller); about.setActionCommand(Constants.ABOUT); help.add(about); menuBar.add(help); setJMenuBar(menuBar); algorithmInfo = new JLabel(); algorithmInfo.setForeground(Color.GRAY); algorithmSelection = new JComboBox<>(); algorithmSelection.addItemListener(itemEvent -> { SortAlgorithm algorithm = (SortAlgorithm) algorithmSelection.getSelectedItem(); if (algorithm == SortAlgorithm.Bubblesort) { algorithmInfo.setText("<html><b>Bubble sort</b> - Compare elements pairwise and perform swaps if necessary.</html>\""); } else if (algorithm == SortAlgorithm.Combsort) { algorithmInfo.setText("<html><b>Comb sort</b> - Improvement of bubble sort with dynamic gap sizes.</html>\""); } else if (algorithm == SortAlgorithm.Mergesort) { algorithmInfo.setText("<html><b>Merge sort</b> - Divide unsorted lists and repeatedly merge sorted sub-lists.</html>\""); } else if (algorithm == SortAlgorithm.Insertionsort) { algorithmInfo.setText("<html><b>Insertion sort</b> - In each iterations finds correct insert position of element</html>\""); } else if (algorithm == SortAlgorithm.Shakersort) { algorithmInfo.setText("<html><b>Shaker sort</b> - Bidirectional bubble sort, also known as cocktail sort.</html>\""); } else if (algorithm == SortAlgorithm.Selectionsort) { algorithmInfo.setText("<html><b>Selection sort</b> - Repeatedly finds the minimum element and append to sorted list.</html>\""); } else if (algorithm == SortAlgorithm.Shellsort) { algorithmInfo.setText("<html><b>Shell sort</b> - Generalization of insertion or bubble sort.</html>\""); } else if (algorithm == SortAlgorithm.Heapsort) { algorithmInfo.setText("<html><b>Heap sort</b> - Builds a heap and repeatedly extracts the current maximum.</html>\""); } else if (algorithm == SortAlgorithm.Quicksort_FIXED) { algorithmInfo.setText("<html><b>Quick sort</b> - Partitioning of lists by choosing a fixed pivot element.</html>\""); } else if (algorithm == SortAlgorithm.Quicksort_RANDOM) { algorithmInfo.setText("<html><b>Quick sort</b> - Partitioning of lists by choosing a random pivot element.</html>\""); } else if (algorithm == SortAlgorithm.Quicksort_MO3) { algorithmInfo.setText("<html><b>Quick sort</b> - Partitioning of lists by choosing a pivot element based on median of three.</html>\""); } else { algorithmInfo.setText("-"); } int prefWidth = algorithmInfo.getPreferredSize().width; algorithmInfo.setMaximumSize(new Dimension(prefWidth, 70)); }); Arrays.stream(SortAlgorithm.values()).forEach(algorithm -> algorithmSelection.addItem(algorithm)); algorithmSelection.setMaximumSize(new Dimension(300, 100)); panelContainer = new JPanel() { @Override protected void paintComponent(Graphics graphics) { super.paintComponent(graphics); Graphics2D g2d = (Graphics2D) graphics; g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); GradientPaint gp = new GradientPaint(0, 0, getBackground(), 0, getHeight(), getBackground().darker()); g2d.setPaint(gp); g2d.fillRect(0, 0, getWidth(), getHeight()); } }; panelContainer.setLayout(new BorderLayout()); playPauseToggle = new PlayPauseToggle(); playPauseToggle.setPlayIcon("/icons/start.png"); playPauseToggle.setPauseIcon("/icons/pause.png"); playPauseToggle.setState(PlayPauseToggle.State.PLAY); playPauseToggle.setToolTipText("Toggle start/pause execution"); playPauseToggle.addActionListener(controller); playPauseToggle.setActionCommand(Constants.START); addAlgorithmBtn = Utility.createButton("/icons/insert.png"); addAlgorithmBtn.setToolTipText("Add selected algorithm."); addAlgorithmBtn.addActionListener(controller); addAlgorithmBtn.setActionCommand(Constants.ADD_SORT); JButton adjustSpeedBtn = Utility.createButton("/icons/timer.png"); adjustSpeedBtn.setToolTipText("Adjust execution speed."); adjustSpeedBtn.addActionListener(controller); adjustSpeedBtn.setActionCommand(Constants.DELAY); listOfElementsBtn = Utility.createButton("/icons/bars.png"); listOfElementsBtn.setToolTipText("Set number of elements."); listOfElementsBtn.addActionListener(controller); listOfElementsBtn.setActionCommand(Constants.NEW_ELEMENTS); nextInstructionBtn = Utility.createButton("/icons/step.png"); nextInstructionBtn.setToolTipText("Step by step execution."); nextInstructionBtn.addActionListener(controller); nextInstructionBtn.setActionCommand(Constants.NEXT_ITERATION); resetBtn = Utility.createButton("/icons/stop.png"); resetBtn.setToolTipText("Reset to initial state."); resetBtn.addActionListener(controller); resetBtn.setActionCommand(Constants.RESET); panelContainer.add(BorderLayout.CENTER, centeredInfoLabel); JSeparator separator = new JSeparator(JSeparator.VERTICAL); Dimension size = new Dimension(separator.getPreferredSize().width, separator.getMaximumSize().height); separator.setMaximumSize(size); algorithmInfo.setToolTipText("Short description of currently selected algorithm."); algorithmInfo.setIcon(new ImageIcon(Constants.class.getResource("/icons/info.png"))); algorithmInfo.setIconTextGap(10); toolBar.add(Box.createHorizontalStrut(3)); toolBar.add(playPauseToggle); toolBar.add(Box.createHorizontalStrut(15)); toolBar.add(resetBtn); toolBar.add(Box.createHorizontalStrut(15)); toolBar.add(separator); toolBar.add(Box.createHorizontalStrut(15)); toolBar.add(nextInstructionBtn); toolBar.add(Box.createHorizontalStrut(15)); toolBar.add(adjustSpeedBtn); toolBar.add(Box.createHorizontalStrut(15)); toolBar.add(listOfElementsBtn); toolBar.add(Box.createHorizontalStrut(15)); toolBar.add(Box.createHorizontalGlue()); toolBar.add(algorithmInfo); toolBar.add(Box.createHorizontalGlue()); toolBar.add(Box.createHorizontalStrut(15)); toolBar.add(addAlgorithmBtn); toolBar.add(Box.createHorizontalStrut(5)); toolBar.add(algorithmSelection); toolBar.add(Box.createHorizontalStrut(3)); java.net.URL icon = MainWindow.class.getResource( "/icons/logo.png"); java.net.URL icon2x = MainWindow.class.getResource( "/icons/logo@2x.png"); java.net.URL icon3x = MainWindow.class.getResource( "/icons/logo@3x.png"); java.net.URL icon4x = MainWindow.class.getResource( "/icons/logo@4x.png"); java.net.URL icon5x = MainWindow.class.getResource( "/icons/logo@5x.png"); java.net.URL icon6x = MainWindow.class.getResource( "/icons/logo@6x.png"); List<Image> icons = new ArrayList<Image>(); icons.add(new ImageIcon(icon).getImage()); icons.add(new ImageIcon(icon2x).getImage()); icons.add(new ImageIcon(icon3x).getImage()); icons.add(new ImageIcon(icon4x).getImage()); icons.add(new ImageIcon(icon5x).getImage()); icons.add(new ImageIcon(icon6x).getImage()); setIconImages(icons); setLayout(new BoxLayout(this.getContentPane(), BoxLayout.Y_AXIS)); add(toolBar); add(panelContainer); add(bottomBar); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); setState(State.EMPTY); } public void setState(State state) { switch (state) { case EMPTY: resetBtn.setEnabled(false); playPauseToggle.setEnabled(false); nextInstructionBtn.setEnabled(false); addAlgorithmBtn.setEnabled(true); playPauseToggle.setState(PlayPauseToggle.State.PLAY); panelContainer.removeAll(); panelContainer.setLayout(new BorderLayout()); panelContainer.add(centeredInfoLabel); panelContainer.repaint(); revalidate(); repaint(); break; case RUNNING: resetBtn.setEnabled(true); playPauseToggle.setEnabled(true); nextInstructionBtn.setEnabled(false); addAlgorithmBtn.setEnabled(false); vsPanel.forEach(v -> v.enableRemoveButton(false)); playPauseToggle.setState(PlayPauseToggle.State.PAUSE); this.setTitle(title); break; case PAUSED: resetBtn.setEnabled(true); playPauseToggle.setEnabled(true); nextInstructionBtn.setEnabled(true); addAlgorithmBtn.setEnabled(false); vsPanel.forEach(v -> v.enableRemoveButton(false)); playPauseToggle.setState(PlayPauseToggle.State.PLAY); this.setTitle(title.concat(" - Paused")); break; case STOPPED: resetBtn.setEnabled(true); playPauseToggle.setEnabled(true); nextInstructionBtn.setEnabled(true); addAlgorithmBtn.setEnabled(true); vsPanel.forEach(v -> v.enableRemoveButton(true)); setExecutionTime(0); playPauseToggle.setState(PlayPauseToggle.State.PLAY); break; } } public void updateSize() { revalidate(); vsPanel.forEach(ElementsCanvas::updateSize); repaint(); } public void addSortVisualizationPanel(FramedElementsCanvas temp) { if (vsPanel.size() == 0) { panelContainer.remove(centeredInfoLabel); panelContainer.setLayout(new BoxLayout(panelContainer, BoxLayout.Y_AXIS)); panelContainer.add(Box.createVerticalStrut(20)); } vsPanel.add(temp); panelContainer.add(temp); revalidate(); } public void removeSortVisualizationPanel(FramedElementsCanvas temp) { if (!vsPanel.contains(temp) || !panelContainer.isAncestorOf(temp)) { throw new IllegalArgumentException("Variable 'temp' was never added"); } panelContainer.remove(temp); vsPanel.remove(temp); updateSize(); } public void updateNumberOfElements(int nof) { numberOfElementsLabel.setText(String.valueOf(nof).concat(" ").concat("number of elements")); } public void setExecutionTime(int milliSeconds) { executionTimeLabel.setText(dataFormat.format(new Date(milliSeconds))); } public SortAlgorithm getSelectedSort() { return (SortAlgorithm) algorithmSelection.getSelectedItem(); } public static void setComponentFont(String source) { try { InputStream in = MainWindow.class.getResourceAsStream(source); if (in != null) { componentFont = Font.createFont(Font.TRUETYPE_FONT, in); } } catch (IOException | FontFormatException e) { e.printStackTrace(); } } public static Font getComponentFont(float size) { return componentFont.deriveFont(size); } public static void setInfoFont(String source, float size) { try { InputStream in = MainWindow.class.getResourceAsStream(source); if (in != null) { infoFont = Font.createFont(Font.TRUETYPE_FONT, in); infoFont = infoFont.deriveFont(size); } } catch (IOException | FontFormatException e) { e.printStackTrace(); } } }
UTF-8
Java
17,108
java
MainWindow.java
Java
[ { "context": "licensed under the MIT License.\n * Copyright 2018, Maurice Koch\n *\n * Permission is hereby granted, free of charg", "end": 120, "score": 0.9998722076416016, "start": 108, "tag": "NAME", "value": "Maurice Koch" } ]
null
[]
package kochme.visualsorting.ui; /* * This software is licensed under the MIT License. * Copyright 2018, <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and * to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED * TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH * THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import java.awt.*; import java.awt.event.KeyEvent; import java.io.IOException; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.*; import java.util.List; import javax.swing.*; import javax.swing.border.Border; import javax.swing.border.CompoundBorder; import javax.swing.border.EmptyBorder; import kochme.visualsorting.app.Constants; import kochme.visualsorting.app.Constants.SortAlgorithm; import kochme.visualsorting.app.Controller; import kochme.visualsorting.app.Configuration; public class MainWindow extends JFrame { private static Font componentFont = new Font("Monospace", Font.BOLD, 13); private static Font infoFont = new Font("Monospace", Font.BOLD, 43); public enum State {EMPTY, RUNNING, PAUSED, STOPPED} private JLabel algorithmInfo; private final String title; private JButton addAlgorithmBtn; private JButton nextInstructionBtn; private JButton resetBtn; private JButton listOfElementsBtn; private PlayPauseToggle playPauseToggle; private JPanel panelContainer; private final Controller controller; private JLabel centeredInfoLabel, executionTimeLabel, numberOfElementsLabel; private JComboBox<SortAlgorithm> algorithmSelection; private SimpleDateFormat dataFormat = new SimpleDateFormat("mm:ss:SSS"); private List<FramedElementsCanvas> vsPanel; public MainWindow(Controller controller, String title, int width, int height) { this.title = title; this.controller = controller; initComponents(width, height); } private void initComponents(int width, int height) { JMenuBar menuBar; centeredInfoLabel = new JLabel("Add some sort algorithm", JLabel.CENTER); centeredInfoLabel.setFont(infoFont); centeredInfoLabel.setForeground(Color.GRAY); executionTimeLabel = new JLabel(); executionTimeLabel.setToolTipText("Execution time [min:sec:msec]."); executionTimeLabel.setForeground(Color.black); executionTimeLabel.setIcon(new ImageIcon(this.getClass().getResource("/icons/timer-small.png"))); JCheckBoxMenuItem switchIntPause = new JCheckBoxMenuItem("Automatic pause enabled"); switchIntPause.addActionListener(controller); switchIntPause.setActionCommand(Constants.AUTO_PAUSE); switchIntPause.setState(Configuration.isAutoPauseEnabled()); numberOfElementsLabel = new JLabel(); numberOfElementsLabel.setToolTipText("Number of elements in list."); numberOfElementsLabel.setForeground(Color.black); setTitle(title); setSize(width, height); vsPanel = new ArrayList<>(); addWindowListener(controller); JToolBar toolBar = new JToolBar(); toolBar.setFloatable(false); toolBar.setRollover(true); menuBar = new JMenuBar(); Border border = BorderFactory.createEtchedBorder(); Border margin = new EmptyBorder(5, 1, 10, 1); toolBar.setBorder(new CompoundBorder(border, margin)); JPanel bottomBar = new JPanel(); bottomBar.setLayout(new BoxLayout(bottomBar, BoxLayout.X_AXIS)); bottomBar.setBackground(bottomBar.getBackground().darker()); bottomBar.setBorder(BorderFactory.createEtchedBorder()); bottomBar.add(executionTimeLabel); bottomBar.add(Box.createHorizontalGlue()); bottomBar.add(numberOfElementsLabel); JMenu help = new JMenu("Help"); JMenuItem about = new JMenuItem("About " + title); about.addActionListener(controller); about.setActionCommand(Constants.ABOUT); help.add(about); menuBar.add(help); setJMenuBar(menuBar); algorithmInfo = new JLabel(); algorithmInfo.setForeground(Color.GRAY); algorithmSelection = new JComboBox<>(); algorithmSelection.addItemListener(itemEvent -> { SortAlgorithm algorithm = (SortAlgorithm) algorithmSelection.getSelectedItem(); if (algorithm == SortAlgorithm.Bubblesort) { algorithmInfo.setText("<html><b>Bubble sort</b> - Compare elements pairwise and perform swaps if necessary.</html>\""); } else if (algorithm == SortAlgorithm.Combsort) { algorithmInfo.setText("<html><b>Comb sort</b> - Improvement of bubble sort with dynamic gap sizes.</html>\""); } else if (algorithm == SortAlgorithm.Mergesort) { algorithmInfo.setText("<html><b>Merge sort</b> - Divide unsorted lists and repeatedly merge sorted sub-lists.</html>\""); } else if (algorithm == SortAlgorithm.Insertionsort) { algorithmInfo.setText("<html><b>Insertion sort</b> - In each iterations finds correct insert position of element</html>\""); } else if (algorithm == SortAlgorithm.Shakersort) { algorithmInfo.setText("<html><b>Shaker sort</b> - Bidirectional bubble sort, also known as cocktail sort.</html>\""); } else if (algorithm == SortAlgorithm.Selectionsort) { algorithmInfo.setText("<html><b>Selection sort</b> - Repeatedly finds the minimum element and append to sorted list.</html>\""); } else if (algorithm == SortAlgorithm.Shellsort) { algorithmInfo.setText("<html><b>Shell sort</b> - Generalization of insertion or bubble sort.</html>\""); } else if (algorithm == SortAlgorithm.Heapsort) { algorithmInfo.setText("<html><b>Heap sort</b> - Builds a heap and repeatedly extracts the current maximum.</html>\""); } else if (algorithm == SortAlgorithm.Quicksort_FIXED) { algorithmInfo.setText("<html><b>Quick sort</b> - Partitioning of lists by choosing a fixed pivot element.</html>\""); } else if (algorithm == SortAlgorithm.Quicksort_RANDOM) { algorithmInfo.setText("<html><b>Quick sort</b> - Partitioning of lists by choosing a random pivot element.</html>\""); } else if (algorithm == SortAlgorithm.Quicksort_MO3) { algorithmInfo.setText("<html><b>Quick sort</b> - Partitioning of lists by choosing a pivot element based on median of three.</html>\""); } else { algorithmInfo.setText("-"); } int prefWidth = algorithmInfo.getPreferredSize().width; algorithmInfo.setMaximumSize(new Dimension(prefWidth, 70)); }); Arrays.stream(SortAlgorithm.values()).forEach(algorithm -> algorithmSelection.addItem(algorithm)); algorithmSelection.setMaximumSize(new Dimension(300, 100)); panelContainer = new JPanel() { @Override protected void paintComponent(Graphics graphics) { super.paintComponent(graphics); Graphics2D g2d = (Graphics2D) graphics; g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); GradientPaint gp = new GradientPaint(0, 0, getBackground(), 0, getHeight(), getBackground().darker()); g2d.setPaint(gp); g2d.fillRect(0, 0, getWidth(), getHeight()); } }; panelContainer.setLayout(new BorderLayout()); playPauseToggle = new PlayPauseToggle(); playPauseToggle.setPlayIcon("/icons/start.png"); playPauseToggle.setPauseIcon("/icons/pause.png"); playPauseToggle.setState(PlayPauseToggle.State.PLAY); playPauseToggle.setToolTipText("Toggle start/pause execution"); playPauseToggle.addActionListener(controller); playPauseToggle.setActionCommand(Constants.START); addAlgorithmBtn = Utility.createButton("/icons/insert.png"); addAlgorithmBtn.setToolTipText("Add selected algorithm."); addAlgorithmBtn.addActionListener(controller); addAlgorithmBtn.setActionCommand(Constants.ADD_SORT); JButton adjustSpeedBtn = Utility.createButton("/icons/timer.png"); adjustSpeedBtn.setToolTipText("Adjust execution speed."); adjustSpeedBtn.addActionListener(controller); adjustSpeedBtn.setActionCommand(Constants.DELAY); listOfElementsBtn = Utility.createButton("/icons/bars.png"); listOfElementsBtn.setToolTipText("Set number of elements."); listOfElementsBtn.addActionListener(controller); listOfElementsBtn.setActionCommand(Constants.NEW_ELEMENTS); nextInstructionBtn = Utility.createButton("/icons/step.png"); nextInstructionBtn.setToolTipText("Step by step execution."); nextInstructionBtn.addActionListener(controller); nextInstructionBtn.setActionCommand(Constants.NEXT_ITERATION); resetBtn = Utility.createButton("/icons/stop.png"); resetBtn.setToolTipText("Reset to initial state."); resetBtn.addActionListener(controller); resetBtn.setActionCommand(Constants.RESET); panelContainer.add(BorderLayout.CENTER, centeredInfoLabel); JSeparator separator = new JSeparator(JSeparator.VERTICAL); Dimension size = new Dimension(separator.getPreferredSize().width, separator.getMaximumSize().height); separator.setMaximumSize(size); algorithmInfo.setToolTipText("Short description of currently selected algorithm."); algorithmInfo.setIcon(new ImageIcon(Constants.class.getResource("/icons/info.png"))); algorithmInfo.setIconTextGap(10); toolBar.add(Box.createHorizontalStrut(3)); toolBar.add(playPauseToggle); toolBar.add(Box.createHorizontalStrut(15)); toolBar.add(resetBtn); toolBar.add(Box.createHorizontalStrut(15)); toolBar.add(separator); toolBar.add(Box.createHorizontalStrut(15)); toolBar.add(nextInstructionBtn); toolBar.add(Box.createHorizontalStrut(15)); toolBar.add(adjustSpeedBtn); toolBar.add(Box.createHorizontalStrut(15)); toolBar.add(listOfElementsBtn); toolBar.add(Box.createHorizontalStrut(15)); toolBar.add(Box.createHorizontalGlue()); toolBar.add(algorithmInfo); toolBar.add(Box.createHorizontalGlue()); toolBar.add(Box.createHorizontalStrut(15)); toolBar.add(addAlgorithmBtn); toolBar.add(Box.createHorizontalStrut(5)); toolBar.add(algorithmSelection); toolBar.add(Box.createHorizontalStrut(3)); java.net.URL icon = MainWindow.class.getResource( "/icons/logo.png"); java.net.URL icon2x = MainWindow.class.getResource( "/icons/logo@2x.png"); java.net.URL icon3x = MainWindow.class.getResource( "/icons/logo@3x.png"); java.net.URL icon4x = MainWindow.class.getResource( "/icons/logo@4x.png"); java.net.URL icon5x = MainWindow.class.getResource( "/icons/logo@5x.png"); java.net.URL icon6x = MainWindow.class.getResource( "/icons/logo@6x.png"); List<Image> icons = new ArrayList<Image>(); icons.add(new ImageIcon(icon).getImage()); icons.add(new ImageIcon(icon2x).getImage()); icons.add(new ImageIcon(icon3x).getImage()); icons.add(new ImageIcon(icon4x).getImage()); icons.add(new ImageIcon(icon5x).getImage()); icons.add(new ImageIcon(icon6x).getImage()); setIconImages(icons); setLayout(new BoxLayout(this.getContentPane(), BoxLayout.Y_AXIS)); add(toolBar); add(panelContainer); add(bottomBar); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); setState(State.EMPTY); } public void setState(State state) { switch (state) { case EMPTY: resetBtn.setEnabled(false); playPauseToggle.setEnabled(false); nextInstructionBtn.setEnabled(false); addAlgorithmBtn.setEnabled(true); playPauseToggle.setState(PlayPauseToggle.State.PLAY); panelContainer.removeAll(); panelContainer.setLayout(new BorderLayout()); panelContainer.add(centeredInfoLabel); panelContainer.repaint(); revalidate(); repaint(); break; case RUNNING: resetBtn.setEnabled(true); playPauseToggle.setEnabled(true); nextInstructionBtn.setEnabled(false); addAlgorithmBtn.setEnabled(false); vsPanel.forEach(v -> v.enableRemoveButton(false)); playPauseToggle.setState(PlayPauseToggle.State.PAUSE); this.setTitle(title); break; case PAUSED: resetBtn.setEnabled(true); playPauseToggle.setEnabled(true); nextInstructionBtn.setEnabled(true); addAlgorithmBtn.setEnabled(false); vsPanel.forEach(v -> v.enableRemoveButton(false)); playPauseToggle.setState(PlayPauseToggle.State.PLAY); this.setTitle(title.concat(" - Paused")); break; case STOPPED: resetBtn.setEnabled(true); playPauseToggle.setEnabled(true); nextInstructionBtn.setEnabled(true); addAlgorithmBtn.setEnabled(true); vsPanel.forEach(v -> v.enableRemoveButton(true)); setExecutionTime(0); playPauseToggle.setState(PlayPauseToggle.State.PLAY); break; } } public void updateSize() { revalidate(); vsPanel.forEach(ElementsCanvas::updateSize); repaint(); } public void addSortVisualizationPanel(FramedElementsCanvas temp) { if (vsPanel.size() == 0) { panelContainer.remove(centeredInfoLabel); panelContainer.setLayout(new BoxLayout(panelContainer, BoxLayout.Y_AXIS)); panelContainer.add(Box.createVerticalStrut(20)); } vsPanel.add(temp); panelContainer.add(temp); revalidate(); } public void removeSortVisualizationPanel(FramedElementsCanvas temp) { if (!vsPanel.contains(temp) || !panelContainer.isAncestorOf(temp)) { throw new IllegalArgumentException("Variable 'temp' was never added"); } panelContainer.remove(temp); vsPanel.remove(temp); updateSize(); } public void updateNumberOfElements(int nof) { numberOfElementsLabel.setText(String.valueOf(nof).concat(" ").concat("number of elements")); } public void setExecutionTime(int milliSeconds) { executionTimeLabel.setText(dataFormat.format(new Date(milliSeconds))); } public SortAlgorithm getSelectedSort() { return (SortAlgorithm) algorithmSelection.getSelectedItem(); } public static void setComponentFont(String source) { try { InputStream in = MainWindow.class.getResourceAsStream(source); if (in != null) { componentFont = Font.createFont(Font.TRUETYPE_FONT, in); } } catch (IOException | FontFormatException e) { e.printStackTrace(); } } public static Font getComponentFont(float size) { return componentFont.deriveFont(size); } public static void setInfoFont(String source, float size) { try { InputStream in = MainWindow.class.getResourceAsStream(source); if (in != null) { infoFont = Font.createFont(Font.TRUETYPE_FONT, in); infoFont = infoFont.deriveFont(size); } } catch (IOException | FontFormatException e) { e.printStackTrace(); } } }
17,102
0.656476
0.652326
388
43.092785
31.011747
152
false
false
0
0
0
0
0
0
0.791237
false
false
12
1cb73ea1fd2f4190659c57c02aa54b1e8cee4a4a
9,637,906,665,279
6d3f7e1b367beb66573d646cbdf1c3dfc6dd8540
/mall-order/mall-order-service/src/main/java/com/mall/order/sender/MiaoshaMsg.java
44ade03f79f382b2e72ba4ee2be9e00636572e8d
[]
no_license
luolili/mall-demo
https://github.com/luolili/mall-demo
8e33caf77d711ee89ae6aedaf2039c4ba8db9dae
3497123df4bda2b790d1b51065167049a03fd186
refs/heads/master
2022-12-24T13:00:06.317000
2020-03-23T04:52:13
2020-03-23T04:52:13
202,844,647
0
0
null
false
2022-12-15T23:29:02
2019-08-17T06:28:35
2020-03-23T04:59:07
2022-12-15T23:28:59
202
0
0
11
Java
false
false
package com.mall.order.sender; import lombok.Data; @Data public class MiaoshaMsg { private Long userId; private Long goodsId; private Integer buyNum; }
UTF-8
Java
167
java
MiaoshaMsg.java
Java
[]
null
[]
package com.mall.order.sender; import lombok.Data; @Data public class MiaoshaMsg { private Long userId; private Long goodsId; private Integer buyNum; }
167
0.724551
0.724551
11
14.181818
12.171638
30
false
false
0
0
0
0
0
0
0.454545
false
false
12
2e829c84069b14d406364f78395b656160720431
30,039,001,269,880
84c459cc920e4036eb801737cae6d5ba64c29387
/src/ae/lesson/second/taxi/repository/ArrayRepositoryInterface.java
5de48981de970633367ef598a13fcdd230166265
[]
no_license
Lastenlol/java-tasks
https://github.com/Lastenlol/java-tasks
7ba2e7601515778e443d47838e26b5ec8e464b6c
f95e1960ff0d8668cc48191b6bc2e1101ffc88b6
refs/heads/master
2021-08-29T22:48:04.930000
2017-12-15T06:28:47
2017-12-15T06:28:47
112,868,671
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ae.lesson.second.taxi.repository; import java.util.Collection; import java.util.Comparator; import java.util.function.Predicate; public interface ArrayRepositoryInterface<Entity> extends RepositoryInterface<Entity> { Collection<Entity> findAll(Criteria<Entity> criteria); Entity findOne(Criteria<Entity> criteria); }
UTF-8
Java
338
java
ArrayRepositoryInterface.java
Java
[]
null
[]
package ae.lesson.second.taxi.repository; import java.util.Collection; import java.util.Comparator; import java.util.function.Predicate; public interface ArrayRepositoryInterface<Entity> extends RepositoryInterface<Entity> { Collection<Entity> findAll(Criteria<Entity> criteria); Entity findOne(Criteria<Entity> criteria); }
338
0.801775
0.801775
13
25
26.990026
87
false
false
0
0
0
0
0
0
0.461538
false
false
12