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
c07dc3f20be1aa3fc6a2e520df49d627928744af
18,013,092,839,733
f038ed38f368ba30cd2882f6142f0ab036682d7e
/src/main/java/ServerSide/Databases/DataTables/Produkt.java
ab220dc58982117d016c2c530c640dad98e0091b
[]
no_license
F0urth/Client-server_app
https://github.com/F0urth/Client-server_app
c010660dc5bb0b27a69b767e512823a2b8782dae
9a80f660cb165515766c150efe9f6264c85fff96
refs/heads/master
2022-07-11T01:15:12.082000
2019-10-22T18:50:31
2019-10-22T18:50:31
189,113,787
0
0
null
false
2020-07-01T23:15:19
2019-05-28T22:49:42
2019-10-22T18:51:08
2020-07-01T23:15:18
54
0
0
1
Java
false
false
package ServerSide.Databases.DataTables; /** * @author F0urth */ public class Produkt { private Integer idProdukt; private String nazwa; public Integer getIdProdukt() { return this.idProdukt; } public String getNazwa() { return this.nazwa; } public void setIdProdukt(Integer idProdukt) { this.idProdukt = idProdukt; } public void setNazwa(String nazwa) { this.nazwa = nazwa; } }
UTF-8
Java
460
java
Produkt.java
Java
[ { "context": "e ServerSide.Databases.DataTables;\n\n/**\n * @author F0urth\n */\n\npublic class Produkt {\n\n private Integer ", "end": 63, "score": 0.9174004197120667, "start": 57, "tag": "USERNAME", "value": "F0urth" } ]
null
[]
package ServerSide.Databases.DataTables; /** * @author F0urth */ public class Produkt { private Integer idProdukt; private String nazwa; public Integer getIdProdukt() { return this.idProdukt; } public String getNazwa() { return this.nazwa; } public void setIdProdukt(Integer idProdukt) { this.idProdukt = idProdukt; } public void setNazwa(String nazwa) { this.nazwa = nazwa; } }
460
0.628261
0.626087
27
16.037037
15.78673
49
false
false
0
0
0
0
0
0
0.259259
false
false
4
0fa05b42e85b1082c3eec9a51bb94f8e833d4b69
26,834,955,707,230
1e42cb17d6acd2e8a570397139abcc6d05ffa233
/GNode/bin/test/.svn/text-base/TestClient.java.svn-base
b92d100647b189143072e98a9e04ea8685be3d3b
[]
no_license
alexyzhou/gsystem
https://github.com/alexyzhou/gsystem
a1ae81a8d9b470ca696f85aec512ecafeba680b7
99309981fb999c9e91ecb55f30c033c66ca6890b
refs/heads/master
2016-09-06T11:30:40.382000
2014-06-12T09:16:49
2014-06-12T09:16:49
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package test; import java.io.IOException; import java.net.InetSocketAddress; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.ipc.RPC; import rpc.GMasterProtocol; import rpc.GServerProtocol; import system.SystemConf; public class TestClient { public static void main(String[] args) { // TODO Auto-generated method stub InetSocketAddress address = new InetSocketAddress("10.60.0.222",SystemConf.getInstance().RPC_GSERVER_PORT); try { GServerProtocol gMprotocol = (GServerProtocol) RPC.waitForProxy(GMasterProtocol.class, 1, address, new Configuration()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
UTF-8
Java
693
TestClient.java.svn-base
Java
[ { "context": "netSocketAddress address = new InetSocketAddress(\"10.60.0.222\",SystemConf.getInstance().RPC_GSERVER_PORT);\n\t\ttr", "end": 412, "score": 0.9995691180229187, "start": 401, "tag": "IP_ADDRESS", "value": "10.60.0.222" } ]
null
[]
package test; import java.io.IOException; import java.net.InetSocketAddress; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.ipc.RPC; import rpc.GMasterProtocol; import rpc.GServerProtocol; import system.SystemConf; public class TestClient { public static void main(String[] args) { // TODO Auto-generated method stub InetSocketAddress address = new InetSocketAddress("10.60.0.222",SystemConf.getInstance().RPC_GSERVER_PORT); try { GServerProtocol gMprotocol = (GServerProtocol) RPC.waitForProxy(GMasterProtocol.class, 1, address, new Configuration()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
693
0.759019
0.746032
27
24.666666
29.839075
123
false
false
0
0
0
0
0
0
1.407407
false
false
4
1dff54ed8fbed688ee4cd2c05830d64403d3446b
24,550,033,109,411
2ee3dcbb27dd683b937dfef376627b3354f293e0
/College Management System/Hostel_details/hosteldetails.java
a343f68d05a8901a789824a61572088e451eba21
[]
no_license
ganpat-university/oop-project-submission-cba-19162102001
https://github.com/ganpat-university/oop-project-submission-cba-19162102001
e8ceaa3d6195e64540cd631fe85d49e9af2fa670
66884b5a4d704d8162115609ab5ebea7f1645cce
refs/heads/master
2021-07-20T20:38:09.642000
2021-07-02T02:36:21
2021-07-02T02:36:21
215,943,787
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.*; class hosteldetails { Scanner sc=new Scanner(System.in); int city; int a; int b; void heading() { System.out.println("\t\t\t\t\t\t\t**********Hostel Details**********"); System.out.println("\t\t\t\t\t\t\t* *"); System.out.println("\t\t\t\t\t\t\t* *"); System.out.println("\t\t\t\t\t\t\t* *"); System.out.println("\t\t\t\t\t\t\t**********************************"); } void info() { System.out.println("Hostel facility is available in.."); System.out.println("1) Ranip"); System.out.println("2) Gota"); System.out.println("At which place you are willing to avail the facitlity of Hostel"); city=sc.nextInt(); take(); } void take() { if(city==1) { ranip(); } else if(city==2) { gota(); } else { System.out.println("Please choose the correct option"); info(); } } void ranip() { System.out.println("You have selected Ranip"); System.out.println("Do you want AC or Non AC"); System.out.println("For AC press 1"); System.out.println("For Non AC press 2"); a=sc.nextInt(); showrout(); } void showrout() { if(a==1) { System.out.println("Rent=5000"); System.out.println("Maximum Sharing=4"); System.out.println("Food Facility=Available"); System.out.println("Laundry=extra charge(monthly=Rs.350)"); } else if(a==2) { System.out.println("Rent=4000"); System.out.println("Maximum Sharing=4"); System.out.println("Food Facility=Available"); System.out.println("Laundry=extra charge(monthly=Rs.350)"); } else { System.out.println("Please choose correct option"); ranip(); } } void gota() { System.out.println("You have selected Gota"); System.out.println("Do you want AC or Non AC"); System.out.println("For AC press 1"); System.out.println("For Non AC press 2"); b=sc.nextInt(); showgout(); } void showgout() { if(b==1) { System.out.println("Rent=5500"); System.out.println("Maximum Sharing=4"); System.out.println("Food Facility=Available"); System.out.println("Laundry=extra charge(monthly=Rs.350)"); } else if(b==2) { System.out.println("Rent=4500"); System.out.println("Maximum Sharing=4"); System.out.println("Food Facility=Available"); System.out.println("Laundry=extra charge(monthly=Rs.350)"); } else { System.out.println("Please choose correct option"); gota(); } } public static void main(String args[]) { hosteldetails hd=new hosteldetails(); hd.heading(); hd.info(); } }
UTF-8
Java
3,993
java
hosteldetails.java
Java
[ { "context": "ity is available in..\");\r\n\n\tSystem.out.println(\"1) Ranip\");\n\t\t\r\n\tSystem.out.println(\"2) Gota\");\n\t\t\r\n\tSyste", "end": 720, "score": 0.7044749855995178, "start": 715, "tag": "NAME", "value": "Ranip" }, { "context": "t.println(\"1) Ranip\");\n\t\t\r\n\tSystem.out.println(\"2) Gota\");\n\t\t\r\n\tSystem.out.println(\"At which place you ar", "end": 756, "score": 0.7063300609588623, "start": 752, "tag": "NAME", "value": "Gota" } ]
null
[]
import java.util.*; class hosteldetails { Scanner sc=new Scanner(System.in); int city; int a; int b; void heading() { System.out.println("\t\t\t\t\t\t\t**********Hostel Details**********"); System.out.println("\t\t\t\t\t\t\t* *"); System.out.println("\t\t\t\t\t\t\t* *"); System.out.println("\t\t\t\t\t\t\t* *"); System.out.println("\t\t\t\t\t\t\t**********************************"); } void info() { System.out.println("Hostel facility is available in.."); System.out.println("1) Ranip"); System.out.println("2) Gota"); System.out.println("At which place you are willing to avail the facitlity of Hostel"); city=sc.nextInt(); take(); } void take() { if(city==1) { ranip(); } else if(city==2) { gota(); } else { System.out.println("Please choose the correct option"); info(); } } void ranip() { System.out.println("You have selected Ranip"); System.out.println("Do you want AC or Non AC"); System.out.println("For AC press 1"); System.out.println("For Non AC press 2"); a=sc.nextInt(); showrout(); } void showrout() { if(a==1) { System.out.println("Rent=5000"); System.out.println("Maximum Sharing=4"); System.out.println("Food Facility=Available"); System.out.println("Laundry=extra charge(monthly=Rs.350)"); } else if(a==2) { System.out.println("Rent=4000"); System.out.println("Maximum Sharing=4"); System.out.println("Food Facility=Available"); System.out.println("Laundry=extra charge(monthly=Rs.350)"); } else { System.out.println("Please choose correct option"); ranip(); } } void gota() { System.out.println("You have selected Gota"); System.out.println("Do you want AC or Non AC"); System.out.println("For AC press 1"); System.out.println("For Non AC press 2"); b=sc.nextInt(); showgout(); } void showgout() { if(b==1) { System.out.println("Rent=5500"); System.out.println("Maximum Sharing=4"); System.out.println("Food Facility=Available"); System.out.println("Laundry=extra charge(monthly=Rs.350)"); } else if(b==2) { System.out.println("Rent=4500"); System.out.println("Maximum Sharing=4"); System.out.println("Food Facility=Available"); System.out.println("Laundry=extra charge(monthly=Rs.350)"); } else { System.out.println("Please choose correct option"); gota(); } } public static void main(String args[]) { hosteldetails hd=new hosteldetails(); hd.heading(); hd.info(); } }
3,993
0.390684
0.379664
215
17.069767
23.487547
87
false
false
0
0
0
0
0
0
1.432558
false
false
4
0e3e6454a9280ac1517c5ddc2309ee815e3ee601
9,285,719,307,348
c63595171aa5b8670d94b0e720247775e103705d
/src/org/yoqu/cms/core/model/User.java
7682f454824797709882f15993507705ecc4c894
[ "Apache-2.0" ]
permissive
FlyTeamLHHC/finalcms
https://github.com/FlyTeamLHHC/finalcms
ed4f0ab826a840108b24fa350587ef4ba1917788
d52d1fe21cc80d28d5d80b9ce4136f95b3bb3687
refs/heads/master
2020-12-26T03:10:27.816000
2016-04-21T08:17:43
2016-04-21T08:17:43
56,751,094
0
0
null
true
2016-04-21T07:15:12
2016-04-21T07:15:12
2016-04-21T07:15:00
2016-04-21T03:26:27
10,799
0
0
0
null
null
null
package org.yoqu.cms.core.model; import com.jfinal.plugin.activerecord.Db; import com.jfinal.plugin.activerecord.Page; import org.yoqu.cms.core.Constant.Constant; import org.yoqu.cms.core.Constant.SystemVariable; import org.yoqu.cms.core.model.base.BaseUser; import org.yoqu.cms.core.util.SqlHandle; import java.sql.SQLException; import java.util.List; /** * Generated by JFinal. */ @SuppressWarnings("serial") public class User extends BaseUser<User> { public static final User dao = new User(); public List<User> finduserByNamePasswordOrName(String... parameters){ if (parameters.length==2){ return find("select * from user where name=? and password=? and is_delete=0",parameters); } else if(parameters.length==1){ return find("select * from user where name=? and is_delete=0",parameters); }else if(parameters.length==0){ return find("select * from user where is_delete=0"); } else return null; } public Role getRole(){ return Role.dao.findById(getRid()); } public Page<User> findUserByPage(int pageNumber){ return paginate(pageNumber, Integer.parseInt(SystemVariable.get(Constant.PAGE_SIZE).trim()),"select *","from user where is_delete=0 order by createDate desc"); } public void softDelete(int uid) throws SQLException { SqlHandle sqlHandle=new SqlHandle(SqlHandle.OPERATES[3],"user"); sqlHandle.OPERATEFILED("id",uid); try { Db.queryNumber(sqlHandle.toString()); }catch (Exception ex){ throw new SQLException(ex.getMessage()); } } @Override public String toString() { return "ID:"+getId()+"Name: "+getName()+" Password: "+getPassword()+" createDate: "+getCreateDate()+" lastDate:"+getLastDate()+"role: "+getRole(); } }
UTF-8
Java
1,686
java
User.java
Java
[ { "context": "rn \"ID:\"+getId()+\"Name: \"+getName()+\" Password: \"+getPassword()+\" createDate: \"+getCreateDate()+\" lastDate:\"+ge", "end": 1599, "score": 0.9971604347229004, "start": 1588, "tag": "PASSWORD", "value": "getPassword" } ]
null
[]
package org.yoqu.cms.core.model; import com.jfinal.plugin.activerecord.Db; import com.jfinal.plugin.activerecord.Page; import org.yoqu.cms.core.Constant.Constant; import org.yoqu.cms.core.Constant.SystemVariable; import org.yoqu.cms.core.model.base.BaseUser; import org.yoqu.cms.core.util.SqlHandle; import java.sql.SQLException; import java.util.List; /** * Generated by JFinal. */ @SuppressWarnings("serial") public class User extends BaseUser<User> { public static final User dao = new User(); public List<User> finduserByNamePasswordOrName(String... parameters){ if (parameters.length==2){ return find("select * from user where name=? and password=? and is_delete=0",parameters); } else if(parameters.length==1){ return find("select * from user where name=? and is_delete=0",parameters); }else if(parameters.length==0){ return find("select * from user where is_delete=0"); } else return null; } public Role getRole(){ return Role.dao.findById(getRid()); } public Page<User> findUserByPage(int pageNumber){ return paginate(pageNumber, Integer.parseInt(SystemVariable.get(Constant.PAGE_SIZE).trim()),"select *","from user where is_delete=0 order by createDate desc"); } public void softDelete(int uid) throws SQLException { SqlHandle sqlHandle=new SqlHandle(SqlHandle.OPERATES[3],"user"); sqlHandle.OPERATEFILED("id",uid); try { Db.queryNumber(sqlHandle.toString()); }catch (Exception ex){ throw new SQLException(ex.getMessage()); } } @Override public String toString() { return "ID:"+getId()+"Name: "+getName()+" Password: "+<PASSWORD>()+" createDate: "+getCreateDate()+" lastDate:"+getLastDate()+"role: "+getRole(); } }
1,685
0.727165
0.72242
51
32.058823
33.546814
161
false
false
0
0
0
0
0
0
1.607843
false
false
4
70b25daea37e6c3ba27510a8fa9cbe1839ca2c34
2,001,454,788,806
41aa56badaaa815d63d73319c50a69503b7be3ba
/biz.api.impl/biz.lar/src/main/java/com/sdcloud/biz/lar/dao/SysConfigDao.java
8049bf803409fd749d9a0d55e295336fc9f35713
[]
no_license
tlz328522853/sound4.0
https://github.com/tlz328522853/sound4.0
86bf2b71deec9e7d39c1ac0a9595320b8b31804f
efbe77bd63c4f6464dae1de3df5b47c79cebd94e
refs/heads/master
2021-01-21T20:30:13.206000
2017-05-24T02:27:21
2017-05-24T02:27:21
92,244,724
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sdcloud.biz.lar.dao; import java.util.List; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import org.springframework.stereotype.Repository; import com.sdcloud.api.lar.entity.SysConfig; @Repository public interface SysConfigDao extends BaseDao<SysConfig> { @Select("select type,value " + "from lar_sys_config ") List<SysConfig> findList(); @Update("update lar_sys_config " + "set value=#{value} " + "where type=#{type} ") @Override int update(SysConfig t); }
UTF-8
Java
563
java
SysConfigDao.java
Java
[]
null
[]
package com.sdcloud.biz.lar.dao; import java.util.List; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import org.springframework.stereotype.Repository; import com.sdcloud.api.lar.entity.SysConfig; @Repository public interface SysConfigDao extends BaseDao<SysConfig> { @Select("select type,value " + "from lar_sys_config ") List<SysConfig> findList(); @Update("update lar_sys_config " + "set value=#{value} " + "where type=#{type} ") @Override int update(SysConfig t); }
563
0.703375
0.703375
25
20.52
18.227715
58
false
false
0
0
0
0
0
0
1
false
false
4
cb7375f66ed94df99882dda778260ce556585288
23,244,363,010,204
b338e52ebc10fd41c1dc6cf1fb2836add00d5d70
/OnlineBookStore/src/com/bookstore/bean/User.java
efaee90041fb78e10fc5d680b40a8af987f8010f
[]
no_license
648-mysuol/Online-BookStore
https://github.com/648-mysuol/Online-BookStore
c91ee506b56bfeda328a188359048c218a7bb1a9
f116c644de894053c76ff01ee30f9d139678a341
refs/heads/master
2023-03-18T06:35:51.830000
2018-10-10T13:29:51
2018-10-10T13:29:51
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bookstore.bean; /** * 储存用户信息 * @author Administrator * */ public class User { private String id; //用户ID (电话) private String username; //用户名 (姓名) private String PIN; //密码 private String sex; //性别 private String idcard; //身份证 public User(){ } public User(String id,String username,String PIN,String sex,String idcard) { super(); this.id = id; this.username = username; this.PIN = PIN; this.sex = sex; this.idcard = idcard; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPIN() { return PIN; } public void setPIN(String pIN) { PIN = pIN; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getIdcard() { return idcard; } public void setIdcard(String idcard) { this.idcard = idcard; } }
GB18030
Java
1,069
java
User.java
Java
[ { "context": "age com.bookstore.bean;\n\n/**\n * \t储存用户信息\n * @author Administrator\n *\n */\npublic class User {\n\tprivate String id;\t\t", "end": 68, "score": 0.8882634043693542, "start": 55, "tag": "USERNAME", "value": "Administrator" }, { "context": "id;\t\t\t\t//用户ID\t\t(电话)\n\tprivate String \tusername;\t\t//用户名\t\t(姓名)\n\tprivate String \tPIN;\t\t\t//密码\n\tprivate Strin", "end": 166, "score": 0.8849307894706726, "start": 163, "tag": "USERNAME", "value": "用户名" }, { "context": " {\n\t\tsuper();\n\t\tthis.id\t\t\t=\tid;\n\t\tthis.username\t=\tusername;\t\t\t\n\t\tthis.PIN\t\t=\tPIN;\n\t\tthis.sex\t\t=\tsex;\n\t\tthis.", "end": 423, "score": 0.9253584742546082, "start": 415, "tag": "USERNAME", "value": "username" }, { "context": "d = id;\n\t}\n\tpublic String getUsername() {\n\t\treturn username;\n\t}\n\tpublic void setUsername(String username) {\n\t", "end": 634, "score": 0.669127881526947, "start": 626, "tag": "USERNAME", "value": "username" }, { "context": "d setUsername(String username) {\n\t\tthis.username = username;\n\t}\n\tpublic String getPIN() {\n\t\treturn PIN;\n\t}\n\tp", "end": 709, "score": 0.9381265640258789, "start": 701, "tag": "USERNAME", "value": "username" } ]
null
[]
package com.bookstore.bean; /** * 储存用户信息 * @author Administrator * */ public class User { private String id; //用户ID (电话) private String username; //用户名 (姓名) private String PIN; //密码 private String sex; //性别 private String idcard; //身份证 public User(){ } public User(String id,String username,String PIN,String sex,String idcard) { super(); this.id = id; this.username = username; this.PIN = PIN; this.sex = sex; this.idcard = idcard; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPIN() { return PIN; } public void setPIN(String pIN) { PIN = pIN; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getIdcard() { return idcard; } public void setIdcard(String idcard) { this.idcard = idcard; } }
1,069
0.640976
0.640976
56
17.303572
15.106668
81
false
false
0
0
0
0
0
0
2.428571
false
false
4
1c01ddf47610edb9fef8bed9cca1beba42a4f2ae
20,667,382,690,417
2efc7cdc64ad6738006dc0b23ca6e0eb717e43f4
/src/main/java/other/TradingProjectTreeRenderer.java
28a33f51cbd9113f1b4ecea43534e1566714695a
[]
no_license
anhtienzz123/QuanLiXeMay
https://github.com/anhtienzz123/QuanLiXeMay
606ca38ae74aa627e03fd2e37c0b7b6bf93a7e35
5eac0e9a7d08391e521722dbfc887f4159b5c6e9
refs/heads/main
2023-02-10T22:02:47.219000
2021-01-07T17:44:47
2021-01-07T17:44:47
305,047,266
0
0
null
false
2020-10-24T08:43:36
2020-10-18T07:33:15
2020-10-24T08:20:44
2020-10-24T08:43:35
26
0
0
0
Java
false
false
package other; import javax.swing.*; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import java.awt.*; import java.util.function.Supplier; public class TradingProjectTreeRenderer extends DefaultTreeCellRenderer { /** * */ private static final long serialVersionUID = 1L; private static final String SPAN_FORMAT = "<span style='color:%s;'>%s</span>"; private Supplier<String> filterTextSupplier; public TradingProjectTreeRenderer(Supplier<String> filterTextSupplier) { this.filterTextSupplier = filterTextSupplier; } @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); DefaultMutableTreeNode node = (DefaultMutableTreeNode) value; Object userObject = node.getUserObject(); String text = String.format(SPAN_FORMAT, "rgb(0,0,0)", renderFilterMatch(node, userObject.toString())); this.setText("<html>" + text + "</html>"); return this; } private String renderFilterMatch(DefaultMutableTreeNode node, String text) { if (node.isRoot()) { return text; } String textToFilter = filterTextSupplier.get(); return TreeHtmlHighlighter.highlightText(text, textToFilter); } }
UTF-8
Java
1,348
java
TradingProjectTreeRenderer.java
Java
[]
null
[]
package other; import javax.swing.*; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import java.awt.*; import java.util.function.Supplier; public class TradingProjectTreeRenderer extends DefaultTreeCellRenderer { /** * */ private static final long serialVersionUID = 1L; private static final String SPAN_FORMAT = "<span style='color:%s;'>%s</span>"; private Supplier<String> filterTextSupplier; public TradingProjectTreeRenderer(Supplier<String> filterTextSupplier) { this.filterTextSupplier = filterTextSupplier; } @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); DefaultMutableTreeNode node = (DefaultMutableTreeNode) value; Object userObject = node.getUserObject(); String text = String.format(SPAN_FORMAT, "rgb(0,0,0)", renderFilterMatch(node, userObject.toString())); this.setText("<html>" + text + "</html>"); return this; } private String renderFilterMatch(DefaultMutableTreeNode node, String text) { if (node.isRoot()) { return text; } String textToFilter = filterTextSupplier.get(); return TreeHtmlHighlighter.highlightText(text, textToFilter); } }
1,348
0.76632
0.763353
39
33.589745
32.197083
117
false
false
0
0
0
0
0
0
2.051282
false
false
4
a7c7e75d34700cef1022863bbd3dc48ddb0ecbd6
7,370,163,892,159
c2e709c396875e9a64bd07dbcbd5eef32b1d035d
/design-patterns/src/main/java/com/wang/action/observer/Client.java
92d28a983d844c019c309da6c4845b67f4d22f92
[]
no_license
wzhongke/spring
https://github.com/wzhongke/spring
3dcbf9de0427c2817e0d1bc9d2845de4f07e6471
97caf707f8cc4c67f1654273a3ac5e8eb8dd9f4b
refs/heads/master
2022-07-09T06:22:47.111000
2020-01-30T10:20:46
2020-01-30T10:20:46
110,086,765
0
0
null
false
2022-06-21T01:43:16
2017-11-09T08:17:17
2020-01-30T10:20:57
2022-06-21T01:43:16
28,577
0
0
12
Java
false
false
package com.wang.action.observer; public class Client { public static void main(String [] args) throws InterruptedException { ClockTimer timer = new ClockTimer(); AnalogClock analogClock = new AnalogClock(timer); DigitalClock digitalClock = new DigitalClock(timer); while (true) { Thread.sleep(1000); timer.tick(); } } }
UTF-8
Java
341
java
Client.java
Java
[]
null
[]
package com.wang.action.observer; public class Client { public static void main(String [] args) throws InterruptedException { ClockTimer timer = new ClockTimer(); AnalogClock analogClock = new AnalogClock(timer); DigitalClock digitalClock = new DigitalClock(timer); while (true) { Thread.sleep(1000); timer.tick(); } } }
341
0.72434
0.71261
14
23.357143
21.979235
70
false
false
0
0
0
0
0
0
1.714286
false
false
4
3ae0a37844a4376e38f92605fe9699dc92d5062d
15,573,551,425,241
1b0f128403d42f39a54c7bd6a393935ac4a352b3
/src/test/java/com/ABS_Automation/ABS/StudentWorkflow.java
5c8c9e6834f3e9b1554e331a99542cfbf1249e2f
[]
no_license
TapanChoudhary/Test_Auto
https://github.com/TapanChoudhary/Test_Auto
28eee0d3413d044c34046b8daa989a2e239716a1
53782a3509c7559c76fe3c41cb6ae4093d7e0eea
refs/heads/master
2018-03-07T11:08:31.865000
2016-09-18T07:05:57
2016-09-18T07:05:57
61,396,065
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ABS_Automation.ABS; import java.util.concurrent.TimeUnit; import com.ABS_Automation.pages.base.BaseWebComponent; public class StudentWorkflow extends BaseWebComponent { // private String openCourse = ".dashboard_row:nth-child(2)> div:nth-child(3)> ul:nth-child(%)";//Stage private String openCourse = ".dashboard_row:nth-child(2)> div:nth-child(2)> ul:nth-child(%)";//QAD private String launchCoursecssID = ".gracePeriodBtn"; private String launchCourseID = "courseURL"; public static String stud_mtURL; public void launchCourseOnMT(){ BaseTestStepdefs.launch_sso(); BaseTestStepdefs.stud_ssoLogin(); if(BaseTestStepdefs.jcount!=1){ BaseTestStepdefs.join_course(); openCourse(); BaseTestStepdefs.navigateToLPN(); } else{ openCourse(); } } public void openCourse(){ waitTillTime(2000); for(int i=5; i<509; i++){ if(findElementByCssPath(openCourse+">li:nth-child(1)>span", Integer.toString(i)).getText().contains(BaseTestStepdefs.courseName)){ findElementByCssPath(openCourse+">li:nth-child(2)>a", Integer.toString(i)).click(); break; } i=i+2; } waitForElementToAppear(findElementByCssPath(launchCoursecssID)); stud_mtURL = findElementById(launchCourseID).getAttribute("Value"); driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); // if (BaseTestStepdefs.mtEnv.equals("qaf") || BaseTestStepdefs.env.equals("prod")){ // driver.get(stud_mtURL); // System.out.println("Student Launches: "+stud_mtURL); // } // if (BaseTestStepdefs.mtEnv.equals("qad")){ // driver.get(stud_mtURL.replaceAll("qaf.", BaseTestStepdefs.mtEnv+"-")); // System.out.println("Student Launches: "+stud_mtURL.replaceAll("qaf.", BaseTestStepdefs.mtEnv+"-")); // } if (BaseTestStepdefs.tier.equalsIgnoreCase("int")){ stud_mtURL = stud_mtURL.replaceAll("qad-ng", "mindtap-int"); driver.get(stud_mtURL); System.out.println("Student Launches: "+ stud_mtURL); } if (BaseTestStepdefs.tier.equalsIgnoreCase("qa")){ stud_mtURL = stud_mtURL.replaceAll("qad-ng", "mindtap-qa"); driver.get(stud_mtURL); System.out.println("Student Launches: "+ stud_mtURL); } else if (BaseTestStepdefs.env.equalsIgnoreCase("cloud")){ driver.get(stud_mtURL); System.out.println("Student Launches: "+ stud_mtURL); } } }
UTF-8
Java
2,317
java
StudentWorkflow.java
Java
[]
null
[]
package com.ABS_Automation.ABS; import java.util.concurrent.TimeUnit; import com.ABS_Automation.pages.base.BaseWebComponent; public class StudentWorkflow extends BaseWebComponent { // private String openCourse = ".dashboard_row:nth-child(2)> div:nth-child(3)> ul:nth-child(%)";//Stage private String openCourse = ".dashboard_row:nth-child(2)> div:nth-child(2)> ul:nth-child(%)";//QAD private String launchCoursecssID = ".gracePeriodBtn"; private String launchCourseID = "courseURL"; public static String stud_mtURL; public void launchCourseOnMT(){ BaseTestStepdefs.launch_sso(); BaseTestStepdefs.stud_ssoLogin(); if(BaseTestStepdefs.jcount!=1){ BaseTestStepdefs.join_course(); openCourse(); BaseTestStepdefs.navigateToLPN(); } else{ openCourse(); } } public void openCourse(){ waitTillTime(2000); for(int i=5; i<509; i++){ if(findElementByCssPath(openCourse+">li:nth-child(1)>span", Integer.toString(i)).getText().contains(BaseTestStepdefs.courseName)){ findElementByCssPath(openCourse+">li:nth-child(2)>a", Integer.toString(i)).click(); break; } i=i+2; } waitForElementToAppear(findElementByCssPath(launchCoursecssID)); stud_mtURL = findElementById(launchCourseID).getAttribute("Value"); driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); // if (BaseTestStepdefs.mtEnv.equals("qaf") || BaseTestStepdefs.env.equals("prod")){ // driver.get(stud_mtURL); // System.out.println("Student Launches: "+stud_mtURL); // } // if (BaseTestStepdefs.mtEnv.equals("qad")){ // driver.get(stud_mtURL.replaceAll("qaf.", BaseTestStepdefs.mtEnv+"-")); // System.out.println("Student Launches: "+stud_mtURL.replaceAll("qaf.", BaseTestStepdefs.mtEnv+"-")); // } if (BaseTestStepdefs.tier.equalsIgnoreCase("int")){ stud_mtURL = stud_mtURL.replaceAll("qad-ng", "mindtap-int"); driver.get(stud_mtURL); System.out.println("Student Launches: "+ stud_mtURL); } if (BaseTestStepdefs.tier.equalsIgnoreCase("qa")){ stud_mtURL = stud_mtURL.replaceAll("qad-ng", "mindtap-qa"); driver.get(stud_mtURL); System.out.println("Student Launches: "+ stud_mtURL); } else if (BaseTestStepdefs.env.equalsIgnoreCase("cloud")){ driver.get(stud_mtURL); System.out.println("Student Launches: "+ stud_mtURL); } } }
2,317
0.706085
0.698317
67
33.582088
31.395479
133
false
false
0
0
0
0
0
0
2.641791
false
false
4
217155a5a70fb0710503ecfa508328a4f1f6c30e
3,427,383,938,405
eb908b8a2ddfdb0574b6c55d067e4ff5d821114a
/app/src/main/java/com/example/instagram/SendingImage.java
ae3b958af15da4ab94e878f408248c03cd9caa0b
[]
no_license
Duong99/Instagram
https://github.com/Duong99/Instagram
7f40b970adb9fa510004536f80cb1b9a61aed8f6
ae30e2c2536025eaf1d2904e4a94c560ad6badd2
refs/heads/master
2022-07-13T18:42:03.082000
2020-05-08T10:26:06
2020-05-08T10:26:06
254,653,316
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.instagram; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.AsyncTask; import android.widget.Toast; import com.facebook.share.model.ShareLinkContent; import com.facebook.share.model.SharePhoto; import com.facebook.share.model.SharePhotoContent; import com.facebook.share.widget.ShareDialog; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; public class SendingImage { private Context context; private String urlPicture; public SendingImage(Context context, String urlPicture) { this.context = context; this.urlPicture = urlPicture; } public void sharingFacebook(){ if (ShareDialog.canShow(ShareLinkContent.class)) { ShareLinkContent linkContent = new ShareLinkContent.Builder() .setContentUrl(Uri.parse(urlPicture)) .build(); ShareDialog.show((Activity) context, linkContent); } } public void sendingApp(){ ArrayList<Uri> uris = new ArrayList<>(); uris.add(Uri.parse(String.valueOf(urlPicture))); Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE); shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris); shareIntent.setType("image/*"); context.startActivity(Intent.createChooser(shareIntent, "Share images to..")); } private class DownloadImgTask extends AsyncTask<String, Void, Bitmap>{ @Override protected Bitmap doInBackground(String... strings) { String url = strings[0]; Bitmap bitmap = null; try { InputStream inputStream = new URL(url).openStream(); bitmap = BitmapFactory.decodeStream(inputStream); } catch (IOException e) { e.printStackTrace(); } return bitmap; } @Override protected void onPostExecute(Bitmap bitmap) { sharePhoto(bitmap); } } private void sharePhoto(Bitmap bitmap){ SharePhoto photo = new SharePhoto.Builder() .setBitmap(bitmap).build(); SharePhotoContent content = new SharePhotoContent.Builder() .addPhoto(photo).build(); ShareDialog dialog = new ShareDialog((Activity) context); if (dialog.canShow(SharePhotoContent.class)){ dialog.show(content); }else { Toast.makeText(context, "You can't share photo :(", Toast.LENGTH_SHORT).show(); } } }
UTF-8
Java
2,754
java
SendingImage.java
Java
[]
null
[]
package com.example.instagram; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.AsyncTask; import android.widget.Toast; import com.facebook.share.model.ShareLinkContent; import com.facebook.share.model.SharePhoto; import com.facebook.share.model.SharePhotoContent; import com.facebook.share.widget.ShareDialog; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; public class SendingImage { private Context context; private String urlPicture; public SendingImage(Context context, String urlPicture) { this.context = context; this.urlPicture = urlPicture; } public void sharingFacebook(){ if (ShareDialog.canShow(ShareLinkContent.class)) { ShareLinkContent linkContent = new ShareLinkContent.Builder() .setContentUrl(Uri.parse(urlPicture)) .build(); ShareDialog.show((Activity) context, linkContent); } } public void sendingApp(){ ArrayList<Uri> uris = new ArrayList<>(); uris.add(Uri.parse(String.valueOf(urlPicture))); Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE); shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris); shareIntent.setType("image/*"); context.startActivity(Intent.createChooser(shareIntent, "Share images to..")); } private class DownloadImgTask extends AsyncTask<String, Void, Bitmap>{ @Override protected Bitmap doInBackground(String... strings) { String url = strings[0]; Bitmap bitmap = null; try { InputStream inputStream = new URL(url).openStream(); bitmap = BitmapFactory.decodeStream(inputStream); } catch (IOException e) { e.printStackTrace(); } return bitmap; } @Override protected void onPostExecute(Bitmap bitmap) { sharePhoto(bitmap); } } private void sharePhoto(Bitmap bitmap){ SharePhoto photo = new SharePhoto.Builder() .setBitmap(bitmap).build(); SharePhotoContent content = new SharePhotoContent.Builder() .addPhoto(photo).build(); ShareDialog dialog = new ShareDialog((Activity) context); if (dialog.canShow(SharePhotoContent.class)){ dialog.show(content); }else { Toast.makeText(context, "You can't share photo :(", Toast.LENGTH_SHORT).show(); } } }
2,754
0.648511
0.648148
88
30.295454
23.637489
91
false
false
0
0
0
0
0
0
0.568182
false
false
4
9b15c16d296a45c1ef453989e81ecab56a27e936
12,859,132,086,831
8336f5b8f1e73900ac897a20fbd06fa84ce31628
/src/main/java/com/nutanix/hack/seeksmart/model/Trending.java
8aacc988264cf14691186df612270b1c80a9ef5e
[]
no_license
hemant-ve/seek-smart
https://github.com/hemant-ve/seek-smart
e24e3acb42aa845b4eccf2f22efc9c9797365070
aad747e6d8925db6da217ddc85b81a2c64df827c
refs/heads/master
2022-03-03T07:54:57.801000
2020-02-14T04:30:00
2020-02-14T04:30:00
239,451,508
0
0
null
false
2022-02-26T01:09:15
2020-02-10T07:22:58
2020-02-14T04:30:12
2022-02-26T01:09:14
68
0
0
1
Java
false
false
package com.nutanix.hack.seeksmart.model; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; @Entity @Table(name = "trending") @Data @NoArgsConstructor @AllArgsConstructor @Builder public class Trending { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "trending_generator") @SequenceGenerator(name = "trending_generator", sequenceName = "trending_seq") @Column(name = "id", unique = true, nullable = false) private Long id; @Column(name = "post_id", nullable = false) private Long postId; @Column(name = "rank", nullable = false) private Double rank; @Column(name = "cycle_count", nullable = false) private Integer cycleCount; }
UTF-8
Java
791
java
Trending.java
Java
[]
null
[]
package com.nutanix.hack.seeksmart.model; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; @Entity @Table(name = "trending") @Data @NoArgsConstructor @AllArgsConstructor @Builder public class Trending { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "trending_generator") @SequenceGenerator(name = "trending_generator", sequenceName = "trending_seq") @Column(name = "id", unique = true, nullable = false) private Long id; @Column(name = "post_id", nullable = false) private Long postId; @Column(name = "rank", nullable = false) private Double rank; @Column(name = "cycle_count", nullable = false) private Integer cycleCount; }
791
0.716814
0.716814
31
24.516129
22.669962
89
false
false
0
0
0
0
0
0
0.548387
false
false
4
5c0ce9df699ee4f150f90d9840a0ae3958e4804e
6,305,012,024,370
e313adb66ee78e8d3daecdf4e78f7bbbd002fda2
/20171204Calculator/src/com/lab/Kalkulat.java
4b785ef8fc168013749520cdb3b874b08deb97cd
[]
no_license
dmlbr/test201903_calculator
https://github.com/dmlbr/test201903_calculator
466052722d799de92eb7baaca5e766ed00e72d7d
fb0c6203678ef5b0142caa6112ede07da39c60ce
refs/heads/master
2020-04-29T13:24:32.734000
2019-03-25T16:23:31
2019-03-25T16:23:31
176,168,115
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lab; public class Kalkulat { public static double summa (double a, double b) { return a + b; } public static double mnorzenie (double a, double b) { return a * b; } public static double minus (double a, double b) { return a - b; } public static double dzielienie (double a, double b) { return a / b; } public static double module (double a, double b) { return a % b; } }
UTF-8
Java
491
java
Kalkulat.java
Java
[]
null
[]
package com.lab; public class Kalkulat { public static double summa (double a, double b) { return a + b; } public static double mnorzenie (double a, double b) { return a * b; } public static double minus (double a, double b) { return a - b; } public static double dzielienie (double a, double b) { return a / b; } public static double module (double a, double b) { return a % b; } }
491
0.543788
0.543788
39
10.589744
16.908073
55
false
false
0
0
0
0
0
0
1.51282
false
false
4
d6acbf8433835248aec20b267beb945b9f395ae0
14,285,061,263,251
3abacf3576b7770febddaf95ffde768dc50e441f
/src/main/java/com/githup/liming495/constants/C.java
b71be34c8a7269f137c73209c15158801c8489c1
[]
no_license
liming495/tools
https://github.com/liming495/tools
212aa4e04ad1484243ade304ed2568683540d2b1
ac8b8402df8b38bef7a266e3c3dbc56f1eb610b0
refs/heads/master
2022-12-07T06:30:30.501000
2022-08-14T02:35:28
2022-08-14T02:35:28
188,763,973
2
0
null
false
2022-11-16T09:31:55
2019-05-27T03:20:33
2022-02-17T11:53:46
2022-11-16T09:31:52
131
1
0
1
Java
false
false
package com.githup.liming495.constants; /** * 常量 * * @author Guppy */ public class C { public static String STATUS_0 = "0"; //状态:0 public static String STATUS_1 = "1"; //状态:1 }
UTF-8
Java
219
java
C.java
Java
[ { "context": "liming495.constants;\r\n\r\n/**\r\n * 常量\r\n *\r\n * @author Guppy\r\n */\r\npublic class C {\r\n public static String ST", "end": 75, "score": 0.9590566158294678, "start": 70, "tag": "NAME", "value": "Guppy" } ]
null
[]
package com.githup.liming495.constants; /** * 常量 * * @author Guppy */ public class C { public static String STATUS_0 = "0"; //状态:0 public static String STATUS_1 = "1"; //状态:1 }
219
0.565217
0.521739
11
16.818182
18.996737
50
false
false
0
0
0
0
0
0
0.272727
false
false
4
4d24d14e2e64826b733ec1e0ce946a3a428db376
14,285,061,260,732
5883eb90ff0fe3b92b1a6ecebda2714e9b62eb35
/LMC/src/com/tcs/ilp/dao/TotalSalesDao.java
6392adb979bd71fe5a1bc0570414ef4d6394dacf
[]
no_license
pranitbose/REST_Demo
https://github.com/pranitbose/REST_Demo
122ce0bac788b67ada15345741fbf3dd860b290c
3ca075e45f37ef3e9ed9b7e70aed29e4cc97bfc4
refs/heads/master
2020-03-27T08:15:08.230000
2018-08-27T02:27:44
2018-08-27T02:27:44
146,236,622
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tcs.ilp.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import com.tcs.ilp.bean.TotalSalesAllRegion; import com.tcs.ilp.bean.TotalSalesBranchBased; import com.tcs.ilp.bean.TotalSalesRegionBased; import com.tcs.ilp.util.DbUtil; import com.tcs.ilp.util.Month; public class TotalSalesDao { public ArrayList<TotalSalesAllRegion> getTotalSalesByAllRegion(String month, String year) { Connection con = DbUtil.createConnection(); PreparedStatement ps = null; ResultSet rs = null; ArrayList<TotalSalesAllRegion> salesList = new ArrayList<TotalSalesAllRegion>(); TotalSalesAllRegion tsar; try { Month mon = Month.valueOf(month); String sql = "SELECT productCode, productName, SUM(quantity) AS salesQuantity, SUM(quantity * price) AS revenue FROM PRODUCTS_1418060 WHERE salesDate BETWEEN TO_DATE(?,'DD/MM/YYYY') AND TO_DATE(?,'DD/MM/YYYY') GROUP BY productName, productCode ORDER BY productCode"; ps = con.prepareStatement(sql); ps.setString(1, "01/"+mon.getMonth()+"/"+year); ps.setString(2, mon.getDays()+"/"+mon.getMonth()+"/"+year); rs = ps.executeQuery(); int slid = 1; while (rs.next()) { tsar = new TotalSalesAllRegion(slid, rs.getString("productCode"), rs.getString("productName"), rs.getInt("salesQuantity"), rs.getDouble("revenue")); salesList.add(tsar); slid++; } } catch(IllegalArgumentException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { DbUtil.closeResultSet(rs); DbUtil.closeStatement(ps); DbUtil.closeConnection(); } return salesList; } public ArrayList<TotalSalesBranchBased> getTotalSalesBranchBased(String prevMonth, String month, String year) { Connection con = DbUtil.createConnection(); PreparedStatement ps1 = null; PreparedStatement ps2 = null; ResultSet rs1 = null; ResultSet rs2 = null; ArrayList<TotalSalesBranchBased> salesList = new ArrayList<TotalSalesBranchBased>(); TotalSalesBranchBased tsbb; try { Month prevMon = Month.valueOf(prevMonth); Month mon = Month.valueOf(month); String sql1 = "SELECT SUBSTR(branchId, 4, 6) AS branch, SUM(quantity) AS salesQuantity, SUM(quantity * price) AS revenue FROM PRODUCTS_1418060 WHERE salesDate BETWEEN TO_DATE(?,'DD/MM/YYYY') AND TO_DATE(?,'DD/MM/YYYY') GROUP BY SUBSTR(branchId, 4, 6) ORDER BY SUBSTR(branchId, 4, 6)"; String sql2 = "SELECT SUBSTR(branchId, 4, 6) AS branch, SUM(quantity) AS salesQuantity, SUM(quantity * price) AS revenue FROM PRODUCTS_1418060 WHERE salesDate BETWEEN TO_DATE(?,'DD/MM/YYYY') AND TO_DATE(?,'DD/MM/YYYY') GROUP BY SUBSTR(branchId, 4, 6) ORDER BY SUBSTR(branchId, 4, 6)"; ps1 = con.prepareStatement(sql1); ps1.setString(1, "01/"+prevMon.getMonth()+"/"+year); ps1.setString(2, prevMon.getDays()+"/"+prevMon.getMonth()+"/"+year); ps2 = con.prepareStatement(sql2); ps2.setString(1, "01/"+mon.getMonth()+"/"+year); ps2.setString(2, mon.getDays()+"/"+mon.getMonth()+"/"+year); rs1 = ps1.executeQuery(); rs2 = ps2.executeQuery(); while (rs1.next() && rs2.next()) { double prevRev = rs1.getDouble(3); double rev = rs2.getDouble(3); double growth = ((rev - prevRev) / prevRev) * 100; tsbb = new TotalSalesBranchBased(rs2.getString(1), rs2.getInt(2), rs2.getDouble(3), growth); salesList.add(tsbb); } } catch(IllegalArgumentException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { DbUtil.closeResultSet(rs2); DbUtil.closeResultSet(rs1); DbUtil.closeStatement(ps2); DbUtil.closeStatement(ps1); DbUtil.closeConnection(); } return salesList; } public ArrayList<TotalSalesRegionBased> getTotalSalesRegionBased(String prevMonth, String month, String year) { Connection con = DbUtil.createConnection(); PreparedStatement ps1 = null; PreparedStatement ps2 = null; ResultSet rs1 = null; ResultSet rs2 = null; ArrayList<TotalSalesRegionBased> salesList = new ArrayList<TotalSalesRegionBased>(); TotalSalesRegionBased tsrb; try { Month prevMon = Month.valueOf(prevMonth); Month mon = Month.valueOf(month); String sql1 = "SELECT SUBSTR(branchId, 0, 3) AS region, SUM(quantity) AS salesQuantity, SUM(quantity * price) AS revenue FROM PRODUCTS_1418060 WHERE salesDate BETWEEN TO_DATE(?,'DD/MM/YYYY') AND TO_DATE(?,'DD/MM/YYYY') GROUP BY SUBSTR(branchId, 0, 3) ORDER BY SUBSTR(branchId, 0, 3)"; String sql2 = "SELECT SUBSTR(branchId, 0, 3) AS region, SUM(quantity) AS salesQuantity, SUM(quantity * price) AS revenue FROM PRODUCTS_1418060 WHERE salesDate BETWEEN TO_DATE(?,'DD/MM/YYYY') AND TO_DATE(?,'DD/MM/YYYY') GROUP BY SUBSTR(branchId, 0, 3) ORDER BY SUBSTR(branchId, 0, 3)"; ps1 = con.prepareStatement(sql1); ps1.setString(1, "01/"+prevMon.getMonth()+"/"+year); ps1.setString(2, prevMon.getDays()+"/"+prevMon.getMonth()+"/"+year); ps2 = con.prepareStatement(sql2); ps2.setString(1, "01/"+mon.getMonth()+"/"+year); ps2.setString(2, mon.getDays()+"/"+mon.getMonth()+"/"+year); rs1 = ps1.executeQuery(); rs2 = ps2.executeQuery(); while (rs1.next() && rs2.next()) { double prevRev = rs1.getDouble(3); double rev = rs2.getDouble(3); double growth = ((rev - prevRev) / prevRev) * 100; tsrb = new TotalSalesRegionBased(rs2.getString(1), rs2.getInt(2), rs2.getDouble(3), growth); salesList.add(tsrb); } } catch(IllegalArgumentException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { DbUtil.closeResultSet(rs2); DbUtil.closeResultSet(rs1); DbUtil.closeStatement(ps2); DbUtil.closeStatement(ps1); DbUtil.closeConnection(); } return salesList; } }
UTF-8
Java
5,761
java
TotalSalesDao.java
Java
[]
null
[]
package com.tcs.ilp.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import com.tcs.ilp.bean.TotalSalesAllRegion; import com.tcs.ilp.bean.TotalSalesBranchBased; import com.tcs.ilp.bean.TotalSalesRegionBased; import com.tcs.ilp.util.DbUtil; import com.tcs.ilp.util.Month; public class TotalSalesDao { public ArrayList<TotalSalesAllRegion> getTotalSalesByAllRegion(String month, String year) { Connection con = DbUtil.createConnection(); PreparedStatement ps = null; ResultSet rs = null; ArrayList<TotalSalesAllRegion> salesList = new ArrayList<TotalSalesAllRegion>(); TotalSalesAllRegion tsar; try { Month mon = Month.valueOf(month); String sql = "SELECT productCode, productName, SUM(quantity) AS salesQuantity, SUM(quantity * price) AS revenue FROM PRODUCTS_1418060 WHERE salesDate BETWEEN TO_DATE(?,'DD/MM/YYYY') AND TO_DATE(?,'DD/MM/YYYY') GROUP BY productName, productCode ORDER BY productCode"; ps = con.prepareStatement(sql); ps.setString(1, "01/"+mon.getMonth()+"/"+year); ps.setString(2, mon.getDays()+"/"+mon.getMonth()+"/"+year); rs = ps.executeQuery(); int slid = 1; while (rs.next()) { tsar = new TotalSalesAllRegion(slid, rs.getString("productCode"), rs.getString("productName"), rs.getInt("salesQuantity"), rs.getDouble("revenue")); salesList.add(tsar); slid++; } } catch(IllegalArgumentException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { DbUtil.closeResultSet(rs); DbUtil.closeStatement(ps); DbUtil.closeConnection(); } return salesList; } public ArrayList<TotalSalesBranchBased> getTotalSalesBranchBased(String prevMonth, String month, String year) { Connection con = DbUtil.createConnection(); PreparedStatement ps1 = null; PreparedStatement ps2 = null; ResultSet rs1 = null; ResultSet rs2 = null; ArrayList<TotalSalesBranchBased> salesList = new ArrayList<TotalSalesBranchBased>(); TotalSalesBranchBased tsbb; try { Month prevMon = Month.valueOf(prevMonth); Month mon = Month.valueOf(month); String sql1 = "SELECT SUBSTR(branchId, 4, 6) AS branch, SUM(quantity) AS salesQuantity, SUM(quantity * price) AS revenue FROM PRODUCTS_1418060 WHERE salesDate BETWEEN TO_DATE(?,'DD/MM/YYYY') AND TO_DATE(?,'DD/MM/YYYY') GROUP BY SUBSTR(branchId, 4, 6) ORDER BY SUBSTR(branchId, 4, 6)"; String sql2 = "SELECT SUBSTR(branchId, 4, 6) AS branch, SUM(quantity) AS salesQuantity, SUM(quantity * price) AS revenue FROM PRODUCTS_1418060 WHERE salesDate BETWEEN TO_DATE(?,'DD/MM/YYYY') AND TO_DATE(?,'DD/MM/YYYY') GROUP BY SUBSTR(branchId, 4, 6) ORDER BY SUBSTR(branchId, 4, 6)"; ps1 = con.prepareStatement(sql1); ps1.setString(1, "01/"+prevMon.getMonth()+"/"+year); ps1.setString(2, prevMon.getDays()+"/"+prevMon.getMonth()+"/"+year); ps2 = con.prepareStatement(sql2); ps2.setString(1, "01/"+mon.getMonth()+"/"+year); ps2.setString(2, mon.getDays()+"/"+mon.getMonth()+"/"+year); rs1 = ps1.executeQuery(); rs2 = ps2.executeQuery(); while (rs1.next() && rs2.next()) { double prevRev = rs1.getDouble(3); double rev = rs2.getDouble(3); double growth = ((rev - prevRev) / prevRev) * 100; tsbb = new TotalSalesBranchBased(rs2.getString(1), rs2.getInt(2), rs2.getDouble(3), growth); salesList.add(tsbb); } } catch(IllegalArgumentException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { DbUtil.closeResultSet(rs2); DbUtil.closeResultSet(rs1); DbUtil.closeStatement(ps2); DbUtil.closeStatement(ps1); DbUtil.closeConnection(); } return salesList; } public ArrayList<TotalSalesRegionBased> getTotalSalesRegionBased(String prevMonth, String month, String year) { Connection con = DbUtil.createConnection(); PreparedStatement ps1 = null; PreparedStatement ps2 = null; ResultSet rs1 = null; ResultSet rs2 = null; ArrayList<TotalSalesRegionBased> salesList = new ArrayList<TotalSalesRegionBased>(); TotalSalesRegionBased tsrb; try { Month prevMon = Month.valueOf(prevMonth); Month mon = Month.valueOf(month); String sql1 = "SELECT SUBSTR(branchId, 0, 3) AS region, SUM(quantity) AS salesQuantity, SUM(quantity * price) AS revenue FROM PRODUCTS_1418060 WHERE salesDate BETWEEN TO_DATE(?,'DD/MM/YYYY') AND TO_DATE(?,'DD/MM/YYYY') GROUP BY SUBSTR(branchId, 0, 3) ORDER BY SUBSTR(branchId, 0, 3)"; String sql2 = "SELECT SUBSTR(branchId, 0, 3) AS region, SUM(quantity) AS salesQuantity, SUM(quantity * price) AS revenue FROM PRODUCTS_1418060 WHERE salesDate BETWEEN TO_DATE(?,'DD/MM/YYYY') AND TO_DATE(?,'DD/MM/YYYY') GROUP BY SUBSTR(branchId, 0, 3) ORDER BY SUBSTR(branchId, 0, 3)"; ps1 = con.prepareStatement(sql1); ps1.setString(1, "01/"+prevMon.getMonth()+"/"+year); ps1.setString(2, prevMon.getDays()+"/"+prevMon.getMonth()+"/"+year); ps2 = con.prepareStatement(sql2); ps2.setString(1, "01/"+mon.getMonth()+"/"+year); ps2.setString(2, mon.getDays()+"/"+mon.getMonth()+"/"+year); rs1 = ps1.executeQuery(); rs2 = ps2.executeQuery(); while (rs1.next() && rs2.next()) { double prevRev = rs1.getDouble(3); double rev = rs2.getDouble(3); double growth = ((rev - prevRev) / prevRev) * 100; tsrb = new TotalSalesRegionBased(rs2.getString(1), rs2.getInt(2), rs2.getDouble(3), growth); salesList.add(tsrb); } } catch(IllegalArgumentException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { DbUtil.closeResultSet(rs2); DbUtil.closeResultSet(rs1); DbUtil.closeStatement(ps2); DbUtil.closeStatement(ps1); DbUtil.closeConnection(); } return salesList; } }
5,761
0.70769
0.680958
131
42.9771
53.778378
287
false
false
0
0
0
0
0
0
3.580153
false
false
4
d0d52f210b53a06c10385574b4e4e98bba80fe60
3,487,513,481,203
13f1797646610ac9997c382986b5e977ad6f8d12
/ZECOMMERCE_PROJECT/src/main/java/Page_objects/shipping_page.java
dfe4b9f15059e9af2a199dd5e45fc34dabc613e5
[]
no_license
gkarthi2802/Ecommerce
https://github.com/gkarthi2802/Ecommerce
8be70ee20d3c8f5cd4c94bc7b9b1c268916c97fd
3f6d3a5a2da8ba06868015d000e14200721518fd
refs/heads/master
2021-06-26T02:41:20.467000
2020-04-28T12:09:11
2020-04-28T12:09:11
220,442,945
0
0
null
false
2021-04-26T19:56:22
2019-11-08T10:26:27
2020-04-28T12:12:23
2021-04-26T19:56:22
141
0
0
2
HTML
false
false
package Page_objects; import java.io.IOException; import Page_objects.Payment_page; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import Base_utilities.Base_class; public class shipping_page extends Base_class { @FindBy(id="cgv") WebElement terms; @FindBy(name="processCarrier") WebElement process_carrier; public shipping_page() throws IOException { super(); PageFactory.initElements(driver, this); } public void click_terms() { terms.click(); } public Payment_page click_proc_carrier() throws IOException { process_carrier.click(); return new Payment_page(); } public Payment_page all_operations_shipping() throws IOException { this.click_terms(); return this.click_proc_carrier(); } }
UTF-8
Java
808
java
shipping_page.java
Java
[]
null
[]
package Page_objects; import java.io.IOException; import Page_objects.Payment_page; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import Base_utilities.Base_class; public class shipping_page extends Base_class { @FindBy(id="cgv") WebElement terms; @FindBy(name="processCarrier") WebElement process_carrier; public shipping_page() throws IOException { super(); PageFactory.initElements(driver, this); } public void click_terms() { terms.click(); } public Payment_page click_proc_carrier() throws IOException { process_carrier.click(); return new Payment_page(); } public Payment_page all_operations_shipping() throws IOException { this.click_terms(); return this.click_proc_carrier(); } }
808
0.751238
0.751238
42
18.238094
19.18433
66
false
false
0
0
0
0
0
0
0.690476
false
false
4
9a08a73b80d2d9185e7656c0a3ecd86eff5485d6
463,856,503,840
fa0b5c085d12317d840aed6c788f2fd13f8b0c04
/src/com/RJBM/x00019315/Main.java
086143973053ecbbf5642bbbe89b338cf93faeda
[]
no_license
javierbeltran425/Tamagochis_parcial01_POO
https://github.com/javierbeltran425/Tamagochis_parcial01_POO
b85a36c8a559cecae39ffbbc38a6c917ea0d06f4
d5c01ec7d10834c395988b3f18e81fd6835c710a
refs/heads/master
2022-04-18T13:34:56.307000
2020-04-20T05:38:53
2020-04-20T05:38:53
256,297,250
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.RJBM.x00019315; import java.util.ArrayList; import java.util.InputMismatchException; import java.util.Scanner; public class Main { static Empresa empresa = new Empresa("Microsoft"); static Scanner in = new Scanner(System.in); public static void main(String[] args) { boolean continuar = true; int opción; double sueldo; do { System.out.println(); System.out.println("*********************"); System.out.println(" Sistema de empresa"); System.out.println("*********************"); System.out.print("1. Agregar empleado\n2. Despedir empleado\n3. Ver lista de empleados\n4. Calcular sueldo" + "\n5. Mostrar totales\n6. Salir"); System.out.println(); System.out.print("Ingrese su opcion: "); opción = in.nextInt(); in.nextLine(); try { switch (opción) { case 1: anadirEmpleado(); System.out.println(); break; case 2: quitEmpleado(); System.out.println(); break; case 3: listaEmpleados(); System.out.println(); break; case 4: String nombre; ArrayList<Empleado> a; CalculadoraImpuestos b; b = new CalculadoraImpuestos(); System.out.print("Ingrese el nombre de empleado: "); nombre = in.nextLine(); a = empresa.getPlanilla(); for (Empleado aux : a) { if (aux.getNombre().equalsIgnoreCase(nombre)) { sueldo = b.calcularPago(aux); System.out.print("Sueldo total: $" + sueldo); } } System.out.println(); break; case 5: CalculadoraImpuestos impuesto = new CalculadoraImpuestos(); empresa.getPlanilla(); System.out.print(impuesto.mostrarTotales()); System.out.println(); break; case 6: System.out.println("Saliendo..."); continuar = false; System.out.println(); break; default: System.out.print("Opción incorrecta"); } } catch(ExcepciónEmpleado ex){ System.out.println(ex.getMessage()); }catch (InputMismatchException mis){ System.out.print(mis.getMessage()); } catch(ArithmeticException ex){ System.out.print(ex.getMessage()); }catch(Exception mes) { System.out.print(mes.getMessage()); } } while (continuar); } public static void anadirEmpleado() throws Exception { String persona; String tipoDocumento; String numeroDocumento; int opción; String puesto; double salario; System.out.println(); System.out.println("**********************************"); System.out.println(" Sistema de registro de empleados"); System.out.println("**********************************"); System.out.print("Ingrese el nombre del empleado: "); persona = in.nextLine(); System.out.print("\nIngrese el puesto a desempeñar: " + "\n\t1. Plaza fija\n\t2. Servicio profesional"); System.out.println(); System.out.print("Opcion: "); opción = in.nextInt(); in.nextLine(); switch (opción){ case 1: try { puesto = "Plaza fija"; System.out.print("Ingrese la extension: "); int extension = in.nextInt(); System.out.print("\nIngrese el salario de este empleado: "); salario = in.nextDouble(); in.nextLine(); System.out.print("Ingrese tipo de documento: "); tipoDocumento = in.nextLine(); System.out.print("Número del documento: "); numeroDocumento = in.nextLine(); Documento doc = new Documento(tipoDocumento, numeroDocumento); PlazaFija p1 = new PlazaFija(persona, puesto, salario, extension); Empresa.addEmpleado(p1); Empleado.addDocumento(doc); }catch (InputMismatchException mis){ in.nextLine(); throw new InputMismatchException("Error"); } catch(Exception e){ System.out.print("Error"); } break; case 2: try { puesto = "Servicio profesional"; System.out.print("Ingrese los meses de contrato: "); int mesesContrato = in.nextInt(); System.out.print("\nIngrese el salario de este empleado: "); salario = in.nextDouble(); in.nextLine(); System.out.print("Ingrese tipo de documento: "); tipoDocumento = in.nextLine(); System.out.print("Número del documento: "); numeroDocumento = in.nextLine(); Documento doc2 = new Documento(tipoDocumento, numeroDocumento); ServicioProfesional p2 = new ServicioProfesional(persona, puesto, salario, mesesContrato); Empresa.addEmpleado(p2); Empleado.addDocumento(doc2); }catch (InputMismatchException mis){ in.nextLine(); throw new InputMismatchException("Error"); }catch (Exception e){ System.out.print("Error"); } break; default: System.out.print("Opción incorrecta"); } } public static void listaEmpleados() { ArrayList<Empleado> e; e = empresa.getPlanilla(); System.out.println(); if (!e.isEmpty()) { for (Empleado aux : e) { System.out.println(); System.out.println("*****"); System.out.print("Nombre: " + aux.getNombre() + "\nPuesto: " + aux.getPuesto() + "\nSalario: " + aux.getSalario()); System.out.println(); } } else System.out.println("La lista está vacia."); } public static void quitEmpleado() throws ExcepciónEmpleado, NotExistingDocuments { String nombre; System.out.print("Ingrese el nombre del empleado: "); nombre = in.nextLine(); Empresa.quitEmpleado(nombre); } }
UTF-8
Java
7,001
java
Main.java
Java
[]
null
[]
package com.RJBM.x00019315; import java.util.ArrayList; import java.util.InputMismatchException; import java.util.Scanner; public class Main { static Empresa empresa = new Empresa("Microsoft"); static Scanner in = new Scanner(System.in); public static void main(String[] args) { boolean continuar = true; int opción; double sueldo; do { System.out.println(); System.out.println("*********************"); System.out.println(" Sistema de empresa"); System.out.println("*********************"); System.out.print("1. Agregar empleado\n2. Despedir empleado\n3. Ver lista de empleados\n4. Calcular sueldo" + "\n5. Mostrar totales\n6. Salir"); System.out.println(); System.out.print("Ingrese su opcion: "); opción = in.nextInt(); in.nextLine(); try { switch (opción) { case 1: anadirEmpleado(); System.out.println(); break; case 2: quitEmpleado(); System.out.println(); break; case 3: listaEmpleados(); System.out.println(); break; case 4: String nombre; ArrayList<Empleado> a; CalculadoraImpuestos b; b = new CalculadoraImpuestos(); System.out.print("Ingrese el nombre de empleado: "); nombre = in.nextLine(); a = empresa.getPlanilla(); for (Empleado aux : a) { if (aux.getNombre().equalsIgnoreCase(nombre)) { sueldo = b.calcularPago(aux); System.out.print("Sueldo total: $" + sueldo); } } System.out.println(); break; case 5: CalculadoraImpuestos impuesto = new CalculadoraImpuestos(); empresa.getPlanilla(); System.out.print(impuesto.mostrarTotales()); System.out.println(); break; case 6: System.out.println("Saliendo..."); continuar = false; System.out.println(); break; default: System.out.print("Opción incorrecta"); } } catch(ExcepciónEmpleado ex){ System.out.println(ex.getMessage()); }catch (InputMismatchException mis){ System.out.print(mis.getMessage()); } catch(ArithmeticException ex){ System.out.print(ex.getMessage()); }catch(Exception mes) { System.out.print(mes.getMessage()); } } while (continuar); } public static void anadirEmpleado() throws Exception { String persona; String tipoDocumento; String numeroDocumento; int opción; String puesto; double salario; System.out.println(); System.out.println("**********************************"); System.out.println(" Sistema de registro de empleados"); System.out.println("**********************************"); System.out.print("Ingrese el nombre del empleado: "); persona = in.nextLine(); System.out.print("\nIngrese el puesto a desempeñar: " + "\n\t1. Plaza fija\n\t2. Servicio profesional"); System.out.println(); System.out.print("Opcion: "); opción = in.nextInt(); in.nextLine(); switch (opción){ case 1: try { puesto = "Plaza fija"; System.out.print("Ingrese la extension: "); int extension = in.nextInt(); System.out.print("\nIngrese el salario de este empleado: "); salario = in.nextDouble(); in.nextLine(); System.out.print("Ingrese tipo de documento: "); tipoDocumento = in.nextLine(); System.out.print("Número del documento: "); numeroDocumento = in.nextLine(); Documento doc = new Documento(tipoDocumento, numeroDocumento); PlazaFija p1 = new PlazaFija(persona, puesto, salario, extension); Empresa.addEmpleado(p1); Empleado.addDocumento(doc); }catch (InputMismatchException mis){ in.nextLine(); throw new InputMismatchException("Error"); } catch(Exception e){ System.out.print("Error"); } break; case 2: try { puesto = "Servicio profesional"; System.out.print("Ingrese los meses de contrato: "); int mesesContrato = in.nextInt(); System.out.print("\nIngrese el salario de este empleado: "); salario = in.nextDouble(); in.nextLine(); System.out.print("Ingrese tipo de documento: "); tipoDocumento = in.nextLine(); System.out.print("Número del documento: "); numeroDocumento = in.nextLine(); Documento doc2 = new Documento(tipoDocumento, numeroDocumento); ServicioProfesional p2 = new ServicioProfesional(persona, puesto, salario, mesesContrato); Empresa.addEmpleado(p2); Empleado.addDocumento(doc2); }catch (InputMismatchException mis){ in.nextLine(); throw new InputMismatchException("Error"); }catch (Exception e){ System.out.print("Error"); } break; default: System.out.print("Opción incorrecta"); } } public static void listaEmpleados() { ArrayList<Empleado> e; e = empresa.getPlanilla(); System.out.println(); if (!e.isEmpty()) { for (Empleado aux : e) { System.out.println(); System.out.println("*****"); System.out.print("Nombre: " + aux.getNombre() + "\nPuesto: " + aux.getPuesto() + "\nSalario: " + aux.getSalario()); System.out.println(); } } else System.out.println("La lista está vacia."); } public static void quitEmpleado() throws ExcepciónEmpleado, NotExistingDocuments { String nombre; System.out.print("Ingrese el nombre del empleado: "); nombre = in.nextLine(); Empresa.quitEmpleado(nombre); } }
7,001
0.483612
0.479319
192
35.390625
24.56345
117
false
false
0
0
0
0
0
0
0.666667
false
false
4
05cfa9b94460968d8c0081e8a7bcaf975d9f709e
16,449,724,781,893
9fac8f5186f4ef1633eebd71744cb0b74051a4b2
/nuxeo-services/nuxeo-platform-dublincore/src/test/java/org/nuxeo/ecm/platform/dublincore/service/DublinCoreStorageServiceImplTest.java
2a26a40ffb409eab0ff8d2b6c9749bddc47bfe5a
[ "Apache-2.0" ]
permissive
sampisamuel/nuxeo
https://github.com/sampisamuel/nuxeo
588e6f468b9cc4292a169f25e64f71edff811910
7ec7c164e508223eef05bb198066920399440efe
refs/heads/master
2020-05-25T13:11:33.468000
2019-05-19T12:15:45
2019-05-20T17:36:52
187,803,485
1
0
Apache-2.0
true
2019-05-21T09:16:14
2019-05-21T09:16:13
2019-05-20T17:37:00
2019-05-20T17:37:15
370,313
0
0
0
null
false
false
/* * (C) Copyright 2018 Nuxeo (http://nuxeo.com/) and others. * * 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. * * Contributors: * Nuno Cunha (ncunha@nuxeo.com) */ package org.nuxeo.ecm.platform.dublincore.service; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.number.OrderingComparison.greaterThan; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.nuxeo.ecm.core.api.event.DocumentEventTypes.ABOUT_TO_CREATE; import static org.nuxeo.ecm.core.api.event.DocumentEventTypes.BEFORE_DOC_UPDATE; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.inject.Inject; import org.junit.Test; import org.junit.runner.RunWith; import org.nuxeo.ecm.core.api.CoreSession; import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.core.api.NuxeoPrincipal; import org.nuxeo.ecm.core.api.SystemPrincipal; import org.nuxeo.ecm.core.event.Event; import org.nuxeo.ecm.core.event.impl.DocumentEventContext; import org.nuxeo.ecm.core.event.impl.EventImpl; import org.nuxeo.ecm.core.test.CoreFeature; import org.nuxeo.runtime.test.runner.Deploy; import org.nuxeo.runtime.test.runner.Features; import org.nuxeo.runtime.test.runner.FeaturesRunner; /** * @since 10.2 */ @RunWith(FeaturesRunner.class) @Features(CoreFeature.class) @Deploy("org.nuxeo.ecm.platform.dublincore") public class DublinCoreStorageServiceImplTest { @Inject protected DublinCoreStorageService storageService; @Inject protected CoreSession session; @Test public void shouldBeUpAndRunning() { assertNotNull(storageService); } @Test public void shouldSetCreationDate() { DocumentModel doc = session.createDocumentModel("/", "file", "File"); Calendar currentDate = Calendar.getInstance(); Map<String, Object> originalProperties = new HashMap<>(doc.getProperties("dublincore")); Set<String> expectedChangedProperties = Collections.singleton("dc:created"); storageService.setCreationDate(doc, currentDate); assertDocumentPropertiesChanges(doc, originalProperties, expectedChangedProperties); assertEquals(currentDate, doc.getPropertyValue("dc:created")); } @Test public void shouldSetModificationDateOnlyWhenCreationDateExists() throws InterruptedException { DocumentModel doc = session.createDocumentModel("/", "file", "File"); Calendar currentDate = Calendar.getInstance(); storageService.setCreationDate(doc, currentDate); Map<String, Object> originalProperties = new HashMap<>(doc.getProperties("dublincore")); Set<String> expectedChangedProperties = Collections.singleton("dc:modified"); Thread.sleep(1000); currentDate = Calendar.getInstance(); storageService.setModificationDate(doc, currentDate); assertDocumentPropertiesChanges(doc, originalProperties, expectedChangedProperties); assertEquals(currentDate, doc.getPropertyValue("dc:modified")); assertThat((Calendar) doc.getPropertyValue("dc:modified"), greaterThan((Calendar) doc.getPropertyValue("dc:created"))); } @Test public void shouldSetModificationDateAndCreationDateWhenCreationDateNotExists() { DocumentModel doc = session.createDocumentModel("/", "file", "File"); Map<String, Object> originalProperties = new HashMap<>(doc.getProperties("dublincore")); Set<String> expectedChangedProperties = new HashSet<>(); expectedChangedProperties.add("dc:created"); expectedChangedProperties.add("dc:modified"); Calendar currentDate = Calendar.getInstance(); storageService.setModificationDate(doc, currentDate); assertDocumentPropertiesChanges(doc, originalProperties, expectedChangedProperties); assertEquals(currentDate, doc.getPropertyValue("dc:created")); assertEquals(currentDate, doc.getPropertyValue("dc:modified")); } @Test public void shouldSetIssuedDate() { DocumentModel doc = session.createDocumentModel("/", "file", "File"); Map<String, Object> originalProperties = new HashMap<>(doc.getProperties("dublincore")); Set<String> expectedChangedProperties = Collections.singleton("dc:issued"); Calendar currentDate = Calendar.getInstance(); storageService.setIssuedDate(doc, currentDate); assertDocumentPropertiesChanges(doc, originalProperties, expectedChangedProperties); assertEquals(currentDate, doc.getPropertyValue("dc:issued")); } @Test(expected = NullPointerException.class) public void shouldThrowExceptionWhenNoPrincipalIsProvided() { DocumentModel doc = session.createDocumentModel("/", "file", "File"); Event event = getEventFromDocumentContext(ABOUT_TO_CREATE, session, null); storageService.addContributor(doc, event); } @Test public void shouldDoNothingWhenNoOriginatingUserIsProvided() { DocumentModel doc = session.createDocumentModel("/", "file", "File"); Map<String, Object> originalProperties = new HashMap<>(doc.getProperties("dublincore")); Event event = getEventFromDocumentContext(BEFORE_DOC_UPDATE, session, new SystemPrincipal(null)); storageService.addContributor(doc, event); assertDocumentPropertiesChanges(doc, originalProperties, new HashSet<>()); } @Test public void shouldDoNothingWhenOriginatingUserIsSystem() { DocumentModel doc = session.createDocumentModel("/", "file", "File"); Map<String, Object> originalProperties = new HashMap<>(doc.getProperties("dublincore")); Event event = getEventFromDocumentContext(BEFORE_DOC_UPDATE, session, new SystemPrincipal(null)); storageService.addContributor(doc, event); assertDocumentPropertiesChanges(doc, originalProperties, new HashSet<>()); } @Test public void shouldAddOriginatingUserWhenSystemPrincipalIsUsed() { DocumentModel doc = session.createDocumentModel("/", "file", "File"); Map<String, Object> originalProperties = new HashMap<>(doc.getProperties("dublincore")); Set<String> expectedChangedProperties = new HashSet<>(); expectedChangedProperties.add("dc:creator"); expectedChangedProperties.add("dc:lastContributor"); expectedChangedProperties.add("dc:contributors"); SystemPrincipal principal = new SystemPrincipal("Myself"); Event event = getEventFromDocumentContext(ABOUT_TO_CREATE, session, principal); storageService.addContributor(doc, event); assertDocumentPropertiesChanges(doc, originalProperties, expectedChangedProperties); String principalName = principal.getOriginatingUser(); assertEquals(principalName, doc.getPropertyValue("dc:creator")); assertEquals(principalName, doc.getPropertyValue("dc:lastContributor")); List<String> contributors = Arrays.asList((String[]) doc.getPropertyValue("dc:contributors")); assertEquals(1, contributors.size()); assertTrue(contributors.contains(principalName)); } @Test public void shouldSetContributorsAndCreatorWhenAboutToCreate() { DocumentModel doc = session.createDocumentModel("/", "file", "File"); Map<String, Object> originalProperties = new HashMap<>(doc.getProperties("dublincore")); Set<String> expectedChangedProperties = new HashSet<>(); expectedChangedProperties.add("dc:creator"); expectedChangedProperties.add("dc:lastContributor"); expectedChangedProperties.add("dc:contributors"); Event event = getEventFromDocumentContext(ABOUT_TO_CREATE, session, session.getPrincipal()); storageService.addContributor(doc, event); assertDocumentPropertiesChanges(doc, originalProperties, expectedChangedProperties); String principalName = session.getPrincipal().getName(); assertEquals(principalName, doc.getPropertyValue("dc:creator")); assertEquals(principalName, doc.getPropertyValue("dc:lastContributor")); List<String> contributors = Arrays.asList((String[]) doc.getPropertyValue("dc:contributors")); assertEquals(1, contributors.size()); assertTrue(contributors.contains(principalName)); } @Test public void shouldAddContributorWhenAlreadyCreated() { DocumentModel doc = session.createDocumentModel("/", "file", "File"); doc.setPropertyValue("dc:creator", "Original Creator"); doc.setPropertyValue("dc:lastContributor", "Original Creator"); doc.setPropertyValue("dc:contributors", new String[] { "Original Creator" }); Map<String, Object> originalProperties = new HashMap<>(doc.getProperties("dublincore")); Set<String> expectedChangedProperties = new HashSet<>(); expectedChangedProperties.add("dc:lastContributor"); expectedChangedProperties.add("dc:contributors"); Event event = getEventFromDocumentContext(BEFORE_DOC_UPDATE, session, session.getPrincipal()); storageService.addContributor(doc, event); assertDocumentPropertiesChanges(doc, originalProperties, expectedChangedProperties); String principalName = session.getPrincipal().getName(); assertEquals("Original Creator", doc.getPropertyValue("dc:creator")); List<String> contributors = Arrays.asList((String[]) doc.getPropertyValue("dc:contributors")); assertEquals(2, contributors.size()); assertTrue(contributors.contains("Original Creator")); assertTrue(contributors.contains(principalName)); } @Test public void shouldRemovePrefixContributorsWhenAdding() { DocumentModel doc = session.createDocumentModel("/", "file", "File"); doc.setPropertyValue("dc:creator", "Original Creator"); doc.setPropertyValue("dc:lastContributor", "Original Creator"); doc.setPropertyValue("dc:contributors", new String[] { "Original Creator", "user:Administrator", "user:Other User" }); Map<String, Object> originalProperties = new HashMap<>(doc.getProperties("dublincore")); Set<String> expectedChangedProperties = new HashSet<>(); expectedChangedProperties.add("dc:lastContributor"); expectedChangedProperties.add("dc:contributors"); Event event = getEventFromDocumentContext(BEFORE_DOC_UPDATE, session, session.getPrincipal()); storageService.addContributor(doc, event); assertDocumentPropertiesChanges(doc, originalProperties, expectedChangedProperties); String principalName = session.getPrincipal().getName(); assertEquals(principalName, doc.getPropertyValue("dc:lastContributor")); List<String> contributors = Arrays.asList((String[]) doc.getPropertyValue("dc:contributors")); assertEquals(3, contributors.size()); assertTrue(contributors.contains("Original Creator")); assertTrue(contributors.contains("Other User")); assertTrue(contributors.contains(principalName)); } @Test public void shouldRemoveRepeatedContributorsWhenAdding() { DocumentModel doc = session.createDocumentModel("/", "file", "File"); doc.setPropertyValue("dc:creator", "Administrator"); doc.setPropertyValue("dc:lastContributor", "Administrator"); doc.setPropertyValue("dc:contributors", new String[] { "user:Administrator", "user:Administrator", "user:Administrator", "user:Administrator" }); Map<String, Object> originalProperties = new HashMap<>(doc.getProperties("dublincore")); Set<String> expectedChangedProperties = Collections.singleton("dc:contributors"); Event event = getEventFromDocumentContext(BEFORE_DOC_UPDATE, session, session.getPrincipal()); storageService.addContributor(doc, event); assertDocumentPropertiesChanges(doc, originalProperties, expectedChangedProperties); String principalName = session.getPrincipal().getName(); List<String> contributors = Arrays.asList((String[]) doc.getPropertyValue("dc:contributors")); assertEquals(1, contributors.size()); assertFalse(contributors.contains("user:Administrator")); assertTrue(contributors.contains(principalName)); } @Test public void shouldDoNothingWhenAddingExistingContributor() { DocumentModel doc = session.createDocumentModel("/", "file", "File"); doc.setPropertyValue("dc:creator", "Administrator"); doc.setPropertyValue("dc:lastContributor", "Administrator"); doc.setPropertyValue("dc:contributors", new String[] { "Administrator" }); Map<String, Object> originalProperties = new HashMap<>(doc.getProperties("dublincore")); Event event = getEventFromDocumentContext(BEFORE_DOC_UPDATE, session, session.getPrincipal()); storageService.addContributor(doc, event); assertDocumentPropertiesChanges(doc, originalProperties, new HashSet<>()); } protected Event getEventFromDocumentContext(String eventName, CoreSession coreSession, NuxeoPrincipal principal) { return new EventImpl(eventName, new DocumentEventContext(coreSession, principal, coreSession.getRootDocument())); } protected static void assertDocumentPropertiesChanges(DocumentModel doc, Map<String, Object> originalProperties, Set<String> expectedChangedPropertyNames) { originalProperties.forEach((key, value) -> { Object currentValue = doc.getProperty("dublincore", key); if (expectedChangedPropertyNames.contains(key)) { assertNotEquals(value, currentValue); } else { assertEquals(currentValue, value); } }); } }
UTF-8
Java
14,609
java
DublinCoreStorageServiceImplTest.java
Java
[ { "context": "ions under the License.\n *\n * Contributors:\n * Nuno Cunha (ncunha@nuxeo.com)\n */\n\npackage org.nuxeo.ecm.pla", "end": 658, "score": 0.999873161315918, "start": 648, "tag": "NAME", "value": "Nuno Cunha" }, { "context": "e License.\n *\n * Contributors:\n * Nuno Cunha (ncunha@nuxeo.com)\n */\n\npackage org.nuxeo.ecm.platform.dublincore.s", "end": 676, "score": 0.9999317526817322, "start": 660, "tag": "EMAIL", "value": "ncunha@nuxeo.com" }, { "context": " SystemPrincipal principal = new SystemPrincipal(\"Myself\");\n\n Event event = getEventFromDocumentCon", "end": 7269, "score": 0.7550369501113892, "start": 7263, "tag": "USERNAME", "value": "Myself" }, { "context": " new String[] { \"Original Creator\", \"user:Administrator\", \"user:Other User\" });\n\n Map<String, Obje", "end": 10842, "score": 0.9433702826499939, "start": 10829, "tag": "USERNAME", "value": "Administrator" } ]
null
[]
/* * (C) Copyright 2018 Nuxeo (http://nuxeo.com/) and others. * * 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. * * Contributors: * <NAME> (<EMAIL>) */ package org.nuxeo.ecm.platform.dublincore.service; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.number.OrderingComparison.greaterThan; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.nuxeo.ecm.core.api.event.DocumentEventTypes.ABOUT_TO_CREATE; import static org.nuxeo.ecm.core.api.event.DocumentEventTypes.BEFORE_DOC_UPDATE; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.inject.Inject; import org.junit.Test; import org.junit.runner.RunWith; import org.nuxeo.ecm.core.api.CoreSession; import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.core.api.NuxeoPrincipal; import org.nuxeo.ecm.core.api.SystemPrincipal; import org.nuxeo.ecm.core.event.Event; import org.nuxeo.ecm.core.event.impl.DocumentEventContext; import org.nuxeo.ecm.core.event.impl.EventImpl; import org.nuxeo.ecm.core.test.CoreFeature; import org.nuxeo.runtime.test.runner.Deploy; import org.nuxeo.runtime.test.runner.Features; import org.nuxeo.runtime.test.runner.FeaturesRunner; /** * @since 10.2 */ @RunWith(FeaturesRunner.class) @Features(CoreFeature.class) @Deploy("org.nuxeo.ecm.platform.dublincore") public class DublinCoreStorageServiceImplTest { @Inject protected DublinCoreStorageService storageService; @Inject protected CoreSession session; @Test public void shouldBeUpAndRunning() { assertNotNull(storageService); } @Test public void shouldSetCreationDate() { DocumentModel doc = session.createDocumentModel("/", "file", "File"); Calendar currentDate = Calendar.getInstance(); Map<String, Object> originalProperties = new HashMap<>(doc.getProperties("dublincore")); Set<String> expectedChangedProperties = Collections.singleton("dc:created"); storageService.setCreationDate(doc, currentDate); assertDocumentPropertiesChanges(doc, originalProperties, expectedChangedProperties); assertEquals(currentDate, doc.getPropertyValue("dc:created")); } @Test public void shouldSetModificationDateOnlyWhenCreationDateExists() throws InterruptedException { DocumentModel doc = session.createDocumentModel("/", "file", "File"); Calendar currentDate = Calendar.getInstance(); storageService.setCreationDate(doc, currentDate); Map<String, Object> originalProperties = new HashMap<>(doc.getProperties("dublincore")); Set<String> expectedChangedProperties = Collections.singleton("dc:modified"); Thread.sleep(1000); currentDate = Calendar.getInstance(); storageService.setModificationDate(doc, currentDate); assertDocumentPropertiesChanges(doc, originalProperties, expectedChangedProperties); assertEquals(currentDate, doc.getPropertyValue("dc:modified")); assertThat((Calendar) doc.getPropertyValue("dc:modified"), greaterThan((Calendar) doc.getPropertyValue("dc:created"))); } @Test public void shouldSetModificationDateAndCreationDateWhenCreationDateNotExists() { DocumentModel doc = session.createDocumentModel("/", "file", "File"); Map<String, Object> originalProperties = new HashMap<>(doc.getProperties("dublincore")); Set<String> expectedChangedProperties = new HashSet<>(); expectedChangedProperties.add("dc:created"); expectedChangedProperties.add("dc:modified"); Calendar currentDate = Calendar.getInstance(); storageService.setModificationDate(doc, currentDate); assertDocumentPropertiesChanges(doc, originalProperties, expectedChangedProperties); assertEquals(currentDate, doc.getPropertyValue("dc:created")); assertEquals(currentDate, doc.getPropertyValue("dc:modified")); } @Test public void shouldSetIssuedDate() { DocumentModel doc = session.createDocumentModel("/", "file", "File"); Map<String, Object> originalProperties = new HashMap<>(doc.getProperties("dublincore")); Set<String> expectedChangedProperties = Collections.singleton("dc:issued"); Calendar currentDate = Calendar.getInstance(); storageService.setIssuedDate(doc, currentDate); assertDocumentPropertiesChanges(doc, originalProperties, expectedChangedProperties); assertEquals(currentDate, doc.getPropertyValue("dc:issued")); } @Test(expected = NullPointerException.class) public void shouldThrowExceptionWhenNoPrincipalIsProvided() { DocumentModel doc = session.createDocumentModel("/", "file", "File"); Event event = getEventFromDocumentContext(ABOUT_TO_CREATE, session, null); storageService.addContributor(doc, event); } @Test public void shouldDoNothingWhenNoOriginatingUserIsProvided() { DocumentModel doc = session.createDocumentModel("/", "file", "File"); Map<String, Object> originalProperties = new HashMap<>(doc.getProperties("dublincore")); Event event = getEventFromDocumentContext(BEFORE_DOC_UPDATE, session, new SystemPrincipal(null)); storageService.addContributor(doc, event); assertDocumentPropertiesChanges(doc, originalProperties, new HashSet<>()); } @Test public void shouldDoNothingWhenOriginatingUserIsSystem() { DocumentModel doc = session.createDocumentModel("/", "file", "File"); Map<String, Object> originalProperties = new HashMap<>(doc.getProperties("dublincore")); Event event = getEventFromDocumentContext(BEFORE_DOC_UPDATE, session, new SystemPrincipal(null)); storageService.addContributor(doc, event); assertDocumentPropertiesChanges(doc, originalProperties, new HashSet<>()); } @Test public void shouldAddOriginatingUserWhenSystemPrincipalIsUsed() { DocumentModel doc = session.createDocumentModel("/", "file", "File"); Map<String, Object> originalProperties = new HashMap<>(doc.getProperties("dublincore")); Set<String> expectedChangedProperties = new HashSet<>(); expectedChangedProperties.add("dc:creator"); expectedChangedProperties.add("dc:lastContributor"); expectedChangedProperties.add("dc:contributors"); SystemPrincipal principal = new SystemPrincipal("Myself"); Event event = getEventFromDocumentContext(ABOUT_TO_CREATE, session, principal); storageService.addContributor(doc, event); assertDocumentPropertiesChanges(doc, originalProperties, expectedChangedProperties); String principalName = principal.getOriginatingUser(); assertEquals(principalName, doc.getPropertyValue("dc:creator")); assertEquals(principalName, doc.getPropertyValue("dc:lastContributor")); List<String> contributors = Arrays.asList((String[]) doc.getPropertyValue("dc:contributors")); assertEquals(1, contributors.size()); assertTrue(contributors.contains(principalName)); } @Test public void shouldSetContributorsAndCreatorWhenAboutToCreate() { DocumentModel doc = session.createDocumentModel("/", "file", "File"); Map<String, Object> originalProperties = new HashMap<>(doc.getProperties("dublincore")); Set<String> expectedChangedProperties = new HashSet<>(); expectedChangedProperties.add("dc:creator"); expectedChangedProperties.add("dc:lastContributor"); expectedChangedProperties.add("dc:contributors"); Event event = getEventFromDocumentContext(ABOUT_TO_CREATE, session, session.getPrincipal()); storageService.addContributor(doc, event); assertDocumentPropertiesChanges(doc, originalProperties, expectedChangedProperties); String principalName = session.getPrincipal().getName(); assertEquals(principalName, doc.getPropertyValue("dc:creator")); assertEquals(principalName, doc.getPropertyValue("dc:lastContributor")); List<String> contributors = Arrays.asList((String[]) doc.getPropertyValue("dc:contributors")); assertEquals(1, contributors.size()); assertTrue(contributors.contains(principalName)); } @Test public void shouldAddContributorWhenAlreadyCreated() { DocumentModel doc = session.createDocumentModel("/", "file", "File"); doc.setPropertyValue("dc:creator", "Original Creator"); doc.setPropertyValue("dc:lastContributor", "Original Creator"); doc.setPropertyValue("dc:contributors", new String[] { "Original Creator" }); Map<String, Object> originalProperties = new HashMap<>(doc.getProperties("dublincore")); Set<String> expectedChangedProperties = new HashSet<>(); expectedChangedProperties.add("dc:lastContributor"); expectedChangedProperties.add("dc:contributors"); Event event = getEventFromDocumentContext(BEFORE_DOC_UPDATE, session, session.getPrincipal()); storageService.addContributor(doc, event); assertDocumentPropertiesChanges(doc, originalProperties, expectedChangedProperties); String principalName = session.getPrincipal().getName(); assertEquals("Original Creator", doc.getPropertyValue("dc:creator")); List<String> contributors = Arrays.asList((String[]) doc.getPropertyValue("dc:contributors")); assertEquals(2, contributors.size()); assertTrue(contributors.contains("Original Creator")); assertTrue(contributors.contains(principalName)); } @Test public void shouldRemovePrefixContributorsWhenAdding() { DocumentModel doc = session.createDocumentModel("/", "file", "File"); doc.setPropertyValue("dc:creator", "Original Creator"); doc.setPropertyValue("dc:lastContributor", "Original Creator"); doc.setPropertyValue("dc:contributors", new String[] { "Original Creator", "user:Administrator", "user:Other User" }); Map<String, Object> originalProperties = new HashMap<>(doc.getProperties("dublincore")); Set<String> expectedChangedProperties = new HashSet<>(); expectedChangedProperties.add("dc:lastContributor"); expectedChangedProperties.add("dc:contributors"); Event event = getEventFromDocumentContext(BEFORE_DOC_UPDATE, session, session.getPrincipal()); storageService.addContributor(doc, event); assertDocumentPropertiesChanges(doc, originalProperties, expectedChangedProperties); String principalName = session.getPrincipal().getName(); assertEquals(principalName, doc.getPropertyValue("dc:lastContributor")); List<String> contributors = Arrays.asList((String[]) doc.getPropertyValue("dc:contributors")); assertEquals(3, contributors.size()); assertTrue(contributors.contains("Original Creator")); assertTrue(contributors.contains("Other User")); assertTrue(contributors.contains(principalName)); } @Test public void shouldRemoveRepeatedContributorsWhenAdding() { DocumentModel doc = session.createDocumentModel("/", "file", "File"); doc.setPropertyValue("dc:creator", "Administrator"); doc.setPropertyValue("dc:lastContributor", "Administrator"); doc.setPropertyValue("dc:contributors", new String[] { "user:Administrator", "user:Administrator", "user:Administrator", "user:Administrator" }); Map<String, Object> originalProperties = new HashMap<>(doc.getProperties("dublincore")); Set<String> expectedChangedProperties = Collections.singleton("dc:contributors"); Event event = getEventFromDocumentContext(BEFORE_DOC_UPDATE, session, session.getPrincipal()); storageService.addContributor(doc, event); assertDocumentPropertiesChanges(doc, originalProperties, expectedChangedProperties); String principalName = session.getPrincipal().getName(); List<String> contributors = Arrays.asList((String[]) doc.getPropertyValue("dc:contributors")); assertEquals(1, contributors.size()); assertFalse(contributors.contains("user:Administrator")); assertTrue(contributors.contains(principalName)); } @Test public void shouldDoNothingWhenAddingExistingContributor() { DocumentModel doc = session.createDocumentModel("/", "file", "File"); doc.setPropertyValue("dc:creator", "Administrator"); doc.setPropertyValue("dc:lastContributor", "Administrator"); doc.setPropertyValue("dc:contributors", new String[] { "Administrator" }); Map<String, Object> originalProperties = new HashMap<>(doc.getProperties("dublincore")); Event event = getEventFromDocumentContext(BEFORE_DOC_UPDATE, session, session.getPrincipal()); storageService.addContributor(doc, event); assertDocumentPropertiesChanges(doc, originalProperties, new HashSet<>()); } protected Event getEventFromDocumentContext(String eventName, CoreSession coreSession, NuxeoPrincipal principal) { return new EventImpl(eventName, new DocumentEventContext(coreSession, principal, coreSession.getRootDocument())); } protected static void assertDocumentPropertiesChanges(DocumentModel doc, Map<String, Object> originalProperties, Set<String> expectedChangedPropertyNames) { originalProperties.forEach((key, value) -> { Object currentValue = doc.getProperty("dublincore", key); if (expectedChangedPropertyNames.contains(key)) { assertNotEquals(value, currentValue); } else { assertEquals(currentValue, value); } }); } }
14,596
0.719146
0.717777
341
41.84164
34.823536
118
false
false
0
0
0
0
65
0.004449
0.941349
false
false
4
8067e88235b9d142ae66fdd49c8543511540e73f
31,464,930,446,079
7e72dc9a8e85a820a1826a64ebf9bca993f78671
/src/main/java/uk/gov/hmcts/reform/sscs/model/docassembly/Respondent.java
d109a8522c9a406ea855e98f149bd78fc1907df1
[ "MIT" ]
permissive
hmcts/sscs-tribunals-case-api
https://github.com/hmcts/sscs-tribunals-case-api
2eadd528fabcd213c8b3403d78c62b09b3d932da
78a8b27c6d2d0add763404b30860c3ba98803b26
refs/heads/master
2023-08-05T21:04:51.261000
2023-08-04T16:48:22
2023-08-04T16:48:22
102,725,188
5
3
MIT
false
2023-09-14T15:04:26
2017-09-07T10:42:01
2023-08-01T17:16:42
2023-09-14T15:03:13
25,316
5
4
79
Java
false
false
package uk.gov.hmcts.reform.sscs.model.docassembly; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Builder; import lombok.Getter; @Builder(toBuilder = true) @Getter @JsonInclude(JsonInclude.Include.NON_NULL) public class Respondent { @JsonProperty("name") private String name; @JsonIgnore public static String[] labelPrefixes = {"Second", "Third", "Fourth", "Fifth", "Sixth", "Seventh", "Eighth", "Ninth", "Tenth", "Eleventh"}; @JsonIgnore public static String HMRC = "Respondent: HM Revenue & Customs"; @JsonIgnore public static String DWP = "Respondent: Secretary of State for Work and Pensions"; }
UTF-8
Java
764
java
Respondent.java
Java
[]
null
[]
package uk.gov.hmcts.reform.sscs.model.docassembly; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Builder; import lombok.Getter; @Builder(toBuilder = true) @Getter @JsonInclude(JsonInclude.Include.NON_NULL) public class Respondent { @JsonProperty("name") private String name; @JsonIgnore public static String[] labelPrefixes = {"Second", "Third", "Fourth", "Fifth", "Sixth", "Seventh", "Eighth", "Ninth", "Tenth", "Eleventh"}; @JsonIgnore public static String HMRC = "Respondent: HM Revenue & Customs"; @JsonIgnore public static String DWP = "Respondent: Secretary of State for Work and Pensions"; }
764
0.740838
0.740838
24
30.833334
32.827412
142
false
false
0
0
0
0
0
0
0.791667
false
false
4
3c4eedf4f9e65e2fd07ebb362936c0ed57dde7fc
27,127,013,475,572
3a2d009860e4817b74387ef2bfac7f0af9121f42
/android_app/ShoppingwithFriends/app/src/main/java/Tests/PostViewItemsNotNullTest.java
7ae9bd4c4b24c262e982ab3637a6039d83910011
[]
no_license
rbro112/Collect
https://github.com/rbro112/Collect
64431de5b052162d91a8ee1c6953fde1f7cb633d
83f5933b8df20ca9f578a7b7c73b9d2e188b86eb
refs/heads/master
2016-08-07T05:03:55.658000
2015-04-06T04:01:39
2015-04-06T04:01:39
29,199,146
0
3
null
false
2015-03-11T03:22:10
2015-01-13T16:25:54
2015-03-05T18:54:09
2015-03-11T03:22:10
5,500
0
2
0
Java
null
null
package Tests; import android.app.Application; //import android.test.ActivityUnitTestCase; import android.test.ApplicationTestCase; import de.hdodenhof.circleimageview.CircleImageView; import shopping.with.friends.Adapters.PostListviewAdapter; import android.test.AndroidTestCase; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import shopping.with.friends.Adapters.PostListviewAdapter.Holder; import shopping.with.friends.MainActivity; import shopping.with.friends.Objects.Post; import android.content.Context; import java.util.ArrayList; /** * Created by andreahu on 4/1/15. */ public class PostViewItemsNotNullTest extends AndroidTestCase { // make sure the holders are not null // check the types of holder's data // instantiate new holder object private PostListviewAdapter plAdapter; public PostViewItemsNotNullTest() { super(); } /** * This is the main test method * @throws Exception */ @Override protected void setUp() throws Exception { super.setUp(); Context c = new MainActivity(); ArrayList<Post> posts = new ArrayList<Post>(); posts.add(new Post()); posts.add(new Post()); posts.add(new Post()); plAdapter = new PostListviewAdapter(c, posts); ViewGroup viewGroup = new ViewGroup(c) { @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { } }; plAdapter.getView(0, null, viewGroup); Holder testHolder = plAdapter.getHolder(); assertNotNull(testHolder); assertNotNull(plAdapter.getHolderDescription()); assertNotNull(plAdapter.getHolderImageView()); assertNotNull(plAdapter.getHolderPrice()); assertNotNull(plAdapter.getHolderProfilePicture()); assertNotNull(plAdapter.getHolderTitle()); } }
UTF-8
Java
1,924
java
PostViewItemsNotNullTest.java
Java
[ { "context": "t;\n\nimport java.util.ArrayList;\n\n/**\n * Created by andreahu on 4/1/15.\n */\npublic class PostViewItemsNotNullT", "end": 619, "score": 0.9964852333068848, "start": 611, "tag": "USERNAME", "value": "andreahu" } ]
null
[]
package Tests; import android.app.Application; //import android.test.ActivityUnitTestCase; import android.test.ApplicationTestCase; import de.hdodenhof.circleimageview.CircleImageView; import shopping.with.friends.Adapters.PostListviewAdapter; import android.test.AndroidTestCase; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import shopping.with.friends.Adapters.PostListviewAdapter.Holder; import shopping.with.friends.MainActivity; import shopping.with.friends.Objects.Post; import android.content.Context; import java.util.ArrayList; /** * Created by andreahu on 4/1/15. */ public class PostViewItemsNotNullTest extends AndroidTestCase { // make sure the holders are not null // check the types of holder's data // instantiate new holder object private PostListviewAdapter plAdapter; public PostViewItemsNotNullTest() { super(); } /** * This is the main test method * @throws Exception */ @Override protected void setUp() throws Exception { super.setUp(); Context c = new MainActivity(); ArrayList<Post> posts = new ArrayList<Post>(); posts.add(new Post()); posts.add(new Post()); posts.add(new Post()); plAdapter = new PostListviewAdapter(c, posts); ViewGroup viewGroup = new ViewGroup(c) { @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { } }; plAdapter.getView(0, null, viewGroup); Holder testHolder = plAdapter.getHolder(); assertNotNull(testHolder); assertNotNull(plAdapter.getHolderDescription()); assertNotNull(plAdapter.getHolderImageView()); assertNotNull(plAdapter.getHolderPrice()); assertNotNull(plAdapter.getHolderProfilePicture()); assertNotNull(plAdapter.getHolderTitle()); } }
1,924
0.695946
0.693347
61
30.540983
20.341005
82
false
false
0
0
0
0
0
0
0.655738
false
false
4
1417780c13fb6f4cc2baaebbf1166c10d3893398
11,768,210,424,605
59b52903ef7a0b77b92d7a06bdcd3518d5523ef1
/src/main/java/simpleboard/board/model/User.java
791101df4f3fbb2fb46e56cfed818c10bb6a95a3
[]
no_license
sungwoong-Noe/board
https://github.com/sungwoong-Noe/board
d91b7c0d8ad7e5ff37d52cc73e597398749ab97d
340b01cd1cbe53e3efaa94c280c8509968485fff
refs/heads/master
2023-06-25T05:02:54.184000
2021-07-25T13:05:47
2021-07-25T13:05:47
386,167,918
0
0
null
false
2021-07-18T09:16:35
2021-07-15T04:55:35
2021-07-17T16:57:14
2021-07-18T09:16:35
88
0
0
1
Java
false
false
package simpleboard.board.model; import lombok.Data; import javax.persistence.*; import java.util.ArrayList; import java.util.List; @Entity @Data public class User { //사용자 테이블 @Id @GeneratedValue(strategy = GenerationType.IDENTITY) //auto_increment를 사용하면 자동으로 게시글 번호가 증가 되도록 해주는 어노테이션 private Long id; private String username; private String password; private Boolean enabled; @ManyToMany @JoinTable( name = "user_role", //Join 테이블: user_role joinColumns = @JoinColumn(name = "user_id"), //user_role 테이블의 user_id inverseJoinColumns = @JoinColumn(name = "role_id") //role테이블의 role_id ) //Many to Many 매핑 하기 위해 JPA 사용, 리스트나 Set 사용 private List<Role> roles = new ArrayList<>(); //멤버 변수 생성, UserRepository를 이용해서 조회하면 권한정보가 roles에 자동으로 담기게 됨 }
UTF-8
Java
1,020
java
User.java
Java
[]
null
[]
package simpleboard.board.model; import lombok.Data; import javax.persistence.*; import java.util.ArrayList; import java.util.List; @Entity @Data public class User { //사용자 테이블 @Id @GeneratedValue(strategy = GenerationType.IDENTITY) //auto_increment를 사용하면 자동으로 게시글 번호가 증가 되도록 해주는 어노테이션 private Long id; private String username; private String password; private Boolean enabled; @ManyToMany @JoinTable( name = "user_role", //Join 테이블: user_role joinColumns = @JoinColumn(name = "user_id"), //user_role 테이블의 user_id inverseJoinColumns = @JoinColumn(name = "role_id") //role테이블의 role_id ) //Many to Many 매핑 하기 위해 JPA 사용, 리스트나 Set 사용 private List<Role> roles = new ArrayList<>(); //멤버 변수 생성, UserRepository를 이용해서 조회하면 권한정보가 roles에 자동으로 담기게 됨 }
1,020
0.661137
0.661137
31
26.225807
31.427038
113
false
false
0
0
0
0
0
0
0.451613
false
false
4
e287ca9aac004febd914f5f48a7f61fa5b09a9bd
25,933,012,551,583
a30aadf3c53ecdb160508ed39a4db49dbb2f7a45
/src/apkdownloader/DownloadBox.java
8b55b719729c6f3bad70fdb6a673b5e403251558
[]
no_license
Warik777/Real-APK-Leecher
https://github.com/Warik777/Real-APK-Leecher
53f8669668851a2329e0aaf23d4b8057f1232855
b5b3f54d8f2f5476d25040b9a79b00cc421a1953
refs/heads/master
2020-04-06T03:40:37.336000
2015-04-26T16:19:40
2015-04-26T16:19:40
20,902,202
4
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * DownloadBox.java * * Created on Mar 8, 2012, 1:57:52 PM */ package apkdownloader; import apkdownloader.dao.ConvertURL; import apkdownloader.dao.ListAppsDAO; import java.awt.Image; import java.awt.Toolkit; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import javax.swing.JFrame; import javax.swing.SwingWorker; /** * * @author CodeBlue */ public class DownloadBox extends JFrame{ private String appId; private String title; private String version; public static ArrayList<Task> downloads = new ArrayList(); ListAppsDAO appDao; private int index; private Task download; /** Creates new form DownloadBox */ public DownloadBox(String appId, String title, String version) { initComponents(); Image icon = getToolkit().getImage(getClass().getResource("/images/download.png")); setIconImage(icon); this.appId = appId; title = ConvertURL.toUrlFriendly(title).replaceAll(":", " -").replaceAll("/", " - "); this.version = version; int type = APKDownloaderApp.config.getFormatFileType(); if (type == 1 || type == 3) { this.title = title + ".apk"; } else { this.title = title + " v" + this.version + ".apk"; } lbFilename.setText(this.title); startDownload(); } private void startDownload() { appDao = new ListAppsDAO(); download = new Task(); downloads.add(download); this.index = downloads.lastIndexOf(download); download.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { if ("progress".equals(evt.getPropertyName())) { if (download.isCancelled()) { btnCancel.setEnabled(false); setTitle("Загрузка отменена"); } int progress = (Integer) evt.getNewValue(); if (progress == 100) { setTitle("Загрузка прошла успешно!"); } pbDownload.setValue(progress); txtPercent.setText(progress + "%"); } } }); download.execute(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); pbDownload = new javax.swing.JProgressBar(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); lbFilename = new javax.swing.JLabel(); btnHide = new org.jdesktop.swingx.JXButton(); btnCancel = new org.jdesktop.swingx.JXButton(); txtPercent = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance().getContext().getResourceMap(DownloadBox.class); setTitle(resourceMap.getString("Form.title")); // NOI18N setName("Form"); // NOI18N setResizable(false); jPanel1.setBackground(resourceMap.getColor("jPanel1.background")); // NOI18N jPanel1.setName("jPanel1"); // NOI18N pbDownload.setName("pbDownload"); // NOI18N jLabel1.setIcon(resourceMap.getIcon("jLabel1.icon")); // NOI18N jLabel1.setName("jLabel1"); // NOI18N jLabel2.setForeground(resourceMap.getColor("jLabel2.foreground")); // NOI18N jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N jLabel2.setName("jLabel2"); // NOI18N lbFilename.setForeground(resourceMap.getColor("lbFilename.foreground")); // NOI18N lbFilename.setText(resourceMap.getString("lbFilename.text")); // NOI18N lbFilename.setName("lbFilename"); // NOI18N btnHide.setText(resourceMap.getString("btnHide.text")); // NOI18N btnHide.setName("btnHide"); // NOI18N btnHide.setPreferredSize(new java.awt.Dimension(65, 23)); btnHide.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnHideActionPerformed(evt); } }); btnCancel.setText(resourceMap.getString("btnCancel.text")); // NOI18N btnCancel.setName("btnCancel"); // NOI18N btnCancel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnCancelActionPerformed(evt); } }); txtPercent.setForeground(resourceMap.getColor("txtPercent.foreground")); // NOI18N txtPercent.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); txtPercent.setText(resourceMap.getString("txtPercent.text")); // NOI18N txtPercent.setName("txtPercent"); // NOI18N javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(btnCancel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 97, Short.MAX_VALUE) .addComponent(btnHide, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(pbDownload, javax.swing.GroupLayout.DEFAULT_SIZE, 246, Short.MAX_VALUE) .addComponent(txtPercent, javax.swing.GroupLayout.DEFAULT_SIZE, 246, Short.MAX_VALUE) .addComponent(lbFilename, javax.swing.GroupLayout.DEFAULT_SIZE, 246, Short.MAX_VALUE) .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 246, Short.MAX_VALUE)) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap(14, Short.MAX_VALUE) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(lbFilename) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtPercent) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(pbDownload, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(11, 11, 11) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnCancel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnHide, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel1) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btnHideActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnHideActionPerformed // TODO add your handling code here: dispose(); }//GEN-LAST:event_btnHideActionPerformed private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed // TODO add your handling code here: download.cancel(true); }//GEN-LAST:event_btnCancelActionPerformed public class Task extends SwingWorker<Void, Void> { @Override public Void doInBackground() { setProgress(0); appDao.appDownload(appId, title, index); return null; } @Override public void done() { if (!isCancelled()) { Toolkit.getDefaultToolkit().beep(); btnCancel.setEnabled(false); } } } // Variables declaration - do not modify//GEN-BEGIN:variables private org.jdesktop.swingx.JXButton btnCancel; private org.jdesktop.swingx.JXButton btnHide; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JPanel jPanel1; private javax.swing.JLabel lbFilename; private javax.swing.JProgressBar pbDownload; private javax.swing.JLabel txtPercent; // End of variables declaration//GEN-END:variables }
UTF-8
Java
10,643
java
DownloadBox.java
Java
[ { "context": "import javax.swing.SwingWorker;\n\n/**\n *\n * @author CodeBlue\n */\npublic class DownloadBox extends JFrame{\n pr", "end": 511, "score": 0.9995632171630859, "start": 503, "tag": "USERNAME", "value": "CodeBlue" } ]
null
[]
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * DownloadBox.java * * Created on Mar 8, 2012, 1:57:52 PM */ package apkdownloader; import apkdownloader.dao.ConvertURL; import apkdownloader.dao.ListAppsDAO; import java.awt.Image; import java.awt.Toolkit; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import javax.swing.JFrame; import javax.swing.SwingWorker; /** * * @author CodeBlue */ public class DownloadBox extends JFrame{ private String appId; private String title; private String version; public static ArrayList<Task> downloads = new ArrayList(); ListAppsDAO appDao; private int index; private Task download; /** Creates new form DownloadBox */ public DownloadBox(String appId, String title, String version) { initComponents(); Image icon = getToolkit().getImage(getClass().getResource("/images/download.png")); setIconImage(icon); this.appId = appId; title = ConvertURL.toUrlFriendly(title).replaceAll(":", " -").replaceAll("/", " - "); this.version = version; int type = APKDownloaderApp.config.getFormatFileType(); if (type == 1 || type == 3) { this.title = title + ".apk"; } else { this.title = title + " v" + this.version + ".apk"; } lbFilename.setText(this.title); startDownload(); } private void startDownload() { appDao = new ListAppsDAO(); download = new Task(); downloads.add(download); this.index = downloads.lastIndexOf(download); download.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { if ("progress".equals(evt.getPropertyName())) { if (download.isCancelled()) { btnCancel.setEnabled(false); setTitle("Загрузка отменена"); } int progress = (Integer) evt.getNewValue(); if (progress == 100) { setTitle("Загрузка прошла успешно!"); } pbDownload.setValue(progress); txtPercent.setText(progress + "%"); } } }); download.execute(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); pbDownload = new javax.swing.JProgressBar(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); lbFilename = new javax.swing.JLabel(); btnHide = new org.jdesktop.swingx.JXButton(); btnCancel = new org.jdesktop.swingx.JXButton(); txtPercent = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance().getContext().getResourceMap(DownloadBox.class); setTitle(resourceMap.getString("Form.title")); // NOI18N setName("Form"); // NOI18N setResizable(false); jPanel1.setBackground(resourceMap.getColor("jPanel1.background")); // NOI18N jPanel1.setName("jPanel1"); // NOI18N pbDownload.setName("pbDownload"); // NOI18N jLabel1.setIcon(resourceMap.getIcon("jLabel1.icon")); // NOI18N jLabel1.setName("jLabel1"); // NOI18N jLabel2.setForeground(resourceMap.getColor("jLabel2.foreground")); // NOI18N jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N jLabel2.setName("jLabel2"); // NOI18N lbFilename.setForeground(resourceMap.getColor("lbFilename.foreground")); // NOI18N lbFilename.setText(resourceMap.getString("lbFilename.text")); // NOI18N lbFilename.setName("lbFilename"); // NOI18N btnHide.setText(resourceMap.getString("btnHide.text")); // NOI18N btnHide.setName("btnHide"); // NOI18N btnHide.setPreferredSize(new java.awt.Dimension(65, 23)); btnHide.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnHideActionPerformed(evt); } }); btnCancel.setText(resourceMap.getString("btnCancel.text")); // NOI18N btnCancel.setName("btnCancel"); // NOI18N btnCancel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnCancelActionPerformed(evt); } }); txtPercent.setForeground(resourceMap.getColor("txtPercent.foreground")); // NOI18N txtPercent.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); txtPercent.setText(resourceMap.getString("txtPercent.text")); // NOI18N txtPercent.setName("txtPercent"); // NOI18N javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(btnCancel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 97, Short.MAX_VALUE) .addComponent(btnHide, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(pbDownload, javax.swing.GroupLayout.DEFAULT_SIZE, 246, Short.MAX_VALUE) .addComponent(txtPercent, javax.swing.GroupLayout.DEFAULT_SIZE, 246, Short.MAX_VALUE) .addComponent(lbFilename, javax.swing.GroupLayout.DEFAULT_SIZE, 246, Short.MAX_VALUE) .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 246, Short.MAX_VALUE)) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap(14, Short.MAX_VALUE) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(lbFilename) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtPercent) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(pbDownload, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(11, 11, 11) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnCancel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnHide, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel1) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btnHideActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnHideActionPerformed // TODO add your handling code here: dispose(); }//GEN-LAST:event_btnHideActionPerformed private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed // TODO add your handling code here: download.cancel(true); }//GEN-LAST:event_btnCancelActionPerformed public class Task extends SwingWorker<Void, Void> { @Override public Void doInBackground() { setProgress(0); appDao.appDownload(appId, title, index); return null; } @Override public void done() { if (!isCancelled()) { Toolkit.getDefaultToolkit().beep(); btnCancel.setEnabled(false); } } } // Variables declaration - do not modify//GEN-BEGIN:variables private org.jdesktop.swingx.JXButton btnCancel; private org.jdesktop.swingx.JXButton btnHide; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JPanel jPanel1; private javax.swing.JLabel lbFilename; private javax.swing.JProgressBar pbDownload; private javax.swing.JLabel txtPercent; // End of variables declaration//GEN-END:variables }
10,643
0.656987
0.645012
235
44.136169
35.857262
166
false
false
0
0
0
0
0
0
0.67234
false
false
4
2d0f5d30f85013205b9972a92e9f72c1779e6f45
29,102,698,412,655
1d5c3f565c9f66a0b94eaeb7f7dc156e7f33582e
/src/test/java/ui/StartVisaApplicationUIPage.java
b47e6e2e3322e122b32a8b6b42754a117841cba8
[]
no_license
shilpabasu22/Serenity-HO
https://github.com/shilpabasu22/Serenity-HO
f83ebde6a0ef07eab6e7e7a65fed57998e4342f3
ce4f584e57949f4c2a2656dc05d872c6ecf1c1ac
refs/heads/master
2023-07-29T18:46:37.628000
2020-07-13T08:05:36
2020-07-13T08:05:36
406,730,615
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ui; import net.serenitybdd.core.annotations.findby.By; import net.serenitybdd.core.pages.PageObject; import net.thucydides.core.annotations.DefaultUrl; import net.thucydides.core.annotations.Managed; import org.junit.Assert; @DefaultUrl("https://www.gov.uk/check-uk-visa") public class StartVisaApplicationUIPage extends PageObject { public void checkVisaStartPageTitle(){ String pageTitle = $(By.className("gem-c-title__text")).getText(); Assert.assertTrue("Page Title matches",pageTitle.equalsIgnoreCase("Check if you need a UK visa")); $(By.xpath("//button[@class='gem-c-button govuk-button gem-c-button--inline']")).click(); } public void clickStartButton(){ $(By.linkText("Start now")).click(); } }
UTF-8
Java
766
java
StartVisaApplicationUIPage.java
Java
[]
null
[]
package ui; import net.serenitybdd.core.annotations.findby.By; import net.serenitybdd.core.pages.PageObject; import net.thucydides.core.annotations.DefaultUrl; import net.thucydides.core.annotations.Managed; import org.junit.Assert; @DefaultUrl("https://www.gov.uk/check-uk-visa") public class StartVisaApplicationUIPage extends PageObject { public void checkVisaStartPageTitle(){ String pageTitle = $(By.className("gem-c-title__text")).getText(); Assert.assertTrue("Page Title matches",pageTitle.equalsIgnoreCase("Check if you need a UK visa")); $(By.xpath("//button[@class='gem-c-button govuk-button gem-c-button--inline']")).click(); } public void clickStartButton(){ $(By.linkText("Start now")).click(); } }
766
0.718016
0.718016
23
32.304348
31.509052
106
false
false
0
0
0
0
0
0
0.478261
false
false
4
4c88d3ebb882a80f2241705dc680317559031713
12,223,476,939,939
1fcc575411c39fd60dea4898516b459ccf143d0b
/src/main/java/com/example/GameServer/controller/UserController.java
63fe63d9933108fedd0734915f1dcedb631ff7ef
[]
no_license
RacNor/ShitiestBackEnd
https://github.com/RacNor/ShitiestBackEnd
1020f8928e45ba0afec408e76d9ef08c36e6e179
d46731d07bbf526b01357949e34f83de535f73a4
refs/heads/master
2020-04-06T15:27:47.638000
2018-11-28T21:08:56
2018-11-28T21:08:56
157,579,325
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.GameServer.controller; import com.example.GameServer.model.User; import com.example.GameServer.service.Facade; import com.example.GameServer.service.UserService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequestMapping(value="api/user") public class UserController { private Logger logger = LoggerFactory.getLogger(UserController.class); @Autowired UserService userservice; @GetMapping("/{user_id}") public ResponseEntity<User> getQuizByCode(@PathVariable Long user_id) { logger.debug("get User with id: {}", user_id); User user = userservice.finByCode(user_id); logger.debug("User found: {}", user); if (user != null) { return new ResponseEntity<>(user, HttpStatus.OK); } else { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } } @GetMapping public ResponseEntity<List<User>> getUsers(){ logger.debug("get Users: {}"); List<User> users = userservice.getUsers(); logger.debug("Users found: {}", users); return new ResponseEntity<>(users,HttpStatus.OK); } }
UTF-8
Java
1,585
java
UserController.java
Java
[]
null
[]
package com.example.GameServer.controller; import com.example.GameServer.model.User; import com.example.GameServer.service.Facade; import com.example.GameServer.service.UserService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequestMapping(value="api/user") public class UserController { private Logger logger = LoggerFactory.getLogger(UserController.class); @Autowired UserService userservice; @GetMapping("/{user_id}") public ResponseEntity<User> getQuizByCode(@PathVariable Long user_id) { logger.debug("get User with id: {}", user_id); User user = userservice.finByCode(user_id); logger.debug("User found: {}", user); if (user != null) { return new ResponseEntity<>(user, HttpStatus.OK); } else { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } } @GetMapping public ResponseEntity<List<User>> getUsers(){ logger.debug("get Users: {}"); List<User> users = userservice.getUsers(); logger.debug("Users found: {}", users); return new ResponseEntity<>(users,HttpStatus.OK); } }
1,585
0.722397
0.721136
47
32.723404
23.313499
75
false
false
0
0
0
0
0
0
0.638298
false
false
4
444710995ea9b394a1866b9e136f87c42bf7001b
32,633,161,530,233
a881668be7451d5ee6d8e6e45fdaa6d5b88870ef
/hausaufgabe/CopyStrategie.java
7b2bd8d301588f1faa45eb3324f979e1ee3ccd8b
[]
no_license
internerz/SE_Entwurfsmuster_Strategie
https://github.com/internerz/SE_Entwurfsmuster_Strategie
1194c35bd8e7388376ebfa5f82e83df7b1f42a5f
219a37e77cefc8a60e34341c27daaf86534bed5a
refs/heads/master
2021-01-25T08:37:35.329000
2015-06-24T18:25:16
2015-06-24T18:25:16
38,002,866
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package hausaufgabe; public class CopyStrategie implements MusterStragegie { public String encrypt(String input) { return input; } public String decrypt(String input) { return input; } }
UTF-8
Java
199
java
CopyStrategie.java
Java
[]
null
[]
package hausaufgabe; public class CopyStrategie implements MusterStragegie { public String encrypt(String input) { return input; } public String decrypt(String input) { return input; } }
199
0.748744
0.748744
13
14.307693
17.782379
55
false
false
0
0
0
0
0
0
0.846154
false
false
4
93decc97f56d8112c95db708ed4661d36f010c40
32,444,182,971,195
183f640b0ab6a6da85da1b09290965618083d874
/modules/host-webapp/src/main/java/org/apache/tuscany/sca/host/webapp/HotUpdateContextListener.java
d7ff73e31f3eb1131993b764575fc70ea0b53dc1
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
apache/tuscany-sca-1.x
https://github.com/apache/tuscany-sca-1.x
8543e4434f4d8650630bddf26b040d48aee789e9
3eb5a6521521398d167f32da995c868ac545163b
refs/heads/trunk
2023-09-04T10:37:39.056000
2011-12-14T12:09:11
2011-12-14T12:09:11
390,001
4
18
null
false
2023-08-29T21:44:23
2009-11-30T09:00:10
2023-06-23T05:04:37
2023-08-29T21:44:23
65,980
2
10
109
Java
false
false
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.apache.tuscany.sca.host.webapp; import java.io.File; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import org.apache.tuscany.sca.host.embedded.impl.HotUpdatableSCADomain; /** * A WebApp ContextListener that starts a Tuscany runtime supporting multiple * SCA contribution jars. All contribution jars found in the repository * directory named "sca-contributions" will be contributed to the SCA * domain. Any changes to the contributions in the repository will be * automatically detected and the SCADomain updated accordingly. * * @version $Rev$ $Date$ */ public class HotUpdateContextListener extends TuscanyContextListener { public static final String REPOSITORY_FOLDER_NAME = "sca-contributions"; @Override public void contextInitialized(ServletContextEvent event) { ServletContext servletContext = event.getServletContext(); // TODO better domaiURI, maybe based on webapp name? String domainURI = "http://localhost/" + servletContext.getServletContextName().replace(' ', '.'); File repository = new File(servletContext.getRealPath(REPOSITORY_FOLDER_NAME)); HotUpdatableSCADomain scaDomain = new HotUpdatableSCADomain(domainURI, repository, 2000); servletContext.setAttribute(SCADomainHelper.SCA_DOMAIN_ATTRIBUTE, scaDomain); super.contextInitialized(event); } }
UTF-8
Java
2,241
java
HotUpdateContextListener.java
Java
[]
null
[]
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.apache.tuscany.sca.host.webapp; import java.io.File; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import org.apache.tuscany.sca.host.embedded.impl.HotUpdatableSCADomain; /** * A WebApp ContextListener that starts a Tuscany runtime supporting multiple * SCA contribution jars. All contribution jars found in the repository * directory named "sca-contributions" will be contributed to the SCA * domain. Any changes to the contributions in the repository will be * automatically detected and the SCADomain updated accordingly. * * @version $Rev$ $Date$ */ public class HotUpdateContextListener extends TuscanyContextListener { public static final String REPOSITORY_FOLDER_NAME = "sca-contributions"; @Override public void contextInitialized(ServletContextEvent event) { ServletContext servletContext = event.getServletContext(); // TODO better domaiURI, maybe based on webapp name? String domainURI = "http://localhost/" + servletContext.getServletContextName().replace(' ', '.'); File repository = new File(servletContext.getRealPath(REPOSITORY_FOLDER_NAME)); HotUpdatableSCADomain scaDomain = new HotUpdatableSCADomain(domainURI, repository, 2000); servletContext.setAttribute(SCADomainHelper.SCA_DOMAIN_ATTRIBUTE, scaDomain); super.contextInitialized(event); } }
2,241
0.746542
0.742972
57
38.315788
32.15432
106
false
false
0
0
0
0
0
0
0.385965
false
false
4
1eaacc814dd7a98aed426f604290ea74e6c38cbc
32,444,182,968,940
1674e12698dfcee79f24313ffdf7b9e52fd267d5
/doma-it/src/main/java/org/seasar/doma/it/dao/ScriptDao.java
93ec983045649e609086a45cd68ba88c74d1247a
[ "Apache-2.0" ]
permissive
gakuzzzz/doma
https://github.com/gakuzzzz/doma
2bc0bb1a0ad58ef3e5fe91dfae7a314a6c287337
95a8704d1fe816937ef8fe976ded0de60c82faf1
refs/heads/master
2020-05-29T12:18:45.351000
2014-01-22T13:47:47
2014-01-22T13:47:47
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.seasar.doma.it.dao; import org.seasar.doma.AccessLevel; import org.seasar.doma.Dao; import org.seasar.doma.Script; import org.seasar.doma.it.ItConfig; @Dao(config = ItConfig.class, accessLevel = AccessLevel.PACKAGE) public interface ScriptDao { static ScriptDao get() { return new ScriptDaoImpl(); } @Script void create(); @Script(haltOnError = false) void drop(); }
UTF-8
Java
436
java
ScriptDao.java
Java
[]
null
[]
package org.seasar.doma.it.dao; import org.seasar.doma.AccessLevel; import org.seasar.doma.Dao; import org.seasar.doma.Script; import org.seasar.doma.it.ItConfig; @Dao(config = ItConfig.class, accessLevel = AccessLevel.PACKAGE) public interface ScriptDao { static ScriptDao get() { return new ScriptDaoImpl(); } @Script void create(); @Script(haltOnError = false) void drop(); }
436
0.669725
0.669725
20
19.799999
17.086838
64
false
false
0
0
0
0
0
0
0.45
false
false
4
c17889e12be9f1c86e4703ebf5d6265979055da0
26,628,797,257,596
fab21ae6505fed694808a5eb8063edde3811f246
/app/src/main/java/br/com/ilegratest/jnitest/output/Premio.java
642c8ecde869d3a06e5ea11a52bd2ec2973c1433
[]
no_license
gbizotto/JniTest
https://github.com/gbizotto/JniTest
c5f01af4f65453f23467ba5ccb03d0498fe8a262
70dc1f4ce3c9b4103ed2d1a56d5a9ce121989d9a
refs/heads/master
2020-06-17T16:52:34.248000
2016-12-12T20:19:02
2016-12-12T20:19:44
74,988,253
0
0
null
true
2016-11-28T15:47:33
2016-11-28T15:47:32
2016-11-08T20:48:00
2016-11-10T15:43:22
26,371
0
0
0
null
null
null
package br.com.ilegratest.jnitest.output; /** * Created by gabrielabizotto on 12/12/16. */ public class Premio { private CalculosVida calculosVida; /** * * @return * The calculosVida */ public CalculosVida getCalculosVida() { return calculosVida; } /** * * @param calculosVida * The calculosVida */ public void setCalculosVida(CalculosVida calculosVida) { this.calculosVida = calculosVida; } @Override public String toString() { return "Premio{" + "calculosVida=" + calculosVida + '}'; } }
UTF-8
Java
633
java
Premio.java
Java
[ { "context": ".com.ilegratest.jnitest.output;\n\n/**\n * Created by gabrielabizotto on 12/12/16.\n */\n\npublic class Premio {\n priva", "end": 76, "score": 0.9986383318901062, "start": 61, "tag": "USERNAME", "value": "gabrielabizotto" } ]
null
[]
package br.com.ilegratest.jnitest.output; /** * Created by gabrielabizotto on 12/12/16. */ public class Premio { private CalculosVida calculosVida; /** * * @return * The calculosVida */ public CalculosVida getCalculosVida() { return calculosVida; } /** * * @param calculosVida * The calculosVida */ public void setCalculosVida(CalculosVida calculosVida) { this.calculosVida = calculosVida; } @Override public String toString() { return "Premio{" + "calculosVida=" + calculosVida + '}'; } }
633
0.56872
0.559242
34
17.617647
16.655708
60
false
false
0
0
0
0
0
0
0.147059
false
false
4
03923f7d4cdb4339d8f5ca65f577067bbfd8d639
31,499,290,167,668
a26c717dd29731af9a81391edec16b19120c043f
/src/test/java/za/co/mwongho/localstack/AwsS3Test.java
ee5e424ece525568128bc6d84a2e9f221d0ee866
[]
no_license
mwongho/localstack
https://github.com/mwongho/localstack
962741c80245b39fa603502650bc19ef4e5a203e
deb2fa8f126e199bae2907cae176ff5573fcfe31
refs/heads/master
2022-04-18T17:52:10.998000
2020-04-18T12:37:29
2020-04-18T12:37:29
256,746,421
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package za.co.mwongho.localstack; import com.amazonaws.services.s3.model.PutObjectResult; import com.amazonaws.services.s3.model.S3ObjectSummary; import org.junit.jupiter.api.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mock.web.MockMultipartFile; import za.co.mwongho.aws.s3.service.AmazonS3ClientService; import java.io.IOException; import java.util.List; @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class AwsS3Test extends LocalStackTest { @Autowired private AmazonS3ClientService amazonS3ClientService; @Test @Order(1) public void uploadFile() throws IOException { MockMultipartFile mockMultipartFile = new MockMultipartFile("file", "test.txt", "text/plain", "Test text".getBytes()); PutObjectResult putObjectResult = this.amazonS3ClientService.uploadFile(mockMultipartFile, true); Assertions.assertNotNull(putObjectResult); } @Test @Order(2) public void listAllTest() { List<S3ObjectSummary> s3ObjectSummaries = this.amazonS3ClientService.listAll(); Assertions.assertNotNull(s3ObjectSummaries); Assertions.assertFalse(s3ObjectSummaries.isEmpty()); } }
UTF-8
Java
1,216
java
AwsS3Test.java
Java
[]
null
[]
package za.co.mwongho.localstack; import com.amazonaws.services.s3.model.PutObjectResult; import com.amazonaws.services.s3.model.S3ObjectSummary; import org.junit.jupiter.api.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mock.web.MockMultipartFile; import za.co.mwongho.aws.s3.service.AmazonS3ClientService; import java.io.IOException; import java.util.List; @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class AwsS3Test extends LocalStackTest { @Autowired private AmazonS3ClientService amazonS3ClientService; @Test @Order(1) public void uploadFile() throws IOException { MockMultipartFile mockMultipartFile = new MockMultipartFile("file", "test.txt", "text/plain", "Test text".getBytes()); PutObjectResult putObjectResult = this.amazonS3ClientService.uploadFile(mockMultipartFile, true); Assertions.assertNotNull(putObjectResult); } @Test @Order(2) public void listAllTest() { List<S3ObjectSummary> s3ObjectSummaries = this.amazonS3ClientService.listAll(); Assertions.assertNotNull(s3ObjectSummaries); Assertions.assertFalse(s3ObjectSummaries.isEmpty()); } }
1,216
0.768092
0.754934
34
34.764706
31.567909
126
false
false
0
0
0
0
0
0
0.588235
false
false
4
f82f951799c06915b953113cb210c1a48ae0cc39
23,115,514,005,930
671e467f78f73aa994a614b03f21e048f12e0ce2
/app/src/main/java/com/mlxing/mlguide/activity/BaseActivity.java
1fb85bd87ffb5386d504f08ac4ad965f9c1c21d3
[]
no_license
sudot/MLguide
https://github.com/sudot/MLguide
3a515a136b55c326a5ffc396ea0a7b75fe7957f6
85c2b72398c4b84b0af368b5e7e8ea6bd70e70d0
refs/heads/master
2021-05-13T21:31:29.031000
2018-01-06T12:04:53
2018-01-06T12:04:53
116,465,599
0
0
null
true
2018-01-06T08:03:36
2018-01-06T08:03:36
2017-12-29T07:32:59
2016-07-11T04:12:02
1,902
0
0
0
null
false
null
package com.mlxing.mlguide.activity; import android.content.Intent; import android.support.v7.app.AppCompatActivity; /** * Created by quan on 2016/6/18. */ public class BaseActivity extends AppCompatActivity { protected void goTo(Class<?> activity) { if (activity.getSimpleName().equals(this.getClass().getSimpleName())) { return; } startActivity(new Intent(this, activity)); } }
UTF-8
Java
431
java
BaseActivity.java
Java
[ { "context": "pport.v7.app.AppCompatActivity;\n\n/**\n * Created by quan on 2016/6/18.\n */\npublic class BaseActivity exten", "end": 141, "score": 0.9955786466598511, "start": 137, "tag": "USERNAME", "value": "quan" } ]
null
[]
package com.mlxing.mlguide.activity; import android.content.Intent; import android.support.v7.app.AppCompatActivity; /** * Created by quan on 2016/6/18. */ public class BaseActivity extends AppCompatActivity { protected void goTo(Class<?> activity) { if (activity.getSimpleName().equals(this.getClass().getSimpleName())) { return; } startActivity(new Intent(this, activity)); } }
431
0.677494
0.658933
19
21.68421
23.577538
79
false
false
0
0
0
0
0
0
0.315789
false
false
4
e3fea7b3890e8a016aa9ff1eef56a84acee68c68
7,602,092,169,627
8315b7456d7819ba36cfe6a12e3b67819fd327b9
/unisinos-dev3-sistemapdv-api/src/main/java/br/unisinos/sistemapdv/application/service/impl/PrevendaServiceImpl.java
702ac8bdb97bee7b15a536aaa78d2e220bb2050b
[]
no_license
lfaitao/unisinos-dev3-sistemapdv
https://github.com/lfaitao/unisinos-dev3-sistemapdv
aa36319b9966b51b2cb2df213866d46d47bee3e9
87a70f52d22edaaed55aefbfb38623d313867de8
refs/heads/master
2021-01-23T01:01:52.923000
2017-06-21T14:32:18
2017-06-21T14:32:18
85,864,597
2
2
null
false
2017-06-20T01:33:39
2017-03-22T18:51:38
2017-04-05T21:43:37
2017-06-20T01:33:39
1,533
1
0
0
Java
null
null
package br.unisinos.sistemapdv.application.service.impl; import br.unisinos.sistemapdv.application.service.PreVendaService; public class PrevendaServiceImpl implements PreVendaService { }
UTF-8
Java
190
java
PrevendaServiceImpl.java
Java
[]
null
[]
package br.unisinos.sistemapdv.application.service.impl; import br.unisinos.sistemapdv.application.service.PreVendaService; public class PrevendaServiceImpl implements PreVendaService { }
190
0.857895
0.857895
6
30.666666
30.47221
66
false
false
0
0
0
0
0
0
0.333333
false
false
4
88dd3c81101145d18a9c3824465a23219c42f6bb
7,567,732,422,521
013caad9818dd06ab1c3dd5446d3693f6b297b15
/src/main/java/com/luxondata/test/component/response/ResponseBody.java
13e8433e030dd1ddd1e5c1dac36c9132082984c2
[]
no_license
baigx-git/test
https://github.com/baigx-git/test
a84d77dd7750cf98cee3b5f526062d3ac6b9ada4
6f2bcfaa38993587ec942a230fc8891469cbf274
refs/heads/main
2021-06-25T18:23:27.660000
2021-03-01T10:09:04
2021-03-01T10:09:04
204,835,441
0
0
null
false
2020-10-13T15:38:08
2019-08-28T02:56:31
2019-08-28T09:01:43
2020-10-13T15:38:07
11
0
0
1
Java
false
false
package com.luxondata.test.component.response; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.luxondata.test.common.enums.ErrorEnum; import com.luxondata.test.vo.Result; import lombok.extern.slf4j.Slf4j; import org.springframework.core.MethodParameter; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; @ControllerAdvice(basePackages = "com.luxondata.test") @Slf4j public class ResponseBody implements ResponseBodyAdvice<Object> { @Override public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) { return returnType.getParameterType() != Result.class; } @Override public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) { Result<Object> result = new Result<>(); result.setCode(200); result.setMessage("操作成功"); result.setData(body); if (body instanceof String) { ObjectMapper o = new ObjectMapper(); try { return o.writeValueAsString(result); } catch (JsonProcessingException e) { e.printStackTrace(); } } return result; } }
UTF-8
Java
1,722
java
ResponseBody.java
Java
[]
null
[]
package com.luxondata.test.component.response; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.luxondata.test.common.enums.ErrorEnum; import com.luxondata.test.vo.Result; import lombok.extern.slf4j.Slf4j; import org.springframework.core.MethodParameter; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; @ControllerAdvice(basePackages = "com.luxondata.test") @Slf4j public class ResponseBody implements ResponseBodyAdvice<Object> { @Override public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) { return returnType.getParameterType() != Result.class; } @Override public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) { Result<Object> result = new Result<>(); result.setCode(200); result.setMessage("操作成功"); result.setData(body); if (body instanceof String) { ObjectMapper o = new ObjectMapper(); try { return o.writeValueAsString(result); } catch (JsonProcessingException e) { e.printStackTrace(); } } return result; } }
1,722
0.743874
0.740373
43
38.813953
38.851089
227
false
false
0
0
0
0
0
0
0.651163
false
false
4
f9d78f78ead176abae91be256094de136943e37c
1,099,511,690,197
80f1b4f6a3fdf2ffdc6d01f3d6877ff530726f34
/app/src/main/java/ch/heiafr/entertainme/recycler/ActorRecyclerViewAdapter.java
d7af3a607a4a9507ed259e2ae64f6b3cdb6231b3
[]
no_license
Lucalborghetti/entertain-me
https://github.com/Lucalborghetti/entertain-me
5e05dd0a5c6a2bcc9bd69efab00afc36a75bc5a3
10bf0828c6a915b0c2ccf0b69aaf4ae0988f51f4
refs/heads/master
2020-03-28T15:57:58.922000
2018-09-13T14:19:07
2018-09-13T14:19:07
148,644,269
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ch.heiafr.entertainme.recycler; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.squareup.picasso.Picasso; import java.util.ArrayList; import java.util.Random; import ch.heiafr.entertainme.R; import ch.heiafr.entertainme.beans.Actor; import ch.heiafr.entertainme.media.MediaListManager; public class ActorRecyclerViewAdapter extends RecyclerView.Adapter<ActorRecyclerViewAdapter.ViewHolder> { private ArrayList<Actor> actors = new ArrayList<>(); private static Random r = new Random(); private Context context; public static class ViewHolder extends RecyclerView.ViewHolder { public ImageView profile; public TextView actorName; public TextView characterName; public ViewHolder(View v) { super(v); profile = (ImageView) v.findViewById(R.id.profile); actorName = (TextView) v.findViewById(R.id.actorName); characterName = (TextView) v.findViewById(R.id.characterName); } } public ActorRecyclerViewAdapter(ArrayList<Actor> actors, Context context) { this.actors = actors; this.context = context; } @Override public ActorRecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.actor_cell_layout, parent, false); ViewHolder vh = new ViewHolder(v); return vh; } @Override public void onBindViewHolder(ViewHolder holder, int position) { Actor a = actors.get(position); holder.actorName.setText(a.getName()); holder.characterName.setText(a.getCharacter()); String imageUrl = MediaListManager.IMAGE_BASE_URL + a.getProfile_path(); Picasso.with(context).load(imageUrl).into(holder.profile); } @Override public int getItemCount() { return actors.size(); } }
UTF-8
Java
2,104
java
ActorRecyclerViewAdapter.java
Java
[]
null
[]
package ch.heiafr.entertainme.recycler; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.squareup.picasso.Picasso; import java.util.ArrayList; import java.util.Random; import ch.heiafr.entertainme.R; import ch.heiafr.entertainme.beans.Actor; import ch.heiafr.entertainme.media.MediaListManager; public class ActorRecyclerViewAdapter extends RecyclerView.Adapter<ActorRecyclerViewAdapter.ViewHolder> { private ArrayList<Actor> actors = new ArrayList<>(); private static Random r = new Random(); private Context context; public static class ViewHolder extends RecyclerView.ViewHolder { public ImageView profile; public TextView actorName; public TextView characterName; public ViewHolder(View v) { super(v); profile = (ImageView) v.findViewById(R.id.profile); actorName = (TextView) v.findViewById(R.id.actorName); characterName = (TextView) v.findViewById(R.id.characterName); } } public ActorRecyclerViewAdapter(ArrayList<Actor> actors, Context context) { this.actors = actors; this.context = context; } @Override public ActorRecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.actor_cell_layout, parent, false); ViewHolder vh = new ViewHolder(v); return vh; } @Override public void onBindViewHolder(ViewHolder holder, int position) { Actor a = actors.get(position); holder.actorName.setText(a.getName()); holder.characterName.setText(a.getCharacter()); String imageUrl = MediaListManager.IMAGE_BASE_URL + a.getProfile_path(); Picasso.with(context).load(imageUrl).into(holder.profile); } @Override public int getItemCount() { return actors.size(); } }
2,104
0.708175
0.7077
66
30.878788
27.84128
109
false
false
0
0
0
0
0
0
0.606061
false
false
4
2ff06ea34572329a1675ea1dd992cd55edafcbb4
2,379,411,919,920
c3c8a33387e4ddef8e86df7e35eb29229e6bfa6d
/src/test/java/ServicesTest/MoveHorizontalTest.java
bd4e6abfa5d8e6cb4a5cebf961efe55aa3d79b64
[]
no_license
KeerthiTejaN/GameMaker
https://github.com/KeerthiTejaN/GameMaker
3a2eff2e22b2318b64f26e7a956b911ff502d0e8
eb6fc5dfef7e6ebc44e7190acfef7fa58e8d180c
refs/heads/master
2021-01-10T18:26:39.129000
2016-11-11T19:21:24
2016-11-11T19:21:24
73,501,501
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ServicesTest; import static org.mockito.Mockito.mock; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import helpers.Constants; import models.Ball; import services.Bounce; import services.MoveHorizontal; public class MoveHorizontalTest { MoveHorizontal moveHorizontal; @Before public void setUp() { moveHorizontal = new MoveHorizontal(); } @Test public void bounceTest(){ // Ball mockBall = mock(Ball.class); // MoveHorizontal.setSprite(mockBall); // Assert.assertEquals(Constants.ZERO, MoveHorizontal.moveTheSprite()); // } }
UTF-8
Java
592
java
MoveHorizontalTest.java
Java
[]
null
[]
package ServicesTest; import static org.mockito.Mockito.mock; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import helpers.Constants; import models.Ball; import services.Bounce; import services.MoveHorizontal; public class MoveHorizontalTest { MoveHorizontal moveHorizontal; @Before public void setUp() { moveHorizontal = new MoveHorizontal(); } @Test public void bounceTest(){ // Ball mockBall = mock(Ball.class); // MoveHorizontal.setSprite(mockBall); // Assert.assertEquals(Constants.ZERO, MoveHorizontal.moveTheSprite()); // } }
592
0.748311
0.748311
29
19.413794
17.297632
73
false
false
0
0
0
0
0
0
1.517241
false
false
4
bc9655fe9e2eeaea722aefd9a87c6a0b34720861
19,456,201,907,257
08bb92d91d9c4f3b9976dd03c6861b286ac43cb5
/src/java/com/model/room.java
f7cbd47d5ba27af21bd90c3dd8a6a5b56e5f670e
[]
no_license
haziqmusa97/smartCollege
https://github.com/haziqmusa97/smartCollege
8ea7db8690c41c1da8a7ef30bd3ea87c1632d3c1
45063815f1d1943779f720150f73e6f2e601f179
refs/heads/master
2020-03-28T18:22:23.592000
2018-09-15T07:44:38
2018-09-15T07:44:38
148,875,715
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.model; /* * 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. */ /** * * @author ROG */ import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.Map; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; import javax.faces.context.FacesContext; @ManagedBean @RequestScoped public class room { private String student_id; private String collage; private String numroom; private String status; public String getStudent_id() { return student_id; } public void setStudent_id(String student_id) { this.student_id = student_id; } public String getCollage() { return collage; } public void setCollage(String collage) { this.collage = collage; } public String getNumroom() { return numroom; } public void setNumroom(String numroom) { this.numroom = numroom; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } //add data into database public String add_room(){ try { Connection connection=null; DB_connection obj_DB_connection=new DB_connection(); connection=obj_DB_connection.get_connection(); PreparedStatement ps=connection.prepareStatement("insert into room(student_id,collage,numroom,status) VALUES('"+student_id+"','"+collage+"','"+numroom+"','"+status+"')"); ps.executeUpdate(); } catch (Exception e) { System.out.println(e); } return "/Studentbidroom.xhtml?faces-redirect=true"; } //view data from database public ArrayList getGet_all_room() throws Exception{ ArrayList list_of_room=new ArrayList(); Connection connection=null; try { DB_connection obj_DB_connection=new DB_connection(); connection=obj_DB_connection.get_connection(); Statement st=connection.createStatement(); ResultSet rs=st.executeQuery("select * from room"); while(rs.next()){ room obj_room=new room(); obj_room.setStudent_id(rs.getString("student_id")); obj_room.setCollage(rs.getString("collage")); obj_room.setNumroom(rs.getString("numroom")); obj_room.setStatus(rs.getString("status")); list_of_room.add(obj_room); } } catch (Exception e) { System.out.println(e); }finally{ if(connection!=null){ connection.close(); } } return list_of_room; } //edit data from database private Map<String,Object> sessionMap = FacesContext.getCurrentInstance().getExternalContext().getSessionMap(); public String edit_student(){ FacesContext fc = FacesContext.getCurrentInstance(); Map<String,String> params = fc.getExternalContext().getRequestParameterMap(); String field_student_id= params.get("action"); try { DB_connection obj_DB_connection=new DB_connection(); Connection connection=obj_DB_connection.get_connection(); Statement st=connection.createStatement(); ResultSet rs=st.executeQuery("select * from room where student_id="+field_student_id); room obj_room=new room(); rs.next(); obj_room.setStudent_id(rs.getString("student_id")); obj_room.setCollage(rs.getString("collage")); obj_room.setNumroom(rs.getString("numroom")); obj_room.setStatus(rs.getString("status")); sessionMap.put("editcategory", obj_room); } catch (Exception e) { System.out.println(e); } return "/editroom.xhtml?faces-redirect=true"; } public String update_room(){ FacesContext fc = FacesContext.getCurrentInstance(); Map<String,String> params = fc.getExternalContext().getRequestParameterMap(); String update_student_id= params.get("update_student_id"); try { DB_connection obj_DB_connection=new DB_connection(); Connection connection=obj_DB_connection.get_connection(); PreparedStatement ps=connection.prepareStatement("update room set collage=?,numroom=?,status=? where student_id=?"); ps.setString(1, collage); ps.setString(2, numroom); ps.setString(3, status); ps.setString(4, update_student_id); System.out.println(ps); ps.executeUpdate(); } catch (Exception e) { System.out.println(e); } return "/viewstudentroom.xhtml?faces-redirect=true"; } }
UTF-8
Java
5,068
java
room.java
Java
[ { "context": "the template in the editor.\n */\n\n/**\n *\n * @author ROG\n */\n\nimport java.sql.Connection;\nimport java.sql.", "end": 227, "score": 0.9974595308303833, "start": 224, "tag": "USERNAME", "value": "ROG" } ]
null
[]
package com.model; /* * 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. */ /** * * @author ROG */ import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.Map; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; import javax.faces.context.FacesContext; @ManagedBean @RequestScoped public class room { private String student_id; private String collage; private String numroom; private String status; public String getStudent_id() { return student_id; } public void setStudent_id(String student_id) { this.student_id = student_id; } public String getCollage() { return collage; } public void setCollage(String collage) { this.collage = collage; } public String getNumroom() { return numroom; } public void setNumroom(String numroom) { this.numroom = numroom; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } //add data into database public String add_room(){ try { Connection connection=null; DB_connection obj_DB_connection=new DB_connection(); connection=obj_DB_connection.get_connection(); PreparedStatement ps=connection.prepareStatement("insert into room(student_id,collage,numroom,status) VALUES('"+student_id+"','"+collage+"','"+numroom+"','"+status+"')"); ps.executeUpdate(); } catch (Exception e) { System.out.println(e); } return "/Studentbidroom.xhtml?faces-redirect=true"; } //view data from database public ArrayList getGet_all_room() throws Exception{ ArrayList list_of_room=new ArrayList(); Connection connection=null; try { DB_connection obj_DB_connection=new DB_connection(); connection=obj_DB_connection.get_connection(); Statement st=connection.createStatement(); ResultSet rs=st.executeQuery("select * from room"); while(rs.next()){ room obj_room=new room(); obj_room.setStudent_id(rs.getString("student_id")); obj_room.setCollage(rs.getString("collage")); obj_room.setNumroom(rs.getString("numroom")); obj_room.setStatus(rs.getString("status")); list_of_room.add(obj_room); } } catch (Exception e) { System.out.println(e); }finally{ if(connection!=null){ connection.close(); } } return list_of_room; } //edit data from database private Map<String,Object> sessionMap = FacesContext.getCurrentInstance().getExternalContext().getSessionMap(); public String edit_student(){ FacesContext fc = FacesContext.getCurrentInstance(); Map<String,String> params = fc.getExternalContext().getRequestParameterMap(); String field_student_id= params.get("action"); try { DB_connection obj_DB_connection=new DB_connection(); Connection connection=obj_DB_connection.get_connection(); Statement st=connection.createStatement(); ResultSet rs=st.executeQuery("select * from room where student_id="+field_student_id); room obj_room=new room(); rs.next(); obj_room.setStudent_id(rs.getString("student_id")); obj_room.setCollage(rs.getString("collage")); obj_room.setNumroom(rs.getString("numroom")); obj_room.setStatus(rs.getString("status")); sessionMap.put("editcategory", obj_room); } catch (Exception e) { System.out.println(e); } return "/editroom.xhtml?faces-redirect=true"; } public String update_room(){ FacesContext fc = FacesContext.getCurrentInstance(); Map<String,String> params = fc.getExternalContext().getRequestParameterMap(); String update_student_id= params.get("update_student_id"); try { DB_connection obj_DB_connection=new DB_connection(); Connection connection=obj_DB_connection.get_connection(); PreparedStatement ps=connection.prepareStatement("update room set collage=?,numroom=?,status=? where student_id=?"); ps.setString(1, collage); ps.setString(2, numroom); ps.setString(3, status); ps.setString(4, update_student_id); System.out.println(ps); ps.executeUpdate(); } catch (Exception e) { System.out.println(e); } return "/viewstudentroom.xhtml?faces-redirect=true"; } }
5,068
0.60517
0.60438
156
31.487179
27.357904
182
false
false
0
0
0
0
0
0
0.615385
false
false
4
78814251a4da191bd35d063aa05c12f2d72774e5
27,401,891,364,135
7e1b62c66ed8d30d51304d6a9aef35f35fe6e716
/src/main/java/it/polimi/LM39/exception/NotEnoughResourcesException.java
960570a3aca6cc76fffeb61d00c2b2653b43cc33
[]
no_license
AlessioCantina/ProgettoIngSW
https://github.com/AlessioCantina/ProgettoIngSW
64aa1c73e059047380208f3cec02fc75c05352fc
accf0443aacc0a384196564b0961ef06c35e0ea0
refs/heads/master
2020-03-17T14:06:11.849000
2017-07-10T07:49:40
2017-07-10T07:49:40
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package it.polimi.LM39.exception; public class NotEnoughResourcesException extends Exception{ private static final long serialVersionUID = -6620522530090261416L; public NotEnoughResourcesException(String s){ super(s); } }
UTF-8
Java
230
java
NotEnoughResourcesException.java
Java
[]
null
[]
package it.polimi.LM39.exception; public class NotEnoughResourcesException extends Exception{ private static final long serialVersionUID = -6620522530090261416L; public NotEnoughResourcesException(String s){ super(s); } }
230
0.808696
0.717391
10
22
25.682678
68
false
false
0
0
0
0
0
0
0.8
false
false
4
93deb8f801e4e0f1422a47ec98e326106149842a
9,113,920,607,704
06ca6e5719a594843fcb34d101347a6c2566a83c
/Week_01/com/geekuniversity/algorithm/homework/week1/TwoSum.java
e17d2d82fd356ac3073e639f2798ffd8fe116e42
[]
no_license
MambaForever824/-algorithm015
https://github.com/MambaForever824/-algorithm015
4725e09d8af6243998318e313943e7e6d4913a8f
77c736e80b4dd816232b63584325682bc391d3e4
refs/heads/master
2023-01-05T12:20:09.239000
2020-10-27T14:25:20
2020-10-27T14:25:20
290,108,285
0
0
null
true
2020-08-25T04:01:38
2020-08-25T04:01:38
2020-08-24T08:03:52
2020-08-13T06:26:22
2
0
0
0
null
false
false
package com.geekuniversity.algorithm.homework.week1; import java.util.HashMap; import java.util.Map; /** * 两数之和 * * 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那【两个】整数,并返回他们的数组下标。 * * 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。 * * 解题思路: * 1、暴力解法 * 双层循环,遍历所有元素,发现两个值相加==target时,返回元素下标 * 时间复杂度为O(N*N),其中N为数组长度 * * 2、借用Map,存储已遍历的元素和下标 * 时间复杂度O(N) */ public class TwoSum { public int[] twoSum(int[] nums, int target) { if (nums == null || nums.length == 0) { return new int[0]; } Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { int val = target - nums[i]; if (map.containsKey(val)) { return new int[]{map.get(val), i}; } map.put(nums[i], i); } return new int[0]; } /** * 暴力求解 * @param nums * @param target * @return */ public int[] twoSum1(int[] nums, int target) { if (nums == null) { return new int[0]; } for (int i = 0; i < nums.length - 1; i++) { for (int j = i + 1; j < nums.length; j++) { if (nums[i] + nums[j] == target) { return new int[]{i, j}; } } } return new int[0]; } }
UTF-8
Java
1,654
java
TwoSum.java
Java
[]
null
[]
package com.geekuniversity.algorithm.homework.week1; import java.util.HashMap; import java.util.Map; /** * 两数之和 * * 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那【两个】整数,并返回他们的数组下标。 * * 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。 * * 解题思路: * 1、暴力解法 * 双层循环,遍历所有元素,发现两个值相加==target时,返回元素下标 * 时间复杂度为O(N*N),其中N为数组长度 * * 2、借用Map,存储已遍历的元素和下标 * 时间复杂度O(N) */ public class TwoSum { public int[] twoSum(int[] nums, int target) { if (nums == null || nums.length == 0) { return new int[0]; } Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { int val = target - nums[i]; if (map.containsKey(val)) { return new int[]{map.get(val), i}; } map.put(nums[i], i); } return new int[0]; } /** * 暴力求解 * @param nums * @param target * @return */ public int[] twoSum1(int[] nums, int target) { if (nums == null) { return new int[0]; } for (int i = 0; i < nums.length - 1; i++) { for (int j = i + 1; j < nums.length; j++) { if (nums[i] + nums[j] == target) { return new int[]{i, j}; } } } return new int[0]; } }
1,654
0.484894
0.475076
57
22.228069
18.380022
65
false
false
0
0
0
0
0
0
0.45614
false
false
4
3f4d9a19046b90606c900855c88af63f05838ed2
11,089,605,622,055
cd81437c8da8cfe3be2d42c50e8127bc9e532593
/src/main/java/com/eGSTbill/dao/ShippingDAO.java
379f19a6be47e5b7d3e3ab5f6b8d0b1e739d65bc
[]
no_license
srinidova/eGSTbill
https://github.com/srinidova/eGSTbill
d6a349682c84aa0d11791128f3b04a2e7ea1b971
08c5f2e182f8409a9b129b0587f4e188b024c8fb
refs/heads/master
2021-01-02T23:16:36.007000
2017-11-28T12:21:00
2017-11-28T12:21:00
99,494,045
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.eGSTbill.dao; import java.util.ArrayList; import org.apache.commons.lang.StringUtils; import com.eGSTbill.connection.IbatisFactory; import com.eGSTbill.model.Product; import com.eGSTbill.model.PurchaserShipping; import com.eGSTbill.model.Shipping; import com.ibatis.sqlmap.client.SqlMapClient; public class ShippingDAO { public String addShipping(Shipping shipping) { String result = "fail"; try { SqlMapClient session = new IbatisFactory().getSession(); session.insert("Shipping.addShipping", shipping); result = "success"; } catch (Exception e) { e.printStackTrace(); } return result; } @SuppressWarnings("unchecked") public ArrayList<Shipping> listShipping(){ ArrayList<Shipping> lstShipping = new ArrayList<Shipping>(); try{ SqlMapClient session = new IbatisFactory().getSession(); lstShipping = (ArrayList<Shipping>) session.queryForList("Shipping.listShipping"); }catch(Exception e){ e.printStackTrace(); } if (!lstShipping.equals(null)) { return lstShipping; } else { return lstShipping; } } public String deleteShipping(Shipping shipping) { String result = "fail"; try { SqlMapClient session = new IbatisFactory().getSession(); session.insert("Shipping.deleteShipping", shipping); result = "success"; } catch (Exception e) { e.printStackTrace(); } return result; } public String updateShipping(Shipping shipping) { String result = "fail"; //System.out.println("in to update Shipping"); try { SqlMapClient session = new IbatisFactory().getSession(); session.insert("Shipping.updateShipping", shipping); result = "success"; } catch (Exception e) { e.printStackTrace(); } return result; } @SuppressWarnings("unchecked") public ArrayList<Shipping> getShippingsBypurchaserId(String sPurchaserId){ ArrayList<Shipping> lstShipping = new ArrayList<Shipping>(); try{ SqlMapClient session = new IbatisFactory().getSession(); PurchaserShipping ps = new PurchaserShipping(); //System.out.println("From DAO sPurchaserId=="+sPurchaserId); if(StringUtils.isNotEmpty(sPurchaserId)){ ps.setPurchaserId(sPurchaserId); } lstShipping = (ArrayList<Shipping>) session.queryForList("Shipping.getShippingsBypurchaserId", ps); }catch(Exception e){ e.printStackTrace(); } if (!lstShipping.equals(null)) { return lstShipping; } else { return lstShipping; } } }
UTF-8
Java
2,426
java
ShippingDAO.java
Java
[]
null
[]
package com.eGSTbill.dao; import java.util.ArrayList; import org.apache.commons.lang.StringUtils; import com.eGSTbill.connection.IbatisFactory; import com.eGSTbill.model.Product; import com.eGSTbill.model.PurchaserShipping; import com.eGSTbill.model.Shipping; import com.ibatis.sqlmap.client.SqlMapClient; public class ShippingDAO { public String addShipping(Shipping shipping) { String result = "fail"; try { SqlMapClient session = new IbatisFactory().getSession(); session.insert("Shipping.addShipping", shipping); result = "success"; } catch (Exception e) { e.printStackTrace(); } return result; } @SuppressWarnings("unchecked") public ArrayList<Shipping> listShipping(){ ArrayList<Shipping> lstShipping = new ArrayList<Shipping>(); try{ SqlMapClient session = new IbatisFactory().getSession(); lstShipping = (ArrayList<Shipping>) session.queryForList("Shipping.listShipping"); }catch(Exception e){ e.printStackTrace(); } if (!lstShipping.equals(null)) { return lstShipping; } else { return lstShipping; } } public String deleteShipping(Shipping shipping) { String result = "fail"; try { SqlMapClient session = new IbatisFactory().getSession(); session.insert("Shipping.deleteShipping", shipping); result = "success"; } catch (Exception e) { e.printStackTrace(); } return result; } public String updateShipping(Shipping shipping) { String result = "fail"; //System.out.println("in to update Shipping"); try { SqlMapClient session = new IbatisFactory().getSession(); session.insert("Shipping.updateShipping", shipping); result = "success"; } catch (Exception e) { e.printStackTrace(); } return result; } @SuppressWarnings("unchecked") public ArrayList<Shipping> getShippingsBypurchaserId(String sPurchaserId){ ArrayList<Shipping> lstShipping = new ArrayList<Shipping>(); try{ SqlMapClient session = new IbatisFactory().getSession(); PurchaserShipping ps = new PurchaserShipping(); //System.out.println("From DAO sPurchaserId=="+sPurchaserId); if(StringUtils.isNotEmpty(sPurchaserId)){ ps.setPurchaserId(sPurchaserId); } lstShipping = (ArrayList<Shipping>) session.queryForList("Shipping.getShippingsBypurchaserId", ps); }catch(Exception e){ e.printStackTrace(); } if (!lstShipping.equals(null)) { return lstShipping; } else { return lstShipping; } } }
2,426
0.720528
0.720528
92
25.369566
22.747536
102
false
false
0
0
0
0
0
0
2.228261
false
false
4
3d8da2a4a7cef19f923d2f0a66d764d2c2b4e592
11,536,282,201,204
7627cb8e71eb3dedb5dc9083cf53bd11375a2049
/java-super-projects/core-java-examples/src/main/java/parser/XpathDemo.java
a388e2ddbebb270097004813a846ca4b340cbd1a
[]
no_license
mountainrock/java-super-projects
https://github.com/mountainrock/java-super-projects
1f374acf7b5d255b405c4a31591716629d58426e
247e99c493b8b61487f9a065add57cf51456d4e8
refs/heads/master
2021-01-23T06:45:07.359000
2015-08-27T07:18:56
2015-08-27T07:18:56
32,129,614
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package parser; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import utils.XpathUtils; /** * Refer: http://www.ibm.com/developerworks/library/x-javaxpathapi.html * @author sandeep * */ public class XpathDemo { public static void main(String[] args) { String xmlResourcePath = "src/main/resources/books.xml"; Document doc = XpathUtils.buildXMLDocument(xmlResourcePath); String xpathExpression = "//book[author='Neal Stephenson']/title/text()"; NodeList nodes = XpathUtils.getNodeList(doc, xpathExpression); for (int i = 0; i < nodes.getLength(); i++) { System.out.println(nodes.item(i).getNodeValue()); } } }
UTF-8
Java
920
java
XpathDemo.java
Java
[ { "context": "loperworks/library/x-javaxpathapi.html\r\n * @author sandeep\r\n *\r\n */\r\npublic class XpathDemo {\r\n\tpublic stati", "end": 450, "score": 0.9973721504211426, "start": 443, "tag": "USERNAME", "value": "sandeep" }, { "context": "h);\r\n\r\n\t\tString xpathExpression = \"//book[author='Neal Stephenson']/title/text()\";\r\n\t\tNodeList nodes = XpathUtils.g", "end": 716, "score": 0.9998732805252075, "start": 701, "tag": "NAME", "value": "Neal Stephenson" } ]
null
[]
package parser; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import utils.XpathUtils; /** * Refer: http://www.ibm.com/developerworks/library/x-javaxpathapi.html * @author sandeep * */ public class XpathDemo { public static void main(String[] args) { String xmlResourcePath = "src/main/resources/books.xml"; Document doc = XpathUtils.buildXMLDocument(xmlResourcePath); String xpathExpression = "//book[author='<NAME>']/title/text()"; NodeList nodes = XpathUtils.getNodeList(doc, xpathExpression); for (int i = 0; i < nodes.getLength(); i++) { System.out.println(nodes.item(i).getNodeValue()); } } }
911
0.722826
0.719565
34
25.058823
24.013405
75
false
false
0
0
0
0
0
0
1.029412
false
false
4
7fd76646f549b5cd4ce0589645120a52ae63d841
19,911,468,428,492
79cc65484073f3b47f8d4d648e6256d90e05abbf
/backend/src/main/java/commands/ApplicationNotifiable.java
c889a0b2678085dc37337d62e804de84e13f9942
[]
no_license
csc30012/psimulator
https://github.com/csc30012/psimulator
341732ffa9f318b152d938a360e9dc8822c064df
63ff9620033b677ef176f391d0ca7fb99ecf46cb
refs/heads/master
2023-03-12T12:38:13.650000
2021-02-26T19:54:11
2021-02-26T19:54:11
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * created 8.3.2012 */ package commands; /** * Rozhrani pro prikazy, ktery volaj ke svymu vykonani jinou aplikaci. Nejde bohuzel dedit od AbstractCommandu, protoze * od nej dedej uz LinuxCommand a CiscoCommand. Rozsirujici je metoda applicationFinished. * * @author Stanislav Rehak <rehaksta@fit.cvut.cz> */ public interface ApplicationNotifiable { public void printLine(String s); public void print(String s); /** * Application notifies that application has finished. */ public void applicationFinished(); }
UTF-8
Java
533
java
ApplicationNotifiable.java
Java
[ { "context": "ujici je metoda applicationFinished.\n *\n * @author Stanislav Rehak <rehaksta@fit.cvut.cz>\n */\npublic interface Appli", "end": 290, "score": 0.9998868703842163, "start": 275, "tag": "NAME", "value": "Stanislav Rehak" }, { "context": "plicationFinished.\n *\n * @author Stanislav Rehak <rehaksta@fit.cvut.cz>\n */\npublic interface ApplicationNotifiable {\n\n\n\t", "end": 312, "score": 0.9999296069145203, "start": 292, "tag": "EMAIL", "value": "rehaksta@fit.cvut.cz" } ]
null
[]
/* * created 8.3.2012 */ package commands; /** * Rozhrani pro prikazy, ktery volaj ke svymu vykonani jinou aplikaci. Nejde bohuzel dedit od AbstractCommandu, protoze * od nej dedej uz LinuxCommand a CiscoCommand. Rozsirujici je metoda applicationFinished. * * @author <NAME> <<EMAIL>> */ public interface ApplicationNotifiable { public void printLine(String s); public void print(String s); /** * Application notifies that application has finished. */ public void applicationFinished(); }
511
0.742964
0.731707
25
20.32
30.224123
119
false
false
0
0
0
0
0
0
0.48
false
false
4
3b98a3a96da0661bfcc788d6ad4dfd92badcf74f
25,709,674,286,824
864f1cccfc5b5d15834ad4d61d6f78760d32a91c
/ejercicios/src/main/java/Tema5/Ejercicio2/Mensajes2.java
f37427a397869bb6da378bc3a0bc9f0eccd2db3b
[]
no_license
dpa3001/entmultijugador
https://github.com/dpa3001/entmultijugador
4a60dde22694efcf2a78e46d96095b0ceda1fff5
f5057c791bf58a685121b1881cbedcfc83b713be
refs/heads/master
2020-04-17T17:02:41.309000
2019-03-18T09:06:36
2019-03-18T09:06:36
166,767,638
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Tema5.Ejercicio2; /** * El código es incorrecto a propósito * @author DPA * */ public class Mensajes2 { private void mensajes() { //Almacenamos los mensajes en un array o buffer String[] mensajes = {"La vida es bella", "O no...", "Los pajaritos cantan", "Y molestan..."}; //Escribrimos cada mensaje por pantalla for (String mensaje : mensajes) { System.out.println(mensaje); /*Debe de esperarse a decir cada frase cada dos * segundos */ Thread.sleep(2000); } } private void exec() { Thread t = new Thread(()->mensajes()); t.start(); t.join(1000); } public static void main(String[] args) { new Mensajes2().exec(); } }
UTF-8
Java
759
java
Mensajes2.java
Java
[ { "context": " * El código es incorrecto a propósito\r\n * @author DPA\r\n *\r\n */\r\npublic class Mensajes2 {\r\n\r\n\tprivate vo", "end": 88, "score": 0.9968558549880981, "start": 85, "tag": "USERNAME", "value": "DPA" } ]
null
[]
package Tema5.Ejercicio2; /** * El código es incorrecto a propósito * @author DPA * */ public class Mensajes2 { private void mensajes() { //Almacenamos los mensajes en un array o buffer String[] mensajes = {"La vida es bella", "O no...", "Los pajaritos cantan", "Y molestan..."}; //Escribrimos cada mensaje por pantalla for (String mensaje : mensajes) { System.out.println(mensaje); /*Debe de esperarse a decir cada frase cada dos * segundos */ Thread.sleep(2000); } } private void exec() { Thread t = new Thread(()->mensajes()); t.start(); t.join(1000); } public static void main(String[] args) { new Mensajes2().exec(); } }
759
0.574637
0.558785
44
15.204545
15.783448
50
false
false
0
0
0
0
0
0
1.727273
false
false
4
0510cfd291ea419633476924aaa772ae5f41c727
4,097,398,800,478
0582ac2d628a2091bec841f58bdc99e2b50bfbd9
/Naum_ALG2_sem_Storage/src/app/StorageInterface.java
8ed09038b533984afa872daed3b1219424ef261f
[]
no_license
NaumJoanis/Skola
https://github.com/NaumJoanis/Skola
2982216aa55cee66d9b5b84c146edf4a01ada016
67f4d23b4d481efcb2e1d7714f0cd8180fc889ca
refs/heads/master
2021-05-20T02:09:21.438000
2020-06-08T13:31:31
2020-06-08T13:31:31
252,141,522
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package app; import java.util.ArrayList; /** * * @author Joanis Naum */ public interface StorageInterface { final ArrayList<Product> products = new ArrayList<>(); }
UTF-8
Java
189
java
StorageInterface.java
Java
[ { "context": "p;\n\nimport java.util.ArrayList;\n\n/**\n *\n * @author Joanis Naum\n */\npublic interface StorageInterface {\n \n ", "end": 72, "score": 0.9998639822006226, "start": 61, "tag": "NAME", "value": "Joanis Naum" } ]
null
[]
package app; import java.util.ArrayList; /** * * @author <NAME> */ public interface StorageInterface { final ArrayList<Product> products = new ArrayList<>(); }
184
0.640212
0.640212
14
12.5
16.538916
58
false
false
0
0
0
0
0
0
0.214286
false
false
4
68b8f9a361b28733fa296c90993a914fd62f76fb
4,432,406,309,190
9d5837231a590f56bfdc2fc85203d8c9846eb691
/src/test/java/test/vedic/astro/data/NobhasYogasTest.java
87e1728570d154c4884a0a4c0aa4ec9b8af3cf73
[]
no_license
sumeer-saxena/vedic-astrogyan
https://github.com/sumeer-saxena/vedic-astrogyan
4f97798d5f65943ec61bccd71d466f7db49840b7
f3f267c9f89ed3fc6de30b107e224489a992083f
refs/heads/master
2017-05-05T07:08:25.354000
2017-01-26T17:40:17
2017-01-26T17:40:17
48,410,209
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package test.vedic.astro.data; import java.util.List; import javax.annotation.Resource; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import com.vedic.astro.domain.BirthChartData; import com.vedic.astro.enums.Yoga; import com.vedic.astro.service.PlanetPositionsDataService; import com.vedic.astro.util.BirthChartUtil; import com.vedic.astro.util.RelationshipUtil; import com.vedic.astro.vo.AbsolutePlanetaryPositions; import com.vedic.astro.vo.BirthChartCalcPrep; import com.vedic.astro.yogas.NabhasYogaFinder; /** * Test case for unit testing the Member repository. * * @author Sumeer Saxena * */ public class NobhasYogasTest extends BaseUtilTest { @Autowired @Qualifier("nabhasYogaFinder") private NabhasYogaFinder nabhasYogaFinder; @Autowired @Qualifier("relationshipUtil") private RelationshipUtil relationshipUtil; @Autowired @Qualifier("birthChartUtil") private BirthChartUtil birthChartUtil; @Autowired @Qualifier("planetPositionsDataService") private PlanetPositionsDataService planetPositionsDataService; @Test public void testNobhasYogas() throws Exception { AbsolutePlanetaryPositions absolutePlanetaryPositions = planetPositionsDataService .getPlanetPositionsData("23/12/2002", "17:55:00", "10304"); BirthChartData d1Chart = birthChartUtil .generateD1Chart(absolutePlanetaryPositions); BirthChartCalcPrep birthChartCalcPrep = relationshipUtil .preparePlanetsForCalc(d1Chart.getChartHouses()); System.out.println("birthChartCalcPrep" + birthChartCalcPrep); System.out.println("Yogas present = " + nabhasYogaFinder.findAshrayaYogaPresent(birthChartCalcPrep)); System.out.println("Yogas present = " + nabhasYogaFinder.findDalaYogaPresent(birthChartCalcPrep)); List<Yoga> yogas = nabhasYogaFinder .findAkritiYogaPresent(birthChartCalcPrep); System.out.println("Sankhya Yogas present = " + nabhasYogaFinder.findSankhyaYogaPresent(birthChartCalcPrep)); System.out.println("Yogas present = " + yogas); for (Yoga yoga : yogas) { System.out.println("Yogas present = " + nabhasYogaFinder.getYogaDetails(yoga)); } } }
UTF-8
Java
2,216
java
NobhasYogasTest.java
Java
[ { "context": "unit testing the Member repository.\n * \n * @author Sumeer Saxena\n * \n */\npublic class NobhasYogasTest extends Base", "end": 704, "score": 0.9998407959938049, "start": 691, "tag": "NAME", "value": "Sumeer Saxena" } ]
null
[]
package test.vedic.astro.data; import java.util.List; import javax.annotation.Resource; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import com.vedic.astro.domain.BirthChartData; import com.vedic.astro.enums.Yoga; import com.vedic.astro.service.PlanetPositionsDataService; import com.vedic.astro.util.BirthChartUtil; import com.vedic.astro.util.RelationshipUtil; import com.vedic.astro.vo.AbsolutePlanetaryPositions; import com.vedic.astro.vo.BirthChartCalcPrep; import com.vedic.astro.yogas.NabhasYogaFinder; /** * Test case for unit testing the Member repository. * * @author <NAME> * */ public class NobhasYogasTest extends BaseUtilTest { @Autowired @Qualifier("nabhasYogaFinder") private NabhasYogaFinder nabhasYogaFinder; @Autowired @Qualifier("relationshipUtil") private RelationshipUtil relationshipUtil; @Autowired @Qualifier("birthChartUtil") private BirthChartUtil birthChartUtil; @Autowired @Qualifier("planetPositionsDataService") private PlanetPositionsDataService planetPositionsDataService; @Test public void testNobhasYogas() throws Exception { AbsolutePlanetaryPositions absolutePlanetaryPositions = planetPositionsDataService .getPlanetPositionsData("23/12/2002", "17:55:00", "10304"); BirthChartData d1Chart = birthChartUtil .generateD1Chart(absolutePlanetaryPositions); BirthChartCalcPrep birthChartCalcPrep = relationshipUtil .preparePlanetsForCalc(d1Chart.getChartHouses()); System.out.println("birthChartCalcPrep" + birthChartCalcPrep); System.out.println("Yogas present = " + nabhasYogaFinder.findAshrayaYogaPresent(birthChartCalcPrep)); System.out.println("Yogas present = " + nabhasYogaFinder.findDalaYogaPresent(birthChartCalcPrep)); List<Yoga> yogas = nabhasYogaFinder .findAkritiYogaPresent(birthChartCalcPrep); System.out.println("Sankhya Yogas present = " + nabhasYogaFinder.findSankhyaYogaPresent(birthChartCalcPrep)); System.out.println("Yogas present = " + yogas); for (Yoga yoga : yogas) { System.out.println("Yogas present = " + nabhasYogaFinder.getYogaDetails(yoga)); } } }
2,209
0.794675
0.784747
72
29.791666
23.781376
84
false
false
0
0
0
0
0
0
1.430556
false
false
4
0ca9fa451a8b56174e5a1d01f5df1acd701c62c4
4,432,406,307,436
3d136dd0c84944dc395d8da2643aed78b989f10f
/Mini_Client/src/main/java/game/TankClient.java
34a3e4d8bdff42189784824a820aa30343365dbc
[]
no_license
jealousMr/mini_chat
https://github.com/jealousMr/mini_chat
532fc3329b3871fabce155e17b40d63609a97869
032371f827333363dc24af3e2c90f1da6a06413c
refs/heads/master
2020-03-22T12:39:13.608000
2018-07-09T10:58:25
2018-07-09T10:58:25
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package game; import java.awt.*; import java.awt.event.*; import java.util.List; import java.util.Random; import javax.swing.ImageIcon; import javax.swing.JFrame; import java.util.ArrayList; public class TankClient extends Frame { // public ImageIcon a = new ImageIcon("images/tank.jpg"); public Toolkit t = Toolkit.getDefaultToolkit(); public Image image = t.getImage("C:\\my\\projectText\\Mini_Client\\src\\main\\java\\GUI_img\\LoginPage_img\\tank.jpg"); public int scores = 10; public int num ; public int rebirthNum1 = 0; public int rebirthNum2 = 0; public boolean j ; public boolean boss = false; protected static Random rr = new Random(); public boolean flag = true; public static final int GAME_WIDTH = 800; public static final int GAME_HEIGHT = 600; Tank yourTank = new YourTank(500, 500, true,Tank.Direction.STOP, this); Tank myTank = new MyTank(750, 500, true, Tank.Direction.STOP, this); Wall w1 = new Wall(400, 200, 20, 150, this), w2 = new Wall(300, 100, 300, 20, this), w3 = new Wall(550, 500, 200, 20, this); List<Explode> explodes = new ArrayList<Explode>(); List<Missile> missiles = new ArrayList<Missile>(); List<Tank> tanks = new ArrayList<Tank>(); Image offScreenImage = null; Blood b = new Blood(); public void paint(Graphics g) { /* * * 指明子弹 -爆炸 -坦克的数量 * * 以及坦克的生命值 * */ g.drawString("Scores:" + (scores-(num = tanks.size())), 10, 50); g.drawString("Tank1 Rebirth:" + rebirthNum1, 10, 70); g.drawString("Tank2 Rebirth:" + rebirthNum2, 10, 90); g.drawString("tanks count:" + tanks.size(), 10, 110); g.drawString("Tank1 life:" + myTank.getLife(), 10, 130); g.drawString("Tank2 life"+ yourTank.getLife(), 10,150); if (tanks.size() <= 0) { boss = true; scores += 5; num += 5; for (int i = 0; i < 5; i++) { tanks.add(new Tank(rr.nextInt(800), rr.nextInt(600), false, Tank.Direction.D, this)); } } for (int i = 0; i < missiles.size(); i++) { Missile m = missiles.get(i); m.hitTanks(tanks); m.hitTank(myTank); m.hitTank(yourTank); m.hitWall(w1); m.hitWall(w2); m.hitWall(w3); m.draw(g); // if(!m.isLive()) missiles.remove(m); // else m.draw(g); } for (int i = 0; i < explodes.size(); i++) { Explode e = explodes.get(i); e.draw(g); } for (int i = 0; i < tanks.size(); i++) { Tank t = tanks.get(i); t.collidesWithWall(w1); t.collidesWithWall(w2); t.collidesWithWall(w3); t.collidesWithTanks(tanks); t.draw(g); } yourTank.collidesWithWall(w1); yourTank.collidesWithWall(w2); yourTank.collidesWithWall(w3); myTank.collidesWithWall(w1); myTank.collidesWithWall(w1); myTank.collidesWithWall(w1); if (j) { myTank.draw(g); } myTank.eat(b); yourTank.draw(g); yourTank.eat(b); w1.draw(g); w2.draw(g); w3.draw(g); b.draw(g); } public void update(Graphics g) { if (offScreenImage == null) { offScreenImage = this.createImage(GAME_WIDTH, GAME_HEIGHT); } Graphics gOffScreen = offScreenImage.getGraphics(); Color c = gOffScreen.getColor(); gOffScreen.setColor(new Color(199,212,247)); gOffScreen.fillRect(0, 0, GAME_WIDTH, GAME_HEIGHT); gOffScreen.setColor(c); paint(gOffScreen); g.drawImage(offScreenImage, 0, 0, null); } public void lauchFrame() { for (int i = 0; i < 10; i++) { tanks.add(new Tank(50 + 40 * (i + 1), 50, false, Tank.Direction.D, this)); } // this.setLocation(400, 300); this.setSize(GAME_WIDTH, GAME_HEIGHT); this.setTitle("TankWar"); this.setIconImage(image); this.setLocationRelativeTo(null); // this.addWindowListener(new WindowAdapter() { // // public void windowClosing(WindowEvent e) { // System.exit(0); // } // // }); this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { super.windowClosing(e); (e.getWindow()).dispose(); } }); this.setResizable(false); this.setBackground(new Color(199,212,247)); this.addKeyListener(new KeyMonitor()); this.setVisible(true); new Thread(new PaintThread()).start(); } private class PaintThread implements Runnable { public void run() { while (true) { repaint(); try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } } } } private class KeyMonitor extends KeyAdapter { public void keyReleased(KeyEvent e) { myTank.keyReleased(e); yourTank.keyReleased(e); } public void keyPressed(KeyEvent e) { myTank.keyPressed(e); yourTank.keyPressed(e); } } }
UTF-8
Java
5,544
java
TankClient.java
Java
[]
null
[]
package game; import java.awt.*; import java.awt.event.*; import java.util.List; import java.util.Random; import javax.swing.ImageIcon; import javax.swing.JFrame; import java.util.ArrayList; public class TankClient extends Frame { // public ImageIcon a = new ImageIcon("images/tank.jpg"); public Toolkit t = Toolkit.getDefaultToolkit(); public Image image = t.getImage("C:\\my\\projectText\\Mini_Client\\src\\main\\java\\GUI_img\\LoginPage_img\\tank.jpg"); public int scores = 10; public int num ; public int rebirthNum1 = 0; public int rebirthNum2 = 0; public boolean j ; public boolean boss = false; protected static Random rr = new Random(); public boolean flag = true; public static final int GAME_WIDTH = 800; public static final int GAME_HEIGHT = 600; Tank yourTank = new YourTank(500, 500, true,Tank.Direction.STOP, this); Tank myTank = new MyTank(750, 500, true, Tank.Direction.STOP, this); Wall w1 = new Wall(400, 200, 20, 150, this), w2 = new Wall(300, 100, 300, 20, this), w3 = new Wall(550, 500, 200, 20, this); List<Explode> explodes = new ArrayList<Explode>(); List<Missile> missiles = new ArrayList<Missile>(); List<Tank> tanks = new ArrayList<Tank>(); Image offScreenImage = null; Blood b = new Blood(); public void paint(Graphics g) { /* * * 指明子弹 -爆炸 -坦克的数量 * * 以及坦克的生命值 * */ g.drawString("Scores:" + (scores-(num = tanks.size())), 10, 50); g.drawString("Tank1 Rebirth:" + rebirthNum1, 10, 70); g.drawString("Tank2 Rebirth:" + rebirthNum2, 10, 90); g.drawString("tanks count:" + tanks.size(), 10, 110); g.drawString("Tank1 life:" + myTank.getLife(), 10, 130); g.drawString("Tank2 life"+ yourTank.getLife(), 10,150); if (tanks.size() <= 0) { boss = true; scores += 5; num += 5; for (int i = 0; i < 5; i++) { tanks.add(new Tank(rr.nextInt(800), rr.nextInt(600), false, Tank.Direction.D, this)); } } for (int i = 0; i < missiles.size(); i++) { Missile m = missiles.get(i); m.hitTanks(tanks); m.hitTank(myTank); m.hitTank(yourTank); m.hitWall(w1); m.hitWall(w2); m.hitWall(w3); m.draw(g); // if(!m.isLive()) missiles.remove(m); // else m.draw(g); } for (int i = 0; i < explodes.size(); i++) { Explode e = explodes.get(i); e.draw(g); } for (int i = 0; i < tanks.size(); i++) { Tank t = tanks.get(i); t.collidesWithWall(w1); t.collidesWithWall(w2); t.collidesWithWall(w3); t.collidesWithTanks(tanks); t.draw(g); } yourTank.collidesWithWall(w1); yourTank.collidesWithWall(w2); yourTank.collidesWithWall(w3); myTank.collidesWithWall(w1); myTank.collidesWithWall(w1); myTank.collidesWithWall(w1); if (j) { myTank.draw(g); } myTank.eat(b); yourTank.draw(g); yourTank.eat(b); w1.draw(g); w2.draw(g); w3.draw(g); b.draw(g); } public void update(Graphics g) { if (offScreenImage == null) { offScreenImage = this.createImage(GAME_WIDTH, GAME_HEIGHT); } Graphics gOffScreen = offScreenImage.getGraphics(); Color c = gOffScreen.getColor(); gOffScreen.setColor(new Color(199,212,247)); gOffScreen.fillRect(0, 0, GAME_WIDTH, GAME_HEIGHT); gOffScreen.setColor(c); paint(gOffScreen); g.drawImage(offScreenImage, 0, 0, null); } public void lauchFrame() { for (int i = 0; i < 10; i++) { tanks.add(new Tank(50 + 40 * (i + 1), 50, false, Tank.Direction.D, this)); } // this.setLocation(400, 300); this.setSize(GAME_WIDTH, GAME_HEIGHT); this.setTitle("TankWar"); this.setIconImage(image); this.setLocationRelativeTo(null); // this.addWindowListener(new WindowAdapter() { // // public void windowClosing(WindowEvent e) { // System.exit(0); // } // // }); this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { super.windowClosing(e); (e.getWindow()).dispose(); } }); this.setResizable(false); this.setBackground(new Color(199,212,247)); this.addKeyListener(new KeyMonitor()); this.setVisible(true); new Thread(new PaintThread()).start(); } private class PaintThread implements Runnable { public void run() { while (true) { repaint(); try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } } } } private class KeyMonitor extends KeyAdapter { public void keyReleased(KeyEvent e) { myTank.keyReleased(e); yourTank.keyReleased(e); } public void keyPressed(KeyEvent e) { myTank.keyPressed(e); yourTank.keyPressed(e); } } }
5,544
0.533418
0.503814
279
18.738352
22.766533
128
false
false
0
0
0
0
0
0
0.65233
false
false
4
c5154c55e0cdf92a921b37f626e8d991af878af3
3,805,341,045,950
e9df4daeaebbb9e9aaa59aa147aee8ba79674362
/advanced/src/chapter02javaio/ObjectStreamTest.java
a15b2f023b8577454a15ddaaa5b9043648415005
[]
no_license
zhengjun1987/CoreJava
https://github.com/zhengjun1987/CoreJava
25059543c13687719b4dd63237d6b5cac64f5874
da3b1278686f133e317c3af4b9e44c989c571c25
refs/heads/master
2021-04-09T10:17:21.730000
2018-05-12T15:47:24
2018-05-12T15:47:24
124,729,943
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package chapter02javaio; import utils.MyUtils; import java.io.*; /** * Author: Zheng Jun * Mail:zhengjun1987@outlook.com * Date: 2018/4/20 10:28 */ public class ObjectStreamTest { public static final String STAFF_DAT = "staff.dat"; public static void main(String[] args) { Manager carl_cracker = new Manager("Carl Cracker", 75000, 1987, 12, 15); Manager harry_hacker = new Manager("Harry Hacker", 50000, 1989, 10, 1); Employee tony_tester = new Employee("Tony Tester", 40000, 1990, 3, 15); carl_cracker.setSecretary(tony_tester); harry_hacker.setSecretary(tony_tester); Employee[] employees = new Employee[3]; employees[0] = carl_cracker; employees[1] = harry_hacker; employees[2] = tony_tester; try { ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(STAFF_DAT)); outputStream.writeObject(employees); } catch (IOException e) { e.printStackTrace(); } try { ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(STAFF_DAT)); Employee[] readObject = (Employee[]) inputStream.readObject(); for (Employee employee : readObject) { System.out.println(MyUtils.getCurrentTime() + "employee = " + employee); } } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } } // 2018-04-20 10:46:24:697 employee = Manager{Employee{name='Carl Cracker', salary=75000, birth_year=1987, birth_month=12, birth_day=15} secretary=Employee{name='Tony Tester', salary=40000, birth_year=1990, birth_month=3, birth_day=15}} // 2018-04-20 10:46:24:713 employee = Manager{Employee{name='Harry Hacker', salary=50000, birth_year=1989, birth_month=10, birth_day=1} secretary=Employee{name='Tony Tester', salary=40000, birth_year=1990, birth_month=3, birth_day=15}} // 2018-04-20 10:46:24:713 employee = Employee{name='Tony Tester', salary=40000, birth_year=1990, birth_month=3, birth_day=15}
UTF-8
Java
2,161
java
ObjectStreamTest.java
Java
[ { "context": " utils.MyUtils;\n\nimport java.io.*;\n\n/**\n * Author: Zheng Jun\n * Mail:zhengjun1987@outlook.com\n * Date: 2018/4/", "end": 92, "score": 0.9998795986175537, "start": 83, "tag": "NAME", "value": "Zheng Jun" }, { "context": "port java.io.*;\n\n/**\n * Author: Zheng Jun\n * Mail:zhengjun1987@outlook.com\n * Date: 2018/4/20 10:28\n */\npublic class ObjectS", "end": 125, "score": 0.9999277591705322, "start": 101, "tag": "EMAIL", "value": "zhengjun1987@outlook.com" }, { "context": "gs) {\n Manager carl_cracker = new Manager(\"Carl Cracker\", 75000, 1987, 12, 15);\n Manager harry_hac", "end": 346, "score": 0.9993734955787659, "start": 334, "tag": "NAME", "value": "Carl Cracker" }, { "context": " 15);\n Manager harry_hacker = new Manager(\"Harry Hacker\", 50000, 1989, 10, 1);\n Employee tony_test", "end": 427, "score": 0.995839536190033, "start": 415, "tag": "NAME", "value": "Harry Hacker" }, { "context": " 1);\n Employee tony_tester = new Employee(\"Tony Tester\", 40000, 1990, 3, 15);\n\n carl_cracker.setS", "end": 507, "score": 0.9995914101600647, "start": 496, "tag": "NAME", "value": "Tony Tester" }, { "context": "0 10:46:24:697 employee = Manager{Employee{name='Carl Cracker', salary=75000, birth_year=1987, birth_month=12, ", "end": 1618, "score": 0.9994301795959473, "start": 1606, "tag": "NAME", "value": "Carl Cracker" }, { "context": "_month=12, birth_day=15} secretary=Employee{name='Tony Tester', salary=40000, birth_year=1990, birth_month=3,", "end": 1716, "score": 0.9989359378814697, "start": 1707, "tag": "NAME", "value": "Tony Test" }, { "context": "0 10:46:24:713 employee = Manager{Employee{name='Harry Hacker', salary=50000, birth_year=1989, birth_month=10, ", "end": 1863, "score": 0.9998830556869507, "start": 1851, "tag": "NAME", "value": "Harry Hacker" }, { "context": "h_month=10, birth_day=1} secretary=Employee{name='Tony Tester', salary=40000, birth_year=1990, birth_month=3, b", "end": 1962, "score": 0.9998551607131958, "start": 1951, "tag": "NAME", "value": "Tony Tester" }, { "context": "018-04-20 10:46:24:713 employee = Employee{name='Tony Tester', salary=40000, birth_year=1990, birth_month=3, b", "end": 2098, "score": 0.9998472332954407, "start": 2087, "tag": "NAME", "value": "Tony Tester" } ]
null
[]
package chapter02javaio; import utils.MyUtils; import java.io.*; /** * Author: <NAME> * Mail:<EMAIL> * Date: 2018/4/20 10:28 */ public class ObjectStreamTest { public static final String STAFF_DAT = "staff.dat"; public static void main(String[] args) { Manager carl_cracker = new Manager("<NAME>", 75000, 1987, 12, 15); Manager harry_hacker = new Manager("<NAME>", 50000, 1989, 10, 1); Employee tony_tester = new Employee("<NAME>", 40000, 1990, 3, 15); carl_cracker.setSecretary(tony_tester); harry_hacker.setSecretary(tony_tester); Employee[] employees = new Employee[3]; employees[0] = carl_cracker; employees[1] = harry_hacker; employees[2] = tony_tester; try { ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(STAFF_DAT)); outputStream.writeObject(employees); } catch (IOException e) { e.printStackTrace(); } try { ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(STAFF_DAT)); Employee[] readObject = (Employee[]) inputStream.readObject(); for (Employee employee : readObject) { System.out.println(MyUtils.getCurrentTime() + "employee = " + employee); } } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } } // 2018-04-20 10:46:24:697 employee = Manager{Employee{name='<NAME>', salary=75000, birth_year=1987, birth_month=12, birth_day=15} secretary=Employee{name='<NAME>er', salary=40000, birth_year=1990, birth_month=3, birth_day=15}} // 2018-04-20 10:46:24:713 employee = Manager{Employee{name='<NAME>', salary=50000, birth_year=1989, birth_month=10, birth_day=1} secretary=Employee{name='<NAME>', salary=40000, birth_year=1990, birth_month=3, birth_day=15}} // 2018-04-20 10:46:24:713 employee = Employee{name='<NAME>', salary=40000, birth_year=1990, birth_month=3, birth_day=15}
2,099
0.642295
0.563628
51
41.372547
51.206985
244
false
false
0
0
0
0
0
0
1.039216
false
false
4
034f0a7a19382fe9fcfc6868c141bbca7ddd0103
26,328,149,529,957
0617a138f632847b38cd218b01b55cb40a7809f4
/LPWAN/LoRa/TheThingsNetwork/server/src/main/java/dtu/exampleFile/SetupExample.java
f2d735cb5297235da1d2aa3ae71ccd7fb67b1a1e
[ "MIT", "LicenseRef-scancode-unknown" ]
permissive
SebastianLJ/Neighbourhood-Watch
https://github.com/SebastianLJ/Neighbourhood-Watch
fca02feedc1caac41906703d57d9ca041997bda3
63d8071cf21fe2f0e7801b9c67703d1b58a59c9e
refs/heads/main
2023-06-01T05:52:00.112000
2021-06-23T14:39:37
2021-06-23T14:39:37
367,356,558
0
0
MIT
true
2021-05-14T12:31:54
2021-05-14T12:31:53
2021-01-25T22:18:40
2021-01-25T22:18:37
5,595
0
0
0
null
false
false
package dtu.exampleFile; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import dtu.components.Component; import dtu.components.ComponentSignal; import dtu.database.Database; import dtu.database.DatabaseArrayList; import dtu.house.House; import dtu.house.HouseID; import dtu.house.HouseIDValue; import dtu.house.HouseImplementation; import dtu.house.PhoneAddress; import dtu.house.PhoneAddressImplementation; /** * Example setup file * @author Arada * */ public class SetupExample { public static void testing(String[] args) throws InterruptedException, IOException { Database<PhoneAddress> phoneAddrDB = new DatabaseArrayList<PhoneAddress>(); Database<House> houseDB = new DatabaseArrayList<House>(); Database<Component> deviceDB = new DatabaseArrayList<Component>(); //Salt example for file with house and two devices byte[] salt = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x00, 0x00}; HouseID houseID = new HouseIDValue("HouseID"); House house = new HouseImplementation("temp addr", houseID, "1234", salt); Component device1 = new ComponentSignal("device_01", houseID); Component device2 = new ComponentSignal("device_02", houseID); PhoneAddress phoneNumber = new PhoneAddressImplementation("+4529869690", houseID); houseDB.add(house); deviceDB.add(device1); deviceDB.add(device2); phoneAddrDB.add(phoneNumber); FileOutputStream f1; try { f1 = new FileOutputStream(new File("database_house.txt")); ObjectOutputStream o1 = new ObjectOutputStream (f1); FileOutputStream f2 = new FileOutputStream(new File("database_phone.txt")); ObjectOutputStream o2 = new ObjectOutputStream (f2); FileOutputStream f3 = new FileOutputStream(new File("database_component.txt")); ObjectOutputStream o3 = new ObjectOutputStream (f3); o1.writeObject(houseDB); o2.writeObject(phoneAddrDB); o3.writeObject(deviceDB); o1.close(); f1.close(); o2.close(); f2.close(); o3.close(); f3.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println("Database Setup Done"); } }
UTF-8
Java
2,313
java
SetupExample.java
Java
[ { "context": "lementation;\n\n/**\n * Example setup file\n * @author Arada\n *\n */\npublic class SetupExample {\n\t\n\tpublic stat", "end": 561, "score": 0.9907307624816895, "start": 556, "tag": "NAME", "value": "Arada" } ]
null
[]
package dtu.exampleFile; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import dtu.components.Component; import dtu.components.ComponentSignal; import dtu.database.Database; import dtu.database.DatabaseArrayList; import dtu.house.House; import dtu.house.HouseID; import dtu.house.HouseIDValue; import dtu.house.HouseImplementation; import dtu.house.PhoneAddress; import dtu.house.PhoneAddressImplementation; /** * Example setup file * @author Arada * */ public class SetupExample { public static void testing(String[] args) throws InterruptedException, IOException { Database<PhoneAddress> phoneAddrDB = new DatabaseArrayList<PhoneAddress>(); Database<House> houseDB = new DatabaseArrayList<House>(); Database<Component> deviceDB = new DatabaseArrayList<Component>(); //Salt example for file with house and two devices byte[] salt = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x00, 0x00}; HouseID houseID = new HouseIDValue("HouseID"); House house = new HouseImplementation("temp addr", houseID, "1234", salt); Component device1 = new ComponentSignal("device_01", houseID); Component device2 = new ComponentSignal("device_02", houseID); PhoneAddress phoneNumber = new PhoneAddressImplementation("+4529869690", houseID); houseDB.add(house); deviceDB.add(device1); deviceDB.add(device2); phoneAddrDB.add(phoneNumber); FileOutputStream f1; try { f1 = new FileOutputStream(new File("database_house.txt")); ObjectOutputStream o1 = new ObjectOutputStream (f1); FileOutputStream f2 = new FileOutputStream(new File("database_phone.txt")); ObjectOutputStream o2 = new ObjectOutputStream (f2); FileOutputStream f3 = new FileOutputStream(new File("database_component.txt")); ObjectOutputStream o3 = new ObjectOutputStream (f3); o1.writeObject(houseDB); o2.writeObject(phoneAddrDB); o3.writeObject(deviceDB); o1.close(); f1.close(); o2.close(); f2.close(); o3.close(); f3.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println("Database Setup Done"); } }
2,313
0.734544
0.697795
77
29.038961
25.894613
113
false
false
0
0
0
0
0
0
2.311688
false
false
4
cf3fb2c4f19d0ec36db1134873c62064a0df0094
27,513,560,539,048
70bcc690e36e4a6be97d19e74dc59bf5484174d1
/src/com/sp/prpall/blsvr/misc/BLPrpMaterial.java
a765820059ae70c0e1d38f55d87f02bcde50eda2
[]
no_license
haierTest/test01
https://github.com/haierTest/test01
fc819888443d49047f04d031a7d5e3c7f8724810
1c03f59e4f709f8f92608ec4a4bd5671d9d0e24b
refs/heads/master
2021-07-14T09:25:36.805000
2017-10-11T03:34:45
2017-10-11T03:34:45
106,499,408
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sp.prpall.blsvr.misc; import java.util.Vector; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.sp.prpall.dbsvr.misc.DBPrpMaterial; import com.sp.prpall.schema.PrpMaterialSchema; import com.sp.utility.SysConst; import com.sp.utility.database.DbPool; import com.sp.utility.error.UserException; /** * 定义PrpMaterial的BL类 * 从pdm中取数据库信息,根据数据库表生成对应的BL类 * <p>Title: SinosoftJavaTools v1.4</p> * <p>Description: 中科软Java源码生成工具</p> * <p>Company: Sinosoft</p> * <p>Copyright: Copyright (c) 2010</p> * <p>@createdate 2010-11-24</p> * @FirstAuthor: Zhouxianli(JavaTools v1.0) * @SecondAuthor: Yangkun(JavaTools v1.1->v1.2->v1.3->v1.4) * @LastVersion: v1.4.3 * @UpdateList: 1.新增对CIXXXXX平台类的生成处理; * 2.修正特殊表生成类cancel()、getdata()方法时获取pdm表主键入参为null的问题; * 3.修正特殊表生成类部分import类为null的问题; * 4.新增log4j日志bl层类自动初始化; * 5.getData方法新增try、catch、finally异常处理; */ public class BLPrpMaterial{ private final Log logger = LogFactory.getLog(getClass()); private Vector schemas = new Vector(); /** * 构造函数 */ public BLPrpMaterial(){ } /** *初始化记录 *@param 无 *@return 无 *@throws Exception */ public void initArr() throws Exception { schemas = new Vector(); } /** * 增加一条PrpMaterialSchema记录 * * @param iPrpMaterialSchema * PrpMaterialSchema * @throws Exception */ public void setArr(PrpMaterialSchema iPrpMaterialSchema) throws Exception { try { schemas.add(iPrpMaterialSchema); } catch (Exception e) { throw e; } } /** * 得到一条PrpMaterialSchema记录 * * @param index * 下标 * @return 一个PrpMaterialSchema对象 * @throws Exception */ public PrpMaterialSchema getArr(int index) throws Exception { PrpMaterialSchema prpMaterialSchema = null; try { prpMaterialSchema = (PrpMaterialSchema) this.schemas.get(index); } catch (Exception e) { throw e; } return prpMaterialSchema; } /** * 删除一条PrpMaterialSchema记录 * * @param index * 下标 * @throws Exception */ public void remove(int index) throws Exception { try { this.schemas.remove(index); } catch (Exception e) { throw e; } } /** * 得到schemas记录数 * * @return schemas记录数 * @throws Exception */ public int getSize() throws Exception { return this.schemas.size(); } /** * 按照查询条件得到一组记录数,并将这组记录赋给schemas对象 * * @param iWherePart * 查询条件(包括排序字句) * @throws UserException * @throws Exception */ public void query(String iWherePart) throws UserException, Exception { this.query(iWherePart, Integer.parseInt(SysConst.getProperty( "QUERY_LIMIT_COUNT").trim())); } /** *按照查询条件和记录数限制得到一组记录数,并将这组记录赋给schemas对象 *@param iWherePart 查询条件(包括排序字句) *@param iLimitCount 记录数限制(iLimitCount=0: 无限制) *@throws UserException *@throws Exception */ public void query(String iWherePart, int iLimitCount) throws UserException, Exception { String strSqlStatement = ""; DBPrpMaterial dbPrpMaterial = new DBPrpMaterial(); if (iLimitCount > 0 && dbPrpMaterial.getCount(iWherePart) > iLimitCount) { throw new UserException(-98, -1003, "BLPrpMaterial.query"); } else { initArr(); strSqlStatement = " SELECT * FROM PrpMaterial WHERE " + iWherePart; schemas = dbPrpMaterial.findByConditions(strSqlStatement); } } /** * 按照查询条件得到一组记录数,并将这组记录赋给schemas对象 * * @param dbpool * 全局池 * @param iWherePart * 查询条件(包括排序字句) * @throws UserException * @throws Exception */ public void query(DbPool dbpool, String iWherePart) throws UserException, Exception { this.query(dbpool, iWherePart, Integer.parseInt(SysConst.getProperty( "QUERY_LIMIT_COUNT").trim())); } /** *按照查询条件和记录数限制得到一组记录数,并将这组记录赋给schemas对象 *@param dbpool 全局池 *@param iWherePart 查询条件(包括排序字句) *@param iLimitCount 记录数限制(iLimitCount=0: 无限制) *@throws UserException *@throws Exception */ public void query(DbPool dbpool, String iWherePart, int iLimitCount) throws UserException, Exception { String strSqlStatement = ""; DBPrpMaterial dbPrpMaterial = new DBPrpMaterial(); if (iLimitCount > 0 && dbPrpMaterial.getCount(iWherePart) > iLimitCount) { throw new UserException(-98, -1003, "BLPrpMaterial.query"); } else { initArr(); strSqlStatement = " SELECT * FROM PrpMaterial WHERE " + iWherePart; schemas = dbPrpMaterial.findByConditions(dbpool, strSqlStatement); } } /** * 按照查询条件和记录限制数,查询条数得到一组记录数,并将这组记录赋给schemas对象 * @param strSQL sql语句 * @param rowNumCount 查询条数 * @param iLimitCount 记录限制数(iLimitCount=0: 无限制) * @throws UserException * @throws Exception * @author Administrator fanjiangtao 2013-12-19 */ public void query(String strSQL,int rowNumCount,int iLimitCount)throws UserException, Exception{ String strSqlStatement = ""; if(iLimitCount > 0 && rowNumCount > iLimitCount){ throw new UserException(-98, -1003, "BLPrpMaterial.query"); }else{ initArr(); strSqlStatement = strSQL +rowNumCount; DBPrpMaterial dbPrpMaterial = new DBPrpMaterial(); schemas = dbPrpMaterial.findByConditions(strSqlStatement); } } /** * 按照查询条件和记录限制数,查询条数得到一组记录数,并将这组记录赋给schemas对象 * @param dbpool 全局池 * @param strSQL sql语句 * @param rowNumCount 查询条数 * @param iLimitCount 记录限制数(iLimitCount=0: 无限制) * @throws UserException * @throws Exception * @author Administrator fanjingtao 20131219 */ public void query(DbPool dbpool,String strSQL,int rowNumCount,int iLimitCount)throws UserException, Exception{ String strSqlStatement = ""; if(iLimitCount > 0 && rowNumCount > iLimitCount){ throw new UserException(-98, -1003, "BLPrpMaterial.query"); }else{ initArr(); strSqlStatement = strSQL +rowNumCount; DBPrpMaterial dbPrpMaterial = new DBPrpMaterial(); schemas = dbPrpMaterial.findByConditions(dbpool,strSqlStatement); } } /** * 带dbpool的save方法 * * @param 无 * @return 无 */ public void save(DbPool dbpool) throws Exception { DBPrpMaterial dbPrpMaterial = new DBPrpMaterial(); int i = 0; for (i = 0; i < schemas.size(); i++) { dbPrpMaterial.setSchema((PrpMaterialSchema) schemas.get(i)); dbPrpMaterial.insert(dbpool); } } /** * 不带dbpool的XXXXX存方法 * * @param 无 * @return 无 */ public void save() throws Exception { DbPool dbpool = new DbPool(); try { dbpool.open(SysConst.getProperty("DDCCDATASOURCE")); dbpool.beginTransaction(); save(dbpool); dbpool.commitTransaction(); } catch (Exception e) { dbpool.rollbackTransaction(); } finally { dbpool.close(); } } /** * 带dbpool的删除方法 * * @param dbpool * 连接池 * @param iBusinessNo * BusinessNo * @return 无 */ public void cancel(DbPool dbpool, String iBusinessNo) throws Exception { String strSqlStatement = ""; strSqlStatement = " DELETE FROM PrpMaterial WHERE BusinessNo= '" + iBusinessNo + "'"; dbpool.delete(strSqlStatement); } /** * 不带dbpool的删除方法 * * @param iBusinessNo * BusinessNo * @return 无 */ public void cancel(String iBusinessNo) throws Exception { DbPool dbpool = new DbPool(); try { dbpool.open(SysConst.getProperty("DDCCDATASOURCE")); dbpool.beginTransaction(); cancel(dbpool, iBusinessNo); dbpool.commitTransaction(); } catch (Exception e) { dbpool.rollbackTransaction(); } finally { dbpool.close(); } } /** * 带dbpool根据BusinessNo获取数据 * * @param iBusinessNo * BusinessNo * @return 无 */ public void getData(String iBusinessNo) throws Exception { DbPool dbpool = new DbPool(); try { dbpool.open(SysConst.getProperty("DDCCDATASOURCE")); getData(dbpool, iBusinessNo); } catch (Exception e) { } finally { dbpool.close(); } } /** * 不带dbpool根据BusinessNo获取数据 * * @param dbpool * 连接池 * @param iBusinessNo * BusinessNo * @return 无 */ public void getData(DbPool dbpool, String iBusinessNo) throws Exception { String strWherePart = ""; strWherePart = "BusinessNo= '" + iBusinessNo + "'"; query(dbpool, strWherePart, 0); } /** * 无序查询 不带dbpool * @author wangchuanzhong 20101125 * @param iWherePart 查询条件 * @param intPageNum 页码 * @param intLineNumPage 每页条数 * @return 无 * @throws Exception */ public void queryWithoutOrder(String iWherePart,int intPageNum,int intLineNumPage) throws UserException,Exception { DbPool dbpool = new DbPool(); try { dbpool.open(SysConst.getProperty("DDCCDATASOURCE")); this.queryWithoutOrder(dbpool,iWherePart,intPageNum,intLineNumPage); }catch (Exception e) { throw e; }finally { dbpool.close(); } } /** * 无序查询 带dbpool * @author wangchuanzhong 20101125 * @param dbpool * @param iWherePart 查询条件 * @param intPageNum 页码 * @param intLineNumPage 每页条数 * @return 无 * @throws Exception */ public void queryWithoutOrder(DbPool dbpool,String iWherePart,int intPageNum,int intLineNumPage) throws UserException,Exception { StringBuffer strSqlStatement = new StringBuffer(); int intStartNum = 0; int intEndNum = 0; intStartNum = (intPageNum - 1) * intLineNumPage; intEndNum = intPageNum * intLineNumPage; DBPrpMaterial dbPrpMaterial = new DBPrpMaterial(); initArr(); strSqlStatement.append(" SELECT * FROM ( "); strSqlStatement.append("Select RowNum As LineNum,M.* From ( "); strSqlStatement.append("Select * From PrpMaterial PM Where "); strSqlStatement.append(iWherePart); strSqlStatement.append(" And PM.SerialNo =(Select MAX(Serialno) From PrpMaterial inPM Where inPM.BusinessNo = PM.BusinessNo)"); strSqlStatement.append(") M Where RowNum<="); strSqlStatement.append(intEndNum); strSqlStatement.append(") Where LineNum>"); strSqlStatement.append(intStartNum); schemas = dbPrpMaterial.findByConditions(dbpool,strSqlStatement.toString()); } /** * 有序查询 带dbpool * @author ronglijun 20140617 * @param dbpool * @param iWherePart 查询条件 * @param intPageNum 页码 * @param intLineNumPage 每页条数 * @return 无 * @throws Exception */ public void queryByOrderNew(DbPool dbpool,String iWherePart,int intPageNum,int intLineNumPage) throws UserException,Exception { StringBuffer strSqlStatement = new StringBuffer(); int intStartNum = 0; int intEndNum = 0; intStartNum = (intPageNum - 1) * intLineNumPage; intEndNum = intPageNum * intLineNumPage; DBPrpMaterial dbPrpMaterial = new DBPrpMaterial(); initArr(); strSqlStatement.append(" SELECT x.* from( "); strSqlStatement.append("SELECT z.*,rownum numbers from( "); strSqlStatement.append("select * from PrpMaterial where "); strSqlStatement.append(iWherePart); strSqlStatement.append(" order by Serialno ) z "); strSqlStatement.append(" Where RowNum<="); strSqlStatement.append(intEndNum); strSqlStatement.append(") x Where x.numbers>"); strSqlStatement.append(intStartNum); schemas = dbPrpMaterial.findByConditions(dbpool,strSqlStatement.toString()); } /** * y序查询 带dbpool * @author ronglijun 20101125 * @param dbpool * @param iWherePart 查询条件 * @param intPageNum 页码 * @param intLineNumPage 每页条数 * @return 无 * @throws Exception */ public void queryByOrder(String iWherePart,int intPageNum,int intLineNumPage) throws UserException,Exception { DbPool dbpool = new DbPool(); try { dbpool.open(SysConst.getProperty("DDCCDATASOURCE")); this.queryByOrderNew(dbpool,iWherePart,intPageNum,intLineNumPage); }catch (Exception e) { throw e; }finally { dbpool.close(); } } /** * 不带dbpool的更新方法 *@return 无 */ public void update() throws Exception { DbPool dbpool = new DbPool(); try { dbpool.open(SysConst.getProperty("DDCCDATASOURCE")); dbpool.beginTransaction(); update(dbpool); dbpool.commitTransaction(); } catch (Exception e) { dbpool.rollbackTransaction(); } finally { dbpool.close(); } } /** *带dbpool的更新方法 *@param dbpool 连接池 *@return 无 */ public void update(DbPool dbpool) throws Exception { DBPrpMaterial dbPrpMaterial = new DBPrpMaterial(); int i = 0; for(i = 0; i< schemas.size(); i++) { dbPrpMaterial.setSchema((PrpMaterialSchema)schemas.get(i)); dbPrpMaterial.update(dbpool); } } /** * 主函数 * * @param args * 参数列表 */ public static void main(String[] args){ } }
GB18030
Java
14,601
java
BLPrpMaterial.java
Java
[ { "context": "\n * <p>@createdate 2010-11-24</p>\n * @FirstAuthor: Zhouxianli(JavaTools v1.0)\n * @SecondAuthor: Yangkun(JavaToo", "end": 616, "score": 0.9996973276138306, "start": 606, "tag": "NAME", "value": "Zhouxianli" }, { "context": "thor: Zhouxianli(JavaTools v1.0)\n * @SecondAuthor: Yangkun(JavaTools v1.1->v1.2->v1.3->v1.4)\n * @LastVersion", "end": 658, "score": 0.9985278248786926, "start": 651, "tag": "NAME", "value": "Yangkun" }, { "context": " * @throws Exception\n * @author Administrator fanjiangtao 2013-12-19\n */\n public void query(String s", "end": 4825, "score": 0.8120256066322327, "start": 4814, "tag": "USERNAME", "value": "fanjiangtao" }, { "context": " @throws Exception\n * @author Administrator fanjingtao 20131219\n */\n public void query(DbPool dbp", "end": 5676, "score": 0.9032791256904602, "start": 5666, "tag": "USERNAME", "value": "fanjingtao" }, { "context": "0);\n\t}\n /**\n * 无序查询 不带dbpool\n * @author wangchuanzhong 20101125\n * @param iWherePart 查询条件\n * @pa", "end": 8576, "score": 0.9933171272277832, "start": 8562, "tag": "USERNAME", "value": "wangchuanzhong" }, { "context": "}\n }\n /**\n * 无序查询 带dbpool\n * @author wangchuanzhong 20101125\n * @param dbpool\n * @param iWher", "end": 9202, "score": 0.9954906105995178, "start": 9188, "tag": "USERNAME", "value": "wangchuanzhong" }, { "context": " \n /**\n * 有序查询 带dbpool\n * @author ronglijun 20140617\n * @param dbpool\n * @param iWh", "end": 10544, "score": 0.9910537600517273, "start": 10535, "tag": "USERNAME", "value": "ronglijun" }, { "context": " \n \n /**\n * y序查询 带dbpool\n * @author ronglijun 20101125\n * @param dbpool\n * @param iWh", "end": 11810, "score": 0.9984743595123291, "start": 11801, "tag": "USERNAME", "value": "ronglijun" } ]
null
[]
package com.sp.prpall.blsvr.misc; import java.util.Vector; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.sp.prpall.dbsvr.misc.DBPrpMaterial; import com.sp.prpall.schema.PrpMaterialSchema; import com.sp.utility.SysConst; import com.sp.utility.database.DbPool; import com.sp.utility.error.UserException; /** * 定义PrpMaterial的BL类 * 从pdm中取数据库信息,根据数据库表生成对应的BL类 * <p>Title: SinosoftJavaTools v1.4</p> * <p>Description: 中科软Java源码生成工具</p> * <p>Company: Sinosoft</p> * <p>Copyright: Copyright (c) 2010</p> * <p>@createdate 2010-11-24</p> * @FirstAuthor: Zhouxianli(JavaTools v1.0) * @SecondAuthor: Yangkun(JavaTools v1.1->v1.2->v1.3->v1.4) * @LastVersion: v1.4.3 * @UpdateList: 1.新增对CIXXXXX平台类的生成处理; * 2.修正特殊表生成类cancel()、getdata()方法时获取pdm表主键入参为null的问题; * 3.修正特殊表生成类部分import类为null的问题; * 4.新增log4j日志bl层类自动初始化; * 5.getData方法新增try、catch、finally异常处理; */ public class BLPrpMaterial{ private final Log logger = LogFactory.getLog(getClass()); private Vector schemas = new Vector(); /** * 构造函数 */ public BLPrpMaterial(){ } /** *初始化记录 *@param 无 *@return 无 *@throws Exception */ public void initArr() throws Exception { schemas = new Vector(); } /** * 增加一条PrpMaterialSchema记录 * * @param iPrpMaterialSchema * PrpMaterialSchema * @throws Exception */ public void setArr(PrpMaterialSchema iPrpMaterialSchema) throws Exception { try { schemas.add(iPrpMaterialSchema); } catch (Exception e) { throw e; } } /** * 得到一条PrpMaterialSchema记录 * * @param index * 下标 * @return 一个PrpMaterialSchema对象 * @throws Exception */ public PrpMaterialSchema getArr(int index) throws Exception { PrpMaterialSchema prpMaterialSchema = null; try { prpMaterialSchema = (PrpMaterialSchema) this.schemas.get(index); } catch (Exception e) { throw e; } return prpMaterialSchema; } /** * 删除一条PrpMaterialSchema记录 * * @param index * 下标 * @throws Exception */ public void remove(int index) throws Exception { try { this.schemas.remove(index); } catch (Exception e) { throw e; } } /** * 得到schemas记录数 * * @return schemas记录数 * @throws Exception */ public int getSize() throws Exception { return this.schemas.size(); } /** * 按照查询条件得到一组记录数,并将这组记录赋给schemas对象 * * @param iWherePart * 查询条件(包括排序字句) * @throws UserException * @throws Exception */ public void query(String iWherePart) throws UserException, Exception { this.query(iWherePart, Integer.parseInt(SysConst.getProperty( "QUERY_LIMIT_COUNT").trim())); } /** *按照查询条件和记录数限制得到一组记录数,并将这组记录赋给schemas对象 *@param iWherePart 查询条件(包括排序字句) *@param iLimitCount 记录数限制(iLimitCount=0: 无限制) *@throws UserException *@throws Exception */ public void query(String iWherePart, int iLimitCount) throws UserException, Exception { String strSqlStatement = ""; DBPrpMaterial dbPrpMaterial = new DBPrpMaterial(); if (iLimitCount > 0 && dbPrpMaterial.getCount(iWherePart) > iLimitCount) { throw new UserException(-98, -1003, "BLPrpMaterial.query"); } else { initArr(); strSqlStatement = " SELECT * FROM PrpMaterial WHERE " + iWherePart; schemas = dbPrpMaterial.findByConditions(strSqlStatement); } } /** * 按照查询条件得到一组记录数,并将这组记录赋给schemas对象 * * @param dbpool * 全局池 * @param iWherePart * 查询条件(包括排序字句) * @throws UserException * @throws Exception */ public void query(DbPool dbpool, String iWherePart) throws UserException, Exception { this.query(dbpool, iWherePart, Integer.parseInt(SysConst.getProperty( "QUERY_LIMIT_COUNT").trim())); } /** *按照查询条件和记录数限制得到一组记录数,并将这组记录赋给schemas对象 *@param dbpool 全局池 *@param iWherePart 查询条件(包括排序字句) *@param iLimitCount 记录数限制(iLimitCount=0: 无限制) *@throws UserException *@throws Exception */ public void query(DbPool dbpool, String iWherePart, int iLimitCount) throws UserException, Exception { String strSqlStatement = ""; DBPrpMaterial dbPrpMaterial = new DBPrpMaterial(); if (iLimitCount > 0 && dbPrpMaterial.getCount(iWherePart) > iLimitCount) { throw new UserException(-98, -1003, "BLPrpMaterial.query"); } else { initArr(); strSqlStatement = " SELECT * FROM PrpMaterial WHERE " + iWherePart; schemas = dbPrpMaterial.findByConditions(dbpool, strSqlStatement); } } /** * 按照查询条件和记录限制数,查询条数得到一组记录数,并将这组记录赋给schemas对象 * @param strSQL sql语句 * @param rowNumCount 查询条数 * @param iLimitCount 记录限制数(iLimitCount=0: 无限制) * @throws UserException * @throws Exception * @author Administrator fanjiangtao 2013-12-19 */ public void query(String strSQL,int rowNumCount,int iLimitCount)throws UserException, Exception{ String strSqlStatement = ""; if(iLimitCount > 0 && rowNumCount > iLimitCount){ throw new UserException(-98, -1003, "BLPrpMaterial.query"); }else{ initArr(); strSqlStatement = strSQL +rowNumCount; DBPrpMaterial dbPrpMaterial = new DBPrpMaterial(); schemas = dbPrpMaterial.findByConditions(strSqlStatement); } } /** * 按照查询条件和记录限制数,查询条数得到一组记录数,并将这组记录赋给schemas对象 * @param dbpool 全局池 * @param strSQL sql语句 * @param rowNumCount 查询条数 * @param iLimitCount 记录限制数(iLimitCount=0: 无限制) * @throws UserException * @throws Exception * @author Administrator fanjingtao 20131219 */ public void query(DbPool dbpool,String strSQL,int rowNumCount,int iLimitCount)throws UserException, Exception{ String strSqlStatement = ""; if(iLimitCount > 0 && rowNumCount > iLimitCount){ throw new UserException(-98, -1003, "BLPrpMaterial.query"); }else{ initArr(); strSqlStatement = strSQL +rowNumCount; DBPrpMaterial dbPrpMaterial = new DBPrpMaterial(); schemas = dbPrpMaterial.findByConditions(dbpool,strSqlStatement); } } /** * 带dbpool的save方法 * * @param 无 * @return 无 */ public void save(DbPool dbpool) throws Exception { DBPrpMaterial dbPrpMaterial = new DBPrpMaterial(); int i = 0; for (i = 0; i < schemas.size(); i++) { dbPrpMaterial.setSchema((PrpMaterialSchema) schemas.get(i)); dbPrpMaterial.insert(dbpool); } } /** * 不带dbpool的XXXXX存方法 * * @param 无 * @return 无 */ public void save() throws Exception { DbPool dbpool = new DbPool(); try { dbpool.open(SysConst.getProperty("DDCCDATASOURCE")); dbpool.beginTransaction(); save(dbpool); dbpool.commitTransaction(); } catch (Exception e) { dbpool.rollbackTransaction(); } finally { dbpool.close(); } } /** * 带dbpool的删除方法 * * @param dbpool * 连接池 * @param iBusinessNo * BusinessNo * @return 无 */ public void cancel(DbPool dbpool, String iBusinessNo) throws Exception { String strSqlStatement = ""; strSqlStatement = " DELETE FROM PrpMaterial WHERE BusinessNo= '" + iBusinessNo + "'"; dbpool.delete(strSqlStatement); } /** * 不带dbpool的删除方法 * * @param iBusinessNo * BusinessNo * @return 无 */ public void cancel(String iBusinessNo) throws Exception { DbPool dbpool = new DbPool(); try { dbpool.open(SysConst.getProperty("DDCCDATASOURCE")); dbpool.beginTransaction(); cancel(dbpool, iBusinessNo); dbpool.commitTransaction(); } catch (Exception e) { dbpool.rollbackTransaction(); } finally { dbpool.close(); } } /** * 带dbpool根据BusinessNo获取数据 * * @param iBusinessNo * BusinessNo * @return 无 */ public void getData(String iBusinessNo) throws Exception { DbPool dbpool = new DbPool(); try { dbpool.open(SysConst.getProperty("DDCCDATASOURCE")); getData(dbpool, iBusinessNo); } catch (Exception e) { } finally { dbpool.close(); } } /** * 不带dbpool根据BusinessNo获取数据 * * @param dbpool * 连接池 * @param iBusinessNo * BusinessNo * @return 无 */ public void getData(DbPool dbpool, String iBusinessNo) throws Exception { String strWherePart = ""; strWherePart = "BusinessNo= '" + iBusinessNo + "'"; query(dbpool, strWherePart, 0); } /** * 无序查询 不带dbpool * @author wangchuanzhong 20101125 * @param iWherePart 查询条件 * @param intPageNum 页码 * @param intLineNumPage 每页条数 * @return 无 * @throws Exception */ public void queryWithoutOrder(String iWherePart,int intPageNum,int intLineNumPage) throws UserException,Exception { DbPool dbpool = new DbPool(); try { dbpool.open(SysConst.getProperty("DDCCDATASOURCE")); this.queryWithoutOrder(dbpool,iWherePart,intPageNum,intLineNumPage); }catch (Exception e) { throw e; }finally { dbpool.close(); } } /** * 无序查询 带dbpool * @author wangchuanzhong 20101125 * @param dbpool * @param iWherePart 查询条件 * @param intPageNum 页码 * @param intLineNumPage 每页条数 * @return 无 * @throws Exception */ public void queryWithoutOrder(DbPool dbpool,String iWherePart,int intPageNum,int intLineNumPage) throws UserException,Exception { StringBuffer strSqlStatement = new StringBuffer(); int intStartNum = 0; int intEndNum = 0; intStartNum = (intPageNum - 1) * intLineNumPage; intEndNum = intPageNum * intLineNumPage; DBPrpMaterial dbPrpMaterial = new DBPrpMaterial(); initArr(); strSqlStatement.append(" SELECT * FROM ( "); strSqlStatement.append("Select RowNum As LineNum,M.* From ( "); strSqlStatement.append("Select * From PrpMaterial PM Where "); strSqlStatement.append(iWherePart); strSqlStatement.append(" And PM.SerialNo =(Select MAX(Serialno) From PrpMaterial inPM Where inPM.BusinessNo = PM.BusinessNo)"); strSqlStatement.append(") M Where RowNum<="); strSqlStatement.append(intEndNum); strSqlStatement.append(") Where LineNum>"); strSqlStatement.append(intStartNum); schemas = dbPrpMaterial.findByConditions(dbpool,strSqlStatement.toString()); } /** * 有序查询 带dbpool * @author ronglijun 20140617 * @param dbpool * @param iWherePart 查询条件 * @param intPageNum 页码 * @param intLineNumPage 每页条数 * @return 无 * @throws Exception */ public void queryByOrderNew(DbPool dbpool,String iWherePart,int intPageNum,int intLineNumPage) throws UserException,Exception { StringBuffer strSqlStatement = new StringBuffer(); int intStartNum = 0; int intEndNum = 0; intStartNum = (intPageNum - 1) * intLineNumPage; intEndNum = intPageNum * intLineNumPage; DBPrpMaterial dbPrpMaterial = new DBPrpMaterial(); initArr(); strSqlStatement.append(" SELECT x.* from( "); strSqlStatement.append("SELECT z.*,rownum numbers from( "); strSqlStatement.append("select * from PrpMaterial where "); strSqlStatement.append(iWherePart); strSqlStatement.append(" order by Serialno ) z "); strSqlStatement.append(" Where RowNum<="); strSqlStatement.append(intEndNum); strSqlStatement.append(") x Where x.numbers>"); strSqlStatement.append(intStartNum); schemas = dbPrpMaterial.findByConditions(dbpool,strSqlStatement.toString()); } /** * y序查询 带dbpool * @author ronglijun 20101125 * @param dbpool * @param iWherePart 查询条件 * @param intPageNum 页码 * @param intLineNumPage 每页条数 * @return 无 * @throws Exception */ public void queryByOrder(String iWherePart,int intPageNum,int intLineNumPage) throws UserException,Exception { DbPool dbpool = new DbPool(); try { dbpool.open(SysConst.getProperty("DDCCDATASOURCE")); this.queryByOrderNew(dbpool,iWherePart,intPageNum,intLineNumPage); }catch (Exception e) { throw e; }finally { dbpool.close(); } } /** * 不带dbpool的更新方法 *@return 无 */ public void update() throws Exception { DbPool dbpool = new DbPool(); try { dbpool.open(SysConst.getProperty("DDCCDATASOURCE")); dbpool.beginTransaction(); update(dbpool); dbpool.commitTransaction(); } catch (Exception e) { dbpool.rollbackTransaction(); } finally { dbpool.close(); } } /** *带dbpool的更新方法 *@param dbpool 连接池 *@return 无 */ public void update(DbPool dbpool) throws Exception { DBPrpMaterial dbPrpMaterial = new DBPrpMaterial(); int i = 0; for(i = 0; i< schemas.size(); i++) { dbPrpMaterial.setSchema((PrpMaterialSchema)schemas.get(i)); dbPrpMaterial.update(dbpool); } } /** * 主函数 * * @param args * 参数列表 */ public static void main(String[] args){ } }
14,601
0.626882
0.617684
488
26.625
23.456289
134
false
false
0
0
0
0
0
0
1.055328
false
false
4
1dda9ea727c0ed247f56d09e488845c95d5b7a00
27,513,560,535,798
aaa5d5ffe73616013e0214477f2a940f2c78fb3d
/src/main/java/com/it/different/courses/internetprovider/services/dto/AddressDTO.java
0b2c5718d1b40a6c35a3af188d1e7f59cce19fbf
[]
no_license
cefothe/internet-provider
https://github.com/cefothe/internet-provider
c5367786c11ea670f9e14fb4e1c32a17dd75b75a
c0dafee3de21fe2edb129cce421e208184a9f7f2
refs/heads/master
2022-12-20T05:03:09.257000
2020-09-23T18:01:02
2020-09-23T18:01:02
290,603,333
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.it.different.courses.internetprovider.services.dto; import lombok.AccessLevel; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; @Getter @Builder @NoArgsConstructor(access = AccessLevel.PROTECTED) public class AddressDTO { private String city; private String street; private String country; }
UTF-8
Java
338
java
AddressDTO.java
Java
[]
null
[]
package com.it.different.courses.internetprovider.services.dto; import lombok.AccessLevel; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; @Getter @Builder @NoArgsConstructor(access = AccessLevel.PROTECTED) public class AddressDTO { private String city; private String street; private String country; }
338
0.819527
0.819527
15
21.533333
17.173105
63
false
false
0
0
0
0
0
0
0.733333
false
false
4
f293cd9f140e3f4f24a6d337b492ba5a6d492a96
19,816,979,104,359
f1c6b9d94061df9e90fd8f4bca903887a82c0591
/app/src/main/java/com/example/faazahmad/androidapp/MainActivity.java
1fdca98538a9f9fe1cc31231c021194a1c0bb0c1
[]
no_license
faazkhan/AndroidApp
https://github.com/faazkhan/AndroidApp
93854c3bacf33fefd1275865813b756a89df0be3
5a447759e3b5a4f5741707c0c0bdea37f13eb473
refs/heads/master
2022-12-01T00:30:04.250000
2020-08-22T18:58:27
2020-08-22T18:58:27
287,783,848
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.faazahmad.androidapp; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.VolleyLog; import com.android.volley.toolbox.JsonArrayRequest; import com.example.faazahmad.androidapp.adapter.CustomAdapter; import com.example.faazahmad.androidapp.model.Movie; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class MainActivity extends AppCompatActivity { private ListView lv; SharedPreferences sharedpreferences; public static final String MyPREFERENCES = "MyPrefs"; private static final String url = "https://api.androidhive.info/json/movies.json"; private List<Movie> movieList = new ArrayList<Movie>(); private CustomAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button reload = findViewById(R.id.button); Button logout = findViewById(R.id.logout); sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE); lv = (ListView) findViewById(R.id.userlist); adapter = new CustomAdapter(this, movieList); lv.setAdapter(adapter); populateList(); reload.setOnClickListener(new View.OnClickListener() { @SuppressLint("LongLogTag") @Override public void onClick(View v) { populateList(); } }); logout.setOnClickListener(new View.OnClickListener() { @SuppressLint("LongLogTag") @Override public void onClick(View v) { sharedpreferences.edit().putBoolean("logged", false).apply(); goToLogin(); } }); // listening to single list item on click lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Movie movie = (Movie) adapter.getItem(position); // Launching new Activity on selecting single List Item Intent i = new Intent(MainActivity.this, SecondActivity.class); // sending data to new activity i.putExtra("movie", movie); startActivity(i); } }); } private JsonArrayRequest fetchMovieData() { return new JsonArrayRequest(url, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { Log.d("Log", response.toString()); movieList.clear(); // Parsing json for (int i = 0; i < response.length(); i++) { try { JSONObject obj = response.getJSONObject(i); Movie movie = new Movie(); movie.setTitle(obj.getString("title")); movie.setThumbnailUrl(obj.getString("image")); movie.setRating("Rating: "+obj.get("rating").toString()); movie.setYear(""+ obj.getInt("releaseYear")); // Genre is json array JSONArray genreArry = obj.getJSONArray("genre"); ArrayList<String> genre = new ArrayList<String>(); for (int j = 0; j < genreArry.length(); j++) { genre.add((String) genreArry.get(j)); } movie.setGenre(genre); // adding movie to movies array movieList.add(movie); } catch (JSONException e) { e.printStackTrace(); } } Collections.shuffle(movieList); // notifying list adapter about data changes // so that it renders the list view with updated data adapter.notifyDataSetChanged(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d("Error", "Error: " + error.getMessage()); // hidePDialog(); } }); } private void populateList() { if (online()) { new GetMovies().execute(); } else { read(); } } private class GetMovies extends AsyncTask<Void, Void, Void> { @Override protected void onPreExecute() { super.onPreExecute(); Toast.makeText(MainActivity.this, "Json Data is downloading", Toast.LENGTH_SHORT).show(); } @Override protected Void doInBackground(Void... arg0) { AppController.getInstance().addToRequestQueue(fetchMovieData()); return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); save(movieList); } } private Boolean read() { Toast.makeText(getApplicationContext(), "Reading Local Databases.", Toast.LENGTH_SHORT).show(); Gson gson = new Gson(); String json = sharedpreferences.getString("movieList", ""); if (json.isEmpty()) { Toast.makeText(getApplicationContext(), "Local Database is empty.", Toast.LENGTH_SHORT).show(); return false; } else { Type type = new TypeToken<List<Movie> >() {}.getType(); List<Movie> movies = gson.fromJson(json, type); if(movies.isEmpty()){ Toast.makeText(getApplicationContext(), "Local List is empty.", Toast.LENGTH_SHORT).show(); return false; } Log.i("list",""+movies.size()); movieList.clear(); movieList.addAll(movies); Collections.shuffle(movieList); adapter.notifyDataSetChanged(); return true; } } private void save(List<Movie> movieList){ Gson gson = new Gson(); String json = gson.toJson(movieList); SharedPreferences.Editor editor = sharedpreferences.edit(); Toast.makeText(getApplicationContext(), "Clearing Previous Records from DB.", Toast.LENGTH_SHORT).show(); editor.remove("movieList"); editor.commit(); Toast.makeText(getApplicationContext(), "Saving Latest Records.", Toast.LENGTH_SHORT).show(); editor.putString("movieList",json); editor.commit(); } public void goToLogin(){ Intent i = new Intent(this,Login.class); startActivity(i); } public Boolean online() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); return activeNetwork != null && activeNetwork.getType() == ConnectivityManager.TYPE_WIFI; } }
UTF-8
Java
8,235
java
MainActivity.java
Java
[]
null
[]
package com.example.faazahmad.androidapp; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.VolleyLog; import com.android.volley.toolbox.JsonArrayRequest; import com.example.faazahmad.androidapp.adapter.CustomAdapter; import com.example.faazahmad.androidapp.model.Movie; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class MainActivity extends AppCompatActivity { private ListView lv; SharedPreferences sharedpreferences; public static final String MyPREFERENCES = "MyPrefs"; private static final String url = "https://api.androidhive.info/json/movies.json"; private List<Movie> movieList = new ArrayList<Movie>(); private CustomAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button reload = findViewById(R.id.button); Button logout = findViewById(R.id.logout); sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE); lv = (ListView) findViewById(R.id.userlist); adapter = new CustomAdapter(this, movieList); lv.setAdapter(adapter); populateList(); reload.setOnClickListener(new View.OnClickListener() { @SuppressLint("LongLogTag") @Override public void onClick(View v) { populateList(); } }); logout.setOnClickListener(new View.OnClickListener() { @SuppressLint("LongLogTag") @Override public void onClick(View v) { sharedpreferences.edit().putBoolean("logged", false).apply(); goToLogin(); } }); // listening to single list item on click lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Movie movie = (Movie) adapter.getItem(position); // Launching new Activity on selecting single List Item Intent i = new Intent(MainActivity.this, SecondActivity.class); // sending data to new activity i.putExtra("movie", movie); startActivity(i); } }); } private JsonArrayRequest fetchMovieData() { return new JsonArrayRequest(url, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { Log.d("Log", response.toString()); movieList.clear(); // Parsing json for (int i = 0; i < response.length(); i++) { try { JSONObject obj = response.getJSONObject(i); Movie movie = new Movie(); movie.setTitle(obj.getString("title")); movie.setThumbnailUrl(obj.getString("image")); movie.setRating("Rating: "+obj.get("rating").toString()); movie.setYear(""+ obj.getInt("releaseYear")); // Genre is json array JSONArray genreArry = obj.getJSONArray("genre"); ArrayList<String> genre = new ArrayList<String>(); for (int j = 0; j < genreArry.length(); j++) { genre.add((String) genreArry.get(j)); } movie.setGenre(genre); // adding movie to movies array movieList.add(movie); } catch (JSONException e) { e.printStackTrace(); } } Collections.shuffle(movieList); // notifying list adapter about data changes // so that it renders the list view with updated data adapter.notifyDataSetChanged(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d("Error", "Error: " + error.getMessage()); // hidePDialog(); } }); } private void populateList() { if (online()) { new GetMovies().execute(); } else { read(); } } private class GetMovies extends AsyncTask<Void, Void, Void> { @Override protected void onPreExecute() { super.onPreExecute(); Toast.makeText(MainActivity.this, "Json Data is downloading", Toast.LENGTH_SHORT).show(); } @Override protected Void doInBackground(Void... arg0) { AppController.getInstance().addToRequestQueue(fetchMovieData()); return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); save(movieList); } } private Boolean read() { Toast.makeText(getApplicationContext(), "Reading Local Databases.", Toast.LENGTH_SHORT).show(); Gson gson = new Gson(); String json = sharedpreferences.getString("movieList", ""); if (json.isEmpty()) { Toast.makeText(getApplicationContext(), "Local Database is empty.", Toast.LENGTH_SHORT).show(); return false; } else { Type type = new TypeToken<List<Movie> >() {}.getType(); List<Movie> movies = gson.fromJson(json, type); if(movies.isEmpty()){ Toast.makeText(getApplicationContext(), "Local List is empty.", Toast.LENGTH_SHORT).show(); return false; } Log.i("list",""+movies.size()); movieList.clear(); movieList.addAll(movies); Collections.shuffle(movieList); adapter.notifyDataSetChanged(); return true; } } private void save(List<Movie> movieList){ Gson gson = new Gson(); String json = gson.toJson(movieList); SharedPreferences.Editor editor = sharedpreferences.edit(); Toast.makeText(getApplicationContext(), "Clearing Previous Records from DB.", Toast.LENGTH_SHORT).show(); editor.remove("movieList"); editor.commit(); Toast.makeText(getApplicationContext(), "Saving Latest Records.", Toast.LENGTH_SHORT).show(); editor.putString("movieList",json); editor.commit(); } public void goToLogin(){ Intent i = new Intent(this,Login.class); startActivity(i); } public Boolean online() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); return activeNetwork != null && activeNetwork.getType() == ConnectivityManager.TYPE_WIFI; } }
8,235
0.562356
0.56187
222
36.094593
27.555595
113
false
false
0
0
0
0
0
0
0.662162
false
false
4
fec628e5288980233007b451e09b477c9f2eee3d
14,336,600,835,409
501bff64e7b38baa2c690cbd02ecef7a4ad6d4c3
/src/main/java/com/bridgelabz/parking/lot/vehicledetails/IPredicate.java
d6abdbfeac84bb911ce2f742df1710b55a3c5659
[]
no_license
kn52/Parking_Lot_Problem
https://github.com/kn52/Parking_Lot_Problem
91c49b1deb28fce2a0d3378e3b151b47f4d183af
e66351db717a76bef2f104a6769e2d3a4e0cd849
refs/heads/master
2021-04-04T22:42:22.628000
2020-04-06T12:42:13
2020-04-06T12:42:13
248,497,013
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bridgelabz.parking.lot.vehicledetails; import com.bridgelabz.parking.lot.parkinglotdetails.SlotDetails; import java.util.function.Predicate; public interface IPredicate { Predicate<SlotDetails> getPredicate(IPredicate ipredicate); }
UTF-8
Java
250
java
IPredicate.java
Java
[]
null
[]
package com.bridgelabz.parking.lot.vehicledetails; import com.bridgelabz.parking.lot.parkinglotdetails.SlotDetails; import java.util.function.Predicate; public interface IPredicate { Predicate<SlotDetails> getPredicate(IPredicate ipredicate); }
250
0.836
0.836
7
34.714287
24.690741
64
false
false
0
0
0
0
0
0
0.571429
false
false
4
4e806e17a3e07b196e07417c37765ffe034b8e3a
2,353,642,109,986
fa58b461f0317f148b76788c545a79c386c9d82b
/hospital/src/main/java/com/song/service/Impl/SalaryServiceImpl.java
b76893dfcdbee8970d57aacec1fa8fa2bc6420fa
[]
no_license
Jeromest/workspace
https://github.com/Jeromest/workspace
c3b3fa40b5922be8978c3c7fda3351552309a941
3837450ea6a058dd21b3e8fab08c02ee3990fab8
refs/heads/main
2023-06-12T18:52:55.258000
2021-07-05T18:48:24
2021-07-05T18:48:24
383,232,572
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.song.service.Impl; import com.song.dao.SalaryDao; import com.song.pojo.PageInfo; import com.song.pojo.Salary; import com.song.service.SalaryService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service("salaryService") public class SalaryServiceImpl implements SalaryService { @Autowired private SalaryDao salaryDao; public int addSalary(Salary salary) { return salaryDao.addSalary(salary); } public int updateSalary(Salary salary) { return salaryDao.updateSalary(salary); } public Salary findSalaryById(Integer salaryId) { return salaryDao.findSalaryById(salaryId); } public List<Salary> getAll() { return salaryDao.getAll(); } public PageInfo<Salary> findPageInfo(String salaryNo, String salaryName, Integer pageIndex, Integer pageSize) { PageInfo<Salary> pi = new PageInfo<Salary>(); pi.setPageIndex(pageIndex); pi.setPageSize(pageSize); //获取总条数 Integer totalCount = salaryDao.totalCount(salaryNo,salaryName); if (totalCount>0){ pi.setTotalCount(totalCount); //每一页显示管理员信息数 //currentPage = (pageIndex-1)*pageSize 当前页码数减1*最大条数=开始行数 List<Salary> salaryList = salaryDao.getSalaryList(salaryNo,salaryName, (pi.getPageIndex()-1)*pi.getPageSize(),pi.getPageSize()); pi.setList(salaryList); } return pi; } }
UTF-8
Java
1,597
java
SalaryServiceImpl.java
Java
[]
null
[]
package com.song.service.Impl; import com.song.dao.SalaryDao; import com.song.pojo.PageInfo; import com.song.pojo.Salary; import com.song.service.SalaryService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service("salaryService") public class SalaryServiceImpl implements SalaryService { @Autowired private SalaryDao salaryDao; public int addSalary(Salary salary) { return salaryDao.addSalary(salary); } public int updateSalary(Salary salary) { return salaryDao.updateSalary(salary); } public Salary findSalaryById(Integer salaryId) { return salaryDao.findSalaryById(salaryId); } public List<Salary> getAll() { return salaryDao.getAll(); } public PageInfo<Salary> findPageInfo(String salaryNo, String salaryName, Integer pageIndex, Integer pageSize) { PageInfo<Salary> pi = new PageInfo<Salary>(); pi.setPageIndex(pageIndex); pi.setPageSize(pageSize); //获取总条数 Integer totalCount = salaryDao.totalCount(salaryNo,salaryName); if (totalCount>0){ pi.setTotalCount(totalCount); //每一页显示管理员信息数 //currentPage = (pageIndex-1)*pageSize 当前页码数减1*最大条数=开始行数 List<Salary> salaryList = salaryDao.getSalaryList(salaryNo,salaryName, (pi.getPageIndex()-1)*pi.getPageSize(),pi.getPageSize()); pi.setList(salaryList); } return pi; } }
1,597
0.681197
0.678595
49
30.367348
25.612253
115
false
false
0
0
0
0
0
0
0.571429
false
false
4
2ba06bf6a6a14c866d5128cef9e4b1d303e58f8f
27,943,057,293,056
7474d95cd5e75b60439c5f2afe224ddd9a6475df
/src/main/java/com/test/bank/constant/Role.java
03726108d136d4946a04d53185f85a6c8fd17b98
[]
no_license
chenpighead/java-backend-home-project
https://github.com/chenpighead/java-backend-home-project
40cf408e78b975c6714a9c04259b34f9557c4ec0
357b3f9827c2751568e65f021bdbf3a6c8312442
refs/heads/master
2020-04-21T14:15:25.615000
2019-02-08T04:07:09
2019-02-08T04:35:57
169,628,696
0
0
null
true
2019-02-07T19:24:15
2019-02-07T19:24:14
2019-01-18T08:28:53
2019-01-22T02:56:49
51
0
0
0
null
false
null
package com.test.bank.constant; public class Role { public static final String TRANSFER = "1"; public static final String VIEW_TRANSACTION_LOG = "2"; public static final String CREDIT_AND_DEBIT = "3"; public static final String SUPER_ADMIN = "4"; }
UTF-8
Java
266
java
Role.java
Java
[]
null
[]
package com.test.bank.constant; public class Role { public static final String TRANSFER = "1"; public static final String VIEW_TRANSACTION_LOG = "2"; public static final String CREDIT_AND_DEBIT = "3"; public static final String SUPER_ADMIN = "4"; }
266
0.703008
0.68797
8
32.25
21.79306
58
false
false
0
0
0
0
0
0
0.625
false
false
4
e095df336634d88390b0bffa1e0d2c5b461abdd6
5,471,788,343,907
d851580f8f79228963f0fbfc7cc12aff18d4a9f3
/assignments/src/assignments/assignment29.java
e579877f85f070b0f6cdcfd61cfdfd8245bd9049
[]
no_license
Sumanth-Govinde/TrainingSessions
https://github.com/Sumanth-Govinde/TrainingSessions
2bb0532bdd938dfd19bde5c3dd57e7fddf73aa75
54c6ed838c7153562091caf179fe8045c518f59a
refs/heads/master
2020-04-05T08:05:07.901000
2018-11-21T11:58:11
2018-11-21T11:58:11
156,700,518
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package assignments; public class assignment29 { public static void main(String[] args) { // TODO Auto-generated method stub int a[]=new int[10]; for(int i=0;i<10;i++) a[i]=(i+1)*2; for(int i=0;i<10;i++) System.out.print(a[i]+" "); } }
UTF-8
Java
271
java
assignment29.java
Java
[]
null
[]
package assignments; public class assignment29 { public static void main(String[] args) { // TODO Auto-generated method stub int a[]=new int[10]; for(int i=0;i<10;i++) a[i]=(i+1)*2; for(int i=0;i<10;i++) System.out.print(a[i]+" "); } }
271
0.571956
0.527675
15
16.066668
13.992697
41
false
false
0
0
0
0
0
0
1.6
false
false
4
ff8240539a400fa08528f8b70bdf32245692be43
5,471,788,344,455
12b24e75b2a739a58aa0c167762c23dcf3cfcce0
/src/main/java/com/aventstack/extentreports/configuration/ConfigurationStore.java
51e2acbac2729a3ddaa3cab250a69b4c46d5a9f0
[ "Apache-2.0" ]
permissive
jgeraigery/extentreports-java
https://github.com/jgeraigery/extentreports-java
eecfcca77ece956adf0e09c8feb4361d833fd6f0
6a71588f55c2eec1cf4a79d77dbf02162195fa13
refs/heads/master
2021-04-08T22:15:15.113000
2021-03-03T16:35:39
2021-03-03T16:35:39
248,814,447
0
0
Apache-2.0
true
2021-03-03T16:35:39
2020-03-20T17:28:43
2020-03-20T17:29:09
2021-03-03T16:35:39
1,798
0
0
4
Java
false
false
package com.aventstack.extentreports.configuration; import java.util.HashMap; import java.util.Map; public class ConfigurationStore { private Map<String, Object> store = new HashMap<String, Object>(); public Map<String, Object> getStore() { return store; } public void storeConfig(String key, Object value) { store.put(key, value); } public boolean containsConfig(String k) { return store.containsKey(k); } public void removeConfig(String k) { store.remove(k); } public Object getConfig(String k) { return store.containsKey(k) ? store.get(k) : null; } public void extendConfig(Map<String, Object> map) { map.forEach((key, value) -> this.storeConfig(key, value)); } public void extendConfig(ConfigurationStore config) { Map<String, Object> map = config.store; this.extendConfig(map); } public boolean isEmpty() { return store.isEmpty(); } }
UTF-8
Java
887
java
ConfigurationStore.java
Java
[]
null
[]
package com.aventstack.extentreports.configuration; import java.util.HashMap; import java.util.Map; public class ConfigurationStore { private Map<String, Object> store = new HashMap<String, Object>(); public Map<String, Object> getStore() { return store; } public void storeConfig(String key, Object value) { store.put(key, value); } public boolean containsConfig(String k) { return store.containsKey(k); } public void removeConfig(String k) { store.remove(k); } public Object getConfig(String k) { return store.containsKey(k) ? store.get(k) : null; } public void extendConfig(Map<String, Object> map) { map.forEach((key, value) -> this.storeConfig(key, value)); } public void extendConfig(ConfigurationStore config) { Map<String, Object> map = config.store; this.extendConfig(map); } public boolean isEmpty() { return store.isEmpty(); } }
887
0.714769
0.714769
43
19.627907
21.050352
67
false
false
0
0
0
0
0
0
1.325581
false
false
4
06974057daf6e51debaf617e76217cb338538d8b
9,826,885,225,227
9bd0163f2746479687f362ce2ee9514281948374
/src/main/java/huzhen/after/ODBackAfter.java
aee84bb8667163dedf69f730156a654b04801fe5
[]
no_license
un-knower/ODReverse
https://github.com/un-knower/ODReverse
f11a91beab51dd5605d74403ef53b23a93d79c2d
c0510e1e75d3b77d260e21bdcdfe51db16523a0f
refs/heads/master
2020-03-17T22:48:43.633000
2017-05-29T06:37:02
2017-05-29T06:37:02
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package huzhen.after; import huzhen.code.readForm.MapAllpath; import huzhen.subwayPkg.pojo.BaseSubway; import huzhen.tableTable.TimeTableMaker; import huzhen.tableTable.TimeTableReader; import huzhen.utils.*; import org.apache.pig.EvalFunc; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import java.io.*; import java.text.ParseException; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Scanner; import static huzhen.code.readForm.MapTimeWalk.getMapWalk; import static huzhen.utils.RouteChangeStationUtil.Route2ChangeStation; /** * Created by hu on 2016/11/3. * * 将OD反推 写成PIG UDF JAVA 跑的太慢 */ public class ODBackAfter extends EvalFunc<String> { private static int IN_STATION;//进站加等待时间记150s private static int OUT_STATION;//出站时间记90s // public int CHANGE_STATION_SMALL = 0;//换乘时间 public static int count =0; private boolean flag =false; public static Map<String,String> linestation2staion= null; public static Map<String,String> linesO2D= null; public static Map<String, List<BaseSubway>> lbs =null; public static Map<String,String> mapWalk =null; public String exec(Tuple input)throws IOException { if (input ==null || input.size() ==0) return null; try{ //读取一次配置文件 try{ if (!flag){ flag =true; //读取配置文件,给IN_STATION和OUT_STATION赋值 try { PropertiesUtil propertiesUtil = new PropertiesUtil("runner.properties"); IN_STATION = Integer.parseInt(propertiesUtil.readValue("IN_STATION")); OUT_STATION = Integer.parseInt(propertiesUtil.readValue("OUT_STATION")); } catch (IOException e) { System.out.println("配置文件读取错误!"); e.printStackTrace(); } linestation2staion= TimeTableReader.getLinestation2staion(); linesO2D = TimeTableReader.getLinesO2D(); lbs = new TimeTableMaker().makeSubwayList(); mapWalk =getMapWalk(); } }catch (Exception e){ System.out.println("error!读取配置文件错误!"); e.printStackTrace(); } //接收参数 String string0 =(String)input.get(0); String string1 =(String)input.get(1); String string2 =(String)input.get(2); String string3 =(String)input.get(3); String string4 =(String)input.get(4); String string5 =(String)input.get(5); String string6 =(String)input.get(6); String string7 =(String)input.get(7); String string8 =(String)input.get(8); String string9 =(String)input.get(9); String string10 =(String)input.get(10); String line =string0+","+string1+","+string2+","+string3+","+string4+","+string5+","+string6+","+string7+","+string8+","+string9+","+string10; /** * -----开始------ */ StringBuilder sb =new StringBuilder(); String[] strings = line.split(","); long time1 = TimeConvert.HourToSeconds(strings[1].substring(11, 19));//16:53:59 long time2 = TimeConvert.HourToSeconds(strings[6].substring(11, 19)); double realTime = (time2 - time1) / 60.0; String cardNo = strings[0]; //读第二张表,将OD站点转化为编号,再转化为序号 String string_O2 =null; String string_D2 =null; if (FunctionsUtils.isContainsChinese(strings[3])){ /** * 站点为中文名称 */ sb.append("-Name2Ser-"); string_O2 = NoNameExUtil.Name2Ser(strings[3]);//"黄贝岭"-->string_O:1263037000-->56 string_D2 = NoNameExUtil.Name2Ser(strings[8]);//"新秀"-->string_D:1260039000-->57 }else { /** * 站点为编号 */ sb.append("-No2Ser-"); string_O2 = NoNameExUtil.NO2Ser((strings[3]));//"黄贝岭"-->string_O:1263037000-->56 string_D2 = NoNameExUtil.NO2Ser((strings[8]));//"新秀"-->string_D:1260039000-->57 } /** * 读第三张表allpathNew.txt,输出结果 */ String fun =CheckAllPathNew(cardNo, string_O2, string_D2, realTime, strings); return fun; } catch (Exception e) { throw new IOException(e.getMessage()); } } public static void main(String[] args) { //为了计算运行程序所用时间 Long start =System.currentTimeMillis(); int countkkkkk =0; String path1 = "conf\\part\\part-m-00"; Scanner scan1 = null; BufferedWriter bw = null; try { scan1 = new Scanner(new FileInputStream(new File(path1)), CodingDetector.checkTxtCode(path1)); bw = new BufferedWriter(new FileWriter("conf\\part\\result_tos")); } catch (IOException e) { e.printStackTrace(); } ODBackAfter test =new ODBackAfter(); while (scan1.hasNext()){ TupleFactory tupleFactory = TupleFactory.getInstance(); Tuple input = tupleFactory.newTuple(); String line =scan1.nextLine(); String[] strings =line.split(","); input.append(strings[0]); input.append(strings[1]); input.append(strings[2]); input.append(strings[3]); input.append(strings[4]); input.append(strings[5]); input.append(strings[6]); input.append(strings[7]); input.append(strings[8]); input.append(strings[9]); input.append(strings[10]); try { String result =test.exec(input).toString(); System.out.println(result); bw.write(result); bw.newLine(); bw.flush(); } catch (IOException e) { e.printStackTrace(); } } System.out.println("time:"+(System.currentTimeMillis() -start)/1000/60.0+"min"); } //将OD站点与表allpathNew.txt 匹配,找出相应OD路径,并输出 public static String CheckAllPathNew(String cardNo, String string_O2, String string_D2, double realTime, String[] strings) throws ParseException { boolean flag_oneChange = false;//是否有一次换乘满足条件 boolean flag_twoChange = false;// boolean flag_threeChange = false;// boolean flag_fourChange =false;//是否有四次换乘满足条件 int isOneChanged = 0; int isTwoChange = 0; int isThreeChange = 0; int isFourChange = 0; String key = string_O2 + "-" + string_D2;//key:56,57 List<String> value = MapAllpath.getAllpath().get(key);//value:[56 57 #0 T 0.00000000 1.76666667 ] int valueNo; for (valueNo = 0; valueNo < value.size(); valueNo++) { /** * 若只有一条路径,则直接输出 */ if (value.size() == 1) { String fun = funtionPrintData(cardNo,value.get(0)); //----------直接输出 return fun; } /** * 若有多条路径,则分别计算 */ String line3 =value.get(valueNo); String[] strings_allpath = line3.split("#");//56 57 #0 T 0.00000000 1.76666667 String[] strings_allpath1 = strings_allpath[0].split(" "); String[] strings_allpath2 = strings_allpath[1].split(" "); double time = Double.parseDouble(strings_allpath2[strings_allpath2.length - 1]); /** * 若OD在同一条线路上 * 若有直达的路径 * 满足直达条件:输出直达路径 * 不满足直达条件:选择时间最接近的路径输出 * 没有直达路径 * 选择时间最接近的路径输出 */ if (linesO2D.get(NoNameExUtil.Ser2NO(string_O2) + NoNameExUtil.Ser2NO(string_D2)) !=null) { if (strings_allpath2[0].equals("0")) { String station2station = NoNameExUtil.Ser2NO(strings_allpath1[0]) + NoNameExUtil.Ser2NO(strings_allpath1[1]); String lineNo = linestation2staion.get(station2station); Boolean flagLine = ODPathBack_isOneNo(strings, lineNo); if (flagLine) { String fun = funtionPrintData(cardNo, line3); //----------直接输出 return fun; } else { String closeLine = CloseTimeLine(value, time, realTime); String fun = funtionPrintData(cardNo, closeLine); return fun; } } else { String closeLine = CloseTimeLine(value, time, realTime); String fun = funtionPrintData(cardNo, closeLine); return fun; } } else { /** * 若OD不在同一条线路上 * O点在哪一条线上,D点在哪一条线上 --------处理一次换乘代码 */ /** * 若经一次换乘的路线不在相邻,则会出错,因此,先对allpathNew排序,将一次换乘的排在最前 * 已经按照顺序排好 表allpathNew2.txt * * 若两条路径均满足换乘条件,则选择一条时间更接近的输出 */ if (strings_allpath2[0].equals("1")) { /** * 有一次换乘路径的 --遍历所有 * 有满足条件的一次换乘路径:输出时间最接近的那条路径 * 没有满足条件的换乘路径: * 是最后一条路径:选择时间最接近的那条路径输出 * 不是最后一条路径:继续多次换乘判断 */ boolean flag_isOneChange =false; if (isOneChanged == 1) { continue; } double closeTime = time; String closeLine = line3; int m; for (m = 0; m < value.size(); m++) {//56 57 #0 T 0.00000000 1.76666667 if (value.get(m).split("#")[1].split(" ")[0].equals("1")) { String[] stations = value.get(m).split("#")[0].split(" "); String changeStations = Route2ChangeStation(value.get(m).split("#")[0].trim().replaceAll(" ", "-"), linestation2staion); flag_oneChange = ODPathBack_isOneChange(stations, changeStations, strings); if (flag_oneChange) { String[] times = value.get(m).split("#")[1].split(" "); if (Double.parseDouble(times[times.length - 1]) <= realTime && Double.parseDouble(times[times.length - 1]) >= closeTime) { flag_oneChange = false; flag_isOneChange =true; closeTime = Double.parseDouble(times[times.length - 1]); closeLine = value.get(m); continue; } } } } if (flag_isOneChange) { String fun = funtionPrintData(cardNo, closeLine); return fun; } else { if (valueNo == value.size() - 1 || m ==value.size()) { closeLine = CloseTimeLine(value, time, realTime); String fun = funtionPrintData(cardNo, closeLine); return fun; } else { isOneChanged = 1; continue; } } } else if (strings_allpath2[0].equals("2")) { /** * 两次换乘判断 * 有满足两次换乘的路径:选取时间最接近的那条路径输出 * 不满足两次换乘路径: * 是最后一条路径:选择时间最接近的一条路径输出 * 不是最后一条路径:继续多次判断 */ boolean flag_isTwoChange =false; if (isTwoChange == 1) { continue; } double closeTime = time; String closeLine = line3; int m; for (m = 0; m < value.size(); m++) {//56 57 #0 T 0.00000000 1.76666667 if (value.get(m).split("#")[1].split(" ")[0].equals("2")) { String[] stations = value.get(m).split("#")[0].split(" "); String changeStations = Route2ChangeStation(value.get(m).split("#")[0].replaceAll(" ", "-"), linestation2staion); flag_twoChange = ODPathBack_isTwoChange(stations, changeStations, strings); if (flag_twoChange) { String[] times = value.get(m).split("#")[1].split(" "); if (Double.parseDouble(times[times.length - 1]) <= realTime && Double.parseDouble(times[times.length - 1]) >= closeTime) { flag_twoChange = false; flag_isTwoChange =true; closeTime = Double.parseDouble(times[times.length - 1]); closeLine = value.get(m); continue; } } } } if (flag_isTwoChange) { String fun = funtionPrintData(cardNo, closeLine); return fun; } else { if (valueNo == value.size() - 1 || m ==value.size()) { closeLine = CloseTimeLine(value, time, realTime); String fun = funtionPrintData(cardNo, closeLine); return fun; } else { isTwoChange = 1; continue; } } } else if (strings_allpath2[0].equals("3")) { /** * 三次换乘判断 --遍历所有路径 * 有满足三次换乘的路径:选取时间最接近的那条路径输出 * 不满足三次换乘路径: * 是最后一条路径:选择时间最接近的一条路径输出 * 不是最后一条路径:继续多次判断 */ boolean flag_isThreeChange =false; if (isThreeChange == 1) { continue; } double closeTime = time; String closeLine = line3; int m; for (m = 0; m < value.size(); m++) {//56 57 #0 T 0.00000000 1.76666667 if (value.get(m).split("#")[1].split(" ")[0].equals("3")) { String[] stations = value.get(m).split("#")[0].split(" "); String changeStations = Route2ChangeStation(value.get(m).split("#")[0].replaceAll(" ", "-"), linestation2staion); flag_threeChange = ODPathBack_isThreeChange(stations, changeStations, strings); if (flag_threeChange) { String[] times = value.get(m).split("#")[1].split(" "); if (Double.parseDouble(times[times.length - 1]) <= realTime && Double.parseDouble(times[times.length - 1]) >= closeTime) { flag_threeChange = false; flag_isThreeChange =true; closeTime = Double.parseDouble(times[times.length - 1]); closeLine = value.get(m); continue; } } } } if (flag_isThreeChange) { String fun = funtionPrintData(cardNo, closeLine); return fun; } else { if (valueNo == value.size() - 1 || m ==value.size()) { closeLine = CloseTimeLine(value, time, realTime); String fun = funtionPrintData(cardNo, closeLine); return fun; } else { isThreeChange = 1; continue; } } } else if (strings_allpath2[0].equals("4")) { /** * 四次换乘判断 --遍历所有路径 * 有满足四次换乘的路径:选取时间最接近的那条路径输出 * 不满足四次换乘路径: * 是最后一条路径:选择时间最接近的一条路径输出 * 不是最后一条路径:继续多次判断 */ boolean flag_isFourChange =false; if (isFourChange == 1) { continue; } double closeTime = time; String closeLine = line3; int m; for (m = 0; m < value.size(); m++) {//56 57 #0 T 0.00000000 1.76666667 if (value.get(m).split("#")[1].split(" ")[0].equals("4")) { String[] stations = value.get(m).split("#")[0].split(" "); String changeStations = Route2ChangeStation(value.get(m).split("#")[0].replaceAll(" ", "-"), linestation2staion); flag_fourChange = ODPathBack_isFourChange(stations, changeStations, strings); if (flag_fourChange) { String[] times = value.get(m).split("#")[1].split(" "); if (Double.parseDouble(times[times.length - 1]) <= realTime && Double.parseDouble(times[times.length - 1]) >= closeTime) { flag_fourChange = false; flag_isFourChange =true; closeTime = Double.parseDouble(times[times.length - 1]); closeLine = value.get(m); continue; } } } } if (flag_isFourChange == true) { String fun = funtionPrintData(cardNo, closeLine); return fun; } else { if (valueNo == value.size() - 1 || m ==value.size()) { closeLine = CloseTimeLine(value, time, realTime); String fun = funtionPrintData(cardNo, closeLine); return fun; } else { isFourChange = 1; continue; } } } else { /** * 如果四次换乘依然不成功,则直接输出时间最接近的一条路径 */ double closeTime = time; String closeLine = line3; closeLine = CloseTimeLine(value, time, realTime); String fun = funtionPrintData(cardNo, closeLine); return fun; } } } String closeLine = value.get(0).toString(); String fun = funtionPrintData(cardNo, closeLine); return fun; } /** * 输出,并跳出循环 * * @param cardNo 卡号 * @throws java.io.IOException */ public static String funtionPrintData(String cardNo,String strings){ count++; String stringCon = ConvertOD(strings); // stringCon =cardNo + "," + stringCon; // System.out.println("count:"+count); // System.out.println("hello"); // System.out.println(cardNo + "," + stringCon); return stringCon; } /** * 判断四次换乘是否成立 #4 */ public static boolean ODPathBack_isFourChange(String[] stations,String changeStations,String[] strings) throws ParseException{ boolean flag = false; String date1 = strings[1].substring(11, 19);//O站出发时间2015-09-16T12:09:47.000Z-->08:21:15 String date2 = strings[6].substring(11, 19);//D站到达时间2015-09-16T12:28:05.000Z-->09:09:30 date1 = TimeConvert.Second2Hour(TimeConvert.HourToSeconds(date1) + 8 * 60 * 60 + IN_STATION);//刷卡进站+等待时间150秒 date2 = TimeConvert.Second2Hour(TimeConvert.HourToSeconds(date2) + 8 * 60 * 60 - OUT_STATION);//出站刷卡时间90秒 String[] odChangeStations =changeStations.split("-"); String string_O2 =odChangeStations[0]; String string_D2 =odChangeStations[1]; String changeStation1 =odChangeStations[2]; String changeStation2 =odChangeStations[3]; String changeStation3 =odChangeStations[4]; String changeStation4 =odChangeStations[5]; String stationNext1 =null; String stationNext2 =null; String stationNext3 =null; for (int i =0;i<stations.length-1;i++) { if (stations[i].equals(NoNameExUtil.NO2Ser(changeStation1))) { stationNext1 = NoNameExUtil.Ser2NO(stations[i + 1]); } if (stations[i].equals(NoNameExUtil.NO2Ser(changeStation2))) { stationNext2 = NoNameExUtil.Ser2NO(stations[i + 1]); } if (stations[i].equals(NoNameExUtil.NO2Ser(changeStation3))) { stationNext3 = NoNameExUtil.Ser2NO(stations[i + 1]); } } String station2stationFirst = NoNameExUtil.Ser2NO(stations[0])+ NoNameExUtil.Ser2NO(stations[1]); String lineNo_First = linestation2staion.get(station2stationFirst); String station2stationLast = NoNameExUtil.Ser2NO(stations[stations.length - 2])+ NoNameExUtil.Ser2NO(stations[stations.length - 1]); String lineNo_Last = linestation2staion.get(station2stationLast); String station2stationSecond =changeStation1+stationNext1; String lineNo_Second =linestation2staion.get(station2stationSecond); String station2stationThird =changeStation2+stationNext2; String lineNo_Third =linestation2staion.get(station2stationThird); String station2stationForth =changeStation3+stationNext3; String lineNo_Forth =linestation2staion.get(station2stationForth); Date timeo_change_first = null;//从第一个换乘站出发的时间 Date timed_change_first = null;//到达第一个换成站的时间 Date timeo_change_second = null; Date timed_change_second = null; Date timeo_change_third = null; Date timed_change_third = null; Date timeo_change_last =null; Date timed_change_last =null; /** * 第一次换乘 到达第一个换乘点的时间 timed_change_first */ timed_change_first =timed_change(lineNo_First,string_O2, TimeConvert.String2Date(date1),changeStation1); /** * 第一次换乘 换乘点changeStation1的换乘时间 */ int CHANGE_STATION_SMALL1 =change_station_walkTime(changeStation1,lineNo_First,lineNo_Second); timeo_change_first = TimeConvert.String2Date(TimeConvert.Second2Hour(TimeConvert.HourToSeconds(TimeConvert.Date2String(timed_change_first)) + 8 * 60 * 60 + CHANGE_STATION_SMALL1)); /** * 找到第二个换乘站到达的时间 timed_change_second */ timed_change_second =timed_change(lineNo_Second,changeStation1,timeo_change_first,changeStation2); /** * 第二个换点点changeStation2 的换乘时间 CHANGE_STATION_SMALL2 */ int CHANGE_STATION_SMALL2 =change_station_walkTime(changeStation2,lineNo_Second,lineNo_Third); timeo_change_second = TimeConvert.String2Date(TimeConvert.Second2Hour(TimeConvert.HourToSeconds(TimeConvert.Date2String(timed_change_second)) + 8 * 60 * 60 + CHANGE_STATION_SMALL2)); /*** * 由第二个换乘点出发时间,可计算计算第三个换乘点 */ timed_change_third =timed_change(lineNo_Third,changeStation2,timeo_change_second,changeStation3); /** * 计算最后一个换乘changeStation3 的换乘时间 CHANGE_STATION_SMALL_LAST */ int CHANGE_STATION_SMALL3 =change_station_walkTime(changeStation3,lineNo_Third,lineNo_Forth); timeo_change_third = TimeConvert.String2Date(TimeConvert.Second2Hour(TimeConvert.HourToSeconds(TimeConvert.Date2String(timed_change_third)) + 8 * 60 * 60 + CHANGE_STATION_SMALL3)); /*** * 由第3个换乘点出发时间,可计算计算第4个换乘点,记最后一个换乘点的 到达时间 */ timed_change_last =timed_change(lineNo_Forth,changeStation3,timeo_change_third,changeStation4); /** * 计算最后一个换乘changeStation3 的换乘时间 CHANGE_STATION_SMALL_LAST */ int CHANGE_STATION_SMALL_LAST =change_station_walkTime(changeStation4,lineNo_Forth,lineNo_Last); /** * 最后一次换乘 从最后一个换乘点出发的时间 timeo_change_last */ timeo_change_last =timeo_change(lineNo_Last,string_D2, TimeConvert.String2Date(date2), changeStation4); /** * */ if (TimeConvert.HourToSeconds(TimeConvert.Date2String(timeo_change_last)) - TimeConvert.HourToSeconds(TimeConvert.Date2String(timed_change_last)) >= CHANGE_STATION_SMALL_LAST) { flag = true; } return flag; } /** * 判断三次换乘是否成立 #3 */ public static boolean ODPathBack_isThreeChange(String[] stations,String changeStations,String[] strings) throws ParseException{ boolean flag = false; String date1 = strings[1].substring(11, 19);//O站出发时间2015-09-16T12:09:47.000Z-->08:21:15 String date2 = strings[6].substring(11, 19);//D站到达时间2015-09-16T12:28:05.000Z-->09:09:30 date1 = TimeConvert.Second2Hour(TimeConvert.HourToSeconds(date1) + 8 * 60 * 60 + IN_STATION);//刷卡进站+等待时间150秒 date2 = TimeConvert.Second2Hour(TimeConvert.HourToSeconds(date2) + 8 * 60 * 60 - OUT_STATION);//出站刷卡时间90秒 String[] odChangeStations =changeStations.split("-"); String string_O2 =odChangeStations[0]; String string_D2 =odChangeStations[1]; String changeStation1 =odChangeStations[2]; String changeStation2 =odChangeStations[3]; String changeStation3 =odChangeStations[4]; String stationNext1 =null; String stationNext2 =null; for (int i =0;i<stations.length-1;i++){ if (stations[i].equals(NoNameExUtil.NO2Ser(changeStation1))){ stationNext1 = NoNameExUtil.Ser2NO(stations[i + 1]); } if (stations[i].equals(NoNameExUtil.NO2Ser(changeStation2))) { stationNext2 = NoNameExUtil.Ser2NO(stations[i + 1]); } } String station2stationFirst = NoNameExUtil.Ser2NO(stations[0])+ NoNameExUtil.Ser2NO(stations[1]); String lineNo_First = linestation2staion.get(station2stationFirst); String station2stationLast = NoNameExUtil.Ser2NO(stations[stations.length - 2])+ NoNameExUtil.Ser2NO(stations[stations.length - 1]); String lineNo_Last = linestation2staion.get(station2stationLast); String station2stationSecond =changeStation1+stationNext1; String lineNo_Second =linestation2staion.get(station2stationSecond); String station2stationThird =changeStation2+stationNext2; String lineNo_Third =linestation2staion.get(station2stationThird); Date timeo_change_first = null;//从第一个换乘站出发的时间 Date timed_change_first = null;//到达第一个换乘站的时间 Date timeo_change_second = null; Date timed_change_second = null; Date timeo_change_last =null; Date timed_change_last =null; /** * 第一次换乘 到达第一个换乘点的时间 timed_change_first */ timed_change_first =timed_change(lineNo_First,string_O2, TimeConvert.String2Date(date1),changeStation1); /** * 第一次换乘 换乘点changeStation1的换乘时间 */ int CHANGE_STATION_SMALL1 =change_station_walkTime(changeStation1,lineNo_First,lineNo_Second); /** * 第一次换乘 第一个换乘点出发时间 timeo_change_first * */ timeo_change_first = TimeConvert.String2Date(TimeConvert.Second2Hour(TimeConvert.HourToSeconds(TimeConvert.Date2String(timed_change_first)) + 8 * 60 * 60 + CHANGE_STATION_SMALL1)); /** * 第一个换乘站出发的时间 timeo_change_first 找到第二个换乘站到达的时间 timed_change_second */ timed_change_second =timed_change(lineNo_Second,changeStation1,timeo_change_first,changeStation2); /** * 第二个换点点changeStation2 的换乘时间 CHANGE_STATION_SMALL2 */ int CHANGE_STATION_SMALL2 =change_station_walkTime(changeStation2,lineNo_Second,lineNo_Third); timeo_change_second = TimeConvert.String2Date(TimeConvert.Second2Hour(TimeConvert.HourToSeconds(TimeConvert.Date2String(timed_change_second)) + 8 * 60 * 60 + CHANGE_STATION_SMALL2)); /*** * 由第二个换乘点出发时间,可计算计算第三个换乘点,记最后一个换乘点的 到达时间 */ timed_change_last =timed_change(lineNo_Third,changeStation2,timeo_change_second,changeStation3); /** * 计算最后一个换乘changeStation3 的换乘时间 CHANGE_STATION_SMALL_LAST */ int CHANGE_STATION_SMALL_LAST =change_station_walkTime(changeStation3,lineNo_Third,lineNo_Last); /** * 最后一次换乘 从最后一个换乘点出发的时间 timeo_change_last */ timeo_change_last =timeo_change(lineNo_Last,string_D2, TimeConvert.String2Date(date2), changeStation3); /** * 若两个时间差满足条件(相当于两次换乘),则返回flag =true; */ if (TimeConvert.HourToSeconds(TimeConvert.Date2String(timeo_change_last)) - TimeConvert.HourToSeconds(TimeConvert.Date2String(timed_change_last)) >= CHANGE_STATION_SMALL_LAST) { flag = true; } return flag; } /** * 判断两次换乘是否成立 #2 */ public static boolean ODPathBack_isTwoChange(String[] stations,String changeStations, String[] strings) throws ParseException{ boolean flag = false; String date1 = strings[1].substring(11, 19);//O站出发时间2015-09-16T12:09:47.000Z-->08:21:15 String date2 = strings[6].substring(11, 19);//D站到达时间2015-09-16T12:28:05.000Z-->09:09:30 date1 = TimeConvert.Second2Hour(TimeConvert.HourToSeconds(date1) + 8 * 60 * 60 + IN_STATION);//刷卡进站+等待时间150秒 date2 = TimeConvert.Second2Hour(TimeConvert.HourToSeconds(date2) + 8 * 60 * 60 - OUT_STATION);//出站刷卡时间90秒 String[] odChangeStations =changeStations.split("-"); String string_O2 =odChangeStations[0]; String string_D2 =odChangeStations[1]; String changeStation1 =odChangeStations[2]; String changeStation2 =odChangeStations[3]; String stationNext =null; for (int i =0;i<stations.length-1;i++){ if (stations[i].equals(NoNameExUtil.NO2Ser(changeStation1))){ stationNext = NoNameExUtil.Ser2NO(stations[i + 1]); break; } } String station2stationFirst = NoNameExUtil.Ser2NO(stations[0])+ NoNameExUtil.Ser2NO(stations[1]); String lineNo_First = linestation2staion.get(station2stationFirst); String station2stationLast = NoNameExUtil.Ser2NO(stations[stations.length - 2])+ NoNameExUtil.Ser2NO(stations[stations.length - 1]); String lineNo_Last = linestation2staion.get(station2stationLast); String station2stationSecond =changeStation1+stationNext; String lineNo_Second =linestation2staion.get(station2stationSecond); Date timeo_change_first = null; Date timed_change_first = null; Date timeo_change_last =null; Date timed_change_last =null; /** * 第一次换乘 到达第一个换乘点的时间 timed_change_first */ timed_change_first =timed_change(lineNo_First,string_O2, TimeConvert.String2Date(date1),changeStation1); /** * 第一次换乘 换乘点changeStation1的换乘时间 */ int CHANGE_STATION_SMALL1 =change_station_walkTime(changeStation1,lineNo_First,lineNo_Second); /** * 第一次换乘 第一个换乘点出发时间 timeo_change_first * */ timeo_change_first = TimeConvert.String2Date(TimeConvert.Second2Hour(TimeConvert.HourToSeconds(TimeConvert.Date2String(timed_change_first)) + 8 * 60 * 60 + CHANGE_STATION_SMALL1)); /** * 第一个换乘站出发的时间 timeo_change_first 找到第二个换乘站到达的时间 timed_change_second */ timed_change_last =timed_change(lineNo_Second,changeStation1,timeo_change_first,changeStation2); /** * 计算最后一个换乘changeStation3 的换乘时间 CHANGE_STATION_SMALL_LAST */ int CHANGE_STATION_SMALL_LAST =change_station_walkTime(changeStation2,lineNo_Second,lineNo_Last); /** * 最后一次换乘 从最后一个换乘点出发的时间 timeo_change_last */ timeo_change_last =timeo_change(lineNo_Last, string_D2, TimeConvert.String2Date(date2), changeStation2); if (TimeConvert.HourToSeconds(TimeConvert.Date2String(timeo_change_last)) - TimeConvert.HourToSeconds(TimeConvert.Date2String(timed_change_last)) >= CHANGE_STATION_SMALL_LAST) { flag = true; } return flag; } /** * 判断一次换乘是否成立 #1 */ //判断两个不同线的两个站点是否为直接换乘 public static boolean ODPathBack_isOneChange(String[] stations,String changeStations, String[] strings) throws ParseException{ boolean flag = false; String date1 = strings[1].substring(11, 19);//O站出发时间2015-09-16T12:09:47.000Z-->08:21:15 String date2 = strings[6].substring(11, 19);//D站到达时间2015-09-16T12:28:05.000Z-->09:09:30 date1 = TimeConvert.Second2Hour(TimeConvert.HourToSeconds(date1) + 8 * 60 * 60 + IN_STATION);//刷卡进站+等待时间150秒 date2 = TimeConvert.Second2Hour(TimeConvert.HourToSeconds(date2) + 8 * 60 * 60 - OUT_STATION);//出站刷卡时间90秒 String[] odChangeStations =changeStations.split("-"); String string_O2 =odChangeStations[0]; String string_D2 =odChangeStations[1]; String changeStation =odChangeStations[2]; String station2stationFirst = NoNameExUtil.Ser2NO(stations[0])+ NoNameExUtil.Ser2NO(stations[1]); String lineNo_First = linestation2staion.get(station2stationFirst); String station2stationLast = NoNameExUtil.Ser2NO(stations[stations.length - 2])+ NoNameExUtil.Ser2NO(stations[stations.length - 1]); String lineNo_Last = linestation2staion.get(station2stationLast); Date timeo_change = null; Date timed_change = null; /** * */ timed_change =timed_change(lineNo_First,string_O2, TimeConvert.String2Date(date1),changeStation); timeo_change =timeo_change(lineNo_Last,string_D2, TimeConvert.String2Date(date2), changeStation); int CHANGE_STATION_SMALL =change_station_walkTime(changeStation,lineNo_First,lineNo_Last); if (TimeConvert.HourToSeconds(TimeConvert.Date2String(timeo_change)) - TimeConvert.HourToSeconds(TimeConvert.Date2String(timed_change)) >= CHANGE_STATION_SMALL) { flag = true; } return flag; } /** * 判断是否满足同一条线不换乘的情况 #0 */ public static boolean ODPathBack_isOneNo(String[] strings, String lineNo) throws ParseException { boolean flag = false;//326816865,2015-09-16T08:21:15.000Z,地铁二号线,新秀,114.1444922,22.55086697,2015-09-16T09:09:30.000Z,地铁二号线,后海,113.9352052,22.52049297 String date1 = strings[1].substring(11, 19);//O站出发时间2015-09-16T12:09:47.000Z-->08:21:15 String date2 = strings[6].substring(11, 19);//D站到达时间2015-09-16T12:28:05.000Z-->09:09:30 date1 = TimeConvert.Second2Hour(TimeConvert.HourToSeconds(date1) + 8 * 60 * 60 + IN_STATION);//刷卡进站+等待时间150秒 date2 = TimeConvert.Second2Hour(TimeConvert.HourToSeconds(date2) + 8 * 60 * 60 - OUT_STATION);//出站刷卡时间90秒 String string_O = strings[3];//O站点 String string_D = strings[8];//D站点 int lineNo_O = 0; int lineNo_D = 0; for (int i = 0; i < lbs.get(lineNo).size()-1; i++) { for (int j = 0; j < lbs.get(lineNo).get(i).getStations().size(); j++) { if (lbs.get(lineNo).get(i).getStations().get(j).getStation().equals((string_O)) && lbs.get(lineNo).get(i).getStations().get(j).getDate().before(TimeConvert.String2Date(date1)) && lbs.get(lineNo).get(i + 1).getStations().get(j).getDate().after(TimeConvert.String2Date(date1))) { lineNo_O = i + 1;//O第18列车,第0站 } if (lbs.get(lineNo).get(i).getStations().get(j).getStation().equals((string_D)) && lbs.get(lineNo).get(i).getStations().get(j).getDate().before(TimeConvert.String2Date(date2)) && lbs.get(lineNo).get(i + 1).getStations().get(j).getDate().after(TimeConvert.String2Date(date2))) { lineNo_D = i ;//D第18列车,第20站 } } } if (lineNo_O == lineNo_D) { flag = true; } return flag; } /** * 不同换乘站点 每次换乘用的时间 * @param changeStation 换乘站 * @param lineNo_0 换乘前的线路2600 * @param lineNo_D 换乘后的线路2611 * @return 此次换乘用的时间 */ public static int change_station_walkTime(String changeStation,String lineNo_0,String lineNo_D){ int CHANGE_STATION_SMALL =0; String key =changeStation+","+lineNo_0.substring(0,3)+","+lineNo_D.substring(0,3); String value =mapWalk.get(key); if (lineNo_0.substring(3).equals("0") && lineNo_D.substring(3).equals("0")){ CHANGE_STATION_SMALL =(int)((Double.parseDouble(value.split(",")[0]))*60); }else if (lineNo_0.substring(3).equals("0") && lineNo_D.substring(3).equals("1")){ CHANGE_STATION_SMALL =(int)((Double.parseDouble(value.split(",")[1]))*60); }else if (lineNo_0.substring(3).equals("1") && lineNo_D.substring(3).equals("0")){ CHANGE_STATION_SMALL =(int)((Double.parseDouble(value.split(",")[2]))*60); }else if (lineNo_0.substring(3).equals("1") && lineNo_D.substring(3).equals("1")){ CHANGE_STATION_SMALL =(int)((Double.parseDouble(value.split(",")[3]))*60); } return CHANGE_STATION_SMALL; } /** * 从此站点o出发到达下一站点的时间 * string_O2 changeStation_first 都是编号 */ public static Date timed_change(String lineNo_first,String string_O2,Date date1,String changeStation_first) throws ParseException { int lineNo_first_no =0; Date timed_change_first =null; boolean flag = false; int num =0; for (int i = 0; i < lbs.get(lineNo_first).size(); i++) { for (int j = 0; j < lbs.get(lineNo_first).get(i).getStations().size(); j++) { if (i !=lbs.get(lineNo_first).size() -1 &&lbs.get(lineNo_first).get(i).getStations().get(j).getStation().equals(string_O2) && lbs.get(lineNo_first).get(i).getStations().get(j).getDate().before(date1) && lbs.get(lineNo_first).get(i + 1).getStations().get(j).getDate().after(date1)) { lineNo_first_no = i + 1; flag =true; num =1; }else if(i ==lbs.get(lineNo_first).size() -1 && num ==0 ) { num =1; flag =true; lineNo_first_no =i; } if (flag ==true &&lbs.get(lineNo_first).get(lineNo_first_no).getStations().get(j).getStation().equals(changeStation_first)) { timed_change_first = lbs.get(lineNo_first).get(lineNo_first_no).getStations().get(j).getDate(); flag =false; break; } } } return timed_change_first; } /** * 由D站点推出前一个换乘站点的出发时间 * string_D2 changeStation_first 都是编号 */ public static Date timeo_change(String lineNo_first,String string_O2,Date date1,String changeStation_first) throws ParseException { int lineNo_first_no =0; Date timed_change_first =null; boolean flag = false; int num =0; for (int i = 0; i < lbs.get(lineNo_first).size(); i++) { for (int j = 0; j < lbs.get(lineNo_first).get(i).getStations().size(); j++) { if (i != lbs.get(lineNo_first).size() - 1 && lbs.get(lineNo_first).get(i).getStations().get(j).getStation().equals(string_O2) && lbs.get(lineNo_first).get(i).getStations().get(j).getDate().before(date1) && lbs.get(lineNo_first).get(i + 1).getStations().get(j).getDate().after(date1)) { lineNo_first_no = i; flag = true; num = 1; break; } else if (i == lbs.get(lineNo_first).size() - 1 && num == 0) { num = 1; flag = true; lineNo_first_no = i - 1; break; } } if (flag ==true){ break; } } if (flag ==true){ for (int k = 0; k < lbs.get(lineNo_first).get(lineNo_first_no).getStations().size(); k++){ if (lbs.get(lineNo_first).get(lineNo_first_no).getStations().get(k).getStation().equals(changeStation_first)) { timed_change_first = lbs.get(lineNo_first).get(lineNo_first_no).getStations().get(k).getDate(); flag =false; break; } } } return timed_change_first; } /** * 转化为最后的结果,每个站点以字符串表示 */ public static String ConvertOD(String string){ // System.out.println("string:"+string); String[] strings = string.split("#")[0].split(" "); StringBuilder sb = new StringBuilder(); for (int i = 0; i < strings.length; i++) { sb.append(NoNameExUtil.Ser2NO(strings[i])); sb.append("-"); } return sb.toString().substring(0, sb.toString().length() - 1); } /** * 找出所有OD路径中的时间最接近实际时间的一条路径 * @param value 所有路径的List */ public static String CloseTimeLine(List<String> value,double time,double realTime){ double closeTime =time; String closeLine =value.get(0).toString(); for(int m =0;m<value.size();m++){//56 57 #0 T 0.00000000 1.76666667 String[] times =value.get(m).split("#")[1].split(" "); if (Double.parseDouble(times[times.length-1]) <=realTime && Double.parseDouble(times[times.length-1]) >=closeTime){ //// 大于 改成 小于了 改回大于最接近的时间 closeTime =Double.parseDouble(times[times.length-1]); closeLine =value.get(m); continue; } } return closeLine; } }
UTF-8
Java
46,732
java
ODBackAfter.java
Java
[ { "context": "tationUtil.Route2ChangeStation;\n\n/**\n * Created by hu on 2016/11/3.\n *\n * 将OD反推 写成PIG UDF JAVA 跑的太慢\n", "end": 615, "score": 0.9938154220581055, "start": 613, "tag": "USERNAME", "value": "hu" }, { "context": " String key = string_O2 + \"-\" + string_D2;//key:56,57\n List<String> value = MapAllpath.getAll", "end": 6844, "score": 0.7727689743041992, "start": 6842, "tag": "KEY", "value": "56" }, { "context": "String key = string_O2 + \"-\" + string_D2;//key:56,57\n List<String> value = MapAllpath.getAllpa", "end": 6846, "score": 0.5139185190200806, "start": 6845, "tag": "KEY", "value": "5" } ]
null
[]
package huzhen.after; import huzhen.code.readForm.MapAllpath; import huzhen.subwayPkg.pojo.BaseSubway; import huzhen.tableTable.TimeTableMaker; import huzhen.tableTable.TimeTableReader; import huzhen.utils.*; import org.apache.pig.EvalFunc; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import java.io.*; import java.text.ParseException; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Scanner; import static huzhen.code.readForm.MapTimeWalk.getMapWalk; import static huzhen.utils.RouteChangeStationUtil.Route2ChangeStation; /** * Created by hu on 2016/11/3. * * 将OD反推 写成PIG UDF JAVA 跑的太慢 */ public class ODBackAfter extends EvalFunc<String> { private static int IN_STATION;//进站加等待时间记150s private static int OUT_STATION;//出站时间记90s // public int CHANGE_STATION_SMALL = 0;//换乘时间 public static int count =0; private boolean flag =false; public static Map<String,String> linestation2staion= null; public static Map<String,String> linesO2D= null; public static Map<String, List<BaseSubway>> lbs =null; public static Map<String,String> mapWalk =null; public String exec(Tuple input)throws IOException { if (input ==null || input.size() ==0) return null; try{ //读取一次配置文件 try{ if (!flag){ flag =true; //读取配置文件,给IN_STATION和OUT_STATION赋值 try { PropertiesUtil propertiesUtil = new PropertiesUtil("runner.properties"); IN_STATION = Integer.parseInt(propertiesUtil.readValue("IN_STATION")); OUT_STATION = Integer.parseInt(propertiesUtil.readValue("OUT_STATION")); } catch (IOException e) { System.out.println("配置文件读取错误!"); e.printStackTrace(); } linestation2staion= TimeTableReader.getLinestation2staion(); linesO2D = TimeTableReader.getLinesO2D(); lbs = new TimeTableMaker().makeSubwayList(); mapWalk =getMapWalk(); } }catch (Exception e){ System.out.println("error!读取配置文件错误!"); e.printStackTrace(); } //接收参数 String string0 =(String)input.get(0); String string1 =(String)input.get(1); String string2 =(String)input.get(2); String string3 =(String)input.get(3); String string4 =(String)input.get(4); String string5 =(String)input.get(5); String string6 =(String)input.get(6); String string7 =(String)input.get(7); String string8 =(String)input.get(8); String string9 =(String)input.get(9); String string10 =(String)input.get(10); String line =string0+","+string1+","+string2+","+string3+","+string4+","+string5+","+string6+","+string7+","+string8+","+string9+","+string10; /** * -----开始------ */ StringBuilder sb =new StringBuilder(); String[] strings = line.split(","); long time1 = TimeConvert.HourToSeconds(strings[1].substring(11, 19));//16:53:59 long time2 = TimeConvert.HourToSeconds(strings[6].substring(11, 19)); double realTime = (time2 - time1) / 60.0; String cardNo = strings[0]; //读第二张表,将OD站点转化为编号,再转化为序号 String string_O2 =null; String string_D2 =null; if (FunctionsUtils.isContainsChinese(strings[3])){ /** * 站点为中文名称 */ sb.append("-Name2Ser-"); string_O2 = NoNameExUtil.Name2Ser(strings[3]);//"黄贝岭"-->string_O:1263037000-->56 string_D2 = NoNameExUtil.Name2Ser(strings[8]);//"新秀"-->string_D:1260039000-->57 }else { /** * 站点为编号 */ sb.append("-No2Ser-"); string_O2 = NoNameExUtil.NO2Ser((strings[3]));//"黄贝岭"-->string_O:1263037000-->56 string_D2 = NoNameExUtil.NO2Ser((strings[8]));//"新秀"-->string_D:1260039000-->57 } /** * 读第三张表allpathNew.txt,输出结果 */ String fun =CheckAllPathNew(cardNo, string_O2, string_D2, realTime, strings); return fun; } catch (Exception e) { throw new IOException(e.getMessage()); } } public static void main(String[] args) { //为了计算运行程序所用时间 Long start =System.currentTimeMillis(); int countkkkkk =0; String path1 = "conf\\part\\part-m-00"; Scanner scan1 = null; BufferedWriter bw = null; try { scan1 = new Scanner(new FileInputStream(new File(path1)), CodingDetector.checkTxtCode(path1)); bw = new BufferedWriter(new FileWriter("conf\\part\\result_tos")); } catch (IOException e) { e.printStackTrace(); } ODBackAfter test =new ODBackAfter(); while (scan1.hasNext()){ TupleFactory tupleFactory = TupleFactory.getInstance(); Tuple input = tupleFactory.newTuple(); String line =scan1.nextLine(); String[] strings =line.split(","); input.append(strings[0]); input.append(strings[1]); input.append(strings[2]); input.append(strings[3]); input.append(strings[4]); input.append(strings[5]); input.append(strings[6]); input.append(strings[7]); input.append(strings[8]); input.append(strings[9]); input.append(strings[10]); try { String result =test.exec(input).toString(); System.out.println(result); bw.write(result); bw.newLine(); bw.flush(); } catch (IOException e) { e.printStackTrace(); } } System.out.println("time:"+(System.currentTimeMillis() -start)/1000/60.0+"min"); } //将OD站点与表allpathNew.txt 匹配,找出相应OD路径,并输出 public static String CheckAllPathNew(String cardNo, String string_O2, String string_D2, double realTime, String[] strings) throws ParseException { boolean flag_oneChange = false;//是否有一次换乘满足条件 boolean flag_twoChange = false;// boolean flag_threeChange = false;// boolean flag_fourChange =false;//是否有四次换乘满足条件 int isOneChanged = 0; int isTwoChange = 0; int isThreeChange = 0; int isFourChange = 0; String key = string_O2 + "-" + string_D2;//key:56,57 List<String> value = MapAllpath.getAllpath().get(key);//value:[56 57 #0 T 0.00000000 1.76666667 ] int valueNo; for (valueNo = 0; valueNo < value.size(); valueNo++) { /** * 若只有一条路径,则直接输出 */ if (value.size() == 1) { String fun = funtionPrintData(cardNo,value.get(0)); //----------直接输出 return fun; } /** * 若有多条路径,则分别计算 */ String line3 =value.get(valueNo); String[] strings_allpath = line3.split("#");//56 57 #0 T 0.00000000 1.76666667 String[] strings_allpath1 = strings_allpath[0].split(" "); String[] strings_allpath2 = strings_allpath[1].split(" "); double time = Double.parseDouble(strings_allpath2[strings_allpath2.length - 1]); /** * 若OD在同一条线路上 * 若有直达的路径 * 满足直达条件:输出直达路径 * 不满足直达条件:选择时间最接近的路径输出 * 没有直达路径 * 选择时间最接近的路径输出 */ if (linesO2D.get(NoNameExUtil.Ser2NO(string_O2) + NoNameExUtil.Ser2NO(string_D2)) !=null) { if (strings_allpath2[0].equals("0")) { String station2station = NoNameExUtil.Ser2NO(strings_allpath1[0]) + NoNameExUtil.Ser2NO(strings_allpath1[1]); String lineNo = linestation2staion.get(station2station); Boolean flagLine = ODPathBack_isOneNo(strings, lineNo); if (flagLine) { String fun = funtionPrintData(cardNo, line3); //----------直接输出 return fun; } else { String closeLine = CloseTimeLine(value, time, realTime); String fun = funtionPrintData(cardNo, closeLine); return fun; } } else { String closeLine = CloseTimeLine(value, time, realTime); String fun = funtionPrintData(cardNo, closeLine); return fun; } } else { /** * 若OD不在同一条线路上 * O点在哪一条线上,D点在哪一条线上 --------处理一次换乘代码 */ /** * 若经一次换乘的路线不在相邻,则会出错,因此,先对allpathNew排序,将一次换乘的排在最前 * 已经按照顺序排好 表allpathNew2.txt * * 若两条路径均满足换乘条件,则选择一条时间更接近的输出 */ if (strings_allpath2[0].equals("1")) { /** * 有一次换乘路径的 --遍历所有 * 有满足条件的一次换乘路径:输出时间最接近的那条路径 * 没有满足条件的换乘路径: * 是最后一条路径:选择时间最接近的那条路径输出 * 不是最后一条路径:继续多次换乘判断 */ boolean flag_isOneChange =false; if (isOneChanged == 1) { continue; } double closeTime = time; String closeLine = line3; int m; for (m = 0; m < value.size(); m++) {//56 57 #0 T 0.00000000 1.76666667 if (value.get(m).split("#")[1].split(" ")[0].equals("1")) { String[] stations = value.get(m).split("#")[0].split(" "); String changeStations = Route2ChangeStation(value.get(m).split("#")[0].trim().replaceAll(" ", "-"), linestation2staion); flag_oneChange = ODPathBack_isOneChange(stations, changeStations, strings); if (flag_oneChange) { String[] times = value.get(m).split("#")[1].split(" "); if (Double.parseDouble(times[times.length - 1]) <= realTime && Double.parseDouble(times[times.length - 1]) >= closeTime) { flag_oneChange = false; flag_isOneChange =true; closeTime = Double.parseDouble(times[times.length - 1]); closeLine = value.get(m); continue; } } } } if (flag_isOneChange) { String fun = funtionPrintData(cardNo, closeLine); return fun; } else { if (valueNo == value.size() - 1 || m ==value.size()) { closeLine = CloseTimeLine(value, time, realTime); String fun = funtionPrintData(cardNo, closeLine); return fun; } else { isOneChanged = 1; continue; } } } else if (strings_allpath2[0].equals("2")) { /** * 两次换乘判断 * 有满足两次换乘的路径:选取时间最接近的那条路径输出 * 不满足两次换乘路径: * 是最后一条路径:选择时间最接近的一条路径输出 * 不是最后一条路径:继续多次判断 */ boolean flag_isTwoChange =false; if (isTwoChange == 1) { continue; } double closeTime = time; String closeLine = line3; int m; for (m = 0; m < value.size(); m++) {//56 57 #0 T 0.00000000 1.76666667 if (value.get(m).split("#")[1].split(" ")[0].equals("2")) { String[] stations = value.get(m).split("#")[0].split(" "); String changeStations = Route2ChangeStation(value.get(m).split("#")[0].replaceAll(" ", "-"), linestation2staion); flag_twoChange = ODPathBack_isTwoChange(stations, changeStations, strings); if (flag_twoChange) { String[] times = value.get(m).split("#")[1].split(" "); if (Double.parseDouble(times[times.length - 1]) <= realTime && Double.parseDouble(times[times.length - 1]) >= closeTime) { flag_twoChange = false; flag_isTwoChange =true; closeTime = Double.parseDouble(times[times.length - 1]); closeLine = value.get(m); continue; } } } } if (flag_isTwoChange) { String fun = funtionPrintData(cardNo, closeLine); return fun; } else { if (valueNo == value.size() - 1 || m ==value.size()) { closeLine = CloseTimeLine(value, time, realTime); String fun = funtionPrintData(cardNo, closeLine); return fun; } else { isTwoChange = 1; continue; } } } else if (strings_allpath2[0].equals("3")) { /** * 三次换乘判断 --遍历所有路径 * 有满足三次换乘的路径:选取时间最接近的那条路径输出 * 不满足三次换乘路径: * 是最后一条路径:选择时间最接近的一条路径输出 * 不是最后一条路径:继续多次判断 */ boolean flag_isThreeChange =false; if (isThreeChange == 1) { continue; } double closeTime = time; String closeLine = line3; int m; for (m = 0; m < value.size(); m++) {//56 57 #0 T 0.00000000 1.76666667 if (value.get(m).split("#")[1].split(" ")[0].equals("3")) { String[] stations = value.get(m).split("#")[0].split(" "); String changeStations = Route2ChangeStation(value.get(m).split("#")[0].replaceAll(" ", "-"), linestation2staion); flag_threeChange = ODPathBack_isThreeChange(stations, changeStations, strings); if (flag_threeChange) { String[] times = value.get(m).split("#")[1].split(" "); if (Double.parseDouble(times[times.length - 1]) <= realTime && Double.parseDouble(times[times.length - 1]) >= closeTime) { flag_threeChange = false; flag_isThreeChange =true; closeTime = Double.parseDouble(times[times.length - 1]); closeLine = value.get(m); continue; } } } } if (flag_isThreeChange) { String fun = funtionPrintData(cardNo, closeLine); return fun; } else { if (valueNo == value.size() - 1 || m ==value.size()) { closeLine = CloseTimeLine(value, time, realTime); String fun = funtionPrintData(cardNo, closeLine); return fun; } else { isThreeChange = 1; continue; } } } else if (strings_allpath2[0].equals("4")) { /** * 四次换乘判断 --遍历所有路径 * 有满足四次换乘的路径:选取时间最接近的那条路径输出 * 不满足四次换乘路径: * 是最后一条路径:选择时间最接近的一条路径输出 * 不是最后一条路径:继续多次判断 */ boolean flag_isFourChange =false; if (isFourChange == 1) { continue; } double closeTime = time; String closeLine = line3; int m; for (m = 0; m < value.size(); m++) {//56 57 #0 T 0.00000000 1.76666667 if (value.get(m).split("#")[1].split(" ")[0].equals("4")) { String[] stations = value.get(m).split("#")[0].split(" "); String changeStations = Route2ChangeStation(value.get(m).split("#")[0].replaceAll(" ", "-"), linestation2staion); flag_fourChange = ODPathBack_isFourChange(stations, changeStations, strings); if (flag_fourChange) { String[] times = value.get(m).split("#")[1].split(" "); if (Double.parseDouble(times[times.length - 1]) <= realTime && Double.parseDouble(times[times.length - 1]) >= closeTime) { flag_fourChange = false; flag_isFourChange =true; closeTime = Double.parseDouble(times[times.length - 1]); closeLine = value.get(m); continue; } } } } if (flag_isFourChange == true) { String fun = funtionPrintData(cardNo, closeLine); return fun; } else { if (valueNo == value.size() - 1 || m ==value.size()) { closeLine = CloseTimeLine(value, time, realTime); String fun = funtionPrintData(cardNo, closeLine); return fun; } else { isFourChange = 1; continue; } } } else { /** * 如果四次换乘依然不成功,则直接输出时间最接近的一条路径 */ double closeTime = time; String closeLine = line3; closeLine = CloseTimeLine(value, time, realTime); String fun = funtionPrintData(cardNo, closeLine); return fun; } } } String closeLine = value.get(0).toString(); String fun = funtionPrintData(cardNo, closeLine); return fun; } /** * 输出,并跳出循环 * * @param cardNo 卡号 * @throws java.io.IOException */ public static String funtionPrintData(String cardNo,String strings){ count++; String stringCon = ConvertOD(strings); // stringCon =cardNo + "," + stringCon; // System.out.println("count:"+count); // System.out.println("hello"); // System.out.println(cardNo + "," + stringCon); return stringCon; } /** * 判断四次换乘是否成立 #4 */ public static boolean ODPathBack_isFourChange(String[] stations,String changeStations,String[] strings) throws ParseException{ boolean flag = false; String date1 = strings[1].substring(11, 19);//O站出发时间2015-09-16T12:09:47.000Z-->08:21:15 String date2 = strings[6].substring(11, 19);//D站到达时间2015-09-16T12:28:05.000Z-->09:09:30 date1 = TimeConvert.Second2Hour(TimeConvert.HourToSeconds(date1) + 8 * 60 * 60 + IN_STATION);//刷卡进站+等待时间150秒 date2 = TimeConvert.Second2Hour(TimeConvert.HourToSeconds(date2) + 8 * 60 * 60 - OUT_STATION);//出站刷卡时间90秒 String[] odChangeStations =changeStations.split("-"); String string_O2 =odChangeStations[0]; String string_D2 =odChangeStations[1]; String changeStation1 =odChangeStations[2]; String changeStation2 =odChangeStations[3]; String changeStation3 =odChangeStations[4]; String changeStation4 =odChangeStations[5]; String stationNext1 =null; String stationNext2 =null; String stationNext3 =null; for (int i =0;i<stations.length-1;i++) { if (stations[i].equals(NoNameExUtil.NO2Ser(changeStation1))) { stationNext1 = NoNameExUtil.Ser2NO(stations[i + 1]); } if (stations[i].equals(NoNameExUtil.NO2Ser(changeStation2))) { stationNext2 = NoNameExUtil.Ser2NO(stations[i + 1]); } if (stations[i].equals(NoNameExUtil.NO2Ser(changeStation3))) { stationNext3 = NoNameExUtil.Ser2NO(stations[i + 1]); } } String station2stationFirst = NoNameExUtil.Ser2NO(stations[0])+ NoNameExUtil.Ser2NO(stations[1]); String lineNo_First = linestation2staion.get(station2stationFirst); String station2stationLast = NoNameExUtil.Ser2NO(stations[stations.length - 2])+ NoNameExUtil.Ser2NO(stations[stations.length - 1]); String lineNo_Last = linestation2staion.get(station2stationLast); String station2stationSecond =changeStation1+stationNext1; String lineNo_Second =linestation2staion.get(station2stationSecond); String station2stationThird =changeStation2+stationNext2; String lineNo_Third =linestation2staion.get(station2stationThird); String station2stationForth =changeStation3+stationNext3; String lineNo_Forth =linestation2staion.get(station2stationForth); Date timeo_change_first = null;//从第一个换乘站出发的时间 Date timed_change_first = null;//到达第一个换成站的时间 Date timeo_change_second = null; Date timed_change_second = null; Date timeo_change_third = null; Date timed_change_third = null; Date timeo_change_last =null; Date timed_change_last =null; /** * 第一次换乘 到达第一个换乘点的时间 timed_change_first */ timed_change_first =timed_change(lineNo_First,string_O2, TimeConvert.String2Date(date1),changeStation1); /** * 第一次换乘 换乘点changeStation1的换乘时间 */ int CHANGE_STATION_SMALL1 =change_station_walkTime(changeStation1,lineNo_First,lineNo_Second); timeo_change_first = TimeConvert.String2Date(TimeConvert.Second2Hour(TimeConvert.HourToSeconds(TimeConvert.Date2String(timed_change_first)) + 8 * 60 * 60 + CHANGE_STATION_SMALL1)); /** * 找到第二个换乘站到达的时间 timed_change_second */ timed_change_second =timed_change(lineNo_Second,changeStation1,timeo_change_first,changeStation2); /** * 第二个换点点changeStation2 的换乘时间 CHANGE_STATION_SMALL2 */ int CHANGE_STATION_SMALL2 =change_station_walkTime(changeStation2,lineNo_Second,lineNo_Third); timeo_change_second = TimeConvert.String2Date(TimeConvert.Second2Hour(TimeConvert.HourToSeconds(TimeConvert.Date2String(timed_change_second)) + 8 * 60 * 60 + CHANGE_STATION_SMALL2)); /*** * 由第二个换乘点出发时间,可计算计算第三个换乘点 */ timed_change_third =timed_change(lineNo_Third,changeStation2,timeo_change_second,changeStation3); /** * 计算最后一个换乘changeStation3 的换乘时间 CHANGE_STATION_SMALL_LAST */ int CHANGE_STATION_SMALL3 =change_station_walkTime(changeStation3,lineNo_Third,lineNo_Forth); timeo_change_third = TimeConvert.String2Date(TimeConvert.Second2Hour(TimeConvert.HourToSeconds(TimeConvert.Date2String(timed_change_third)) + 8 * 60 * 60 + CHANGE_STATION_SMALL3)); /*** * 由第3个换乘点出发时间,可计算计算第4个换乘点,记最后一个换乘点的 到达时间 */ timed_change_last =timed_change(lineNo_Forth,changeStation3,timeo_change_third,changeStation4); /** * 计算最后一个换乘changeStation3 的换乘时间 CHANGE_STATION_SMALL_LAST */ int CHANGE_STATION_SMALL_LAST =change_station_walkTime(changeStation4,lineNo_Forth,lineNo_Last); /** * 最后一次换乘 从最后一个换乘点出发的时间 timeo_change_last */ timeo_change_last =timeo_change(lineNo_Last,string_D2, TimeConvert.String2Date(date2), changeStation4); /** * */ if (TimeConvert.HourToSeconds(TimeConvert.Date2String(timeo_change_last)) - TimeConvert.HourToSeconds(TimeConvert.Date2String(timed_change_last)) >= CHANGE_STATION_SMALL_LAST) { flag = true; } return flag; } /** * 判断三次换乘是否成立 #3 */ public static boolean ODPathBack_isThreeChange(String[] stations,String changeStations,String[] strings) throws ParseException{ boolean flag = false; String date1 = strings[1].substring(11, 19);//O站出发时间2015-09-16T12:09:47.000Z-->08:21:15 String date2 = strings[6].substring(11, 19);//D站到达时间2015-09-16T12:28:05.000Z-->09:09:30 date1 = TimeConvert.Second2Hour(TimeConvert.HourToSeconds(date1) + 8 * 60 * 60 + IN_STATION);//刷卡进站+等待时间150秒 date2 = TimeConvert.Second2Hour(TimeConvert.HourToSeconds(date2) + 8 * 60 * 60 - OUT_STATION);//出站刷卡时间90秒 String[] odChangeStations =changeStations.split("-"); String string_O2 =odChangeStations[0]; String string_D2 =odChangeStations[1]; String changeStation1 =odChangeStations[2]; String changeStation2 =odChangeStations[3]; String changeStation3 =odChangeStations[4]; String stationNext1 =null; String stationNext2 =null; for (int i =0;i<stations.length-1;i++){ if (stations[i].equals(NoNameExUtil.NO2Ser(changeStation1))){ stationNext1 = NoNameExUtil.Ser2NO(stations[i + 1]); } if (stations[i].equals(NoNameExUtil.NO2Ser(changeStation2))) { stationNext2 = NoNameExUtil.Ser2NO(stations[i + 1]); } } String station2stationFirst = NoNameExUtil.Ser2NO(stations[0])+ NoNameExUtil.Ser2NO(stations[1]); String lineNo_First = linestation2staion.get(station2stationFirst); String station2stationLast = NoNameExUtil.Ser2NO(stations[stations.length - 2])+ NoNameExUtil.Ser2NO(stations[stations.length - 1]); String lineNo_Last = linestation2staion.get(station2stationLast); String station2stationSecond =changeStation1+stationNext1; String lineNo_Second =linestation2staion.get(station2stationSecond); String station2stationThird =changeStation2+stationNext2; String lineNo_Third =linestation2staion.get(station2stationThird); Date timeo_change_first = null;//从第一个换乘站出发的时间 Date timed_change_first = null;//到达第一个换乘站的时间 Date timeo_change_second = null; Date timed_change_second = null; Date timeo_change_last =null; Date timed_change_last =null; /** * 第一次换乘 到达第一个换乘点的时间 timed_change_first */ timed_change_first =timed_change(lineNo_First,string_O2, TimeConvert.String2Date(date1),changeStation1); /** * 第一次换乘 换乘点changeStation1的换乘时间 */ int CHANGE_STATION_SMALL1 =change_station_walkTime(changeStation1,lineNo_First,lineNo_Second); /** * 第一次换乘 第一个换乘点出发时间 timeo_change_first * */ timeo_change_first = TimeConvert.String2Date(TimeConvert.Second2Hour(TimeConvert.HourToSeconds(TimeConvert.Date2String(timed_change_first)) + 8 * 60 * 60 + CHANGE_STATION_SMALL1)); /** * 第一个换乘站出发的时间 timeo_change_first 找到第二个换乘站到达的时间 timed_change_second */ timed_change_second =timed_change(lineNo_Second,changeStation1,timeo_change_first,changeStation2); /** * 第二个换点点changeStation2 的换乘时间 CHANGE_STATION_SMALL2 */ int CHANGE_STATION_SMALL2 =change_station_walkTime(changeStation2,lineNo_Second,lineNo_Third); timeo_change_second = TimeConvert.String2Date(TimeConvert.Second2Hour(TimeConvert.HourToSeconds(TimeConvert.Date2String(timed_change_second)) + 8 * 60 * 60 + CHANGE_STATION_SMALL2)); /*** * 由第二个换乘点出发时间,可计算计算第三个换乘点,记最后一个换乘点的 到达时间 */ timed_change_last =timed_change(lineNo_Third,changeStation2,timeo_change_second,changeStation3); /** * 计算最后一个换乘changeStation3 的换乘时间 CHANGE_STATION_SMALL_LAST */ int CHANGE_STATION_SMALL_LAST =change_station_walkTime(changeStation3,lineNo_Third,lineNo_Last); /** * 最后一次换乘 从最后一个换乘点出发的时间 timeo_change_last */ timeo_change_last =timeo_change(lineNo_Last,string_D2, TimeConvert.String2Date(date2), changeStation3); /** * 若两个时间差满足条件(相当于两次换乘),则返回flag =true; */ if (TimeConvert.HourToSeconds(TimeConvert.Date2String(timeo_change_last)) - TimeConvert.HourToSeconds(TimeConvert.Date2String(timed_change_last)) >= CHANGE_STATION_SMALL_LAST) { flag = true; } return flag; } /** * 判断两次换乘是否成立 #2 */ public static boolean ODPathBack_isTwoChange(String[] stations,String changeStations, String[] strings) throws ParseException{ boolean flag = false; String date1 = strings[1].substring(11, 19);//O站出发时间2015-09-16T12:09:47.000Z-->08:21:15 String date2 = strings[6].substring(11, 19);//D站到达时间2015-09-16T12:28:05.000Z-->09:09:30 date1 = TimeConvert.Second2Hour(TimeConvert.HourToSeconds(date1) + 8 * 60 * 60 + IN_STATION);//刷卡进站+等待时间150秒 date2 = TimeConvert.Second2Hour(TimeConvert.HourToSeconds(date2) + 8 * 60 * 60 - OUT_STATION);//出站刷卡时间90秒 String[] odChangeStations =changeStations.split("-"); String string_O2 =odChangeStations[0]; String string_D2 =odChangeStations[1]; String changeStation1 =odChangeStations[2]; String changeStation2 =odChangeStations[3]; String stationNext =null; for (int i =0;i<stations.length-1;i++){ if (stations[i].equals(NoNameExUtil.NO2Ser(changeStation1))){ stationNext = NoNameExUtil.Ser2NO(stations[i + 1]); break; } } String station2stationFirst = NoNameExUtil.Ser2NO(stations[0])+ NoNameExUtil.Ser2NO(stations[1]); String lineNo_First = linestation2staion.get(station2stationFirst); String station2stationLast = NoNameExUtil.Ser2NO(stations[stations.length - 2])+ NoNameExUtil.Ser2NO(stations[stations.length - 1]); String lineNo_Last = linestation2staion.get(station2stationLast); String station2stationSecond =changeStation1+stationNext; String lineNo_Second =linestation2staion.get(station2stationSecond); Date timeo_change_first = null; Date timed_change_first = null; Date timeo_change_last =null; Date timed_change_last =null; /** * 第一次换乘 到达第一个换乘点的时间 timed_change_first */ timed_change_first =timed_change(lineNo_First,string_O2, TimeConvert.String2Date(date1),changeStation1); /** * 第一次换乘 换乘点changeStation1的换乘时间 */ int CHANGE_STATION_SMALL1 =change_station_walkTime(changeStation1,lineNo_First,lineNo_Second); /** * 第一次换乘 第一个换乘点出发时间 timeo_change_first * */ timeo_change_first = TimeConvert.String2Date(TimeConvert.Second2Hour(TimeConvert.HourToSeconds(TimeConvert.Date2String(timed_change_first)) + 8 * 60 * 60 + CHANGE_STATION_SMALL1)); /** * 第一个换乘站出发的时间 timeo_change_first 找到第二个换乘站到达的时间 timed_change_second */ timed_change_last =timed_change(lineNo_Second,changeStation1,timeo_change_first,changeStation2); /** * 计算最后一个换乘changeStation3 的换乘时间 CHANGE_STATION_SMALL_LAST */ int CHANGE_STATION_SMALL_LAST =change_station_walkTime(changeStation2,lineNo_Second,lineNo_Last); /** * 最后一次换乘 从最后一个换乘点出发的时间 timeo_change_last */ timeo_change_last =timeo_change(lineNo_Last, string_D2, TimeConvert.String2Date(date2), changeStation2); if (TimeConvert.HourToSeconds(TimeConvert.Date2String(timeo_change_last)) - TimeConvert.HourToSeconds(TimeConvert.Date2String(timed_change_last)) >= CHANGE_STATION_SMALL_LAST) { flag = true; } return flag; } /** * 判断一次换乘是否成立 #1 */ //判断两个不同线的两个站点是否为直接换乘 public static boolean ODPathBack_isOneChange(String[] stations,String changeStations, String[] strings) throws ParseException{ boolean flag = false; String date1 = strings[1].substring(11, 19);//O站出发时间2015-09-16T12:09:47.000Z-->08:21:15 String date2 = strings[6].substring(11, 19);//D站到达时间2015-09-16T12:28:05.000Z-->09:09:30 date1 = TimeConvert.Second2Hour(TimeConvert.HourToSeconds(date1) + 8 * 60 * 60 + IN_STATION);//刷卡进站+等待时间150秒 date2 = TimeConvert.Second2Hour(TimeConvert.HourToSeconds(date2) + 8 * 60 * 60 - OUT_STATION);//出站刷卡时间90秒 String[] odChangeStations =changeStations.split("-"); String string_O2 =odChangeStations[0]; String string_D2 =odChangeStations[1]; String changeStation =odChangeStations[2]; String station2stationFirst = NoNameExUtil.Ser2NO(stations[0])+ NoNameExUtil.Ser2NO(stations[1]); String lineNo_First = linestation2staion.get(station2stationFirst); String station2stationLast = NoNameExUtil.Ser2NO(stations[stations.length - 2])+ NoNameExUtil.Ser2NO(stations[stations.length - 1]); String lineNo_Last = linestation2staion.get(station2stationLast); Date timeo_change = null; Date timed_change = null; /** * */ timed_change =timed_change(lineNo_First,string_O2, TimeConvert.String2Date(date1),changeStation); timeo_change =timeo_change(lineNo_Last,string_D2, TimeConvert.String2Date(date2), changeStation); int CHANGE_STATION_SMALL =change_station_walkTime(changeStation,lineNo_First,lineNo_Last); if (TimeConvert.HourToSeconds(TimeConvert.Date2String(timeo_change)) - TimeConvert.HourToSeconds(TimeConvert.Date2String(timed_change)) >= CHANGE_STATION_SMALL) { flag = true; } return flag; } /** * 判断是否满足同一条线不换乘的情况 #0 */ public static boolean ODPathBack_isOneNo(String[] strings, String lineNo) throws ParseException { boolean flag = false;//326816865,2015-09-16T08:21:15.000Z,地铁二号线,新秀,114.1444922,22.55086697,2015-09-16T09:09:30.000Z,地铁二号线,后海,113.9352052,22.52049297 String date1 = strings[1].substring(11, 19);//O站出发时间2015-09-16T12:09:47.000Z-->08:21:15 String date2 = strings[6].substring(11, 19);//D站到达时间2015-09-16T12:28:05.000Z-->09:09:30 date1 = TimeConvert.Second2Hour(TimeConvert.HourToSeconds(date1) + 8 * 60 * 60 + IN_STATION);//刷卡进站+等待时间150秒 date2 = TimeConvert.Second2Hour(TimeConvert.HourToSeconds(date2) + 8 * 60 * 60 - OUT_STATION);//出站刷卡时间90秒 String string_O = strings[3];//O站点 String string_D = strings[8];//D站点 int lineNo_O = 0; int lineNo_D = 0; for (int i = 0; i < lbs.get(lineNo).size()-1; i++) { for (int j = 0; j < lbs.get(lineNo).get(i).getStations().size(); j++) { if (lbs.get(lineNo).get(i).getStations().get(j).getStation().equals((string_O)) && lbs.get(lineNo).get(i).getStations().get(j).getDate().before(TimeConvert.String2Date(date1)) && lbs.get(lineNo).get(i + 1).getStations().get(j).getDate().after(TimeConvert.String2Date(date1))) { lineNo_O = i + 1;//O第18列车,第0站 } if (lbs.get(lineNo).get(i).getStations().get(j).getStation().equals((string_D)) && lbs.get(lineNo).get(i).getStations().get(j).getDate().before(TimeConvert.String2Date(date2)) && lbs.get(lineNo).get(i + 1).getStations().get(j).getDate().after(TimeConvert.String2Date(date2))) { lineNo_D = i ;//D第18列车,第20站 } } } if (lineNo_O == lineNo_D) { flag = true; } return flag; } /** * 不同换乘站点 每次换乘用的时间 * @param changeStation 换乘站 * @param lineNo_0 换乘前的线路2600 * @param lineNo_D 换乘后的线路2611 * @return 此次换乘用的时间 */ public static int change_station_walkTime(String changeStation,String lineNo_0,String lineNo_D){ int CHANGE_STATION_SMALL =0; String key =changeStation+","+lineNo_0.substring(0,3)+","+lineNo_D.substring(0,3); String value =mapWalk.get(key); if (lineNo_0.substring(3).equals("0") && lineNo_D.substring(3).equals("0")){ CHANGE_STATION_SMALL =(int)((Double.parseDouble(value.split(",")[0]))*60); }else if (lineNo_0.substring(3).equals("0") && lineNo_D.substring(3).equals("1")){ CHANGE_STATION_SMALL =(int)((Double.parseDouble(value.split(",")[1]))*60); }else if (lineNo_0.substring(3).equals("1") && lineNo_D.substring(3).equals("0")){ CHANGE_STATION_SMALL =(int)((Double.parseDouble(value.split(",")[2]))*60); }else if (lineNo_0.substring(3).equals("1") && lineNo_D.substring(3).equals("1")){ CHANGE_STATION_SMALL =(int)((Double.parseDouble(value.split(",")[3]))*60); } return CHANGE_STATION_SMALL; } /** * 从此站点o出发到达下一站点的时间 * string_O2 changeStation_first 都是编号 */ public static Date timed_change(String lineNo_first,String string_O2,Date date1,String changeStation_first) throws ParseException { int lineNo_first_no =0; Date timed_change_first =null; boolean flag = false; int num =0; for (int i = 0; i < lbs.get(lineNo_first).size(); i++) { for (int j = 0; j < lbs.get(lineNo_first).get(i).getStations().size(); j++) { if (i !=lbs.get(lineNo_first).size() -1 &&lbs.get(lineNo_first).get(i).getStations().get(j).getStation().equals(string_O2) && lbs.get(lineNo_first).get(i).getStations().get(j).getDate().before(date1) && lbs.get(lineNo_first).get(i + 1).getStations().get(j).getDate().after(date1)) { lineNo_first_no = i + 1; flag =true; num =1; }else if(i ==lbs.get(lineNo_first).size() -1 && num ==0 ) { num =1; flag =true; lineNo_first_no =i; } if (flag ==true &&lbs.get(lineNo_first).get(lineNo_first_no).getStations().get(j).getStation().equals(changeStation_first)) { timed_change_first = lbs.get(lineNo_first).get(lineNo_first_no).getStations().get(j).getDate(); flag =false; break; } } } return timed_change_first; } /** * 由D站点推出前一个换乘站点的出发时间 * string_D2 changeStation_first 都是编号 */ public static Date timeo_change(String lineNo_first,String string_O2,Date date1,String changeStation_first) throws ParseException { int lineNo_first_no =0; Date timed_change_first =null; boolean flag = false; int num =0; for (int i = 0; i < lbs.get(lineNo_first).size(); i++) { for (int j = 0; j < lbs.get(lineNo_first).get(i).getStations().size(); j++) { if (i != lbs.get(lineNo_first).size() - 1 && lbs.get(lineNo_first).get(i).getStations().get(j).getStation().equals(string_O2) && lbs.get(lineNo_first).get(i).getStations().get(j).getDate().before(date1) && lbs.get(lineNo_first).get(i + 1).getStations().get(j).getDate().after(date1)) { lineNo_first_no = i; flag = true; num = 1; break; } else if (i == lbs.get(lineNo_first).size() - 1 && num == 0) { num = 1; flag = true; lineNo_first_no = i - 1; break; } } if (flag ==true){ break; } } if (flag ==true){ for (int k = 0; k < lbs.get(lineNo_first).get(lineNo_first_no).getStations().size(); k++){ if (lbs.get(lineNo_first).get(lineNo_first_no).getStations().get(k).getStation().equals(changeStation_first)) { timed_change_first = lbs.get(lineNo_first).get(lineNo_first_no).getStations().get(k).getDate(); flag =false; break; } } } return timed_change_first; } /** * 转化为最后的结果,每个站点以字符串表示 */ public static String ConvertOD(String string){ // System.out.println("string:"+string); String[] strings = string.split("#")[0].split(" "); StringBuilder sb = new StringBuilder(); for (int i = 0; i < strings.length; i++) { sb.append(NoNameExUtil.Ser2NO(strings[i])); sb.append("-"); } return sb.toString().substring(0, sb.toString().length() - 1); } /** * 找出所有OD路径中的时间最接近实际时间的一条路径 * @param value 所有路径的List */ public static String CloseTimeLine(List<String> value,double time,double realTime){ double closeTime =time; String closeLine =value.get(0).toString(); for(int m =0;m<value.size();m++){//56 57 #0 T 0.00000000 1.76666667 String[] times =value.get(m).split("#")[1].split(" "); if (Double.parseDouble(times[times.length-1]) <=realTime && Double.parseDouble(times[times.length-1]) >=closeTime){ //// 大于 改成 小于了 改回大于最接近的时间 closeTime =Double.parseDouble(times[times.length-1]); closeLine =value.get(m); continue; } } return closeLine; } }
46,732
0.533964
0.502871
1,076
39.470261
38.624878
190
false
false
0
0
0
0
0
0
0.618959
false
false
4
8fdebe818a65bcac9c4417757dfc05010c817c39
14,834,817,066,815
7d212e8450d8844d0091d1805cd3732a7a7f2767
/src/test/java/common_utilities/TestData.java
6cbfab823287d5d55f93dc370201eabb2405097b
[]
no_license
PINPOINTG2/Pinpointe_Copy-of-Client-version
https://github.com/PINPOINTG2/Pinpointe_Copy-of-Client-version
3e971c527832b06770d43400afa1ab9e1a636b16
80d0508f9f73325e83e98a97ecd93e113836a2af
refs/heads/master
2020-06-21T11:14:38.817000
2019-07-17T17:24:03
2019-07-17T17:24:03
197,432,920
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package common_utilities; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import org.testng.annotations.DataProvider; public class TestData { private Utilities utils = new Utilities(); public ArrayList<String[]> getaddSubscriberData() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_postiveData")); return data; } public ArrayList<String[]> getCustomeFieldDataforAddSubscriber() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_postive_CustomfieldData")); return data; } public ArrayList<String[]> getupdateSubscriberData() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_postiveData")); return data; } public ArrayList<String[]> getCustomeFieldDataforUpdateSubscriber() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_postive_CustomfieldData")); return data; } public ArrayList<String[]> getdeleteSubscriberData(){ ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_postiveData")); return data; } public ArrayList<String[]> getSubscriberData(){ ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_postiveData")); return data; } public ArrayList<String[]> getListsData(){ ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Lists_postiveData")); return data; } public ArrayList<String[]> getTagsData(){ ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Tags_postiveData")); return data; } public ArrayList<String[]> getCreateTagsData(){ ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Tags_PostiveData_CreateTags")); return data; } @DataProvider(name = "getaddSubscriber_negData") public Object[] getaddSubscriber_negData() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_AddSubscribers_NegativeData")); Object[] obj = data.toArray(); return obj; } @DataProvider(name = "addMultipleSubscriberBulkData") public Object[] addMultipleSubscriberBulkData() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_addMultipleSubscriberBulkData")); Object[] obj = data.toArray(); return obj; } @DataProvider(name = "getSubscriber_negData") public Object[] getSubscriber_negData() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_GetSubscribers_NegativeData")); Object[] obj = data.toArray(); return obj; } @DataProvider(name = "getupdateSubscriber_negData") public Object[] getupdateSubscriber_negData() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_UpdateSubscribers_NegativeData")); Object[] obj = data.toArray(); return obj; } @DataProvider(name = "getDeleteSubscriber_negData") public Object[] getDeleteSubscriber_negData() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_DeleteSubscribers_NegativeData")); Object[] obj = data.toArray(); return obj; } @DataProvider(name = "CheckListForSubscriber_negData") public Object[] CheckListForSubscriber_negData() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_CheckListForContact_NegativeData")); Object[] obj = data.toArray(); return obj; } @DataProvider(name = "getUnsubscriber_negData") public Object[] getUnsubscriber_negData() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_Unsubscriber_NegativeData")); Object[] obj = data.toArray(); return obj; } @DataProvider(name = "getCheckListForUnsubscriber_negData") public Object[] getCheckListForUnsubscriber_negData() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_CheckListForUnsubscriber_NegativeData")); Object[] obj = data.toArray(); return obj; } @DataProvider(name = "getaddmultipleSubscribers_negData") public Object[] getaddmultipleSubscribers_negData() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_AddMultipleSubscribers_NegativeData")); Object[] obj = data.toArray(); return obj; } @DataProvider(name = "getaddmultipleSubscribers") public Object[] getaddmultipleSubscribers() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_AddMultipleSubscribers")); Object[] obj = data.toArray(); return obj; } @DataProvider(name = "getLists_Negative_FindLists") public Object[] getLists_Negative_FindLists() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Lists_Negative_FindLists")); Object[] obj = data.toArray(); return obj; } @DataProvider(name = "getLists_Negative_GetListSubscribers") public Object[] getLists_Negative_GetListSubscribers() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Lists_Negative_GetListSubscribers")); Object[] obj = data.toArray(); return obj; } @DataProvider(name = "getLists_Negative_GetCustomFieldStructure") public Object[] getLists_Negative_GetCustomFieldStructure() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Lists_Negative_GetCustomFieldStructure")); Object[] obj = data.toArray(); return obj; } @DataProvider(name = "getLists_Negative_GetUsersCustomField") public Object[] getLists_Negative_GetUsersCustomField() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Lists_Negative_GetUsersCustomField")); Object[] obj = data.toArray(); return obj; } @DataProvider(name = "gettags_Negative_TagSubscribers") public Object[] gettags_Negative_TagSubscribers() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Tags_Negative_TagSubscribers")); Object[] obj = data.toArray(); return obj; } @DataProvider(name = "gettags_negative_GetTagSubscribers") public Object[] gettags_negative_GetTagSubscribers() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Tags_Negative_GetTagSubscribers")); Object[] obj = data.toArray(); return obj; } @DataProvider(name = "gettags_Negative_untagSubscribers") public Object[] gettags_Negative_untagSubscribers() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Tags_Negative_UntagSubscribers")); Object[] obj = data.toArray(); return obj; } @DataProvider(name = "gettags_Negative_CreateTags") public Object[] gettags_Negative_CreateTags() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Tags_Negative_CreateTags")); Object[] obj = data.toArray(); return obj; } public ArrayList<String[]> getNegativeCreateTagsData(){ ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Tags_Negative_CreateTags_Tags")); return data; } public ArrayList<String[]> getContactforAddMultipleSubscribers(){ ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_Contact_AddMultipleSubscribers")); return data; } public ArrayList<String[]> getCustomeFieldforAddMultipleSubscriber(){ ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_Custom_AddMultipleSubscribers")); return data; } public ArrayList<String[]> getContactforAddMultipleSubscribersBulkData(){ ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_Contact_AddMultipleSubscribersBulkData")); return data; } public ArrayList<String[]> getCustomeFieldforAddMultipleSubscriberBulkData(){ ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_Custom_AddMultipleSubscribersBulkData")); return data; } public ArrayList<String[]> getContactforAddMultipleSubscribers_negData(){ ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_Contact_AddMultipleSubscribers_NegativeData")); return data; } public ArrayList<String[]> getCustomeFieldforAddMultipleSubscriber_negData(){ ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_Custom_AddMultipleSubscribers_NegativeData")); return data; } public ArrayList<String[]> getCustomeFieldforAddSubscriber_negData(){ ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_Custom_AddSubscribers_NegativeData")); return data; } public ArrayList<String[]> getCustomeFieldforupdateSubscriber_negData(){ ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_Custom_updateSubscribers_NegativeData")); return data; } public ArrayList<String[]> getContactforCreateTagsBulkData(){ ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Tags_Bulk_CreateTags")); return data; } public ArrayList<String[]> getCopyContactData(){ ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscribers_Postive_Copy_Contact_List")); return data; } public ArrayList<String[]> getContactDataforAddMultiSubscriber() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "AddmultiSubscribers_Contact")); return data; } public ArrayList<String[]> getCustomeFieldDataforAddMultiSubscriber() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "AddmultiSubscribers_Fields")); return data; } @DataProvider(name = "getSubscriberDataBulk") public Object[] getSubscriberDataBulk() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "GetSubscriberDataBulk")); Object[] obj = data.toArray(); return obj; } public ArrayList<String[]> GetdataFromCSV(String dataFile) { ArrayList<String[]> data = new ArrayList<String[]>(); int i=1; String Seperator = ",";/*System.getProperty("file.separator");*/ FileReader file = null; try { file = new FileReader("testdata/" + dataFile); } catch (FileNotFoundException e) { e.printStackTrace(); } BufferedReader csvReader = new BufferedReader(file); String row =null; try { while ((row = csvReader.readLine()) != null) { if(i!=1) { String[] dataStrings = row.split(Seperator); data.add(dataStrings); } i = i+1; } csvReader.close(); } catch (IOException e) { e.printStackTrace(); } return data; } }
UTF-8
Java
10,800
java
TestData.java
Java
[]
null
[]
package common_utilities; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import org.testng.annotations.DataProvider; public class TestData { private Utilities utils = new Utilities(); public ArrayList<String[]> getaddSubscriberData() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_postiveData")); return data; } public ArrayList<String[]> getCustomeFieldDataforAddSubscriber() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_postive_CustomfieldData")); return data; } public ArrayList<String[]> getupdateSubscriberData() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_postiveData")); return data; } public ArrayList<String[]> getCustomeFieldDataforUpdateSubscriber() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_postive_CustomfieldData")); return data; } public ArrayList<String[]> getdeleteSubscriberData(){ ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_postiveData")); return data; } public ArrayList<String[]> getSubscriberData(){ ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_postiveData")); return data; } public ArrayList<String[]> getListsData(){ ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Lists_postiveData")); return data; } public ArrayList<String[]> getTagsData(){ ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Tags_postiveData")); return data; } public ArrayList<String[]> getCreateTagsData(){ ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Tags_PostiveData_CreateTags")); return data; } @DataProvider(name = "getaddSubscriber_negData") public Object[] getaddSubscriber_negData() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_AddSubscribers_NegativeData")); Object[] obj = data.toArray(); return obj; } @DataProvider(name = "addMultipleSubscriberBulkData") public Object[] addMultipleSubscriberBulkData() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_addMultipleSubscriberBulkData")); Object[] obj = data.toArray(); return obj; } @DataProvider(name = "getSubscriber_negData") public Object[] getSubscriber_negData() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_GetSubscribers_NegativeData")); Object[] obj = data.toArray(); return obj; } @DataProvider(name = "getupdateSubscriber_negData") public Object[] getupdateSubscriber_negData() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_UpdateSubscribers_NegativeData")); Object[] obj = data.toArray(); return obj; } @DataProvider(name = "getDeleteSubscriber_negData") public Object[] getDeleteSubscriber_negData() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_DeleteSubscribers_NegativeData")); Object[] obj = data.toArray(); return obj; } @DataProvider(name = "CheckListForSubscriber_negData") public Object[] CheckListForSubscriber_negData() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_CheckListForContact_NegativeData")); Object[] obj = data.toArray(); return obj; } @DataProvider(name = "getUnsubscriber_negData") public Object[] getUnsubscriber_negData() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_Unsubscriber_NegativeData")); Object[] obj = data.toArray(); return obj; } @DataProvider(name = "getCheckListForUnsubscriber_negData") public Object[] getCheckListForUnsubscriber_negData() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_CheckListForUnsubscriber_NegativeData")); Object[] obj = data.toArray(); return obj; } @DataProvider(name = "getaddmultipleSubscribers_negData") public Object[] getaddmultipleSubscribers_negData() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_AddMultipleSubscribers_NegativeData")); Object[] obj = data.toArray(); return obj; } @DataProvider(name = "getaddmultipleSubscribers") public Object[] getaddmultipleSubscribers() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_AddMultipleSubscribers")); Object[] obj = data.toArray(); return obj; } @DataProvider(name = "getLists_Negative_FindLists") public Object[] getLists_Negative_FindLists() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Lists_Negative_FindLists")); Object[] obj = data.toArray(); return obj; } @DataProvider(name = "getLists_Negative_GetListSubscribers") public Object[] getLists_Negative_GetListSubscribers() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Lists_Negative_GetListSubscribers")); Object[] obj = data.toArray(); return obj; } @DataProvider(name = "getLists_Negative_GetCustomFieldStructure") public Object[] getLists_Negative_GetCustomFieldStructure() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Lists_Negative_GetCustomFieldStructure")); Object[] obj = data.toArray(); return obj; } @DataProvider(name = "getLists_Negative_GetUsersCustomField") public Object[] getLists_Negative_GetUsersCustomField() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Lists_Negative_GetUsersCustomField")); Object[] obj = data.toArray(); return obj; } @DataProvider(name = "gettags_Negative_TagSubscribers") public Object[] gettags_Negative_TagSubscribers() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Tags_Negative_TagSubscribers")); Object[] obj = data.toArray(); return obj; } @DataProvider(name = "gettags_negative_GetTagSubscribers") public Object[] gettags_negative_GetTagSubscribers() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Tags_Negative_GetTagSubscribers")); Object[] obj = data.toArray(); return obj; } @DataProvider(name = "gettags_Negative_untagSubscribers") public Object[] gettags_Negative_untagSubscribers() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Tags_Negative_UntagSubscribers")); Object[] obj = data.toArray(); return obj; } @DataProvider(name = "gettags_Negative_CreateTags") public Object[] gettags_Negative_CreateTags() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Tags_Negative_CreateTags")); Object[] obj = data.toArray(); return obj; } public ArrayList<String[]> getNegativeCreateTagsData(){ ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Tags_Negative_CreateTags_Tags")); return data; } public ArrayList<String[]> getContactforAddMultipleSubscribers(){ ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_Contact_AddMultipleSubscribers")); return data; } public ArrayList<String[]> getCustomeFieldforAddMultipleSubscriber(){ ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_Custom_AddMultipleSubscribers")); return data; } public ArrayList<String[]> getContactforAddMultipleSubscribersBulkData(){ ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_Contact_AddMultipleSubscribersBulkData")); return data; } public ArrayList<String[]> getCustomeFieldforAddMultipleSubscriberBulkData(){ ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_Custom_AddMultipleSubscribersBulkData")); return data; } public ArrayList<String[]> getContactforAddMultipleSubscribers_negData(){ ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_Contact_AddMultipleSubscribers_NegativeData")); return data; } public ArrayList<String[]> getCustomeFieldforAddMultipleSubscriber_negData(){ ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_Custom_AddMultipleSubscribers_NegativeData")); return data; } public ArrayList<String[]> getCustomeFieldforAddSubscriber_negData(){ ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_Custom_AddSubscribers_NegativeData")); return data; } public ArrayList<String[]> getCustomeFieldforupdateSubscriber_negData(){ ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscriber_Custom_updateSubscribers_NegativeData")); return data; } public ArrayList<String[]> getContactforCreateTagsBulkData(){ ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Tags_Bulk_CreateTags")); return data; } public ArrayList<String[]> getCopyContactData(){ ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "Subscribers_Postive_Copy_Contact_List")); return data; } public ArrayList<String[]> getContactDataforAddMultiSubscriber() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "AddmultiSubscribers_Contact")); return data; } public ArrayList<String[]> getCustomeFieldDataforAddMultiSubscriber() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "AddmultiSubscribers_Fields")); return data; } @DataProvider(name = "getSubscriberDataBulk") public Object[] getSubscriberDataBulk() { ArrayList<String[]> data = GetdataFromCSV(utils.getproperty("config", "GetSubscriberDataBulk")); Object[] obj = data.toArray(); return obj; } public ArrayList<String[]> GetdataFromCSV(String dataFile) { ArrayList<String[]> data = new ArrayList<String[]>(); int i=1; String Seperator = ",";/*System.getProperty("file.separator");*/ FileReader file = null; try { file = new FileReader("testdata/" + dataFile); } catch (FileNotFoundException e) { e.printStackTrace(); } BufferedReader csvReader = new BufferedReader(file); String row =null; try { while ((row = csvReader.readLine()) != null) { if(i!=1) { String[] dataStrings = row.split(Seperator); data.add(dataStrings); } i = i+1; } csvReader.close(); } catch (IOException e) { e.printStackTrace(); } return data; } }
10,800
0.719444
0.719167
340
29.764706
37.088257
131
false
false
0
0
0
0
0
0
1.591177
false
false
4
0f5f4b833db78b44dc33c7dd44ff615d89a96808
14,989,435,863,308
38e18c403475501234bf95b8e98bbe48b2185a9a
/spring-framerwork/src/main/java/com/jimi/spring/framework/dataaccess/jdbc/AutoGeneratedKeysDemo.java
4b933aad5c1556ffa93adb57c70805166a2a7471
[]
no_license
JimiStephen/spring-boot-tutorials
https://github.com/JimiStephen/spring-boot-tutorials
19258ff002eea3f2e96d87df94cc3c2c553b42dc
e2617a843866bb5d78e52265f86595128c36d1e2
refs/heads/master
2021-06-14T16:25:14.742000
2020-08-07T02:29:58
2020-08-07T02:29:58
179,438,578
0
0
null
false
2021-03-31T22:19:34
2019-04-04T06:49:31
2020-08-07T02:30:18
2021-03-31T22:19:32
29,593
0
0
3
Java
false
false
package com.jimi.spring.framework.dataaccess.jdbc; import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementCreator; import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.KeyHolder; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; /** * @author jimi * @version 1.0 * @date 2020/7/24 10:48 */ public class AutoGeneratedKeysDemo { private static final JdbcTemplate jdbcTemplate = new JdbcTemplate(); static { jdbcTemplate.setDataSource( DataSourceBuilder.create() .driverClassName("com.mysql.jdbc.Driver") .url("jdbc:mysql://localhost:3306/sakila?useSSL=false&amp;allowPublicKeyRetrieval=true") .username("root") .password("90jimi@mysql") .build()); } public static void main(String[] args) { final String INSERT_SQL = "insert into my_test (name) values(?)"; final String name = "Rob"; KeyHolder keyHolder = new GeneratedKeyHolder(); jdbcTemplate.update( new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { PreparedStatement ps = connection.prepareStatement(INSERT_SQL, new String[] {"id"}); ps.setString(1, name); return ps; } }, keyHolder); } }
UTF-8
Java
1,678
java
AutoGeneratedKeysDemo.java
Java
[ { "context": "ent;\nimport java.sql.SQLException;\n\n/**\n * @author jimi\n * @version 1.0\n * @date 2020/7/24 10:48\n */\npubl", "end": 447, "score": 0.999652624130249, "start": 443, "tag": "USERNAME", "value": "jimi" }, { "context": "ername(\"root\")\n .password(\"90jimi@mysql\")\n .build());\n }\n pu", "end": 964, "score": 0.9993684887886047, "start": 952, "tag": "PASSWORD", "value": "90jimi@mysql" }, { "context": "t (name) values(?)\";\n final String name = \"Rob\";\n KeyHolder keyHolder = new GeneratedKeyH", "end": 1159, "score": 0.9995406270027161, "start": 1156, "tag": "NAME", "value": "Rob" } ]
null
[]
package com.jimi.spring.framework.dataaccess.jdbc; import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementCreator; import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.KeyHolder; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; /** * @author jimi * @version 1.0 * @date 2020/7/24 10:48 */ public class AutoGeneratedKeysDemo { private static final JdbcTemplate jdbcTemplate = new JdbcTemplate(); static { jdbcTemplate.setDataSource( DataSourceBuilder.create() .driverClassName("com.mysql.jdbc.Driver") .url("jdbc:mysql://localhost:3306/sakila?useSSL=false&amp;allowPublicKeyRetrieval=true") .username("root") .password("<PASSWORD>") .build()); } public static void main(String[] args) { final String INSERT_SQL = "insert into my_test (name) values(?)"; final String name = "Rob"; KeyHolder keyHolder = new GeneratedKeyHolder(); jdbcTemplate.update( new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { PreparedStatement ps = connection.prepareStatement(INSERT_SQL, new String[] {"id"}); ps.setString(1, name); return ps; } }, keyHolder); } }
1,676
0.622765
0.610846
44
37.136364
28.739893
113
false
false
0
0
0
0
0
0
0.5
false
false
4
1e721a1c21a67fc134e0d847bdf660518e9a46bc
2,662,879,741,480
38b88c2b843e419209c640a8bbd05bc6661357ac
/AugurX/trunk/src/com/runstate/augur/controller/DoorEvent.java
232c01d6ebea075381dfe0687deb2efdf407889e
[]
no_license
codepope/augurx
https://github.com/codepope/augurx
9ba73e4939056300907e9a31e8f822a6952300f0
bcdd82b770ab3690d0e70fb0129c72e68f67ac40
refs/heads/master
2016-09-06T13:53:48.830000
2011-10-25T18:43:48
2011-10-25T18:43:48
33,052,952
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * DoorEvent.java * * @author Created by Omnicore CodeGuide */ package com.runstate.augur.controller; import java.util.Date; public class DoorEvent { Door door; String msg; Date date=new Date(); /** * Constructor * * @param door a Door * @param msg a String */ public DoorEvent(Door door, String msg) { this.door = door; this.msg = msg; } /** * Sets Door * * @param door a Door */ public void setDoor(Door door) { this.door = door; } /** * Returns Door * * @return a Door */ public Door getDoor() { return door; } /** * Sets Msg * * @param msg a String */ public void setMsg(String msg) { this.msg = msg; } public Date getDate() { return date; } /** * Returns Msg * * @return a String */ public String getMsg() { return msg; } public String toString() { return "DoorEvent("+door.getDoorname()+","+msg+")"; } }
UTF-8
Java
1,135
java
DoorEvent.java
Java
[]
null
[]
/** * DoorEvent.java * * @author Created by Omnicore CodeGuide */ package com.runstate.augur.controller; import java.util.Date; public class DoorEvent { Door door; String msg; Date date=new Date(); /** * Constructor * * @param door a Door * @param msg a String */ public DoorEvent(Door door, String msg) { this.door = door; this.msg = msg; } /** * Sets Door * * @param door a Door */ public void setDoor(Door door) { this.door = door; } /** * Returns Door * * @return a Door */ public Door getDoor() { return door; } /** * Sets Msg * * @param msg a String */ public void setMsg(String msg) { this.msg = msg; } public Date getDate() { return date; } /** * Returns Msg * * @return a String */ public String getMsg() { return msg; } public String toString() { return "DoorEvent("+door.getDoorname()+","+msg+")"; } }
1,135
0.473128
0.473128
79
12.341772
13.2071
53
false
false
0
0
0
0
0
0
1.037975
false
false
4
216fd2d66432fe3a9959a7b3d1d25954b32e5375
22,308,060,183,392
962af384d599ceab6bd907dfa012f212dbc5d0a8
/src/main/java/rumahsakit/dao/PoliDaoImpl.java
d2fb6bc8ea17caddd508dbeb3b926397f01cd815
[]
no_license
Bootcamp114/rumah-sakit
https://github.com/Bootcamp114/rumah-sakit
3f880db5e86d9603b81cc06c75e787af1a8ba3f4
361e4cd90ab5a144c1f18663f43abc0557dce095
refs/heads/master
2021-01-15T12:37:43.488000
2017-08-30T06:51:07
2017-08-30T06:51:07
99,652,818
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package rumahsakit.dao; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import rumahsakit.model.Pasien; import rumahsakit.model.Poli; @Repository public class PoliDaoImpl implements PoliDao { @Autowired public SessionFactory sessionFactory; @Override public void save(Poli pol) { // TODO Auto-generated method stub Session session = sessionFactory.getCurrentSession(); session.save(pol); session.flush(); } @Override public void update(Poli pol) { // TODO Auto-generated method stub Session session = sessionFactory.getCurrentSession(); session.update(pol); session.flush(); } @Override public void delete(int id) { // TODO Auto-generated method stub Session session = sessionFactory.getCurrentSession(); Poli pol = new Poli(); pol.setId(id); session.delete(pol); session.flush(); } @Override public Poli getById(int id) { // TODO Auto-generated method stub Session session = sessionFactory.getCurrentSession(); Poli pol = session.get(Poli.class, id); return pol; } @Override public List<Poli> getAllPoli() { // TODO Auto-generated method stub Session session = sessionFactory.getCurrentSession(); List<Poli> list = session.createCriteria(Poli.class).list(); return list; } }
UTF-8
Java
1,464
java
PoliDaoImpl.java
Java
[]
null
[]
package rumahsakit.dao; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import rumahsakit.model.Pasien; import rumahsakit.model.Poli; @Repository public class PoliDaoImpl implements PoliDao { @Autowired public SessionFactory sessionFactory; @Override public void save(Poli pol) { // TODO Auto-generated method stub Session session = sessionFactory.getCurrentSession(); session.save(pol); session.flush(); } @Override public void update(Poli pol) { // TODO Auto-generated method stub Session session = sessionFactory.getCurrentSession(); session.update(pol); session.flush(); } @Override public void delete(int id) { // TODO Auto-generated method stub Session session = sessionFactory.getCurrentSession(); Poli pol = new Poli(); pol.setId(id); session.delete(pol); session.flush(); } @Override public Poli getById(int id) { // TODO Auto-generated method stub Session session = sessionFactory.getCurrentSession(); Poli pol = session.get(Poli.class, id); return pol; } @Override public List<Poli> getAllPoli() { // TODO Auto-generated method stub Session session = sessionFactory.getCurrentSession(); List<Poli> list = session.createCriteria(Poli.class).list(); return list; } }
1,464
0.715847
0.715847
61
22
18.644209
62
false
false
0
0
0
0
0
0
1.442623
false
false
4
48538832361e94e60aaef373082bb1443fc0b4da
3,899,830,332,985
749b5456ab80300cc069308b0b2c7a5b3960dc21
/app/src/main/java/chiarahsieh/skypieah/happytranslator/HappyBackupAgent.java
8feb8dbd0dedb5a16563ecfff7defad6a8d522e5
[]
no_license
ChiaraHsieh/HappyTranslator
https://github.com/ChiaraHsieh/HappyTranslator
d9a490ee722162ad099be9c637604dcead697195
67d737f6daf1334fa141b4974c90b3c9825ef8fb
refs/heads/master
2021-01-18T18:04:34.634000
2016-07-04T11:44:19
2016-07-04T11:44:19
48,017,235
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package chiarahsieh.skypieah.happytranslator; import android.app.backup.BackupAgent; import android.app.backup.BackupAgentHelper; import android.app.backup.BackupDataInput; import android.app.backup.BackupDataOutput; import android.app.backup.BackupManager; import android.app.backup.FileBackupHelper; import android.content.Context; import android.os.ParcelFileDescriptor; import android.util.Log; import java.io.IOException; /** * Created by ChiaraHsieh on 2016/7/1. */ public class HappyBackupAgent extends BackupAgentHelper { static final private String KEY_PREFIX="dictBackup"; public void requestBackup() { BackupManager bm = new BackupManager(this); bm.dataChanged(); } @Override public void onCreate() { Log.i("BackupAgent","oncreate() backing up "+HappyDict.name); FileBackupHelper helper = new FileBackupHelper(this, HappyDict.name); addHelper(KEY_PREFIX,helper); } @Override public void onBackup(ParcelFileDescriptor oldState, BackupDataOutput data, ParcelFileDescriptor newState) throws IOException { Log.i("BackupAgent","onBackUp"); synchronized(SearchActivity.sDataLock) { super.onBackup(oldState, data, newState); } } @Override public void onRestore(BackupDataInput data, int appVersionCode, ParcelFileDescriptor newState) throws IOException { Log.i("BackupAgent","onRestore"); synchronized(SearchActivity.sDataLock) { super.onRestore(data, appVersionCode, newState); } } }
UTF-8
Java
1,558
java
HappyBackupAgent.java
Java
[ { "context": "g;\n\nimport java.io.IOException;\n\n/**\n * Created by ChiaraHsieh on 2016/7/1.\n */\npublic class HappyBackupAgent ex", "end": 459, "score": 0.9863637089729309, "start": 448, "tag": "NAME", "value": "ChiaraHsieh" } ]
null
[]
package chiarahsieh.skypieah.happytranslator; import android.app.backup.BackupAgent; import android.app.backup.BackupAgentHelper; import android.app.backup.BackupDataInput; import android.app.backup.BackupDataOutput; import android.app.backup.BackupManager; import android.app.backup.FileBackupHelper; import android.content.Context; import android.os.ParcelFileDescriptor; import android.util.Log; import java.io.IOException; /** * Created by ChiaraHsieh on 2016/7/1. */ public class HappyBackupAgent extends BackupAgentHelper { static final private String KEY_PREFIX="dictBackup"; public void requestBackup() { BackupManager bm = new BackupManager(this); bm.dataChanged(); } @Override public void onCreate() { Log.i("BackupAgent","oncreate() backing up "+HappyDict.name); FileBackupHelper helper = new FileBackupHelper(this, HappyDict.name); addHelper(KEY_PREFIX,helper); } @Override public void onBackup(ParcelFileDescriptor oldState, BackupDataOutput data, ParcelFileDescriptor newState) throws IOException { Log.i("BackupAgent","onBackUp"); synchronized(SearchActivity.sDataLock) { super.onBackup(oldState, data, newState); } } @Override public void onRestore(BackupDataInput data, int appVersionCode, ParcelFileDescriptor newState) throws IOException { Log.i("BackupAgent","onRestore"); synchronized(SearchActivity.sDataLock) { super.onRestore(data, appVersionCode, newState); } } }
1,558
0.724647
0.720796
48
31.458334
28.826319
130
false
false
0
0
0
0
0
0
0.708333
false
false
4
77c5e930434c7f56c0885ce56b3a3ac52c387e9b
6,528,350,360,015
5d16fb0c6c52a031a652ba153ff3770a2cd8fb13
/src/com/ciet/test/TestBasic.java
75716d8062d3ea6c266e5ea2215c6e7c7d235286
[]
no_license
orlandirafael/WebLogCIET
https://github.com/orlandirafael/WebLogCIET
c55e75db5bb54fa9b652b0fcf0d996328d0bc6b7
e0a0ebd23bc980f0962b58aacfcff0a00d107615
refs/heads/master
2021-01-23T08:56:48.692000
2015-08-12T15:15:40
2015-08-12T15:15:40
40,530,789
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ciet.test; import java.util.ArrayList; import java.util.List; import junit.framework.TestCase; import com.ciet.base.bo.MapaBO; import com.ciet.base.bo.MapaBOImpl; import com.ciet.base.util.CachedMap; import com.ciet.base.util.VerticeComparable; /** * * TestBasic.java * * <P>Classe de testes básicos do sistema * * @author Rafael Mandacaru Orlandi * @version 1.0 */ public class TestBasic extends TestCase { private MapaBO mapaBO = new MapaBOImpl(); public void testIncluiBaseControlada() { List<String> malha = new ArrayList<String>(); malha.add("A B 10"); malha.add("B D 15"); malha.add("A C 20"); malha.add("C D 30"); malha.add("B E 50"); malha.add("D E 30"); System.out.println("Iniciando o cadastramento de mapa controlado"); try { mapaBO.gravarMapa("mapaControlado", malha); List<VerticeComparable> result = CachedMap.getInstance().getMelhorCaminho("A", "D"); assertEquals("25", result.get(result.size()-1).getDistancia()+""); } catch (Exception e) { e.printStackTrace(); } } public void testFalhaCadastramentoDeMapas() { try { System.out.println("Iniciando o cadastramento de mapas"); List<String> malha = new ArrayList<String>(); for(int i=0; i< 200; i++){ malha.add("nodo"+i+" "+"nodo"+(i+1)+" "+0); } mapaBO.gravarMapa("mapa_teste", malha); } catch (Exception e) { System.out.println("Erro esperado no cadastro de dados incompatíveis"); } } public void testRemove(){ System.out.println("Removendo a base cadastrada"); mapaBO.removerMapa("mapa_para_remover"); } public void testCadastramentoDeMapaParaRemover() { try { System.out.println("Iniciando o cadastramento de mapa a ser removido"); List<String> malha = new ArrayList<String>(); for(int i=0; i< 200; i++){ malha.add("x"+i+" "+"x"+(i+1)+" "+(Math.round(Math.random()*100)+1)); } mapaBO.gravarMapa("mapa_para_remover", malha); } catch (Exception e) { e.printStackTrace(); } } }
WINDOWS-1250
Java
1,999
java
TestBasic.java
Java
[ { "context": "lasse de testes básicos do sistema\n * \n * @author Rafael Mandacaru Orlandi\n * @version 1.0\n */\npublic class TestBasic extend", "end": 372, "score": 0.9998888969421387, "start": 348, "tag": "NAME", "value": "Rafael Mandacaru Orlandi" } ]
null
[]
package com.ciet.test; import java.util.ArrayList; import java.util.List; import junit.framework.TestCase; import com.ciet.base.bo.MapaBO; import com.ciet.base.bo.MapaBOImpl; import com.ciet.base.util.CachedMap; import com.ciet.base.util.VerticeComparable; /** * * TestBasic.java * * <P>Classe de testes básicos do sistema * * @author <NAME> * @version 1.0 */ public class TestBasic extends TestCase { private MapaBO mapaBO = new MapaBOImpl(); public void testIncluiBaseControlada() { List<String> malha = new ArrayList<String>(); malha.add("A B 10"); malha.add("B D 15"); malha.add("A C 20"); malha.add("C D 30"); malha.add("B E 50"); malha.add("D E 30"); System.out.println("Iniciando o cadastramento de mapa controlado"); try { mapaBO.gravarMapa("mapaControlado", malha); List<VerticeComparable> result = CachedMap.getInstance().getMelhorCaminho("A", "D"); assertEquals("25", result.get(result.size()-1).getDistancia()+""); } catch (Exception e) { e.printStackTrace(); } } public void testFalhaCadastramentoDeMapas() { try { System.out.println("Iniciando o cadastramento de mapas"); List<String> malha = new ArrayList<String>(); for(int i=0; i< 200; i++){ malha.add("nodo"+i+" "+"nodo"+(i+1)+" "+0); } mapaBO.gravarMapa("mapa_teste", malha); } catch (Exception e) { System.out.println("Erro esperado no cadastro de dados incompatíveis"); } } public void testRemove(){ System.out.println("Removendo a base cadastrada"); mapaBO.removerMapa("mapa_para_remover"); } public void testCadastramentoDeMapaParaRemover() { try { System.out.println("Iniciando o cadastramento de mapa a ser removido"); List<String> malha = new ArrayList<String>(); for(int i=0; i< 200; i++){ malha.add("x"+i+" "+"x"+(i+1)+" "+(Math.round(Math.random()*100)+1)); } mapaBO.gravarMapa("mapa_para_remover", malha); } catch (Exception e) { e.printStackTrace(); } } }
1,981
0.667501
0.651477
78
24.602564
22.645166
87
false
false
0
0
0
0
0
0
1.961538
false
false
4
54540273641e3e03ba5afb2386439b17ad2d27e3
22,084,721,870,719
99cd44e4c6c093c814c17f86a3e6d1d3b539214c
/projeto/v02/ws_pousada/src/ws_pousada/test/ConsoleTest.java
d16899e1d3ad2f61f90a26b860465937d21603e5
[]
no_license
niltonfjr086/MobDev2018-01
https://github.com/niltonfjr086/MobDev2018-01
90b4e528d89fb5f85e3def675b063b3258041f24
405be2af05ea9597f54072ff9354faa255b79913
refs/heads/master
2021-04-06T06:41:11.446000
2018-07-09T11:31:53
2018-07-09T11:31:53
124,879,817
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ws_pousada.test; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import org.junit.Test; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import ws_pousada.model.FactoryDAO; import ws_pousada.model.HttpConnector; import ws_pousada.model.dao.CategoriaDAO; import ws_pousada.model.dao.ProdutoDAO; import ws_pousada.model.entity.Categoria; import ws_pousada.model.entity.Endereco; import ws_pousada.model.entity.Estadia; import ws_pousada.model.entity.Produto; public class ConsoleTest { private Endereco endereco = new Endereco(); @Test public void toConsole() { System.out.println("TESTE"); FactoryDAO.sessionInstance(); this.postEstadiaTest(); // this.postEnderecoTest(); // this.postSaveCategoria(); // this.postUpdateCategoria(); // this.listAllCategorias(); // this.postSaveProduto(); // this.saveProduto(); // this.postUpdateProduto(); // this.getListAllProdutos(); // this.getProduto(); FactoryDAO.closeInstance(); assertEquals(0, 0); } public void postEstadiaTest() { Estadia e = new Estadia(); e.setConsumo_pago(200d); e.setDiarias_consumidas(3); e.setDiarias_pagas(3); e.setDiarias_reservadas(3); e.setIsAtivo(true); e.setObservacoes("blbobloblbobloblbolob"); e.setQtde_hospede(2); ObjectMapper mapper = new ObjectMapper(); String jsonInString = ""; try { jsonInString = mapper.writeValueAsString(e); System.out.println(jsonInString); } catch (JsonProcessingException ex) { ex.printStackTrace(); } String entityResponse = HttpConnector.savePostConnect("http://localhost:8080/ws_pousada/estadia/save", jsonInString); System.out.println(entityResponse); } public void postEnderecoTest() { this.endereco = new Endereco(); this.endereco.setBairro("Santa Mônica"); this.endereco.setCep("1221928"); this.endereco.setCidade("Florianópolis"); this.endereco.setComplemento("Casa"); this.endereco.setNumero(9090); this.endereco.setPais("Brasil"); this.endereco.setRua("Testes Street"); this.endereco.setUf("SC"); ObjectMapper mapper = new ObjectMapper(); String jsonInString = ""; try { jsonInString = mapper.writeValueAsString(this.endereco); System.out.println(jsonInString); } catch (JsonProcessingException e) { e.printStackTrace(); } String entityResponse = HttpConnector.savePostConnect("http://localhost:8080/ws_pousada/intro/saveAddress", jsonInString); System.out.println(entityResponse); } public void postSaveCategoria() { Categoria c = new Categoria(); c.setNome("Lanches"); ObjectMapper mapper = new ObjectMapper(); String jsonInString = ""; try { jsonInString = mapper.writeValueAsString(c); System.out.println(jsonInString); } catch (JsonProcessingException e) { e.printStackTrace(); } String entityResponse = HttpConnector.savePostConnect("http://localhost:8080/ws_pousada/categoria/save", jsonInString); System.out.println(entityResponse); } public void postUpdateCategoria() { Categoria c = new Categoria(); CategoriaDAO categoriaDAO = new CategoriaDAO(); // c = categoriaDAO.findById(6L); // c.setNome("Pratos Quentes"); c = categoriaDAO.findById(1L); c.setNome("Pizzas Doces ou Salgadas"); ObjectMapper mapper = new ObjectMapper(); String jsonInString = ""; try { jsonInString = mapper.writeValueAsString(c); System.out.println(jsonInString); } catch (JsonProcessingException e) { e.printStackTrace(); } String entityResponse = HttpConnector.savePostConnect("http://localhost:8080/ws_pousada/categoria/update", jsonInString); System.out.println(entityResponse); } public void listAllCategorias() { HttpConnector.getConnect("http://localhost:8080/ws_pousada/categoria/listAll"); } public void postSaveProduto() { Categoria c = new Categoria(); CategoriaDAO categoriaDAO = new CategoriaDAO(); c = categoriaDAO.findById(1L); Produto p = new Produto(); p.setCategoria(c); p.setNome("Cheese Salada"); p.setValor(17.0); ObjectMapper mapper = new ObjectMapper(); String jsonInString = ""; try { jsonInString = mapper.writeValueAsString(p); System.out.println(jsonInString); } catch (JsonProcessingException e) { e.printStackTrace(); } String entityResponse = HttpConnector.savePostConnect("http://localhost:8080/ws_pousada/produto/save", jsonInString); System.out.println(entityResponse); } public void saveProduto() { Categoria c = new Categoria(); CategoriaDAO categoriaDAO = new CategoriaDAO(); c = categoriaDAO.findById(3L); Produto p = new Produto(); p.setCategoria(c); p.setNome("Batata Frita"); ProdutoDAO produtoDAO = new ProdutoDAO(); produtoDAO.save(p); } public void postUpdateProduto() { ProdutoDAO produtoDAO = new ProdutoDAO(); Produto p = produtoDAO.findById(1L); p.setNome("Batata Frita Média"); Categoria c = new Categoria(); CategoriaDAO categoriaDAO = new CategoriaDAO(); c = categoriaDAO.findById(2L); p.setCategoria(c); ObjectMapper mapper = new ObjectMapper(); String jsonInString = ""; try { jsonInString = mapper.writeValueAsString(p); System.out.println(jsonInString); } catch (JsonProcessingException e) { e.printStackTrace(); } String entityResponse = HttpConnector.savePostConnect("http://localhost:8080/ws_pousada/produto/update", jsonInString); System.out.println(entityResponse); } private void getListAllProdutos() { String retorno = HttpConnector.getConnect("http://localhost:8080/ws_pousada/produto/listAll"); ObjectMapper mapper = new ObjectMapper(); List<Produto> produtos = new ArrayList<>(); try { List<Object> voidList = mapper.readValue(retorno, List.class); for (Object o : voidList) { Produto p = mapper.readValue(mapper.writeValueAsString(o), Produto.class); produtos.add(p); } } catch (Exception e) { e.printStackTrace(); } System.out.println(produtos); } private void getProduto() { String retorno = HttpConnector.getConnect("http://localhost:8080/ws_pousada/produto/getById", "2"); ObjectMapper mapper = new ObjectMapper(); Produto produto = null; try { produto = mapper.readValue(retorno, Produto.class); } catch (IOException e) { e.printStackTrace(); } System.out.println(produto); System.out.println("LALA"); try { } catch (Exception e) { e.printStackTrace(); } } }
UTF-8
Java
6,669
java
ConsoleTest.java
Java
[ { "context": "new Produto();\n\n\t\tp.setCategoria(c);\n\t\tp.setNome(\"Cheese Salada\");\n\t\tp.setValor(17.0);\n\n\t\tObjectMapper mapper = n", "end": 4257, "score": 0.8724242448806763, "start": 4244, "tag": "NAME", "value": "Cheese Salada" }, { "context": "new Produto();\n\n\t\tp.setCategoria(c);\n\t\tp.setNome(\"Batata Frita\");\n\n\t\tProdutoDAO produtoDAO = new ProdutoDAO();\n\t", "end": 4908, "score": 0.9968629479408264, "start": 4896, "tag": "NAME", "value": "Batata Frita" }, { "context": "roduto p = produtoDAO.findById(1L);\n\n\t\tp.setNome(\"Batata Frita Média\");\n\n\t\tCategoria c = new Categoria();\n\t\tCategoriaD", "end": 5134, "score": 0.997539758682251, "start": 5116, "tag": "NAME", "value": "Batata Frita Média" } ]
null
[]
package ws_pousada.test; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import org.junit.Test; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import ws_pousada.model.FactoryDAO; import ws_pousada.model.HttpConnector; import ws_pousada.model.dao.CategoriaDAO; import ws_pousada.model.dao.ProdutoDAO; import ws_pousada.model.entity.Categoria; import ws_pousada.model.entity.Endereco; import ws_pousada.model.entity.Estadia; import ws_pousada.model.entity.Produto; public class ConsoleTest { private Endereco endereco = new Endereco(); @Test public void toConsole() { System.out.println("TESTE"); FactoryDAO.sessionInstance(); this.postEstadiaTest(); // this.postEnderecoTest(); // this.postSaveCategoria(); // this.postUpdateCategoria(); // this.listAllCategorias(); // this.postSaveProduto(); // this.saveProduto(); // this.postUpdateProduto(); // this.getListAllProdutos(); // this.getProduto(); FactoryDAO.closeInstance(); assertEquals(0, 0); } public void postEstadiaTest() { Estadia e = new Estadia(); e.setConsumo_pago(200d); e.setDiarias_consumidas(3); e.setDiarias_pagas(3); e.setDiarias_reservadas(3); e.setIsAtivo(true); e.setObservacoes("blbobloblbobloblbolob"); e.setQtde_hospede(2); ObjectMapper mapper = new ObjectMapper(); String jsonInString = ""; try { jsonInString = mapper.writeValueAsString(e); System.out.println(jsonInString); } catch (JsonProcessingException ex) { ex.printStackTrace(); } String entityResponse = HttpConnector.savePostConnect("http://localhost:8080/ws_pousada/estadia/save", jsonInString); System.out.println(entityResponse); } public void postEnderecoTest() { this.endereco = new Endereco(); this.endereco.setBairro("Santa Mônica"); this.endereco.setCep("1221928"); this.endereco.setCidade("Florianópolis"); this.endereco.setComplemento("Casa"); this.endereco.setNumero(9090); this.endereco.setPais("Brasil"); this.endereco.setRua("Testes Street"); this.endereco.setUf("SC"); ObjectMapper mapper = new ObjectMapper(); String jsonInString = ""; try { jsonInString = mapper.writeValueAsString(this.endereco); System.out.println(jsonInString); } catch (JsonProcessingException e) { e.printStackTrace(); } String entityResponse = HttpConnector.savePostConnect("http://localhost:8080/ws_pousada/intro/saveAddress", jsonInString); System.out.println(entityResponse); } public void postSaveCategoria() { Categoria c = new Categoria(); c.setNome("Lanches"); ObjectMapper mapper = new ObjectMapper(); String jsonInString = ""; try { jsonInString = mapper.writeValueAsString(c); System.out.println(jsonInString); } catch (JsonProcessingException e) { e.printStackTrace(); } String entityResponse = HttpConnector.savePostConnect("http://localhost:8080/ws_pousada/categoria/save", jsonInString); System.out.println(entityResponse); } public void postUpdateCategoria() { Categoria c = new Categoria(); CategoriaDAO categoriaDAO = new CategoriaDAO(); // c = categoriaDAO.findById(6L); // c.setNome("Pratos Quentes"); c = categoriaDAO.findById(1L); c.setNome("Pizzas Doces ou Salgadas"); ObjectMapper mapper = new ObjectMapper(); String jsonInString = ""; try { jsonInString = mapper.writeValueAsString(c); System.out.println(jsonInString); } catch (JsonProcessingException e) { e.printStackTrace(); } String entityResponse = HttpConnector.savePostConnect("http://localhost:8080/ws_pousada/categoria/update", jsonInString); System.out.println(entityResponse); } public void listAllCategorias() { HttpConnector.getConnect("http://localhost:8080/ws_pousada/categoria/listAll"); } public void postSaveProduto() { Categoria c = new Categoria(); CategoriaDAO categoriaDAO = new CategoriaDAO(); c = categoriaDAO.findById(1L); Produto p = new Produto(); p.setCategoria(c); p.setNome("<NAME>"); p.setValor(17.0); ObjectMapper mapper = new ObjectMapper(); String jsonInString = ""; try { jsonInString = mapper.writeValueAsString(p); System.out.println(jsonInString); } catch (JsonProcessingException e) { e.printStackTrace(); } String entityResponse = HttpConnector.savePostConnect("http://localhost:8080/ws_pousada/produto/save", jsonInString); System.out.println(entityResponse); } public void saveProduto() { Categoria c = new Categoria(); CategoriaDAO categoriaDAO = new CategoriaDAO(); c = categoriaDAO.findById(3L); Produto p = new Produto(); p.setCategoria(c); p.setNome("<NAME>"); ProdutoDAO produtoDAO = new ProdutoDAO(); produtoDAO.save(p); } public void postUpdateProduto() { ProdutoDAO produtoDAO = new ProdutoDAO(); Produto p = produtoDAO.findById(1L); p.setNome("<NAME>"); Categoria c = new Categoria(); CategoriaDAO categoriaDAO = new CategoriaDAO(); c = categoriaDAO.findById(2L); p.setCategoria(c); ObjectMapper mapper = new ObjectMapper(); String jsonInString = ""; try { jsonInString = mapper.writeValueAsString(p); System.out.println(jsonInString); } catch (JsonProcessingException e) { e.printStackTrace(); } String entityResponse = HttpConnector.savePostConnect("http://localhost:8080/ws_pousada/produto/update", jsonInString); System.out.println(entityResponse); } private void getListAllProdutos() { String retorno = HttpConnector.getConnect("http://localhost:8080/ws_pousada/produto/listAll"); ObjectMapper mapper = new ObjectMapper(); List<Produto> produtos = new ArrayList<>(); try { List<Object> voidList = mapper.readValue(retorno, List.class); for (Object o : voidList) { Produto p = mapper.readValue(mapper.writeValueAsString(o), Produto.class); produtos.add(p); } } catch (Exception e) { e.printStackTrace(); } System.out.println(produtos); } private void getProduto() { String retorno = HttpConnector.getConnect("http://localhost:8080/ws_pousada/produto/getById", "2"); ObjectMapper mapper = new ObjectMapper(); Produto produto = null; try { produto = mapper.readValue(retorno, Produto.class); } catch (IOException e) { e.printStackTrace(); } System.out.println(produto); System.out.println("LALA"); try { } catch (Exception e) { e.printStackTrace(); } } }
6,643
0.720522
0.710621
281
22.72242
22.661234
109
false
false
0
0
0
0
0
0
1.88968
false
false
4
014c800b769986c3efa4b47469d39d6f6a6c3fe5
23,613,730,258,969
8ec474e67a199509974e94536f0379ff7bdf9fee
/src/main/java/com/epam/bookscatalog/service/AuthorService.java
6099c65256c62da19b77fc90a33fb778a3a26a66
[]
no_license
gayane911/bookscatalog
https://github.com/gayane911/bookscatalog
e1412c4e91c97def37a5fae737778e1530785dfa
2c6b4133cb77bdceb623792f78ce87057926d94f
refs/heads/master
2020-07-07T13:11:48.800000
2019-09-06T10:54:57
2019-09-06T10:54:57
201,029,650
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.epam.bookscatalog.service; import com.epam.bookscatalog.model.Author; import com.epam.bookscatalog.payload.AuthorRequest; import com.epam.bookscatalog.repository.AuthorRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class AuthorService { @Autowired private AuthorRepository authorRepository; public Author createAuthor(AuthorRequest authorRequest) { Author author = new Author(); author.setFullName(authorRequest.getFullName()); return authorRepository.save(author); } }
UTF-8
Java
597
java
AuthorService.java
Java
[]
null
[]
package com.epam.bookscatalog.service; import com.epam.bookscatalog.model.Author; import com.epam.bookscatalog.payload.AuthorRequest; import com.epam.bookscatalog.repository.AuthorRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class AuthorService { @Autowired private AuthorRepository authorRepository; public Author createAuthor(AuthorRequest authorRequest) { Author author = new Author(); author.setFullName(authorRequest.getFullName()); return authorRepository.save(author); } }
597
0.81072
0.81072
20
28.85
22.654526
62
false
false
0
0
0
0
0
0
0.5
false
false
4
ee31a4d66b8c8c28a69f1f6cca44b5b0fb94841d
25,640,954,759,378
8813bce74ccf72bb4ad747e234c7f9a88bfef22a
/src/main/java/com/nthread/outthere/projecteuler/Problem43.java
1bcee46d0cd70a2b8802798f4a338a4882c9834f
[]
no_license
stevedbrown/outthere
https://github.com/stevedbrown/outthere
051ba222f8da36b5957c51d72d9c4b503de29a94
377962affcc8ef41b653328f434391c41835ce21
refs/heads/master
2021-01-04T14:05:41.727000
2016-10-14T05:08:22
2016-10-14T05:08:22
24,398,936
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.nthread.outthere.projecteuler; import java.util.List; /** * The number, 1406357289, is a 0 to 9 pandigital number because it is made up of each * of the digits 0 to 9 in some order, but it also has a rather interesting sub-string * divisibility property. * * Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we note the following: * * d2d3d4=406 is divisible by 2 * d3d4d5=063 is divisible by 3 * d4d5d6=635 is divisible by 5 * d5d6d7=357 is divisible by 7 * d6d7d8=572 is divisible by 11 * d7d8d9=728 is divisible by 13 * d8d9d10=289 is divisible by 17 * * Find the sum of all 0 to 9 pandigital numbers with this property. */ public class Problem43 { public static void main(String[] args) { Tester<String> tester = new Tester<String>() { @Override public boolean test(String t) { return four3Divisible(t); } }; List<String> pans = PandigitalUtil.getPandigitals(tester); long sum = 0; for ( String val : pans ) { sum += Long.parseLong(val); } System.out.println("sum is:" + sum); } public static boolean four3Divisible(String val) { return isDivisible(val.substring(1,4), 2) && isDivisible(val.substring(2,5), 3) && isDivisible(val.substring(3,6), 5) && isDivisible(val.substring(4,7), 7) && isDivisible(val.substring(5,8), 11) && isDivisible(val.substring(6,9), 13) && isDivisible(val.substring(7,10), 17); } private static boolean isDivisible(String substring, int i) { return Integer.parseInt(substring) % i == 0; } }
UTF-8
Java
1,554
java
Problem43.java
Java
[]
null
[]
package com.nthread.outthere.projecteuler; import java.util.List; /** * The number, 1406357289, is a 0 to 9 pandigital number because it is made up of each * of the digits 0 to 9 in some order, but it also has a rather interesting sub-string * divisibility property. * * Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we note the following: * * d2d3d4=406 is divisible by 2 * d3d4d5=063 is divisible by 3 * d4d5d6=635 is divisible by 5 * d5d6d7=357 is divisible by 7 * d6d7d8=572 is divisible by 11 * d7d8d9=728 is divisible by 13 * d8d9d10=289 is divisible by 17 * * Find the sum of all 0 to 9 pandigital numbers with this property. */ public class Problem43 { public static void main(String[] args) { Tester<String> tester = new Tester<String>() { @Override public boolean test(String t) { return four3Divisible(t); } }; List<String> pans = PandigitalUtil.getPandigitals(tester); long sum = 0; for ( String val : pans ) { sum += Long.parseLong(val); } System.out.println("sum is:" + sum); } public static boolean four3Divisible(String val) { return isDivisible(val.substring(1,4), 2) && isDivisible(val.substring(2,5), 3) && isDivisible(val.substring(3,6), 5) && isDivisible(val.substring(4,7), 7) && isDivisible(val.substring(5,8), 11) && isDivisible(val.substring(6,9), 13) && isDivisible(val.substring(7,10), 17); } private static boolean isDivisible(String substring, int i) { return Integer.parseInt(substring) % i == 0; } }
1,554
0.679537
0.612613
55
27.254545
24.354368
95
false
false
0
0
0
0
0
0
1.818182
false
false
4
3ada4dfbc9fbf25635d4c17538dc35a1d52e9dc1
1,623,497,698,101
90726a8e556de73311e0a1faa51a7afe616ce810
/src/com/parang/colorpicker/ParangColorPicker.java
ee623eddcb42138dc4edad440e42e749e23a6d7d
[]
no_license
ParangCo/ParangColorPicker
https://github.com/ParangCo/ParangColorPicker
cdc98c858f06b1c6dd943bf899f4980037a2b04d
093a9bac51c873a3512dabe684b79c856202548d
refs/heads/master
2021-01-22T00:59:37.884000
2014-10-03T14:47:46
2014-10-03T14:47:46
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.parang.colorpicker; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.view.LayoutInflater; import android.view.View; public class ParangColorPicker { public interface ParangColorPickerListener { void onCancel(); void onOk(int color); } private AlertDialog dialog; private ParangColorPickerListener listener; private ParangColorPickerWidget ParangColorPickerWidget; public ParangColorPicker(Context context, Boolean IsPersian, ParangColorPickerListener Listener) { View mView = LayoutInflater.from(context).inflate(R.layout.color_picker_dialog_layout, null); ParangColorPickerWidget = (ParangColorPickerWidget) mView.findViewById(R.id.ColorPicker); ParangColorPickerWidget.PersianMode(IsPersian); this.listener = Listener; dialog = new AlertDialog.Builder(context).setView(mView).setPositiveButton(context.getString(R.string.OK), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { listener.onOk(ParangColorPickerWidget.getColor()); } }).setNegativeButton(context.getString(R.string.Cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { listener.onCancel(); } }).create(); } public void show(int InitColor) { ParangColorPickerWidget.setColor(InitColor); dialog.show(); } public void SetColor(int Color) { ParangColorPickerWidget.setColor(Color); } public void PersianMode(Boolean IsPersian) { ParangColorPickerWidget.PersianMode(IsPersian); } }
UTF-8
Java
1,678
java
ParangColorPicker.java
Java
[]
null
[]
package com.parang.colorpicker; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.view.LayoutInflater; import android.view.View; public class ParangColorPicker { public interface ParangColorPickerListener { void onCancel(); void onOk(int color); } private AlertDialog dialog; private ParangColorPickerListener listener; private ParangColorPickerWidget ParangColorPickerWidget; public ParangColorPicker(Context context, Boolean IsPersian, ParangColorPickerListener Listener) { View mView = LayoutInflater.from(context).inflate(R.layout.color_picker_dialog_layout, null); ParangColorPickerWidget = (ParangColorPickerWidget) mView.findViewById(R.id.ColorPicker); ParangColorPickerWidget.PersianMode(IsPersian); this.listener = Listener; dialog = new AlertDialog.Builder(context).setView(mView).setPositiveButton(context.getString(R.string.OK), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { listener.onOk(ParangColorPickerWidget.getColor()); } }).setNegativeButton(context.getString(R.string.Cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { listener.onCancel(); } }).create(); } public void show(int InitColor) { ParangColorPickerWidget.setColor(InitColor); dialog.show(); } public void SetColor(int Color) { ParangColorPickerWidget.setColor(Color); } public void PersianMode(Boolean IsPersian) { ParangColorPickerWidget.PersianMode(IsPersian); } }
1,678
0.756853
0.755661
58
26.931034
31.437876
148
false
false
0
0
0
0
0
0
1.62069
false
false
4
b29ba6ba3953b2dab187d38e0ec662865d805bac
4,964,982,209,404
55b6a2b885d76b099b94f2d4ba884a5a3dbd1d7d
/app/src/main/java/com/qf/sxy/day36_design/ToolBar2Activity.java
6e60150a3e4a1b7039e256681af45aa8b6c0c11e
[]
no_license
mdjsxy111/Day36_Design
https://github.com/mdjsxy111/Day36_Design
799528d65e3b33d4c91d51d5041b94c12808d86e
f5752f80ff5108942024a9f95392f91a2884a1fd
refs/heads/master
2021-01-22T07:18:49.125000
2017-02-13T09:09:23
2017-02-13T09:09:23
81,805,637
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.qf.sxy.day36_design; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; public class ToolBar2Activity extends AppCompatActivity { private Toolbar toolbar; private DrawerLayout drawerLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tool_bar2); toolbar = ((Toolbar) findViewById(R.id.toolbar)); drawerLayout = ((DrawerLayout) findViewById(R.id.drawerLayout)); toolbar.setTitle("AAAAAAAAAAAAAAAA"); // setSupportActionBar(toolbar); //toolBar和Drawerlayout开关进行绑定 // getSupportActionBar().setDisplayHomeAsUpEnabled(true); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( ToolBar2Activity.this ,drawerLayout ,toolbar ,R.string.app_open ,R.string.app_close ); //ActionBarDrawerToggle与drawerLayout状态同步 toggle.syncState(); //drawerLayout绑定toggle drawerLayout.addDrawerListener(toggle); } }
UTF-8
Java
1,311
java
ToolBar2Activity.java
Java
[]
null
[]
package com.qf.sxy.day36_design; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; public class ToolBar2Activity extends AppCompatActivity { private Toolbar toolbar; private DrawerLayout drawerLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tool_bar2); toolbar = ((Toolbar) findViewById(R.id.toolbar)); drawerLayout = ((DrawerLayout) findViewById(R.id.drawerLayout)); toolbar.setTitle("AAAAAAAAAAAAAAAA"); // setSupportActionBar(toolbar); //toolBar和Drawerlayout开关进行绑定 // getSupportActionBar().setDisplayHomeAsUpEnabled(true); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( ToolBar2Activity.this ,drawerLayout ,toolbar ,R.string.app_open ,R.string.app_close ); //ActionBarDrawerToggle与drawerLayout状态同步 toggle.syncState(); //drawerLayout绑定toggle drawerLayout.addDrawerListener(toggle); } }
1,311
0.685113
0.678098
44
28.15909
22.472147
72
false
false
0
0
0
0
0
0
0.5
false
false
4
4ff4c1e64a73e8f59fcce80711af0b847816656f
26,877,905,391,695
3df2a0c02bfce5510cf0823355ee22886e6fdb58
/src/main/java/lesson8/task3/Terminal.java
05b8667b3c8673f60bbdd1c8bd5fd15f0df169f0
[]
no_license
IgorSamoilov/training-java-core
https://github.com/IgorSamoilov/training-java-core
87739b9d91c4975eef06b455b17d2aa592d40f67
68fe214541c6c5faa115936909ed12403df7ae97
refs/heads/master
2023-06-13T08:28:07.657000
2021-07-07T16:51:56
2021-07-07T16:51:56
359,341,149
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package lesson8.task3; public abstract class Terminal implements TopUpBalance { protected String terminalAddress; protected FirmOwner firmOwner; protected double commissions; protected double noCommissions; public Terminal(String terminalAddress) { this.terminalAddress = terminalAddress; } @Override public void pay(String phone, double amount) { double payment = amount >= noCommissions ? amount : (1d - commissions / 100) * amount; System.out.printf("Внесена сумма %.2f для пополнения телефона %s. Баланс пополнен на сумму %.2f. С уважением, ваш %s, %s%n", amount, phone, payment, firmOwner.getName(), terminalAddress); } }
UTF-8
Java
805
java
Terminal.java
Java
[]
null
[]
package lesson8.task3; public abstract class Terminal implements TopUpBalance { protected String terminalAddress; protected FirmOwner firmOwner; protected double commissions; protected double noCommissions; public Terminal(String terminalAddress) { this.terminalAddress = terminalAddress; } @Override public void pay(String phone, double amount) { double payment = amount >= noCommissions ? amount : (1d - commissions / 100) * amount; System.out.printf("Внесена сумма %.2f для пополнения телефона %s. Баланс пополнен на сумму %.2f. С уважением, ваш %s, %s%n", amount, phone, payment, firmOwner.getName(), terminalAddress); } }
805
0.665312
0.654472
21
34.142857
30.879622
132
false
false
0
0
0
0
0
0
0.761905
false
false
4
3689a238ef83f43057787c886fe67d3c5dada827
11,166,915,020,505
50d921566816872a246fb74732582d8c6adef90c
/hekate-core/src/main/java/io/hekate/cluster/ClusterHash.java
0b84fc36b766c76b21d03f89f65021fc48755748
[ "LicenseRef-scancode-free-unknown", "Apache-2.0", "BSD-3-Clause", "MIT", "LGPL-2.1-only", "LicenseRef-scancode-unknown-license-reference" ]
permissive
hekate-io/hekate
https://github.com/hekate-io/hekate
d33216bf802c00a8eb4a2729adc603d6cd7dcbd3
cf577c98e66cdcc9c10d582da006c22b0d8da8fa
refs/heads/master
2023-07-20T10:21:17.453000
2022-11-25T17:19:49
2022-11-25T17:19:49
84,603,051
24
4
Apache-2.0
false
2023-07-05T20:52:50
2017-03-10T21:43:25
2022-12-14T22:41:16
2023-07-05T20:52:50
7,348
18
2
2
Java
false
false
/* * Copyright 2022 The Hekate Project * * The Hekate Project licenses this file to you 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 io.hekate.cluster; /** * Cryptographic hash of the {@link ClusterTopology}. * * @see ClusterTopology#hash() */ public interface ClusterHash { /** * Returns a copy of the bytes of this hash. * * @return Bytes copy. */ byte[] bytes(); }
UTF-8
Java
912
java
ClusterHash.java
Java
[]
null
[]
/* * Copyright 2022 The Hekate Project * * The Hekate Project licenses this file to you 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 io.hekate.cluster; /** * Cryptographic hash of the {@link ClusterTopology}. * * @see ClusterTopology#hash() */ public interface ClusterHash { /** * Returns a copy of the bytes of this hash. * * @return Bytes copy. */ byte[] bytes(); }
912
0.702851
0.694079
31
28.419355
28.080271
78
false
false
0
0
0
0
0
0
0.225806
false
false
4
b74785ce4a3628c295951d62db2de8f6c8cc6e06
15,771,119,975,793
1b308e540c445cf8f82a94670ed9ba1379b15b21
/compositions/com/oi/ds/stack/AppStack.java
61c1211360c733eb679f9f33c54b78755f6bdcc1
[]
no_license
ogorifuwe/ds-and-algorithms
https://github.com/ogorifuwe/ds-and-algorithms
aa1e7f556148e4bd297d9f520db4e130b87c4262
e12808ab4b3e3cda76ee9cac9e22f892f66ed159
refs/heads/master
2022-05-26T06:34:22.592000
2022-04-06T14:49:55
2022-04-06T14:49:55
153,824,489
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.oi.ds.stack; public class AppStack { public static void main(String[] args) { StackNode<String> names = new StackNode<>(); names.push("Paulie"); names.push("Peter"); names.push("Paul"); names.push("Michael"); while(!names.isEmpty()){ System.out.println(names.pop()); } StackArray<Integer> numbers = new StackArray<>(); numbers.push(1); numbers.push(2); numbers.push(3); numbers.push(4); numbers.push(5); numbers.push(6); Integer top = numbers.peek(); System.out.println(top); Integer removedTop = numbers.pop(); System.out.println(removedTop); Integer newTop = numbers.peek(); System.out.println(newTop); String expr = "( ( 1 + 2 ) * ( 2 + 1 ) )"; DijkstraInterpreter dijkstraInterpreter = new DijkstraInterpreter(); dijkstraInterpreter.interpretExpression(expr); dijkstraInterpreter.displayResult(); } }
UTF-8
Java
945
java
AppStack.java
Java
[ { "context": "tring> names = new StackNode<>();\n names.push(\"Paulie\");\n names.push(\"Peter\");\n names.push(\"Paul\"", "end": 170, "score": 0.9997138381004333, "start": 164, "tag": "NAME", "value": "Paulie" }, { "context": "de<>();\n names.push(\"Paulie\");\n names.push(\"Peter\");\n names.push(\"Paul\");\n names.push(\"Michae", "end": 195, "score": 0.9996833205223083, "start": 190, "tag": "NAME", "value": "Peter" }, { "context": "aulie\");\n names.push(\"Peter\");\n names.push(\"Paul\");\n names.push(\"Michael\");\n\n while(!names.i", "end": 219, "score": 0.9996556043624878, "start": 215, "tag": "NAME", "value": "Paul" }, { "context": "\"Peter\");\n names.push(\"Paul\");\n names.push(\"Michael\");\n\n while(!names.isEmpty()){\n System.out", "end": 246, "score": 0.9998236298561096, "start": 239, "tag": "NAME", "value": "Michael" } ]
null
[]
package com.oi.ds.stack; public class AppStack { public static void main(String[] args) { StackNode<String> names = new StackNode<>(); names.push("Paulie"); names.push("Peter"); names.push("Paul"); names.push("Michael"); while(!names.isEmpty()){ System.out.println(names.pop()); } StackArray<Integer> numbers = new StackArray<>(); numbers.push(1); numbers.push(2); numbers.push(3); numbers.push(4); numbers.push(5); numbers.push(6); Integer top = numbers.peek(); System.out.println(top); Integer removedTop = numbers.pop(); System.out.println(removedTop); Integer newTop = numbers.peek(); System.out.println(newTop); String expr = "( ( 1 + 2 ) * ( 2 + 1 ) )"; DijkstraInterpreter dijkstraInterpreter = new DijkstraInterpreter(); dijkstraInterpreter.interpretExpression(expr); dijkstraInterpreter.displayResult(); } }
945
0.62963
0.619048
43
20.976744
16.903954
53
false
false
0
0
0
0
0
0
0.55814
false
false
9
1f7cd3ca8a91a1ef105a8593669808ce61d44347
18,202,071,457,582
6cd0d649c553b977de2567759c19c441cdf61a19
/src/elementLocators/GmailLogin.java
d3237024927a428a4737addc15d5b685e8b5c4ae
[]
no_license
Manju80/Automation
https://github.com/Manju80/Automation
eb32cebadbf085506fb06c46c7d36b82751368ca
9fc3dc2c0588f2fb72ce370a4bf52b13242c521c
refs/heads/master
2020-12-04T18:30:05.323000
2020-01-11T04:53:01
2020-01-11T04:53:01
231,867,957
0
0
null
false
2020-01-11T04:53:02
2020-01-05T04:39:22
2020-01-05T04:44:37
2020-01-11T04:53:02
19,741
0
0
0
Java
false
false
package elementLocators; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class GmailLogin { public static void main(String[] args) throws InterruptedException { System.setProperty("webdriver.gecko.driver","./Drivers/geckodriver.exe"); //System.setProperty("webdriver.chrome.driver", "./Drivers/chromedriver.exe"); WebDriver driver=new FirefoxDriver(); driver.get("https://www.gmail.com"); driver.manage().window().maximize(); driver.findElement(By.cssSelector("Input[Type='email']")).sendKeys("manju.preva@gmail.com"); driver.findElement(By.cssSelector("span[class='RveJvd snByac']")).click(); Thread.sleep(2000); driver.findElement(By.cssSelector("Input[Type='password']")).sendKeys("Chintamani!123#"); driver.findElement(By.cssSelector("span[class='RveJvd snByac']")).click(); Thread.sleep(3000); driver.close(); } }
UTF-8
Java
997
java
GmailLogin.java
Java
[ { "context": "(By.cssSelector(\"Input[Type='email']\")).sendKeys(\"manju.preva@gmail.com\");\n\t\tdriver.findElement(By.cssSelector(\"span[clas", "end": 673, "score": 0.9999171495437622, "start": 652, "tag": "EMAIL", "value": "manju.preva@gmail.com" }, { "context": ".cssSelector(\"Input[Type='password']\")).sendKeys(\"Chintamani!123#\");\n\t\tdriver.findElement(By.cssSelector(\"span[clas", "end": 863, "score": 0.9986670613288879, "start": 849, "tag": "PASSWORD", "value": "Chintamani!123" } ]
null
[]
package elementLocators; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class GmailLogin { public static void main(String[] args) throws InterruptedException { System.setProperty("webdriver.gecko.driver","./Drivers/geckodriver.exe"); //System.setProperty("webdriver.chrome.driver", "./Drivers/chromedriver.exe"); WebDriver driver=new FirefoxDriver(); driver.get("https://www.gmail.com"); driver.manage().window().maximize(); driver.findElement(By.cssSelector("Input[Type='email']")).sendKeys("<EMAIL>"); driver.findElement(By.cssSelector("span[class='RveJvd snByac']")).click(); Thread.sleep(2000); driver.findElement(By.cssSelector("Input[Type='password']")).sendKeys("<PASSWORD>#"); driver.findElement(By.cssSelector("span[class='RveJvd snByac']")).click(); Thread.sleep(3000); driver.close(); } }
979
0.7332
0.722166
33
29.181818
30.464539
94
false
false
0
0
0
0
0
0
1.787879
false
false
9
8ae5757bca490c98963e15bb949fa868808a6ca7
23,871,428,300,030
b386aa5676319b12523dab56fa68b027fb9f30f3
/Linguaggi per il cloud/src/funzioni/dado.java
bf3828cf50510e1e0358d1cd89701fd60336aafa
[]
no_license
mmorritti/ITS_Java
https://github.com/mmorritti/ITS_Java
dca3dc1fec1077e2caec4e3136934ccba79a7b9f
2a7482e612fd65cd53f7b148488809d05171b72b
refs/heads/master
2022-11-13T00:50:02.672000
2020-07-04T08:50:22
2020-07-04T08:50:22
276,847,989
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package funzioni; public class dado { private int facce; public dado(int facce) { super(); this.facce = facce; } public int getFacce() { return facce; } public void setFacce(int facce) { this.facce = facce; } public int lancio() { return MyLibrary.casuale(1, facce); } @Override public String toString() { return "dado [facce=" + facce + ", lancio()=" + lancio() + "]"; } }
UTF-8
Java
410
java
dado.java
Java
[]
null
[]
package funzioni; public class dado { private int facce; public dado(int facce) { super(); this.facce = facce; } public int getFacce() { return facce; } public void setFacce(int facce) { this.facce = facce; } public int lancio() { return MyLibrary.casuale(1, facce); } @Override public String toString() { return "dado [facce=" + facce + ", lancio()=" + lancio() + "]"; } }
410
0.617073
0.614634
30
12.666667
14.938392
65
false
false
0
0
0
0
0
0
1.233333
false
false
9
d550ef10d640e4f95cd5bd3759dadbc559d5f5d6
29,850,022,762,864
19d6ef751ce5cd9cc23df0d48d974d714371bc43
/src/main/java/com/reckue/post/transfer/PostRequest.java
82bb54fa6519c1bef6e59a71970d5eb3d908fd9c
[ "MIT" ]
permissive
Reckue/post-service
https://github.com/Reckue/post-service
4c95767eb18e02fe56dc0fb72c54515043e34e31
974202525fb467f049add5ecd736940edc62f44f
refs/heads/develop
2023-04-10T22:17:43.460000
2021-02-23T10:11:28
2021-02-23T10:11:28
250,591,338
0
0
MIT
false
2021-02-23T10:11:29
2020-03-27T16:53:53
2021-02-23T08:54:13
2021-02-23T10:11:28
1,142
10
10
41
Java
false
false
package com.reckue.post.transfer; import com.reckue.post.model.Tag; import com.reckue.post.model.type.PostStatusType; import io.swagger.annotations.ApiModelProperty; import lombok.Builder; import lombok.Data; import javax.validation.Valid; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.util.List; /** * Class PostRequest represents an incoming DTO for adding a post. * * @author Kamila Meshcheryakova */ @Builder @Data public class PostRequest { @NotNull @ApiModelProperty(notes = "Post title") private String title; @ApiModelProperty(notes = "List of nodes the post consists of") @Valid private List<NodeRequest> nodes; @Size(max = 128) @ApiModelProperty(notes = "The source used to write the post") private String source; @ApiModelProperty(notes = "List of keywords used in the post") private List<Tag> tags; @ApiModelProperty(notes = "Post activity status") private PostStatusType status; }
UTF-8
Java
1,011
java
PostRequest.java
Java
[ { "context": "s an incoming DTO for adding a post.\n *\n * @author Kamila Meshcheryakova\n */\n@Builder\n@Data\npublic class PostRequest {\n\n ", "end": 459, "score": 0.9998301863670349, "start": 438, "tag": "NAME", "value": "Kamila Meshcheryakova" } ]
null
[]
package com.reckue.post.transfer; import com.reckue.post.model.Tag; import com.reckue.post.model.type.PostStatusType; import io.swagger.annotations.ApiModelProperty; import lombok.Builder; import lombok.Data; import javax.validation.Valid; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.util.List; /** * Class PostRequest represents an incoming DTO for adding a post. * * @author <NAME> */ @Builder @Data public class PostRequest { @NotNull @ApiModelProperty(notes = "Post title") private String title; @ApiModelProperty(notes = "List of nodes the post consists of") @Valid private List<NodeRequest> nodes; @Size(max = 128) @ApiModelProperty(notes = "The source used to write the post") private String source; @ApiModelProperty(notes = "List of keywords used in the post") private List<Tag> tags; @ApiModelProperty(notes = "Post activity status") private PostStatusType status; }
996
0.74184
0.738872
40
24.275
21.340088
67
false
false
0
0
0
0
0
0
0.375
false
false
9
71aea25fb1ffd7aaaef457a2788d020a11a6c605
27,169,963,134,915
6b88f04560744d66a074aeafbd189f4196d1547d
/src/test/java/org/govithub/govac/consumerapi/controller/UsersControllerTest.java
9899f672d090b95b5b1637493a1b392fb03f460e
[ "Apache-2.0" ]
permissive
cozu/asistentul_cetateanului_api_intern
https://github.com/cozu/asistentul_cetateanului_api_intern
31fd4cc3a64d381171713c6d33c535ae449a93a9
3b29af50e9388b27f76c3c96de962cf94c5aa288
refs/heads/master
2020-12-24T06:16:48.142000
2016-12-05T14:18:09
2016-12-05T14:18:09
73,481,121
0
0
null
true
2016-11-11T13:46:43
2016-11-11T13:46:42
2016-10-30T06:14:03
2016-10-30T06:14:24
9
0
0
0
null
null
null
package org.govithub.govac.consumerapi.controller; import static io.restassured.RestAssured.given; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertEquals; import java.io.IOException; import org.apache.http.HttpStatus; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import org.govithub.govac.dao.model.User; import org.govithub.govac.dao.repository.NotificationRepository; import org.govithub.govac.dao.repository.UserRepository; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import io.restassured.RestAssured; import io.restassured.http.ContentType; @ContextConfiguration(locations = {"classpath:test-context.xml"}) @RunWith(SpringJUnit4ClassRunner.class) @TestPropertySource(locations="classpath:test.properties") @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class UsersControllerTest { @Autowired public UserRepository userRepository; @Autowired public NotificationRepository notificationsRepository; private User user; @Value("${local.server.port}") int port; private ObjectMapper objectMapper = new ObjectMapper(); @Before public void setup() { RestAssured.port = port; cleanUp(); user = userRepository.save(new User("user1FN", "user1LN", "user1@email.com", "123456", "1231231231122")); userRepository.save(new User("user2FN", "user2LN", "user2@email.com", "345678", "2345677654433")); } @After public void cleanUp(){ notificationsRepository.deleteAll(); userRepository.deleteAll(); } @Test public void shouldUpdateUser() throws JsonGenerationException, JsonMappingException, IOException { given(). contentType(ContentType.JSON). body(objectMapper.writeValueAsString(new User("userFN-updated", "userLN-updated", "updated@email.com", "111222", "111222"))). when(). post("/users/{id}", user.id). then(). statusCode(HttpStatus.SC_OK). body("firstName", is("userFN-updated")). body("lastName", is("userLN-updated")). body("email", is("updated@email.com")). body("phone", is("111222")). body("cnp", is("111222")); User u = userRepository.findOne(user.id); assertEquals("updated@email.com", u.email); assertEquals("111222", u.phone); } }
UTF-8
Java
2,802
java
UsersControllerTest.java
Java
[ { "context": "cleanUp();\n\t\tuser = userRepository.save(new User(\"user1FN\", \"user1LN\", \"user1@email.com\", \"123456\", \"123123", "end": 1778, "score": 0.9623966813087463, "start": 1771, "tag": "USERNAME", "value": "user1FN" }, { "context": "\t\tuser = userRepository.save(new User(\"user1FN\", \"user1LN\", \"user1@email.com\", \"123456\", \"1231231231122\"));", "end": 1789, "score": 0.9563238620758057, "start": 1782, "tag": "USERNAME", "value": "user1LN" }, { "context": "erRepository.save(new User(\"user1FN\", \"user1LN\", \"user1@email.com\", \"123456\", \"1231231231122\"));\n\t\tuserRepository.s", "end": 1808, "score": 0.9998390674591064, "start": 1793, "tag": "EMAIL", "value": "user1@email.com" }, { "context": "1231231231122\"));\n\t\tuserRepository.save(new User(\"user2FN\", \"user2LN\", \"user2@email.com\", \"345678\", \"234567", "end": 1879, "score": 0.9985089302062988, "start": 1872, "tag": "USERNAME", "value": "user2FN" }, { "context": "22\"));\n\t\tuserRepository.save(new User(\"user2FN\", \"user2LN\", \"user2@email.com\", \"345678\", \"2345677654433\"));", "end": 1890, "score": 0.9988215565681458, "start": 1883, "tag": "USERNAME", "value": "user2LN" }, { "context": "erRepository.save(new User(\"user2FN\", \"user2LN\", \"user2@email.com\", \"345678\", \"2345677654433\"));\t\t\n\t}\n\t\n\t@After\n\tpu", "end": 1909, "score": 0.9999234080314636, "start": 1894, "tag": "EMAIL", "value": "user2@email.com" }, { "context": "ing(new User(\"userFN-updated\", \"userLN-updated\", \"updated@email.com\", \"111222\", \"111222\"))).\n\t\twhen().\n \tpost(", "end": 2310, "score": 0.9999205470085144, "start": 2293, "tag": "EMAIL", "value": "updated@email.com" }, { "context": "is(\"userLN-updated\")).\n \tbody(\"email\", is(\"updated@email.com\")).\n \tbody(\"phone\", is(\"111222\")).\n ", "end": 2583, "score": 0.9999228715896606, "start": 2566, "tag": "EMAIL", "value": "updated@email.com" }, { "context": " userRepository.findOne(user.id);\n\t\tassertEquals(\"updated@email.com\", u.email);\n\t\tassertEquals(\"111222\", u.phone);\n\t}", "end": 2749, "score": 0.9999223947525024, "start": 2732, "tag": "EMAIL", "value": "updated@email.com" } ]
null
[]
package org.govithub.govac.consumerapi.controller; import static io.restassured.RestAssured.given; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertEquals; import java.io.IOException; import org.apache.http.HttpStatus; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import org.govithub.govac.dao.model.User; import org.govithub.govac.dao.repository.NotificationRepository; import org.govithub.govac.dao.repository.UserRepository; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import io.restassured.RestAssured; import io.restassured.http.ContentType; @ContextConfiguration(locations = {"classpath:test-context.xml"}) @RunWith(SpringJUnit4ClassRunner.class) @TestPropertySource(locations="classpath:test.properties") @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class UsersControllerTest { @Autowired public UserRepository userRepository; @Autowired public NotificationRepository notificationsRepository; private User user; @Value("${local.server.port}") int port; private ObjectMapper objectMapper = new ObjectMapper(); @Before public void setup() { RestAssured.port = port; cleanUp(); user = userRepository.save(new User("user1FN", "user1LN", "<EMAIL>", "123456", "1231231231122")); userRepository.save(new User("user2FN", "user2LN", "<EMAIL>", "345678", "2345677654433")); } @After public void cleanUp(){ notificationsRepository.deleteAll(); userRepository.deleteAll(); } @Test public void shouldUpdateUser() throws JsonGenerationException, JsonMappingException, IOException { given(). contentType(ContentType.JSON). body(objectMapper.writeValueAsString(new User("userFN-updated", "userLN-updated", "<EMAIL>", "111222", "111222"))). when(). post("/users/{id}", user.id). then(). statusCode(HttpStatus.SC_OK). body("firstName", is("userFN-updated")). body("lastName", is("userLN-updated")). body("email", is("<EMAIL>")). body("phone", is("111222")). body("cnp", is("111222")); User u = userRepository.findOne(user.id); assertEquals("<EMAIL>", u.email); assertEquals("111222", u.phone); } }
2,756
0.75803
0.73055
83
32.759037
27.507542
128
false
false
0
0
0
0
0
0
1.46988
false
false
9
b4d8f7f4608c755e4d70bbb021c06acb908aed3d
13,580,686,653,902
97eac5a858373e7beb191f7426cebf4886c78d2a
/managesystem2.0/src/log/Register.java
3adedc47f5f9f89bb24f5ac62ae5d9ff660e37fe
[]
no_license
Fxk2020/JavaProjection
https://github.com/Fxk2020/JavaProjection
756f013b7a3cb1a2362c87fbbf16722aa321342b
b3188b0c5ad04ad804573da3158a01ddf1db88c0
refs/heads/master
2022-08-18T13:02:29.019000
2020-05-25T04:13:15
2020-05-25T04:14:06
263,352,043
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package log; import javax.swing.*; //import com.microsoft.sqlserver.jdbc.SQLServerException; import common.MessageType; import common.Users; import model.ConServer; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class Register extends JPanel { final int W = 450; final int H = 240; JFrame this1 = new JFrame(); JTextField f1 = new JTextField(25);// 真实姓名 JPasswordField f2 = new JPasswordField(25);// 密码 JPasswordField f3 = new JPasswordField(25);// 二次密码 JTextField fie1 = new JTextField(25);// 学号 JTextField fie2 = new JTextField(25);// 昵称 public Register() { //this1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// this1.setSize(W, H); this1.setVisible(true); this1.setTitle("用户注册"); this1.addWindowListener(new WindowAdapter() {// 匿名类 public void windowClosing(WindowEvent e) { this1.setVisible(false); } }); Toolkit kit = Toolkit.getDefaultToolkit(); Dimension size = kit.getScreenSize(); // 获得屏幕的分辨率大小 double w = size.getWidth(); double h = size.getHeight(); int x = (int) ((w - W) / 2); int y = (int) ((h - H) / 2); this1.setLocation(x, y);// 使窗口位于屏幕的中央 Font font2 = new Font("宋体", Font.PLAIN, 18); JLabel l1 = new JLabel("姓名"); JLabel bel1 = new JLabel("学号"); JLabel bel2 = new JLabel("昵称");// 添加到数据库的user JLabel l2 = new JLabel("密码"); JLabel l3 = new JLabel("确认密码"); l1.setFont(font2); l2.setFont(font2); l3.setFont(font2); bel1.setFont(font2); bel2.setFont(font2); l1.setForeground(new Color(0,0,0)); l2.setForeground(new Color(0,0,0)); l3.setForeground(new Color(0,0,0)); bel1.setForeground(new Color(0,0,0)); bel2.setForeground(new Color(0,0,0)); GridBagLayout lay = new GridBagLayout();// gridbaglayout布局管理器 this.setLayout(lay); JLabel label1 = new JLabel("学生注册"); Font font = new Font("宋体", Font.PLAIN, 25);// 创建1个字体实例 label1.setFont(font); // 设置JLabel的字体 label1.setForeground(new Color(255, 100, 89));// 设置文字的颜色 JButton b1 = new JButton("确认"); b1.setBackground(new Color(30, 144, 255)); b1.setForeground(Color.white); B1listener listener1 = new B1listener(); b1.addActionListener(listener1); GridBagConstraints con = new GridBagConstraints(); con.fill = GridBagConstraints.BOTH; con.anchor = GridBagConstraints.NORTH; this.add(label1, con, 1, 0, 1, 1); this.add(l1, con, 0, 1, 1, 1); this.add(bel1, con, 0, 2, 1, 1); this.add(bel2, con, 0, 3, 1, 1); this.add(l2, con, 0, 4, 1, 1); this.add(l3, con, 0, 5, 1, 1); this.add(f1, con, 1, 1, 2, 1); this.add(fie1, con, 1, 2, 2, 1); this.add(fie2, con, 1, 3, 2, 1); this.add(f2, con, 1, 4, 2, 1); this.add(f3, con, 1, 5, 2, 1); this.add(b1, con, 2, 7, 0, 0); ImageIcon backGroundIma = new ImageIcon("imag/图片1.jpg"); // 在Java项目下放图片 JLabel backGroundPic = new JLabel(backGroundIma); // 设置一个标签将图片加在标签上 backGroundPic.setBounds(0, 0, 450, 240); // 参数X,Y,W,H大小必须超过JFrame的大小否则图片不会覆盖窗体 this1.getLayeredPane().add(backGroundPic, new Integer(Integer.MIN_VALUE)); ((JPanel) this1.getContentPane()).setOpaque(false); this.setOpaque(false); // 将面板设为透明SETOpaque()方法 this1.setResizable(false);// 使用户不能调节窗口的大小 this1.setContentPane(this); } public void add(Component c, GridBagConstraints grid, int x, int y, int w, int h) { grid.gridx = x; grid.gridy = y; grid.gridwidth = w; grid.gridheight = h; add(c, grid); } private class B1listener implements ActionListener { public void actionPerformed(ActionEvent arg0) { String name = f1.getText();//真实姓名 String number = fie1.getText();//学号 String user = fie2.getText();// 昵称 String pass1 =String.valueOf( f2.getPassword());//密码 String pass2 =String.valueOf( f3.getPassword()); if ((!f1.getText().equals("")) && (!fie1.getText().equals("")) && (!fie2.getText().equals(""))) {// 当三个位置中有一个是空的就不执行下列语句) if(pass1.equals(pass2)) { Users u = new Users(); u.setId(number); u.setName(name); u.setvName(user); u.setPassword(pass1); u.setDosomething("6"); ConServer cs = new ConServer(); cs.sendInformationLogin(u); } else { JOptionPane.showMessageDialog(null, "两次输入的密码不一致", "请重新输入",JOptionPane.ERROR_MESSAGE); }} else { JOptionPane.showMessageDialog(null, "有的输入是空的", "请继续输入", JOptionPane.ERROR_MESSAGE); } } } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { // 匿名内部类,重写了run方法 public void run() { new Register(); } }); } }
GB18030
Java
5,188
java
Register.java
Java
[ { "context": "u = new Users();\n\t\t\tu.setId(number);\n\t\t\tu.setName(name);\n\t\t\tu.setvName(user);\n\t\t\tu.setPassword(pass1);\n\t", "end": 4152, "score": 0.8647176623344421, "start": 4148, "tag": "NAME", "value": "name" }, { "context": ".setId(number);\n\t\t\tu.setName(name);\n\t\t\tu.setvName(user);\n\t\t\tu.setPassword(pass1);\n\t\t\tu.setDosomething(\"6", "end": 4173, "score": 0.5536289811134338, "start": 4169, "tag": "NAME", "value": "user" }, { "context": "Name(name);\n\t\t\tu.setvName(user);\n\t\t\tu.setPassword(pass1);\n\t\t\tu.setDosomething(\"6\");\n\t\t\t\n\t\t\tConServer cs =", "end": 4198, "score": 0.9989334344863892, "start": 4193, "tag": "PASSWORD", "value": "pass1" } ]
null
[]
package log; import javax.swing.*; //import com.microsoft.sqlserver.jdbc.SQLServerException; import common.MessageType; import common.Users; import model.ConServer; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class Register extends JPanel { final int W = 450; final int H = 240; JFrame this1 = new JFrame(); JTextField f1 = new JTextField(25);// 真实姓名 JPasswordField f2 = new JPasswordField(25);// 密码 JPasswordField f3 = new JPasswordField(25);// 二次密码 JTextField fie1 = new JTextField(25);// 学号 JTextField fie2 = new JTextField(25);// 昵称 public Register() { //this1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// this1.setSize(W, H); this1.setVisible(true); this1.setTitle("用户注册"); this1.addWindowListener(new WindowAdapter() {// 匿名类 public void windowClosing(WindowEvent e) { this1.setVisible(false); } }); Toolkit kit = Toolkit.getDefaultToolkit(); Dimension size = kit.getScreenSize(); // 获得屏幕的分辨率大小 double w = size.getWidth(); double h = size.getHeight(); int x = (int) ((w - W) / 2); int y = (int) ((h - H) / 2); this1.setLocation(x, y);// 使窗口位于屏幕的中央 Font font2 = new Font("宋体", Font.PLAIN, 18); JLabel l1 = new JLabel("姓名"); JLabel bel1 = new JLabel("学号"); JLabel bel2 = new JLabel("昵称");// 添加到数据库的user JLabel l2 = new JLabel("密码"); JLabel l3 = new JLabel("确认密码"); l1.setFont(font2); l2.setFont(font2); l3.setFont(font2); bel1.setFont(font2); bel2.setFont(font2); l1.setForeground(new Color(0,0,0)); l2.setForeground(new Color(0,0,0)); l3.setForeground(new Color(0,0,0)); bel1.setForeground(new Color(0,0,0)); bel2.setForeground(new Color(0,0,0)); GridBagLayout lay = new GridBagLayout();// gridbaglayout布局管理器 this.setLayout(lay); JLabel label1 = new JLabel("学生注册"); Font font = new Font("宋体", Font.PLAIN, 25);// 创建1个字体实例 label1.setFont(font); // 设置JLabel的字体 label1.setForeground(new Color(255, 100, 89));// 设置文字的颜色 JButton b1 = new JButton("确认"); b1.setBackground(new Color(30, 144, 255)); b1.setForeground(Color.white); B1listener listener1 = new B1listener(); b1.addActionListener(listener1); GridBagConstraints con = new GridBagConstraints(); con.fill = GridBagConstraints.BOTH; con.anchor = GridBagConstraints.NORTH; this.add(label1, con, 1, 0, 1, 1); this.add(l1, con, 0, 1, 1, 1); this.add(bel1, con, 0, 2, 1, 1); this.add(bel2, con, 0, 3, 1, 1); this.add(l2, con, 0, 4, 1, 1); this.add(l3, con, 0, 5, 1, 1); this.add(f1, con, 1, 1, 2, 1); this.add(fie1, con, 1, 2, 2, 1); this.add(fie2, con, 1, 3, 2, 1); this.add(f2, con, 1, 4, 2, 1); this.add(f3, con, 1, 5, 2, 1); this.add(b1, con, 2, 7, 0, 0); ImageIcon backGroundIma = new ImageIcon("imag/图片1.jpg"); // 在Java项目下放图片 JLabel backGroundPic = new JLabel(backGroundIma); // 设置一个标签将图片加在标签上 backGroundPic.setBounds(0, 0, 450, 240); // 参数X,Y,W,H大小必须超过JFrame的大小否则图片不会覆盖窗体 this1.getLayeredPane().add(backGroundPic, new Integer(Integer.MIN_VALUE)); ((JPanel) this1.getContentPane()).setOpaque(false); this.setOpaque(false); // 将面板设为透明SETOpaque()方法 this1.setResizable(false);// 使用户不能调节窗口的大小 this1.setContentPane(this); } public void add(Component c, GridBagConstraints grid, int x, int y, int w, int h) { grid.gridx = x; grid.gridy = y; grid.gridwidth = w; grid.gridheight = h; add(c, grid); } private class B1listener implements ActionListener { public void actionPerformed(ActionEvent arg0) { String name = f1.getText();//真实姓名 String number = fie1.getText();//学号 String user = fie2.getText();// 昵称 String pass1 =String.valueOf( f2.getPassword());//密码 String pass2 =String.valueOf( f3.getPassword()); if ((!f1.getText().equals("")) && (!fie1.getText().equals("")) && (!fie2.getText().equals(""))) {// 当三个位置中有一个是空的就不执行下列语句) if(pass1.equals(pass2)) { Users u = new Users(); u.setId(number); u.setName(name); u.setvName(user); u.setPassword(<PASSWORD>); u.setDosomething("6"); ConServer cs = new ConServer(); cs.sendInformationLogin(u); } else { JOptionPane.showMessageDialog(null, "两次输入的密码不一致", "请重新输入",JOptionPane.ERROR_MESSAGE); }} else { JOptionPane.showMessageDialog(null, "有的输入是空的", "请继续输入", JOptionPane.ERROR_MESSAGE); } } } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { // 匿名内部类,重写了run方法 public void run() { new Register(); } }); } }
5,193
0.67083
0.631033
167
27.27545
22.160995
124
false
false
0
0
0
0
0
0
2.802395
false
false
9
a0bee47dd0d6565c4a516da693d79cc73bf1761f
15,547,781,664,860
bfc8cd3112e3625870c61e71db71794e645712f0
/app/src/main/java/com/shiyculture/coupon/MainActivity.java
8bceb641288e99a3999e900c9c5e47f7e9c1197c
[]
no_license
ThinkmanWang/coupon-android
https://github.com/ThinkmanWang/coupon-android
2fcc471d6f86fa386248c4bb3c8edc77e4baa43e
097f52aa4c686088a48450dea74211764ef47656
refs/heads/master
2020-09-05T20:22:23.856000
2019-11-07T09:53:31
2019-11-07T09:53:31
220,203,979
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.shiyculture.coupon; import android.Manifest; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.webkit.WebSettings; import com.tbruyelle.rxpermissions2.RxPermissions; import com.tencent.smtt.sdk.WebChromeClient; import com.tencent.smtt.sdk.WebView; import com.tencent.smtt.sdk.WebViewClient; import com.vondear.rxtool.RxDeviceTool; import butterknife.BindView; import butterknife.ButterKnife; public class MainActivity extends AppCompatActivity { final RxPermissions rxPermissions = new RxPermissions(this); @BindView(R.id.main_webview) WebView m_wvMain; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); initUI(); } public void onBackPressed() { if (m_wvMain.canGoBack()) { m_wvMain.goBack(); } else { super.onBackPressed(); } } public void initUI() { rxPermissions.request(Manifest.permission.READ_PHONE_STATE , Manifest.permission.WRITE_EXTERNAL_STORAGE , Manifest.permission.ACCESS_NETWORK_STATE , Manifest.permission.ACCESS_WIFI_STATE) .subscribe(granted -> { if (granted) { initWebView(); } else { } }); } public void initWebView() { m_wvMain.getSettings().setJavaScriptEnabled(true); m_wvMain.getSettings().setSupportZoom(true); //支持缩放,默认为true。是下面那个的前提。 m_wvMain.getSettings().setBuiltInZoomControls(true); //设置内置的缩放控件。若为false,则该WebView不可缩放 m_wvMain.getSettings().setDisplayZoomControls(true); //隐藏原生的缩放控件 m_wvMain.getSettings().setBlockNetworkImage(false);//解决图片不显示 m_wvMain.getSettings().setLoadsImagesAutomatically(true); //支持自动加载图片 m_wvMain.getSettings().setDefaultTextEncodingName("utf-8");//设置编码格式 m_wvMain.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW); String szIMEI = RxDeviceTool.getIMEI(MainActivity.this); String szUrl = String.format("https://coupon.shiyculture.com/?user_id=%s&app_key=609d544b98d347a5bcc17637c529b95a&app_secret=609d544b98d347a5bcc17637c529b95a&allow_buy=1", szIMEI); m_wvMain.loadUrl(szUrl); m_wvMain.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView webView, String s) { webView.loadUrl(s); return true; } }); m_wvMain.setWebChromeClient(new WebChromeClient() { @Override public void onProgressChanged(WebView webView, int i) { // if (i < 100 && MainTaskFragment.this.isVisible()) { // tvTaskProgress.setVisibility(View.VISIBLE); // webView.setVisibility(View.GONE); // } else { // if (MainTaskFragment.this.isVisible()) { // tvTaskProgress.setVisibility(View.GONE); // webView.setVisibility(View.VISIBLE); // } // } } }); } }
UTF-8
Java
3,473
java
MainActivity.java
Java
[ { "context": "ttps://coupon.shiyculture.com/?user_id=%s&app_key=609d544b98d347a5bcc17637c529b95a&app_secret=609d544b98d347a5bcc17637c529b95a&allow", "end": 2344, "score": 0.9997358918190002, "start": 2312, "tag": "KEY", "value": "609d544b98d347a5bcc17637c529b95a" }, { "context": "p_key=609d544b98d347a5bcc17637c529b95a&app_secret=609d544b98d347a5bcc17637c529b95a&allow_buy=1\", szIMEI);\n\n m_wvMain.loadUrl(", "end": 2388, "score": 0.9997379779815674, "start": 2356, "tag": "KEY", "value": "609d544b98d347a5bcc17637c529b95a" }, { "context": "secret=609d544b98d347a5bcc17637c529b95a&allow_buy=1\", szIMEI);\n\n m_wvMain.loadUrl(szUrl);\n\n ", "end": 2400, "score": 0.6876307129859924, "start": 2399, "tag": "KEY", "value": "1" } ]
null
[]
package com.shiyculture.coupon; import android.Manifest; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.webkit.WebSettings; import com.tbruyelle.rxpermissions2.RxPermissions; import com.tencent.smtt.sdk.WebChromeClient; import com.tencent.smtt.sdk.WebView; import com.tencent.smtt.sdk.WebViewClient; import com.vondear.rxtool.RxDeviceTool; import butterknife.BindView; import butterknife.ButterKnife; public class MainActivity extends AppCompatActivity { final RxPermissions rxPermissions = new RxPermissions(this); @BindView(R.id.main_webview) WebView m_wvMain; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); initUI(); } public void onBackPressed() { if (m_wvMain.canGoBack()) { m_wvMain.goBack(); } else { super.onBackPressed(); } } public void initUI() { rxPermissions.request(Manifest.permission.READ_PHONE_STATE , Manifest.permission.WRITE_EXTERNAL_STORAGE , Manifest.permission.ACCESS_NETWORK_STATE , Manifest.permission.ACCESS_WIFI_STATE) .subscribe(granted -> { if (granted) { initWebView(); } else { } }); } public void initWebView() { m_wvMain.getSettings().setJavaScriptEnabled(true); m_wvMain.getSettings().setSupportZoom(true); //支持缩放,默认为true。是下面那个的前提。 m_wvMain.getSettings().setBuiltInZoomControls(true); //设置内置的缩放控件。若为false,则该WebView不可缩放 m_wvMain.getSettings().setDisplayZoomControls(true); //隐藏原生的缩放控件 m_wvMain.getSettings().setBlockNetworkImage(false);//解决图片不显示 m_wvMain.getSettings().setLoadsImagesAutomatically(true); //支持自动加载图片 m_wvMain.getSettings().setDefaultTextEncodingName("utf-8");//设置编码格式 m_wvMain.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW); String szIMEI = RxDeviceTool.getIMEI(MainActivity.this); String szUrl = String.format("https://coupon.shiyculture.com/?user_id=%s&app_key=<KEY>&app_secret=<KEY>&allow_buy=1", szIMEI); m_wvMain.loadUrl(szUrl); m_wvMain.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView webView, String s) { webView.loadUrl(s); return true; } }); m_wvMain.setWebChromeClient(new WebChromeClient() { @Override public void onProgressChanged(WebView webView, int i) { // if (i < 100 && MainTaskFragment.this.isVisible()) { // tvTaskProgress.setVisibility(View.VISIBLE); // webView.setVisibility(View.GONE); // } else { // if (MainTaskFragment.this.isVisible()) { // tvTaskProgress.setVisibility(View.GONE); // webView.setVisibility(View.VISIBLE); // } // } } }); } }
3,419
0.624139
0.608865
95
34.147369
29.805676
188
false
false
0
0
0
0
0
0
0.505263
false
false
9
060fcd6a2716c46c2748e47f21d8636ea70b091e
13,520,557,077,820
c5b909a17cd722056fcd6d54b9e8bcc67ef4de3f
/src/main/java/com/sdrc/covid19odisha/collections/Question.java
aecba6aeadd3730f7335eca6fb8ba811af1bf9c6
[]
no_license
SDRCDev/covid19odisha_backend
https://github.com/SDRCDev/covid19odisha_backend
ddc97775753f013c387acbb001281ac486fd15c3
b916360ca46ba5f670fad1613ac704e2ab964a10
refs/heads/main
2022-12-21T01:31:33.577000
2020-10-08T17:10:12
2020-10-08T17:10:12
302,408,895
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sdrc.covid19odisha.collections; import java.util.List; import java.util.Map; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import lombok.Data; @Document @Data public class Question { @Id private String id; private int formId; private List<Map<String,Object>> questions; }
UTF-8
Java
363
java
Question.java
Java
[]
null
[]
package com.sdrc.covid19odisha.collections; import java.util.List; import java.util.Map; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import lombok.Data; @Document @Data public class Question { @Id private String id; private int formId; private List<Map<String,Object>> questions; }
363
0.77686
0.77135
23
14.782609
17.961206
62
false
false
0
0
0
0
0
0
0.695652
false
false
9
298973001ba292885ec39540315bfb504fb78eae
19,181,324,011,534
473fc28d466ddbe9758ca49c7d4fb42e7d82586e
/app/src/main/java/com/syd/source/aosp/cts/apps/CtsVerifier/src/com/android/cts/verifier/sensors/sixdof/Renderer/RobustnessRenderer.java
6a5f9e79239c03a035d0e88fc1dcc2c027a1e37b
[]
no_license
lz-purple/Source
https://github.com/lz-purple/Source
a7788070623f2965a8caa3264778f48d17372bab
e2745b756317aac3c7a27a4c10bdfe0921a82a1c
refs/heads/master
2020-12-23T17:03:12.412000
2020-01-31T01:54:37
2020-01-31T01:54:37
237,205,127
4
2
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.cts.verifier.sensors.sixdof.Renderer; import android.content.Context; import com.android.cts.verifier.sensors.sixdof.Renderer.Renderable.RectangleRenderable; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; /** * Renderer for the robustness test */ public class RobustnessRenderer extends BaseRenderer { private float[] mRectanglePositionData; private RectangleRenderable mRectangle; public RobustnessRenderer(Context context) { super(context); } @Override public void onSurfaceCreated(GL10 glUnused, EGLConfig config) { super.onSurfaceCreated(glUnused, config); mRectangle = new RectangleRenderable(); } @Override public void onSurfaceChanged(GL10 glUnused, int width, int height) { super.onSurfaceChanged(glUnused, width, height); mRectangle.initialiseRectangle(mRectanglePositionData); mProjectionMatrix = mFrustrumProjectionMatrix; } public void setLineColor(float[] newColor) { if (mIsValid) { mRectangle.setLineColor(newColor); } } public void updateCurrentAngle(float newAngle) { if (mIsValid) { mRectangle.setRotationAngle(newAngle); } } public void updateTargetAngle(float newAngle) { if (mIsValid) { mCameraPreview.setRotationAngle(newAngle); } } @Override protected void doPreRenderingSetup() { // Set view matrix to one that doesn't move. mViewMatrix = mOrthogonalViewMatrix; // Set projection matrix to show camera preview slightly set back. mProjectionMatrix = mFrustrumProjectionMatrix; } @Override protected void doTestSpecificRendering() { // Update the texture with the latest camera frame if there is an update pending. updateCameraTexture(); mDrawParameters.update(mViewMatrix, mProjectionMatrix); mRectangle.draw(mDrawParameters); } @Override protected float[] getCameraCoordinates(float left, float right, float bottom, float top) { // Set rectangle coordinates to be the exact same as the camera preview. mRectanglePositionData = new float[]{ 2 * left, 2 * top, 0.0f, 2 * left, 2 * bottom, 0.0f, 2 * left, 2 * bottom, 0.0f, 2 * right, 2 * bottom, 0.0f, 2 * right, 2 * bottom, 0.0f, 2 * right, 2 * top, 0.0f, 2 * right, 2 * top, 0.0f, 2 * left, 2 * top, 0.0f, }; return new float[]{ 2 * left, 2 * top, 0.0f, 2 * left, 2 * bottom, 0.0f, 2 * right, 2 * top, 0.0f, 2 * left, 2 * bottom, 0.0f, 2 * right, 2 * bottom, 0.0f, 2 * right, 2 * top, 0.0f, }; } }
UTF-8
Java
3,544
java
RobustnessRenderer.java
Java
[]
null
[]
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.cts.verifier.sensors.sixdof.Renderer; import android.content.Context; import com.android.cts.verifier.sensors.sixdof.Renderer.Renderable.RectangleRenderable; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; /** * Renderer for the robustness test */ public class RobustnessRenderer extends BaseRenderer { private float[] mRectanglePositionData; private RectangleRenderable mRectangle; public RobustnessRenderer(Context context) { super(context); } @Override public void onSurfaceCreated(GL10 glUnused, EGLConfig config) { super.onSurfaceCreated(glUnused, config); mRectangle = new RectangleRenderable(); } @Override public void onSurfaceChanged(GL10 glUnused, int width, int height) { super.onSurfaceChanged(glUnused, width, height); mRectangle.initialiseRectangle(mRectanglePositionData); mProjectionMatrix = mFrustrumProjectionMatrix; } public void setLineColor(float[] newColor) { if (mIsValid) { mRectangle.setLineColor(newColor); } } public void updateCurrentAngle(float newAngle) { if (mIsValid) { mRectangle.setRotationAngle(newAngle); } } public void updateTargetAngle(float newAngle) { if (mIsValid) { mCameraPreview.setRotationAngle(newAngle); } } @Override protected void doPreRenderingSetup() { // Set view matrix to one that doesn't move. mViewMatrix = mOrthogonalViewMatrix; // Set projection matrix to show camera preview slightly set back. mProjectionMatrix = mFrustrumProjectionMatrix; } @Override protected void doTestSpecificRendering() { // Update the texture with the latest camera frame if there is an update pending. updateCameraTexture(); mDrawParameters.update(mViewMatrix, mProjectionMatrix); mRectangle.draw(mDrawParameters); } @Override protected float[] getCameraCoordinates(float left, float right, float bottom, float top) { // Set rectangle coordinates to be the exact same as the camera preview. mRectanglePositionData = new float[]{ 2 * left, 2 * top, 0.0f, 2 * left, 2 * bottom, 0.0f, 2 * left, 2 * bottom, 0.0f, 2 * right, 2 * bottom, 0.0f, 2 * right, 2 * bottom, 0.0f, 2 * right, 2 * top, 0.0f, 2 * right, 2 * top, 0.0f, 2 * left, 2 * top, 0.0f, }; return new float[]{ 2 * left, 2 * top, 0.0f, 2 * left, 2 * bottom, 0.0f, 2 * right, 2 * top, 0.0f, 2 * left, 2 * bottom, 0.0f, 2 * right, 2 * bottom, 0.0f, 2 * right, 2 * top, 0.0f, }; } }
3,544
0.632901
0.613149
111
30.927927
25.929464
94
false
false
0
0
0
0
0
0
0.720721
false
false
9
a30c8d7e937db5c266e01ce9fe7928ae952a0323
3,246,995,316,759
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/16/16_b0cfd31980af1acec0e35f6870ac7a48d5eda424/BasicParserSettings/16_b0cfd31980af1acec0e35f6870ac7a48d5eda424_BasicParserSettings_s.java
3deca70a3579030b571d79fa79ae74ee3839b0f0
[]
no_license
zhongxingyu/Seer
https://github.com/zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516000
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
false
2023-06-22T07:55:57
2020-04-28T11:07:49
2023-06-21T00:53:27
2023-06-22T07:55:57
2,849,868
2
2
0
null
false
false
/* * Licensed to Aduna under one or more contributor license agreements. * See the NOTICE.txt file distributed with this work for additional * information regarding copyright ownership. * * Aduna licenses this file to you under the terms of the Aduna BSD * License (the "License"); you may not use this file except in compliance * with the License. See the LICENSE.txt file distributed with this work * for the full License. * * 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.openrdf.rio.helpers; import org.openrdf.rio.RioSetting; import org.openrdf.rio.RDFParser.DatatypeHandling; /** * A class encapsulating the basic parser settings that most parsers may * support. * * @author Peter Ansell * @since 2.7.0 */ public class BasicParserSettings { /** * Boolean setting for parser to determine whether data values are verified. * <p> * Defaults to true. * * @since 2.7.0 */ public static final RioSetting<Boolean> VERIFY_DATA = new RioSettingImpl<Boolean>( "org.openrdf.rio.verifydata", "Verify data", Boolean.TRUE); /** * Boolean setting for parser to determine whether parser should stop at * first error or continue if that is possible. If the parser is unable to * continue after an error it will still fail regardless of this setting. * <p> * Defaults to true. * * @since 2.7.0 */ public static final RioSetting<Boolean> STOP_AT_FIRST_ERROR = new RioSettingImpl<Boolean>( "org.openrdf.rio.stopatfirsterror", "Stop at first error", Boolean.TRUE); /** * Boolean setting for parser to determine whether parser should attempt to * preserve identifiers for blank nodes. If the blank node did not have an * identifier in the document a new identifier will be generated for it. * <p> * Defaults to false. * * @since 2.7.0 */ public static final RioSetting<Boolean> PRESERVE_BNODE_IDS = new RioSettingImpl<Boolean>( "org.openrdf.rio.preservebnodeids", "Preserve blank node identifiers", Boolean.FALSE); /** * Determines which mode of {@link DatatypeHandling} will be used by the * parser. * <p> * Defaults to {@link DatatypeHandling#VERIFY}. * * @since 2.7.0 */ public static final RioSetting<DatatypeHandling> DATATYPE_HANDLING = new RioSettingImpl<DatatypeHandling>( "org.openrdf.rio.datatypehandling", "Datatype handling", DatatypeHandling.VERIFY); /** * Boolean setting for parser to determine whether parser should preserve, * truncate, drop, or otherwise manipulate statements that contain long * literals. The maximum length of literals if this setting is set to * truncate or drop is configured using {@link #LARGE_LITERALS_LIMIT}. * <p> * Defaults to {@link LiteralHandling#PRESERVE}. * * @since 2.7.0 */ public static final RioSetting<LiteralHandling> LARGE_LITERALS_HANDLING = new RioSettingImpl<LiteralHandling>( "org.openrdf.rio.largeliterals", "Large literals handling", LiteralHandling.PRESERVE); /** * If {@link #LARGE_LITERALS_HANDLING} is set to true, then the value of this * setting corresponds to the maximum number of bytes for a literal before * the statement it is a part of is dropped silently by the parser. * <p> * Defaults to 1048576 bytes, which is equivalent to 1 megabyte. * * @since 2.7.0 */ public static final RioSetting<Long> LARGE_LITERALS_LIMIT = new RioSettingImpl<Long>( "org.openrdf.rio.largeliteralslimit", "Size limit for large literals", 1048576L); /** * Private default constructor. */ private BasicParserSettings() { } }
UTF-8
Java
3,927
java
16_b0cfd31980af1acec0e35f6870ac7a48d5eda424_BasicParserSettings_s.java
Java
[ { "context": "hat most parsers may\n * support.\n * \n * @author Peter Ansell\n * @since 2.7.0\n */\n public class BasicParserSe", "end": 1035, "score": 0.999188244342804, "start": 1023, "tag": "NAME", "value": "Peter Ansell" } ]
null
[]
/* * Licensed to Aduna under one or more contributor license agreements. * See the NOTICE.txt file distributed with this work for additional * information regarding copyright ownership. * * Aduna licenses this file to you under the terms of the Aduna BSD * License (the "License"); you may not use this file except in compliance * with the License. See the LICENSE.txt file distributed with this work * for the full License. * * 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.openrdf.rio.helpers; import org.openrdf.rio.RioSetting; import org.openrdf.rio.RDFParser.DatatypeHandling; /** * A class encapsulating the basic parser settings that most parsers may * support. * * @author <NAME> * @since 2.7.0 */ public class BasicParserSettings { /** * Boolean setting for parser to determine whether data values are verified. * <p> * Defaults to true. * * @since 2.7.0 */ public static final RioSetting<Boolean> VERIFY_DATA = new RioSettingImpl<Boolean>( "org.openrdf.rio.verifydata", "Verify data", Boolean.TRUE); /** * Boolean setting for parser to determine whether parser should stop at * first error or continue if that is possible. If the parser is unable to * continue after an error it will still fail regardless of this setting. * <p> * Defaults to true. * * @since 2.7.0 */ public static final RioSetting<Boolean> STOP_AT_FIRST_ERROR = new RioSettingImpl<Boolean>( "org.openrdf.rio.stopatfirsterror", "Stop at first error", Boolean.TRUE); /** * Boolean setting for parser to determine whether parser should attempt to * preserve identifiers for blank nodes. If the blank node did not have an * identifier in the document a new identifier will be generated for it. * <p> * Defaults to false. * * @since 2.7.0 */ public static final RioSetting<Boolean> PRESERVE_BNODE_IDS = new RioSettingImpl<Boolean>( "org.openrdf.rio.preservebnodeids", "Preserve blank node identifiers", Boolean.FALSE); /** * Determines which mode of {@link DatatypeHandling} will be used by the * parser. * <p> * Defaults to {@link DatatypeHandling#VERIFY}. * * @since 2.7.0 */ public static final RioSetting<DatatypeHandling> DATATYPE_HANDLING = new RioSettingImpl<DatatypeHandling>( "org.openrdf.rio.datatypehandling", "Datatype handling", DatatypeHandling.VERIFY); /** * Boolean setting for parser to determine whether parser should preserve, * truncate, drop, or otherwise manipulate statements that contain long * literals. The maximum length of literals if this setting is set to * truncate or drop is configured using {@link #LARGE_LITERALS_LIMIT}. * <p> * Defaults to {@link LiteralHandling#PRESERVE}. * * @since 2.7.0 */ public static final RioSetting<LiteralHandling> LARGE_LITERALS_HANDLING = new RioSettingImpl<LiteralHandling>( "org.openrdf.rio.largeliterals", "Large literals handling", LiteralHandling.PRESERVE); /** * If {@link #LARGE_LITERALS_HANDLING} is set to true, then the value of this * setting corresponds to the maximum number of bytes for a literal before * the statement it is a part of is dropped silently by the parser. * <p> * Defaults to 1048576 bytes, which is equivalent to 1 megabyte. * * @since 2.7.0 */ public static final RioSetting<Long> LARGE_LITERALS_LIMIT = new RioSettingImpl<Long>( "org.openrdf.rio.largeliteralslimit", "Size limit for large literals", 1048576L); /** * Private default constructor. */ private BasicParserSettings() { } }
3,921
0.709447
0.70028
107
35.691589
33.839756
112
false
false
0
0
0
0
0
0
1.037383
false
false
9
7c4c34144c7538e951061e2ff22eb7fad9a68699
4,964,982,255,653
36f7e1be7475a4088cf8c6d13bf5954659188526
/Parcial_CuantoSabesDeFutbol/app/src/main/java/com/example/parcial_cuantosabesdefutbol/Administrador.java
444225c6968cabfc3126eeda16da333e258fa80a
[]
no_license
yesenialg/LenguajesProgramacionII
https://github.com/yesenialg/LenguajesProgramacionII
bf295cfb08c056bb1ff1edbf9f85b00f955f73b8
2da5103265796c5861f61845047ef3a752cc5fb9
refs/heads/master
2020-12-19T08:33:11.592000
2020-04-07T17:55:11
2020-04-07T17:55:11
235,682,360
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.parcial_cuantosabesdefutbol; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AppCompatActivity; import android.app.DatePickerDialog; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CalendarView; import android.widget.DatePicker; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; public class Administrador extends AppCompatActivity { ArrayAdapter adapter; Button btnAgregar, btnInformacion; Spinner lvEquipo1, lvEquipo2; DatePicker dp; String fecha; String [] equipos = {"America", "Nacional", "Medellin", "Junior", "Cali", "Millos", "Santafe", "Tolima", "Envigado", "Cucuta"}; String equipo1, equipo2; ArchivoPartidos arc; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_administrador); conectar(); adapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_expandable_list_item_1,equipos); lvEquipo1.setAdapter(adapter); lvEquipo2.setAdapter(adapter); btnAgregar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Calendar cal = new GregorianCalendar(); Date date = cal.getTime(); SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy"); String formatteDate = df.format(date); int dayForm = dia(formatteDate); int montuForm = mes(formatteDate); escribirFecha(); if(lvEquipo1.getSelectedItem().toString() == lvEquipo2.getSelectedItem().toString()) { Toast.makeText(getApplicationContext(), "Seleccione equipos diferentes", Toast.LENGTH_LONG).show(); }else if(dayForm >= dp.getDayOfMonth() && montuForm > dp.getMonth() ) { Toast.makeText(getApplicationContext(), "Seleccione una fecha valida", Toast.LENGTH_LONG).show(); }else { Toast.makeText(getApplicationContext(), "Los equipos: " + lvEquipo1.getSelectedItem().toString() + " - " + lvEquipo2.getSelectedItem().toString() + " Juegan el " + fecha, Toast.LENGTH_LONG).show(); equipo1 = lvEquipo1.getSelectedItem().toString(); equipo2 = lvEquipo2.getSelectedItem().toString(); try { Cargar(); } catch (IOException e) { e.printStackTrace(); } } } }); //Dirige al activity de informacionAdministrador btnInformacion.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent a = new Intent(getApplicationContext(), InformacionAdministrador.class); startActivity(a); } }); } //Extrae el mes del String fecha private int mes(String formatteDate) { String a = formatteDate.charAt(3) + "" + formatteDate.charAt(4) + ""; int mes = Integer.parseInt(a); return mes; } //Extrae el dia del String fecha private int dia(String formatteDate) { String a = formatteDate.charAt(0) + "" + formatteDate.charAt(1) + ""; int dia = Integer.parseInt(a); return dia; } //Cambia los dias y meses con un solo digito, a dos "3" --> "03" private void escribirFecha() { String day, month; if(dp.getDayOfMonth() < 10){ day = "0" + dp.getDayOfMonth(); }else{ day = dp.getDayOfMonth() + ""; } if((dp.getMonth()+1) < 10){ month = "0" + (dp.getMonth()+1); }else{ month = (dp.getMonth()+1) + ""; } fecha = day + "/" + month + "/" + dp.getYear(); } //Manda los equipos y la fecha seleccionada a la clase ArchivoPartido para guardar en el archivo plano private void Cargar() throws IOException { arc = new ArchivoPartidos(this); String esc = equipo1 + "\n" + equipo2 + "\n" + fecha; arc.escribir(esc); } private void conectar() { btnAgregar = findViewById(R.id.btnAgregarPartido); lvEquipo1 = findViewById(R.id.lvEquipo1); lvEquipo2 = findViewById(R.id.lvEquipo2); dp = findViewById(R.id.datePicker); btnInformacion = findViewById(R.id.btnInformacion); } }
UTF-8
Java
4,911
java
Administrador.java
Java
[]
null
[]
package com.example.parcial_cuantosabesdefutbol; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AppCompatActivity; import android.app.DatePickerDialog; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CalendarView; import android.widget.DatePicker; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; public class Administrador extends AppCompatActivity { ArrayAdapter adapter; Button btnAgregar, btnInformacion; Spinner lvEquipo1, lvEquipo2; DatePicker dp; String fecha; String [] equipos = {"America", "Nacional", "Medellin", "Junior", "Cali", "Millos", "Santafe", "Tolima", "Envigado", "Cucuta"}; String equipo1, equipo2; ArchivoPartidos arc; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_administrador); conectar(); adapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_expandable_list_item_1,equipos); lvEquipo1.setAdapter(adapter); lvEquipo2.setAdapter(adapter); btnAgregar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Calendar cal = new GregorianCalendar(); Date date = cal.getTime(); SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy"); String formatteDate = df.format(date); int dayForm = dia(formatteDate); int montuForm = mes(formatteDate); escribirFecha(); if(lvEquipo1.getSelectedItem().toString() == lvEquipo2.getSelectedItem().toString()) { Toast.makeText(getApplicationContext(), "Seleccione equipos diferentes", Toast.LENGTH_LONG).show(); }else if(dayForm >= dp.getDayOfMonth() && montuForm > dp.getMonth() ) { Toast.makeText(getApplicationContext(), "Seleccione una fecha valida", Toast.LENGTH_LONG).show(); }else { Toast.makeText(getApplicationContext(), "Los equipos: " + lvEquipo1.getSelectedItem().toString() + " - " + lvEquipo2.getSelectedItem().toString() + " Juegan el " + fecha, Toast.LENGTH_LONG).show(); equipo1 = lvEquipo1.getSelectedItem().toString(); equipo2 = lvEquipo2.getSelectedItem().toString(); try { Cargar(); } catch (IOException e) { e.printStackTrace(); } } } }); //Dirige al activity de informacionAdministrador btnInformacion.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent a = new Intent(getApplicationContext(), InformacionAdministrador.class); startActivity(a); } }); } //Extrae el mes del String fecha private int mes(String formatteDate) { String a = formatteDate.charAt(3) + "" + formatteDate.charAt(4) + ""; int mes = Integer.parseInt(a); return mes; } //Extrae el dia del String fecha private int dia(String formatteDate) { String a = formatteDate.charAt(0) + "" + formatteDate.charAt(1) + ""; int dia = Integer.parseInt(a); return dia; } //Cambia los dias y meses con un solo digito, a dos "3" --> "03" private void escribirFecha() { String day, month; if(dp.getDayOfMonth() < 10){ day = "0" + dp.getDayOfMonth(); }else{ day = dp.getDayOfMonth() + ""; } if((dp.getMonth()+1) < 10){ month = "0" + (dp.getMonth()+1); }else{ month = (dp.getMonth()+1) + ""; } fecha = day + "/" + month + "/" + dp.getYear(); } //Manda los equipos y la fecha seleccionada a la clase ArchivoPartido para guardar en el archivo plano private void Cargar() throws IOException { arc = new ArchivoPartidos(this); String esc = equipo1 + "\n" + equipo2 + "\n" + fecha; arc.escribir(esc); } private void conectar() { btnAgregar = findViewById(R.id.btnAgregarPartido); lvEquipo1 = findViewById(R.id.lvEquipo1); lvEquipo2 = findViewById(R.id.lvEquipo2); dp = findViewById(R.id.datePicker); btnInformacion = findViewById(R.id.btnInformacion); } }
4,911
0.60843
0.600896
130
36.776924
31.873611
221
false
false
0
0
0
0
0
0
0.738462
false
false
9
20a61a6a9130a88f3598c3762c001fb0e3ef3c20
1,657,857,437,727
4401d65ed5c5f61cba10ef6af7f0e774903bd844
/fooding_v2/src/dominio/Consulta.java
d0abfe23b24355a862b5fd97520d1bb061e4d7e1
[]
no_license
gonchistrauss/fooding2.0-strauss_rezy
https://github.com/gonchistrauss/fooding2.0-strauss_rezy
1347eb8266290cb8d59042137fd0f2709bd7ca69
6bd7e6d161459bc96e1e3a06ac405aff3a3b3f85
refs/heads/master
2021-08-18T22:00:57.286000
2017-11-24T02:40:16
2017-11-24T02:40:16
111,149,457
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package dominio; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import utils.Tipos.*; public class Consulta implements Serializable { private int id; private Usuario usuario; private Profesional profesional; private Estado estado; private ArrayList<Incidencia> listaIncidencias; private Categoria categoria; public int getId() { return id; } public void setId(int id) { this.id = id; } public Usuario getUsuario() { return usuario; } public void setUsuario(Usuario usuario) { this.usuario = usuario; } public Profesional getProfesional() { return profesional; } public void setProfesional(Profesional profesional) { this.profesional = profesional; } public Estado getEstado() { return estado; } public void setEstado(Estado estado) { this.estado = estado; } public ArrayList<Incidencia> getListaIncidencias() { return listaIncidencias; } public void agregarIncidencia(String mensaje, String fecha, Persona creador) { Incidencia nuevaIncidencia = new Incidencia(mensaje, fecha, this, creador); this.listaIncidencias.add(nuevaIncidencia); } public Categoria getCategoria() { return categoria; } public void setCategoria(Categoria categoria) { this.categoria = categoria; } public Consulta(Usuario unUsuario, Categoria unaCategoria) { this.setUsuario(unUsuario); this.setEstado(Estado.PENDIENTE); this.setCategoria(unaCategoria); profesional = new Profesional(); listaIncidencias = new ArrayList<Incidencia>(); } public String toStringDescripcion() { String res = "Categoria: " + this.getCategoria().name() + " - Estado: " + this.getEstado().name() + " - Usuario: " + this.getUsuario().getNombre().toUpperCase() + " " + this.getUsuario().getApellidos().toUpperCase() + " - Profesional: "; if (this.getProfesional() == null) { res += "N/A"; } else { res += this.getProfesional().getNombre() + " " + this.getProfesional().getApellidos(); } return res; } @Override public boolean equals(Object obj) { Consulta unaC = (Consulta) obj; return this.getId() == unaC.getId() && this.getProfesional().equals(unaC.getProfesional()) && this.getUsuario().equals(unaC.getUsuario()); } //Metodo toString @Override public String toString() { String consulta = "Tipo: " + this.getCategoria().toString() + "\n"; for (Incidencia incidencia : this.getListaIncidencias()) { consulta += incidencia.toString() + "\n *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n"; } return consulta; } }
UTF-8
Java
2,976
java
Consulta.java
Java
[]
null
[]
package dominio; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import utils.Tipos.*; public class Consulta implements Serializable { private int id; private Usuario usuario; private Profesional profesional; private Estado estado; private ArrayList<Incidencia> listaIncidencias; private Categoria categoria; public int getId() { return id; } public void setId(int id) { this.id = id; } public Usuario getUsuario() { return usuario; } public void setUsuario(Usuario usuario) { this.usuario = usuario; } public Profesional getProfesional() { return profesional; } public void setProfesional(Profesional profesional) { this.profesional = profesional; } public Estado getEstado() { return estado; } public void setEstado(Estado estado) { this.estado = estado; } public ArrayList<Incidencia> getListaIncidencias() { return listaIncidencias; } public void agregarIncidencia(String mensaje, String fecha, Persona creador) { Incidencia nuevaIncidencia = new Incidencia(mensaje, fecha, this, creador); this.listaIncidencias.add(nuevaIncidencia); } public Categoria getCategoria() { return categoria; } public void setCategoria(Categoria categoria) { this.categoria = categoria; } public Consulta(Usuario unUsuario, Categoria unaCategoria) { this.setUsuario(unUsuario); this.setEstado(Estado.PENDIENTE); this.setCategoria(unaCategoria); profesional = new Profesional(); listaIncidencias = new ArrayList<Incidencia>(); } public String toStringDescripcion() { String res = "Categoria: " + this.getCategoria().name() + " - Estado: " + this.getEstado().name() + " - Usuario: " + this.getUsuario().getNombre().toUpperCase() + " " + this.getUsuario().getApellidos().toUpperCase() + " - Profesional: "; if (this.getProfesional() == null) { res += "N/A"; } else { res += this.getProfesional().getNombre() + " " + this.getProfesional().getApellidos(); } return res; } @Override public boolean equals(Object obj) { Consulta unaC = (Consulta) obj; return this.getId() == unaC.getId() && this.getProfesional().equals(unaC.getProfesional()) && this.getUsuario().equals(unaC.getUsuario()); } //Metodo toString @Override public String toString() { String consulta = "Tipo: " + this.getCategoria().toString() + "\n"; for (Incidencia incidencia : this.getListaIncidencias()) { consulta += incidencia.toString() + "\n *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n"; } return consulta; } }
2,976
0.592742
0.592742
107
26.813084
24.239124
113
false
false
0
0
0
0
0
0
0.411215
false
false
9
b8749f898e8929a98b5c5ee16c2402e5b4e12246
20,306,605,436,166
f3faa8360c7f63a40eb0a9cb6b90606b0a441a87
/Demo/src/Exception/throws_example_1.java
4fbaf4d19122735e9dd66f960c0adf2e7d0e5dd7
[]
no_license
Riyazvk/eclipse
https://github.com/Riyazvk/eclipse
2b85f468cf92305501f466e1b016dc6193cba7f9
e01e64b266c09c6b728ea92037f44a74bad87685
refs/heads/master
2021-07-07T03:22:14.570000
2020-03-25T11:31:54
2020-03-25T11:31:54
241,807,422
0
0
null
false
2021-04-26T20:05:32
2020-02-20T06:08:49
2020-03-25T11:32:26
2021-04-26T20:05:32
55,219
0
0
12
HTML
false
false
package Exception; public class throws_example_1 { public void f1() throws ArithmeticException { System.out.println("In f1 before "); int a=10,b=0,c; c=a/b; System.out.println("in f1-after"); } public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("in main-before"); try { throws_example_1 te=new throws_example_1(); te.f1(); } catch(ArithmeticException ae) { System.out.println("IN Arithmeticexception"); } System.out.println("in main-after"); } }
UTF-8
Java
556
java
throws_example_1.java
Java
[]
null
[]
package Exception; public class throws_example_1 { public void f1() throws ArithmeticException { System.out.println("In f1 before "); int a=10,b=0,c; c=a/b; System.out.println("in f1-after"); } public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("in main-before"); try { throws_example_1 te=new throws_example_1(); te.f1(); } catch(ArithmeticException ae) { System.out.println("IN Arithmeticexception"); } System.out.println("in main-after"); } }
556
0.640288
0.622302
26
19.384615
17.504015
48
false
false
0
0
0
0
0
0
1.076923
false
false
9
ea5c58afaf8db4ec7ebf7aa7a35399a6031e327c
23,819,888,667,489
24a516af271db759033e85bbf7906b5e02fd98bb
/src/flertrådatProgrammeringL3V2/TruckThread.java
7c70f1f3671f017ceebcb9bd033a6d5f88d12e8f
[]
no_license
13120dde/SchoolAssignmentsMaH
https://github.com/13120dde/SchoolAssignmentsMaH
8328d2947d6b37a0b0f93b255c022b149ff145f5
09cfcb25b252f6f5ba9d16a64e44e77994253f81
refs/heads/master
2021-01-20T21:15:32.071000
2018-01-15T22:05:52
2018-01-15T22:05:52
101,758,571
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package flertrådatProgrammeringL3V2; import java.util.LinkedList; /** * Created by Patrik Lind on 2016-11-29. * * This class represents a consumer-thread that retrieves objects from the buffer. This class has constaints on how * many objects it can retrieve, aswell as maximum volume and weight. */ public class TruckThread implements Runnable{ private final boolean continueLoad; private String consumerName; private Thread thread; private boolean threadRunning; private double maxWeight, maxVolume, currentWeight, currentVolume; private int currentCapacity, maxCapacity; private Storage buffer; private LinkedList<FoodItem> cargo = new LinkedList<FoodItem>(); private GUISemaphore gui; /**Instantiate this object. * * @param consumerName * @param buffer * @param gui * @param weight * @param volume * @param nbrOfItems * @param continiueLoad */ public TruckThread(String consumerName, Storage buffer, GUISemaphore gui, double weight, double volume, int nbrOfItems, boolean continiueLoad){ this.gui = gui; this.consumerName =consumerName; this.buffer=buffer; threadRunning=false; this.maxWeight =weight; this.maxVolume =volume; this.maxCapacity =nbrOfItems; this.continueLoad=continiueLoad; currentCapacity = 0; currentVolume = 0; currentWeight = 0; } /**Starts the thread. While the thread is running it will attempt to retrieve objects from the buffer if the buffer * isn't empty. When the thread reaches its capacity-limit it will either terminate or wait for 5 seconds (if * 'continiue load' checkbox is selected. * */ public void startConsuming(){ if(thread == null){ thread = new Thread(this); threadRunning=true; thread.start(); } } /**Stops the thread. * */ public void stopConsuming(){ if(thread!=null){ threadRunning = false; } } /**Returns true if there is more place to store the items, othewise false. * * @return : boolean */ public boolean isFull(){ if(currentCapacity>=maxCapacity){ return true; }else{ if((int)currentVolume>=maxVolume-1 || (int)currentWeight>=maxWeight-1){ return true; } return false; } } private double remainingVolume(){ return maxVolume-currentVolume; } private double remaningWeight(){ return maxWeight-currentWeight; } @Override public void run() { gui.updateConsumerStatus(consumerName, ": Running"); while(threadRunning){ if(!isFull()){ try { thread.sleep(100); Storage.semConsumer.acquire(); Storage.mutex.lock(); if(buffer.getNextItemsWeight()<remaningWeight() && buffer.getNextItemsVolume()<remainingVolume()) { FoodItem item = buffer.get(); currentCapacity++; currentWeight += item.getWeight(); currentVolume += item.getVolume(); gui.updateConsumerCargo(item.getItemName(), consumerName, currentCapacity, currentVolume, currentWeight); }else{ Storage.semConsumer.release(); } } catch (InterruptedException e) { e.printStackTrace(); } Storage.mutex.unlock(); Storage.semProducer.release(); }else{ //Put the thread to sleep, reset capacity-variables and update the gui. if(continueLoad){ try { int s=5; while(s>=0){ gui.updateConsumerStatus(consumerName, ": Sleeping: "+s); thread.sleep(1000); s--; } currentVolume=0; currentWeight=0; currentCapacity=0; gui.updateConsumerCargo("clear list", consumerName, currentCapacity, currentVolume, currentWeight); gui.updateConsumerStatus(consumerName, ": Running"); } catch (InterruptedException e) { e.printStackTrace(); } }else{ stopConsuming(); } } } gui.updateConsumerStatus(consumerName, ": Idle"); gui.changeButtonAvaibility(consumerName); } }
UTF-8
Java
4,825
java
TruckThread.java
Java
[ { "context": ";\n\nimport java.util.LinkedList;\n\n/**\n * Created by Patrik Lind on 2016-11-29.\n *\n * This class represents a cons", "end": 97, "score": 0.9998437166213989, "start": 86, "tag": "NAME", "value": "Patrik Lind" } ]
null
[]
package flertrådatProgrammeringL3V2; import java.util.LinkedList; /** * Created by <NAME> on 2016-11-29. * * This class represents a consumer-thread that retrieves objects from the buffer. This class has constaints on how * many objects it can retrieve, aswell as maximum volume and weight. */ public class TruckThread implements Runnable{ private final boolean continueLoad; private String consumerName; private Thread thread; private boolean threadRunning; private double maxWeight, maxVolume, currentWeight, currentVolume; private int currentCapacity, maxCapacity; private Storage buffer; private LinkedList<FoodItem> cargo = new LinkedList<FoodItem>(); private GUISemaphore gui; /**Instantiate this object. * * @param consumerName * @param buffer * @param gui * @param weight * @param volume * @param nbrOfItems * @param continiueLoad */ public TruckThread(String consumerName, Storage buffer, GUISemaphore gui, double weight, double volume, int nbrOfItems, boolean continiueLoad){ this.gui = gui; this.consumerName =consumerName; this.buffer=buffer; threadRunning=false; this.maxWeight =weight; this.maxVolume =volume; this.maxCapacity =nbrOfItems; this.continueLoad=continiueLoad; currentCapacity = 0; currentVolume = 0; currentWeight = 0; } /**Starts the thread. While the thread is running it will attempt to retrieve objects from the buffer if the buffer * isn't empty. When the thread reaches its capacity-limit it will either terminate or wait for 5 seconds (if * 'continiue load' checkbox is selected. * */ public void startConsuming(){ if(thread == null){ thread = new Thread(this); threadRunning=true; thread.start(); } } /**Stops the thread. * */ public void stopConsuming(){ if(thread!=null){ threadRunning = false; } } /**Returns true if there is more place to store the items, othewise false. * * @return : boolean */ public boolean isFull(){ if(currentCapacity>=maxCapacity){ return true; }else{ if((int)currentVolume>=maxVolume-1 || (int)currentWeight>=maxWeight-1){ return true; } return false; } } private double remainingVolume(){ return maxVolume-currentVolume; } private double remaningWeight(){ return maxWeight-currentWeight; } @Override public void run() { gui.updateConsumerStatus(consumerName, ": Running"); while(threadRunning){ if(!isFull()){ try { thread.sleep(100); Storage.semConsumer.acquire(); Storage.mutex.lock(); if(buffer.getNextItemsWeight()<remaningWeight() && buffer.getNextItemsVolume()<remainingVolume()) { FoodItem item = buffer.get(); currentCapacity++; currentWeight += item.getWeight(); currentVolume += item.getVolume(); gui.updateConsumerCargo(item.getItemName(), consumerName, currentCapacity, currentVolume, currentWeight); }else{ Storage.semConsumer.release(); } } catch (InterruptedException e) { e.printStackTrace(); } Storage.mutex.unlock(); Storage.semProducer.release(); }else{ //Put the thread to sleep, reset capacity-variables and update the gui. if(continueLoad){ try { int s=5; while(s>=0){ gui.updateConsumerStatus(consumerName, ": Sleeping: "+s); thread.sleep(1000); s--; } currentVolume=0; currentWeight=0; currentCapacity=0; gui.updateConsumerCargo("clear list", consumerName, currentCapacity, currentVolume, currentWeight); gui.updateConsumerStatus(consumerName, ": Running"); } catch (InterruptedException e) { e.printStackTrace(); } }else{ stopConsuming(); } } } gui.updateConsumerStatus(consumerName, ": Idle"); gui.changeButtonAvaibility(consumerName); } }
4,820
0.549337
0.543532
155
30.122581
28.699631
147
false
false
0
0
0
0
0
0
0.541936
false
false
9
4607b62cdde07f7a78782cdb3189e8736f68d59b
19,026,705,132,150
9528993f63a35c8ee989e05456a098e3f6aef5e0
/examples/Language/src/main/java/generics/list/List.java
847ff3e3593088accf0eb0779dbfdb195290ef19
[]
no_license
SF3/Java-and-Spring
https://github.com/SF3/Java-and-Spring
6443f461935544cbc7687715b4baa658deb644dc
e186379788f1d7fb805168798e1ea2f3f09c7860
refs/heads/main
2023-05-31T05:54:15.579000
2021-07-01T09:34:49
2021-07-01T09:34:49
382,361,770
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package generics.list; public interface List<T> { int size(); void clear(); void add(T value); void remove(T value) throws ListEmptyException, ItemNotInListException; T get(int index) throws ListEmptyException, ItemNotInListException; }
UTF-8
Java
242
java
List.java
Java
[]
null
[]
package generics.list; public interface List<T> { int size(); void clear(); void add(T value); void remove(T value) throws ListEmptyException, ItemNotInListException; T get(int index) throws ListEmptyException, ItemNotInListException; }
242
0.77686
0.77686
9
26
24.913183
72
false
false
0
0
0
0
0
0
1.444444
false
false
9
25e2c8be79d8d8d4f8592d57262d6f47e182c022
18,614,388,285,042
d512be3d07b32a12ce7b89b338241e66f81c4949
/src/main/java/com/example/myblog/configuration/XssConfig.java
b96c41b9ab2466316871e3f36ddeca8053a45e60
[]
no_license
DeweyNULL/blogdemo
https://github.com/DeweyNULL/blogdemo
48578f35b6d80ff2970ec04528521da05b312ef7
95928266a1e16a5fa8abeebd73234ab0c8f1e6d0
refs/heads/master
2020-03-28T19:19:33.265000
2018-12-21T09:19:17
2018-12-21T09:19:17
148,965,121
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.myblog.configuration; import com.example.myblog.controller.filter.XssFilter; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.HashMap; import java.util.Map; /** * @program myblog * @description: xss配置文件 * @author: xielinzhi * @create: 2018/12/17 17:00 */ @Configuration public class XssConfig { @Bean public FilterRegistrationBean xssFilterRegistrationBean() { FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); filterRegistrationBean.setFilter(new XssFilter()); filterRegistrationBean.setOrder(1); filterRegistrationBean.setEnabled(true); filterRegistrationBean.addUrlPatterns("/*"); Map<String, String> initParameters = new HashMap<>(); initParameters.put("excludes", "/favicon.ico,/img/*,/js/*,/css/*"); filterRegistrationBean.setInitParameters(initParameters); return filterRegistrationBean; } }
UTF-8
Java
1,100
java
XssConfig.java
Java
[ { "context": "rogram myblog\n * @description: xss配置文件\n * @author: xielinzhi\n * @create: 2018/12/17 17:00\n */\n\n@Configuration\n", "end": 399, "score": 0.999600350856781, "start": 390, "tag": "USERNAME", "value": "xielinzhi" } ]
null
[]
package com.example.myblog.configuration; import com.example.myblog.controller.filter.XssFilter; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.HashMap; import java.util.Map; /** * @program myblog * @description: xss配置文件 * @author: xielinzhi * @create: 2018/12/17 17:00 */ @Configuration public class XssConfig { @Bean public FilterRegistrationBean xssFilterRegistrationBean() { FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); filterRegistrationBean.setFilter(new XssFilter()); filterRegistrationBean.setOrder(1); filterRegistrationBean.setEnabled(true); filterRegistrationBean.addUrlPatterns("/*"); Map<String, String> initParameters = new HashMap<>(); initParameters.put("excludes", "/favicon.ico,/img/*,/js/*,/css/*"); filterRegistrationBean.setInitParameters(initParameters); return filterRegistrationBean; } }
1,100
0.74359
0.731685
35
30.200001
26.122568
85
false
false
0
0
0
0
0
0
0.6
false
false
9
b8cce4ba935f7b79c8bbaf7840d2a976c19daadf
18,614,388,287,824
715b3ca66c9cc3aafee395a660c6029f5a8bc00a
/src/zoo/http/common/src/main/java/org/tio/http/common/HttpConfig.java
7443e626623e54b4ab4f622f6446ae6df7155f57
[ "Apache-2.0" ]
permissive
tywo45/t-io
https://github.com/tywo45/t-io
2a4cec7a5cd7ac570dfef6f593da35b7ca235509
63cf4a424308ceede6a041558be6b76264074158
refs/heads/master
2023-08-31T04:50:40.950000
2023-08-30T02:46:00
2023-08-30T02:46:00
86,653,876
2,013
609
Apache-2.0
false
2022-09-01T22:48:07
2017-03-30T03:17:13
2022-08-28T10:44:21
2022-09-01T22:48:06
33,336
1,516
528
14
Java
false
false
/* Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: You must give any other recipients of the Work or Derivative Works a copy of this License; and You must cause any modified files to carry prominent notices stating that You changed the files; and You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2020 t-io 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.tio.http.common; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.tio.http.common.handler.HttpRequestHandler; import org.tio.http.common.session.HttpSession; import org.tio.http.common.session.id.ISessionIdGenerator; import org.tio.http.common.session.limiter.SessionRateLimiter; import org.tio.http.common.view.freemarker.FreemarkerConfig; import org.tio.utils.cache.ICache; import org.tio.utils.hutool.FileUtil; import org.tio.utils.hutool.StrUtil; /** * @author tanyaowu * 2017年8月15日 下午1:21:14 */ public class HttpConfig { private static Logger log = LoggerFactory.getLogger(HttpConfig.class); /** * 用于覆盖session cookie的参数名,客户端可以用这个传递sessionid */ public static final String TIO_HTTP_SESSIONID = "tio_http_sessionid"; /** * 存放HttpSession对象的cacheName */ public static final String SESSION_CACHE_NAME = "tio-h-s"; /** * 存放sessionId的cookie value */ public static final String SESSION_COOKIE_NAME = "PHPSESSID"; /** * session默认的超时时间,单位:秒 */ public static final long DEFAULT_SESSION_TIMEOUT = 30 * 60; /** * 默认的静态资源缓存时间,单位:秒 */ public static final int MAX_LIVETIME_OF_STATICRES = 60 * 10; /** * 文件上传时,boundary值的最大长度 */ public static final int MAX_LENGTH_OF_BOUNDARY = 512; /** * 文件上传时,头部的最大长度 */ public static final int MAX_LENGTH_OF_MULTI_HEADER = 512; /** * 文件上传时,体的最大长度(默认值2M) */ public static final int MAX_LENGTH_OF_MULTI_BODY = 1024 * 1024 * 2; /** * 文件上传时,体的最大长度 */ private int maxLengthOfMultiBody = MAX_LENGTH_OF_MULTI_BODY; /** *POST体的最大长度默认值(2M) */ public static final int MAX_LENGTH_OF_POST_BODY = 1024 * 1024 * 2; /** * jsonp时,回调参数名 */ public static final String JSONP_PARAM_NAME = "tio_http_jsonp"; /** * POST体的最大长度 */ private int maxLengthOfPostBody = MAX_LENGTH_OF_POST_BODY; public static final int MAX_FORWARD_COUNT = 10; public int maxForwardCount = MAX_FORWARD_COUNT; /** * 是否使用session */ private boolean useSession = true; /** * 是否兼容1.0 * true:兼容 * false:不兼容 * 默认兼容 */ public boolean compatible1_0 = true; /** * 是否拼接http request header value * */ private boolean appendRequestHeaderString = false; private String bindIp = null; //"127.0.0.1"; /** * 监听端口 */ private Integer bindPort = 80; private String serverInfo = HttpConst.SERVER_INFO; private String charset = HttpConst.CHARSET_NAME; private ICache sessionStore = null; public SessionRateLimiter sessionRateLimiter; /** * 访问路径前缀,譬如"/api" */ private String contextPath = ""; /** * 加后缀,譬如".php" */ private String suffix = ""; /** * 如果访问路径是以"/"结束,则实际访问路径会自动加上welcomeFile,从而变成形如"/index.html"的路径 */ private String welcomeFile = null; //"index.html"; /** * 允许访问的域名,如果不限制,则为null */ private String[] allowDomains = null; /** * 存放HttpSession对象的cacheName */ private String sessionCacheName = SESSION_CACHE_NAME; /** * session超时时间,单位:秒 */ private long sessionTimeout = DEFAULT_SESSION_TIMEOUT; private String sessionCookieName = SESSION_COOKIE_NAME; /** * 静态资源缓存时间,如果小于等于0则不缓存,单位:秒 */ private int maxLiveTimeOfStaticRes = MAX_LIVETIME_OF_STATICRES; private String page404 = "/404.html"; private String page500 = "/500.html"; private ISessionIdGenerator sessionIdGenerator; private HttpRequestHandler httpRequestHandler; /** * ip被拉黑时,服务器给的响应,如果是null,服务器会直接断开连接 */ private HttpResponse respForBlackIp = null; /** * 是否被代理 */ private boolean isProxied = false; /** * 示例: * 1、classpath中:classpath:page * 2、绝对路径:/page */ private String pageRoot = null; //FileUtil.getAbsolutePath("page");//"/page"; private boolean pageInClasspath = false; /** * 临时支持freemarker,主要用于开发环境中的前端开发,暂时不重点作为tio-http-server功能<br> * 请大家暂时不要使用该功能,因为api随时会变 */ private FreemarkerConfig freemarkerConfig = null; /** * 域名和页面根目录映射。当客户端通过不同域名访问时,其页面根目录是不一样的<br> * key: www.t-io.org<br> * value: 域名对应的页面根目录<br> */ private volatile Map<String, String> domainPageMap = null; //new HashMap<>(); public boolean checkHost = true; private String name = null; /** * jsonp时,回调参数名 */ private String jsonpParamName = JSONP_PARAM_NAME; /** * 是否监控文件变化 */ public boolean monitorFileChange = false; public Map<String, String> getDomainPageMap() { return domainPageMap; } public HttpConfig(Integer bindPort, boolean useSession) { this.bindPort = bindPort; this.useSession = useSession; } /** * * @param bindPort * @param sessionTimeout session超时时间,单位:秒 * @param contextPath * @param suffix */ public HttpConfig(Integer bindPort, Long sessionTimeout, String contextPath, String suffix) { this.bindPort = bindPort; if (sessionTimeout != null) { this.sessionTimeout = sessionTimeout; } if (contextPath == null) { contextPath = ""; } this.contextPath = contextPath; if (suffix == null) { suffix = ""; } this.suffix = suffix; } /** * @return the bindIp */ public String getBindIp() { return bindIp; } /** * @return the bindPort */ public Integer getBindPort() { return bindPort; } /** * @return the charset */ public String getCharset() { return charset; } /** * @return the maxLiveTimeOfStaticRes */ public int getMaxLiveTimeOfStaticRes() { return maxLiveTimeOfStaticRes; } public String getPage404() { return page404; } public String getPage500() { return page500; } /** * @return the pageRoot */ public String getPageRoot() { return pageRoot; } public String getPageRoot(HttpRequest request) { if (domainPageMap == null || domainPageMap.isEmpty()) { return pageRoot; } String domain = request.getDomain(); String root = domainPageMap.get(domain); if (root != null) { return root; } Set<Entry<String, String>> set = domainPageMap.entrySet(); for (Entry<String, String> entry : set) { String d = entry.getKey(); if (d.startsWith(".") && domain.endsWith(d)) { String file = entry.getValue(); domainPageMap.put(domain, file); return file; } } domainPageMap.put(domain, pageRoot); return pageRoot; } /** * * @param request * @param path 形如 /xx/aa.html * @return * @throws Exception * @author tanyaowu */ public HttpResource getResource(HttpRequest request, String path) throws Exception { String pageRoot = getPageRoot(request); HttpResource httpResource = null; // File file = null; if (pageRoot != null) { if (StrUtil.endWith(path, "/")) { path = path + "index.html"; } String complatePath = pageRoot + path; if (pageInClasspath) { URL url = this.getClass().getClassLoader().getResource(complatePath); if (url != null) { String protocol = url.getProtocol(); if (Objects.equals(protocol, "jar")) { InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(complatePath); httpResource = new HttpResource(path, inputStream, null); } else { File file = new File(url.toURI()); if (file.exists()) { httpResource = new HttpResource(path, null, file); } } } } else { File file = new File(complatePath); if (file.exists()) { httpResource = new HttpResource(path, null, file); } } } return httpResource; } /** * @return the serverInfo */ public String getServerInfo() { return serverInfo; } /** * @return the sessionCacheName */ public String getSessionCacheName() { return sessionCacheName; } public String getSessionCookieName() { return sessionCookieName; } // public void setSessionTimeout(long sessionTimeout) { // this.sessionTimeout = sessionTimeout; // } public ISessionIdGenerator getSessionIdGenerator() { return sessionIdGenerator; } public ICache getSessionStore() { return sessionStore; } public long getSessionTimeout() { return sessionTimeout; } /** * @param bindIp the bindIp to set */ public void setBindIp(String bindIp) { this.bindIp = bindIp; } /** * @param charset the charset to set */ public void setCharset(String charset) { this.charset = charset; } /** * @param maxLiveTimeOfStaticRes the maxLiveTimeOfStaticRes to set */ public void setMaxLiveTimeOfStaticRes(int maxLiveTimeOfStaticRes) { this.maxLiveTimeOfStaticRes = maxLiveTimeOfStaticRes; } public void setPage404(String page404) { this.page404 = page404; } public void setPage500(String page500) { this.page500 = page500; } /** * 静态文件路径,必须先设置好pageRoot后再用 * key: 文件名后缀 * path: 访问路径 如 /user/set.html */ private Map<String, Set<String>> staticPathsMap = null; /** * path: 访问路径 如 /user/set.html */ private Set<String> staticPaths = null; public Map<String, Set<String>> getStaticPathsMap() { initStaticPaths(); return staticPathsMap; } public Set<String> getStaticPaths() { initStaticPaths(); return staticPaths; } private Map<String, Set<String>> initStaticPaths() { if (staticPathsMap != null) { return staticPathsMap; } if (pageInClasspath) { throw new RuntimeException("classpath的pageRoot是"); } staticPathsMap = new TreeMap<>(); staticPaths = new TreeSet<>(); List<File> files = FileUtil.loopFiles(pageRoot, new FileFilter() { @Override public boolean accept(File file) { String filename = file.getName(); String ext = FileUtil.extName(filename);//.getExtension(filename); if (file.isDirectory()) { if ("svn-base".equalsIgnoreCase(ext)) { return false; } return true; } // String ext = FileUtil.extName(file); return true; } }); if (files == null) { return staticPathsMap; } if (log.isInfoEnabled()) { log.info("一共{}个文件", files.size()); } File pageRootFile = new File(pageRoot); String pageRootAbs; try { pageRootAbs = pageRootFile.getCanonicalPath(); } catch (IOException e1) { log.error(e1.toString(), e1); return null; } for (File file : files) { try { if (file.isDirectory()) { } else { String absPath = file.getCanonicalPath(); // long start = System.currentTimeMillis(); String path = absPath.substring(pageRootAbs.length()); path = path.replaceAll("\\\\", "/"); if (!(path.startsWith("/"))) { path = "/" + path; } log.info("访问路径:{}", path); String ext = FileUtil.extName(path); Set<String> set = staticPathsMap.get(ext); if (set == null) { set = new TreeSet<>(); staticPathsMap.put(ext, set); } set.add(path); staticPaths.add(path); } } catch (Exception e) { log.error(e.toString()); } } return staticPathsMap; } /** * 获取文件的URL访问路径 * @param file * @return * @throws IOException */ public String getPath(File file) throws IOException { String absPath = file.getCanonicalPath(); File pageRootFile = new File(pageRoot); String pageRootAbs = pageRootFile.getCanonicalPath(); String path = absPath.substring(pageRootAbs.length()); path = path.replaceAll("\\\\", "/"); if (!(path.startsWith("/"))) { path = "/" + path; } return path; } /** * * @param pageRoot 如果是以"classpath:"开头,则从classpath中查找,否则视为普通的文件路径 * @author tanyaowu * @throws IOException */ public void setPageRoot(String pageRoot) throws IOException { staticPathsMap = null; if (StrUtil.startWith(pageRoot, "classpath:")) { this.pageRoot = pageRoot.substring("classpath:".length());//.replaceFirst("classpath:", "classpath:/"); if (this.pageRoot.startsWith("/")) { this.pageRoot = this.pageRoot.substring(1); } this.pageInClasspath = true; } else { this.pageRoot = pageRoot;//fromPath(pageRoot); } } /** * * @param path 如果是以"classpath:"开头,则从classpath中查找,否则视为普通的文件路径 * @return */ // public static File fromPath(String path) { // if (path == null) { // return null; // } // // if (StrUtil.startWithIgnoreCase(path, "classpath:")) { // return new File(ResourceUtil.getAbsolutePath(path)); // } else { // return new File(path); // } // } /** * * @param domain 形如www.t-io.org的域名,也可以是形如.t-io.org这样的通配域名 * @param pageRoot 如果是以"classpath:"开头,则从classpath中查找,否则视为普通的文件路径 * @throws IOException */ public void addDomainPage(String domain, String pageRoot) throws IOException { // File pageRootFile = fromPath(pageRoot); // if (!pageRootFile.exists()) { // throw new IOException("文件【" + pageRoot + "】不存在"); // } // // if (!pageRootFile.isDirectory()) { // throw new IOException("文件【" + pageRoot + "】不是目录"); // } if (domainPageMap == null) { synchronized (this) { if (domainPageMap == null) { domainPageMap = new HashMap<>(); } } } domainPageMap.put(domain, pageRoot); if (this.freemarkerConfig != null) { freemarkerConfig.addDomainConfiguration(domain, pageRoot); } } /** * @param serverInfo the serverInfo to set */ public void setServerInfo(String serverInfo) { this.serverInfo = serverInfo; } /** * @param sessionCacheName the sessionCacheName to set */ public void setSessionCacheName(String sessionCacheName) { this.sessionCacheName = sessionCacheName; } public void setSessionCookieName(String sessionCookieName) { this.sessionCookieName = sessionCookieName; } public void setSessionIdGenerator(ISessionIdGenerator sessionIdGenerator) { this.sessionIdGenerator = sessionIdGenerator; } public void setSessionStore(ICache sessionStore) { this.sessionStore = sessionStore; // this.httpSessionManager = HttpSessionManager.getInstance(sessionStore); } /** * @return the httpRequestHandler */ public HttpRequestHandler getHttpRequestHandler() { return httpRequestHandler; } /** * @param httpRequestHandler the httpRequestHandler to set */ public void setHttpRequestHandler(HttpRequestHandler httpRequestHandler) { this.httpRequestHandler = httpRequestHandler; } public String getContextPath() { return contextPath; } public String getSuffix() { return suffix; } public String[] getAllowDomains() { return allowDomains; } public void setAllowDomains(String[] allowDomains) { this.allowDomains = allowDomains; } /** * @return the isProxied */ public boolean isProxied() { return isProxied; } /** * @param isProxied the isProxied to set */ public void setProxied(boolean isProxied) { this.isProxied = isProxied; } public boolean isUseSession() { return useSession; } public void setUseSession(boolean useSession) { this.useSession = useSession; } /** * 根据sessionId获取HttpSession对象 * @param sessionId * @return */ public HttpSession getHttpSession(String sessionId) { if (StrUtil.isBlank(sessionId)) { return null; } HttpSession httpSession = (HttpSession) getSessionStore().get(sessionId); return httpSession; } public String getWelcomeFile() { return welcomeFile; } public void setWelcomeFile(String welcomeFile) { this.welcomeFile = welcomeFile; } public FreemarkerConfig getFreemarkerConfig() { return freemarkerConfig; } public void setFreemarkerConfig(FreemarkerConfig freemarkerConfig) { this.freemarkerConfig = freemarkerConfig; } /** * @return the appendRequestHeaderString */ public boolean isAppendRequestHeaderString() { return appendRequestHeaderString; } /** * @param appendRequestHeaderString the appendRequestHeaderString to set */ public void setAppendRequestHeaderString(boolean appendRequestHeaderString) { this.appendRequestHeaderString = appendRequestHeaderString; } /** * @return the maxLengthOfMultiBody */ public int getMaxLengthOfMultiBody() { return maxLengthOfMultiBody; } /** * @param maxLengthOfMultiBody the maxLengthOfMultiBody to set */ public void setMaxLengthOfMultiBody(int maxLengthOfMultiBody) { this.maxLengthOfMultiBody = maxLengthOfMultiBody; } public HttpResponse getRespForBlackIp() { return respForBlackIp; } public void setRespForBlackIp(HttpResponse respForBlackIp) { this.respForBlackIp = respForBlackIp; } /** * @param checkHost * @author tanyaowu */ public void setCheckHost(boolean checkHost) { this.checkHost = checkHost; } public void setCompatible1_0(boolean compatible1_0) { this.compatible1_0 = compatible1_0; } public boolean isPageInClasspath() { return pageInClasspath; } public void setPageInClasspath(boolean pageInClasspath) { this.pageInClasspath = pageInClasspath; } public SessionRateLimiter getSessionRateLimiter() { return sessionRateLimiter; } public void setSessionRateLimiter(SessionRateLimiter sessionRateLimiter) { this.sessionRateLimiter = sessionRateLimiter; } public int getMaxForwardCount() { return maxForwardCount; } public void setMaxForwardCount(int maxForwardCount) { this.maxForwardCount = maxForwardCount; } public int getMaxLengthOfPostBody() { return maxLengthOfPostBody; } public void setMaxLengthOfPostBody(int maxLengthOfPostBody) { this.maxLengthOfPostBody = maxLengthOfPostBody; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } public String getJsonpParamName() { return jsonpParamName; } public void setJsonpParamName(String jsonpParamName) { this.jsonpParamName = jsonpParamName; } public boolean isMonitorFileChange() { return monitorFileChange; } public void setMonitorFileChange(boolean monitorFileChange) { this.monitorFileChange = monitorFileChange; } }
UTF-8
Java
29,754
java
HttpConfig.java
Java
[ { "context": "port org.tio.utils.hutool.StrUtil;\n\n/**\n * @author tanyaowu\n * 2017年8月15日 下午1:21:14\n */\npublic class HttpConf", "end": 11279, "score": 0.9995402097702026, "start": 11271, "tag": "USERNAME", "value": "tanyaowu" }, { "context": "vate String\t\t\t\t\t\t\tbindIp\t\t\t\t\t\t= null;\t\t\t\t\t\t\t\t\t\t//\"127.0.0.1\";\n\t/**\n\t * 监听端口\n\t */\n\tprivate Integer\t\t\t\t\t\t\tbindP", "end": 13102, "score": 0.9997765421867371, "start": 13093, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": " 域名和页面根目录映射。当客户端通过不同域名访问时,其页面根目录是不一样的<br>\n\t * key: www.t-io.org<br>\n\t * value: 域名对应的页面根目录<br>\n\t */\n\tprivate volat", "end": 14943, "score": 0.9119148254394531, "start": 14931, "tag": "KEY", "value": "www.t-io.org" }, { "context": "html\n\t * @return\n\t * @throws Exception\n\t * @author tanyaowu\n\t */\n\tpublic HttpResource getResource(HttpRequest", "end": 17296, "score": 0.8639867305755615, "start": 17288, "tag": "USERNAME", "value": "tanyaowu" }, { "context": "asspath:\"开头,则从classpath中查找,否则视为普通的文件路径\n\t * @author tanyaowu\n\t * @throws IOException \n\t */\n\tpublic void setPag", "end": 22250, "score": 0.9979047179222107, "start": 22242, "tag": "USERNAME", "value": "tanyaowu" }, { "context": "BlackIp;\n\t}\n\n\t/**\n\t * @param checkHost\n\t * @author tanyaowu\n\t */\n\tpublic void setCheckHost(boolean checkHost)", "end": 27112, "score": 0.9249458312988281, "start": 27104, "tag": "USERNAME", "value": "tanyaowu" } ]
null
[]
/* Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: You must give any other recipients of the Work or Derivative Works a copy of this License; and You must cause any modified files to carry prominent notices stating that You changed the files; and You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2020 t-io 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.tio.http.common; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.tio.http.common.handler.HttpRequestHandler; import org.tio.http.common.session.HttpSession; import org.tio.http.common.session.id.ISessionIdGenerator; import org.tio.http.common.session.limiter.SessionRateLimiter; import org.tio.http.common.view.freemarker.FreemarkerConfig; import org.tio.utils.cache.ICache; import org.tio.utils.hutool.FileUtil; import org.tio.utils.hutool.StrUtil; /** * @author tanyaowu * 2017年8月15日 下午1:21:14 */ public class HttpConfig { private static Logger log = LoggerFactory.getLogger(HttpConfig.class); /** * 用于覆盖session cookie的参数名,客户端可以用这个传递sessionid */ public static final String TIO_HTTP_SESSIONID = "tio_http_sessionid"; /** * 存放HttpSession对象的cacheName */ public static final String SESSION_CACHE_NAME = "tio-h-s"; /** * 存放sessionId的cookie value */ public static final String SESSION_COOKIE_NAME = "PHPSESSID"; /** * session默认的超时时间,单位:秒 */ public static final long DEFAULT_SESSION_TIMEOUT = 30 * 60; /** * 默认的静态资源缓存时间,单位:秒 */ public static final int MAX_LIVETIME_OF_STATICRES = 60 * 10; /** * 文件上传时,boundary值的最大长度 */ public static final int MAX_LENGTH_OF_BOUNDARY = 512; /** * 文件上传时,头部的最大长度 */ public static final int MAX_LENGTH_OF_MULTI_HEADER = 512; /** * 文件上传时,体的最大长度(默认值2M) */ public static final int MAX_LENGTH_OF_MULTI_BODY = 1024 * 1024 * 2; /** * 文件上传时,体的最大长度 */ private int maxLengthOfMultiBody = MAX_LENGTH_OF_MULTI_BODY; /** *POST体的最大长度默认值(2M) */ public static final int MAX_LENGTH_OF_POST_BODY = 1024 * 1024 * 2; /** * jsonp时,回调参数名 */ public static final String JSONP_PARAM_NAME = "tio_http_jsonp"; /** * POST体的最大长度 */ private int maxLengthOfPostBody = MAX_LENGTH_OF_POST_BODY; public static final int MAX_FORWARD_COUNT = 10; public int maxForwardCount = MAX_FORWARD_COUNT; /** * 是否使用session */ private boolean useSession = true; /** * 是否兼容1.0 * true:兼容 * false:不兼容 * 默认兼容 */ public boolean compatible1_0 = true; /** * 是否拼接http request header value * */ private boolean appendRequestHeaderString = false; private String bindIp = null; //"127.0.0.1"; /** * 监听端口 */ private Integer bindPort = 80; private String serverInfo = HttpConst.SERVER_INFO; private String charset = HttpConst.CHARSET_NAME; private ICache sessionStore = null; public SessionRateLimiter sessionRateLimiter; /** * 访问路径前缀,譬如"/api" */ private String contextPath = ""; /** * 加后缀,譬如".php" */ private String suffix = ""; /** * 如果访问路径是以"/"结束,则实际访问路径会自动加上welcomeFile,从而变成形如"/index.html"的路径 */ private String welcomeFile = null; //"index.html"; /** * 允许访问的域名,如果不限制,则为null */ private String[] allowDomains = null; /** * 存放HttpSession对象的cacheName */ private String sessionCacheName = SESSION_CACHE_NAME; /** * session超时时间,单位:秒 */ private long sessionTimeout = DEFAULT_SESSION_TIMEOUT; private String sessionCookieName = SESSION_COOKIE_NAME; /** * 静态资源缓存时间,如果小于等于0则不缓存,单位:秒 */ private int maxLiveTimeOfStaticRes = MAX_LIVETIME_OF_STATICRES; private String page404 = "/404.html"; private String page500 = "/500.html"; private ISessionIdGenerator sessionIdGenerator; private HttpRequestHandler httpRequestHandler; /** * ip被拉黑时,服务器给的响应,如果是null,服务器会直接断开连接 */ private HttpResponse respForBlackIp = null; /** * 是否被代理 */ private boolean isProxied = false; /** * 示例: * 1、classpath中:classpath:page * 2、绝对路径:/page */ private String pageRoot = null; //FileUtil.getAbsolutePath("page");//"/page"; private boolean pageInClasspath = false; /** * 临时支持freemarker,主要用于开发环境中的前端开发,暂时不重点作为tio-http-server功能<br> * 请大家暂时不要使用该功能,因为api随时会变 */ private FreemarkerConfig freemarkerConfig = null; /** * 域名和页面根目录映射。当客户端通过不同域名访问时,其页面根目录是不一样的<br> * key: www.t-io.org<br> * value: 域名对应的页面根目录<br> */ private volatile Map<String, String> domainPageMap = null; //new HashMap<>(); public boolean checkHost = true; private String name = null; /** * jsonp时,回调参数名 */ private String jsonpParamName = JSONP_PARAM_NAME; /** * 是否监控文件变化 */ public boolean monitorFileChange = false; public Map<String, String> getDomainPageMap() { return domainPageMap; } public HttpConfig(Integer bindPort, boolean useSession) { this.bindPort = bindPort; this.useSession = useSession; } /** * * @param bindPort * @param sessionTimeout session超时时间,单位:秒 * @param contextPath * @param suffix */ public HttpConfig(Integer bindPort, Long sessionTimeout, String contextPath, String suffix) { this.bindPort = bindPort; if (sessionTimeout != null) { this.sessionTimeout = sessionTimeout; } if (contextPath == null) { contextPath = ""; } this.contextPath = contextPath; if (suffix == null) { suffix = ""; } this.suffix = suffix; } /** * @return the bindIp */ public String getBindIp() { return bindIp; } /** * @return the bindPort */ public Integer getBindPort() { return bindPort; } /** * @return the charset */ public String getCharset() { return charset; } /** * @return the maxLiveTimeOfStaticRes */ public int getMaxLiveTimeOfStaticRes() { return maxLiveTimeOfStaticRes; } public String getPage404() { return page404; } public String getPage500() { return page500; } /** * @return the pageRoot */ public String getPageRoot() { return pageRoot; } public String getPageRoot(HttpRequest request) { if (domainPageMap == null || domainPageMap.isEmpty()) { return pageRoot; } String domain = request.getDomain(); String root = domainPageMap.get(domain); if (root != null) { return root; } Set<Entry<String, String>> set = domainPageMap.entrySet(); for (Entry<String, String> entry : set) { String d = entry.getKey(); if (d.startsWith(".") && domain.endsWith(d)) { String file = entry.getValue(); domainPageMap.put(domain, file); return file; } } domainPageMap.put(domain, pageRoot); return pageRoot; } /** * * @param request * @param path 形如 /xx/aa.html * @return * @throws Exception * @author tanyaowu */ public HttpResource getResource(HttpRequest request, String path) throws Exception { String pageRoot = getPageRoot(request); HttpResource httpResource = null; // File file = null; if (pageRoot != null) { if (StrUtil.endWith(path, "/")) { path = path + "index.html"; } String complatePath = pageRoot + path; if (pageInClasspath) { URL url = this.getClass().getClassLoader().getResource(complatePath); if (url != null) { String protocol = url.getProtocol(); if (Objects.equals(protocol, "jar")) { InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(complatePath); httpResource = new HttpResource(path, inputStream, null); } else { File file = new File(url.toURI()); if (file.exists()) { httpResource = new HttpResource(path, null, file); } } } } else { File file = new File(complatePath); if (file.exists()) { httpResource = new HttpResource(path, null, file); } } } return httpResource; } /** * @return the serverInfo */ public String getServerInfo() { return serverInfo; } /** * @return the sessionCacheName */ public String getSessionCacheName() { return sessionCacheName; } public String getSessionCookieName() { return sessionCookieName; } // public void setSessionTimeout(long sessionTimeout) { // this.sessionTimeout = sessionTimeout; // } public ISessionIdGenerator getSessionIdGenerator() { return sessionIdGenerator; } public ICache getSessionStore() { return sessionStore; } public long getSessionTimeout() { return sessionTimeout; } /** * @param bindIp the bindIp to set */ public void setBindIp(String bindIp) { this.bindIp = bindIp; } /** * @param charset the charset to set */ public void setCharset(String charset) { this.charset = charset; } /** * @param maxLiveTimeOfStaticRes the maxLiveTimeOfStaticRes to set */ public void setMaxLiveTimeOfStaticRes(int maxLiveTimeOfStaticRes) { this.maxLiveTimeOfStaticRes = maxLiveTimeOfStaticRes; } public void setPage404(String page404) { this.page404 = page404; } public void setPage500(String page500) { this.page500 = page500; } /** * 静态文件路径,必须先设置好pageRoot后再用 * key: 文件名后缀 * path: 访问路径 如 /user/set.html */ private Map<String, Set<String>> staticPathsMap = null; /** * path: 访问路径 如 /user/set.html */ private Set<String> staticPaths = null; public Map<String, Set<String>> getStaticPathsMap() { initStaticPaths(); return staticPathsMap; } public Set<String> getStaticPaths() { initStaticPaths(); return staticPaths; } private Map<String, Set<String>> initStaticPaths() { if (staticPathsMap != null) { return staticPathsMap; } if (pageInClasspath) { throw new RuntimeException("classpath的pageRoot是"); } staticPathsMap = new TreeMap<>(); staticPaths = new TreeSet<>(); List<File> files = FileUtil.loopFiles(pageRoot, new FileFilter() { @Override public boolean accept(File file) { String filename = file.getName(); String ext = FileUtil.extName(filename);//.getExtension(filename); if (file.isDirectory()) { if ("svn-base".equalsIgnoreCase(ext)) { return false; } return true; } // String ext = FileUtil.extName(file); return true; } }); if (files == null) { return staticPathsMap; } if (log.isInfoEnabled()) { log.info("一共{}个文件", files.size()); } File pageRootFile = new File(pageRoot); String pageRootAbs; try { pageRootAbs = pageRootFile.getCanonicalPath(); } catch (IOException e1) { log.error(e1.toString(), e1); return null; } for (File file : files) { try { if (file.isDirectory()) { } else { String absPath = file.getCanonicalPath(); // long start = System.currentTimeMillis(); String path = absPath.substring(pageRootAbs.length()); path = path.replaceAll("\\\\", "/"); if (!(path.startsWith("/"))) { path = "/" + path; } log.info("访问路径:{}", path); String ext = FileUtil.extName(path); Set<String> set = staticPathsMap.get(ext); if (set == null) { set = new TreeSet<>(); staticPathsMap.put(ext, set); } set.add(path); staticPaths.add(path); } } catch (Exception e) { log.error(e.toString()); } } return staticPathsMap; } /** * 获取文件的URL访问路径 * @param file * @return * @throws IOException */ public String getPath(File file) throws IOException { String absPath = file.getCanonicalPath(); File pageRootFile = new File(pageRoot); String pageRootAbs = pageRootFile.getCanonicalPath(); String path = absPath.substring(pageRootAbs.length()); path = path.replaceAll("\\\\", "/"); if (!(path.startsWith("/"))) { path = "/" + path; } return path; } /** * * @param pageRoot 如果是以"classpath:"开头,则从classpath中查找,否则视为普通的文件路径 * @author tanyaowu * @throws IOException */ public void setPageRoot(String pageRoot) throws IOException { staticPathsMap = null; if (StrUtil.startWith(pageRoot, "classpath:")) { this.pageRoot = pageRoot.substring("classpath:".length());//.replaceFirst("classpath:", "classpath:/"); if (this.pageRoot.startsWith("/")) { this.pageRoot = this.pageRoot.substring(1); } this.pageInClasspath = true; } else { this.pageRoot = pageRoot;//fromPath(pageRoot); } } /** * * @param path 如果是以"classpath:"开头,则从classpath中查找,否则视为普通的文件路径 * @return */ // public static File fromPath(String path) { // if (path == null) { // return null; // } // // if (StrUtil.startWithIgnoreCase(path, "classpath:")) { // return new File(ResourceUtil.getAbsolutePath(path)); // } else { // return new File(path); // } // } /** * * @param domain 形如www.t-io.org的域名,也可以是形如.t-io.org这样的通配域名 * @param pageRoot 如果是以"classpath:"开头,则从classpath中查找,否则视为普通的文件路径 * @throws IOException */ public void addDomainPage(String domain, String pageRoot) throws IOException { // File pageRootFile = fromPath(pageRoot); // if (!pageRootFile.exists()) { // throw new IOException("文件【" + pageRoot + "】不存在"); // } // // if (!pageRootFile.isDirectory()) { // throw new IOException("文件【" + pageRoot + "】不是目录"); // } if (domainPageMap == null) { synchronized (this) { if (domainPageMap == null) { domainPageMap = new HashMap<>(); } } } domainPageMap.put(domain, pageRoot); if (this.freemarkerConfig != null) { freemarkerConfig.addDomainConfiguration(domain, pageRoot); } } /** * @param serverInfo the serverInfo to set */ public void setServerInfo(String serverInfo) { this.serverInfo = serverInfo; } /** * @param sessionCacheName the sessionCacheName to set */ public void setSessionCacheName(String sessionCacheName) { this.sessionCacheName = sessionCacheName; } public void setSessionCookieName(String sessionCookieName) { this.sessionCookieName = sessionCookieName; } public void setSessionIdGenerator(ISessionIdGenerator sessionIdGenerator) { this.sessionIdGenerator = sessionIdGenerator; } public void setSessionStore(ICache sessionStore) { this.sessionStore = sessionStore; // this.httpSessionManager = HttpSessionManager.getInstance(sessionStore); } /** * @return the httpRequestHandler */ public HttpRequestHandler getHttpRequestHandler() { return httpRequestHandler; } /** * @param httpRequestHandler the httpRequestHandler to set */ public void setHttpRequestHandler(HttpRequestHandler httpRequestHandler) { this.httpRequestHandler = httpRequestHandler; } public String getContextPath() { return contextPath; } public String getSuffix() { return suffix; } public String[] getAllowDomains() { return allowDomains; } public void setAllowDomains(String[] allowDomains) { this.allowDomains = allowDomains; } /** * @return the isProxied */ public boolean isProxied() { return isProxied; } /** * @param isProxied the isProxied to set */ public void setProxied(boolean isProxied) { this.isProxied = isProxied; } public boolean isUseSession() { return useSession; } public void setUseSession(boolean useSession) { this.useSession = useSession; } /** * 根据sessionId获取HttpSession对象 * @param sessionId * @return */ public HttpSession getHttpSession(String sessionId) { if (StrUtil.isBlank(sessionId)) { return null; } HttpSession httpSession = (HttpSession) getSessionStore().get(sessionId); return httpSession; } public String getWelcomeFile() { return welcomeFile; } public void setWelcomeFile(String welcomeFile) { this.welcomeFile = welcomeFile; } public FreemarkerConfig getFreemarkerConfig() { return freemarkerConfig; } public void setFreemarkerConfig(FreemarkerConfig freemarkerConfig) { this.freemarkerConfig = freemarkerConfig; } /** * @return the appendRequestHeaderString */ public boolean isAppendRequestHeaderString() { return appendRequestHeaderString; } /** * @param appendRequestHeaderString the appendRequestHeaderString to set */ public void setAppendRequestHeaderString(boolean appendRequestHeaderString) { this.appendRequestHeaderString = appendRequestHeaderString; } /** * @return the maxLengthOfMultiBody */ public int getMaxLengthOfMultiBody() { return maxLengthOfMultiBody; } /** * @param maxLengthOfMultiBody the maxLengthOfMultiBody to set */ public void setMaxLengthOfMultiBody(int maxLengthOfMultiBody) { this.maxLengthOfMultiBody = maxLengthOfMultiBody; } public HttpResponse getRespForBlackIp() { return respForBlackIp; } public void setRespForBlackIp(HttpResponse respForBlackIp) { this.respForBlackIp = respForBlackIp; } /** * @param checkHost * @author tanyaowu */ public void setCheckHost(boolean checkHost) { this.checkHost = checkHost; } public void setCompatible1_0(boolean compatible1_0) { this.compatible1_0 = compatible1_0; } public boolean isPageInClasspath() { return pageInClasspath; } public void setPageInClasspath(boolean pageInClasspath) { this.pageInClasspath = pageInClasspath; } public SessionRateLimiter getSessionRateLimiter() { return sessionRateLimiter; } public void setSessionRateLimiter(SessionRateLimiter sessionRateLimiter) { this.sessionRateLimiter = sessionRateLimiter; } public int getMaxForwardCount() { return maxForwardCount; } public void setMaxForwardCount(int maxForwardCount) { this.maxForwardCount = maxForwardCount; } public int getMaxLengthOfPostBody() { return maxLengthOfPostBody; } public void setMaxLengthOfPostBody(int maxLengthOfPostBody) { this.maxLengthOfPostBody = maxLengthOfPostBody; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } public String getJsonpParamName() { return jsonpParamName; } public void setJsonpParamName(String jsonpParamName) { this.jsonpParamName = jsonpParamName; } public boolean isMonitorFileChange() { return monitorFileChange; } public void setMonitorFileChange(boolean monitorFileChange) { this.monitorFileChange = monitorFileChange; } }
29,754
0.719461
0.714141
981
28.123344
27.131952
106
false
false
0
0
0
0
0
0
2.268094
false
false
9
382700b31702839f55bf5f2d794318ec672738b9
22,978,075,082,732
b8adeb52b9b507f4ad3e2ffa73a779234d6b3a5e
/hms/src/com/mysoft/hms/SellComparator.java
e7d161b6346b5e7fcd0a0cc0707d27afd77eb78c
[]
no_license
nikalala/hmsnew
https://github.com/nikalala/hmsnew
242d065aa952581b6a3c4dc8927ff59f63f00556
453d649077cc0e869c8141b967600c7efb337e27
refs/heads/master
2021-01-14T08:16:57.818000
2015-05-05T08:44:07
2015-05-05T08:44:07
33,726,507
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// -------------------------------------------------------- // Generated by sql2java - http://sql2java.sourceforge.net/ // jdbc driver used at code generation time: org.postgresql.Driver // // Please help us improve this tool by reporting: // problems, // suggestions, // feedbacks, // ideas, // to http://sourceforge.net/projects/sql2java/ // -------------------------------------------------------- package com.mysoft.hms; import java.util.Comparator; // imports+ // imports- /** * Comparator class is used to sort the SellBean objects. */ public class SellComparator implements Comparator // extends+ // extends- { /** * Holds the field on which the comparison is performed. */ private int iType; /** * Value that will contain the information about the order of the sort: normal or reversal. */ private boolean bReverse; /** * Constructor class for SellComparator. * <br> * Example: * <br> * <code>Arrays.sort(pArray, new SellComparator(SellManager.SELLID, bReverse));<code> * * @param iType the field from which you want to sort * <br> * Possible values are: * <ul> * <li>SellManager.ID_SELLID * <li>SellManager.ID_CUSTOMERID * <li>SellManager.ID_SELLTYPEID * <li>SellManager.ID_SELLDATE * <li>SellManager.ID_SPRODUCTID * <li>SellManager.ID_PRICE * </ul> */ public SellComparator(int iType) { this(iType, false); } /** * Constructor class for SellComparator. * <br> * Example: * <br> * <code>Arrays.sort(pArray, new SellComparator(SellManager.SELLID, bReverse));<code> * * @param iType the field from which you want to sort. * <br> * Possible values are: * <ul> * <li>SellManager.ID_SELLID * <li>SellManager.ID_CUSTOMERID * <li>SellManager.ID_SELLTYPEID * <li>SellManager.ID_SELLDATE * <li>SellManager.ID_SPRODUCTID * <li>SellManager.ID_PRICE * </ul> * * @param bReverse set this value to true, if you want to reverse the sorting results */ public SellComparator(int iType, boolean bReverse) { this.iType = iType; this.bReverse = bReverse; } /** * Implementation of the compare method. */ public int compare(Object pObj1, Object pObj2) { SellBean b1 = (SellBean)pObj1; SellBean b2 = (SellBean)pObj2; int iReturn = 0; switch(iType) { case SellManager.ID_SELLID: if (b1.getSellid() == null && b2.getSellid() != null) { iReturn = -1; } else if (b1.getSellid() == null && b2.getSellid() == null) { iReturn = 0; } else if (b1.getSellid() != null && b2.getSellid() == null) { iReturn = 1; } else { iReturn = b1.getSellid().compareTo(b2.getSellid()); } break; case SellManager.ID_CUSTOMERID: if (b1.getCustomerid() == null && b2.getCustomerid() != null) { iReturn = -1; } else if (b1.getCustomerid() == null && b2.getCustomerid() == null) { iReturn = 0; } else if (b1.getCustomerid() != null && b2.getCustomerid() == null) { iReturn = 1; } else { iReturn = b1.getCustomerid().compareTo(b2.getCustomerid()); } break; case SellManager.ID_SELLTYPEID: if (b1.getSelltypeid() == null && b2.getSelltypeid() != null) { iReturn = -1; } else if (b1.getSelltypeid() == null && b2.getSelltypeid() == null) { iReturn = 0; } else if (b1.getSelltypeid() != null && b2.getSelltypeid() == null) { iReturn = 1; } else { iReturn = b1.getSelltypeid().compareTo(b2.getSelltypeid()); } break; case SellManager.ID_SELLDATE: if (b1.getSelldate() == null && b2.getSelldate() != null) { iReturn = -1; } else if (b1.getSelldate() == null && b2.getSelldate() == null) { iReturn = 0; } else if (b1.getSelldate() != null && b2.getSelldate() == null) { iReturn = 1; } else { iReturn = b1.getSelldate().compareTo(b2.getSelldate()); } break; case SellManager.ID_SPRODUCTID: if (b1.getSproductid() == null && b2.getSproductid() != null) { iReturn = -1; } else if (b1.getSproductid() == null && b2.getSproductid() == null) { iReturn = 0; } else if (b1.getSproductid() != null && b2.getSproductid() == null) { iReturn = 1; } else { iReturn = b1.getSproductid().compareTo(b2.getSproductid()); } break; case SellManager.ID_PRICE: if (b1.getPrice() == null && b2.getPrice() != null) { iReturn = -1; } else if (b1.getPrice() == null && b2.getPrice() == null) { iReturn = 0; } else if (b1.getPrice() != null && b2.getPrice() == null) { iReturn = 1; } else { iReturn = b1.getPrice().compareTo(b2.getPrice()); } break; default: throw new IllegalArgumentException("Type passed for the field is not supported"); } return bReverse ? (-1 * iReturn) : iReturn; } // class+ // class- }
UTF-8
Java
5,921
java
SellComparator.java
Java
[]
null
[]
// -------------------------------------------------------- // Generated by sql2java - http://sql2java.sourceforge.net/ // jdbc driver used at code generation time: org.postgresql.Driver // // Please help us improve this tool by reporting: // problems, // suggestions, // feedbacks, // ideas, // to http://sourceforge.net/projects/sql2java/ // -------------------------------------------------------- package com.mysoft.hms; import java.util.Comparator; // imports+ // imports- /** * Comparator class is used to sort the SellBean objects. */ public class SellComparator implements Comparator // extends+ // extends- { /** * Holds the field on which the comparison is performed. */ private int iType; /** * Value that will contain the information about the order of the sort: normal or reversal. */ private boolean bReverse; /** * Constructor class for SellComparator. * <br> * Example: * <br> * <code>Arrays.sort(pArray, new SellComparator(SellManager.SELLID, bReverse));<code> * * @param iType the field from which you want to sort * <br> * Possible values are: * <ul> * <li>SellManager.ID_SELLID * <li>SellManager.ID_CUSTOMERID * <li>SellManager.ID_SELLTYPEID * <li>SellManager.ID_SELLDATE * <li>SellManager.ID_SPRODUCTID * <li>SellManager.ID_PRICE * </ul> */ public SellComparator(int iType) { this(iType, false); } /** * Constructor class for SellComparator. * <br> * Example: * <br> * <code>Arrays.sort(pArray, new SellComparator(SellManager.SELLID, bReverse));<code> * * @param iType the field from which you want to sort. * <br> * Possible values are: * <ul> * <li>SellManager.ID_SELLID * <li>SellManager.ID_CUSTOMERID * <li>SellManager.ID_SELLTYPEID * <li>SellManager.ID_SELLDATE * <li>SellManager.ID_SPRODUCTID * <li>SellManager.ID_PRICE * </ul> * * @param bReverse set this value to true, if you want to reverse the sorting results */ public SellComparator(int iType, boolean bReverse) { this.iType = iType; this.bReverse = bReverse; } /** * Implementation of the compare method. */ public int compare(Object pObj1, Object pObj2) { SellBean b1 = (SellBean)pObj1; SellBean b2 = (SellBean)pObj2; int iReturn = 0; switch(iType) { case SellManager.ID_SELLID: if (b1.getSellid() == null && b2.getSellid() != null) { iReturn = -1; } else if (b1.getSellid() == null && b2.getSellid() == null) { iReturn = 0; } else if (b1.getSellid() != null && b2.getSellid() == null) { iReturn = 1; } else { iReturn = b1.getSellid().compareTo(b2.getSellid()); } break; case SellManager.ID_CUSTOMERID: if (b1.getCustomerid() == null && b2.getCustomerid() != null) { iReturn = -1; } else if (b1.getCustomerid() == null && b2.getCustomerid() == null) { iReturn = 0; } else if (b1.getCustomerid() != null && b2.getCustomerid() == null) { iReturn = 1; } else { iReturn = b1.getCustomerid().compareTo(b2.getCustomerid()); } break; case SellManager.ID_SELLTYPEID: if (b1.getSelltypeid() == null && b2.getSelltypeid() != null) { iReturn = -1; } else if (b1.getSelltypeid() == null && b2.getSelltypeid() == null) { iReturn = 0; } else if (b1.getSelltypeid() != null && b2.getSelltypeid() == null) { iReturn = 1; } else { iReturn = b1.getSelltypeid().compareTo(b2.getSelltypeid()); } break; case SellManager.ID_SELLDATE: if (b1.getSelldate() == null && b2.getSelldate() != null) { iReturn = -1; } else if (b1.getSelldate() == null && b2.getSelldate() == null) { iReturn = 0; } else if (b1.getSelldate() != null && b2.getSelldate() == null) { iReturn = 1; } else { iReturn = b1.getSelldate().compareTo(b2.getSelldate()); } break; case SellManager.ID_SPRODUCTID: if (b1.getSproductid() == null && b2.getSproductid() != null) { iReturn = -1; } else if (b1.getSproductid() == null && b2.getSproductid() == null) { iReturn = 0; } else if (b1.getSproductid() != null && b2.getSproductid() == null) { iReturn = 1; } else { iReturn = b1.getSproductid().compareTo(b2.getSproductid()); } break; case SellManager.ID_PRICE: if (b1.getPrice() == null && b2.getPrice() != null) { iReturn = -1; } else if (b1.getPrice() == null && b2.getPrice() == null) { iReturn = 0; } else if (b1.getPrice() != null && b2.getPrice() == null) { iReturn = 1; } else { iReturn = b1.getPrice().compareTo(b2.getPrice()); } break; default: throw new IllegalArgumentException("Type passed for the field is not supported"); } return bReverse ? (-1 * iReturn) : iReturn; } // class+ // class- }
5,921
0.48708
0.474075
176
32.642044
26.490612
97
false
false
0
0
0
0
0
0
0.318182
false
false
9
2a27fbdd4a104fadfcb2e8e53bad0bbd24d38c05
9,964,324,170,114
078248872fef2b34a78c7f854b21c06f7d4346fa
/src/main/java/io/github/ghacupha/fassets/web/rest/DepreciationResource.java
ad6480c6dfc4cdd8bdadfc6b9b5e3bafdf9485a1
[]
no_license
ghacupha/fassets
https://github.com/ghacupha/fassets
21ab074ee3b315866f5d8813613b3af7dcdc0b2a
e5333523e0f726d1744f0782657ba38f91c8a5de
refs/heads/master
2021-05-09T14:16:38.081000
2019-03-04T10:39:16
2019-03-04T10:39:16
119,056,645
0
0
null
false
2018-04-15T10:05:26
2018-01-26T13:48:15
2018-04-15T09:48:02
2018-04-15T10:05:26
4,825
0
0
9
Java
false
null
package io.github.ghacupha.fassets.web.rest; import io.github.ghacupha.fassets.service.DepreciationService; import io.github.ghacupha.fassets.web.rest.errors.BadRequestAlertException; import io.github.ghacupha.fassets.web.rest.util.HeaderUtil; import io.github.ghacupha.fassets.web.rest.util.PaginationUtil; import io.github.ghacupha.fassets.service.dto.DepreciationDTO; import io.github.ghacupha.fassets.service.dto.DepreciationCriteria; import io.github.ghacupha.fassets.service.DepreciationQueryService; import io.github.jhipster.web.util.ResponseUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.Optional; import java.util.stream.StreamSupport; /** * REST controller for managing Depreciation. */ @RestController @RequestMapping("/api") public class DepreciationResource { private final Logger log = LoggerFactory.getLogger(DepreciationResource.class); private static final String ENTITY_NAME = "depreciation"; private final DepreciationService depreciationService; private final DepreciationQueryService depreciationQueryService; public DepreciationResource(DepreciationService depreciationService, DepreciationQueryService depreciationQueryService) { this.depreciationService = depreciationService; this.depreciationQueryService = depreciationQueryService; } /** * POST /depreciations : Create a new depreciation. * * @param depreciationDTO the depreciationDTO to create * @return the ResponseEntity with status 201 (Created) and with body the new depreciationDTO, or with status 400 (Bad Request) if the depreciation has already an ID * @throws URISyntaxException if the Location URI syntax is incorrect */ @PostMapping("/depreciations") public ResponseEntity<DepreciationDTO> createDepreciation(@Valid @RequestBody DepreciationDTO depreciationDTO) throws URISyntaxException { log.debug("REST request to save Depreciation : {}", depreciationDTO); if (depreciationDTO.getId() != null) { throw new BadRequestAlertException("A new depreciation cannot already have an ID", ENTITY_NAME, "idexists"); } DepreciationDTO result = depreciationService.save(depreciationDTO); return ResponseEntity.created(new URI("/api/depreciations/" + result.getId())) .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString())) .body(result); } /** * PUT /depreciations : Updates an existing depreciation. * * @param depreciationDTO the depreciationDTO to update * @return the ResponseEntity with status 200 (OK) and with body the updated depreciationDTO, * or with status 400 (Bad Request) if the depreciationDTO is not valid, * or with status 500 (Internal Server Error) if the depreciationDTO couldn't be updated * @throws URISyntaxException if the Location URI syntax is incorrect */ @PutMapping("/depreciations") public ResponseEntity<DepreciationDTO> updateDepreciation(@Valid @RequestBody DepreciationDTO depreciationDTO) throws URISyntaxException { log.debug("REST request to update Depreciation : {}", depreciationDTO); if (depreciationDTO.getId() == null) { throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); } DepreciationDTO result = depreciationService.save(depreciationDTO); return ResponseEntity.ok() .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, depreciationDTO.getId().toString())) .body(result); } /** * GET /depreciations : get all the depreciations. * * @param pageable the pagination information * @param criteria the criterias which the requested entities should match * @return the ResponseEntity with status 200 (OK) and the list of depreciations in body */ @GetMapping("/depreciations") public ResponseEntity<List<DepreciationDTO>> getAllDepreciations(DepreciationCriteria criteria, Pageable pageable) { log.debug("REST request to get Depreciations by criteria: {}", criteria); Page<DepreciationDTO> page = depreciationQueryService.findByCriteria(criteria, pageable); HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/depreciations"); return ResponseEntity.ok().headers(headers).body(page.getContent()); } /** * GET /depreciations/count : count all the depreciations. * * @param criteria the criterias which the requested entities should match * @return the ResponseEntity with status 200 (OK) and the count in body */ @GetMapping("/depreciations/count") public ResponseEntity<Long> countDepreciations(DepreciationCriteria criteria) { log.debug("REST request to count Depreciations by criteria: {}", criteria); return ResponseEntity.ok().body(depreciationQueryService.countByCriteria(criteria)); } /** * GET /depreciations/:id : get the "id" depreciation. * * @param id the id of the depreciationDTO to retrieve * @return the ResponseEntity with status 200 (OK) and with body the depreciationDTO, or with status 404 (Not Found) */ @GetMapping("/depreciations/{id}") public ResponseEntity<DepreciationDTO> getDepreciation(@PathVariable Long id) { log.debug("REST request to get Depreciation : {}", id); Optional<DepreciationDTO> depreciationDTO = depreciationService.findOne(id); return ResponseUtil.wrapOrNotFound(depreciationDTO); } /** * DELETE /depreciations/:id : delete the "id" depreciation. * * @param id the id of the depreciationDTO to delete * @return the ResponseEntity with status 200 (OK) */ @DeleteMapping("/depreciations/{id}") public ResponseEntity<Void> deleteDepreciation(@PathVariable Long id) { log.debug("REST request to delete Depreciation : {}", id); depreciationService.delete(id); return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build(); } }
UTF-8
Java
6,515
java
DepreciationResource.java
Java
[ { "context": "package io.github.ghacupha.fassets.web.rest;\nimport io.github.ghacupha.fasse", "end": 26, "score": 0.974329948425293, "start": 18, "tag": "USERNAME", "value": "ghacupha" }, { "context": "ithub.ghacupha.fassets.web.rest;\nimport io.github.ghacupha.fassets.service.DepreciationService;\nimport io.gi", "end": 70, "score": 0.990691065788269, "start": 62, "tag": "USERNAME", "value": "ghacupha" }, { "context": "ets.service.DepreciationService;\nimport io.github.ghacupha.fassets.web.rest.errors.BadRequestAlertException;", "end": 133, "score": 0.9636968374252319, "start": 125, "tag": "USERNAME", "value": "ghacupha" }, { "context": "errors.BadRequestAlertException;\nimport io.github.ghacupha.fassets.web.rest.util.HeaderUtil;\nimport io.githu", "end": 209, "score": 0.9628340005874634, "start": 201, "tag": "USERNAME", "value": "ghacupha" }, { "context": "assets.web.rest.util.HeaderUtil;\nimport io.github.ghacupha.fassets.web.rest.util.PaginationUtil;\nimport io.g", "end": 269, "score": 0.955284059047699, "start": 261, "tag": "USERNAME", "value": "ghacupha" }, { "context": "ts.web.rest.util.PaginationUtil;\nimport io.github.ghacupha.fassets.service.dto.DepreciationDTO;\nimport io.gi", "end": 333, "score": 0.9863075017929077, "start": 325, "tag": "USERNAME", "value": "ghacupha" }, { "context": "ets.service.dto.DepreciationDTO;\nimport io.github.ghacupha.fassets.service.dto.DepreciationCriteria;\nimport ", "end": 396, "score": 0.9735985398292542, "start": 388, "tag": "USERNAME", "value": "ghacupha" }, { "context": "ervice.dto.DepreciationCriteria;\nimport io.github.ghacupha.fassets.service.DepreciationQueryService;\nimport ", "end": 464, "score": 0.9007095098495483, "start": 456, "tag": "USERNAME", "value": "ghacupha" } ]
null
[]
package io.github.ghacupha.fassets.web.rest; import io.github.ghacupha.fassets.service.DepreciationService; import io.github.ghacupha.fassets.web.rest.errors.BadRequestAlertException; import io.github.ghacupha.fassets.web.rest.util.HeaderUtil; import io.github.ghacupha.fassets.web.rest.util.PaginationUtil; import io.github.ghacupha.fassets.service.dto.DepreciationDTO; import io.github.ghacupha.fassets.service.dto.DepreciationCriteria; import io.github.ghacupha.fassets.service.DepreciationQueryService; import io.github.jhipster.web.util.ResponseUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.Optional; import java.util.stream.StreamSupport; /** * REST controller for managing Depreciation. */ @RestController @RequestMapping("/api") public class DepreciationResource { private final Logger log = LoggerFactory.getLogger(DepreciationResource.class); private static final String ENTITY_NAME = "depreciation"; private final DepreciationService depreciationService; private final DepreciationQueryService depreciationQueryService; public DepreciationResource(DepreciationService depreciationService, DepreciationQueryService depreciationQueryService) { this.depreciationService = depreciationService; this.depreciationQueryService = depreciationQueryService; } /** * POST /depreciations : Create a new depreciation. * * @param depreciationDTO the depreciationDTO to create * @return the ResponseEntity with status 201 (Created) and with body the new depreciationDTO, or with status 400 (Bad Request) if the depreciation has already an ID * @throws URISyntaxException if the Location URI syntax is incorrect */ @PostMapping("/depreciations") public ResponseEntity<DepreciationDTO> createDepreciation(@Valid @RequestBody DepreciationDTO depreciationDTO) throws URISyntaxException { log.debug("REST request to save Depreciation : {}", depreciationDTO); if (depreciationDTO.getId() != null) { throw new BadRequestAlertException("A new depreciation cannot already have an ID", ENTITY_NAME, "idexists"); } DepreciationDTO result = depreciationService.save(depreciationDTO); return ResponseEntity.created(new URI("/api/depreciations/" + result.getId())) .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString())) .body(result); } /** * PUT /depreciations : Updates an existing depreciation. * * @param depreciationDTO the depreciationDTO to update * @return the ResponseEntity with status 200 (OK) and with body the updated depreciationDTO, * or with status 400 (Bad Request) if the depreciationDTO is not valid, * or with status 500 (Internal Server Error) if the depreciationDTO couldn't be updated * @throws URISyntaxException if the Location URI syntax is incorrect */ @PutMapping("/depreciations") public ResponseEntity<DepreciationDTO> updateDepreciation(@Valid @RequestBody DepreciationDTO depreciationDTO) throws URISyntaxException { log.debug("REST request to update Depreciation : {}", depreciationDTO); if (depreciationDTO.getId() == null) { throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); } DepreciationDTO result = depreciationService.save(depreciationDTO); return ResponseEntity.ok() .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, depreciationDTO.getId().toString())) .body(result); } /** * GET /depreciations : get all the depreciations. * * @param pageable the pagination information * @param criteria the criterias which the requested entities should match * @return the ResponseEntity with status 200 (OK) and the list of depreciations in body */ @GetMapping("/depreciations") public ResponseEntity<List<DepreciationDTO>> getAllDepreciations(DepreciationCriteria criteria, Pageable pageable) { log.debug("REST request to get Depreciations by criteria: {}", criteria); Page<DepreciationDTO> page = depreciationQueryService.findByCriteria(criteria, pageable); HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/depreciations"); return ResponseEntity.ok().headers(headers).body(page.getContent()); } /** * GET /depreciations/count : count all the depreciations. * * @param criteria the criterias which the requested entities should match * @return the ResponseEntity with status 200 (OK) and the count in body */ @GetMapping("/depreciations/count") public ResponseEntity<Long> countDepreciations(DepreciationCriteria criteria) { log.debug("REST request to count Depreciations by criteria: {}", criteria); return ResponseEntity.ok().body(depreciationQueryService.countByCriteria(criteria)); } /** * GET /depreciations/:id : get the "id" depreciation. * * @param id the id of the depreciationDTO to retrieve * @return the ResponseEntity with status 200 (OK) and with body the depreciationDTO, or with status 404 (Not Found) */ @GetMapping("/depreciations/{id}") public ResponseEntity<DepreciationDTO> getDepreciation(@PathVariable Long id) { log.debug("REST request to get Depreciation : {}", id); Optional<DepreciationDTO> depreciationDTO = depreciationService.findOne(id); return ResponseUtil.wrapOrNotFound(depreciationDTO); } /** * DELETE /depreciations/:id : delete the "id" depreciation. * * @param id the id of the depreciationDTO to delete * @return the ResponseEntity with status 200 (OK) */ @DeleteMapping("/depreciations/{id}") public ResponseEntity<Void> deleteDepreciation(@PathVariable Long id) { log.debug("REST request to delete Depreciation : {}", id); depreciationService.delete(id); return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build(); } }
6,515
0.735073
0.730161
139
45.870502
37.433842
169
false
false
0
0
0
0
0
0
0.503597
false
false
9
6823e01518ad0537a319c2588a7a11631342304d
22,754,736,787,958
8ccd0514385a7b4a4b7ed784c5a369774fc2ad61
/Photons/src/ui/Photons.java
adb46b2dce6876d545178c1643608f3be67e1926
[]
no_license
dyeopensource/Photons
https://github.com/dyeopensource/Photons
37ca30cf643d76fa19dedc0174416f9d958b20dd
d6a1533e52621042661ec5c5d647373caf954674
refs/heads/master
2021-01-18T21:25:08.282000
2016-04-21T18:23:51
2016-04-21T18:23:51
21,876,231
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ui; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.text.SimpleDateFormat; import java.util.Date; import modell.FileImporter; import common.FileUtil; import common.MyLogger; public class Photons { public static final int errorCodeImportSourceFolderDoesNotExist = 1; public static final int errorCodeImportDestinationFolderDoesNotExist = 2; public static final int errorCodeFailedToCreateLogFile = 3; public static final int errorCodeLengthMismatch = 4; public static final int errorCodeHashMismatch = 5; public static final int errorCodeFailedToInsertFileIntoDatabase = 6; public static final int errorCodeFailedToAddSourcePathInformationToDatabase = 7; public static final int errorCodeFailedToGetFileInformationFromDatabase = 8; public static final int errorCodeUnsupportedDatabaseVersion = 9; public static final int errorCodeFailedToInsertFileGroupInformationIntoDatabase = 10; public static final int errorCodeFailedToInsertFileGroupAssignmentInformationIntoDatabase = 11; public static final int errorCodeDuplicateImportedFile = 12; public static final int errorCodeFileInsertionVerificationFailed = 13; public static final int errorCodeFailedToInsertFileInfoInformationIntoDatabase = 14; public static final int errorCodeCommandOrOptionDoesNotExist = 15; public static final int errorCodeWrongUsage = 16; public static final int errorCodeFailedToOpenOrCreateDatabase = 17; public static final int errorCodeDatabaseVersionCheckFailure = 18; public static final int errorCodeFailedToInsertFileTypeInformationIntoDatabase = 19; public static final int errorCodeFailedToGetFileTypeInformation = 20; public static final int errorCodeJDBCNotFound = 21; public static final int errorCodeSourceFolderUUIDReadingError = 22; private static final int actionShowUsage = 0; private static final int actionShowUI = 1; private static final int actionImport = 2; private static final int actionVerify = 3; private static final int actionCheck = 4; private static final SimpleDateFormat dateTimeFormatter = new SimpleDateFormat("yyyyMMdd-HHmmSS"); private static final String commandImport = "import"; private static final String commandVerify = "verify"; private static final String commandCheck = "check"; private static final String argSource = "source"; private static final String argDestination = "destination"; private static final String argTypes = "types"; private static final String usage = "\n" + "Usage:\n" + "\n" + "java -jar photons.jar [CommandLineParamaters]\n" + "\n" + "Command line parameters:\n" + "\n" + "import /source=<SourcePath> /destination=<DestinationPath> /types=<Types>\n" + "verify /source=<SourcePath> /destination=<DestinationPath> /types=<Types>\n" + "check /destination=<DestinationPath>\n" + "\n" + "Example:\n" + "\n" + "Importing jpg files:\n" + "java -jar photons.jar import /source=/media/store /destination=/home/myUser/pictures /types=jpg\n" + "Verifying that all jpg files were imported correctly:\n" + "java -jar photons.jar verify /source=/media/store /destination=/home/myUser/pictures /types=jpg\n" + "Checking consistency of the target path (e.g. after making a copy of it):\n" + "java -jar photons.jar check /destination=/home/myUser/pictures\n" ; private static String command = null; private static String sourcePath = null; private static String destinationPath = null; private static String[] types = null; private static int action = actionShowUsage; private static int errorCode = 0; // TODO: introduce command: fillmediatimestamp (this would analyse EXIF information etc. - update database information) /** * @param args */ public static void main(String[] args) { MyLogger.setLogLevel(MyLogger.logLevelInformation); InterpretCommandLineArguments(args); if (Photons.action == Photons.actionShowUsage) { MyLogger.displayInformationMessage(usage); System.exit(errorCode); } final Path logPath = Paths.get(Photons.destinationPath, String.format("actions_%s.txt", dateTimeFormatter.format(new Date()))); try { MyLogger.setLogFile(logPath); } catch (IOException e) { System.err.println(String.format("ERROR: Could not create logfile '%s'.", logPath)); e.printStackTrace(); System.exit(errorCodeFailedToCreateLogFile); } if (Photons.action == Photons.actionImport) { FileImporter fileImporter = new FileImporter(Photons.sourcePath, Photons.destinationPath, Photons.types); try { //String uuidPath = FileUtil.getDeviceBasedUniformPath(Photons.sourcePath, Photons.sourcePath); //String u2 = uuidPath; fileImporter.Import(); } catch (IOException e) { MyLogger.displayAndLogExceptionMessage(e, "Import failed"); } } else if (Photons.action == Photons.actionVerify) { FileImporter fileImporter = new FileImporter(Photons.sourcePath, Photons.destinationPath, Photons.types); try { if (fileImporter.Verify()) { MyLogger.displayAndLogInformationMessage("Verification success."); } else { MyLogger.displayAndLogErrorMessage("Verification failed."); } } catch (IOException e) { MyLogger.displayAndLogExceptionMessage(e, "Import failed"); } } else if (Photons.action == Photons.actionCheck) { // TODO: implement MyLogger.displayAndLogErrorMessage("Command [%s] is not implemented yet.", Photons.command); Photons.errorCode = errorCodeCommandOrOptionDoesNotExist; } if (Photons.errorCode != 0) { System.exit(Photons.errorCode); } MyLogger.displayAndLogInformationMessage("Done"); } /** * Interprets the command line arguments and sets the appropriate fields * @param args The command line arguments */ private static void InterpretCommandLineArguments(String[] args) { if (args.length == 0) { // This will show the UI. Not implemented yet Photons.action = Photons.actionShowUI; } else { for (int i = 0; i < args.length; i++) { String arg = args[i]; String lowerCaseArg = arg.toLowerCase(); if (lowerCaseArg.equals(Photons.commandImport)) { Photons.action = Photons.actionImport; } else if (lowerCaseArg.equals(Photons.commandVerify)) { Photons.action = Photons.actionVerify; } else if (lowerCaseArg.equals(Photons.commandCheck)) { Photons.action = Photons.actionCheck; } else if (lowerCaseArg.startsWith("/")) { int equationSignIndex = arg.indexOf("="); if (equationSignIndex > 0) { String valueName = lowerCaseArg.substring(1, equationSignIndex); String value = arg.substring(equationSignIndex + 1, arg.length()); if (valueName.equals(argSource)) { Photons.sourcePath = value; } else if (valueName.equals(argDestination)) { Photons.destinationPath = value; } else if (valueName.equals(argTypes)) { Photons.types = value.split(","); } } } else { MyLogger.displayErrorMessage("Command or option [%s] does not exist. Cannot proceed.", lowerCaseArg); errorCode = errorCodeCommandOrOptionDoesNotExist; } } if (Photons.action == Photons.actionImport) { CheckSourcePath(); CheckDestinationPath(); CheckTypes(); } else if (Photons.action == Photons.actionVerify) { CheckSourcePath(); CheckDestinationPath(); CheckTypes(); } else if (Photons.action == Photons.actionCheck) { CheckDestinationPath(); } } } private static void CheckSourcePath() { if (Photons.sourcePath == null) { MyLogger.displayAndLogErrorMessage("Source path not specified."); Photons.action = Photons.actionShowUsage; } else if (!FileUtil.folderExists(sourcePath)) { MyLogger.displayAndLogErrorMessage("Source folder [%s] does not exist. Cannot %s.", Photons.sourcePath, Photons.command); System.exit(errorCodeImportSourceFolderDoesNotExist); } } private static void CheckDestinationPath() { if (Photons.destinationPath == null) { MyLogger.displayAndLogErrorMessage("Destination path not specified."); Photons.action = Photons.actionShowUsage; } else if (Photons.destinationPath != null && !FileUtil.folderExists(Photons.destinationPath)) { MyLogger.displayAndLogErrorMessage("Destination folder [%s] does not exist. Cannot %s.", Photons.destinationPath, Photons.command); System.exit(errorCodeImportDestinationFolderDoesNotExist); } } private static void CheckTypes() { if (Photons.types == null) { MyLogger.displayAndLogErrorMessage("Types not specified."); Photons.action = Photons.actionShowUsage; } } }
UTF-8
Java
8,587
java
Photons.java
Java
[]
null
[]
package ui; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.text.SimpleDateFormat; import java.util.Date; import modell.FileImporter; import common.FileUtil; import common.MyLogger; public class Photons { public static final int errorCodeImportSourceFolderDoesNotExist = 1; public static final int errorCodeImportDestinationFolderDoesNotExist = 2; public static final int errorCodeFailedToCreateLogFile = 3; public static final int errorCodeLengthMismatch = 4; public static final int errorCodeHashMismatch = 5; public static final int errorCodeFailedToInsertFileIntoDatabase = 6; public static final int errorCodeFailedToAddSourcePathInformationToDatabase = 7; public static final int errorCodeFailedToGetFileInformationFromDatabase = 8; public static final int errorCodeUnsupportedDatabaseVersion = 9; public static final int errorCodeFailedToInsertFileGroupInformationIntoDatabase = 10; public static final int errorCodeFailedToInsertFileGroupAssignmentInformationIntoDatabase = 11; public static final int errorCodeDuplicateImportedFile = 12; public static final int errorCodeFileInsertionVerificationFailed = 13; public static final int errorCodeFailedToInsertFileInfoInformationIntoDatabase = 14; public static final int errorCodeCommandOrOptionDoesNotExist = 15; public static final int errorCodeWrongUsage = 16; public static final int errorCodeFailedToOpenOrCreateDatabase = 17; public static final int errorCodeDatabaseVersionCheckFailure = 18; public static final int errorCodeFailedToInsertFileTypeInformationIntoDatabase = 19; public static final int errorCodeFailedToGetFileTypeInformation = 20; public static final int errorCodeJDBCNotFound = 21; public static final int errorCodeSourceFolderUUIDReadingError = 22; private static final int actionShowUsage = 0; private static final int actionShowUI = 1; private static final int actionImport = 2; private static final int actionVerify = 3; private static final int actionCheck = 4; private static final SimpleDateFormat dateTimeFormatter = new SimpleDateFormat("yyyyMMdd-HHmmSS"); private static final String commandImport = "import"; private static final String commandVerify = "verify"; private static final String commandCheck = "check"; private static final String argSource = "source"; private static final String argDestination = "destination"; private static final String argTypes = "types"; private static final String usage = "\n" + "Usage:\n" + "\n" + "java -jar photons.jar [CommandLineParamaters]\n" + "\n" + "Command line parameters:\n" + "\n" + "import /source=<SourcePath> /destination=<DestinationPath> /types=<Types>\n" + "verify /source=<SourcePath> /destination=<DestinationPath> /types=<Types>\n" + "check /destination=<DestinationPath>\n" + "\n" + "Example:\n" + "\n" + "Importing jpg files:\n" + "java -jar photons.jar import /source=/media/store /destination=/home/myUser/pictures /types=jpg\n" + "Verifying that all jpg files were imported correctly:\n" + "java -jar photons.jar verify /source=/media/store /destination=/home/myUser/pictures /types=jpg\n" + "Checking consistency of the target path (e.g. after making a copy of it):\n" + "java -jar photons.jar check /destination=/home/myUser/pictures\n" ; private static String command = null; private static String sourcePath = null; private static String destinationPath = null; private static String[] types = null; private static int action = actionShowUsage; private static int errorCode = 0; // TODO: introduce command: fillmediatimestamp (this would analyse EXIF information etc. - update database information) /** * @param args */ public static void main(String[] args) { MyLogger.setLogLevel(MyLogger.logLevelInformation); InterpretCommandLineArguments(args); if (Photons.action == Photons.actionShowUsage) { MyLogger.displayInformationMessage(usage); System.exit(errorCode); } final Path logPath = Paths.get(Photons.destinationPath, String.format("actions_%s.txt", dateTimeFormatter.format(new Date()))); try { MyLogger.setLogFile(logPath); } catch (IOException e) { System.err.println(String.format("ERROR: Could not create logfile '%s'.", logPath)); e.printStackTrace(); System.exit(errorCodeFailedToCreateLogFile); } if (Photons.action == Photons.actionImport) { FileImporter fileImporter = new FileImporter(Photons.sourcePath, Photons.destinationPath, Photons.types); try { //String uuidPath = FileUtil.getDeviceBasedUniformPath(Photons.sourcePath, Photons.sourcePath); //String u2 = uuidPath; fileImporter.Import(); } catch (IOException e) { MyLogger.displayAndLogExceptionMessage(e, "Import failed"); } } else if (Photons.action == Photons.actionVerify) { FileImporter fileImporter = new FileImporter(Photons.sourcePath, Photons.destinationPath, Photons.types); try { if (fileImporter.Verify()) { MyLogger.displayAndLogInformationMessage("Verification success."); } else { MyLogger.displayAndLogErrorMessage("Verification failed."); } } catch (IOException e) { MyLogger.displayAndLogExceptionMessage(e, "Import failed"); } } else if (Photons.action == Photons.actionCheck) { // TODO: implement MyLogger.displayAndLogErrorMessage("Command [%s] is not implemented yet.", Photons.command); Photons.errorCode = errorCodeCommandOrOptionDoesNotExist; } if (Photons.errorCode != 0) { System.exit(Photons.errorCode); } MyLogger.displayAndLogInformationMessage("Done"); } /** * Interprets the command line arguments and sets the appropriate fields * @param args The command line arguments */ private static void InterpretCommandLineArguments(String[] args) { if (args.length == 0) { // This will show the UI. Not implemented yet Photons.action = Photons.actionShowUI; } else { for (int i = 0; i < args.length; i++) { String arg = args[i]; String lowerCaseArg = arg.toLowerCase(); if (lowerCaseArg.equals(Photons.commandImport)) { Photons.action = Photons.actionImport; } else if (lowerCaseArg.equals(Photons.commandVerify)) { Photons.action = Photons.actionVerify; } else if (lowerCaseArg.equals(Photons.commandCheck)) { Photons.action = Photons.actionCheck; } else if (lowerCaseArg.startsWith("/")) { int equationSignIndex = arg.indexOf("="); if (equationSignIndex > 0) { String valueName = lowerCaseArg.substring(1, equationSignIndex); String value = arg.substring(equationSignIndex + 1, arg.length()); if (valueName.equals(argSource)) { Photons.sourcePath = value; } else if (valueName.equals(argDestination)) { Photons.destinationPath = value; } else if (valueName.equals(argTypes)) { Photons.types = value.split(","); } } } else { MyLogger.displayErrorMessage("Command or option [%s] does not exist. Cannot proceed.", lowerCaseArg); errorCode = errorCodeCommandOrOptionDoesNotExist; } } if (Photons.action == Photons.actionImport) { CheckSourcePath(); CheckDestinationPath(); CheckTypes(); } else if (Photons.action == Photons.actionVerify) { CheckSourcePath(); CheckDestinationPath(); CheckTypes(); } else if (Photons.action == Photons.actionCheck) { CheckDestinationPath(); } } } private static void CheckSourcePath() { if (Photons.sourcePath == null) { MyLogger.displayAndLogErrorMessage("Source path not specified."); Photons.action = Photons.actionShowUsage; } else if (!FileUtil.folderExists(sourcePath)) { MyLogger.displayAndLogErrorMessage("Source folder [%s] does not exist. Cannot %s.", Photons.sourcePath, Photons.command); System.exit(errorCodeImportSourceFolderDoesNotExist); } } private static void CheckDestinationPath() { if (Photons.destinationPath == null) { MyLogger.displayAndLogErrorMessage("Destination path not specified."); Photons.action = Photons.actionShowUsage; } else if (Photons.destinationPath != null && !FileUtil.folderExists(Photons.destinationPath)) { MyLogger.displayAndLogErrorMessage("Destination folder [%s] does not exist. Cannot %s.", Photons.destinationPath, Photons.command); System.exit(errorCodeImportDestinationFolderDoesNotExist); } } private static void CheckTypes() { if (Photons.types == null) { MyLogger.displayAndLogErrorMessage("Types not specified."); Photons.action = Photons.actionShowUsage; } } }
8,587
0.739956
0.734366
219
38.210045
30.627556
134
false
false
0
0
0
0
65
0.00757
2.863014
false
false
9
d0efaa1b4b68da5771860bc5d28250d4ef8a3e05
22,754,736,789,871
a6abf800ba5be47e1a5195ed17e7dad096ff2ee8
/src/main/java/net/sourceforge/fenixedu/presentationTier/Action/publico/GetEncryptedPassword.java
b5197447c216be94d4c34bdabfbf090bf74e35e6
[]
no_license
samfcmc/fenix
https://github.com/samfcmc/fenix
a005f4a2909bfd31b2540f63acd775663f8fd026
0737ba8bde80b27219cef40d7d635fd83b995f92
refs/heads/master
2021-01-18T06:55:35.026000
2013-11-13T18:30:11
2013-11-13T18:30:11
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Created on 10/Set/2003, 18:36:21 changed on 4/Jan/2004, 19:45:11 (generalize * for any execution course) By Goncalo Luiz gedl [AT] rnl [DOT] ist [DOT] utl * [DOT] pt */ package net.sourceforge.fenixedu.presentationTier.Action.publico; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sourceforge.fenixedu.applicationTier.Servico.gesdis.teacher.ReadTeacherByUsername; import net.sourceforge.fenixedu.dataTransferObject.InfoTeacher; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; /** * @author Goncalo Luiz gedl [AT] rnl [DOT] ist [DOT] utl [DOT] pt * * * Created at 10/Set/2003, 18:36:21 * */ public class GetEncryptedPassword extends Action { /** * error codes: 1-> service unavailable 2-> input data error 3-> no such * user */ @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { String username = request.getParameter("login"); String timestamp = request.getParameter("timestamp"); String url = request.getParameter("url"); InfoTeacher infoTeacher = null; url = url + "?"; Integer error = new Integer(0); if (username.equals("") || timestamp.equals("") || url.equals("?")) { error = new Integer(2); } else { infoTeacher = ReadTeacherByUsername.run(username); } if (infoTeacher == null) { error = new Integer(3); } else { url = url + "encrypted_password=" + infoTeacher.getInfoPerson().getPassword() + "&"; } url = url + "timestamp=" + timestamp + "&"; url = url + "error=" + error.toString(); try { response.sendRedirect(url); } catch (IOException e) { e.printStackTrace(); // ignored exception } return null; } }
UTF-8
Java
2,124
java
GetEncryptedPassword.java
Java
[ { "context": ":45:11 (generalize\n * for any execution course) By Goncalo Luiz gedl [AT] rnl [DOT] ist [DOT] utl\n * [DOT] pt\n */", "end": 127, "score": 0.9998911023139954, "start": 115, "tag": "NAME", "value": "Goncalo Luiz" }, { "context": "pache.struts.action.ActionMapping;\n\n/**\n * @author Goncalo Luiz gedl [AT] rnl [DOT] ist [DOT] utl [DOT] pt\n * \n *", "end": 733, "score": 0.999896764755249, "start": 721, "tag": "NAME", "value": "Goncalo Luiz" } ]
null
[]
/* * Created on 10/Set/2003, 18:36:21 changed on 4/Jan/2004, 19:45:11 (generalize * for any execution course) By <NAME> gedl [AT] rnl [DOT] ist [DOT] utl * [DOT] pt */ package net.sourceforge.fenixedu.presentationTier.Action.publico; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sourceforge.fenixedu.applicationTier.Servico.gesdis.teacher.ReadTeacherByUsername; import net.sourceforge.fenixedu.dataTransferObject.InfoTeacher; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; /** * @author <NAME> gedl [AT] rnl [DOT] ist [DOT] utl [DOT] pt * * * Created at 10/Set/2003, 18:36:21 * */ public class GetEncryptedPassword extends Action { /** * error codes: 1-> service unavailable 2-> input data error 3-> no such * user */ @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { String username = request.getParameter("login"); String timestamp = request.getParameter("timestamp"); String url = request.getParameter("url"); InfoTeacher infoTeacher = null; url = url + "?"; Integer error = new Integer(0); if (username.equals("") || timestamp.equals("") || url.equals("?")) { error = new Integer(2); } else { infoTeacher = ReadTeacherByUsername.run(username); } if (infoTeacher == null) { error = new Integer(3); } else { url = url + "encrypted_password=" + infoTeacher.getInfoPerson().getPassword() + "&"; } url = url + "timestamp=" + timestamp + "&"; url = url + "error=" + error.toString(); try { response.sendRedirect(url); } catch (IOException e) { e.printStackTrace(); // ignored exception } return null; } }
2,112
0.637476
0.618173
67
30.716417
29.155684
130
false
false
0
0
0
0
0
0
0.522388
false
false
9
7f0820885f4cd82d478478888aa1b5b779eea50d
26,645,977,118,197
3d4bfdece9b5f31a9fea8a3b9da0ddffd40b011e
/src/org/usfirst/frc/team3501/robot/commands/MoveArmFor.java
eb2a5ce28ff71339246c2662823ddb26322b9e35
[]
no_license
glinia/3501-spark-go
https://github.com/glinia/3501-spark-go
0fc2c734e64802ac618a97e5e9acb8cea92a8383
f3db6e7b243bd1acfb89790e5bffc3f8d2c768b2
refs/heads/master
2021-01-22T11:55:08.987000
2015-10-25T23:25:30
2015-10-25T23:25:30
34,091,358
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.usfirst.frc.team3501.robot.commands; import org.usfirst.frc.team3501.bases.Command; public class MoveArmFor extends Command { private double speed; public MoveArmFor(double secs, double speed) { super("MoveArmFor"); requires(arm); setTimeout(secs); this.speed = speed; } protected void execute() { arm.set(speed); } protected boolean isFinished() { return isTimedOut(); } }
UTF-8
Java
469
java
MoveArmFor.java
Java
[]
null
[]
package org.usfirst.frc.team3501.robot.commands; import org.usfirst.frc.team3501.bases.Command; public class MoveArmFor extends Command { private double speed; public MoveArmFor(double secs, double speed) { super("MoveArmFor"); requires(arm); setTimeout(secs); this.speed = speed; } protected void execute() { arm.set(speed); } protected boolean isFinished() { return isTimedOut(); } }
469
0.633262
0.616205
24
18.541666
17.298794
50
false
false
0
0
0
0
0
0
0.416667
false
false
9
35f8086f00aada5dec1726ca70193db7177d9c4d
28,802,050,730,403
f5cfb8fcf739c37cf689a77ab37d53635a6e7830
/src/test/java/sncf/oui/demo/services/PackagingBotServiceTest.java
8ffb53abbe3a12d623eb49a3990dbf75ec63068e
[]
no_license
khocef/xspeedit
https://github.com/khocef/xspeedit
eebad9012172bd477bd1bd848d41b85778ff5730
3b03d589957b92070e041440370ff6630903bc48
refs/heads/master
2020-04-22T15:11:28.694000
2019-02-13T08:56:20
2019-02-13T08:56:20
170,469,745
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package sncf.oui.demo.services; import org.junit.Test; import sncf.oui.demo.exceptions.PackagingBotException; import static org.junit.Assert.assertEquals; public class PackagingBotServiceTest { private final PackagingBotService service = new PackagingBotService(); @Test(expected = PackagingBotException.class) public void packageArticlesNoArticlesToPackageTest() throws PackagingBotException { service.packageArticles(""); } @Test(expected = PackagingBotException.class) public void packageArticlesNoArticlesOfSizeZeroAllowedTest() throws PackagingBotException { service.packageArticles("847120487303"); } @Test(expected = PackagingBotException.class) public void packageArticlesNotNumericTest() throws PackagingBotException { service.packageArticles("8473487353A"); } @Test() public void packageArticles() throws PackagingBotException { String packageArticles = service.packageArticles("163841689525773"); assertEquals("163/81/46/82/9/55/73/7", packageArticles); } }
UTF-8
Java
1,070
java
PackagingBotServiceTest.java
Java
[]
null
[]
package sncf.oui.demo.services; import org.junit.Test; import sncf.oui.demo.exceptions.PackagingBotException; import static org.junit.Assert.assertEquals; public class PackagingBotServiceTest { private final PackagingBotService service = new PackagingBotService(); @Test(expected = PackagingBotException.class) public void packageArticlesNoArticlesToPackageTest() throws PackagingBotException { service.packageArticles(""); } @Test(expected = PackagingBotException.class) public void packageArticlesNoArticlesOfSizeZeroAllowedTest() throws PackagingBotException { service.packageArticles("847120487303"); } @Test(expected = PackagingBotException.class) public void packageArticlesNotNumericTest() throws PackagingBotException { service.packageArticles("8473487353A"); } @Test() public void packageArticles() throws PackagingBotException { String packageArticles = service.packageArticles("163841689525773"); assertEquals("163/81/46/82/9/55/73/7", packageArticles); } }
1,070
0.754206
0.705607
34
30.5
30.422756
95
false
false
0
0
0
0
0
0
0.323529
false
false
9
3cfd403f3101af9368d354cd6b220d154045ff4a
26,972,394,667,890
a06605b7d675f56edbd96f826cbf87fdf40766e3
/src/controller/impl/command/frame/scoring/HideScoringPanelCommand.java
949eeada6d3565f535af3faee24cf0af39eb4d02
[]
no_license
VictorPereraTarajano/Pictionary
https://github.com/VictorPereraTarajano/Pictionary
230d17d262b21bb4aec2b7de40b510cecf223d28
d674f931542e2a787dab982654f2724ce9630df9
refs/heads/master
2021-03-12T23:46:58.091000
2015-07-22T19:10:37
2015-07-22T19:10:37
30,469,229
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package controller.impl.command.frame.scoring; import controller.interfaces.Command; import model.manager.ManagerLobby; public class HideScoringPanelCommand implements Command{ @Override public void execute() { ManagerLobby.myLobbyFrame.getScoringPanel().setVisible(false); } }
UTF-8
Java
300
java
HideScoringPanelCommand.java
Java
[]
null
[]
package controller.impl.command.frame.scoring; import controller.interfaces.Command; import model.manager.ManagerLobby; public class HideScoringPanelCommand implements Command{ @Override public void execute() { ManagerLobby.myLobbyFrame.getScoringPanel().setVisible(false); } }
300
0.776667
0.776667
11
26.272728
23.370886
70
false
false
0
0
0
0
0
0
0.363636
false
false
9
f677a416c1808f380ee84e4265e0218855ba0a4d
32,298,154,131,278
1e770ae3c164049bc3dd0ed269d24118e6565a45
/src/main/java/org/personal/model/Categories.java
296ca0801d6810d90d2303880eef0b2e80a65eb3
[]
no_license
elihub/spring-freemarker
https://github.com/elihub/spring-freemarker
0048eef44b5cad2e8a4e4610611085ee0a6a655e
60fa758237b18bcb579d00fb3b3c9c87c81f732b
refs/heads/master
2021-01-13T03:44:00.194000
2016-12-23T16:31:03
2016-12-23T16:31:03
77,237,568
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.personal.model; import java.util.List; import org.springframework.transaction.annotation.Transactional; /** * * @author elida */ @Transactional public interface Categories { List<Category> getAll(); void create(Category category); void update(Category category); void delete(Long id); }
UTF-8
Java
325
java
Categories.java
Java
[ { "context": "ction.annotation.Transactional;\n\n/**\n *\n * @author elida\n */\n@Transactional\npublic interface Categories {\n", "end": 142, "score": 0.9798579812049866, "start": 137, "tag": "USERNAME", "value": "elida" } ]
null
[]
package org.personal.model; import java.util.List; import org.springframework.transaction.annotation.Transactional; /** * * @author elida */ @Transactional public interface Categories { List<Category> getAll(); void create(Category category); void update(Category category); void delete(Long id); }
325
0.72
0.72
21
14.476191
17.01993
64
false
false
0
0
0
0
0
0
0.333333
false
false
9
901e5b7f745c5d5b7395abdb998992df24757db5
3,977,139,785,511
8b8cb6292b667c1c590620a9009bede8431518ac
/src/testinggame/utils/Context.java
de2ab2564acb16d5556990086421dee2b315b495
[]
no_license
exroot/Proyecto-QQSM
https://github.com/exroot/Proyecto-QQSM
575ec18207b1b8db05740b749164c289d863fe04
e6ec186a46e28631153c024b066d8644743402be
refs/heads/master
2022-04-08T18:34:46.796000
2020-02-09T23:03:43
2020-02-09T23:03:43
233,945,091
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package testinggame.utils; import java.util.List; import testinggame.Modelos.Usuario; import testinggame.Modelos.Categoria; public class Context { private static Usuario usuario = null; private static Integer ronda = null; private static Integer dificultad = null; private static Float puntaje = null; private static String[] categorias; public static Usuario getUsuario() { return usuario; } public static void setUsuario(Usuario usuario) { Context.usuario = usuario; } public static Integer getRonda() { return ronda; } public static void setRonda(Integer ronda) { Context.ronda = ronda; } public static Integer getDificultad() { return dificultad; } public static void setDificultad(Integer dificultad) { Context.dificultad = dificultad; } public static String[] getCategorias() { return categorias; } public static void setCategorias(String[] categorias) { Context.categorias = categorias; } public static void clear() { Context.usuario = null; } }
UTF-8
Java
1,141
java
Context.java
Java
[]
null
[]
package testinggame.utils; import java.util.List; import testinggame.Modelos.Usuario; import testinggame.Modelos.Categoria; public class Context { private static Usuario usuario = null; private static Integer ronda = null; private static Integer dificultad = null; private static Float puntaje = null; private static String[] categorias; public static Usuario getUsuario() { return usuario; } public static void setUsuario(Usuario usuario) { Context.usuario = usuario; } public static Integer getRonda() { return ronda; } public static void setRonda(Integer ronda) { Context.ronda = ronda; } public static Integer getDificultad() { return dificultad; } public static void setDificultad(Integer dificultad) { Context.dificultad = dificultad; } public static String[] getCategorias() { return categorias; } public static void setCategorias(String[] categorias) { Context.categorias = categorias; } public static void clear() { Context.usuario = null; } }
1,141
0.655565
0.655565
50
21.82
18.687632
59
false
false
0
0
0
0
0
0
0.36
false
false
9
20d6b575fea6fe7e1d4c53259ff96ae9d0a54331
14,637,248,549,482
9ec41b30cd36c208a01391d2e9ab3a116e6fd55b
/puffin-core-rest/src/main/java/com/puffincreek/annotations/EnableRestCore.java
aee246da0e920d2ad71f33e2a67218e6dfcea5d8
[ "Apache-2.0" ]
permissive
maggmanu77/scratch
https://github.com/maggmanu77/scratch
97956405b5faa0f267dfbd4103ad9c8d6004631f
d59be1d6b2bc23797c7736f4ca68928bc8bd9c31
refs/heads/master
2020-03-20T02:30:29.989000
2018-07-09T21:42:03
2018-07-09T21:42:03
137,115,235
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.puffincreek.annotations; import com.puffincreek.context.PuffinWebContext; import org.springframework.context.annotation.Import; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Import(PuffinWebContext.class) public @interface EnableRestCore { }
UTF-8
Java
435
java
EnableRestCore.java
Java
[]
null
[]
package com.puffincreek.annotations; import com.puffincreek.context.PuffinWebContext; import org.springframework.context.annotation.Import; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Import(PuffinWebContext.class) public @interface EnableRestCore { }
435
0.843678
0.843678
15
28
17.929491
53
false
false
0
0
0
0
0
0
0.466667
false
false
9
21a8d2aca23ea3973fe662f7d235c75fee554653
14,637,248,549,493
d09d1a8d1f0d0727b7b7504a655c024efba99b9c
/src/com/javaTutorial/inheritance/AreaCalculatorTest.java
b79f9074d8d1a3985520af269feab9cd45fdff87
[]
no_license
siddarthmannem/Core-Java-Tutorial
https://github.com/siddarthmannem/Core-Java-Tutorial
fabd09634d68df1e16d221c9bcb2ac9ee946a46c
59edc027b0cdcd28ed3ff6221ed3684f8a578048
refs/heads/master
2018-11-03T08:58:53.985000
2018-08-25T22:30:54
2018-08-25T22:30:54
93,576,674
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.javaTutorial.inheritance; public class AreaCalculatorTest { public static void main(String[] args) { Rectangle r = new Rectangle(2.0, 2.0); r.calculateArea(); r.permiter(); Circle c = new Circle(2.0); c.calculateArea(); System.out.println("--------------------"); // Polymorphism Shape rec = new Rectangle(3.0, 3.0); rec.calculateArea(); } }
UTF-8
Java
393
java
AreaCalculatorTest.java
Java
[]
null
[]
package com.javaTutorial.inheritance; public class AreaCalculatorTest { public static void main(String[] args) { Rectangle r = new Rectangle(2.0, 2.0); r.calculateArea(); r.permiter(); Circle c = new Circle(2.0); c.calculateArea(); System.out.println("--------------------"); // Polymorphism Shape rec = new Rectangle(3.0, 3.0); rec.calculateArea(); } }
393
0.613232
0.587786
23
16.086956
16.043184
45
false
false
0
0
0
0
0
0
1.782609
false
false
9
f4f126f90930ddad1b4f0c9e5007b60d7f315488
14,388,140,498,317
2baee49530792b32bd5c41bf173e998e7a972831
/src/text/mybatis/TestCascadeSelect.java
cebc93daaba1a9262cfbf687d6e483821b72a835
[]
no_license
HappyMinChao/DynamicSqlAndCascadeSelect
https://github.com/HappyMinChao/DynamicSqlAndCascadeSelect
1938685c0e3b403a15eb1c6c5bbf8d0393f55135
e4dd717c1ade0e2349724b9bb2362ff333f1b1ef
refs/heads/master
2021-01-20T22:22:39.824000
2016-08-14T08:45:56
2016-08-14T08:45:56
65,657,295
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package text.mybatis; import java.io.IOException; import java.io.InputStream; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Before; import org.junit.Test; import com.bj.mybatis.entity.Dept; import com.bj.mybatis.entity.Lock; import com.bj.mybatis.mapper.java.DeptMapper; import com.bj.mybatis.mapper.java.LockMapper; public class TestCascadeSelect { SqlSessionFactory sqlSessionFactory = null; @Before public void before() throws IOException{ InputStream reader = Resources.getResourceAsStream("mybatis-config.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); } /** *@Description:根据id获取dept *@Author:du_minchao *@Version: *@CreateDate:2016年3月16日 *@return:void */ @Test public void testGetDeptById(){ SqlSession sqlSession = sqlSessionFactory.openSession(); DeptMapper mapper = sqlSession.getMapper(DeptMapper.class); //因为在lock中有key Dept lockById = mapper.getDeptById(1); System.out.println(lockById); //System.out.println(lockById.getKey().getKeyName()); sqlSession.commit(); if(sqlSession != null){ sqlSession.close(); } } /** *@Description: 测试向数据库中添加Student *@Author:du_minchao *@Version:1.0 *@CreateDate:2016年3月15日 *@return:void */ @Test public void testGetLockById(){ SqlSession sqlSession = sqlSessionFactory.openSession(); LockMapper mapper = sqlSession.getMapper(LockMapper.class); //因为在lock中有key Lock lockById = mapper.getLockById(1); System.out.println(lockById); //System.out.println(lockById.getKey().getKeyName()); sqlSession.commit(); if(sqlSession != null){ sqlSession.close(); } } }
UTF-8
Java
1,869
java
TestCascadeSelect.java
Java
[ { "context": "\t}\n\t\n\t\n\t/**\n\t *@Description:根据id获取dept\n\t *@Author:du_minchao\n\t *@Version:\n\t *@CreateDate:2016年3月16日\n\t *@return", "end": 820, "score": 0.9996879696846008, "start": 810, "tag": "USERNAME", "value": "du_minchao" }, { "context": "\t/**\n\t *@Description:\t测试向数据库中添加Student\n\t *@Author:du_minchao\n\t *@Version:1.0\n\t *@CreateDate:2016年3月15日\n\t *@ret", "end": 1345, "score": 0.9996799230575562, "start": 1335, "tag": "USERNAME", "value": "du_minchao" } ]
null
[]
package text.mybatis; import java.io.IOException; import java.io.InputStream; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Before; import org.junit.Test; import com.bj.mybatis.entity.Dept; import com.bj.mybatis.entity.Lock; import com.bj.mybatis.mapper.java.DeptMapper; import com.bj.mybatis.mapper.java.LockMapper; public class TestCascadeSelect { SqlSessionFactory sqlSessionFactory = null; @Before public void before() throws IOException{ InputStream reader = Resources.getResourceAsStream("mybatis-config.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); } /** *@Description:根据id获取dept *@Author:du_minchao *@Version: *@CreateDate:2016年3月16日 *@return:void */ @Test public void testGetDeptById(){ SqlSession sqlSession = sqlSessionFactory.openSession(); DeptMapper mapper = sqlSession.getMapper(DeptMapper.class); //因为在lock中有key Dept lockById = mapper.getDeptById(1); System.out.println(lockById); //System.out.println(lockById.getKey().getKeyName()); sqlSession.commit(); if(sqlSession != null){ sqlSession.close(); } } /** *@Description: 测试向数据库中添加Student *@Author:du_minchao *@Version:1.0 *@CreateDate:2016年3月15日 *@return:void */ @Test public void testGetLockById(){ SqlSession sqlSession = sqlSessionFactory.openSession(); LockMapper mapper = sqlSession.getMapper(LockMapper.class); //因为在lock中有key Lock lockById = mapper.getLockById(1); System.out.println(lockById); //System.out.println(lockById.getKey().getKeyName()); sqlSession.commit(); if(sqlSession != null){ sqlSession.close(); } } }
1,869
0.737714
0.727775
79
21.924051
19.975157
75
false
false
0
0
0
0
0
0
1.556962
false
false
9
9238b2bcaf0841b6ee4737a7dea1e34533253077
24,867,860,699,955
98ea16c6d0143847c1ae95f60c7fe01529e2adee
/src/main/java/com/maurofokker/test/arrays/SumTwoValues.java
bbc5dc13f767a81389ddb71d2e69ebbbd493c517
[]
no_license
maurofokker/testcode
https://github.com/maurofokker/testcode
fdddbf634fcc91568111e9f996773523f7dbdd0a
25faa102f31453c6c43db645d4fdf1065fca7b15
refs/heads/master
2021-07-14T09:49:20.654000
2017-10-17T18:23:28
2017-10-17T18:23:28
105,613,948
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.maurofokker.test.arrays; import java.util.HashSet; import java.util.Set; /** * Created by mauro on 10/3/17. * * Given an array of integers and a value, determine if there are any two integers in the array * which sum equal to the given value * i.e. * array = {5, 7, 1, 2, 8, 4, 3} * given sum 10: * 7 + 3 = 10 * 2 + 8 = 10 * given sum 19 * there are no 2 values that sum 19 * Hint: * - hashtable * - sort array */ public class SumTwoValues { /** * Runtime complex O(n) linear * Memory complex O(n) * * Scan whole array once and store visited elements in a hash set. * During scan, for every element 'e' in array, we check if 'val' - 'e' is present in the hash set i.e. 'val' - 'e' is already visited. * If 'val' - 'e' is found in the hash set, it means there is a pair (e, val - e) in array whose sum is equal to the given val. * If we have exhausted all elements in the array and didn't find any such pair, function will return false * * @param array * @param val * @return true if there are 2 values that sum val or false otherwise */ public boolean findSumOfTwoValuesSolutionOne(int[] array, int val) { Set<Integer> foundValues = new HashSet<>(); for (int a : array) { if (foundValues.contains(val - a)) { return true; } foundValues.add(a); } return false; } /** * Solution suppose is a sorted array * Runtime complex O(n) * Memory complex O(1) constant * * Algorithm * * // assume 0 is the first index in array * // and n is the total number of elements in array * left = 0 * right = n - 1 * while left is less than right * sum = array[left] + array[right] * if sum == val return true * if sum is less than val * // sum is smaller than value * // means pair can only exist to the * // right of left element, so left element * // should be moved one step next * left = left + 1 * else * // sum is greater than value * // means pair can only exist to the * // left of right element, so right element * // should be moved one step previous * right = right - 1 * * @param array * @param val * @return */ public boolean findSumOfTwoValuesSolutionTwo(int[] array, int val) { for (int i = 0, j = array.length - 1; i < j;) { int sum = array[i] + array[j]; if (sum == val) { return true; } if (sum < val) { ++i; } else { --j; } } return false; } }
UTF-8
Java
2,808
java
SumTwoValues.java
Java
[ { "context": ".HashSet;\nimport java.util.Set;\n\n/**\n * Created by mauro on 10/3/17.\n *\n * Given an array of integers and ", "end": 110, "score": 0.9990041255950928, "start": 105, "tag": "USERNAME", "value": "mauro" } ]
null
[]
package com.maurofokker.test.arrays; import java.util.HashSet; import java.util.Set; /** * Created by mauro on 10/3/17. * * Given an array of integers and a value, determine if there are any two integers in the array * which sum equal to the given value * i.e. * array = {5, 7, 1, 2, 8, 4, 3} * given sum 10: * 7 + 3 = 10 * 2 + 8 = 10 * given sum 19 * there are no 2 values that sum 19 * Hint: * - hashtable * - sort array */ public class SumTwoValues { /** * Runtime complex O(n) linear * Memory complex O(n) * * Scan whole array once and store visited elements in a hash set. * During scan, for every element 'e' in array, we check if 'val' - 'e' is present in the hash set i.e. 'val' - 'e' is already visited. * If 'val' - 'e' is found in the hash set, it means there is a pair (e, val - e) in array whose sum is equal to the given val. * If we have exhausted all elements in the array and didn't find any such pair, function will return false * * @param array * @param val * @return true if there are 2 values that sum val or false otherwise */ public boolean findSumOfTwoValuesSolutionOne(int[] array, int val) { Set<Integer> foundValues = new HashSet<>(); for (int a : array) { if (foundValues.contains(val - a)) { return true; } foundValues.add(a); } return false; } /** * Solution suppose is a sorted array * Runtime complex O(n) * Memory complex O(1) constant * * Algorithm * * // assume 0 is the first index in array * // and n is the total number of elements in array * left = 0 * right = n - 1 * while left is less than right * sum = array[left] + array[right] * if sum == val return true * if sum is less than val * // sum is smaller than value * // means pair can only exist to the * // right of left element, so left element * // should be moved one step next * left = left + 1 * else * // sum is greater than value * // means pair can only exist to the * // left of right element, so right element * // should be moved one step previous * right = right - 1 * * @param array * @param val * @return */ public boolean findSumOfTwoValuesSolutionTwo(int[] array, int val) { for (int i = 0, j = array.length - 1; i < j;) { int sum = array[i] + array[j]; if (sum == val) { return true; } if (sum < val) { ++i; } else { --j; } } return false; } }
2,808
0.53953
0.526709
101
26.801981
26.686674
141
false
false
0
0
0
0
0
0
0.306931
false
false
9
06ace10b2949b1960a42b935169e1fbdf1f150ce
27,298,812,186,239
3f138509a3c3aa175f0dd4b55e86d0adf6d3b00e
/src/main/06-alipay/com/otzg/alipay/redbag/api/AlipayMarketingCampaignCashCreateController.java
3684fc5acc96e2f3f2964a9ac4ed98ae7cc7e23d
[]
no_license
Dragon5170/otzg-pay-service
https://github.com/Dragon5170/otzg-pay-service
33430701b94b3ff89c5b00f9733e704d28bbbe31
d2a3d8fcf30da532f52e5a75e9a1cdb4727fd204
refs/heads/master
2023-04-11T13:08:36.150000
2021-04-17T14:33:26
2021-04-17T14:33:26
315,011,821
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.otzg.alipay.redbag.api; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Properties; import com.otzg.alipay.redbag.entity.Result; import com.otzg.alipay.redbag.util.AlipayConfig; import com.otzg.alipay.redbag.util.DefaultAlipayClientFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.alipay.api.AlipayApiException; import com.alipay.api.AlipayClient; import com.alipay.api.domain.AlipayMarketingCampaignCashCreateModel; import com.alipay.api.request.AlipayMarketingCampaignCashCreateRequest; import com.alipay.api.response.AlipayMarketingCampaignCashCreateResponse; @Controller public class AlipayMarketingCampaignCashCreateController { @RequestMapping(value="/alipayMarketingCampaignCashCreate.htm") public String toHtml(HttpServletRequest request,ModelMap modelMap){ return "api/alipayMarketingCampaignCashCreate"; } @RequestMapping(value="/alipayMarketingCampaignCashCreate.json", method = RequestMethod.POST) @ResponseBody public Object doPost(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap,AlipayMarketingCampaignCashCreateModel alipayModel){ Result<AlipayMarketingCampaignCashCreateResponse> result = new Result<AlipayMarketingCampaignCashCreateResponse>(); Properties prop = AlipayConfig.getProperties(); //初始化请求类 AlipayMarketingCampaignCashCreateRequest alipayRequest = new AlipayMarketingCampaignCashCreateRequest(); //添加demo请求标示,用于标记是demo发出 alipayRequest.putOtherTextParam(AlipayConfig.ALIPAY_DEMO, AlipayConfig.ALIPAY_DEMO_VERSION); //设置业务参数,alipayModel为前端发送的请求信息,开发者需要根据实际情况填充此类 alipayRequest.setBizModel(alipayModel); alipayRequest.setReturnUrl(prop.getProperty("RETURN_URL")); alipayRequest.setNotifyUrl(prop.getProperty("NOTIFY_URL")); //sdk请求客户端,已将配置信息初始化 AlipayClient alipayClient = DefaultAlipayClientFactory.getAlipayClient(); try { //因为是接口服务,使用exexcute方法获取到返回值 AlipayMarketingCampaignCashCreateResponse alipayResponse = alipayClient.execute(alipayRequest); if(alipayResponse.isSuccess()){ System.out.println("调用成功"); //TODO 实际业务处理,开发者编写。可以通过alipayResponse.getXXX的形式获取到返回值 } else { System.out.println("调用失败"); } result.setSuccess(true); result.setValue(alipayResponse); return result; } catch (AlipayApiException e) { e.printStackTrace(); if(e.getCause() instanceof java.security.spec.InvalidKeySpecException){ result.setMessage("商户私钥格式不正确,请确认配置文件Alipay-Config.properties中是否配置正确"); return result; } } return null; } }
UTF-8
Java
3,185
java
AlipayMarketingCampaignCashCreateController.java
Java
[]
null
[]
package com.otzg.alipay.redbag.api; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Properties; import com.otzg.alipay.redbag.entity.Result; import com.otzg.alipay.redbag.util.AlipayConfig; import com.otzg.alipay.redbag.util.DefaultAlipayClientFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.alipay.api.AlipayApiException; import com.alipay.api.AlipayClient; import com.alipay.api.domain.AlipayMarketingCampaignCashCreateModel; import com.alipay.api.request.AlipayMarketingCampaignCashCreateRequest; import com.alipay.api.response.AlipayMarketingCampaignCashCreateResponse; @Controller public class AlipayMarketingCampaignCashCreateController { @RequestMapping(value="/alipayMarketingCampaignCashCreate.htm") public String toHtml(HttpServletRequest request,ModelMap modelMap){ return "api/alipayMarketingCampaignCashCreate"; } @RequestMapping(value="/alipayMarketingCampaignCashCreate.json", method = RequestMethod.POST) @ResponseBody public Object doPost(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap,AlipayMarketingCampaignCashCreateModel alipayModel){ Result<AlipayMarketingCampaignCashCreateResponse> result = new Result<AlipayMarketingCampaignCashCreateResponse>(); Properties prop = AlipayConfig.getProperties(); //初始化请求类 AlipayMarketingCampaignCashCreateRequest alipayRequest = new AlipayMarketingCampaignCashCreateRequest(); //添加demo请求标示,用于标记是demo发出 alipayRequest.putOtherTextParam(AlipayConfig.ALIPAY_DEMO, AlipayConfig.ALIPAY_DEMO_VERSION); //设置业务参数,alipayModel为前端发送的请求信息,开发者需要根据实际情况填充此类 alipayRequest.setBizModel(alipayModel); alipayRequest.setReturnUrl(prop.getProperty("RETURN_URL")); alipayRequest.setNotifyUrl(prop.getProperty("NOTIFY_URL")); //sdk请求客户端,已将配置信息初始化 AlipayClient alipayClient = DefaultAlipayClientFactory.getAlipayClient(); try { //因为是接口服务,使用exexcute方法获取到返回值 AlipayMarketingCampaignCashCreateResponse alipayResponse = alipayClient.execute(alipayRequest); if(alipayResponse.isSuccess()){ System.out.println("调用成功"); //TODO 实际业务处理,开发者编写。可以通过alipayResponse.getXXX的形式获取到返回值 } else { System.out.println("调用失败"); } result.setSuccess(true); result.setValue(alipayResponse); return result; } catch (AlipayApiException e) { e.printStackTrace(); if(e.getCause() instanceof java.security.spec.InvalidKeySpecException){ result.setMessage("商户私钥格式不正确,请确认配置文件Alipay-Config.properties中是否配置正确"); return result; } } return null; } }
3,185
0.790818
0.790818
71
39.816902
32.532242
151
false
false
0
0
0
0
0
0
1.84507
false
false
9
316a0c956227828558c394521320e625571c1c91
2,156,073,650,188
fd7c1b0c51d5d84be1e26a0f77d8a66d73a4451f
/03A.java
b5c8f34fea01fbaf5dc36d7b4f9f386db88ac372
[]
no_license
heziel/InterviewBit
https://github.com/heziel/InterviewBit
cb9d6f04e3c302ccef9eee415fc8dda5b9cd96c2
4a32a2951cef9c469d8c30802b3cb860233ab515
refs/heads/master
2021-01-11T10:24:54.437000
2017-01-26T22:27:23
2017-01-26T22:27:23
79,419,139
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Solution { public static int kthsmallest( final List<Integer> a, int k) { ArrayList<Integer> al = new ArrayList<>(a); return find(0,a.size()-1,k, al); } public static int find(int pivot, int high,int k, ArrayList<Integer> a){ int kth =0; if(pivot <= high){ int hold = 0; int i = pivot; for (int j = pivot+1; j <= high ; j ++){ if(a.get(pivot) >= a.get(j)){ hold = a.get(i+1); a.set(i+1, a.get(j)); a.set(j,hold); i++; } } hold = a.get(i); a.set(i, a.get(pivot)); a.set(pivot,hold); /* * make recursive calls */ if(i+1 == k) return a.get(i); else if(k < i+1) kth = find(pivot, i-1,k,a); else kth = find(i+1,high,k,a); } return kth; } }
UTF-8
Java
759
java
03A.java
Java
[]
null
[]
public class Solution { public static int kthsmallest( final List<Integer> a, int k) { ArrayList<Integer> al = new ArrayList<>(a); return find(0,a.size()-1,k, al); } public static int find(int pivot, int high,int k, ArrayList<Integer> a){ int kth =0; if(pivot <= high){ int hold = 0; int i = pivot; for (int j = pivot+1; j <= high ; j ++){ if(a.get(pivot) >= a.get(j)){ hold = a.get(i+1); a.set(i+1, a.get(j)); a.set(j,hold); i++; } } hold = a.get(i); a.set(i, a.get(pivot)); a.set(pivot,hold); /* * make recursive calls */ if(i+1 == k) return a.get(i); else if(k < i+1) kth = find(pivot, i-1,k,a); else kth = find(i+1,high,k,a); } return kth; } }
759
0.521739
0.507246
41
17.512196
16.979359
73
false
false
0
0
0
0
0
0
3.243902
false
false
9
0f0042020f1f00d0411d675681e4cafa959b3c2e
30,382,598,683,861
6b374800ec20c74bea527f712dd81b7833700c3e
/src/mod/blazecake/com/Plugin.java
018e28e54a9f8a7e7a6e02f78a7e19f8206f0aa6
[]
no_license
TheKeksinator26/Bukkit-Plugin
https://github.com/TheKeksinator26/Bukkit-Plugin
9f660104b3591d52c4c97f08c17c6b94caa09538
ef941e28ca26726e99b91580f3e253a395061de8
refs/heads/master
2021-01-19T16:56:31.394000
2014-11-29T15:45:17
2014-11-29T15:45:17
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package mod.blazecake.com; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; public class Plugin extends JavaPlugin { @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { //Umwandlung Sender -> Player Player p = null; if(sender instanceof Player){ p = (Player) sender; } //Kommando "TEST" if(cmd.getName().equalsIgnoreCase("test")){ if(p != null){ String version = this.getDescription().getVersion(); @SuppressWarnings("unused") String name = this.getDescription().getName(); String mainauthor = this.getDescription().getAuthors().get(0); for(int i = 0; i < this.getDescription().getAuthors().size(); i++){ } p.sendMessage(ChatColor.RED + "Hallo, " + p.getDisplayName()); p.sendMessage(ChatColor.GREEN + "[BlazeCraft] Geladen."); p.sendMessage("Version; " + version); p.sendMessage("Eine Idee von: " + mainauthor); } else { sender.sendMessage(ChatColor.GREEN + "[BlazeCraft] Geladen."); return true; } } return false; } }
UTF-8
Java
1,237
java
Plugin.java
Java
[]
null
[]
package mod.blazecake.com; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; public class Plugin extends JavaPlugin { @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { //Umwandlung Sender -> Player Player p = null; if(sender instanceof Player){ p = (Player) sender; } //Kommando "TEST" if(cmd.getName().equalsIgnoreCase("test")){ if(p != null){ String version = this.getDescription().getVersion(); @SuppressWarnings("unused") String name = this.getDescription().getName(); String mainauthor = this.getDescription().getAuthors().get(0); for(int i = 0; i < this.getDescription().getAuthors().size(); i++){ } p.sendMessage(ChatColor.RED + "Hallo, " + p.getDisplayName()); p.sendMessage(ChatColor.GREEN + "[BlazeCraft] Geladen."); p.sendMessage("Version; " + version); p.sendMessage("Eine Idee von: " + mainauthor); } else { sender.sendMessage(ChatColor.GREEN + "[BlazeCraft] Geladen."); return true; } } return false; } }
1,237
0.658044
0.656427
50
23.700001
23.535717
91
false
false
0
0
0
0
0
0
2.92
false
false
9