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
95ec0b2bf3b1b154bb6c08f9ee6181193fa506eb
21,217,138,510,886
0f4f1e94f068cb9e72e675941aee35a1e5575707
/shoppingapp/app/src/main/java/com/example/shoppingapp/Item.java
b0d1f0ad4fa0df2bc9aa9920deac0f4fbe024e46
[]
no_license
aawab/newShoppingApp
https://github.com/aawab/newShoppingApp
32528b7c6a4c4afcd44a96c8a49fe78a8eb72f88
7e36d4654b4f2c8c755ccc0f3867c76f37129aba
refs/heads/master
2023-02-16T03:58:04.498000
2021-01-14T02:55:31
2021-01-14T02:55:31
329,177,971
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.shoppingapp; import android.view.View; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; public class Item { /** * Basic holder class for the items from database * Probably have to wait for Tony to send backend API so we can know how to name fields,etc */ //TODO wait for tony backend stuff to see if we need pics or not private String name; private String price; private String description; public Item(String name, String price, String description) { this.name = name; this.price = price; this.description = description; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
UTF-8
Java
1,097
java
Item.java
Java
[]
null
[]
package com.example.shoppingapp; import android.view.View; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; public class Item { /** * Basic holder class for the items from database * Probably have to wait for Tony to send backend API so we can know how to name fields,etc */ //TODO wait for tony backend stuff to see if we need pics or not private String name; private String price; private String description; public Item(String name, String price, String description) { this.name = name; this.price = price; this.description = description; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
1,097
0.645397
0.645397
51
20.509804
21.426914
95
false
false
0
0
0
0
0
0
0.372549
false
false
6
7834e909bdd37a449f12f9c8a617a37768af7d60
28,664,611,746,928
1e6deadb3d71d91e7c51bd7ecd679fe139c40fac
/time-utils/src/main/java/com/zxn/time/PatternType.java
7a0ca88af446a3974a6fd9bbea507ef419d70c33
[]
no_license
Lyngzh/TimeUtils
https://github.com/Lyngzh/TimeUtils
4e3c5d2b9fd25107ab9cb4865298d9e309c24107
a7b6f3cf99ad17ddbad6e420e26711250e7f83d7
refs/heads/master
2023-01-24T00:10:52.529000
2021-04-21T06:26:35
2021-04-21T06:26:35
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.zxn.time; import androidx.annotation.StringDef; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Updated by zxn on 2020/8/23. */ @StringDef({ SDFPattern.M_SDF_M, SDFPattern.yyyy_SDF_Y, SDFPattern.Md_SDF_P, SDFPattern.yyyyM_SDF_YM, SDFPattern.MMdd_SDF_P, SDFPattern.yyyyMMddHHmm_SDF, SDFPattern.yyyyMMddHHmmssSSS_SDF, SDFPattern.MMddHHmmSS_SDF_RCC, SDFPattern.yyyyMMdd_SDF_PP, SDFPattern.yyyyMMddHHmm_SDF_PPC, SDFPattern.yyyyMMddHHCmmCss_SDF_PPCC, SDFPattern.yyMMddHHmmssSSS_SDF, SDFPattern.yyyyMMddHHmmss_SDF, SDFPattern.yyyyMMdd_SDF, SDFPattern.yyyyMMddHHmm_SDF_RRC, SDFPattern.yyyyMMddHH_SDF_RR, SDFPattern.yyyyMM_SDF_R, SDFPattern.MMddHHmm_SDF_RC, SDFPattern.HHmmSS_SDF_CC, SDFPattern.HHmm_SDF_C, SDFPattern.yyyyMMddHHmmSS_SDF_YMDCC, SDFPattern.yyyyMdHHmmSS_SDF_YMDCC, SDFPattern.yyyyMdHHmm_SDF_YMDC, SDFPattern.yyyyMMdd_SDF_YMD, SDFPattern.yyyyMd_SDF_YMD, SDFPattern.MMdd_SDF_MD, SDFPattern.Md_SDF_MD, SDFPattern.MMddHHmmSS_SDF_MDCC, SDFPattern.MdHHmmSS_SDF_MDCC, SDFPattern.MdHHmm_SDF_MDC, SDFPattern.HHmmss_SDF, SDFPattern.HHmm_SDF, SDFPattern.MMdd_SDF_R, SDFPattern.yyyyMMdd_SDF_SPSP, SDFPattern.yyyyMMdd_SDF_RR, SDFPattern.yyyyMMddHHmmSS_SDF_SPSPCC, SDFPattern.yyyyMMddHHmmSS_SDF_RRCC,}) @Retention(RetentionPolicy.SOURCE) public @interface PatternType { }
UTF-8
Java
1,620
java
PatternType.java
Java
[ { "context": "ang.annotation.RetentionPolicy;\n\n/**\n * Updated by zxn on 2020/8/23.\n */\n@StringDef({\n SDFPattern", "end": 168, "score": 0.9996038675308228, "start": 165, "tag": "USERNAME", "value": "zxn" } ]
null
[]
package com.zxn.time; import androidx.annotation.StringDef; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Updated by zxn on 2020/8/23. */ @StringDef({ SDFPattern.M_SDF_M, SDFPattern.yyyy_SDF_Y, SDFPattern.Md_SDF_P, SDFPattern.yyyyM_SDF_YM, SDFPattern.MMdd_SDF_P, SDFPattern.yyyyMMddHHmm_SDF, SDFPattern.yyyyMMddHHmmssSSS_SDF, SDFPattern.MMddHHmmSS_SDF_RCC, SDFPattern.yyyyMMdd_SDF_PP, SDFPattern.yyyyMMddHHmm_SDF_PPC, SDFPattern.yyyyMMddHHCmmCss_SDF_PPCC, SDFPattern.yyMMddHHmmssSSS_SDF, SDFPattern.yyyyMMddHHmmss_SDF, SDFPattern.yyyyMMdd_SDF, SDFPattern.yyyyMMddHHmm_SDF_RRC, SDFPattern.yyyyMMddHH_SDF_RR, SDFPattern.yyyyMM_SDF_R, SDFPattern.MMddHHmm_SDF_RC, SDFPattern.HHmmSS_SDF_CC, SDFPattern.HHmm_SDF_C, SDFPattern.yyyyMMddHHmmSS_SDF_YMDCC, SDFPattern.yyyyMdHHmmSS_SDF_YMDCC, SDFPattern.yyyyMdHHmm_SDF_YMDC, SDFPattern.yyyyMMdd_SDF_YMD, SDFPattern.yyyyMd_SDF_YMD, SDFPattern.MMdd_SDF_MD, SDFPattern.Md_SDF_MD, SDFPattern.MMddHHmmSS_SDF_MDCC, SDFPattern.MdHHmmSS_SDF_MDCC, SDFPattern.MdHHmm_SDF_MDC, SDFPattern.HHmmss_SDF, SDFPattern.HHmm_SDF, SDFPattern.MMdd_SDF_R, SDFPattern.yyyyMMdd_SDF_SPSP, SDFPattern.yyyyMMdd_SDF_RR, SDFPattern.yyyyMMddHHmmSS_SDF_SPSPCC, SDFPattern.yyyyMMddHHmmSS_SDF_RRCC,}) @Retention(RetentionPolicy.SOURCE) public @interface PatternType { }
1,620
0.667901
0.66358
52
30.153847
12.936806
45
false
false
0
0
0
0
0
0
0.788462
false
false
6
f0930bf5271ac95aa6305fa54d71bb9ddca83741
18,141,941,924,385
7e69cc90dd151a43dd64cc9af7a652235cac048a
/DesignPatterns/src/couriercompany/ChainOResMain.java
6908bcce99ba3df5a826c447678270d1a4e0e6d2
[]
no_license
deyan98/design-patterns
https://github.com/deyan98/design-patterns
066324a0367dd68e7736793aef9fc4ff25b98012
dd0d8dfea131261cab29c45aa80b266a6e12e10e
refs/heads/master
2021-05-26T08:43:25.453000
2020-06-22T13:12:30
2020-06-22T13:12:30
254,062,780
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package couriercompany; public class ChainOResMain { private static Employee getChain() { Employee abroad = new AbroadEmployee(); Employee country = new CountryEmployee(); Employee insidePlovdiv = new InsidePlovdivEmployee(); insidePlovdiv.setNextEmployee(country); country.setNextEmployee(abroad); return insidePlovdiv; } public static void main(String[] args) { Employee chain = getChain(); Context abroad = new Context(""); Context country = new Context(""); Context insidePlovdiv = new Context(""); PreparationState preparationState = new PreparationState(); WaitingState waitingState = new WaitingState(); preparationState.applyState(abroad); waitingState.applyState(country); preparationState.applyState(insidePlovdiv); String firstEmployeeState = abroad.getState().getStateName(); String secondEmployeeState = country.getState().getStateName(); String thirdEmployeeState = insidePlovdiv.getState().getStateName(); Observer firstEmloyeeObserver = new ObserverState(firstEmployeeState); Observer secondEmloyeeObserver = new ObserverState(secondEmployeeState); Observer thirdEmloyeeObserver = new ObserverState(thirdEmployeeState); chain.chooseEmployee(1, firstEmployeeState, firstEmloyeeObserver); chain.chooseEmployee(2, secondEmployeeState, secondEmloyeeObserver); chain.chooseEmployee(3, thirdEmployeeState, thirdEmloyeeObserver); } }
UTF-8
Java
1,472
java
ChainOResMain.java
Java
[]
null
[]
package couriercompany; public class ChainOResMain { private static Employee getChain() { Employee abroad = new AbroadEmployee(); Employee country = new CountryEmployee(); Employee insidePlovdiv = new InsidePlovdivEmployee(); insidePlovdiv.setNextEmployee(country); country.setNextEmployee(abroad); return insidePlovdiv; } public static void main(String[] args) { Employee chain = getChain(); Context abroad = new Context(""); Context country = new Context(""); Context insidePlovdiv = new Context(""); PreparationState preparationState = new PreparationState(); WaitingState waitingState = new WaitingState(); preparationState.applyState(abroad); waitingState.applyState(country); preparationState.applyState(insidePlovdiv); String firstEmployeeState = abroad.getState().getStateName(); String secondEmployeeState = country.getState().getStateName(); String thirdEmployeeState = insidePlovdiv.getState().getStateName(); Observer firstEmloyeeObserver = new ObserverState(firstEmployeeState); Observer secondEmloyeeObserver = new ObserverState(secondEmployeeState); Observer thirdEmloyeeObserver = new ObserverState(thirdEmployeeState); chain.chooseEmployee(1, firstEmployeeState, firstEmloyeeObserver); chain.chooseEmployee(2, secondEmployeeState, secondEmloyeeObserver); chain.chooseEmployee(3, thirdEmployeeState, thirdEmloyeeObserver); } }
1,472
0.751359
0.749321
44
31.431818
26.088484
74
false
false
0
0
0
0
0
0
2.318182
false
false
6
5ad6bbec834e1775d9249012ee91ee6f5e46afd7
22,222,160,801,363
b94d00a255a7d366dab4c2f348de4df74bea48e6
/cloud-config-center-3344/src/main/java/com/atguigu/springcloud/ConfigCenterMain9527.java
d9ded930a98c53de4e86c2f0a356bd5559476277
[]
no_license
HelloWorldwangjiacheng/springcloud-config
https://github.com/HelloWorldwangjiacheng/springcloud-config
be626819433f619f3b96ddf52e6200109302a076
29a86b2d7f0665a44851d93724b578d8c564e9a8
refs/heads/master
2022-12-04T12:09:51.422000
2020-08-10T03:45:28
2020-08-10T03:45:28
286,363,732
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.atguigu.springcloud; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration; import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.config.server.EnableConfigServer; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; /** * @author w1586 */ @SpringBootApplication(exclude = { DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class}) @EnableEurekaClient @EnableDiscoveryClient @EnableConfigServer public class ConfigCenterMain9527 { public static void main(String[] args) { SpringApplication.run(ConfigCenterMain9527.class, args); } }
UTF-8
Java
1,053
java
ConfigCenterMain9527.java
Java
[ { "context": "netflix.eureka.EnableEurekaClient;\n\n/**\n * @author w1586\n */\n@SpringBootApplication(exclude = {\n Da", "end": 646, "score": 0.9993470311164856, "start": 641, "tag": "USERNAME", "value": "w1586" } ]
null
[]
package com.atguigu.springcloud; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration; import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.config.server.EnableConfigServer; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; /** * @author w1586 */ @SpringBootApplication(exclude = { DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class}) @EnableEurekaClient @EnableDiscoveryClient @EnableConfigServer public class ConfigCenterMain9527 { public static void main(String[] args) { SpringApplication.run(ConfigCenterMain9527.class, args); } }
1,053
0.834758
0.823362
27
38
29.229614
97
false
false
0
0
0
0
0
0
0.481481
false
false
6
df9e26c5f2812a0616860858443c5a7f09a74aed
23,880,018,202,505
6ef4869c6bc2ce2e77b422242e347819f6a5f665
/devices/google/Pixel 2/29/QPP6.190730.005/src/bouncycastle/com/android/org/bouncycastle/jcajce/provider/config/PKCS12StoreParameter.java
ceaeebba1e4f179a1493e087d47bd393f4e17af6
[]
no_license
hacking-android/frameworks
https://github.com/hacking-android/frameworks
40e40396bb2edacccabf8a920fa5722b021fb060
943f0b4d46f72532a419fb6171e40d1c93984c8e
refs/heads/master
2020-07-03T19:32:28.876000
2019-08-13T03:31:06
2019-08-13T03:31:06
202,017,534
2
0
null
false
2019-08-13T03:33:19
2019-08-12T22:19:30
2019-08-13T03:31:53
2019-08-13T03:33:18
63,898
0
0
0
Java
false
false
/* * Decompiled with CFR 0.145. */ package com.android.org.bouncycastle.jcajce.provider.config; import java.io.OutputStream; import java.security.KeyStore; public class PKCS12StoreParameter extends com.android.org.bouncycastle.jcajce.PKCS12StoreParameter { public PKCS12StoreParameter(OutputStream outputStream, KeyStore.ProtectionParameter protectionParameter) { super(outputStream, protectionParameter, false); } public PKCS12StoreParameter(OutputStream outputStream, KeyStore.ProtectionParameter protectionParameter, boolean bl) { super(outputStream, protectionParameter, bl); } public PKCS12StoreParameter(OutputStream outputStream, char[] arrc) { super(outputStream, arrc, false); } public PKCS12StoreParameter(OutputStream outputStream, char[] arrc, boolean bl) { super(outputStream, new KeyStore.PasswordProtection(arrc), bl); } }
UTF-8
Java
910
java
PKCS12StoreParameter.java
Java
[]
null
[]
/* * Decompiled with CFR 0.145. */ package com.android.org.bouncycastle.jcajce.provider.config; import java.io.OutputStream; import java.security.KeyStore; public class PKCS12StoreParameter extends com.android.org.bouncycastle.jcajce.PKCS12StoreParameter { public PKCS12StoreParameter(OutputStream outputStream, KeyStore.ProtectionParameter protectionParameter) { super(outputStream, protectionParameter, false); } public PKCS12StoreParameter(OutputStream outputStream, KeyStore.ProtectionParameter protectionParameter, boolean bl) { super(outputStream, protectionParameter, bl); } public PKCS12StoreParameter(OutputStream outputStream, char[] arrc) { super(outputStream, arrc, false); } public PKCS12StoreParameter(OutputStream outputStream, char[] arrc, boolean bl) { super(outputStream, new KeyStore.PasswordProtection(arrc), bl); } }
910
0.763736
0.746154
26
33.96154
36.109322
122
false
false
0
0
0
0
0
0
0.807692
false
false
6
f51bda156e46fee3b1d2836ec28c013c6b13aa93
18,313,740,560,992
5e9696feef2631fc29a0b29200825910859db920
/src/main/java/com/example/webflux/domain/User.java
53ae454d0e368e301e8b1eba6017fcb733a5c59b
[]
no_license
LucasAlvez/webflux-functional-scylla
https://github.com/LucasAlvez/webflux-functional-scylla
12690e5e7bff4c2821caf6a5e3ad022d2b526314
a3094b6083be4ef22c4b08234156e3aedaeacf61
refs/heads/master
2020-05-16T19:04:17.244000
2019-09-02T01:54:41
2019-09-02T01:54:41
183,246,624
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.webflux.domain; import org.springframework.data.cassandra.core.mapping.Column; import org.springframework.data.cassandra.core.mapping.PrimaryKey; import org.springframework.data.cassandra.core.mapping.Table; /** * The type User. */ @Table("user") public class User { /** * User key. */ @PrimaryKey private UserKey key; /** * User name. */ @Column("name") private String name; /** * User domain */ @Column("domain") private String domain; /** * Instantiates a new User. */ public User() { // Default constructor. } /** * Instantiates a new User. * * @param key the key * @param name the name * @param domain the domain */ public User(UserKey key, String name, String domain) { this.key = key; this.name = name; this.domain = domain; } /** * Gets key. * * @return the key */ public UserKey getKey() { return key; } /** * Sets key. * * @param key the key */ public void setKey(UserKey key) { this.key = key; } /** * Gets name. * * @return the name */ public String getName() { return name; } /** * Sets name. * * @param name the name */ public void setName(String name) { this.name = name; } /** * Gets domain. * * @return the domain */ public String getDomain() { return domain; } /** * Sets domain. * * @param domain the domain */ public void setDomain(String domain) { this.domain = domain; } }
UTF-8
Java
1,737
java
User.java
Java
[]
null
[]
package com.example.webflux.domain; import org.springframework.data.cassandra.core.mapping.Column; import org.springframework.data.cassandra.core.mapping.PrimaryKey; import org.springframework.data.cassandra.core.mapping.Table; /** * The type User. */ @Table("user") public class User { /** * User key. */ @PrimaryKey private UserKey key; /** * User name. */ @Column("name") private String name; /** * User domain */ @Column("domain") private String domain; /** * Instantiates a new User. */ public User() { // Default constructor. } /** * Instantiates a new User. * * @param key the key * @param name the name * @param domain the domain */ public User(UserKey key, String name, String domain) { this.key = key; this.name = name; this.domain = domain; } /** * Gets key. * * @return the key */ public UserKey getKey() { return key; } /** * Sets key. * * @param key the key */ public void setKey(UserKey key) { this.key = key; } /** * Gets name. * * @return the name */ public String getName() { return name; } /** * Sets name. * * @param name the name */ public void setName(String name) { this.name = name; } /** * Gets domain. * * @return the domain */ public String getDomain() { return domain; } /** * Sets domain. * * @param domain the domain */ public void setDomain(String domain) { this.domain = domain; } }
1,737
0.512378
0.512378
104
15.701923
14.222733
66
false
false
0
0
0
0
0
0
0.173077
false
false
6
b59076a0217f3915080a31851487dfc216d755ba
2,628,519,998,545
6c29e7cdf8a0d86fd93fe1a5897f61d086fde6e2
/src/main/java/com/leet/common/Console.java
6079735156bfb71969e36235f213eafc1c041276
[]
no_license
shivam-tripathi/compSci
https://github.com/shivam-tripathi/compSci
dd835d6704c042ac0f2c6fa4afc13989dd9fc38e
32846cf9c38116e1b325b1dfbadf25ff31fdb8e6
refs/heads/master
2021-12-10T04:11:43.399000
2021-12-08T16:28:29
2021-12-08T16:28:29
205,308,548
3
0
null
false
2020-07-19T19:35:39
2019-08-30T05:08:37
2020-03-07T03:43:45
2020-07-19T19:35:38
188
3
0
2
Java
false
false
package com.leet.common; import java.util.Arrays; import java.util.Objects; import java.util.stream.Collectors; public class Console { static void log(Object... objects) { System.out.println(Arrays.stream(objects).map(Objects::toString).collect(Collectors.joining(" "))); } }
UTF-8
Java
286
java
Console.java
Java
[]
null
[]
package com.leet.common; import java.util.Arrays; import java.util.Objects; import java.util.stream.Collectors; public class Console { static void log(Object... objects) { System.out.println(Arrays.stream(objects).map(Objects::toString).collect(Collectors.joining(" "))); } }
286
0.741259
0.741259
11
25
28.081051
103
false
false
0
0
0
0
0
0
0.454545
false
false
6
bd20aaa2006970dae836788d9d35af6f597021e6
9,259,949,536,329
e6edadd37fb423c62d1e6f8f018bdb65ee017294
/ReadFile.java
e90afb6258c1771a2eb4e7c10fb12244d419d413
[]
no_license
linkai1994/Online-Store
https://github.com/linkai1994/Online-Store
a32c00a431d4198a382fe881278ea3167b460829
44f02a408a0065a86ad8a0b9e942963244d4180a
refs/heads/master
2020-03-07T17:19:08.430000
2018-04-01T08:03:17
2018-04-01T08:03:17
127,607,923
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class ReadFile { public byte[] GetFileArray(String absolutePath) throws IOException { FileInputStream fs=new FileInputStream(absolutePath); byte[] filearr=new byte[fs.available()]; try { while(fs.read(filearr)>0){} } finally { fs.close(); } return filearr; } }
UTF-8
Java
409
java
ReadFile.java
Java
[]
null
[]
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class ReadFile { public byte[] GetFileArray(String absolutePath) throws IOException { FileInputStream fs=new FileInputStream(absolutePath); byte[] filearr=new byte[fs.available()]; try { while(fs.read(filearr)>0){} } finally { fs.close(); } return filearr; } }
409
0.694377
0.691932
26
14.730769
18.373386
67
false
false
0
0
0
0
0
0
1.653846
false
false
6
ed2e59593aa96a09b9d5bb5d7510188f5174a8f6
9,259,949,537,224
e717c6c8b6020fd8dec3acb7ca488e4be7c23d85
/src/linghun/me/custompvp/Command/AdminCommand.java
8fbafc6c1c2f608caa62c55cfbeed0f7c54f0342
[]
no_license
shellljx/CustomPVP
https://github.com/shellljx/CustomPVP
75256ea24fc15542a1e2ec26fedd09e73de771f8
39e8abf923da413fccec6898d094c6d2e1739b9d
refs/heads/master
2017-12-04T05:50:55.637000
2015-08-29T14:47:25
2015-08-29T14:47:25
40,771,705
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package linghun.me.custompvp.Command; /** * Created by shell on 15-8-15. */ import java.util.ArrayList; import java.util.List; import linghun.me.custompvp.CustomPVP; import linghun.me.custompvp.Model.Arena; import linghun.me.custompvp.Model.PersonArena; import linghun.me.custompvp.Model.TeamArena; import linghun.me.custompvp.utils.SerializableLocation; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Item; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; public class AdminCommand implements CommandExecutor { private CustomPVP plugin; public AdminCommand(CustomPVP plugin) { this.plugin = plugin; } public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if ((args.length == 0) && (sender.isOp())) { sender.sendMessage(ChatColor.AQUA + "====================" + ChatColor.YELLOW + this.plugin.getConfig().getString("setting.menu.title") + ChatColor.AQUA + "===================="); sender.sendMessage(ChatColor.AQUA + "/cpadmin create <竞技场名字> <模式(person/team)>" + ChatColor.YELLOW + " 创建竞技场(所站位置为竞技场出生点)"); sender.sendMessage(ChatColor.AQUA + "/cpadmin del <竞技场名字> " + ChatColor.YELLOW + "删除竞技场"); sender.sendMessage(ChatColor.AQUA + "/cpadmin sethome " + ChatColor.YELLOW + "设置竞技场出生点"); //sender.sendMessage(ChatColor.AQUA + "/cpadmin set <属性> <值> <值类型(int/true/false)> " + ChatColor.YELLOW + "设置竞技场属性"); //sender.sendMessage(ChatColor.AQUA + "������������:" + ChatColor.YELLOW + "limited(������������),friendlyFire(������������)"); sender.sendMessage(ChatColor.AQUA + "========================================================================="); return true; } if ((args.length == 3) && (args[0].equals("create")) && (sender.isOp())) { Player player = (Player)sender; Location location = player.getLocation(); String mode = args[2]; if ((!mode.equals("person")) && (!mode.equals("team"))) { sender.sendMessage(ChatColor.RED + "[竞技场系统]没有该竞技场模式!"); return true; } if (this.plugin.getArenas().containsKey(args[1])) { sender.sendMessage(ChatColor.RED + "[竞技场系统]该竞技场已经存在请重新输入"); return true; } Arena arena = null; if (mode.equals("team")) { arena = new TeamArena(args[1], 30, false, mode, location); } else if (mode.equals("person")) { arena = new PersonArena(args[1], 30, false, mode, location); } if (arena == null) { sender.sendMessage("[竞技场系统]创建竞技场失败!"); return true; } this.plugin.getArenas().put(args[1], arena); sender.sendMessage(ChatColor.AQUA + "[竞技场系统]竞技场" + ChatColor.YELLOW + args[1] + ChatColor.AQUA + "创建成功"); return true; } if ((args.length == 1) && (args[0].equals("sethome")) && (sender.isOp())) { Player player = (Player)sender; Location location = player.getLocation(); SerializableLocation sl = new SerializableLocation(location); this.plugin.getConfig().set("setting.resurrection-point", sl); player.sendMessage(ChatColor.AQUA + "[竞技场系统]" + ChatColor.YELLOW + "竞技场复活点创建成功!"); return true; } if(args.length==2&&args[0].equals("del")&&sender.isOp()){ Arena arena = plugin.getArenas().get(args[1]); if(arena.isRunning()){ sender.sendMessage(ChatColor.AQUA+"[竞技场系统]"+ChatColor.YELLOW+"竞技场正在运行,不能删除!"); return true; } plugin.getArenas().remove(args[1]); sender.sendMessage(ChatColor.AQUA+"[竞技场系统]"+ChatColor.YELLOW+"该竞技场已经被删除!"); return true; } if(args.length==2&&args[0].equals("kits")&&sender.isOp()){ String areaName = args[1]; Player player = (Player)sender; List<ItemStack> invItems = new ArrayList<>(); if(isInvEmpty(player,invItems)&&isArmEmpty(player)){ sender.sendMessage(ChatColor.AQUA+"[竞技场系统]执行该指令请确定背包里有物品"); return true; } if(plugin.getConfig().contains("setting.items."+areaName)){ plugin.getConfig().set("setting.items."+areaName,null); } for (int i=0;i<invItems.size();i++){ plugin.getConfig().set("setting.items." + areaName + ".inv.item-"+i, invItems.get(i)); } resotreArmItems(player, areaName); sender.sendMessage(ChatColor.AQUA + "[竞技场系统]成功添加竞技场装备!"); return true; } if(args[0].equals("test")){ Player player = (Player)sender; if (plugin.getConfig().contains("setting.items.pvp.inv")){ for (String key:plugin.getConfig().getConfigurationSection("setting.items.pvp.inv").getValues(false).keySet()){ ItemStack itemStack = (ItemStack) plugin.getConfig().get("setting.items.pvp.inv."+key); player.getInventory().addItem(itemStack); } } player.getInventory().setBoots((ItemStack) plugin.getConfig().get("setting.items.pvp.arm.boots")); player.getInventory().setLeggings((ItemStack) plugin.getConfig().get("setting.items.pvp.arm.leggings")); player.getInventory().setChestplate((ItemStack) plugin.getConfig().get("setting.items.pvp.arm.chestplate")); player.getInventory().setHelmet((ItemStack) plugin.getConfig().get("setting.items.pvp.arm.helmet")); } return true; } private void resotreArmItems(Player player,String areaName){ if (player.getInventory().getHelmet()!=null){ plugin.getConfig().set("setting.items." + areaName + ".arm.helmet", player.getInventory().getHelmet()); } if (player.getInventory().getChestplate()!=null){ plugin.getConfig().set("setting.items." + areaName + ".arm.chestplate", player.getInventory().getChestplate()); } if (player.getInventory().getLeggings()!=null){ plugin.getConfig().set("setting.items." + areaName + ".arm.leggings", player.getInventory().getLeggings()); } if (player.getInventory().getBoots()!=null){ plugin.getConfig().set("setting.items." + areaName + ".arm.boots", player.getInventory().getBoots()); } } private boolean isInvEmpty(Player player,List<ItemStack> inv){ boolean status = true; for (ItemStack item:player.getInventory().getContents()){ if (item!=null){ status = false; inv.add(item); } } return status; } private boolean isArmEmpty(Player player){ ItemStack[] arms = player.getInventory().getArmorContents(); if (arms[0].getType().equals(Material.AIR)&&arms[1].getType().equals(Material.AIR)&&arms[2].getType().equals(Material.AIR)&&arms[3].getType().equals(Material.AIR)) return true; return false; } }
UTF-8
Java
7,926
java
AdminCommand.java
Java
[ { "context": "e linghun.me.custompvp.Command;\n\n/**\n * Created by shell on 15-8-15.\n */\n\nimport java.util.ArrayList;\nimpo", "end": 62, "score": 0.9962087273597717, "start": 57, "tag": "USERNAME", "value": "shell" } ]
null
[]
package linghun.me.custompvp.Command; /** * Created by shell on 15-8-15. */ import java.util.ArrayList; import java.util.List; import linghun.me.custompvp.CustomPVP; import linghun.me.custompvp.Model.Arena; import linghun.me.custompvp.Model.PersonArena; import linghun.me.custompvp.Model.TeamArena; import linghun.me.custompvp.utils.SerializableLocation; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Item; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; public class AdminCommand implements CommandExecutor { private CustomPVP plugin; public AdminCommand(CustomPVP plugin) { this.plugin = plugin; } public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if ((args.length == 0) && (sender.isOp())) { sender.sendMessage(ChatColor.AQUA + "====================" + ChatColor.YELLOW + this.plugin.getConfig().getString("setting.menu.title") + ChatColor.AQUA + "===================="); sender.sendMessage(ChatColor.AQUA + "/cpadmin create <竞技场名字> <模式(person/team)>" + ChatColor.YELLOW + " 创建竞技场(所站位置为竞技场出生点)"); sender.sendMessage(ChatColor.AQUA + "/cpadmin del <竞技场名字> " + ChatColor.YELLOW + "删除竞技场"); sender.sendMessage(ChatColor.AQUA + "/cpadmin sethome " + ChatColor.YELLOW + "设置竞技场出生点"); //sender.sendMessage(ChatColor.AQUA + "/cpadmin set <属性> <值> <值类型(int/true/false)> " + ChatColor.YELLOW + "设置竞技场属性"); //sender.sendMessage(ChatColor.AQUA + "������������:" + ChatColor.YELLOW + "limited(������������),friendlyFire(������������)"); sender.sendMessage(ChatColor.AQUA + "========================================================================="); return true; } if ((args.length == 3) && (args[0].equals("create")) && (sender.isOp())) { Player player = (Player)sender; Location location = player.getLocation(); String mode = args[2]; if ((!mode.equals("person")) && (!mode.equals("team"))) { sender.sendMessage(ChatColor.RED + "[竞技场系统]没有该竞技场模式!"); return true; } if (this.plugin.getArenas().containsKey(args[1])) { sender.sendMessage(ChatColor.RED + "[竞技场系统]该竞技场已经存在请重新输入"); return true; } Arena arena = null; if (mode.equals("team")) { arena = new TeamArena(args[1], 30, false, mode, location); } else if (mode.equals("person")) { arena = new PersonArena(args[1], 30, false, mode, location); } if (arena == null) { sender.sendMessage("[竞技场系统]创建竞技场失败!"); return true; } this.plugin.getArenas().put(args[1], arena); sender.sendMessage(ChatColor.AQUA + "[竞技场系统]竞技场" + ChatColor.YELLOW + args[1] + ChatColor.AQUA + "创建成功"); return true; } if ((args.length == 1) && (args[0].equals("sethome")) && (sender.isOp())) { Player player = (Player)sender; Location location = player.getLocation(); SerializableLocation sl = new SerializableLocation(location); this.plugin.getConfig().set("setting.resurrection-point", sl); player.sendMessage(ChatColor.AQUA + "[竞技场系统]" + ChatColor.YELLOW + "竞技场复活点创建成功!"); return true; } if(args.length==2&&args[0].equals("del")&&sender.isOp()){ Arena arena = plugin.getArenas().get(args[1]); if(arena.isRunning()){ sender.sendMessage(ChatColor.AQUA+"[竞技场系统]"+ChatColor.YELLOW+"竞技场正在运行,不能删除!"); return true; } plugin.getArenas().remove(args[1]); sender.sendMessage(ChatColor.AQUA+"[竞技场系统]"+ChatColor.YELLOW+"该竞技场已经被删除!"); return true; } if(args.length==2&&args[0].equals("kits")&&sender.isOp()){ String areaName = args[1]; Player player = (Player)sender; List<ItemStack> invItems = new ArrayList<>(); if(isInvEmpty(player,invItems)&&isArmEmpty(player)){ sender.sendMessage(ChatColor.AQUA+"[竞技场系统]执行该指令请确定背包里有物品"); return true; } if(plugin.getConfig().contains("setting.items."+areaName)){ plugin.getConfig().set("setting.items."+areaName,null); } for (int i=0;i<invItems.size();i++){ plugin.getConfig().set("setting.items." + areaName + ".inv.item-"+i, invItems.get(i)); } resotreArmItems(player, areaName); sender.sendMessage(ChatColor.AQUA + "[竞技场系统]成功添加竞技场装备!"); return true; } if(args[0].equals("test")){ Player player = (Player)sender; if (plugin.getConfig().contains("setting.items.pvp.inv")){ for (String key:plugin.getConfig().getConfigurationSection("setting.items.pvp.inv").getValues(false).keySet()){ ItemStack itemStack = (ItemStack) plugin.getConfig().get("setting.items.pvp.inv."+key); player.getInventory().addItem(itemStack); } } player.getInventory().setBoots((ItemStack) plugin.getConfig().get("setting.items.pvp.arm.boots")); player.getInventory().setLeggings((ItemStack) plugin.getConfig().get("setting.items.pvp.arm.leggings")); player.getInventory().setChestplate((ItemStack) plugin.getConfig().get("setting.items.pvp.arm.chestplate")); player.getInventory().setHelmet((ItemStack) plugin.getConfig().get("setting.items.pvp.arm.helmet")); } return true; } private void resotreArmItems(Player player,String areaName){ if (player.getInventory().getHelmet()!=null){ plugin.getConfig().set("setting.items." + areaName + ".arm.helmet", player.getInventory().getHelmet()); } if (player.getInventory().getChestplate()!=null){ plugin.getConfig().set("setting.items." + areaName + ".arm.chestplate", player.getInventory().getChestplate()); } if (player.getInventory().getLeggings()!=null){ plugin.getConfig().set("setting.items." + areaName + ".arm.leggings", player.getInventory().getLeggings()); } if (player.getInventory().getBoots()!=null){ plugin.getConfig().set("setting.items." + areaName + ".arm.boots", player.getInventory().getBoots()); } } private boolean isInvEmpty(Player player,List<ItemStack> inv){ boolean status = true; for (ItemStack item:player.getInventory().getContents()){ if (item!=null){ status = false; inv.add(item); } } return status; } private boolean isArmEmpty(Player player){ ItemStack[] arms = player.getInventory().getArmorContents(); if (arms[0].getType().equals(Material.AIR)&&arms[1].getType().equals(Material.AIR)&&arms[2].getType().equals(Material.AIR)&&arms[3].getType().equals(Material.AIR)) return true; return false; } }
7,926
0.578384
0.57397
164
44.585365
38.345016
191
false
false
0
0
0
0
73
0.009765
0.664634
false
false
6
5d4aabca02dc582e1eb091cfdca4b91b980b01cd
10,625,749,133,851
24056ce985637199283155b3bd07e9d1d2206469
/src/main/java/com/lhh/config/Neo4jJdbcUtils.java
7953b030bdfe0fd451db28136cd86a8d81953ef9
[]
no_license
hwaggLee-lhh/lhh-neo4j
https://github.com/hwaggLee-lhh/lhh-neo4j
ea796b70c84c647e869a85c21c751fba0cad4348
b4d1db10e20ace1af804fd620e9f66b2b16b9dfc
refs/heads/master
2020-06-18T19:32:09.946000
2016-12-15T08:28:53
2016-12-15T08:28:53
74,944,386
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lhh.config; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class Neo4jJdbcUtils { // 数据库用户名 private static String USERNAME = "neo4j"; // 数据库密码 private static String PASSWORD = "a123456"; // 驱动信息 private static String DRIVER = "org.neo4j.jdbc.Driver"; public static int JDBCPOOLINITSIZE = 10; // 数据库地址 private static String URL = "jdbc:neo4j:http://61.152.154.22:7474"; // static{ // InputStream in = Neo4jJdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties"); // Properties prop = new Properties(); // try { // prop.load(in); // DRIVER = prop.getProperty("neo4j.connection.driver_class"); // URL = prop.getProperty("neo4j.db.connection.url"); // USERNAME = prop.getProperty("neo4j.db.connection.username"); // PASSWORD = prop.getProperty("neo4j.db.connection.password"); // JDBCPOOLINITSIZE =Integer.parseInt(prop.getProperty("neo4j.jdbcPoolInitSize"));//数据库连接池的初始化连接数大小 // Class.forName(DRIVER); // } catch (Exception e) { // throw new ExceptionInInitializerError(e); // } // } public Neo4jJdbcUtils() { } public Connection getConnection(){ return getCreateConnection(); } private Connection conn; /** * 调用这个连接将不允许被关闭 * @return */ public synchronized Connection getFreeConnection(){ if( conn == null ){ conn = getCreateConnection(); return conn; } try { if( conn.isClosed() ){ conn = getCreateConnection(); return conn; } } catch (SQLException e) { e.printStackTrace(); } return conn; } public Neo4jJdbcUtils(String username, String password, String driver, String url) { USERNAME = username; PASSWORD = password; DRIVER = driver; URL = url; } /** * 获得数据库的连接 * * @return */ private Connection getCreateConnection() { Connection connection = null; try { Class.forName(DRIVER); connection = DriverManager.getConnection(URL, USERNAME, PASSWORD); } catch (Exception e) { e.printStackTrace(); } return connection; } public static void closeStatement(Statement stmt) { if (stmt != null) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static void closeResultSett(ResultSet rs) { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } public void testJDBC() throws SQLException { Connection con = DriverManager.getConnection(URL, USERNAME, PASSWORD); // Querying try (Statement stmt = con.createStatement()) { ResultSet rs = stmt.executeQuery("MATCH (n) RETURN n"); while (rs.next()) { System.out.println(rs.getString("n")); } } } public static void main(String[] args) { Neo4jJdbcUtils utils = new Neo4jJdbcUtils(); try { utils.testJDBC(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
UTF-8
Java
3,184
java
Neo4jJdbcUtils.java
Java
[ { "context": " {\n\n\t// 数据库用户名\n\tprivate static String USERNAME = \"neo4j\";\n\t// 数据库密码\n\tprivate static String PASSWORD = \"a1", "end": 251, "score": 0.9990065693855286, "start": 246, "tag": "USERNAME", "value": "neo4j" }, { "context": "4j\";\n\t// 数据库密码\n\tprivate static String...
null
[]
package com.lhh.config; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class Neo4jJdbcUtils { // 数据库用户名 private static String USERNAME = "neo4j"; // 数据库密码 private static String PASSWORD = "<PASSWORD>"; // 驱动信息 private static String DRIVER = "org.neo4j.jdbc.Driver"; public static int JDBCPOOLINITSIZE = 10; // 数据库地址 private static String URL = "jdbc:neo4j:http://192.168.3.11:7474"; // static{ // InputStream in = Neo4jJdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties"); // Properties prop = new Properties(); // try { // prop.load(in); // DRIVER = prop.getProperty("neo4j.connection.driver_class"); // URL = prop.getProperty("neo4j.db.connection.url"); // USERNAME = prop.getProperty("neo4j.db.connection.username"); // PASSWORD = prop.getProperty("neo4j.db.connection.password"); // JDBCPOOLINITSIZE =Integer.parseInt(prop.getProperty("neo4j.jdbcPoolInitSize"));//数据库连接池的初始化连接数大小 // Class.forName(DRIVER); // } catch (Exception e) { // throw new ExceptionInInitializerError(e); // } // } public Neo4jJdbcUtils() { } public Connection getConnection(){ return getCreateConnection(); } private Connection conn; /** * 调用这个连接将不允许被关闭 * @return */ public synchronized Connection getFreeConnection(){ if( conn == null ){ conn = getCreateConnection(); return conn; } try { if( conn.isClosed() ){ conn = getCreateConnection(); return conn; } } catch (SQLException e) { e.printStackTrace(); } return conn; } public Neo4jJdbcUtils(String username, String password, String driver, String url) { USERNAME = username; PASSWORD = <PASSWORD>; DRIVER = driver; URL = url; } /** * 获得数据库的连接 * * @return */ private Connection getCreateConnection() { Connection connection = null; try { Class.forName(DRIVER); connection = DriverManager.getConnection(URL, USERNAME, PASSWORD); } catch (Exception e) { e.printStackTrace(); } return connection; } public static void closeStatement(Statement stmt) { if (stmt != null) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static void closeResultSett(ResultSet rs) { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } public void testJDBC() throws SQLException { Connection con = DriverManager.getConnection(URL, USERNAME, PASSWORD); // Querying try (Statement stmt = con.createStatement()) { ResultSet rs = stmt.executeQuery("MATCH (n) RETURN n"); while (rs.next()) { System.out.println(rs.getString("n")); } } } public static void main(String[] args) { Neo4jJdbcUtils utils = new Neo4jJdbcUtils(); try { utils.testJDBC(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
3,188
0.648763
0.637044
130
22.63077
22.698742
110
false
false
0
0
0
0
0
0
1.861538
false
false
6
448daafaf5b7f6394a79c3bec1ee459c761305e5
36,223,754,185,078
1f3fd708ebd23dbf94a9ea00b9581d1dae96c174
/src/main/java/com/ryankolbe/factory/PackagingFactory.java
d0007cb5838a4385e0bda8e5cda31d5b00481b4b
[]
no_license
RyanKolbe/ArtDomain
https://github.com/RyanKolbe/ArtDomain
4d29fe339021b9f7be8e686d43929f5a326b1563
b479a37c3c87cf38a00e83df70759bf525e207b2
refs/heads/master
2022-07-29T11:34:38.529000
2019-09-29T18:19:06
2019-09-29T18:19:06
180,628,934
0
0
null
false
2022-06-21T01:54:12
2019-04-10T17:16:05
2019-09-29T18:21:04
2022-06-21T01:54:12
1,480
0
0
2
Java
false
false
package com.ryankolbe.factory; import com.ryankolbe.domain.Packaging; public class PackagingFactory { public static Packaging createPackaging(String packagingId, String packagingHeight, String packagingWidth, String packagingLength) { return new Packaging.Builder() .packagingId(packagingId) .packagingHeight(packagingHeight) .packagingWidth(packagingWidth) .packagingLength(packagingLength) .build(); } }
UTF-8
Java
548
java
PackagingFactory.java
Java
[]
null
[]
package com.ryankolbe.factory; import com.ryankolbe.domain.Packaging; public class PackagingFactory { public static Packaging createPackaging(String packagingId, String packagingHeight, String packagingWidth, String packagingLength) { return new Packaging.Builder() .packagingId(packagingId) .packagingHeight(packagingHeight) .packagingWidth(packagingWidth) .packagingLength(packagingLength) .build(); } }
548
0.622263
0.622263
16
33.3125
28.720026
110
false
false
0
0
0
0
0
0
0.375
false
false
6
5f26f03eca163ded6ecef4c4b2870fc36ad67c7e
36,404,142,821,732
5fa6b4c32f8c5363692c4926f0fbb3ae1247699c
/src/Driver.java
04f266abfc314e44a575f53ff3a6578fac13f94c
[]
no_license
brohand/Math2605Project
https://github.com/brohand/Math2605Project
4af2c187039b58e20482fc90f399cb4b7ea9cb52
e4640f1def3ef2e86ca78698b80d35b04278a4cb
refs/heads/master
2021-01-17T11:05:52.341000
2017-04-25T05:22:02
2017-04-25T05:22:02
32,362,725
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Created by super_000 on 3/9/2015. */ import java.text.NumberFormat; import java.util.Scanner; //import com.googlecode.charts4j.*; import java.io.*; import com.xeiam.xchart.Chart; import com.xeiam.xchart.QuickChart; import com.xeiam.xchart.SwingWrapper; public class Driver { private static Scanner darkly = new Scanner(System.in); public static void main(String[] args) throws FileNotFoundException { NumberFormat nf = NumberFormat.getInstance(); nf.setMaximumFractionDigits(5); boolean loop = true; while(loop) { System.out.println("HILBERT ERROR VISUALIZATION PROGRAM ULTIMATE ARCADE EDITION v0.0000001"); System.out.println("CHOOSE THY FATE"); System.out.println("1. Hilbert QR Visualization"); System.out.println("2. Hilbert LU Visualization"); System.out.println("3. Test Matrix Functions"); System.out.println("4. Exit"); int fate = darkly.nextInt(); switch (fate) { case 1: qrVisualizer(); break; case 2: luVisualizer(); break; case 3: matrixMenu(); break; case 4: System.out.println(""); System.out.println("JU"); loop = false; break; } } } public static void matrixMenu() throws FileNotFoundException{ boolean loop = true; //File augFile = new File(darkly.next()); while(loop) { //Matrix System.out.println("What would you liked to do?"); System.out.println("1. Find Q and R of a matrix with HouseHolders"); System.out.println("2. Find Q and R of matrix with Givens"); System.out.println("3. Ax = b with HouseHolders"); System.out.println("4. Ax = b with Givens"); System.out.println("5. LU Decomposition of a matrix"); System.out.println("6. Solve LU b"); System.out.println("7. Go back"); String pause; try { switch (darkly.nextInt()) { case 1: System.out.println("Please enter a matrix as a .dat file into the project root."); System.out.println("Enter the full name of the file, with the .dat extension."); Matrix A = DatParser.datToMatrix(new File(darkly.next())); System.out.println("QR Calculation of a matrix with HouseHolders is in progress."); Matrix Q = Householder.getQ(A); Matrix R = Householder.getR(A); System.out.println("The original matrix is: "); A.print(10, 5); System.out.print("The Q matrix : "); Q.print(10, 5); System.out.print("The R matrix is: "); R.print(10, 5); System.out.print("Error (QR - H) = " + Householder.error(A)); System.out.println(""); System.out.println(""); System.out.print("Enter any letter to continue... "); pause = darkly.next(); System.out.println(""); break; case 2: System.out.println("Please enter a matrix as a .dat file into the project root."); System.out.println("Enter the full name of the file, with the .dat extension."); A = DatParser.datToMatrix(new File(darkly.next())); System.out.println("QR Calculation of a matrix with Givens is in progress."); GivensQR qrA = new GivensQR(A); Q = qrA.Q; R = qrA.R; System.out.println("The original matrix is: "); A.print(10, 5); System.out.print("The Q matrix : "); Q.print(10, 5); System.out.print("The R matrix is: "); R.print(10, 5); System.out.print("Error (QR - H) = " + qrA.getError()); System.out.println(""); System.out.println(""); System.out.print("Enter any letter to continue... "); pause = darkly.next(); System.out.println(""); break; case 3: System.out.println("Please enter an augmented matrix as a .dat file into the project root."); System.out.println("Enter the full name of the file, with the .dat extension."); File augFile = new File(darkly.next()); A = augSplitA(augFile); System.out.println("Ax=b Calculation of a matrix with Householders is in progress."); Matrix b = augSplitb(augFile); Matrix sol = solve_qr_b.houseSolve(A, b); System.out.println("The original matrix, A, is: "); A.print(10, 5); System.out.print("The solved vector, x, is: "); sol.print(10, 10); System.out.print("The b vector is: "); b.print(10, 10); System.out.print("Error (Hx - b) = " + A.times(sol).minus(b).norm()); System.out.println(""); System.out.println(""); System.out.print("Enter any letter to continue... "); pause = darkly.next(); System.out.println(""); break; case 4: System.out.println("Please enter an augmented matrix as a .dat file into the project root."); System.out.println("Enter the full name of the file, with the .dat extension."); augFile = new File(darkly.next()); A = augSplitA(augFile); b = augSplitb(augFile); System.out.println("Ax=b Calculation of a matrix with Givens is in progress."); sol = solve_qr_b.givensSolve(A, b); System.out.println("The original matrix, A, is: "); A.print(10, 5); System.out.print("The solved vector, x, is: "); sol.print(10, 10); System.out.print("The b vector is: "); b.print(10, 10); System.out.print("Error (Hx - b) = " + A.times(sol).minus(b).norm()); System.out.println(""); System.out.println(""); System.out.print("Enter any letter to continue... "); pause = darkly.next(); System.out.println(""); break; case 5: System.out.println("Please enter a matrix as a .dat file into the project root."); System.out.println("Enter the full name of the file, with the .dat extension."); A = DatParser.datToMatrix(new File(darkly.next())); System.out.println("LU Decomposition of a matrix is in progress."); LU lu = new LU(A); lu.lu_fact(); Matrix L = lu.getLower(); Matrix U = lu.getUpper(); System.out.println("The original matrix is: "); A.print(10, 5); System.out.print("The L matrix : "); L.print(10, 5); System.out.print("The U matrix is: "); U.print(10, 5); System.out.print("Error (LU - H) = " + lu.getError()); System.out.println(""); System.out.println(""); System.out.print("Enter any letter to continue... "); pause = darkly.next(); System.out.println(""); break; case 6: System.out.println("Please enter an augmented matrix as a .dat file into the project root."); System.out.println("Enter the full name of the file, with the .dat extension."); augFile = new File(darkly.next()); A = augSplitA(augFile); b = augSplitb(augFile); System.out.println("Solve LU b is in progress."); LU luSolve = new LU(A); luSolve.lu_fact(); sol = luSolve.solve(b); System.out.println("The original matrix, A, is: "); A.print(10, 5); System.out.print("The solved vector, x, is: "); sol.print(10, 10); System.out.print("The b vector is: "); b.print(10, 10); System.out.print("Error (Hx - b) = " + A.times(sol).minus(b).norm()); System.out.println(""); System.out.println(""); System.out.print("Enter any letter to continue... "); pause = darkly.next(); System.out.println(""); break; case 7: loop = false; break; } } catch (Exception e) { System.out.println("An error has occurred. Please check your .dat file."); loop = false; } } } public static Matrix augSplitA(File a) throws FileNotFoundException { Matrix Aug = DatParser.datToMatrix(a); Matrix b = new Matrix(Aug.getRowDimension(), 1); Matrix A = new Matrix(Aug.getRowDimension(), Aug.getColumnDimension() - 1); for(int row = 0; row < Aug.getRowDimension(); row++) { for(int col = 0; col < Aug.getColumnDimension(); col++) { if(col != Aug.getColumnDimension() - 1) { A.set(row, col, Aug.get(row, col)); } else { b.set(row, 0, Aug.get(row, col)); } } } return A; } public static Matrix augSplitb(File a) throws FileNotFoundException { Matrix Aug = DatParser.datToMatrix(a); Matrix b = new Matrix(Aug.getRowDimension(), 1); Matrix A = new Matrix(Aug.getRowDimension(), Aug.getColumnDimension() - 1); for(int row = 0; row < Aug.getRowDimension(); row++) { for(int col = 0; col < Aug.getColumnDimension(); col++) { if(col != Aug.getColumnDimension() - 1) { A.set(row, col, Aug.get(row, col)); } else { b.set(row, 0, Aug.get(row, col)); } } } return b; } public static Matrix createHilbert(int rows, int columns) { double[][] hilbert = new double[rows][columns]; for(int i = 0; i < rows; i++) { for (int j =0; j < columns; j++) { hilbert[i][j] = 1. / (i + j + 1.); } } return new Matrix(hilbert); } public static Matrix createB(int size) { double[][] b = new double[size][1]; for (int i = 0; i < size; i++) { b[i][0] = Math.pow(0.1, (double)size/3); } return new Matrix(b); } public static void qrVisualizer() { System.out.println("QR Factorization for Hilbert Matricies"); System.out.println(""); double[] x = new double[19]; double[] qrhError = new double[19]; double[] qrGError = new double[19]; double[] hxError = new double[19]; double[] gxError = new double[19]; int i = 0; for(int n = 2; n <= 20; n++) { Matrix hilbert = createHilbert(n, n); GivensQR qrA = new GivensQR(hilbert); Matrix b = createB(n); Matrix xSol = solve_qr_b.houseSolve(hilbert, b); System.out.println("For Hilbert of size " + n + " With HouseHolders:"); System.out.println("Xsol = "); xSol.print(10, 10); System.out.print("------"); double qrhErr = Householder.error(hilbert); System.out.println("||QR - H|| = " + qrhErr); //Solution Error with HouseHolders double hxErr = (hilbert.times(xSol).minus(b)).norm(); System.out.println("------ ||HXsol - b||" + hxErr); System.out.println(":)"); //GIVENS System.out.println("For Hilbert of size " + n + " With Givens:"); xSol = solve_qr_b.givensSolve(hilbert, b); System.out.println("Xsol = "); xSol.print(10, 10); System.out.print("------"); double qrGErr = qrA.getError(); System.out.println("||QR - H|| = " + qrGErr); //Solution Error with givens double gxErr = ((hilbert.times(xSol).minus(b)).norm()); System.out.println("------ ||HXsol - b||" + gxErr); //Graphin stuff double scale = 1000000.0; x[i] = n; qrGError[i] = qrGErr*scale; qrhError[i] = qrhErr*scale; hxError[i] = hxErr*scale; gxError[i] = gxErr*scale; i++; } Chart houseChart = QuickChart.getChart("QR Error of Hilbert Matrix with HouseHolders" , "Hilbert size", "Error (*scaled by 10^6)", "||QR - H||", x, qrhError); //houseChart.getStyleManager().setYAxisLogarithmic(true); new SwingWrapper(houseChart).displayChart(); Chart givensChart = QuickChart.getChart("QR Error of Hilbert Matrix with Givens" , "Hilbert size", "Error (*scaled by 10^6)", "||QR - H||", x, qrGError); new SwingWrapper(givensChart).displayChart(); Chart hSolChart = QuickChart.getChart("Solution Error of Hilbert Matrix with HouseHolders" , "Hilbert size", "Error (*scaled by 10^6)", "||HXsol - b||", x, hxError);; new SwingWrapper(hSolChart).displayChart(); Chart gSolChart = QuickChart.getChart("Solution Error of Hilbert Matrix with Givens" , "Hilbert size", "Error (*scaled by 10^6)", "||HXsol - b||", x, gxError); new SwingWrapper(gSolChart).displayChart(); } public static void luVisualizer() { System.out.println("LU Factorization for Hilbert Matricies"); System.out.println(""); double[] x = new double[19]; double[] luError = new double[19]; double[] luSolError = new double[19]; int k = 0; for (int n = 2; n <= 20; n++) { Matrix hilbert = createHilbert(n, n); Matrix b = createB(n); LU lu = new LU(hilbert); lu.lu_fact(); double luErr = lu.getError(); System.out.println("The error for a hilbert matrix of size " + n + " is " + luErr); Matrix c = lu.solve(b); System.out.println("The solution, x, for LU is "); for (int i = 0; i < c.getRowDimension(); i++) { System.out.println(c.get(i, 0)); } System.out.print("The error, Hx - b, for LU is "); Matrix e = (hilbert.times(c).minus(b)); double luSolErr = e.norm(); System.out.print(luSolErr); System.out.println(""); System.out.println("----------------------------------------"); System.out.println(""); double luErrscale = 10000000000.0; x[k] = n; luError[k] = luErr*luErrscale; luSolError[k] = luSolErr*luErrscale; k++; } Chart luChart = QuickChart.getChart("LU error of Hilbert FX" , "Hilbert size", "Error (*scaled by 10^6)", "||HXsol - b||", x, luError); new SwingWrapper(luChart).displayChart(); Chart luSolChart = QuickChart.getChart("Solution Error of Hilbert Matrix with LU" , "Hilbert size", "Error (*scaled by 10^6)", "||HXsol - b||", x, luSolError); new SwingWrapper(luSolChart).displayChart(); } }
UTF-8
Java
17,009
java
Driver.java
Java
[ { "context": "/**\n * Created by super_000 on 3/9/2015.\n */\n\nimport java.text.NumberFormat;\n", "end": 27, "score": 0.9994208216667175, "start": 18, "tag": "USERNAME", "value": "super_000" } ]
null
[]
/** * Created by super_000 on 3/9/2015. */ import java.text.NumberFormat; import java.util.Scanner; //import com.googlecode.charts4j.*; import java.io.*; import com.xeiam.xchart.Chart; import com.xeiam.xchart.QuickChart; import com.xeiam.xchart.SwingWrapper; public class Driver { private static Scanner darkly = new Scanner(System.in); public static void main(String[] args) throws FileNotFoundException { NumberFormat nf = NumberFormat.getInstance(); nf.setMaximumFractionDigits(5); boolean loop = true; while(loop) { System.out.println("HILBERT ERROR VISUALIZATION PROGRAM ULTIMATE ARCADE EDITION v0.0000001"); System.out.println("CHOOSE THY FATE"); System.out.println("1. Hilbert QR Visualization"); System.out.println("2. Hilbert LU Visualization"); System.out.println("3. Test Matrix Functions"); System.out.println("4. Exit"); int fate = darkly.nextInt(); switch (fate) { case 1: qrVisualizer(); break; case 2: luVisualizer(); break; case 3: matrixMenu(); break; case 4: System.out.println(""); System.out.println("JU"); loop = false; break; } } } public static void matrixMenu() throws FileNotFoundException{ boolean loop = true; //File augFile = new File(darkly.next()); while(loop) { //Matrix System.out.println("What would you liked to do?"); System.out.println("1. Find Q and R of a matrix with HouseHolders"); System.out.println("2. Find Q and R of matrix with Givens"); System.out.println("3. Ax = b with HouseHolders"); System.out.println("4. Ax = b with Givens"); System.out.println("5. LU Decomposition of a matrix"); System.out.println("6. Solve LU b"); System.out.println("7. Go back"); String pause; try { switch (darkly.nextInt()) { case 1: System.out.println("Please enter a matrix as a .dat file into the project root."); System.out.println("Enter the full name of the file, with the .dat extension."); Matrix A = DatParser.datToMatrix(new File(darkly.next())); System.out.println("QR Calculation of a matrix with HouseHolders is in progress."); Matrix Q = Householder.getQ(A); Matrix R = Householder.getR(A); System.out.println("The original matrix is: "); A.print(10, 5); System.out.print("The Q matrix : "); Q.print(10, 5); System.out.print("The R matrix is: "); R.print(10, 5); System.out.print("Error (QR - H) = " + Householder.error(A)); System.out.println(""); System.out.println(""); System.out.print("Enter any letter to continue... "); pause = darkly.next(); System.out.println(""); break; case 2: System.out.println("Please enter a matrix as a .dat file into the project root."); System.out.println("Enter the full name of the file, with the .dat extension."); A = DatParser.datToMatrix(new File(darkly.next())); System.out.println("QR Calculation of a matrix with Givens is in progress."); GivensQR qrA = new GivensQR(A); Q = qrA.Q; R = qrA.R; System.out.println("The original matrix is: "); A.print(10, 5); System.out.print("The Q matrix : "); Q.print(10, 5); System.out.print("The R matrix is: "); R.print(10, 5); System.out.print("Error (QR - H) = " + qrA.getError()); System.out.println(""); System.out.println(""); System.out.print("Enter any letter to continue... "); pause = darkly.next(); System.out.println(""); break; case 3: System.out.println("Please enter an augmented matrix as a .dat file into the project root."); System.out.println("Enter the full name of the file, with the .dat extension."); File augFile = new File(darkly.next()); A = augSplitA(augFile); System.out.println("Ax=b Calculation of a matrix with Householders is in progress."); Matrix b = augSplitb(augFile); Matrix sol = solve_qr_b.houseSolve(A, b); System.out.println("The original matrix, A, is: "); A.print(10, 5); System.out.print("The solved vector, x, is: "); sol.print(10, 10); System.out.print("The b vector is: "); b.print(10, 10); System.out.print("Error (Hx - b) = " + A.times(sol).minus(b).norm()); System.out.println(""); System.out.println(""); System.out.print("Enter any letter to continue... "); pause = darkly.next(); System.out.println(""); break; case 4: System.out.println("Please enter an augmented matrix as a .dat file into the project root."); System.out.println("Enter the full name of the file, with the .dat extension."); augFile = new File(darkly.next()); A = augSplitA(augFile); b = augSplitb(augFile); System.out.println("Ax=b Calculation of a matrix with Givens is in progress."); sol = solve_qr_b.givensSolve(A, b); System.out.println("The original matrix, A, is: "); A.print(10, 5); System.out.print("The solved vector, x, is: "); sol.print(10, 10); System.out.print("The b vector is: "); b.print(10, 10); System.out.print("Error (Hx - b) = " + A.times(sol).minus(b).norm()); System.out.println(""); System.out.println(""); System.out.print("Enter any letter to continue... "); pause = darkly.next(); System.out.println(""); break; case 5: System.out.println("Please enter a matrix as a .dat file into the project root."); System.out.println("Enter the full name of the file, with the .dat extension."); A = DatParser.datToMatrix(new File(darkly.next())); System.out.println("LU Decomposition of a matrix is in progress."); LU lu = new LU(A); lu.lu_fact(); Matrix L = lu.getLower(); Matrix U = lu.getUpper(); System.out.println("The original matrix is: "); A.print(10, 5); System.out.print("The L matrix : "); L.print(10, 5); System.out.print("The U matrix is: "); U.print(10, 5); System.out.print("Error (LU - H) = " + lu.getError()); System.out.println(""); System.out.println(""); System.out.print("Enter any letter to continue... "); pause = darkly.next(); System.out.println(""); break; case 6: System.out.println("Please enter an augmented matrix as a .dat file into the project root."); System.out.println("Enter the full name of the file, with the .dat extension."); augFile = new File(darkly.next()); A = augSplitA(augFile); b = augSplitb(augFile); System.out.println("Solve LU b is in progress."); LU luSolve = new LU(A); luSolve.lu_fact(); sol = luSolve.solve(b); System.out.println("The original matrix, A, is: "); A.print(10, 5); System.out.print("The solved vector, x, is: "); sol.print(10, 10); System.out.print("The b vector is: "); b.print(10, 10); System.out.print("Error (Hx - b) = " + A.times(sol).minus(b).norm()); System.out.println(""); System.out.println(""); System.out.print("Enter any letter to continue... "); pause = darkly.next(); System.out.println(""); break; case 7: loop = false; break; } } catch (Exception e) { System.out.println("An error has occurred. Please check your .dat file."); loop = false; } } } public static Matrix augSplitA(File a) throws FileNotFoundException { Matrix Aug = DatParser.datToMatrix(a); Matrix b = new Matrix(Aug.getRowDimension(), 1); Matrix A = new Matrix(Aug.getRowDimension(), Aug.getColumnDimension() - 1); for(int row = 0; row < Aug.getRowDimension(); row++) { for(int col = 0; col < Aug.getColumnDimension(); col++) { if(col != Aug.getColumnDimension() - 1) { A.set(row, col, Aug.get(row, col)); } else { b.set(row, 0, Aug.get(row, col)); } } } return A; } public static Matrix augSplitb(File a) throws FileNotFoundException { Matrix Aug = DatParser.datToMatrix(a); Matrix b = new Matrix(Aug.getRowDimension(), 1); Matrix A = new Matrix(Aug.getRowDimension(), Aug.getColumnDimension() - 1); for(int row = 0; row < Aug.getRowDimension(); row++) { for(int col = 0; col < Aug.getColumnDimension(); col++) { if(col != Aug.getColumnDimension() - 1) { A.set(row, col, Aug.get(row, col)); } else { b.set(row, 0, Aug.get(row, col)); } } } return b; } public static Matrix createHilbert(int rows, int columns) { double[][] hilbert = new double[rows][columns]; for(int i = 0; i < rows; i++) { for (int j =0; j < columns; j++) { hilbert[i][j] = 1. / (i + j + 1.); } } return new Matrix(hilbert); } public static Matrix createB(int size) { double[][] b = new double[size][1]; for (int i = 0; i < size; i++) { b[i][0] = Math.pow(0.1, (double)size/3); } return new Matrix(b); } public static void qrVisualizer() { System.out.println("QR Factorization for Hilbert Matricies"); System.out.println(""); double[] x = new double[19]; double[] qrhError = new double[19]; double[] qrGError = new double[19]; double[] hxError = new double[19]; double[] gxError = new double[19]; int i = 0; for(int n = 2; n <= 20; n++) { Matrix hilbert = createHilbert(n, n); GivensQR qrA = new GivensQR(hilbert); Matrix b = createB(n); Matrix xSol = solve_qr_b.houseSolve(hilbert, b); System.out.println("For Hilbert of size " + n + " With HouseHolders:"); System.out.println("Xsol = "); xSol.print(10, 10); System.out.print("------"); double qrhErr = Householder.error(hilbert); System.out.println("||QR - H|| = " + qrhErr); //Solution Error with HouseHolders double hxErr = (hilbert.times(xSol).minus(b)).norm(); System.out.println("------ ||HXsol - b||" + hxErr); System.out.println(":)"); //GIVENS System.out.println("For Hilbert of size " + n + " With Givens:"); xSol = solve_qr_b.givensSolve(hilbert, b); System.out.println("Xsol = "); xSol.print(10, 10); System.out.print("------"); double qrGErr = qrA.getError(); System.out.println("||QR - H|| = " + qrGErr); //Solution Error with givens double gxErr = ((hilbert.times(xSol).minus(b)).norm()); System.out.println("------ ||HXsol - b||" + gxErr); //Graphin stuff double scale = 1000000.0; x[i] = n; qrGError[i] = qrGErr*scale; qrhError[i] = qrhErr*scale; hxError[i] = hxErr*scale; gxError[i] = gxErr*scale; i++; } Chart houseChart = QuickChart.getChart("QR Error of Hilbert Matrix with HouseHolders" , "Hilbert size", "Error (*scaled by 10^6)", "||QR - H||", x, qrhError); //houseChart.getStyleManager().setYAxisLogarithmic(true); new SwingWrapper(houseChart).displayChart(); Chart givensChart = QuickChart.getChart("QR Error of Hilbert Matrix with Givens" , "Hilbert size", "Error (*scaled by 10^6)", "||QR - H||", x, qrGError); new SwingWrapper(givensChart).displayChart(); Chart hSolChart = QuickChart.getChart("Solution Error of Hilbert Matrix with HouseHolders" , "Hilbert size", "Error (*scaled by 10^6)", "||HXsol - b||", x, hxError);; new SwingWrapper(hSolChart).displayChart(); Chart gSolChart = QuickChart.getChart("Solution Error of Hilbert Matrix with Givens" , "Hilbert size", "Error (*scaled by 10^6)", "||HXsol - b||", x, gxError); new SwingWrapper(gSolChart).displayChart(); } public static void luVisualizer() { System.out.println("LU Factorization for Hilbert Matricies"); System.out.println(""); double[] x = new double[19]; double[] luError = new double[19]; double[] luSolError = new double[19]; int k = 0; for (int n = 2; n <= 20; n++) { Matrix hilbert = createHilbert(n, n); Matrix b = createB(n); LU lu = new LU(hilbert); lu.lu_fact(); double luErr = lu.getError(); System.out.println("The error for a hilbert matrix of size " + n + " is " + luErr); Matrix c = lu.solve(b); System.out.println("The solution, x, for LU is "); for (int i = 0; i < c.getRowDimension(); i++) { System.out.println(c.get(i, 0)); } System.out.print("The error, Hx - b, for LU is "); Matrix e = (hilbert.times(c).minus(b)); double luSolErr = e.norm(); System.out.print(luSolErr); System.out.println(""); System.out.println("----------------------------------------"); System.out.println(""); double luErrscale = 10000000000.0; x[k] = n; luError[k] = luErr*luErrscale; luSolError[k] = luSolErr*luErrscale; k++; } Chart luChart = QuickChart.getChart("LU error of Hilbert FX" , "Hilbert size", "Error (*scaled by 10^6)", "||HXsol - b||", x, luError); new SwingWrapper(luChart).displayChart(); Chart luSolChart = QuickChart.getChart("Solution Error of Hilbert Matrix with LU" , "Hilbert size", "Error (*scaled by 10^6)", "||HXsol - b||", x, luSolError); new SwingWrapper(luSolChart).displayChart(); } }
17,009
0.471045
0.45958
393
42.2799
28.402739
117
false
false
0
0
0
0
0
0
1.063613
false
false
6
5330c08899bb7a4353a39461d157f6a49a4e0467
34,454,227,679,881
9c4066cd153f8f7334ae47e9a442bfda4b68cf64
/app/src/main/java/com/frxs/dispatch/listener/ParentUIListener.java
d3561b99bb648039332e28aee43f09a952d1f405
[]
no_license
shenkeneng/DispatchApp
https://github.com/shenkeneng/DispatchApp
2f3efdc5d998f020f3712b53a50a394b8fc71827
d342e770176a72577940cc0fd22a24158f3a60cf
refs/heads/master
2020-06-16T23:06:12.098000
2019-07-08T03:13:23
2019-07-08T03:13:23
195,728,302
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.frxs.dispatch.listener; import android.content.Intent; /** * <pre> * author : ewu * e-mail : xxx@xx * time : 2017/06/09 * desc : xxxx描述 * version: 1.0 * </pre> */ public interface ParentUIListener { public abstract void onParentResult(Intent data); }
UTF-8
Java
305
java
ParentUIListener.java
Java
[ { "context": "roid.content.Intent;\n\n/**\n * <pre>\n * author : ewu\n * e-mail : xxx@xx\n * time : 2017/06/09", "end": 101, "score": 0.9820120334625244, "start": 98, "tag": "USERNAME", "value": "ewu" }, { "context": "\n\n/**\n * <pre>\n * author : ewu\n * e-mai...
null
[]
package com.frxs.dispatch.listener; import android.content.Intent; /** * <pre> * author : ewu * e-mail : <EMAIL> * time : 2017/06/09 * desc : xxxx描述 * version: 1.0 * </pre> */ public interface ParentUIListener { public abstract void onParentResult(Intent data); }
306
0.614618
0.581395
16
17.8125
15.025889
53
false
false
0
0
0
0
0
0
0.1875
false
false
6
c25a434d115c859349258bd089aaf3aebc115181
34,454,227,681,917
482d09844baf9eb4123949f479ec96b71577faa0
/SpringProject/Shoppingmall/src/main/java/com/company/shoppingmall/dto/requestDTO.java
fe6ffc2906cf3d475527fc70128cb636ad0573e7
[]
no_license
teidjx25/myPortfolio
https://github.com/teidjx25/myPortfolio
1070860d5d2e93e0e1b638af030c5e356fd40320
62342f3876943998f1b4d297ab0ae5f874f62e1a
refs/heads/main
2023-04-05T09:17:19.531000
2021-04-15T13:53:43
2021-04-15T13:53:43
358,267,172
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.company.shoppingmall.dto; import java.util.Date; import org.springframework.web.multipart.MultipartFile; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; public class requestDTO { private int qnum; private String title; private String name; private String password; private String category; private int reRef; private int reLev; private int reSeq; private int bnum; private int state; private String contents; private Date qRdate; private MultipartFile uploadFile; private String requestImg; public int getQnum() { return qnum; } public void setQnum(int qnum) { this.qnum = qnum; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public int getReRef() { return reRef; } public void setReRef(int reRef) { this.reRef = reRef; } public int getReLev() { return reLev; } public void setReLev(int reLev) { this.reLev = reLev; } public int getReSeq() { return reSeq; } public void setReSeq(int reSeq) { this.reSeq = reSeq; } public int getBnum() { return bnum; } public void setBnum(int bnum) { this.bnum = bnum; } public int getState() { return state; } public void setState(int state) { this.state = state; } public String getContents() { return contents; } public void setContents(String contents) { this.contents = contents; } public Date getqRdate() { return qRdate; } public void setqRdate(Date qRdate) { this.qRdate = qRdate; } public MultipartFile getUploadFile() { return uploadFile; } public void setUploadFile(MultipartFile uploadFile) { this.uploadFile = uploadFile; } public String getRequestImg() { return requestImg; } public void setRequestImg(String requestImg) { this.requestImg = requestImg; } @Override public String toString() { return "requestDTO [qnum=" + qnum + ", title=" + title + ", name=" + name + ", password=" + password + ", category=" + category + ", reRef=" + reRef + ", reLev=" + reLev + ", reSeq=" + reSeq + ", bnum=" + bnum + ", state=" + state + ", contents=" + contents + ", qRdate=" + qRdate + ", uploadFile=" + uploadFile + ", requestImg=" + requestImg + "]"; } }
UTF-8
Java
2,577
java
requestDTO.java
Java
[ { "context": "d setPassword(String password) {\n\t\tthis.password = password;\n\t}\n\tpublic String getCategory() {\n\t\treturn categ", "end": 986, "score": 0.6476767063140869, "start": 978, "tag": "PASSWORD", "value": "password" }, { "context": "tle=\" + title + \", name=\" + name +...
null
[]
package com.company.shoppingmall.dto; import java.util.Date; import org.springframework.web.multipart.MultipartFile; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; public class requestDTO { private int qnum; private String title; private String name; private String password; private String category; private int reRef; private int reLev; private int reSeq; private int bnum; private int state; private String contents; private Date qRdate; private MultipartFile uploadFile; private String requestImg; public int getQnum() { return qnum; } public void setQnum(int qnum) { this.qnum = qnum; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = <PASSWORD>; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public int getReRef() { return reRef; } public void setReRef(int reRef) { this.reRef = reRef; } public int getReLev() { return reLev; } public void setReLev(int reLev) { this.reLev = reLev; } public int getReSeq() { return reSeq; } public void setReSeq(int reSeq) { this.reSeq = reSeq; } public int getBnum() { return bnum; } public void setBnum(int bnum) { this.bnum = bnum; } public int getState() { return state; } public void setState(int state) { this.state = state; } public String getContents() { return contents; } public void setContents(String contents) { this.contents = contents; } public Date getqRdate() { return qRdate; } public void setqRdate(Date qRdate) { this.qRdate = qRdate; } public MultipartFile getUploadFile() { return uploadFile; } public void setUploadFile(MultipartFile uploadFile) { this.uploadFile = uploadFile; } public String getRequestImg() { return requestImg; } public void setRequestImg(String requestImg) { this.requestImg = requestImg; } @Override public String toString() { return "requestDTO [qnum=" + qnum + ", title=" + title + ", name=" + name + ", password=" + <PASSWORD> + ", category=" + category + ", reRef=" + reRef + ", reLev=" + reLev + ", reSeq=" + reSeq + ", bnum=" + bnum + ", state=" + state + ", contents=" + contents + ", qRdate=" + qRdate + ", uploadFile=" + uploadFile + ", requestImg=" + requestImg + "]"; } }
2,581
0.685681
0.685681
121
20.297522
19.196524
105
false
false
0
0
0
0
0
0
1.710744
false
false
6
2719bed3c707ac8fb1b6820149d12c6fa4cfb12d
38,568,806,325,821
0e9cfb5ca6299c923153b5d5c67df55f7347bdce
/HomeWork3_NguyenThiYenKhoa_B1709343/app/src/main/java/com/example/homework3_nguyenthiyenkhoa_b1709343/MainActivity.java
52bab22272c56b2a0a7d6262d45fd1248a38ea77
[]
no_license
nguyenyenkhoa/learn-android
https://github.com/nguyenyenkhoa/learn-android
429d627996aae5395bf9cba67e024eb5b7179fe5
5cdcc7c5ff4771c0eac29b5f4bf588cb0076c6e8
refs/heads/master
2023-02-09T02:47:59.683000
2021-01-05T15:29:32
2021-01-05T15:29:32
326,946,414
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.homework3_nguyenthiyenkhoa_b1709343; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AnalogClock; import android.widget.Button; import android.widget.CheckBox; public class MainActivity extends AppCompatActivity { Button btnexit ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btnmenu=(Button)findViewById(R.id.btntmenu); btnmenu.setOnCreateContextMenuListener(this); //---CheckBox--- CheckBox checkBox = (CheckBox) findViewById(R.id.chkAutosave); final AnalogClock an = (AnalogClock) findViewById(R.id.dongho); checkBox.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (((CheckBox)v).isChecked()) an.setVisibility(AnalogClock.INVISIBLE); else an.setVisibility(AnalogClock.VISIBLE); } }); btnexit = findViewById(R.id.btnthoat); btnexit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { System.exit(0); } }); } @Override public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo){ super.onCreateContextMenu(menu, view, menuInfo); CreateContextMenu(menu); }; @Override public boolean onContextItemSelected(MenuItem item) { return contextmenuChoice(item); }; public void CreateContextMenu(Menu menu) { MenuItem m1=menu.add(0, 0, 0, "KIỂM TRA CHẲN LẼ"); { m1.setAlphabeticShortcut('e'); } MenuItem m2=menu.add(0, 1, 1, "ĐỔI THẬP PHÂN-NHỊ PHÂN"); { m2.setAlphabeticShortcut('f'); } MenuItem m3=menu.add(0, 2, 2, "TÍNH TIỀN BÁN HÀNG"); { m3.setAlphabeticShortcut('g'); } }; public boolean contextmenuChoice(MenuItem item){ switch(item.getItemId()){ case 0: Intent i0 = new Intent(MainActivity.this, KiemTraChanLe.class); startActivity(i0); return true; case 1: Intent i1 = new Intent(MainActivity.this, DoiThapPhan_NhiPhan.class); startActivity(i1); return true; case 2: Intent i2 = new Intent(MainActivity.this, TinhTienBanHang.class); startActivity(i2); return true; } return false; }; }
UTF-8
Java
2,880
java
MainActivity.java
Java
[]
null
[]
package com.example.homework3_nguyenthiyenkhoa_b1709343; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AnalogClock; import android.widget.Button; import android.widget.CheckBox; public class MainActivity extends AppCompatActivity { Button btnexit ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btnmenu=(Button)findViewById(R.id.btntmenu); btnmenu.setOnCreateContextMenuListener(this); //---CheckBox--- CheckBox checkBox = (CheckBox) findViewById(R.id.chkAutosave); final AnalogClock an = (AnalogClock) findViewById(R.id.dongho); checkBox.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (((CheckBox)v).isChecked()) an.setVisibility(AnalogClock.INVISIBLE); else an.setVisibility(AnalogClock.VISIBLE); } }); btnexit = findViewById(R.id.btnthoat); btnexit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { System.exit(0); } }); } @Override public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo){ super.onCreateContextMenu(menu, view, menuInfo); CreateContextMenu(menu); }; @Override public boolean onContextItemSelected(MenuItem item) { return contextmenuChoice(item); }; public void CreateContextMenu(Menu menu) { MenuItem m1=menu.add(0, 0, 0, "KIỂM TRA CHẲN LẼ"); { m1.setAlphabeticShortcut('e'); } MenuItem m2=menu.add(0, 1, 1, "ĐỔI THẬP PHÂN-NHỊ PHÂN"); { m2.setAlphabeticShortcut('f'); } MenuItem m3=menu.add(0, 2, 2, "TÍNH TIỀN BÁN HÀNG"); { m3.setAlphabeticShortcut('g'); } }; public boolean contextmenuChoice(MenuItem item){ switch(item.getItemId()){ case 0: Intent i0 = new Intent(MainActivity.this, KiemTraChanLe.class); startActivity(i0); return true; case 1: Intent i1 = new Intent(MainActivity.this, DoiThapPhan_NhiPhan.class); startActivity(i1); return true; case 2: Intent i2 = new Intent(MainActivity.this, TinhTienBanHang.class); startActivity(i2); return true; } return false; }; }
2,880
0.606993
0.595455
87
31.873564
23.270426
103
false
false
0
0
0
0
0
0
0.724138
false
false
6
051551452ddc0bb800dff150f594acd519156af2
29,626,684,464,368
5ce569bd9451e0b296d2af69f8800076895bdbbf
/copycat-core/src/main/java/net/kuujo/copycat/serializer/SerializerFactory.java
2e42d796405697954dfb920678656cc5617921bd
[ "Apache-2.0" ]
permissive
porcelli/copycat
https://github.com/porcelli/copycat
5623bda2a947e80e7104e46208b3ea3107c787b4
6fe753471e8cdabe178f72cbe24e8b077e7b3a1c
refs/heads/master
2020-03-04T03:59:04.878000
2014-09-02T04:10:44
2014-09-02T04:10:44
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright 2014 the original author or authors. * * 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 net.kuujo.copycat.serializer; import net.kuujo.copycat.util.ServiceInfo; import net.kuujo.copycat.util.ServiceLoader; /** * Serializer factory. * * @author <a href="http://github.com/kuujo">Jordan Halterman</a> */ public abstract class SerializerFactory { private static Serializer serializer; /** * Returns the current serializer instance. * * @return A singleton serializer instance. */ @SuppressWarnings("unchecked") public static Serializer getSerializer() { if (serializer == null) { ServiceInfo info = ServiceLoader.load("net.kuujo.copycat.Serializer"); Class<? extends SerializerFactory> factoryClass = info.getProperty("class", Class.class); try { SerializerFactory factory = factoryClass.newInstance(); serializer = factory.createSerializer(); } catch (InstantiationException | IllegalAccessException e) { throw new SerializationException(e.getMessage()); } } return serializer; } /** * Creates a new serializer instance. * * @return A new serializer instance. */ public abstract Serializer createSerializer(); }
UTF-8
Java
1,760
java
SerializerFactory.java
Java
[ { "context": "factory.\n *\n * @author <a href=\"http://github.com/kuujo\">Jordan Halterman</a>\n */\npublic abstract class S", "end": 812, "score": 0.9953276515007019, "start": 807, "tag": "USERNAME", "value": "kuujo" }, { "context": ".\n *\n * @author <a href=\"http://github.com/ku...
null
[]
/* * Copyright 2014 the original author or authors. * * 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 net.kuujo.copycat.serializer; import net.kuujo.copycat.util.ServiceInfo; import net.kuujo.copycat.util.ServiceLoader; /** * Serializer factory. * * @author <a href="http://github.com/kuujo"><NAME></a> */ public abstract class SerializerFactory { private static Serializer serializer; /** * Returns the current serializer instance. * * @return A singleton serializer instance. */ @SuppressWarnings("unchecked") public static Serializer getSerializer() { if (serializer == null) { ServiceInfo info = ServiceLoader.load("net.kuujo.copycat.Serializer"); Class<? extends SerializerFactory> factoryClass = info.getProperty("class", Class.class); try { SerializerFactory factory = factoryClass.newInstance(); serializer = factory.createSerializer(); } catch (InstantiationException | IllegalAccessException e) { throw new SerializationException(e.getMessage()); } } return serializer; } /** * Creates a new serializer instance. * * @return A new serializer instance. */ public abstract Serializer createSerializer(); }
1,750
0.711364
0.706818
57
29.877193
26.798187
95
false
false
0
0
0
0
0
0
0.315789
false
false
6
5e4f7a881dd1ef00332c0ddb8acd064eb1c4e81b
35,837,207,146,377
bf1f88becdc9c6ce1816de21ea6beff29091528f
/hk2-dw/src/main/java/org/serge/ws/rs/hk2/guice/GuiceModule.java
1272c494bfc5ccd7b4fabee4bbbdfb0eeb669986
[]
no_license
serhiypal/hk2
https://github.com/serhiypal/hk2
53e6e7b4bc4d358830ff7346dd1b6c22ae8de3ab
0a6c5f8fe90e4cffc3e72cbb78d9ef6c72289b9b
refs/heads/master
2021-01-11T10:06:29.147000
2017-06-29T07:35:28
2017-06-29T07:35:28
81,181,080
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.serge.ws.rs.hk2.guice; import com.google.inject.Binder; import com.google.inject.Module; import com.google.inject.Singleton; public class GuiceModule implements Module { @Override public void configure(Binder binder) { binder.bind(Status.class).to(GuiceStatus.class).in(Singleton.class); } }
UTF-8
Java
328
java
GuiceModule.java
Java
[]
null
[]
package org.serge.ws.rs.hk2.guice; import com.google.inject.Binder; import com.google.inject.Module; import com.google.inject.Singleton; public class GuiceModule implements Module { @Override public void configure(Binder binder) { binder.bind(Status.class).to(GuiceStatus.class).in(Singleton.class); } }
328
0.740854
0.737805
14
22.428572
22.452217
76
false
false
0
0
0
0
0
0
0.357143
false
false
6
c36cd3e7c931820a7e568f3d16365fce39b29826
25,795,573,644,679
e37294be1b45e867ee44a8fd42c1c04034f494bb
/Android/04-Ortho Triangle/GLESView.java
112f3dadc558c4488969a141486fee5bf574f02d
[]
no_license
NeerajChandel/Real-Time-Rendering-with-OpenGL
https://github.com/NeerajChandel/Real-Time-Rendering-with-OpenGL
94cc03e470b9351af800e7d562c37fc4202e0678
f08483b6dbf5ac4b62a12e99838a50222ba59e21
refs/heads/master
2020-03-30T17:44:45.279000
2018-10-16T12:02:43
2018-10-16T12:02:43
151,468,152
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.neeraj5.window; import android.content.Context; import android.opengl.GLSurfaceView; import android.opengl.GLES31; //GLES 3.1 * 100 = GLES31 import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.egl.EGLConfig; import android.view.MotionEvent; import android.view.GestureDetector; import android.view.GestureDetector.OnGestureListener; import android.view.GestureDetector.OnDoubleTapListener; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import android.opengl.Matrix; public class GLESView extends GLSurfaceView implements GLSurfaceView.Renderer, OnGestureListener, OnDoubleTapListener { private final Context context; private GestureDetector gestureDetector; private int vertexShaderObject; private int fragmentShaderObject; private int shaderProgramObject; private int[] vao = new int[1]; private int[] vbo = new int[1]; private int mvpUniform; private float orthographicProjectionMatrix[] = new float[16]; public GLESView(Context drawingContext) { super(drawingContext); context = drawingContext; setEGLContextClientVersion(3); setRenderer(this); setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY); gestureDetector = new GestureDetector(context, this, null, false); gestureDetector.setOnDoubleTapListener(this); } @Override public void onSurfaceCreated(GL10 gl, EGLConfig config) { String glesVersion = gl.glGetString(GL10.GL_VERSION); System.out.println("NRC: OpenGL-ES Version: " + glesVersion); String glslVersion = gl.glGetString(GLES31.GL_SHADING_LANGUAGE_VERSION); System.out.println("NRC: GLSL Version: " + glslVersion); initialize(gl); } @Override public void onSurfaceChanged(GL10 unused, int width, int height) { resize(width, height); } @Override public void onDrawFrame(GL10 unused) { display(); } @Override public boolean onTouchEvent(MotionEvent e) { int eventaction = e.getAction(); if(!gestureDetector.onTouchEvent(e)) super.onTouchEvent(e); return(true); } @Override public boolean onDoubleTap(MotionEvent e) { return(true); } @Override public boolean onDoubleTapEvent(MotionEvent e) { return(true); } @Override public boolean onSingleTapConfirmed(MotionEvent e) { return(true); } @Override public boolean onDown(MotionEvent e) { return(true); } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { return(true); } @Override public void onLongPress(MotionEvent e) { } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { uninitialize(); System.exit(0); return(true); } @Override public void onShowPress(MotionEvent e) { } @Override public boolean onSingleTapUp(MotionEvent e) { return(true); } private void initialize(GL10 gl) { // ************** VERTEX SHADER ********************************* vertexShaderObject = GLES31.glCreateShader(GLES31.GL_VERTEX_SHADER); final String vertexShaderSourceCode = String.format ( "#version 310 es" + "\n" + "in vec4 vPosition;" + "uniform mat4 u_mvp_matrix;" + "void main(void)" + "{" + "gl_Position = u_mvp_matrix * vPosition;" + "}" ); GLES31.glShaderSource(vertexShaderObject, vertexShaderSourceCode); GLES31.glCompileShader(vertexShaderObject); // error checking int[] iShaderCompiledStatus = new int[1]; int[] iInfoLogLength = new int[1]; String szInfoLog = null; GLES31.glGetShaderiv(vertexShaderObject, GLES31.GL_COMPILE_STATUS, iShaderCompiledStatus, 0); if(iShaderCompiledStatus[0] == GLES31.GL_FALSE) { GLES31.glGetShaderiv(vertexShaderObject, GLES31.GL_INFO_LOG_LENGTH, iInfoLogLength, 0); if(iInfoLogLength[0] > 0) { szInfoLog = GLES31.glGetShaderInfoLog(vertexShaderObject); System.out.println("NRC: Vertex Shader Compilation Log: " + szInfoLog); uninitialize(); System.exit(0); } } // ************** FRAGMENT SHADER ********************************* fragmentShaderObject = GLES31.glCreateShader(GLES31.GL_FRAGMENT_SHADER); final String fragmentShaderSourceCode = String.format ( "version 310 es" + "\n" + "precision highp float;" + "out vec4 FragColor;" + "void main(void)" + "{" + "FragColor = vec4(1.0, 1.0, 1.0, 1.0);" + "}" ); GLES31.glShaderSource(fragmentShaderObject, fragmentShaderSourceCode); GLES31.glCompileShader(fragmentShaderObject); // error checking iShaderCompiledStatus[0] = 0; iInfoLogLength[0] = 0; szInfoLog = null; GLES31.glGetShaderiv(fragmentShaderObject, GLES31.GL_COMPILE_STATUS, iShaderCompiledStatus, 0); if(iShaderCompiledStatus[0] == GLES31.GL_FALSE) { GLES31.glGetShaderiv(fragmentShaderObject, GLES31.GL_INFO_LOG_LENGTH, iInfoLogLength, 0); if(iInfoLogLength[0] > 0) { szInfoLog = GLES31.glGetShaderInfoLog(fragmentShaderObject); System.out.println("NRC: Fragment Shader Compilation Log = " + szInfoLog); uninitialize(); System.exit(0); } } // ***************** SHADER PROGRAM ******************** shaderProgramObject = GLES31.glCreateProgram(); GLES31.glAttachShader(shaderProgramObject, vertexShaderObject); GLES31.glAttachShader(shaderProgramObject, fragmentShaderObject); GLES31.glBindAttribLocation(shaderProgramObject, GLESMacros.NRC_ATTRIBUTE_VERTEX, "vPosition"); GLES31.glLinkProgram(shaderProgramObject); int[] iShaderProgramLinkStatus = new int[1]; iInfoLogLength[0] = 0; szInfoLog = null; GLES31.glGetProgramiv(shaderProgramObject, GLES31.GL_LINK_STATUS, iShaderProgramLinkStatus, 0); if(iShaderProgramLinkStatus[0] == GLES31.GL_FALSE) { GLES31.glGetProgramiv(shaderProgramObject, GLES31.GL_INFO_LOG_LENGTH, iInfoLogLength, 0); if(iInfoLogLength[0] > 0) { szInfoLog = GLES31.glGetProgramInfoLog(shaderProgramObject); System.out.println("NRC: Shader Program Link Log: " + szInfoLog); uninitialize(); System.exit(0); } } mvpUniform = GLES31.glGetUniformLocation(shaderProgramObject, "u_mvp_matrix"); final float triangleVertices[] = new float[] { 0.0f, 50.0f, 0.0f, -50.0f, -50.0f, 0.0f, 50.0f, -50.0f, 0.0f }; // binding with VAO GLES31.glGenVertexArrays(1, vao, 0); GLES31.glBindVertexArray(vao[0]); // binding with VBO GLES31.glGenBuffers(1, vbo, 0); GLES31.glBindBuffer(GLES31.GL_ARRAY_BUFFER, vbo[0]); ByteBuffer byteBuffer = ByteBuffer.allocateDirect(triangleVertices.length * 4); byteBuffer.order(ByteOrder.nativeOrder()); FloatBuffer verticesBuffer = byteBuffer.asFloatBuffer(); verticesBuffer.put(triangleVertices); verticesBuffer.position(0); GLES31.glBufferData(GLES31.GL_ARRAY_BUFFER, triangleVertices.length * 4, verticesBuffer, GLES31.GL_STATIC_DRAW); GLES31.glVertexAttribPointer(GLESMacros.NRC_ATTRIBUTE_VERTEX, 3, GLES31.GL_FLOAT, false, 0, 0); GLES31.glEnableVertexAttribArray(GLESMacros.NRC_ATTRIBUTE_VERTEX); // unbinding VBO and then VAO GLES31.glBindBuffer(GLES31.GL_ARRAY_BUFFER, 0); GLES31.glBindVertexArray(0); GLES31.glEnable(GLES31.GL_DEPTH_TEST); GLES31.glDepthFunc(GLES31.GL_LEQUAL); GLES31.glEnable(GLES31.GL_CULL_FACE); GLES31.glClearColor(0.0f, 0.0f, 1.0f, 1.0f); Matrix.setIdentityM(orthographicProjectionMatrix,0); } private void resize(int width, int height) { GLES31.glViewport(0, 0, width, height); if (width <= height) Matrix.orthoM(orthographicProjectionMatrix, 0, -100.0f, 100.0f, (-100.0f * (height / width)), (100.0f * (height / width)), -100.0f, 100.0f); else Matrix.orthoM(orthographicProjectionMatrix, 0, (-100.0f * (width / height)), (100.0f * (width / height)), -100.0f, 100.0f, -100.0f, 100.0f); } public void display() { GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT | GLES31.GL_DEPTH_BUFFER_BIT); GLES31.glUseProgram(shaderProgramObject); float modelViewMatrix[] = new float[16]; float modelViewProjectionMatrix[] = new float[16]; Matrix.setIdentityM(modelViewMatrix, 0); Matrix.setIdentityM(modelViewProjectionMatrix, 0); Matrix.multiplyMM(modelViewProjectionMatrix, 0, orthographicProjectionMatrix, 0, modelViewMatrix, 0); GLES31.glUniformMatrix4fv(mvpUniform, 1, false, modelViewProjectionMatrix, 0); GLES31.glBindVertexArray(vao[0]); GLES31.glDrawArrays(GLES31.GL_TRIANGLES, 0, 3); GLES31.glBindVertexArray(0); GLES31.glUseProgram(0); requestRender(); } void uninitialize() { if(vao[0] != 0) { GLES31.glDeleteVertexArrays(1, vao, 0); vao[0] = 0; } if(vbo[0] != 0) { GLES31.glDeleteBuffers(1, vbo, 0); vbo[0] = 0; } if(shaderProgramObject != 0) { if(vertexShaderObject != 0) { GLES31.glDetachShader(shaderProgramObject, vertexShaderObject); GLES31.glDeleteShader(vertexShaderObject); vertexShaderObject = 0; } if(fragmentShaderObject != 0) { GLES31.glDetachShader(shaderProgramObject, fragmentShaderObject); GLES31.glDeleteShader(fragmentShaderObject); fragmentShaderObject = 0; } } if(shaderProgramObject != 0) { GLES31.glDeleteProgram(shaderProgramObject); shaderProgramObject = 0; } } }
UTF-8
Java
10,276
java
GLESView.java
Java
[]
null
[]
package com.example.neeraj5.window; import android.content.Context; import android.opengl.GLSurfaceView; import android.opengl.GLES31; //GLES 3.1 * 100 = GLES31 import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.egl.EGLConfig; import android.view.MotionEvent; import android.view.GestureDetector; import android.view.GestureDetector.OnGestureListener; import android.view.GestureDetector.OnDoubleTapListener; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import android.opengl.Matrix; public class GLESView extends GLSurfaceView implements GLSurfaceView.Renderer, OnGestureListener, OnDoubleTapListener { private final Context context; private GestureDetector gestureDetector; private int vertexShaderObject; private int fragmentShaderObject; private int shaderProgramObject; private int[] vao = new int[1]; private int[] vbo = new int[1]; private int mvpUniform; private float orthographicProjectionMatrix[] = new float[16]; public GLESView(Context drawingContext) { super(drawingContext); context = drawingContext; setEGLContextClientVersion(3); setRenderer(this); setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY); gestureDetector = new GestureDetector(context, this, null, false); gestureDetector.setOnDoubleTapListener(this); } @Override public void onSurfaceCreated(GL10 gl, EGLConfig config) { String glesVersion = gl.glGetString(GL10.GL_VERSION); System.out.println("NRC: OpenGL-ES Version: " + glesVersion); String glslVersion = gl.glGetString(GLES31.GL_SHADING_LANGUAGE_VERSION); System.out.println("NRC: GLSL Version: " + glslVersion); initialize(gl); } @Override public void onSurfaceChanged(GL10 unused, int width, int height) { resize(width, height); } @Override public void onDrawFrame(GL10 unused) { display(); } @Override public boolean onTouchEvent(MotionEvent e) { int eventaction = e.getAction(); if(!gestureDetector.onTouchEvent(e)) super.onTouchEvent(e); return(true); } @Override public boolean onDoubleTap(MotionEvent e) { return(true); } @Override public boolean onDoubleTapEvent(MotionEvent e) { return(true); } @Override public boolean onSingleTapConfirmed(MotionEvent e) { return(true); } @Override public boolean onDown(MotionEvent e) { return(true); } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { return(true); } @Override public void onLongPress(MotionEvent e) { } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { uninitialize(); System.exit(0); return(true); } @Override public void onShowPress(MotionEvent e) { } @Override public boolean onSingleTapUp(MotionEvent e) { return(true); } private void initialize(GL10 gl) { // ************** VERTEX SHADER ********************************* vertexShaderObject = GLES31.glCreateShader(GLES31.GL_VERTEX_SHADER); final String vertexShaderSourceCode = String.format ( "#version 310 es" + "\n" + "in vec4 vPosition;" + "uniform mat4 u_mvp_matrix;" + "void main(void)" + "{" + "gl_Position = u_mvp_matrix * vPosition;" + "}" ); GLES31.glShaderSource(vertexShaderObject, vertexShaderSourceCode); GLES31.glCompileShader(vertexShaderObject); // error checking int[] iShaderCompiledStatus = new int[1]; int[] iInfoLogLength = new int[1]; String szInfoLog = null; GLES31.glGetShaderiv(vertexShaderObject, GLES31.GL_COMPILE_STATUS, iShaderCompiledStatus, 0); if(iShaderCompiledStatus[0] == GLES31.GL_FALSE) { GLES31.glGetShaderiv(vertexShaderObject, GLES31.GL_INFO_LOG_LENGTH, iInfoLogLength, 0); if(iInfoLogLength[0] > 0) { szInfoLog = GLES31.glGetShaderInfoLog(vertexShaderObject); System.out.println("NRC: Vertex Shader Compilation Log: " + szInfoLog); uninitialize(); System.exit(0); } } // ************** FRAGMENT SHADER ********************************* fragmentShaderObject = GLES31.glCreateShader(GLES31.GL_FRAGMENT_SHADER); final String fragmentShaderSourceCode = String.format ( "version 310 es" + "\n" + "precision highp float;" + "out vec4 FragColor;" + "void main(void)" + "{" + "FragColor = vec4(1.0, 1.0, 1.0, 1.0);" + "}" ); GLES31.glShaderSource(fragmentShaderObject, fragmentShaderSourceCode); GLES31.glCompileShader(fragmentShaderObject); // error checking iShaderCompiledStatus[0] = 0; iInfoLogLength[0] = 0; szInfoLog = null; GLES31.glGetShaderiv(fragmentShaderObject, GLES31.GL_COMPILE_STATUS, iShaderCompiledStatus, 0); if(iShaderCompiledStatus[0] == GLES31.GL_FALSE) { GLES31.glGetShaderiv(fragmentShaderObject, GLES31.GL_INFO_LOG_LENGTH, iInfoLogLength, 0); if(iInfoLogLength[0] > 0) { szInfoLog = GLES31.glGetShaderInfoLog(fragmentShaderObject); System.out.println("NRC: Fragment Shader Compilation Log = " + szInfoLog); uninitialize(); System.exit(0); } } // ***************** SHADER PROGRAM ******************** shaderProgramObject = GLES31.glCreateProgram(); GLES31.glAttachShader(shaderProgramObject, vertexShaderObject); GLES31.glAttachShader(shaderProgramObject, fragmentShaderObject); GLES31.glBindAttribLocation(shaderProgramObject, GLESMacros.NRC_ATTRIBUTE_VERTEX, "vPosition"); GLES31.glLinkProgram(shaderProgramObject); int[] iShaderProgramLinkStatus = new int[1]; iInfoLogLength[0] = 0; szInfoLog = null; GLES31.glGetProgramiv(shaderProgramObject, GLES31.GL_LINK_STATUS, iShaderProgramLinkStatus, 0); if(iShaderProgramLinkStatus[0] == GLES31.GL_FALSE) { GLES31.glGetProgramiv(shaderProgramObject, GLES31.GL_INFO_LOG_LENGTH, iInfoLogLength, 0); if(iInfoLogLength[0] > 0) { szInfoLog = GLES31.glGetProgramInfoLog(shaderProgramObject); System.out.println("NRC: Shader Program Link Log: " + szInfoLog); uninitialize(); System.exit(0); } } mvpUniform = GLES31.glGetUniformLocation(shaderProgramObject, "u_mvp_matrix"); final float triangleVertices[] = new float[] { 0.0f, 50.0f, 0.0f, -50.0f, -50.0f, 0.0f, 50.0f, -50.0f, 0.0f }; // binding with VAO GLES31.glGenVertexArrays(1, vao, 0); GLES31.glBindVertexArray(vao[0]); // binding with VBO GLES31.glGenBuffers(1, vbo, 0); GLES31.glBindBuffer(GLES31.GL_ARRAY_BUFFER, vbo[0]); ByteBuffer byteBuffer = ByteBuffer.allocateDirect(triangleVertices.length * 4); byteBuffer.order(ByteOrder.nativeOrder()); FloatBuffer verticesBuffer = byteBuffer.asFloatBuffer(); verticesBuffer.put(triangleVertices); verticesBuffer.position(0); GLES31.glBufferData(GLES31.GL_ARRAY_BUFFER, triangleVertices.length * 4, verticesBuffer, GLES31.GL_STATIC_DRAW); GLES31.glVertexAttribPointer(GLESMacros.NRC_ATTRIBUTE_VERTEX, 3, GLES31.GL_FLOAT, false, 0, 0); GLES31.glEnableVertexAttribArray(GLESMacros.NRC_ATTRIBUTE_VERTEX); // unbinding VBO and then VAO GLES31.glBindBuffer(GLES31.GL_ARRAY_BUFFER, 0); GLES31.glBindVertexArray(0); GLES31.glEnable(GLES31.GL_DEPTH_TEST); GLES31.glDepthFunc(GLES31.GL_LEQUAL); GLES31.glEnable(GLES31.GL_CULL_FACE); GLES31.glClearColor(0.0f, 0.0f, 1.0f, 1.0f); Matrix.setIdentityM(orthographicProjectionMatrix,0); } private void resize(int width, int height) { GLES31.glViewport(0, 0, width, height); if (width <= height) Matrix.orthoM(orthographicProjectionMatrix, 0, -100.0f, 100.0f, (-100.0f * (height / width)), (100.0f * (height / width)), -100.0f, 100.0f); else Matrix.orthoM(orthographicProjectionMatrix, 0, (-100.0f * (width / height)), (100.0f * (width / height)), -100.0f, 100.0f, -100.0f, 100.0f); } public void display() { GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT | GLES31.GL_DEPTH_BUFFER_BIT); GLES31.glUseProgram(shaderProgramObject); float modelViewMatrix[] = new float[16]; float modelViewProjectionMatrix[] = new float[16]; Matrix.setIdentityM(modelViewMatrix, 0); Matrix.setIdentityM(modelViewProjectionMatrix, 0); Matrix.multiplyMM(modelViewProjectionMatrix, 0, orthographicProjectionMatrix, 0, modelViewMatrix, 0); GLES31.glUniformMatrix4fv(mvpUniform, 1, false, modelViewProjectionMatrix, 0); GLES31.glBindVertexArray(vao[0]); GLES31.glDrawArrays(GLES31.GL_TRIANGLES, 0, 3); GLES31.glBindVertexArray(0); GLES31.glUseProgram(0); requestRender(); } void uninitialize() { if(vao[0] != 0) { GLES31.glDeleteVertexArrays(1, vao, 0); vao[0] = 0; } if(vbo[0] != 0) { GLES31.glDeleteBuffers(1, vbo, 0); vbo[0] = 0; } if(shaderProgramObject != 0) { if(vertexShaderObject != 0) { GLES31.glDetachShader(shaderProgramObject, vertexShaderObject); GLES31.glDeleteShader(vertexShaderObject); vertexShaderObject = 0; } if(fragmentShaderObject != 0) { GLES31.glDetachShader(shaderProgramObject, fragmentShaderObject); GLES31.glDeleteShader(fragmentShaderObject); fragmentShaderObject = 0; } } if(shaderProgramObject != 0) { GLES31.glDeleteProgram(shaderProgramObject); shaderProgramObject = 0; } } }
10,276
0.639451
0.604905
379
26.110819
28.102119
152
false
false
0
0
0
0
0
0
1.229551
false
false
6
9a46c0939129f47a131a5513937355ec9c2cd6ff
36,103,495,112,129
6ca8f59cca39fa15d12d74fec43e1b62f843657f
/src/main/java/com/jeeplus/modules/gatepass/GatePassController.java
693be01667fa5038056a82d2311e1796ee7bfa04
[]
no_license
TomYu1991/Source
https://github.com/TomYu1991/Source
05508d9e8774c4aa5d06627814a0c04c003aa50b
39ec0d501773cabdd0c1ff8710f9db16307fa53b
refs/heads/master
2022-12-22T19:58:40.548000
2019-11-25T07:24:25
2019-11-25T07:24:25
223,887,871
0
0
null
false
2022-12-16T10:52:24
2019-11-25T07:32:24
2019-11-25T07:33:30
2022-12-16T10:52:24
14,729
0
0
30
JavaScript
false
false
/** * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.gatepass; import com.google.common.collect.Lists; import com.jeeplus.common.json.AjaxJson; import com.jeeplus.common.utils.*; import com.jeeplus.common.utils.excel.ExportExcel; import com.jeeplus.common.utils.excel.ImportExcel; import com.jeeplus.core.persistence.Page; import com.jeeplus.core.web.BaseController; import com.jeeplus.modules.consign.entity.Consign; import com.jeeplus.modules.consign.service.ConsignService; import com.jeeplus.modules.interfaceTest.Controller.InterfaceTest; import com.jeeplus.modules.interfaceTest.entry.JsonType; import com.jeeplus.modules.interfaceTest.entry.PassFeedBack; import com.jeeplus.modules.passcheck.entity.PassCheck; import com.jeeplus.modules.passcheck.service.PassCheckService; import com.jeeplus.modules.passchecksub.entity.PassCheckSub; import com.jeeplus.modules.passchecksub.service.PassCheckSubService; import com.jeeplus.modules.station.entity.WorkStation; import com.jeeplus.modules.station.service.WorkStationService; import com.jeeplus.modules.vehicleaccessrecord.entity.VehicleAccessRecord; import com.jeeplus.modules.vehicleaccessrecord.service.VehicleAccessRecordService; import com.jeeplus.modules.vehicleinfo.entity.VehicleInfo; import com.jeeplus.modules.vehicleinfo.service.VehicleInfoService; import com.jeeplus.modules.warninginfo.entity.WarningInfo; import com.jeeplus.modules.warninginfo.service.WarningInfoService; import com.jeeplus.modules.weight.entity.Weight; import com.jeeplus.modules.weight.service.WeightService; import net.sf.ezmorph.object.DateMorpher; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import net.sf.json.JsonConfig; import net.sf.json.util.CycleDetectionStrategy; import net.sf.json.util.JSONUtils; import org.apache.shiro.authz.annotation.Logical; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.ConstraintViolationException; import java.net.URLDecoder; import java.text.SimpleDateFormat; import java.util.*; /** * 出门条信息Controller * * @author llh * @version 2018-12-24 */ @Controller @RequestMapping(value = "${adminPath}/gatepass/passcheck") public class GatePassController extends BaseController { @Autowired private PassCheckService passCheckService; @Autowired private WorkStationService workStationService; //车辆信息 @Autowired private VehicleInfoService vehicleInfoService; //预约单、委托单 @Autowired private ConsignService consignService; //磅单信息 @Autowired private WeightService weightService; //车辆进出记录 @Autowired private VehicleAccessRecordService vehicleAccessRecordService; //出门条明细 @Autowired private PassCheckSubService passCheckSubService; @Autowired private WarningInfoService warningInfoService; @ModelAttribute public PassCheck get(@RequestParam(required = false) String id) { PassCheck entity = null; if (StringUtils.isNotBlank(id)) { entity = passCheckService.get(id); } if (entity == null) { entity = new PassCheck(); } return entity; } /** * 出门条信息列表页面 */ @RequestMapping(value = {"list", ""}) public String list(PassCheck passCheck, Model model) { model.addAttribute("passCheck", passCheck); return "modules/gatepass/gatePassCheckList"; } /** * 出门条信息列表数据 */ @ResponseBody @RequestMapping(value = "data") public Map<String, Object> data(PassCheck passCheck, HttpServletRequest request, HttpServletResponse response, Model model) { Page<PassCheck> page = new Page<>(); if (passCheck.getSearchFlag() != null && "1".equals(passCheck.getSearchFlag())) { page = passCheckService.findPage(new Page<PassCheck>(request, response), passCheck); } return getBootstrapData(page); } /** * 查看,增加,编辑出门条信息表单页面 */ @RequiresPermissions(value = {"gatepass:passcheck:view", "gatepass:passcheck:add", "gatepass:passcheck:edit"}, logical = Logical.OR) @RequestMapping(value = "form") public String form(PassCheck passCheck, Model model) { model.addAttribute("passCheck", passCheck); return "modules/gatepass/gatePassCheckForm"; } /** * 保存出门条信息 */ @ResponseBody @RequiresPermissions(value = {"gatepass:passcheck:add", "gatepass:passcheck:edit"}, logical = Logical.OR) @RequestMapping(value = "save") public AjaxJson save(PassCheck passCheck, Model model) throws Exception { AjaxJson j = new AjaxJson(); /** * 后台hibernate-validation插件校验 */ String errMsg = beanValidator(passCheck); if (StringUtils.isNotBlank(errMsg)) { j.setSuccess(false); j.setMsg(errMsg); return j; } //新增或编辑表单保存 passCheckService.save(passCheck);//保存 j.setSuccess(true); j.setMsg("保存出门条信息成功"); return j; } /** * 删除出门条信息 */ @ResponseBody @RequiresPermissions("gatepass:passcheck:del") @RequestMapping(value = "delete") public AjaxJson delete(PassCheck passCheck) { AjaxJson j = new AjaxJson(); passCheckService.delete(passCheck); j.setMsg("删除出门条信息成功"); return j; } /** * 批量删除出门条信息 */ @ResponseBody @RequiresPermissions("gatepass:passcheck:del") @RequestMapping(value = "deleteAll") public AjaxJson deleteAll(String ids) { AjaxJson j = new AjaxJson(); String idArray[] = ids.split(","); for (String id : idArray) { passCheckService.delete(passCheckService.get(id)); } j.setMsg("删除出门条信息成功"); return j; } /** * 根据车牌号查询车辆信息、预约单/委托单和出门条等信息 */ @ResponseBody @RequestMapping(value = {"checkPass"}) public AjaxJson findPassByVehicleNo(String vehicleNo, String rfidNo, HttpServletRequest request, HttpServletResponse response) { AjaxJson j = new AjaxJson(); PassCheck p = new PassCheck(); String a = request.getRemoteAddr(); System.out.println("===================ip:"+a); WorkStation ws = workStationService.queryByStationIp(a); //1。未识别到车牌 if ((vehicleNo == null || "".equals(vehicleNo.trim())) && (rfidNo == null || "".equals(rfidNo))) { j.setSuccess(false); return j; } if (vehicleNo != null && !"".equals(vehicleNo.trim())) { String errvehicleNo = vehicleNo.substring(1, 2); if (StringUtils.isNumeric(errvehicleNo)) { j.setSuccess(false); return j; } } //根据RFID查询车牌 if (rfidNo != null && !"".equals(rfidNo)) { List<VehicleInfo> vi = vehicleInfoService.getVehicleNoByRfid(rfidNo); if (vi.size() > 0) { vehicleNo = vi.get(0).getVehicleNo(); } } j.setErrorCode(vehicleNo); if (vehicleNo != null && !"".equals(vehicleNo.trim())) { //公务车直接放行 List<VehicleInfo> vl = vehicleInfoService.checkByVehicleNo(vehicleNo); if (vl.size() > 0) { for (VehicleInfo v : vl) { if (v.getTypeCode() != null && "01".equals(v.getTypeCode())) { j.setObject("10"); j.setSuccess(true); j.setMsg(v.getVehicleNo() + " " + v.getGroupCompanyName()); return j; } } } //2.违章车辆不允许出门 List<WarningInfo> wi = warningInfoService.findInfoByVehicleNo(vehicleNo); if (wi.size() > 0) { System.out.println(new Date() + "," + wi.get(0).getVehicleNo() + "," + "违章信息: " + wi.get(0).getReason()); String msg = wi.get(0).getVehicleNo() + " 违章车辆! 违章信息: " + wi.get(0).getReason(); j.setMsg(msg); j.setSuccess(false); return j; } Date da = new Date(); Date date = new Date(); StringBuilder str = new StringBuilder(); str.append(vehicleNo); //查询该车是重车还是空车 //查询该车辆进门后是否过磅 if (!"10.12.241.107".equals(a) && !"10.12.240.139".equals(a)) { List<Weight> vehicle = weightService.queryVehicle(vehicleNo); if (vehicle.size() > 0) { String veh = vehicle.get(0).getWeightType(); //根据过磅类型判断空重车 if ("01".equals(veh) || "06".equals(veh) || "07".equals(veh) || "08".equals(veh)) { if (null != vehicle.get(0).getMatWt() && !"0.00".equals(vehicle.get(0).getMatWt()) && !"".equals(vehicle.get(0).getMatWt())) { str.append(" 重车 净重:" + vehicle.get(0).getMatWt()); } } } } //查询车辆是否有出门条信息 p.setVehicleNo(vehicleNo); List<PassCheck> pcl = passCheckService.findPassByVehicleNo(p); if (pcl.size() > 0) { for (PassCheck pc : pcl) { if (pc.getTypeName() != null) { str.append("物资类别:" + pc.getTypeName()); } if (pc.getStartTime().getTime() < da.getTime() && pc.getEndTime().getTime() > da.getTime()) { if (ws != null && ws.getOutPassCode() != null) { String[] strs = pc.getPassCode().split(","); for (String s : strs) { if (s.equals(ws.getOutPassCode())) { if ("07".equals(pc.getTypeCode())) { str.append(" 出门条物资清单:"); List<PassCheckSub> ps = passCheckSubService.findPassCheckSubList(pc.getTrnpAppNo()); if (ps.size() > 0) { for (PassCheckSub pcs : ps) { str.append(pcs.getProdCname() + ", 件数:" + pcs.getSubNum() + ", 规格:" + pcs.getMatSpecDesc() + ", 合计:" + pcs.getProdNum() + pcs.getMeasureUnit() + " "); } } } else { List<PassCheckSub> ps = passCheckSubService.findCheckSubList(pc.getTrnpAppNo()); if (ps.size() > 0) { for (PassCheckSub pcs : ps) { str.append(pcs.getProdCname() + ", 规格:" + pcs.getMatSpecDesc() + ", 合计:" + pcs.getOutStockQty() + pcs.getMeasureUnit() + " "); } } } j.setObject("3"); j.setSuccess(true); j.setMsg(str.toString()); return j; } } j.setSuccess(false); j.setMsg(vehicleNo + " 请从其他门岗出门!"); return j; } } } } //4.判断放行码,放行码符合自动开门 Consign cos = new Consign(); cos.setVehicleNo(vehicleNo); List<Consign> coslist = consignService.checkOutByVehicleNo(cos); if (ws != null && ws.getOutPassCode() != null) { String outPass = ws.getOutPassCode(); List<VehicleInfo> veh = vehicleInfoService.checkByVehicleNo(vehicleNo); if (veh.size() > 0) { for (VehicleInfo ve : veh) { if (ve.getStartTime().getTime() < date.getTime() && ve.getEndTime().getTime() > date.getTime()) { String PassCode = ve.getPassCode(); if (PassCode != null && !"".equals(PassCode)) { String[] strs = PassCode.split(","); for (String s : strs) { if (outPass.equals(s)) { j.setObject("2"); j.setSuccess(true); j.setMsg(ve.getVehicleNo() + " " + ve.getGroupCompanyName()); return j; } } for (String s : strs) { if (ws.getInPassCode().equals(s)) { j.setObject("4"); j.setSuccess(true); j.setMsg(ve.getVehicleNo() + " " + ve.getGroupCompanyName() + ",请检查"); return j; } } if (coslist.size() > 0) { for (Consign s : coslist) { if (s.getPassCode() != null) { if (s.getPassCode().equals(ws.getInPassCode())) { j.setSuccess(false); j.setMsg(vehicleNo + " 临时车辆,请检查!"); return j; } } } j.setSuccess(false); j.setMsg(vehicleNo + " 请从其他门岗出门!"); return j; } else { j.setSuccess(false); j.setMsg(vehicleNo + " 请从其他门岗出门!"); return j; } } } } } } if (coslist != null && coslist.size() > 0) { if (ws != null && ws.getInPassCode() != null) { for (Consign s : coslist) { if (s.getPassCode() != null) { String[] strs = s.getPassCode().split(","); for (String sr : strs) { if (ws.getInPassCode().equals(sr)) { j.setSuccess(false); j.setMsg(vehicleNo + " 临时车辆,请检查!"); return j; } } } } j.setSuccess(false); j.setMsg(vehicleNo + " 请从其他门岗出门!"); return j; } } else { if ("10.12.241.107".equals(a)) { j.setSuccess(false); j.setMsg(vehicleNo + " 临时车辆,请检查!"); return j; } else { j.setSuccess(false); j.setMsg(vehicleNo + " 过夜车辆,请检查!"); return j; } } } j.setSuccess(false); return j; } /** * 导出excel文件 */ @ResponseBody @RequiresPermissions("gatepass:passcheck:export") @RequestMapping(value = "export") public AjaxJson exportFile(PassCheck passCheck, HttpServletRequest request, HttpServletResponse response) { AjaxJson j = new AjaxJson(); try { String param = URLDecoder.decode(request.getParameter("data"), "UTF-8"); JSONObject jo = JSONObject.fromObject(param); if (jo.get("startTime") == null || "".equals(jo.get("startTime"))) { jo.remove("startTime"); } if (jo.get("endTime") == null || "".equals(jo.get("endTime"))) { jo.remove("endTime"); } JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass(PassCheck.class); String[] dateFamates = new String[]{"yyyy-MM-dd HH:mm:ss"}; JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(dateFamates)); passCheck = (PassCheck) JSONObject.toBean(jo, PassCheck.class); String fileName = "出门条信息" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx"; Page<PassCheck> page = passCheckService.findPage(new Page<PassCheck>(request, response, -1), passCheck); new ExportExcel("出门条信息", PassCheck.class).setDataList(page.getList()).write(response, fileName).dispose(); j.setSuccess(true); j.setMsg("导出成功!"); return j; } catch (Exception e) { j.setSuccess(false); j.setMsg("导出出门条信息记录失败!失败信息:" + e.getMessage()); } return j; } /** * 导入Excel数据 */ @ResponseBody @RequiresPermissions("gatepass:passcheck:import") @RequestMapping(value = "import") public AjaxJson importFile(@RequestParam("file") MultipartFile file, HttpServletResponse response, HttpServletRequest request) { AjaxJson j = new AjaxJson(); try { int successNum = 0; int failureNum = 0; StringBuilder failureMsg = new StringBuilder(); ImportExcel ei = new ImportExcel(file, 1, 0); List<PassCheck> list = ei.getDataList(PassCheck.class); for (PassCheck passCheck : list) { try { passCheckService.save(passCheck); successNum++; } catch (ConstraintViolationException ex) { failureNum++; } catch (Exception ex) { failureNum++; } } if (failureNum > 0) { failureMsg.insert(0, ",失败 " + failureNum + " 条出门条信息记录。"); } j.setMsg("已成功导入 " + successNum + " 条出门条信息记录" + failureMsg); } catch (Exception e) { j.setSuccess(false); j.setMsg("导入出门条信息失败!失败信息:" + e.getMessage()); } return j; } /** * 下载导入出门条信息数据模板 */ @ResponseBody @RequiresPermissions("gatepass:passcheck:import") @RequestMapping(value = "import/template") public AjaxJson importFileTemplate(HttpServletResponse response) { AjaxJson j = new AjaxJson(); try { String fileName = "出门条信息数据导入模板.xlsx"; List<PassCheck> list = Lists.newArrayList(); new ExportExcel("出门条信息数据", PassCheck.class, 1).setDataList(list).write(response, fileName).dispose(); return null; } catch (Exception e) { j.setSuccess(false); j.setMsg("导入模板下载失败!失败信息:" + e.getMessage()); } return j; } /** * 查看出门条信息,客户模板展示 */ @RequestMapping(value = "form1") public String form1(String trnpAppNo, Model model) { List<PassCheckSub> list = passCheckSubService.findPassCheckSubList(trnpAppNo); System.out.println(list.toString()); model.addAttribute("list", list); return "modules/gatepass/gatePassCheckInfoForm"; } /** * 保存抓拍图片信息 */ @ResponseBody @RequestMapping(value = {"saveTackPhoto"}) public AjaxJson saveTackPhoto(String vehicleNo, String rfidNo, String ct, HttpServletRequest request, HttpServletResponse response) { AjaxJson j = new AjaxJson(); PassCheck p = new PassCheck(); String a = request.getRemoteAddr(); WorkStation ws = workStationService.queryByStationIp(a); //1。未识别到车牌 if ((vehicleNo == null || "".equals(vehicleNo)) && (rfidNo == null || "".equals(rfidNo))) { j.setMsg("未识别到车牌!"); j.setSuccess(false); return j; } //根据RFID查询车牌 if (rfidNo != null && !"".equals(rfidNo)) { List<VehicleInfo> vi = vehicleInfoService.getVehicleNoByRfid(rfidNo); if (vi.size() > 0) { vehicleNo = vi.get(0).getVehicleNo(); } } //保存车辆出门信息 VehicleAccessRecord vehicleaccessRecord = new VehicleAccessRecord(); vehicleaccessRecord.setVehicleNo(vehicleNo); if (vehicleNo != null && !"".equals(vehicleNo)) { List<VehicleAccessRecord> ve = vehicleAccessRecordService.queryRecord(vehicleaccessRecord); PropertiesLoader pro = new PropertiesLoader("/properties/config.properties"); String gatePath = pro.getProperty("gatePath") + ""; String http = "http://"; String hostip = pro.getProperty("hostip") + ""; String hostport = pro.getProperty("hostport") + ""; String path = http + hostip + ":" + hostport + gatePath; SimpleDateFormat sdfs = new SimpleDateFormat("yyyy/MM/dd/"); String timefile = sdfs.format(new Date()); if (ve.size() > 0) { ve.get(0).setTakePhotos(path + timefile + ct); vehicleAccessRecordService.updatePic(ve.get(0)); } } return j; } /** * 保存出门信息 */ @ResponseBody @RequestMapping(value = "saveVehicleOut") public AjaxJson saveVehicleOut(Consign consign, HttpServletRequest request) { AjaxJson j = new AjaxJson(); try { String a = request.getRemoteAddr(); WorkStation ws = workStationService.queryByStationIp(a); if (ws != null) { //保存车辆出门信息 VehicleAccessRecord vehicleaccessRecord = new VehicleAccessRecord(); vehicleaccessRecord.setVehicleNo(consign.getVehicleNo()); vehicleaccessRecord.setOutTime(new Date()); vehicleaccessRecord.setCreateDate(new Date()); vehicleaccessRecord.setRemarks(ws.getWorkStation()); vehicleaccessRecord.setIdcard(""); if (consign.getRemarks() != null && "1".equals(consign.getRemarks())) { vehicleaccessRecord.setRfidNo("2"); } else { vehicleaccessRecord.setRfidNo("3"); } List<VehicleInfo> vil = vehicleInfoService.checkByVehicleNo(consign.getVehicleNo()); if (vil.size() > 0) { for (VehicleInfo v : vil) { vehicleaccessRecord.setTransContactPerson(v.getTransContactPerson()); vehicleaccessRecord.setTransContactPersonTel(v.getTransContactPersonTel()); } } //根据车牌号查询委托信息 List<Consign> cl = consignService.findConsignByVehicleNo(consign); if (cl.size() > 0) { vehicleaccessRecord.setConsignType(cl.get(0).getType()); vehicleaccessRecord.setTransContactPerson(cl.get(0).getUserName()); vehicleaccessRecord.setTransContactPersonTel(cl.get(0).getTel()); } vehicleAccessRecordService.save(vehicleaccessRecord); j.setSuccess(true); } } catch (Exception e) { j.setSuccess(false); } return j; } /** * 作废出门条 */ @ResponseBody @RequestMapping(value = "deletePass") public AjaxJson deletePass(String vehicleNo, String rfidNo, String ickh) { AjaxJson j = new AjaxJson(); try { //根据RFID查询车牌 if (rfidNo != null && !"".equals(rfidNo)) { List<VehicleInfo> vi = vehicleInfoService.getVehicleNoByRfid(rfidNo); if (vi.size() > 0) { vehicleNo = vi.get(0).getVehicleNo(); } } //查询是否有出门条,给四级反馈 InterfaceTest ift = new InterfaceTest(); ift.postPasscheck(vehicleNo, ickh); PassCheck p = new PassCheck(); p.setVehicleNo(vehicleNo); System.out.println("删除出门条"); p.setValidFlag("2"); passCheckService.delByLogic(p); j.setSuccess(true); } catch (Exception e) { j.setSuccess(false); } return j; } }
UTF-8
Java
26,616
java
GatePassController.java
Java
[ { "context": "java.util.*;\n\n/**\n * 出门条信息Controller\n *\n * @author llh\n * @version 2018-12-24\n */\n@Controller\n@RequestMa", "end": 2680, "score": 0.999564528465271, "start": 2677, "tag": "USERNAME", "value": "llh" }, { "context": "还是空车\n //查询该车辆进门后是否过磅\n i...
null
[]
/** * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.gatepass; import com.google.common.collect.Lists; import com.jeeplus.common.json.AjaxJson; import com.jeeplus.common.utils.*; import com.jeeplus.common.utils.excel.ExportExcel; import com.jeeplus.common.utils.excel.ImportExcel; import com.jeeplus.core.persistence.Page; import com.jeeplus.core.web.BaseController; import com.jeeplus.modules.consign.entity.Consign; import com.jeeplus.modules.consign.service.ConsignService; import com.jeeplus.modules.interfaceTest.Controller.InterfaceTest; import com.jeeplus.modules.interfaceTest.entry.JsonType; import com.jeeplus.modules.interfaceTest.entry.PassFeedBack; import com.jeeplus.modules.passcheck.entity.PassCheck; import com.jeeplus.modules.passcheck.service.PassCheckService; import com.jeeplus.modules.passchecksub.entity.PassCheckSub; import com.jeeplus.modules.passchecksub.service.PassCheckSubService; import com.jeeplus.modules.station.entity.WorkStation; import com.jeeplus.modules.station.service.WorkStationService; import com.jeeplus.modules.vehicleaccessrecord.entity.VehicleAccessRecord; import com.jeeplus.modules.vehicleaccessrecord.service.VehicleAccessRecordService; import com.jeeplus.modules.vehicleinfo.entity.VehicleInfo; import com.jeeplus.modules.vehicleinfo.service.VehicleInfoService; import com.jeeplus.modules.warninginfo.entity.WarningInfo; import com.jeeplus.modules.warninginfo.service.WarningInfoService; import com.jeeplus.modules.weight.entity.Weight; import com.jeeplus.modules.weight.service.WeightService; import net.sf.ezmorph.object.DateMorpher; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import net.sf.json.JsonConfig; import net.sf.json.util.CycleDetectionStrategy; import net.sf.json.util.JSONUtils; import org.apache.shiro.authz.annotation.Logical; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.ConstraintViolationException; import java.net.URLDecoder; import java.text.SimpleDateFormat; import java.util.*; /** * 出门条信息Controller * * @author llh * @version 2018-12-24 */ @Controller @RequestMapping(value = "${adminPath}/gatepass/passcheck") public class GatePassController extends BaseController { @Autowired private PassCheckService passCheckService; @Autowired private WorkStationService workStationService; //车辆信息 @Autowired private VehicleInfoService vehicleInfoService; //预约单、委托单 @Autowired private ConsignService consignService; //磅单信息 @Autowired private WeightService weightService; //车辆进出记录 @Autowired private VehicleAccessRecordService vehicleAccessRecordService; //出门条明细 @Autowired private PassCheckSubService passCheckSubService; @Autowired private WarningInfoService warningInfoService; @ModelAttribute public PassCheck get(@RequestParam(required = false) String id) { PassCheck entity = null; if (StringUtils.isNotBlank(id)) { entity = passCheckService.get(id); } if (entity == null) { entity = new PassCheck(); } return entity; } /** * 出门条信息列表页面 */ @RequestMapping(value = {"list", ""}) public String list(PassCheck passCheck, Model model) { model.addAttribute("passCheck", passCheck); return "modules/gatepass/gatePassCheckList"; } /** * 出门条信息列表数据 */ @ResponseBody @RequestMapping(value = "data") public Map<String, Object> data(PassCheck passCheck, HttpServletRequest request, HttpServletResponse response, Model model) { Page<PassCheck> page = new Page<>(); if (passCheck.getSearchFlag() != null && "1".equals(passCheck.getSearchFlag())) { page = passCheckService.findPage(new Page<PassCheck>(request, response), passCheck); } return getBootstrapData(page); } /** * 查看,增加,编辑出门条信息表单页面 */ @RequiresPermissions(value = {"gatepass:passcheck:view", "gatepass:passcheck:add", "gatepass:passcheck:edit"}, logical = Logical.OR) @RequestMapping(value = "form") public String form(PassCheck passCheck, Model model) { model.addAttribute("passCheck", passCheck); return "modules/gatepass/gatePassCheckForm"; } /** * 保存出门条信息 */ @ResponseBody @RequiresPermissions(value = {"gatepass:passcheck:add", "gatepass:passcheck:edit"}, logical = Logical.OR) @RequestMapping(value = "save") public AjaxJson save(PassCheck passCheck, Model model) throws Exception { AjaxJson j = new AjaxJson(); /** * 后台hibernate-validation插件校验 */ String errMsg = beanValidator(passCheck); if (StringUtils.isNotBlank(errMsg)) { j.setSuccess(false); j.setMsg(errMsg); return j; } //新增或编辑表单保存 passCheckService.save(passCheck);//保存 j.setSuccess(true); j.setMsg("保存出门条信息成功"); return j; } /** * 删除出门条信息 */ @ResponseBody @RequiresPermissions("gatepass:passcheck:del") @RequestMapping(value = "delete") public AjaxJson delete(PassCheck passCheck) { AjaxJson j = new AjaxJson(); passCheckService.delete(passCheck); j.setMsg("删除出门条信息成功"); return j; } /** * 批量删除出门条信息 */ @ResponseBody @RequiresPermissions("gatepass:passcheck:del") @RequestMapping(value = "deleteAll") public AjaxJson deleteAll(String ids) { AjaxJson j = new AjaxJson(); String idArray[] = ids.split(","); for (String id : idArray) { passCheckService.delete(passCheckService.get(id)); } j.setMsg("删除出门条信息成功"); return j; } /** * 根据车牌号查询车辆信息、预约单/委托单和出门条等信息 */ @ResponseBody @RequestMapping(value = {"checkPass"}) public AjaxJson findPassByVehicleNo(String vehicleNo, String rfidNo, HttpServletRequest request, HttpServletResponse response) { AjaxJson j = new AjaxJson(); PassCheck p = new PassCheck(); String a = request.getRemoteAddr(); System.out.println("===================ip:"+a); WorkStation ws = workStationService.queryByStationIp(a); //1。未识别到车牌 if ((vehicleNo == null || "".equals(vehicleNo.trim())) && (rfidNo == null || "".equals(rfidNo))) { j.setSuccess(false); return j; } if (vehicleNo != null && !"".equals(vehicleNo.trim())) { String errvehicleNo = vehicleNo.substring(1, 2); if (StringUtils.isNumeric(errvehicleNo)) { j.setSuccess(false); return j; } } //根据RFID查询车牌 if (rfidNo != null && !"".equals(rfidNo)) { List<VehicleInfo> vi = vehicleInfoService.getVehicleNoByRfid(rfidNo); if (vi.size() > 0) { vehicleNo = vi.get(0).getVehicleNo(); } } j.setErrorCode(vehicleNo); if (vehicleNo != null && !"".equals(vehicleNo.trim())) { //公务车直接放行 List<VehicleInfo> vl = vehicleInfoService.checkByVehicleNo(vehicleNo); if (vl.size() > 0) { for (VehicleInfo v : vl) { if (v.getTypeCode() != null && "01".equals(v.getTypeCode())) { j.setObject("10"); j.setSuccess(true); j.setMsg(v.getVehicleNo() + " " + v.getGroupCompanyName()); return j; } } } //2.违章车辆不允许出门 List<WarningInfo> wi = warningInfoService.findInfoByVehicleNo(vehicleNo); if (wi.size() > 0) { System.out.println(new Date() + "," + wi.get(0).getVehicleNo() + "," + "违章信息: " + wi.get(0).getReason()); String msg = wi.get(0).getVehicleNo() + " 违章车辆! 违章信息: " + wi.get(0).getReason(); j.setMsg(msg); j.setSuccess(false); return j; } Date da = new Date(); Date date = new Date(); StringBuilder str = new StringBuilder(); str.append(vehicleNo); //查询该车是重车还是空车 //查询该车辆进门后是否过磅 if (!"10.12.241.107".equals(a) && !"10.12.240.139".equals(a)) { List<Weight> vehicle = weightService.queryVehicle(vehicleNo); if (vehicle.size() > 0) { String veh = vehicle.get(0).getWeightType(); //根据过磅类型判断空重车 if ("01".equals(veh) || "06".equals(veh) || "07".equals(veh) || "08".equals(veh)) { if (null != vehicle.get(0).getMatWt() && !"0.00".equals(vehicle.get(0).getMatWt()) && !"".equals(vehicle.get(0).getMatWt())) { str.append(" 重车 净重:" + vehicle.get(0).getMatWt()); } } } } //查询车辆是否有出门条信息 p.setVehicleNo(vehicleNo); List<PassCheck> pcl = passCheckService.findPassByVehicleNo(p); if (pcl.size() > 0) { for (PassCheck pc : pcl) { if (pc.getTypeName() != null) { str.append("物资类别:" + pc.getTypeName()); } if (pc.getStartTime().getTime() < da.getTime() && pc.getEndTime().getTime() > da.getTime()) { if (ws != null && ws.getOutPassCode() != null) { String[] strs = pc.getPassCode().split(","); for (String s : strs) { if (s.equals(ws.getOutPassCode())) { if ("07".equals(pc.getTypeCode())) { str.append(" 出门条物资清单:"); List<PassCheckSub> ps = passCheckSubService.findPassCheckSubList(pc.getTrnpAppNo()); if (ps.size() > 0) { for (PassCheckSub pcs : ps) { str.append(pcs.getProdCname() + ", 件数:" + pcs.getSubNum() + ", 规格:" + pcs.getMatSpecDesc() + ", 合计:" + pcs.getProdNum() + pcs.getMeasureUnit() + " "); } } } else { List<PassCheckSub> ps = passCheckSubService.findCheckSubList(pc.getTrnpAppNo()); if (ps.size() > 0) { for (PassCheckSub pcs : ps) { str.append(pcs.getProdCname() + ", 规格:" + pcs.getMatSpecDesc() + ", 合计:" + pcs.getOutStockQty() + pcs.getMeasureUnit() + " "); } } } j.setObject("3"); j.setSuccess(true); j.setMsg(str.toString()); return j; } } j.setSuccess(false); j.setMsg(vehicleNo + " 请从其他门岗出门!"); return j; } } } } //4.判断放行码,放行码符合自动开门 Consign cos = new Consign(); cos.setVehicleNo(vehicleNo); List<Consign> coslist = consignService.checkOutByVehicleNo(cos); if (ws != null && ws.getOutPassCode() != null) { String outPass = ws.getOutPassCode(); List<VehicleInfo> veh = vehicleInfoService.checkByVehicleNo(vehicleNo); if (veh.size() > 0) { for (VehicleInfo ve : veh) { if (ve.getStartTime().getTime() < date.getTime() && ve.getEndTime().getTime() > date.getTime()) { String PassCode = ve.getPassCode(); if (PassCode != null && !"".equals(PassCode)) { String[] strs = PassCode.split(","); for (String s : strs) { if (outPass.equals(s)) { j.setObject("2"); j.setSuccess(true); j.setMsg(ve.getVehicleNo() + " " + ve.getGroupCompanyName()); return j; } } for (String s : strs) { if (ws.getInPassCode().equals(s)) { j.setObject("4"); j.setSuccess(true); j.setMsg(ve.getVehicleNo() + " " + ve.getGroupCompanyName() + ",请检查"); return j; } } if (coslist.size() > 0) { for (Consign s : coslist) { if (s.getPassCode() != null) { if (s.getPassCode().equals(ws.getInPassCode())) { j.setSuccess(false); j.setMsg(vehicleNo + " 临时车辆,请检查!"); return j; } } } j.setSuccess(false); j.setMsg(vehicleNo + " 请从其他门岗出门!"); return j; } else { j.setSuccess(false); j.setMsg(vehicleNo + " 请从其他门岗出门!"); return j; } } } } } } if (coslist != null && coslist.size() > 0) { if (ws != null && ws.getInPassCode() != null) { for (Consign s : coslist) { if (s.getPassCode() != null) { String[] strs = s.getPassCode().split(","); for (String sr : strs) { if (ws.getInPassCode().equals(sr)) { j.setSuccess(false); j.setMsg(vehicleNo + " 临时车辆,请检查!"); return j; } } } } j.setSuccess(false); j.setMsg(vehicleNo + " 请从其他门岗出门!"); return j; } } else { if ("10.12.241.107".equals(a)) { j.setSuccess(false); j.setMsg(vehicleNo + " 临时车辆,请检查!"); return j; } else { j.setSuccess(false); j.setMsg(vehicleNo + " 过夜车辆,请检查!"); return j; } } } j.setSuccess(false); return j; } /** * 导出excel文件 */ @ResponseBody @RequiresPermissions("gatepass:passcheck:export") @RequestMapping(value = "export") public AjaxJson exportFile(PassCheck passCheck, HttpServletRequest request, HttpServletResponse response) { AjaxJson j = new AjaxJson(); try { String param = URLDecoder.decode(request.getParameter("data"), "UTF-8"); JSONObject jo = JSONObject.fromObject(param); if (jo.get("startTime") == null || "".equals(jo.get("startTime"))) { jo.remove("startTime"); } if (jo.get("endTime") == null || "".equals(jo.get("endTime"))) { jo.remove("endTime"); } JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass(PassCheck.class); String[] dateFamates = new String[]{"yyyy-MM-dd HH:mm:ss"}; JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(dateFamates)); passCheck = (PassCheck) JSONObject.toBean(jo, PassCheck.class); String fileName = "出门条信息" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx"; Page<PassCheck> page = passCheckService.findPage(new Page<PassCheck>(request, response, -1), passCheck); new ExportExcel("出门条信息", PassCheck.class).setDataList(page.getList()).write(response, fileName).dispose(); j.setSuccess(true); j.setMsg("导出成功!"); return j; } catch (Exception e) { j.setSuccess(false); j.setMsg("导出出门条信息记录失败!失败信息:" + e.getMessage()); } return j; } /** * 导入Excel数据 */ @ResponseBody @RequiresPermissions("gatepass:passcheck:import") @RequestMapping(value = "import") public AjaxJson importFile(@RequestParam("file") MultipartFile file, HttpServletResponse response, HttpServletRequest request) { AjaxJson j = new AjaxJson(); try { int successNum = 0; int failureNum = 0; StringBuilder failureMsg = new StringBuilder(); ImportExcel ei = new ImportExcel(file, 1, 0); List<PassCheck> list = ei.getDataList(PassCheck.class); for (PassCheck passCheck : list) { try { passCheckService.save(passCheck); successNum++; } catch (ConstraintViolationException ex) { failureNum++; } catch (Exception ex) { failureNum++; } } if (failureNum > 0) { failureMsg.insert(0, ",失败 " + failureNum + " 条出门条信息记录。"); } j.setMsg("已成功导入 " + successNum + " 条出门条信息记录" + failureMsg); } catch (Exception e) { j.setSuccess(false); j.setMsg("导入出门条信息失败!失败信息:" + e.getMessage()); } return j; } /** * 下载导入出门条信息数据模板 */ @ResponseBody @RequiresPermissions("gatepass:passcheck:import") @RequestMapping(value = "import/template") public AjaxJson importFileTemplate(HttpServletResponse response) { AjaxJson j = new AjaxJson(); try { String fileName = "出门条信息数据导入模板.xlsx"; List<PassCheck> list = Lists.newArrayList(); new ExportExcel("出门条信息数据", PassCheck.class, 1).setDataList(list).write(response, fileName).dispose(); return null; } catch (Exception e) { j.setSuccess(false); j.setMsg("导入模板下载失败!失败信息:" + e.getMessage()); } return j; } /** * 查看出门条信息,客户模板展示 */ @RequestMapping(value = "form1") public String form1(String trnpAppNo, Model model) { List<PassCheckSub> list = passCheckSubService.findPassCheckSubList(trnpAppNo); System.out.println(list.toString()); model.addAttribute("list", list); return "modules/gatepass/gatePassCheckInfoForm"; } /** * 保存抓拍图片信息 */ @ResponseBody @RequestMapping(value = {"saveTackPhoto"}) public AjaxJson saveTackPhoto(String vehicleNo, String rfidNo, String ct, HttpServletRequest request, HttpServletResponse response) { AjaxJson j = new AjaxJson(); PassCheck p = new PassCheck(); String a = request.getRemoteAddr(); WorkStation ws = workStationService.queryByStationIp(a); //1。未识别到车牌 if ((vehicleNo == null || "".equals(vehicleNo)) && (rfidNo == null || "".equals(rfidNo))) { j.setMsg("未识别到车牌!"); j.setSuccess(false); return j; } //根据RFID查询车牌 if (rfidNo != null && !"".equals(rfidNo)) { List<VehicleInfo> vi = vehicleInfoService.getVehicleNoByRfid(rfidNo); if (vi.size() > 0) { vehicleNo = vi.get(0).getVehicleNo(); } } //保存车辆出门信息 VehicleAccessRecord vehicleaccessRecord = new VehicleAccessRecord(); vehicleaccessRecord.setVehicleNo(vehicleNo); if (vehicleNo != null && !"".equals(vehicleNo)) { List<VehicleAccessRecord> ve = vehicleAccessRecordService.queryRecord(vehicleaccessRecord); PropertiesLoader pro = new PropertiesLoader("/properties/config.properties"); String gatePath = pro.getProperty("gatePath") + ""; String http = "http://"; String hostip = pro.getProperty("hostip") + ""; String hostport = pro.getProperty("hostport") + ""; String path = http + hostip + ":" + hostport + gatePath; SimpleDateFormat sdfs = new SimpleDateFormat("yyyy/MM/dd/"); String timefile = sdfs.format(new Date()); if (ve.size() > 0) { ve.get(0).setTakePhotos(path + timefile + ct); vehicleAccessRecordService.updatePic(ve.get(0)); } } return j; } /** * 保存出门信息 */ @ResponseBody @RequestMapping(value = "saveVehicleOut") public AjaxJson saveVehicleOut(Consign consign, HttpServletRequest request) { AjaxJson j = new AjaxJson(); try { String a = request.getRemoteAddr(); WorkStation ws = workStationService.queryByStationIp(a); if (ws != null) { //保存车辆出门信息 VehicleAccessRecord vehicleaccessRecord = new VehicleAccessRecord(); vehicleaccessRecord.setVehicleNo(consign.getVehicleNo()); vehicleaccessRecord.setOutTime(new Date()); vehicleaccessRecord.setCreateDate(new Date()); vehicleaccessRecord.setRemarks(ws.getWorkStation()); vehicleaccessRecord.setIdcard(""); if (consign.getRemarks() != null && "1".equals(consign.getRemarks())) { vehicleaccessRecord.setRfidNo("2"); } else { vehicleaccessRecord.setRfidNo("3"); } List<VehicleInfo> vil = vehicleInfoService.checkByVehicleNo(consign.getVehicleNo()); if (vil.size() > 0) { for (VehicleInfo v : vil) { vehicleaccessRecord.setTransContactPerson(v.getTransContactPerson()); vehicleaccessRecord.setTransContactPersonTel(v.getTransContactPersonTel()); } } //根据车牌号查询委托信息 List<Consign> cl = consignService.findConsignByVehicleNo(consign); if (cl.size() > 0) { vehicleaccessRecord.setConsignType(cl.get(0).getType()); vehicleaccessRecord.setTransContactPerson(cl.get(0).getUserName()); vehicleaccessRecord.setTransContactPersonTel(cl.get(0).getTel()); } vehicleAccessRecordService.save(vehicleaccessRecord); j.setSuccess(true); } } catch (Exception e) { j.setSuccess(false); } return j; } /** * 作废出门条 */ @ResponseBody @RequestMapping(value = "deletePass") public AjaxJson deletePass(String vehicleNo, String rfidNo, String ickh) { AjaxJson j = new AjaxJson(); try { //根据RFID查询车牌 if (rfidNo != null && !"".equals(rfidNo)) { List<VehicleInfo> vi = vehicleInfoService.getVehicleNoByRfid(rfidNo); if (vi.size() > 0) { vehicleNo = vi.get(0).getVehicleNo(); } } //查询是否有出门条,给四级反馈 InterfaceTest ift = new InterfaceTest(); ift.postPasscheck(vehicleNo, ickh); PassCheck p = new PassCheck(); p.setVehicleNo(vehicleNo); System.out.println("删除出门条"); p.setValidFlag("2"); passCheckService.delByLogic(p); j.setSuccess(true); } catch (Exception e) { j.setSuccess(false); } return j; } }
26,616
0.519143
0.514426
646
38.382355
29.684631
209
false
false
0
0
0
0
0
0
0.549536
false
false
6
3984ed14ae48f5c7b9c1634387eebef4f9c3d6c3
9,594,956,996,247
21fd3e2805671160236045899ef3e51c4c139a67
/concurrency/src/com/timbuchalka/java/ThreadDemo.java
119fbc146db6a3d4075c2d9998836efebd7df9d4
[]
no_license
ayunas/java
https://github.com/ayunas/java
34898e3c7b15237e4e57a7c026c3e947df1834d5
28f32f4ed9cc08efe6c0dbe6af8de0f4b48cc308
refs/heads/master
2021-05-23T13:10:58.396000
2020-06-15T11:30:17
2020-06-15T11:30:17
253,302,309
0
0
null
false
2020-10-13T22:36:16
2020-04-05T18:19:32
2020-06-15T11:31:09
2020-10-13T22:36:15
1,003
0
0
1
Java
false
false
package com.timbuchalka.java; import static com.timbuchalka.java.ThreadColors.*; public class ThreadDemo extends Thread { ThreadDemo() { run(); //this runs on same thread of where it was invoked i.e. main start(); //this runs in a new thread } @Override public void run() { System.out.println(ANSI_BLUE + "running the thread demo from " + currentThread().getName()); try { Thread.sleep(3000); } catch(InterruptedException e) { System.out.println(ANSI_RED + " Another thread woke me up"); } System.out.println(ANSI_CYAN + " 3 SECONDS HAVE PASSED AND I'M AWAKE"); } }
UTF-8
Java
672
java
ThreadDemo.java
Java
[]
null
[]
package com.timbuchalka.java; import static com.timbuchalka.java.ThreadColors.*; public class ThreadDemo extends Thread { ThreadDemo() { run(); //this runs on same thread of where it was invoked i.e. main start(); //this runs in a new thread } @Override public void run() { System.out.println(ANSI_BLUE + "running the thread demo from " + currentThread().getName()); try { Thread.sleep(3000); } catch(InterruptedException e) { System.out.println(ANSI_RED + " Another thread woke me up"); } System.out.println(ANSI_CYAN + " 3 SECONDS HAVE PASSED AND I'M AWAKE"); } }
672
0.614583
0.607143
24
27
29.151901
100
false
false
0
0
0
0
0
0
0.333333
false
false
6
c53218d99fabdb28b94bce87b345bb113ff17bfe
3,856,880,692,910
6c10565e44495cca2cc337835c7a6d6489d657ba
/src/main/java/com/android/base/mvvm/viewmodel/ErrorEnvelope.java
bb5a0799c529f694d1d617fbd05346788b13a5d6
[]
no_license
yuzhongrong/base
https://github.com/yuzhongrong/base
57f1a95919d40c6994c2ea4ae5b543c51f1b98ba
80293b25e0cc35a3f715ff34d2891a23050d6022
refs/heads/master
2022-05-26T10:33:50.498000
2020-05-02T06:06:11
2020-05-02T06:06:11
260,625,045
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.android.base.mvvm.viewmodel; import androidx.annotation.Nullable; public class ErrorEnvelope { public final int code; @Nullable public final String message; @Nullable private final Throwable throwable; public ErrorEnvelope(@Nullable String message) { this(Constants.ErrorCode.UNKNOWN, message); } public ErrorEnvelope(int code, @Nullable String message) { this(code, message, null); } public ErrorEnvelope(int code, @Nullable String message, @Nullable Throwable throwable) { this.code = code; this.message = message; this.throwable = throwable; } }
UTF-8
Java
651
java
ErrorEnvelope.java
Java
[]
null
[]
package com.android.base.mvvm.viewmodel; import androidx.annotation.Nullable; public class ErrorEnvelope { public final int code; @Nullable public final String message; @Nullable private final Throwable throwable; public ErrorEnvelope(@Nullable String message) { this(Constants.ErrorCode.UNKNOWN, message); } public ErrorEnvelope(int code, @Nullable String message) { this(code, message, null); } public ErrorEnvelope(int code, @Nullable String message, @Nullable Throwable throwable) { this.code = code; this.message = message; this.throwable = throwable; } }
651
0.683564
0.683564
26
24.038462
23.187332
93
false
false
0
0
0
0
0
0
0.615385
false
false
6
381b73d63cf7d86e7f59daabfebd302727a94b38
2,602,750,215,706
6cc578677b67498a94d8e9902a555c2f2ea9c0d0
/src/main/java/com/yjg/service/serviceImpl/ChinaTypeServiceImpl.java
a5d1e68a64c16fbb63fdf59e9085191780eea6f7
[]
no_license
wenxuefeng3930/ChinaShoppingManagementSystem
https://github.com/wenxuefeng3930/ChinaShoppingManagementSystem
5274027b69670097e60b670da30c30935e232bff
d450c1a19da2165f88c2959d1682b918e55d2667
refs/heads/main
2023-06-26T04:45:03.550000
2021-07-18T04:26:38
2021-07-18T04:26:38
437,567,608
1
0
null
true
2021-12-12T14:28:00
2021-12-12T14:28:00
2021-12-12T14:27:58
2021-07-18T04:26:50
2,710
0
0
0
null
false
false
package com.yjg.service.serviceImpl; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.yjg.api.model.ChinaType; import com.yjg.api.model.ChinaTypeD; import com.yjg.api.service.ChinaTypeService; import com.yjg.service.mapper.ChinaTypeDMapper; import com.yjg.service.mapper.ChinaTypeMapper; import com.yjg.util.MyException; @Service public class ChinaTypeServiceImpl implements ChinaTypeService{ @Resource private ChinaTypeMapper chinaTypeMapper; @Resource private ChinaTypeDMapper chinaTypeDMapper; @Override public Map<String, Object> addChinaType(Map<String, Object> map) throws MyException{ // TODO Auto-generated method stub ChinaType chinaType =(ChinaType) map.get("ChinaType"); if(chinaType.getName()==null){ throw new MyException("类别名不能为空!"); } Map<String,Object> returnMap=new HashMap<String,Object>(); chinaTypeMapper.inserChinaType(chinaType); returnMap.put("RetCode", "1"); returnMap.put("RetMessage", "成功"); return returnMap; } @Override public Map<String, Object> addChinaTypeD(Map<String, Object> map) throws MyException{ // TODO Auto-generated method stub ChinaTypeD chinaTypeD =(ChinaTypeD) map.get("ChinaTypeD"); if(chinaTypeD.getTypeId()==null){ throw new MyException("主类别ID不能为空!"); } if(chinaTypeD.getName()==null){ throw new MyException("类别名不能为空!"); } Map<String,Object> returnMap=new HashMap<String,Object>(); chinaTypeDMapper.inserChinaTypeD(chinaTypeD); returnMap.put("RetCode", "1"); returnMap.put("RetMessage", "成功"); return returnMap; } @Override public Map<String, Object> updateChinaType(Map<String, Object> map) throws MyException{ // TODO Auto-generated method stub ChinaType chinaType =(ChinaType) map.get("ChinaType"); if(chinaType.getTypeId()==null){ throw new MyException("类别ID不能为空!"); } Map<String,Object> returnMap=new HashMap<String,Object>(); chinaTypeMapper.updateChinaType(chinaType); returnMap.put("RetCode", "1"); returnMap.put("RetMessage", "成功"); return returnMap; } @Override public Map<String, Object> updateChinaTypeD(Map<String, Object> map) throws MyException{ ChinaTypeD chinaTypeD =(ChinaTypeD) map.get("ChinaTypeD"); if(chinaTypeD.getTypeDid()==null){ throw new MyException("类别ID不能为空!"); } if(chinaTypeD.getTypeId()==null){ throw new MyException("主类别ID不能为空!"); } Map<String,Object> returnMap=new HashMap<String,Object>(); chinaTypeDMapper.updateChinaTypeD(chinaTypeD); returnMap.put("RetCode", "1"); returnMap.put("RetMessage", "成功"); return returnMap; } @Override public Map<String, Object> selectOneChinaType(Map<String, Object> map)throws MyException { if(map.get("ChinaType")==null){ throw new MyException("ChinaType不能为空!"); } ChinaType chinaType=(ChinaType) map.get("ChinaType"); if(chinaType.getTypeId()==null){ throw new MyException("typeId不能为空!"); } ChinaType chinaType2 = chinaTypeMapper.selectOneChinaType(chinaType); Map<String,Object> returnMap=new HashMap<String,Object>(); returnMap.put("RetData", chinaType2); returnMap.put("RetCode", "1"); returnMap.put("RetMessage", "成功"); return returnMap; } @Override public Map<String, Object> selectAllChinaType(Map<String, Object> map) throws MyException{ ChinaType chinaType=(ChinaType) map.get("ChinaType"); List<ChinaType> list = chinaTypeMapper.selectAllChinaType(chinaType); Map<String,Object> returnMap=new HashMap<String,Object>(); returnMap.put("RetData", list); returnMap.put("RetCode", "1"); returnMap.put("RetMessage", "成功"); return returnMap; } @Override public Map<String, Object> selectOneChinaTypeD(Map<String, Object> map) throws MyException{ if(map.get("ChinaTypeD")==null){ throw new MyException("ChinaTypeD不能为空!"); } ChinaTypeD chinaTypeD=(ChinaTypeD) map.get("ChinaTypeD"); if(chinaTypeD.getTypeDid()==null){ throw new MyException("typeDid不能为空!"); } ChinaTypeD chinaTypeD2 = chinaTypeDMapper.selectOneChinaTypeD(chinaTypeD); Map<String,Object> returnMap=new HashMap<String,Object>(); returnMap.put("RetData", chinaTypeD2); returnMap.put("RetCode", "1"); returnMap.put("RetMessage", "成功"); return returnMap; } @Override public Map<String, Object> selectAllChinaTypeD(Map<String, Object> map) throws MyException{ ChinaTypeD chinaTypeD=(ChinaTypeD) map.get("ChinaTypeD"); List<ChinaTypeD> list = chinaTypeDMapper.findAllChinaTypeD(chinaTypeD); Map<String,Object> returnMap=new HashMap<String,Object>(); returnMap.put("RetData", list); returnMap.put("RetCode", "1"); returnMap.put("RetMessage", "成功"); return returnMap; } @Override public Map<String, Object> selectChinaTypeDByName(ChinaTypeD chinaTypeD) { ChinaTypeD chinaTypeD2 = chinaTypeDMapper.selectChinaTypeDByName(chinaTypeD); Map<String,Object> returnMap=new HashMap<String,Object>(); returnMap.put("RetData", chinaTypeD2); returnMap.put("RetCode", "1"); returnMap.put("RetMessage", "成功"); return returnMap; } @Override public Map<String, Object> deletChinaType(Map<String, Object> map) { if(map.get("ChinaType")==null){ throw new MyException("ChinaType不能为空!"); } ChinaType chinaType=(ChinaType) map.get("ChinaType"); if(chinaType.getTypeId()==null){ throw new MyException("typeID不能为空!"); } chinaTypeDMapper.removeChinaTypeD(chinaType.getTypeId()); chinaTypeMapper.removeChinaType(chinaType); Map<String,Object> returnMap=new HashMap<String,Object>(); returnMap.put("RetCode", "1"); returnMap.put("RetMessage", "成功"); return returnMap; } @Override public Map<String, Object> deletChinaTypeD(Map<String, Object> map) { if(map.get("ChinaTypeD")==null){ throw new MyException("ChinaTypeD不能为空!"); } ChinaTypeD ChinaTypeD=(ChinaTypeD) map.get("ChinaTypeD"); if(ChinaTypeD.getTypeDid()==null){ throw new MyException("typeDiD不能为空!"); } chinaTypeDMapper.removeChinaTypeD2(ChinaTypeD); Map<String,Object> returnMap=new HashMap<String,Object>(); returnMap.put("RetCode", "1"); returnMap.put("RetMessage", "成功"); return returnMap; } }
GB18030
Java
6,338
java
ChinaTypeServiceImpl.java
Java
[]
null
[]
package com.yjg.service.serviceImpl; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.yjg.api.model.ChinaType; import com.yjg.api.model.ChinaTypeD; import com.yjg.api.service.ChinaTypeService; import com.yjg.service.mapper.ChinaTypeDMapper; import com.yjg.service.mapper.ChinaTypeMapper; import com.yjg.util.MyException; @Service public class ChinaTypeServiceImpl implements ChinaTypeService{ @Resource private ChinaTypeMapper chinaTypeMapper; @Resource private ChinaTypeDMapper chinaTypeDMapper; @Override public Map<String, Object> addChinaType(Map<String, Object> map) throws MyException{ // TODO Auto-generated method stub ChinaType chinaType =(ChinaType) map.get("ChinaType"); if(chinaType.getName()==null){ throw new MyException("类别名不能为空!"); } Map<String,Object> returnMap=new HashMap<String,Object>(); chinaTypeMapper.inserChinaType(chinaType); returnMap.put("RetCode", "1"); returnMap.put("RetMessage", "成功"); return returnMap; } @Override public Map<String, Object> addChinaTypeD(Map<String, Object> map) throws MyException{ // TODO Auto-generated method stub ChinaTypeD chinaTypeD =(ChinaTypeD) map.get("ChinaTypeD"); if(chinaTypeD.getTypeId()==null){ throw new MyException("主类别ID不能为空!"); } if(chinaTypeD.getName()==null){ throw new MyException("类别名不能为空!"); } Map<String,Object> returnMap=new HashMap<String,Object>(); chinaTypeDMapper.inserChinaTypeD(chinaTypeD); returnMap.put("RetCode", "1"); returnMap.put("RetMessage", "成功"); return returnMap; } @Override public Map<String, Object> updateChinaType(Map<String, Object> map) throws MyException{ // TODO Auto-generated method stub ChinaType chinaType =(ChinaType) map.get("ChinaType"); if(chinaType.getTypeId()==null){ throw new MyException("类别ID不能为空!"); } Map<String,Object> returnMap=new HashMap<String,Object>(); chinaTypeMapper.updateChinaType(chinaType); returnMap.put("RetCode", "1"); returnMap.put("RetMessage", "成功"); return returnMap; } @Override public Map<String, Object> updateChinaTypeD(Map<String, Object> map) throws MyException{ ChinaTypeD chinaTypeD =(ChinaTypeD) map.get("ChinaTypeD"); if(chinaTypeD.getTypeDid()==null){ throw new MyException("类别ID不能为空!"); } if(chinaTypeD.getTypeId()==null){ throw new MyException("主类别ID不能为空!"); } Map<String,Object> returnMap=new HashMap<String,Object>(); chinaTypeDMapper.updateChinaTypeD(chinaTypeD); returnMap.put("RetCode", "1"); returnMap.put("RetMessage", "成功"); return returnMap; } @Override public Map<String, Object> selectOneChinaType(Map<String, Object> map)throws MyException { if(map.get("ChinaType")==null){ throw new MyException("ChinaType不能为空!"); } ChinaType chinaType=(ChinaType) map.get("ChinaType"); if(chinaType.getTypeId()==null){ throw new MyException("typeId不能为空!"); } ChinaType chinaType2 = chinaTypeMapper.selectOneChinaType(chinaType); Map<String,Object> returnMap=new HashMap<String,Object>(); returnMap.put("RetData", chinaType2); returnMap.put("RetCode", "1"); returnMap.put("RetMessage", "成功"); return returnMap; } @Override public Map<String, Object> selectAllChinaType(Map<String, Object> map) throws MyException{ ChinaType chinaType=(ChinaType) map.get("ChinaType"); List<ChinaType> list = chinaTypeMapper.selectAllChinaType(chinaType); Map<String,Object> returnMap=new HashMap<String,Object>(); returnMap.put("RetData", list); returnMap.put("RetCode", "1"); returnMap.put("RetMessage", "成功"); return returnMap; } @Override public Map<String, Object> selectOneChinaTypeD(Map<String, Object> map) throws MyException{ if(map.get("ChinaTypeD")==null){ throw new MyException("ChinaTypeD不能为空!"); } ChinaTypeD chinaTypeD=(ChinaTypeD) map.get("ChinaTypeD"); if(chinaTypeD.getTypeDid()==null){ throw new MyException("typeDid不能为空!"); } ChinaTypeD chinaTypeD2 = chinaTypeDMapper.selectOneChinaTypeD(chinaTypeD); Map<String,Object> returnMap=new HashMap<String,Object>(); returnMap.put("RetData", chinaTypeD2); returnMap.put("RetCode", "1"); returnMap.put("RetMessage", "成功"); return returnMap; } @Override public Map<String, Object> selectAllChinaTypeD(Map<String, Object> map) throws MyException{ ChinaTypeD chinaTypeD=(ChinaTypeD) map.get("ChinaTypeD"); List<ChinaTypeD> list = chinaTypeDMapper.findAllChinaTypeD(chinaTypeD); Map<String,Object> returnMap=new HashMap<String,Object>(); returnMap.put("RetData", list); returnMap.put("RetCode", "1"); returnMap.put("RetMessage", "成功"); return returnMap; } @Override public Map<String, Object> selectChinaTypeDByName(ChinaTypeD chinaTypeD) { ChinaTypeD chinaTypeD2 = chinaTypeDMapper.selectChinaTypeDByName(chinaTypeD); Map<String,Object> returnMap=new HashMap<String,Object>(); returnMap.put("RetData", chinaTypeD2); returnMap.put("RetCode", "1"); returnMap.put("RetMessage", "成功"); return returnMap; } @Override public Map<String, Object> deletChinaType(Map<String, Object> map) { if(map.get("ChinaType")==null){ throw new MyException("ChinaType不能为空!"); } ChinaType chinaType=(ChinaType) map.get("ChinaType"); if(chinaType.getTypeId()==null){ throw new MyException("typeID不能为空!"); } chinaTypeDMapper.removeChinaTypeD(chinaType.getTypeId()); chinaTypeMapper.removeChinaType(chinaType); Map<String,Object> returnMap=new HashMap<String,Object>(); returnMap.put("RetCode", "1"); returnMap.put("RetMessage", "成功"); return returnMap; } @Override public Map<String, Object> deletChinaTypeD(Map<String, Object> map) { if(map.get("ChinaTypeD")==null){ throw new MyException("ChinaTypeD不能为空!"); } ChinaTypeD ChinaTypeD=(ChinaTypeD) map.get("ChinaTypeD"); if(ChinaTypeD.getTypeDid()==null){ throw new MyException("typeDiD不能为空!"); } chinaTypeDMapper.removeChinaTypeD2(ChinaTypeD); Map<String,Object> returnMap=new HashMap<String,Object>(); returnMap.put("RetCode", "1"); returnMap.put("RetMessage", "成功"); return returnMap; } }
6,338
0.737341
0.734401
186
31.913979
24.34901
92
false
false
0
0
0
0
0
0
2.44086
false
false
6
aaf07eca4d5784ba2d79ee6672ffeac50acb92db
33,234,456,991,175
8b34e0b8f1fbea71257a4480cbaa06da5add5204
/src/main/java/com/example/demo/service/YetAnotherService.java
d5ed4c0a2183c8700b994d69369369055cb849b1
[]
no_license
kamil-jasek/javapoz22-demo
https://github.com/kamil-jasek/javapoz22-demo
137fd95744da6a328344b3a079898597caa9774a
ce3ad96e304d12610dc2f9c021d46690f746319a
refs/heads/master
2023-01-23T16:01:21.773000
2020-11-29T13:51:13
2020-11-29T13:51:13
318,992,052
0
0
null
true
2020-12-06T09:05:29
2020-12-06T09:05:28
2020-11-29T13:51:20
2020-12-05T11:09:36
77
0
0
0
null
false
false
package com.example.demo.service; import org.springframework.stereotype.Service; @Service public class YetAnotherService { private MyService a; public YetAnotherService(MyService a) { this.a = a; } public void somthing(){ a.doSomething(); } }
UTF-8
Java
283
java
YetAnotherService.java
Java
[]
null
[]
package com.example.demo.service; import org.springframework.stereotype.Service; @Service public class YetAnotherService { private MyService a; public YetAnotherService(MyService a) { this.a = a; } public void somthing(){ a.doSomething(); } }
283
0.671378
0.671378
16
16.6875
15.770696
46
false
false
0
0
0
0
0
0
0.3125
false
false
6
2d3707457b1401319d2bd349e41cb7dcad48b17c
1,778,116,485,689
4a6631cab97ed4da835160aa0a34b93cbdc0fd70
/ypump-common/src/main/java/com/yanyue/ypump/common/persistence/Page.java
e6eebe32072af881751b9ce56c03ea5e5ea161fa
[]
no_license
xp8100/ypump
https://github.com/xp8100/ypump
8ed75ad1368d8f0fd5bec40778fc8be33e943301
e3522622145fc3fea47183ba8ce1713cd60f9b0c
refs/heads/master
2018-10-25T19:30:34.323000
2018-10-24T15:44:19
2018-10-24T15:44:19
142,390,526
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yanyue.ypump.common.persistence; import java.io.Serializable; /** * * @author xiaoping.zhang * */ public class Page implements Serializable { private static final long serialVersionUID = 3269886663478889866L; public int getCurrPage() { if (currPage < 1) { return 1; } else { return currPage; } } public int getPrevPage() { if (isFirstPage()) { return getCurrPage(); } else { return getCurrPage() - 1; } } public int getNextPage() { if (isLastPage()) { return getCurrPage(); } else { return getCurrPage() + 1; } } public int getPageSize() { if (pageSize < 0) { return 0; } else { return pageSize; } } public int getTotalPage() { if (getPageSize() == 0) return 0; totalPage = getTotalRow() / getPageSize(); if (getTotalRow() % getPageSize() != 0 || totalPage == 0) { return ++ totalPage; } else { return totalPage; } } public boolean isFirstPage() { return getCurrPage() <= 1; } public boolean isLastPage() { return getCurrPage() >= getTotalPage(); } public int getStartNo() { return (getCurrPage() - 1) * getPageSize() + 1; } public int getTotalRow() { if (totalRow < 0) { return 0; } else { return totalRow; } } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public void setCurrPage(int currPage) { this.currPage = currPage; } public void setTotalRow(int totalRow) { this.totalRow = totalRow; int tmpTotalPage = getTotalRow() / getPageSize(); int lastPage = 1; if (getTotalRow() % getPageSize() != 0 || tmpTotalPage == 0) { lastPage = ++ tmpTotalPage; } else { lastPage = tmpTotalPage; } if (lastPage < getCurrPage()) { setCurrPage(lastPage); } } private int pageSize = 10; // 每页多少行 private int currPage = 1; // 当前页 private int totalPage; // 共多少页 private int totalRow; // 共多少行 private int page = 1; // 用于与grid交互,表示第1页 private int rows = 10; // 用于与grid交互,表示每页10条记录 public void setPage(int page) { setCurrPage(page); } public void setRows(int rows) { setPageSize(rows); } }
UTF-8
Java
2,186
java
Page.java
Java
[ { "context": "\n\nimport java.io.Serializable;\n\n/**\n * \n * @author xiaoping.zhang\n *\n */\npublic class Page implements Serializable ", "end": 109, "score": 0.9975349307060242, "start": 95, "tag": "NAME", "value": "xiaoping.zhang" } ]
null
[]
package com.yanyue.ypump.common.persistence; import java.io.Serializable; /** * * @author xiaoping.zhang * */ public class Page implements Serializable { private static final long serialVersionUID = 3269886663478889866L; public int getCurrPage() { if (currPage < 1) { return 1; } else { return currPage; } } public int getPrevPage() { if (isFirstPage()) { return getCurrPage(); } else { return getCurrPage() - 1; } } public int getNextPage() { if (isLastPage()) { return getCurrPage(); } else { return getCurrPage() + 1; } } public int getPageSize() { if (pageSize < 0) { return 0; } else { return pageSize; } } public int getTotalPage() { if (getPageSize() == 0) return 0; totalPage = getTotalRow() / getPageSize(); if (getTotalRow() % getPageSize() != 0 || totalPage == 0) { return ++ totalPage; } else { return totalPage; } } public boolean isFirstPage() { return getCurrPage() <= 1; } public boolean isLastPage() { return getCurrPage() >= getTotalPage(); } public int getStartNo() { return (getCurrPage() - 1) * getPageSize() + 1; } public int getTotalRow() { if (totalRow < 0) { return 0; } else { return totalRow; } } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public void setCurrPage(int currPage) { this.currPage = currPage; } public void setTotalRow(int totalRow) { this.totalRow = totalRow; int tmpTotalPage = getTotalRow() / getPageSize(); int lastPage = 1; if (getTotalRow() % getPageSize() != 0 || tmpTotalPage == 0) { lastPage = ++ tmpTotalPage; } else { lastPage = tmpTotalPage; } if (lastPage < getCurrPage()) { setCurrPage(lastPage); } } private int pageSize = 10; // 每页多少行 private int currPage = 1; // 当前页 private int totalPage; // 共多少页 private int totalRow; // 共多少行 private int page = 1; // 用于与grid交互,表示第1页 private int rows = 10; // 用于与grid交互,表示每页10条记录 public void setPage(int page) { setCurrPage(page); } public void setRows(int rows) { setPageSize(rows); } }
2,186
0.631879
0.610057
114
17.491228
16.567377
67
false
false
0
0
0
0
0
0
1.842105
false
false
6
05fbf2b6f897b62de11762defe0dba3edd6a01c8
33,466,385,233,003
d82779b19dd654b4df93a3392cf8f1af18e1027b
/Nodemac/src/nodemac/ResponderClass.java
52bcd787a11a63d74005f486cc1bdba7cfb1953f
[]
no_license
GJarzebakPrivate/LB2
https://github.com/GJarzebakPrivate/LB2
fa2dae8b755874b59b372284ff1d7a97ebf13df5
9ff3034709a6120c256be6a8723883fe0ba95011
refs/heads/main
2023-05-05T17:55:41.168000
2021-05-31T20:46:05
2021-05-31T20:46:05
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package nodemac; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Gerard */ public class ResponderClass implements Runnable { int messageCapacity; String messageContent; String host; DatagramSocket socket; public ResponderClass(String stringFromPacket, String host, int nodeportArg) { String[] messageParts = stringFromPacket.split(","); this.messageContent = messageParts[0]; this.messageCapacity = Integer.parseInt(messageParts[1]); this.host = host; try { this.socket = new DatagramSocket(nodeportArg); } catch (SocketException ex) { Logger.getLogger(ResponderClass.class.getName()).log(Level.SEVERE, null, ex); } ; } @Override public void run() { try { for (int i = 0; i < this.messageCapacity; i++) { System.out.println("Currently working on the message : " + this.messageContent); //TimeUnit.SECONDS.sleep(1); Thread.sleep(1000); } InetAddress addr = InetAddress.getByName(this.host); //String message = "REGISTER,node2,102.772.1.20,8000"; DatagramPacket packet1 = new DatagramPacket(this.messageContent.getBytes(), this.messageContent.getBytes().length, addr, 5000); //DatagramPacket packet = new DatagramPacket(message.getBytes(), message.getBytes().length, addr, 5000); //DatagramSocket socket = new DatagramSocket(4000); this.socket.send(packet1); socket.close(); } catch (Exception error) { System.out.print("error"); } } }
UTF-8
Java
2,052
java
ResponderClass.java
Java
[ { "context": "mport java.util.logging.Logger;\n\n/**\n *\n * @author Gerard\n */\npublic class ResponderClass implements Runnab", "end": 457, "score": 0.9996840953826904, "start": 451, "tag": "NAME", "value": "Gerard" }, { "context": ");\n //String message = \"REGISTER,nod...
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package nodemac; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Gerard */ public class ResponderClass implements Runnable { int messageCapacity; String messageContent; String host; DatagramSocket socket; public ResponderClass(String stringFromPacket, String host, int nodeportArg) { String[] messageParts = stringFromPacket.split(","); this.messageContent = messageParts[0]; this.messageCapacity = Integer.parseInt(messageParts[1]); this.host = host; try { this.socket = new DatagramSocket(nodeportArg); } catch (SocketException ex) { Logger.getLogger(ResponderClass.class.getName()).log(Level.SEVERE, null, ex); } ; } @Override public void run() { try { for (int i = 0; i < this.messageCapacity; i++) { System.out.println("Currently working on the message : " + this.messageContent); //TimeUnit.SECONDS.sleep(1); Thread.sleep(1000); } InetAddress addr = InetAddress.getByName(this.host); //String message = "REGISTER,node2,102.772.1.20,8000"; DatagramPacket packet1 = new DatagramPacket(this.messageContent.getBytes(), this.messageContent.getBytes().length, addr, 5000); //DatagramPacket packet = new DatagramPacket(message.getBytes(), message.getBytes().length, addr, 5000); //DatagramSocket socket = new DatagramSocket(4000); this.socket.send(packet1); socket.close(); } catch (Exception error) { System.out.print("error"); } } }
2,052
0.639864
0.62232
64
31.0625
30.622641
139
false
false
0
0
0
0
0
0
0.765625
false
false
6
3f36f52df4b4834284bb213738804cef627da68b
22,625,887,764,581
452a524e2faf3dd6cd356fe97c602d09d2ec35ca
/src/test/java/com/main/Page04.java
02fde910f05bb251f17ad2c7262450a1c41f4096
[]
no_license
svene/JPATips
https://github.com/svene/JPATips
913a8ac09e44e7ec0c78dd837b7a03f856951f93
cf51f796d16b3105b95e08c0439a22988f037284
refs/heads/master
2021-01-18T18:25:03.806000
2014-05-31T10:00:40
2014-05-31T10:00:40
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.main; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; import javax.persistence.EntityManager; import javax.persistence.Query; import com.model.Dog; import com.model.Person; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class Page04 { private EntityManager em; @Before public void setUp() throws Exception { CodeGenerator.startConnection(); CodeGenerator.generateData(); em = CodeGenerator.getEntityManager(); } @After public void tearDown() throws Exception { CodeGenerator.rollback(); } @Test public void all_dogs() throws Exception { List<Dog> dogs = listAllDogs(em); List<String> dogNames = dogs.stream().map(Dog::getName).collect(Collectors.toList()); List<String> expectedDogNames = CodeGenerator.ALL_DOGS.stream().map(Dog::getName).collect(Collectors.toList()); assertThat(dogNames).containsAll(expectedDogNames); } @Test public void person_by_name() throws Exception { Person person03 = findPersonByName(em, CodeGenerator.PERSON03_NAME); assertThat(person03.getName()).isEqualTo(CodeGenerator.PERSON03_NAME); } @Test public void person_by_person_object() throws Exception { Person person01 = new Person(); person01.setId(1); Person savedPerson = findPersonByPersonObject(em, person01); assertThat(savedPerson.getName()).isEqualTo(CodeGenerator.PERSON01_NAME); } @Test public void all_dogs_ordered_by_weight() throws Exception { List<Dog> dogs = listAllDogsOrderingByWeight(em); List<String> dogNames = dogs.stream().map(Dog::getName).collect(Collectors.toList()); List<String> expectedDogNames = dogs.stream().sorted(Comparator.comparingDouble(Dog::getWeight).reversed()).map(Dog::getName).collect(Collectors.toList()); assertThat(dogNames).isEqualTo(expectedDogNames); } @Test public void findAddressNameOfPerson() throws Exception { String addressName = findAddressNameOfPerson(em, CodeGenerator.PERSON04_NAME); assertThat(addressName).isEqualTo("Street C"); } @Test public void findPersonByNameWithAllDogs() throws Exception { Person person02 = findPersonByNameWithAllDogs(em, CodeGenerator.PERSON02_NAME); List<String> dogNames = person02.getDogs().stream().map(Dog::getName).collect(Collectors.toList()); List<String> expectedDogNames = CodeGenerator.ALL_DOGS.subList(3, 6).stream().map(Dog::getName).collect(Collectors.toList()); assertThat(person02.getName()).isEqualTo(CodeGenerator.PERSON02_NAME); assertThat(dogNames).isEqualTo(expectedDogNames); } @Test public void findPersonByNameThatMayNotHaveDogs() throws Exception { Person person06 = findPersonByNameThatMayNotHaveDogs(em, CodeGenerator.PERSON06_NAME); List<String> dogNames = person06.getDogs().stream().map(Dog::getName).collect(Collectors.toList()); assertThat(person06.getName()).isEqualTo(CodeGenerator.PERSON06_NAME); assertThat(dogNames).isEqualTo(Collections.emptyList()); } /** * Easiest way to do a query */ @SuppressWarnings("unchecked") private static List<Dog> listAllDogs(EntityManager em) { Query query = em.createQuery("select d from Dog d", Dog.class); return query.getResultList(); } /** * Easiest way to do a query with parameters */ private static Person findPersonByName(EntityManager em, String name) { Query query = em.createQuery("select p from Person p where name = :name", Person.class); query.setParameter("name", name); return (Person) query.getSingleResult(); } /** * Executes a query that has as parameter an object */ private static Person findPersonByPersonObject(EntityManager em, Person person) { Query query = em.createQuery("select p from Person p where p = :person"); query.setParameter("person", person); return (Person) query.getSingleResult(); } /** * Query that will list all dogs with an order */ @SuppressWarnings("unchecked") private static List<Dog> listAllDogsOrderingByWeight(EntityManager em) { Query query = em.createQuery("select d from Dog d order by d.weight desc", Dog.class); return query.getResultList(); } /** * Query that get only a field instead a complete class object */ private static String findAddressNameOfPerson(EntityManager em, String name) { Query query = em.createQuery("select p.address.streetName from Person p where p.name = :name"); query.setParameter("name", name); return (String) query.getSingleResult(); } /** * Query that will fetch a lazy relationship Be carefull, with this kind of * query only those who have the relationship will come in the result */ private static Person findPersonByNameWithAllDogs(EntityManager em, String name) { Query query = em.createQuery("select p from Person p join fetch p.dogs where p.name = :name", Person.class); query.setParameter("name", name); return (Person) query.getSingleResult(); } /** * With this query will will bring results that may not have arelationship */ private static Person findPersonByNameThatMayNotHaveDogs(EntityManager em, String name) { Query query = em.createQuery("select p from Person p left join fetch p.dogs where p.name = :name", Person.class); query.setParameter("name", name); return (Person) query.getSingleResult(); } }
UTF-8
Java
5,317
java
Page04.java
Java
[ { "context": "name\", Person.class);\n\t\tquery.setParameter(\"name\", name);\n\t\treturn (Person) query.getSingleResult();\n\t}\n\n", "end": 3521, "score": 0.9355450868606567, "start": 3517, "tag": "NAME", "value": "name" } ]
null
[]
package com.main; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; import javax.persistence.EntityManager; import javax.persistence.Query; import com.model.Dog; import com.model.Person; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class Page04 { private EntityManager em; @Before public void setUp() throws Exception { CodeGenerator.startConnection(); CodeGenerator.generateData(); em = CodeGenerator.getEntityManager(); } @After public void tearDown() throws Exception { CodeGenerator.rollback(); } @Test public void all_dogs() throws Exception { List<Dog> dogs = listAllDogs(em); List<String> dogNames = dogs.stream().map(Dog::getName).collect(Collectors.toList()); List<String> expectedDogNames = CodeGenerator.ALL_DOGS.stream().map(Dog::getName).collect(Collectors.toList()); assertThat(dogNames).containsAll(expectedDogNames); } @Test public void person_by_name() throws Exception { Person person03 = findPersonByName(em, CodeGenerator.PERSON03_NAME); assertThat(person03.getName()).isEqualTo(CodeGenerator.PERSON03_NAME); } @Test public void person_by_person_object() throws Exception { Person person01 = new Person(); person01.setId(1); Person savedPerson = findPersonByPersonObject(em, person01); assertThat(savedPerson.getName()).isEqualTo(CodeGenerator.PERSON01_NAME); } @Test public void all_dogs_ordered_by_weight() throws Exception { List<Dog> dogs = listAllDogsOrderingByWeight(em); List<String> dogNames = dogs.stream().map(Dog::getName).collect(Collectors.toList()); List<String> expectedDogNames = dogs.stream().sorted(Comparator.comparingDouble(Dog::getWeight).reversed()).map(Dog::getName).collect(Collectors.toList()); assertThat(dogNames).isEqualTo(expectedDogNames); } @Test public void findAddressNameOfPerson() throws Exception { String addressName = findAddressNameOfPerson(em, CodeGenerator.PERSON04_NAME); assertThat(addressName).isEqualTo("Street C"); } @Test public void findPersonByNameWithAllDogs() throws Exception { Person person02 = findPersonByNameWithAllDogs(em, CodeGenerator.PERSON02_NAME); List<String> dogNames = person02.getDogs().stream().map(Dog::getName).collect(Collectors.toList()); List<String> expectedDogNames = CodeGenerator.ALL_DOGS.subList(3, 6).stream().map(Dog::getName).collect(Collectors.toList()); assertThat(person02.getName()).isEqualTo(CodeGenerator.PERSON02_NAME); assertThat(dogNames).isEqualTo(expectedDogNames); } @Test public void findPersonByNameThatMayNotHaveDogs() throws Exception { Person person06 = findPersonByNameThatMayNotHaveDogs(em, CodeGenerator.PERSON06_NAME); List<String> dogNames = person06.getDogs().stream().map(Dog::getName).collect(Collectors.toList()); assertThat(person06.getName()).isEqualTo(CodeGenerator.PERSON06_NAME); assertThat(dogNames).isEqualTo(Collections.emptyList()); } /** * Easiest way to do a query */ @SuppressWarnings("unchecked") private static List<Dog> listAllDogs(EntityManager em) { Query query = em.createQuery("select d from Dog d", Dog.class); return query.getResultList(); } /** * Easiest way to do a query with parameters */ private static Person findPersonByName(EntityManager em, String name) { Query query = em.createQuery("select p from Person p where name = :name", Person.class); query.setParameter("name", name); return (Person) query.getSingleResult(); } /** * Executes a query that has as parameter an object */ private static Person findPersonByPersonObject(EntityManager em, Person person) { Query query = em.createQuery("select p from Person p where p = :person"); query.setParameter("person", person); return (Person) query.getSingleResult(); } /** * Query that will list all dogs with an order */ @SuppressWarnings("unchecked") private static List<Dog> listAllDogsOrderingByWeight(EntityManager em) { Query query = em.createQuery("select d from Dog d order by d.weight desc", Dog.class); return query.getResultList(); } /** * Query that get only a field instead a complete class object */ private static String findAddressNameOfPerson(EntityManager em, String name) { Query query = em.createQuery("select p.address.streetName from Person p where p.name = :name"); query.setParameter("name", name); return (String) query.getSingleResult(); } /** * Query that will fetch a lazy relationship Be carefull, with this kind of * query only those who have the relationship will come in the result */ private static Person findPersonByNameWithAllDogs(EntityManager em, String name) { Query query = em.createQuery("select p from Person p join fetch p.dogs where p.name = :name", Person.class); query.setParameter("name", name); return (Person) query.getSingleResult(); } /** * With this query will will bring results that may not have arelationship */ private static Person findPersonByNameThatMayNotHaveDogs(EntityManager em, String name) { Query query = em.createQuery("select p from Person p left join fetch p.dogs where p.name = :name", Person.class); query.setParameter("name", name); return (Person) query.getSingleResult(); } }
5,317
0.751928
0.743841
156
33.089745
34.07653
157
false
false
0
0
0
0
0
0
1.576923
false
false
6
45df5a4fc8eed8d3b7556434625dd8bc37c2af3c
3,006,477,172,078
3b5fcdbbd927a89961d157100e3a034c60f4455b
/src/application/GameMain.java
d1661eb96dc7254965164352646c1e6be8bdeaa0
[]
no_license
Zariem/BumpMeDumpy
https://github.com/Zariem/BumpMeDumpy
16c72ed5770ec8860b448de22dc59e0946d01dbb
d4fc6621cba5007c03386ed3677288816479284c
refs/heads/master
2021-01-20T17:20:48.063000
2016-07-05T08:08:05
2016-07-05T08:08:05
62,343,612
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package application; import javax.swing.JFrame; public class GameMain { public static void main(String[] args) { // starte das Spiel! int windowHeight = 400; int windowWidth = 600; Menu mainMenu = new Menu(windowWidth,windowHeight); mainMenu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainMenu.setSize(windowWidth,windowHeight); mainMenu.setLayout(null); mainMenu.setVisible(true); mainMenu.setResizable(false); } }
UTF-8
Java
445
java
GameMain.java
Java
[]
null
[]
package application; import javax.swing.JFrame; public class GameMain { public static void main(String[] args) { // starte das Spiel! int windowHeight = 400; int windowWidth = 600; Menu mainMenu = new Menu(windowWidth,windowHeight); mainMenu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainMenu.setSize(windowWidth,windowHeight); mainMenu.setLayout(null); mainMenu.setVisible(true); mainMenu.setResizable(false); } }
445
0.752809
0.739326
19
22.421053
17.912994
58
false
false
0
0
0
0
0
0
1.684211
false
false
6
babbbe3ccd3ec1e9b7ad9a946c59db4e1cab4d33
29,171,417,924,403
fce7ea1503c7d22f4ab26bc0bd4dfe7e9c4e8ce6
/app/src/main/java/com/cdkj/myxb/module/appointment/AppointmentCommentActivity.java
dadc6c385d3ef18d09472627db1f9430cf4b347e
[]
no_license
ibisTime/xn-myxb-android
https://github.com/ibisTime/xn-myxb-android
3675e723ff9abc9f1888ba5ed1ab2b763b64f09a
89eb4fdb19befe241c123a938782dea1e7fdbe0c
refs/heads/master
2021-05-03T18:26:49.360000
2018-06-13T04:00:12
2018-06-13T04:00:12
120,411,529
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cdkj.myxb.module.appointment; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.widget.LinearLayoutManager; import android.text.TextUtils; import android.view.View; import com.cdkj.baselibrary.api.BaseApiServer; import com.cdkj.baselibrary.appmanager.SPUtilHelpr; import com.cdkj.baselibrary.base.AbsBaseLoadActivity; import com.cdkj.baselibrary.dialog.UITipDialog; import com.cdkj.baselibrary.model.CodeModel; import com.cdkj.baselibrary.nets.BaseResponseListCallBack; import com.cdkj.baselibrary.nets.BaseResponseModelCallBack; import com.cdkj.baselibrary.nets.RetrofitUtils; import com.cdkj.baselibrary.utils.StringUtils; import com.cdkj.myxb.R; import com.cdkj.myxb.adapters.CommentItemAdapter; import com.cdkj.myxb.databinding.ActivityCommentsEditBinding; import com.cdkj.myxb.models.AppointmentCommentsSucc; import com.cdkj.myxb.models.CommentItemModel; import com.cdkj.myxb.models.CommentRequest; import com.cdkj.myxb.models.IntegralOrderCommentsSucc; import com.cdkj.myxb.module.api.MyApiServer; import org.greenrobot.eventbus.EventBus; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import retrofit2.Call; /** * 预约评价 * Created by cdkj on 2018/2/23. */ public class AppointmentCommentActivity extends AbsBaseLoadActivity { private ActivityCommentsEditBinding mBinding; private String mOrderCode; private CommentItemAdapter commentItemAdapter; private String mType; //用户类型 private String owner; private final static String TYPE = "state"; private final static String OWNER = "owner"; private final static String ORDERCODE = "ordercode"; /** * @param context * @param orderCode 订单编号 */ public static void open(Context context, String orderCode, String type, String owner) { if (context == null) { return; } Intent intent = new Intent(context, AppointmentCommentActivity.class); intent.putExtra(ORDERCODE, orderCode); intent.putExtra(TYPE, type); intent.putExtra(OWNER, owner); context.startActivity(intent); } @Override public View addMainView() { mBinding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.activity_comments_edit, null, false); return mBinding.getRoot(); } @Override public void topTitleViewRightClick() { if (!checkInputInfoIsEmpty()) { return; } releaseRequest(); } private boolean checkInputInfoIsEmpty() { for (int i = 0; i < commentItemAdapter.getData().size(); i++) { CommentItemModel commentItemModel = commentItemAdapter.getItem(i); if (commentItemModel == null) continue; if (TextUtils.equals("0", commentItemModel.getcScore())) { UITipDialog.showInfo(this, "请对" + commentItemModel.getCvalue() + "进行评分"); return false; } } if (TextUtils.isEmpty(mBinding.editInfo.getText().toString())) { UITipDialog.showInfo(this, "请输入内容"); return false; } return true; } @Override public void afterCreate(Bundle savedInstanceState) { mBaseBinding.titleView.setMidTitle("提交评价"); mBaseBinding.titleView.setRightTitle("发布"); if (getIntent() != null) { mOrderCode = getIntent().getStringExtra(ORDERCODE); owner = getIntent().getStringExtra(OWNER); mType = getIntent().getStringExtra(TYPE); } initRecyclerView(); getCommentItem(); } private void initRecyclerView() { LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false) { @Override public boolean canScrollVertically() { return false; } }; mBinding.recyclerViewComments.setLayoutManager(linearLayoutManager); mBinding.recyclerViewComments.setVisibility(View.VISIBLE); } /** * 发布评价 */ public void releaseRequest() { if (TextUtils.isEmpty(mOrderCode) || TextUtils.isEmpty(mType)) { return; } Map<String, Object> map = new HashMap<>(); map.put("commenter", SPUtilHelpr.getUserId()); map.put("content", mBinding.editInfo.getText().toString()); map.put("orderCode", mOrderCode); map.put("entityCode", owner); map.put("type", mType);/*Lecturer("L", "讲师"), Specialist("S", "专家"), Tutor("T", "服务团队"), PRODUCT("P", "产品"), IP:积分商品*/ map.put("req", getCommentRequests()); Call call = RetrofitUtils.createApi(BaseApiServer.class).codeRequest("805420", StringUtils.getJsonToString(map)); addCall(call); showLoadingDialog(); call.enqueue(new BaseResponseModelCallBack<CodeModel>(this) { @Override protected void onSuccess(CodeModel data, String SucMessage) { checkReleaseState(data); } @Override protected void onFinish() { disMissLoading(); } }); } /** * 获取评价项进行请求 * * @return */ @NonNull private List<CommentRequest> getCommentRequests() { List<CommentRequest> req = new ArrayList<>(); for (int i = 0; i < commentItemAdapter.getData().size(); i++) { CommentItemModel commentItemModel = commentItemAdapter.getItem(i); if (commentItemModel == null) continue; CommentRequest commentRequest = new CommentRequest(); commentRequest.setScore(commentItemModel.getcScore()); commentRequest.setCkey(commentItemModel.getCkey()); req.add(commentRequest); } return req; } /** * 获取要评分的项 */ public void getCommentItem() { Map map = RetrofitUtils.getRequestMap(); map.put("type", "ISR");//type=ISW物品 ISR人 Call call = RetrofitUtils.createApi(MyApiServer.class).getCommentItem("805914", StringUtils.getJsonToString(map)); addCall(call); showLoadingDialog(); call.enqueue(new BaseResponseListCallBack<CommentItemModel>(this) { @Override protected void onSuccess(List<CommentItemModel> data, String SucMessage) { commentItemAdapter = new CommentItemAdapter(data); mBinding.recyclerViewComments.setAdapter(commentItemAdapter); } @Override protected void onFinish() { disMissLoading(); } }); } /** * 监测发布状态 * * @param data */ private void checkReleaseState(CodeModel data) { String s = "filter";//是否包含敏感词汇 if (!TextUtils.isEmpty(data.getCode()) && !StringUtils.contains(data.getCode(), s)) { EventBus.getDefault().post(new AppointmentCommentsSucc()); UITipDialog.showSuccess(AppointmentCommentActivity.this, "发布评价成功", new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialogInterface) { finish(); } }); } else if (StringUtils.contains(data.getCode(), s)) { EventBus.getDefault().post(new IntegralOrderCommentsSucc()); UITipDialog.showSuccess(AppointmentCommentActivity.this, "评价成功, 您的评价包含敏感字符,我们将进行审核", new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialogInterface) { finish(); } }); } else { showToast("发布失败"); finish(); } } }
UTF-8
Java
8,192
java
AppointmentCommentActivity.java
Java
[ { "context": "\nimport retrofit2.Call;\n\n/**\n * 预约评价\n * Created by cdkj on 2018/2/23.\n */\n\npublic class AppointmentCommen", "end": 1407, "score": 0.9996355175971985, "start": 1403, "tag": "USERNAME", "value": "cdkj" }, { "context": "\"state\";\n private final static String O...
null
[]
package com.cdkj.myxb.module.appointment; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.widget.LinearLayoutManager; import android.text.TextUtils; import android.view.View; import com.cdkj.baselibrary.api.BaseApiServer; import com.cdkj.baselibrary.appmanager.SPUtilHelpr; import com.cdkj.baselibrary.base.AbsBaseLoadActivity; import com.cdkj.baselibrary.dialog.UITipDialog; import com.cdkj.baselibrary.model.CodeModel; import com.cdkj.baselibrary.nets.BaseResponseListCallBack; import com.cdkj.baselibrary.nets.BaseResponseModelCallBack; import com.cdkj.baselibrary.nets.RetrofitUtils; import com.cdkj.baselibrary.utils.StringUtils; import com.cdkj.myxb.R; import com.cdkj.myxb.adapters.CommentItemAdapter; import com.cdkj.myxb.databinding.ActivityCommentsEditBinding; import com.cdkj.myxb.models.AppointmentCommentsSucc; import com.cdkj.myxb.models.CommentItemModel; import com.cdkj.myxb.models.CommentRequest; import com.cdkj.myxb.models.IntegralOrderCommentsSucc; import com.cdkj.myxb.module.api.MyApiServer; import org.greenrobot.eventbus.EventBus; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import retrofit2.Call; /** * 预约评价 * Created by cdkj on 2018/2/23. */ public class AppointmentCommentActivity extends AbsBaseLoadActivity { private ActivityCommentsEditBinding mBinding; private String mOrderCode; private CommentItemAdapter commentItemAdapter; private String mType; //用户类型 private String owner; private final static String TYPE = "state"; private final static String OWNER = "owner"; private final static String ORDERCODE = "ordercode"; /** * @param context * @param orderCode 订单编号 */ public static void open(Context context, String orderCode, String type, String owner) { if (context == null) { return; } Intent intent = new Intent(context, AppointmentCommentActivity.class); intent.putExtra(ORDERCODE, orderCode); intent.putExtra(TYPE, type); intent.putExtra(OWNER, owner); context.startActivity(intent); } @Override public View addMainView() { mBinding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.activity_comments_edit, null, false); return mBinding.getRoot(); } @Override public void topTitleViewRightClick() { if (!checkInputInfoIsEmpty()) { return; } releaseRequest(); } private boolean checkInputInfoIsEmpty() { for (int i = 0; i < commentItemAdapter.getData().size(); i++) { CommentItemModel commentItemModel = commentItemAdapter.getItem(i); if (commentItemModel == null) continue; if (TextUtils.equals("0", commentItemModel.getcScore())) { UITipDialog.showInfo(this, "请对" + commentItemModel.getCvalue() + "进行评分"); return false; } } if (TextUtils.isEmpty(mBinding.editInfo.getText().toString())) { UITipDialog.showInfo(this, "请输入内容"); return false; } return true; } @Override public void afterCreate(Bundle savedInstanceState) { mBaseBinding.titleView.setMidTitle("提交评价"); mBaseBinding.titleView.setRightTitle("发布"); if (getIntent() != null) { mOrderCode = getIntent().getStringExtra(ORDERCODE); owner = getIntent().getStringExtra(OWNER); mType = getIntent().getStringExtra(TYPE); } initRecyclerView(); getCommentItem(); } private void initRecyclerView() { LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false) { @Override public boolean canScrollVertically() { return false; } }; mBinding.recyclerViewComments.setLayoutManager(linearLayoutManager); mBinding.recyclerViewComments.setVisibility(View.VISIBLE); } /** * 发布评价 */ public void releaseRequest() { if (TextUtils.isEmpty(mOrderCode) || TextUtils.isEmpty(mType)) { return; } Map<String, Object> map = new HashMap<>(); map.put("commenter", SPUtilHelpr.getUserId()); map.put("content", mBinding.editInfo.getText().toString()); map.put("orderCode", mOrderCode); map.put("entityCode", owner); map.put("type", mType);/*Lecturer("L", "讲师"), Specialist("S", "专家"), Tutor("T", "服务团队"), PRODUCT("P", "产品"), IP:积分商品*/ map.put("req", getCommentRequests()); Call call = RetrofitUtils.createApi(BaseApiServer.class).codeRequest("805420", StringUtils.getJsonToString(map)); addCall(call); showLoadingDialog(); call.enqueue(new BaseResponseModelCallBack<CodeModel>(this) { @Override protected void onSuccess(CodeModel data, String SucMessage) { checkReleaseState(data); } @Override protected void onFinish() { disMissLoading(); } }); } /** * 获取评价项进行请求 * * @return */ @NonNull private List<CommentRequest> getCommentRequests() { List<CommentRequest> req = new ArrayList<>(); for (int i = 0; i < commentItemAdapter.getData().size(); i++) { CommentItemModel commentItemModel = commentItemAdapter.getItem(i); if (commentItemModel == null) continue; CommentRequest commentRequest = new CommentRequest(); commentRequest.setScore(commentItemModel.getcScore()); commentRequest.setCkey(commentItemModel.getCkey()); req.add(commentRequest); } return req; } /** * 获取要评分的项 */ public void getCommentItem() { Map map = RetrofitUtils.getRequestMap(); map.put("type", "ISR");//type=ISW物品 ISR人 Call call = RetrofitUtils.createApi(MyApiServer.class).getCommentItem("805914", StringUtils.getJsonToString(map)); addCall(call); showLoadingDialog(); call.enqueue(new BaseResponseListCallBack<CommentItemModel>(this) { @Override protected void onSuccess(List<CommentItemModel> data, String SucMessage) { commentItemAdapter = new CommentItemAdapter(data); mBinding.recyclerViewComments.setAdapter(commentItemAdapter); } @Override protected void onFinish() { disMissLoading(); } }); } /** * 监测发布状态 * * @param data */ private void checkReleaseState(CodeModel data) { String s = "filter";//是否包含敏感词汇 if (!TextUtils.isEmpty(data.getCode()) && !StringUtils.contains(data.getCode(), s)) { EventBus.getDefault().post(new AppointmentCommentsSucc()); UITipDialog.showSuccess(AppointmentCommentActivity.this, "发布评价成功", new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialogInterface) { finish(); } }); } else if (StringUtils.contains(data.getCode(), s)) { EventBus.getDefault().post(new IntegralOrderCommentsSucc()); UITipDialog.showSuccess(AppointmentCommentActivity.this, "评价成功, 您的评价包含敏感字符,我们将进行审核", new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialogInterface) { finish(); } }); } else { showToast("发布失败"); finish(); } } }
8,192
0.635542
0.63253
275
27.974545
28.66349
138
false
false
0
0
0
0
0
0
0.574545
false
false
6
8464f6ca2129611621b1b1a9137364ecb75b40aa
27,041,114,097,037
00c07582802a015e11eb31224f9aecc48e5f0f71
/app/src/main/java/com/qinshou/qinshoubox/me/bean/floor/Floor12.java
e6fed262171a3c3167c7793acdb1e5b13594274b
[]
no_license
mrqinshou/QinshouBox
https://github.com/mrqinshou/QinshouBox
6e01abaf9799e6949917b8802ccbb83ae9f3c5d3
ef7a3e5f38ce99dc1795f1147ab7341e98d34e31
refs/heads/master
2021-07-19T06:29:55.735000
2020-05-22T11:46:13
2020-05-22T11:46:13
163,412,746
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.qinshou.qinshoubox.me.bean.floor; import com.qinshou.qinshoubox.me.bean.CaseBean; import com.qinshou.qinshoubox.me.bean.Position; import com.qinshou.qinshoubox.me.bean.building.Road; import com.qinshou.qinshoubox.me.bean.building.Wall; import com.qinshou.qinshoubox.me.bean.monster.GaoJiWeiBing; import com.qinshou.qinshoubox.me.bean.monster.JinDuiZhang; import com.qinshou.qinshoubox.me.bean.monster.JinWeiShi; import com.qinshou.qinshoubox.me.bean.monster.LingFaShi; import com.qinshou.qinshoubox.me.bean.monster.LingWuShi; import com.qinshou.qinshoubox.me.bean.monster.MingWeiBing; import com.qinshou.qinshoubox.me.bean.monster.MingZhanShi; import com.qinshou.qinshoubox.me.bean.monster.ShuangShouJianShi; import com.qinshou.qinshoubox.me.bean.npc.BlueGate; import com.qinshou.qinshoubox.me.bean.npc.BusinessManFloor12; import com.qinshou.qinshoubox.me.bean.npc.GoDownstairs; import com.qinshou.qinshoubox.me.bean.npc.GoUpstairs; import com.qinshou.qinshoubox.me.bean.npc.YellowGate; import com.qinshou.qinshoubox.me.bean.prop.BigBloodBottle; import com.qinshou.qinshoubox.me.bean.prop.BlueGem; import com.qinshou.qinshoubox.me.bean.prop.RedGem; import com.qinshou.qinshoubox.me.bean.prop.SmallBloodBottle; import com.qinshou.qinshoubox.me.bean.prop.StarLightGodHammer; import com.qinshou.qinshoubox.me.bean.prop.YellowKey; import com.qinshou.qinshoubox.me.bean.warrior.WarriorBean; import com.qinshou.qinshoubox.util.MagicGameManager; import java.util.ArrayList; import java.util.List; /** * Description:第 12 层 * Created by 禽兽先生 * Created on 2017/4/27 */ public class Floor12 extends AbsFloor { @Override public int getFloor() { return 12; } @Override public List<List<CaseBean>> setData() { List<List<CaseBean>> floor12 = new ArrayList<>(); List<CaseBean> row0 = new ArrayList<>(); row0.add(new BusinessManFloor12()); row0.add(new BlueGem()); row0.add(new Wall()); row0.add(new Road()); row0.add(new JinWeiShi()); row0.add(new JinDuiZhang()); row0.add(new JinWeiShi()); row0.add(new Road()); row0.add(new Wall()); row0.add(new BigBloodBottle()); row0.add(new StarLightGodHammer()); floor12.add(row0); List<CaseBean> row1 = new ArrayList<>(); row1.add(new RedGem()); row1.add(new Road()); row1.add(new Wall()); row1.add(new Road()); row1.add(new Wall()); row1.add(new YellowGate()); row1.add(new Wall()); row1.add(new Road()); row1.add(new Wall()); row1.add(new Road()); row1.add(new BigBloodBottle()); floor12.add(row1); List<CaseBean> row2 = new ArrayList<>(); row2.add(new Road()); row2.add(new Road()); row2.add(new Wall()); row2.add(new Road()); row2.add(new Wall()); row2.add(new JinDuiZhang()); row2.add(new Wall()); row2.add(new Road()); row2.add(new Wall()); row2.add(new Road()); row2.add(new Road()); floor12.add(row2); List<CaseBean> row3 = new ArrayList<>(); row3.add(new Road()); row3.add(new ShuangShouJianShi()); row3.add(new Wall()); row3.add(new Road()); row3.add(new Wall()); row3.add(new YellowKey()); row3.add(new Wall()); row3.add(new Road()); row3.add(new Wall()); row3.add(new LingWuShi()); row3.add(new Road()); floor12.add(row3); List<CaseBean> row4 = new ArrayList<>(); row4.add(new ShuangShouJianShi()); row4.add(new MingZhanShi()); row4.add(new Wall()); row4.add(new Road()); row4.add(new Wall()); row4.add(new YellowKey()); row4.add(new Wall()); row4.add(new Road()); row4.add(new Wall()); row4.add(new LingFaShi()); row4.add(new LingWuShi()); floor12.add(row4); List<CaseBean> row5 = new ArrayList<>(); row5.add(new Wall()); row5.add(new BlueGate()); row5.add(new Wall()); row5.add(new Road()); row5.add(new Wall()); row5.add(new SmallBloodBottle()); row5.add(new Wall()); row5.add(new Road()); row5.add(new Wall()); row5.add(new BlueGate()); row5.add(new Wall()); floor12.add(row5); List<CaseBean> row6 = new ArrayList<>(); row6.add(new Road()); row6.add(new Road()); row6.add(new Road()); row6.add(new Road()); row6.add(new Wall()); row6.add(new SmallBloodBottle()); row6.add(new Wall()); row6.add(new Road()); row6.add(new Road()); row6.add(new Road()); row6.add(new Road()); floor12.add(row6); List<CaseBean> row7 = new ArrayList<>(); row7.add(new Wall()); row7.add(new Wall()); row7.add(new Wall()); row7.add(new Road()); row7.add(new Wall()); row7.add(new Wall()); row7.add(new Wall()); row7.add(new Road()); row7.add(new Wall()); row7.add(new Wall()); row7.add(new Wall()); floor12.add(row7); List<CaseBean> row8 = new ArrayList<>(); row8.add(new BlueGem()); row8.add(new ShuangShouJianShi()); row8.add(new YellowGate()); row8.add(new MingWeiBing()); row8.add(new MingWeiBing()); row8.add(new GaoJiWeiBing()); row8.add(new MingWeiBing()); row8.add(new MingWeiBing()); row8.add(new YellowGate()); row8.add(new ShuangShouJianShi()); row8.add(new RedGem()); floor12.add(row8); List<CaseBean> row9 = new ArrayList<>(); row9.add(new Wall()); row9.add(new Wall()); row9.add(new Wall()); row9.add(new Wall()); row9.add(new Wall()); row9.add(new BlueGate()); row9.add(new Wall()); row9.add(new Wall()); row9.add(new Wall()); row9.add(new Wall()); row9.add(new Wall()); floor12.add(row9); List<CaseBean> row10 = new ArrayList<>(); row10.add(new GoUpstairs()); row10.add(new Road()); row10.add(new Road()); row10.add(new Road()); row10.add(new Road()); row10.add(new Road()); row10.add(new Road()); row10.add(new Road()); row10.add(new Road()); row10.add(new Road()); row10.add(new GoDownstairs()); floor12.add(row10); return floor12; } @Override public void fromUpstairsToThisFloor() { WarriorBean warriorBean = MagicGameManager.SINGLETON.getWarriorBean(); warriorBean.setPosition(new Position(10, 1)); MagicGameManager.SINGLETON.setCase(warriorBean.getPosition(), warriorBean); } @Override public void fromDownstairsToThisFloor() { WarriorBean warriorBean = MagicGameManager.SINGLETON.getWarriorBean(); warriorBean.setPosition(new Position(10, 9)); MagicGameManager.SINGLETON.setCase(warriorBean.getPosition(), warriorBean); } }
UTF-8
Java
7,175
java
Floor12.java
Java
[ { "context": "il.List;\n\n/**\n * Description:第 12 层\n * Created by 禽兽先生\n * Created on 2017/4/27\n */\n\npublic class Floor12", "end": 1550, "score": 0.8147039413452148, "start": 1546, "tag": "NAME", "value": "禽兽先生" } ]
null
[]
package com.qinshou.qinshoubox.me.bean.floor; import com.qinshou.qinshoubox.me.bean.CaseBean; import com.qinshou.qinshoubox.me.bean.Position; import com.qinshou.qinshoubox.me.bean.building.Road; import com.qinshou.qinshoubox.me.bean.building.Wall; import com.qinshou.qinshoubox.me.bean.monster.GaoJiWeiBing; import com.qinshou.qinshoubox.me.bean.monster.JinDuiZhang; import com.qinshou.qinshoubox.me.bean.monster.JinWeiShi; import com.qinshou.qinshoubox.me.bean.monster.LingFaShi; import com.qinshou.qinshoubox.me.bean.monster.LingWuShi; import com.qinshou.qinshoubox.me.bean.monster.MingWeiBing; import com.qinshou.qinshoubox.me.bean.monster.MingZhanShi; import com.qinshou.qinshoubox.me.bean.monster.ShuangShouJianShi; import com.qinshou.qinshoubox.me.bean.npc.BlueGate; import com.qinshou.qinshoubox.me.bean.npc.BusinessManFloor12; import com.qinshou.qinshoubox.me.bean.npc.GoDownstairs; import com.qinshou.qinshoubox.me.bean.npc.GoUpstairs; import com.qinshou.qinshoubox.me.bean.npc.YellowGate; import com.qinshou.qinshoubox.me.bean.prop.BigBloodBottle; import com.qinshou.qinshoubox.me.bean.prop.BlueGem; import com.qinshou.qinshoubox.me.bean.prop.RedGem; import com.qinshou.qinshoubox.me.bean.prop.SmallBloodBottle; import com.qinshou.qinshoubox.me.bean.prop.StarLightGodHammer; import com.qinshou.qinshoubox.me.bean.prop.YellowKey; import com.qinshou.qinshoubox.me.bean.warrior.WarriorBean; import com.qinshou.qinshoubox.util.MagicGameManager; import java.util.ArrayList; import java.util.List; /** * Description:第 12 层 * Created by 禽兽先生 * Created on 2017/4/27 */ public class Floor12 extends AbsFloor { @Override public int getFloor() { return 12; } @Override public List<List<CaseBean>> setData() { List<List<CaseBean>> floor12 = new ArrayList<>(); List<CaseBean> row0 = new ArrayList<>(); row0.add(new BusinessManFloor12()); row0.add(new BlueGem()); row0.add(new Wall()); row0.add(new Road()); row0.add(new JinWeiShi()); row0.add(new JinDuiZhang()); row0.add(new JinWeiShi()); row0.add(new Road()); row0.add(new Wall()); row0.add(new BigBloodBottle()); row0.add(new StarLightGodHammer()); floor12.add(row0); List<CaseBean> row1 = new ArrayList<>(); row1.add(new RedGem()); row1.add(new Road()); row1.add(new Wall()); row1.add(new Road()); row1.add(new Wall()); row1.add(new YellowGate()); row1.add(new Wall()); row1.add(new Road()); row1.add(new Wall()); row1.add(new Road()); row1.add(new BigBloodBottle()); floor12.add(row1); List<CaseBean> row2 = new ArrayList<>(); row2.add(new Road()); row2.add(new Road()); row2.add(new Wall()); row2.add(new Road()); row2.add(new Wall()); row2.add(new JinDuiZhang()); row2.add(new Wall()); row2.add(new Road()); row2.add(new Wall()); row2.add(new Road()); row2.add(new Road()); floor12.add(row2); List<CaseBean> row3 = new ArrayList<>(); row3.add(new Road()); row3.add(new ShuangShouJianShi()); row3.add(new Wall()); row3.add(new Road()); row3.add(new Wall()); row3.add(new YellowKey()); row3.add(new Wall()); row3.add(new Road()); row3.add(new Wall()); row3.add(new LingWuShi()); row3.add(new Road()); floor12.add(row3); List<CaseBean> row4 = new ArrayList<>(); row4.add(new ShuangShouJianShi()); row4.add(new MingZhanShi()); row4.add(new Wall()); row4.add(new Road()); row4.add(new Wall()); row4.add(new YellowKey()); row4.add(new Wall()); row4.add(new Road()); row4.add(new Wall()); row4.add(new LingFaShi()); row4.add(new LingWuShi()); floor12.add(row4); List<CaseBean> row5 = new ArrayList<>(); row5.add(new Wall()); row5.add(new BlueGate()); row5.add(new Wall()); row5.add(new Road()); row5.add(new Wall()); row5.add(new SmallBloodBottle()); row5.add(new Wall()); row5.add(new Road()); row5.add(new Wall()); row5.add(new BlueGate()); row5.add(new Wall()); floor12.add(row5); List<CaseBean> row6 = new ArrayList<>(); row6.add(new Road()); row6.add(new Road()); row6.add(new Road()); row6.add(new Road()); row6.add(new Wall()); row6.add(new SmallBloodBottle()); row6.add(new Wall()); row6.add(new Road()); row6.add(new Road()); row6.add(new Road()); row6.add(new Road()); floor12.add(row6); List<CaseBean> row7 = new ArrayList<>(); row7.add(new Wall()); row7.add(new Wall()); row7.add(new Wall()); row7.add(new Road()); row7.add(new Wall()); row7.add(new Wall()); row7.add(new Wall()); row7.add(new Road()); row7.add(new Wall()); row7.add(new Wall()); row7.add(new Wall()); floor12.add(row7); List<CaseBean> row8 = new ArrayList<>(); row8.add(new BlueGem()); row8.add(new ShuangShouJianShi()); row8.add(new YellowGate()); row8.add(new MingWeiBing()); row8.add(new MingWeiBing()); row8.add(new GaoJiWeiBing()); row8.add(new MingWeiBing()); row8.add(new MingWeiBing()); row8.add(new YellowGate()); row8.add(new ShuangShouJianShi()); row8.add(new RedGem()); floor12.add(row8); List<CaseBean> row9 = new ArrayList<>(); row9.add(new Wall()); row9.add(new Wall()); row9.add(new Wall()); row9.add(new Wall()); row9.add(new Wall()); row9.add(new BlueGate()); row9.add(new Wall()); row9.add(new Wall()); row9.add(new Wall()); row9.add(new Wall()); row9.add(new Wall()); floor12.add(row9); List<CaseBean> row10 = new ArrayList<>(); row10.add(new GoUpstairs()); row10.add(new Road()); row10.add(new Road()); row10.add(new Road()); row10.add(new Road()); row10.add(new Road()); row10.add(new Road()); row10.add(new Road()); row10.add(new Road()); row10.add(new Road()); row10.add(new GoDownstairs()); floor12.add(row10); return floor12; } @Override public void fromUpstairsToThisFloor() { WarriorBean warriorBean = MagicGameManager.SINGLETON.getWarriorBean(); warriorBean.setPosition(new Position(10, 1)); MagicGameManager.SINGLETON.setCase(warriorBean.getPosition(), warriorBean); } @Override public void fromDownstairsToThisFloor() { WarriorBean warriorBean = MagicGameManager.SINGLETON.getWarriorBean(); warriorBean.setPosition(new Position(10, 9)); MagicGameManager.SINGLETON.setCase(warriorBean.getPosition(), warriorBean); } }
7,175
0.601005
0.572386
219
31.707762
16.398197
83
false
false
0
0
0
0
0
0
0.840183
false
false
6
75c73f2efd5b11f7bbae25cddb6b7910ad6dffda
111,669,192,795
5d100eb7d0de7a0613297d0c2044bc1b381fc6c9
/purdy-gwt/src/main/java/org/dmp/gwtpurdy/client/grid/FixedHeaderGrid.java
4c958bccbd61947faa1d1e23d9d91d99df1b7688
[ "MIT" ]
permissive
logicpeters/dodecahelix
https://github.com/logicpeters/dodecahelix
8776d7de30b9b89f25fcff6fd436db8fc6a67fe0
6c3a5959c78fa7ec775b15c0343a6538e0bf51a7
refs/heads/master
2023-04-30T01:11:11.706000
2022-06-22T19:46:40
2022-06-22T19:46:40
90,810,004
0
0
MIT
false
2022-06-22T19:46:29
2017-05-10T02:00:27
2022-06-22T19:46:23
2022-06-22T19:46:28
1,793
0
0
1
Java
false
false
package org.dmp.gwtpurdy.client.grid; import java.util.List; import org.dmp.gwtpurdy.client.base.BaseResource; import org.dmp.gwtpurdy.client.grid.column.ColumnConfig; import org.dmp.gwtpurdy.client.grid.data.GridRecord; import com.google.gwt.core.client.GWT; import com.google.gwt.user.cellview.client.SimplePager; import com.google.gwt.user.cellview.client.SimplePager.TextLocation; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.ScrollPanel; import com.google.gwt.user.client.ui.SimplePanel; /** * A styled grid with a fixed header (does not scroll, when content scrolls) * and paging controls * * @author dpeters * */ public class FixedHeaderGrid extends Composite { private FlowPanel flowPanel = new FlowPanel(); private GridHeader headerGrid; private ScrollPanel headerGridPanel; private GridContent contentGrid; private ScrollPanel contentGridPanel; private SimplePanel pagerPanel; public FixedHeaderGrid(int pageSize, boolean hasCheckboxColumn) { contentGridPanel = new ScrollPanel(); contentGridPanel.setStyleName(BaseResource.INSTANCE.baseCss().fixedHeaderGridContentPanel()); contentGrid = new GridContent(pageSize, hasCheckboxColumn); contentGridPanel.setWidget(contentGrid); // Does this have to be a scroll panel? headerGridPanel = new ScrollPanel(); headerGridPanel.setStyleName(BaseResource.INSTANCE.baseCss().fixedHeaderGridHeaderPanel()); headerGrid = new GridHeader(this, hasCheckboxColumn); headerGridPanel.setWidget(headerGrid); flowPanel.add(headerGridPanel); flowPanel.add(contentGridPanel); this.initWidget(flowPanel); this.addPagerControl(); } private void addPagerControl() { // add a pager SimplePager.Resources pagerResources = GWT.create(SimplePager.Resources.class); SimplePager pager = new SimplePager(TextLocation.CENTER, pagerResources, false, 0, true); contentGrid.addPagerControl(pager); // TODO -- make this a Horizontal Panel so that dev can control the alignment/location of pager pagerPanel = new SimplePanel(pager); pagerPanel.setStyleName(BaseResource.INSTANCE.baseCss().fixedHeaderGridPagerPanel()); flowPanel.add(pagerPanel); } public void setHeight(String height) { contentGridPanel.setHeight(height); super.setHeight(height); } public void addColumn(final ColumnConfig columnConfig) { headerGrid.addColumn(columnConfig); columnConfig.setHeader(null); contentGrid.addColumn(columnConfig); } public GridContent getGridView() { return contentGrid; } public void checkAllColumns(boolean checked) { contentGrid.checkAllColumns(checked); } public void sortColumn(int i, boolean sortAscending) { contentGrid.sortColumn(i, sortAscending); } public void addRecords(List<GridRecord> demoValues) { contentGrid.addRecords(demoValues); } }
UTF-8
Java
3,236
java
FixedHeaderGrid.java
Java
[ { "context": "scrolls)\n * and paging controls\n * \n * @author dpeters\n *\n */\npublic class FixedHeaderGrid extends Compo", "end": 717, "score": 0.9976649284362793, "start": 710, "tag": "USERNAME", "value": "dpeters" } ]
null
[]
package org.dmp.gwtpurdy.client.grid; import java.util.List; import org.dmp.gwtpurdy.client.base.BaseResource; import org.dmp.gwtpurdy.client.grid.column.ColumnConfig; import org.dmp.gwtpurdy.client.grid.data.GridRecord; import com.google.gwt.core.client.GWT; import com.google.gwt.user.cellview.client.SimplePager; import com.google.gwt.user.cellview.client.SimplePager.TextLocation; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.ScrollPanel; import com.google.gwt.user.client.ui.SimplePanel; /** * A styled grid with a fixed header (does not scroll, when content scrolls) * and paging controls * * @author dpeters * */ public class FixedHeaderGrid extends Composite { private FlowPanel flowPanel = new FlowPanel(); private GridHeader headerGrid; private ScrollPanel headerGridPanel; private GridContent contentGrid; private ScrollPanel contentGridPanel; private SimplePanel pagerPanel; public FixedHeaderGrid(int pageSize, boolean hasCheckboxColumn) { contentGridPanel = new ScrollPanel(); contentGridPanel.setStyleName(BaseResource.INSTANCE.baseCss().fixedHeaderGridContentPanel()); contentGrid = new GridContent(pageSize, hasCheckboxColumn); contentGridPanel.setWidget(contentGrid); // Does this have to be a scroll panel? headerGridPanel = new ScrollPanel(); headerGridPanel.setStyleName(BaseResource.INSTANCE.baseCss().fixedHeaderGridHeaderPanel()); headerGrid = new GridHeader(this, hasCheckboxColumn); headerGridPanel.setWidget(headerGrid); flowPanel.add(headerGridPanel); flowPanel.add(contentGridPanel); this.initWidget(flowPanel); this.addPagerControl(); } private void addPagerControl() { // add a pager SimplePager.Resources pagerResources = GWT.create(SimplePager.Resources.class); SimplePager pager = new SimplePager(TextLocation.CENTER, pagerResources, false, 0, true); contentGrid.addPagerControl(pager); // TODO -- make this a Horizontal Panel so that dev can control the alignment/location of pager pagerPanel = new SimplePanel(pager); pagerPanel.setStyleName(BaseResource.INSTANCE.baseCss().fixedHeaderGridPagerPanel()); flowPanel.add(pagerPanel); } public void setHeight(String height) { contentGridPanel.setHeight(height); super.setHeight(height); } public void addColumn(final ColumnConfig columnConfig) { headerGrid.addColumn(columnConfig); columnConfig.setHeader(null); contentGrid.addColumn(columnConfig); } public GridContent getGridView() { return contentGrid; } public void checkAllColumns(boolean checked) { contentGrid.checkAllColumns(checked); } public void sortColumn(int i, boolean sortAscending) { contentGrid.sortColumn(i, sortAscending); } public void addRecords(List<GridRecord> demoValues) { contentGrid.addRecords(demoValues); } }
3,236
0.697775
0.697466
99
31.686869
26.905613
103
false
false
0
0
0
0
0
0
0.616162
false
false
6
8d2dbb9df2a75fb7e62eee49835bac87a5612c4d
36,593,121,373,441
b6b7174f77766cd19d36abb624f06ec4b270f61e
/src/main/java/overtime/Main.java
0893e863ebc2b06807367593fa17360613422751
[]
no_license
amarraja123/OvertimePayCalculator
https://github.com/amarraja123/OvertimePayCalculator
173d2c227147aa9e2e3312eb7db4ed85e8c6186e
032e221b203aaaf0c84bf60490482be42ad9fcf7
refs/heads/master
2021-01-10T13:44:03.412000
2016-01-13T04:13:19
2016-01-13T04:13:46
49,316,174
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package overtime; import java.util.ArrayList; import java.util.List; public class Main { public static final void main(String args[]) { OverTimeCalculator ot1 = new OverTimeMoreThan70HrsDecorator(new OverTime40to60HrsDecorator(new OverTimeLessThan40HrsDecorator(new SimpleOverTimeCalculator()))); Division division = new Division(ot1); List<Division> divisionList = new ArrayList<Division>(); Company c = new Company(); c.setDivision(divisionList); Employee e = new Employee(division); e.setWeeklyHours(75); System.out.println(division.getOverTimeBenefits(e.getWeeklyHours())); } }
UTF-8
Java
611
java
Main.java
Java
[]
null
[]
package overtime; import java.util.ArrayList; import java.util.List; public class Main { public static final void main(String args[]) { OverTimeCalculator ot1 = new OverTimeMoreThan70HrsDecorator(new OverTime40to60HrsDecorator(new OverTimeLessThan40HrsDecorator(new SimpleOverTimeCalculator()))); Division division = new Division(ot1); List<Division> divisionList = new ArrayList<Division>(); Company c = new Company(); c.setDivision(divisionList); Employee e = new Employee(division); e.setWeeklyHours(75); System.out.println(division.getOverTimeBenefits(e.getWeeklyHours())); } }
611
0.765957
0.746318
21
28.095238
36.131908
162
false
false
0
0
0
0
0
0
1.619048
false
false
6
acd7a9f462de9e20f597641a99e3fd118c74f435
34,703,335,770,561
1ab4d941a8fd03b81ebaa1592ad2b4b1586d96f3
/src/fr/eazyender/skyblock/world/SkyBlockGen.java
e7b6dcb86d25a61a3decd6b2f878f7b8af207915
[]
no_license
EazyEnder/Skyeim
https://github.com/EazyEnder/Skyeim
78ca319898e16b7a5eec7108b1956f7f236f8a95
8c284edbb8b37185b3ee1ee6b099299bfb1f31b6
refs/heads/master
2020-07-02T18:34:22.707000
2020-06-17T14:47:09
2020-06-17T14:47:09
201,623,610
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package fr.eazyender.skyblock.world; import java.util.Arrays; import java.util.List; import java.util.Random; import org.bukkit.World; import org.bukkit.generator.BlockPopulator; import org.bukkit.generator.ChunkGenerator; public class SkyBlockGen extends ChunkGenerator { public List<BlockPopulator> getDefaultPopulators(World world) { return Arrays.asList(new BlockPopulator[0]); } public boolean canSpawn(World world, int x, int z) { return true; } public byte[] generate(World world, Random rand, int chunkx, int chunkz) { return new byte[32768]; } @Override public ChunkData generateChunkData(World world, Random random, int x, int z, BiomeGrid biome) { return createChunkData(world); } }
UTF-8
Java
826
java
SkyBlockGen.java
Java
[]
null
[]
package fr.eazyender.skyblock.world; import java.util.Arrays; import java.util.List; import java.util.Random; import org.bukkit.World; import org.bukkit.generator.BlockPopulator; import org.bukkit.generator.ChunkGenerator; public class SkyBlockGen extends ChunkGenerator { public List<BlockPopulator> getDefaultPopulators(World world) { return Arrays.asList(new BlockPopulator[0]); } public boolean canSpawn(World world, int x, int z) { return true; } public byte[] generate(World world, Random rand, int chunkx, int chunkz) { return new byte[32768]; } @Override public ChunkData generateChunkData(World world, Random random, int x, int z, BiomeGrid biome) { return createChunkData(world); } }
826
0.66707
0.659806
31
24.645161
25.728794
100
false
false
0
0
0
0
0
0
0.677419
false
false
6
8bab4a2a14d0f7c46e4c17027f80d309fc8ca4fe
31,490,700,271,454
97262b832b73b38083cd817df401f91d0a7cd602
/src/com/shpp/p2p/cs/vkolisnichenko/assignment15/Assignment15Part1.java
ee9f13edbbb9d0b4d80a0d4b5a475bcbcce06834
[]
no_license
Slava0271/Computer-science
https://github.com/Slava0271/Computer-science
a738232b40b8467ece0a0aa24afa1f6d2cc06a94
30aaac8d997a1d93b88cfae491ea470eb2ef4112
refs/heads/master
2023-02-27T20:33:46.368000
2021-02-07T19:28:39
2021-02-07T19:28:39
336,870,935
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.shpp.p2p.cs.vkolisnichenko.assignment15; import java.io.File; /** * The main class in which objects are created and * methods are called to implement the Huffman algorithm. * The class also implements a method that collects information */ public class Assignment15Part1 { /** * A method in which, depending on the variable a, * the program decides whether it needs to be archived or * unzipped, the information is also displayed in the console * * @param args * @throws Exception */ public static void main(String[] args) throws Exception { //Get the start time of the program long timeMillis = System.currentTimeMillis(); var readParameters = new ReadParameters(); //get action (archive or unarchive) int getAction = readParameters.readParameters(args); //variables with filenames String inputFile = readParameters.getInputFile(); String outputFile = readParameters.getOutputFile(); if (getAction == 1) { Archive archive = new Archive(inputFile, outputFile); //archive file archive.archive(); } else if (getAction == 2) { UnArchive unArchive = new UnArchive(inputFile, outputFile); //unarchive file unArchive.unArchive(); } //write information to console getInformation(getAction, timeMillis, inputFile, outputFile); } /** * The method in which we output information about * the execution of the program to the console: * file size, execution time and efficiency * * @param operation - get operation( archive or unarchive) * @param timeMillis - get start program time */ private static void getInformation(int operation, long timeMillis , String inputFile, String outputFile) { if (operation == 1) { if (isInputFileLarger(inputFile, outputFile)) System.out.println("Archiving was efficient"); else System.out.println("Archiving was ineffective"); } else if (operation == 2) { if (!isInputFileLarger(inputFile, outputFile)) System.out.println("Archiving was ineffective"); else System.out.println("Archiving was efficient"); } System.out.println("execution time - " + (double) (System.currentTimeMillis() - timeMillis) / 1000 + " Seconds"); if (operation == 1) { System.out.println("inputFile : " + getFileSizeBytes(new File(inputFile)) + " bytes"); System.out.println("outputFile : " + getFileSizeBytes(new File(outputFile)) + " bytes"); } else if (operation == 2) { System.out.println("inputFile : " + getFileSizeBytes(new File(outputFile)) + " bytes"); System.out.println("outputFile : " + getFileSizeBytes(new File(inputFile)) + " bytes"); } } /** * Check if the input file is greater than * the output and return a boolean value * * @return - true or false */ private static boolean isInputFileLarger(String inputFile, String outputFile) { return getFileSizeBytes(new File(inputFile)) >= getFileSizeBytes(new File(outputFile)); } /** * The method in which we get the size of the input file * * @param file - input file * @return - size */ private static long getFileSizeBytes(File file) { return file.length(); } }
UTF-8
Java
3,523
java
Assignment15Part1.java
Java
[]
null
[]
package com.shpp.p2p.cs.vkolisnichenko.assignment15; import java.io.File; /** * The main class in which objects are created and * methods are called to implement the Huffman algorithm. * The class also implements a method that collects information */ public class Assignment15Part1 { /** * A method in which, depending on the variable a, * the program decides whether it needs to be archived or * unzipped, the information is also displayed in the console * * @param args * @throws Exception */ public static void main(String[] args) throws Exception { //Get the start time of the program long timeMillis = System.currentTimeMillis(); var readParameters = new ReadParameters(); //get action (archive or unarchive) int getAction = readParameters.readParameters(args); //variables with filenames String inputFile = readParameters.getInputFile(); String outputFile = readParameters.getOutputFile(); if (getAction == 1) { Archive archive = new Archive(inputFile, outputFile); //archive file archive.archive(); } else if (getAction == 2) { UnArchive unArchive = new UnArchive(inputFile, outputFile); //unarchive file unArchive.unArchive(); } //write information to console getInformation(getAction, timeMillis, inputFile, outputFile); } /** * The method in which we output information about * the execution of the program to the console: * file size, execution time and efficiency * * @param operation - get operation( archive or unarchive) * @param timeMillis - get start program time */ private static void getInformation(int operation, long timeMillis , String inputFile, String outputFile) { if (operation == 1) { if (isInputFileLarger(inputFile, outputFile)) System.out.println("Archiving was efficient"); else System.out.println("Archiving was ineffective"); } else if (operation == 2) { if (!isInputFileLarger(inputFile, outputFile)) System.out.println("Archiving was ineffective"); else System.out.println("Archiving was efficient"); } System.out.println("execution time - " + (double) (System.currentTimeMillis() - timeMillis) / 1000 + " Seconds"); if (operation == 1) { System.out.println("inputFile : " + getFileSizeBytes(new File(inputFile)) + " bytes"); System.out.println("outputFile : " + getFileSizeBytes(new File(outputFile)) + " bytes"); } else if (operation == 2) { System.out.println("inputFile : " + getFileSizeBytes(new File(outputFile)) + " bytes"); System.out.println("outputFile : " + getFileSizeBytes(new File(inputFile)) + " bytes"); } } /** * Check if the input file is greater than * the output and return a boolean value * * @return - true or false */ private static boolean isInputFileLarger(String inputFile, String outputFile) { return getFileSizeBytes(new File(inputFile)) >= getFileSizeBytes(new File(outputFile)); } /** * The method in which we get the size of the input file * * @param file - input file * @return - size */ private static long getFileSizeBytes(File file) { return file.length(); } }
3,523
0.624184
0.619642
98
34.938774
28.394026
100
false
false
0
0
0
0
0
0
0.387755
false
false
6
4191f8644cc1708dc3e70d5954117686d376b298
34,849,364,677,003
fdabfe461e9601c0fcd9aaee945fc7be1bc07615
/old-external/JavaHamcrest/hamcrest-core/src/test/java/org/hamcrest/TypeSafeDiagnosingMatcherTest.java
0b00139129f2ec8f81e33fe8da1b1b223295393f
[ "BSD-3-Clause", "Apache-2.0", "BSD-2-Clause" ]
permissive
veriktig/scandium
https://github.com/veriktig/scandium
b6e8bb0e495d44c7fa278c066fda0d616f2d65c3
bcba8f9d6ce15575655fa323dcf9a5d06568c805
refs/heads/master
2023-03-16T12:37:09.597000
2022-04-06T23:16:42
2022-04-06T23:16:42
120,193,106
1
0
Apache-2.0
false
2023-02-22T08:02:11
2018-02-04T14:41:29
2023-02-15T02:04:22
2023-02-22T08:02:10
85,248
1
0
9
Java
false
false
package org.hamcrest; import org.junit.Test; import static org.hamcrest.AbstractMatcherTest.*; /** * @author Steve Freeman 2016 http://www.hamcrest.com */ @SuppressWarnings("WeakerAccess") public class TypeSafeDiagnosingMatcherTest { @Test public void describesMismatches() { assertMismatchDescription("was null", STRING_MATCHER, null); assertMismatchDescription("was Character \"c\"", STRING_MATCHER, 'c'); assertMismatchDescription("mismatching", STRING_MATCHER, "other"); } @Test public void detects_non_builtin_types() { final Matcher<NotBuiltIn> matcher = new TypeSafeDiagnosingMatcher<NotBuiltIn>() { @Override protected boolean matchesSafely(NotBuiltIn item, Description mismatchDescription) { return true; } @Override public void describeTo(Description description) { description.appendText("a not builtin"); } }; assertMatches("not built in", matcher, new NotBuiltIn()); assertDoesNotMatch("other not built in", (Matcher)matcher, new OtherNotBuiltIn()); } @Test public void filters_type_for_subclassed_matcher_when_expected_type_passed_in() { final Matcher<NotBuiltIn> matcher = new SubMatcher<>(new NotBuiltIn()); assertMatches("not built in", matcher, new NotBuiltIn()); assertDoesNotMatch("other not built in", (Matcher)matcher, new OtherNotBuiltIn()); } @Test public void but_cannot_detect_generic_type_in_subclassed_matcher_using_reflection() { final Matcher<NotBuiltIn> matcher = new SubMatcher<>(); assertMatches("not built in", matcher, new NotBuiltIn()); assertMatches("other not built in", (Matcher)matcher, new OtherNotBuiltIn()); } private static final TypeSafeDiagnosingMatcher STRING_MATCHER = new TypeSafeDiagnosingMatcher<String>() { @Override protected boolean matchesSafely(String item, Description mismatchDescription) { mismatchDescription.appendText("mismatching"); return false; } @Override public void describeTo(Description description) { } }; public static class SubMatcher<T> extends TypeSafeDiagnosingMatcher<T> { public SubMatcher() { super(); } public SubMatcher(T expectedObject) { super(expectedObject.getClass()); } @Override protected boolean matchesSafely(T item, Description mismatchDescription) { return true; } @Override public void describeTo(Description description) { description.appendText("sub type"); } } public static class NotBuiltIn { public final String value = "not built in"; @Override public String toString() { return "NotBuiltIn"; } } public static class OtherNotBuiltIn { // empty } }
UTF-8
Java
2,804
java
TypeSafeDiagnosingMatcherTest.java
Java
[ { "context": "rg.hamcrest.AbstractMatcherTest.*;\n\n/**\n * @author Steve Freeman 2016 http://www.hamcrest.com\n */\n@SuppressWarning", "end": 126, "score": 0.9998494982719421, "start": 113, "tag": "NAME", "value": "Steve Freeman" } ]
null
[]
package org.hamcrest; import org.junit.Test; import static org.hamcrest.AbstractMatcherTest.*; /** * @author <NAME> 2016 http://www.hamcrest.com */ @SuppressWarnings("WeakerAccess") public class TypeSafeDiagnosingMatcherTest { @Test public void describesMismatches() { assertMismatchDescription("was null", STRING_MATCHER, null); assertMismatchDescription("was Character \"c\"", STRING_MATCHER, 'c'); assertMismatchDescription("mismatching", STRING_MATCHER, "other"); } @Test public void detects_non_builtin_types() { final Matcher<NotBuiltIn> matcher = new TypeSafeDiagnosingMatcher<NotBuiltIn>() { @Override protected boolean matchesSafely(NotBuiltIn item, Description mismatchDescription) { return true; } @Override public void describeTo(Description description) { description.appendText("a not builtin"); } }; assertMatches("not built in", matcher, new NotBuiltIn()); assertDoesNotMatch("other not built in", (Matcher)matcher, new OtherNotBuiltIn()); } @Test public void filters_type_for_subclassed_matcher_when_expected_type_passed_in() { final Matcher<NotBuiltIn> matcher = new SubMatcher<>(new NotBuiltIn()); assertMatches("not built in", matcher, new NotBuiltIn()); assertDoesNotMatch("other not built in", (Matcher)matcher, new OtherNotBuiltIn()); } @Test public void but_cannot_detect_generic_type_in_subclassed_matcher_using_reflection() { final Matcher<NotBuiltIn> matcher = new SubMatcher<>(); assertMatches("not built in", matcher, new NotBuiltIn()); assertMatches("other not built in", (Matcher)matcher, new OtherNotBuiltIn()); } private static final TypeSafeDiagnosingMatcher STRING_MATCHER = new TypeSafeDiagnosingMatcher<String>() { @Override protected boolean matchesSafely(String item, Description mismatchDescription) { mismatchDescription.appendText("mismatching"); return false; } @Override public void describeTo(Description description) { } }; public static class SubMatcher<T> extends TypeSafeDiagnosingMatcher<T> { public SubMatcher() { super(); } public SubMatcher(T expectedObject) { super(expectedObject.getClass()); } @Override protected boolean matchesSafely(T item, Description mismatchDescription) { return true; } @Override public void describeTo(Description description) { description.appendText("sub type"); } } public static class NotBuiltIn { public final String value = "not built in"; @Override public String toString() { return "NotBuiltIn"; } } public static class OtherNotBuiltIn { // empty } }
2,797
0.683666
0.68224
81
33.617283
33.754951
110
false
false
0
0
0
0
0
0
0.580247
false
false
6
f696978e8436a3e6065758fe8c7f8ee82a680b08
38,817,914,427,659
1d3535a9eb80212ac26d0d62d6f6544945ca5461
/src/main/java/pglott/design/observer/selfmade/WeatherStation.java
2a95516cc38607acb18542376ed7524ad199111b
[ "MIT" ]
permissive
pglott/design-patterns
https://github.com/pglott/design-patterns
9973c0549b59230b3339ab9c641545cd44000f5e
8fa0781146092b2a34eb64c5dfff4631465d4516
refs/heads/master
2018-11-12T09:23:02.177000
2018-08-27T21:13:53
2018-08-27T21:13:53
145,763,756
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pglott.design.observer.selfmade; import pglott.design.observer.selfmade.displays.CurrentConditionsDisplay; import pglott.design.observer.selfmade.displays.LCDWeatherDisplay; import pglott.design.observer.selfmade.displays.WeatherDisplay; public class WeatherStation { public static void main(String ...args) { WeatherData data = new WeatherData(); WeatherDisplay currentConditionsDisplay = new CurrentConditionsDisplay(data); WeatherDisplay lcdDisplay = new LCDWeatherDisplay(data); data.setMeasurements(32.0, 88.0, 1015); data.setMeasurements(37.0, 99.0, 1005); } }
UTF-8
Java
648
java
WeatherStation.java
Java
[]
null
[]
package pglott.design.observer.selfmade; import pglott.design.observer.selfmade.displays.CurrentConditionsDisplay; import pglott.design.observer.selfmade.displays.LCDWeatherDisplay; import pglott.design.observer.selfmade.displays.WeatherDisplay; public class WeatherStation { public static void main(String ...args) { WeatherData data = new WeatherData(); WeatherDisplay currentConditionsDisplay = new CurrentConditionsDisplay(data); WeatherDisplay lcdDisplay = new LCDWeatherDisplay(data); data.setMeasurements(32.0, 88.0, 1015); data.setMeasurements(37.0, 99.0, 1005); } }
648
0.733025
0.70216
17
35.882355
28.7195
85
false
false
0
0
0
0
0
0
0.764706
false
false
6
f5706371dd3c5e3ba30898d236e567bdcbd48e55
38,225,208,943,598
e39fd1b02a9389d150f68d4b291252510ca31609
/src/main/java/guru/oussama/blog/hexarchi/domain/entities/PhoneBook.java
86069b750ab6036b1e95749e5e773dd045a6a3ca
[]
no_license
oussama-guru/java-hexagonal-architecture
https://github.com/oussama-guru/java-hexagonal-architecture
ac710531a51a703df60aa2639b6528aee501890c
f14b8e1027be044e13ae19f635a4a7ab0e438990
refs/heads/main
2022-12-26T07:38:32.677000
2020-10-04T10:44:08
2020-10-04T10:44:08
300,702,640
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package guru.oussama.blog.hexarchi.domain.entities; import java.util.List; public class PhoneBook { private Long id; private List<String> numbers; public PhoneBook(Long id, List<String> numbers) { this.id = id; this.numbers = numbers; } public void addNumber(String number) { numbers.add(number); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public List<String> getNumbers() { return numbers; } public void setNumbers(List<String> numbers) { this.numbers = numbers; } }
UTF-8
Java
627
java
PhoneBook.java
Java
[]
null
[]
package guru.oussama.blog.hexarchi.domain.entities; import java.util.List; public class PhoneBook { private Long id; private List<String> numbers; public PhoneBook(Long id, List<String> numbers) { this.id = id; this.numbers = numbers; } public void addNumber(String number) { numbers.add(number); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public List<String> getNumbers() { return numbers; } public void setNumbers(List<String> numbers) { this.numbers = numbers; } }
627
0.599681
0.599681
33
18
16.711454
53
false
false
0
0
0
0
0
0
0.363636
false
false
6
f031f8252595716f857665ae8b12435eafc41149
37,340,445,691,021
016ebadd697e756103039c0890f61c0c4f0b3fd0
/Java GUI/PieChart/PieChart.java
6f3169e957b103c6a0418a57d6651d1c7f03ee9d
[]
no_license
thisIsJooS/Java-Exercises
https://github.com/thisIsJooS/Java-Exercises
b1f0c50e11fc831e8d58721f37c6b53029dd1eb2
28c4c449b17fb05940f7278739bca3ebe36c453c
refs/heads/main
2023-05-28T00:11:54.140000
2023-01-24T06:41:09
2023-01-24T06:41:09
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
//명품 Java Programming ch12 Q011 681p //draw Pie Chart import java.awt.*; import java.awt.event.*; import javax.swing.*; public class PieChart extends JFrame{ private String [] itemName = {"apple", "cherry", "strawberry", "prune"}; private JTextField [] tf = new JTextField [4]; private int [] data = {0,0,0,0}; private int [] arcAngle = new int[4]; private Color [] color = {Color.red, Color.blue, Color.magenta, Color.orange}; private ChartPanel chartPanel = new ChartPanel(); private int [] ratio = {0,0,0,0}; public PieChart(){ setTitle("Pie Chart"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); getContentPane().add(new InputPanel(), BorderLayout.NORTH); getContentPane().add(chartPanel, BorderLayout.CENTER); setSize(500,400); setVisible(true); drawChart(); } public static void main(String[] args){ new PieChart(); } public void drawChart(){ int sum=0; for(int i=0; i< data.length; i++){ data[i] = Integer.parseInt(tf[i].getText()); sum+=data[i]; } if(sum==0) return; for(int i=0; i< data.length; i++){ ratio[i] = (int)Math.round((double)data[i]/(double)sum*100); arcAngle[i] = (int)Math.round(360*(double)data[i]/(double)sum); } chartPanel.repaint(); } private class InputPanel extends JPanel{ private MyActionListener listener = new MyActionListener(); public InputPanel(){ setLayout(new FlowLayout()); setBackground(Color.LIGHT_GRAY); for(int i=0; i<data.length; i++){ add(new JLabel(itemName[i])); tf[i] = new JTextField("0", 5); tf[i].addActionListener(listener); add(tf[i]); } } } class MyActionListener implements ActionListener{ @Override public void actionPerformed(ActionEvent e){ JTextField t = (JTextField)e.getSource(); //textfield에 입력한 값이 정수인지를 판단한다. 정수가 아닐경우 0으로 setText하고 리턴. int k; try{ k = Integer.parseInt(t.getText()); }catch(NumberFormatException ex){ t.setText("0"); return; } drawChart(); } } private class ChartPanel extends JPanel{ public void paintComponent(Graphics g){ super.paintComponent(g); for(int i=0; i<data.length; i++){ g.setColor(color[i]); g.drawString(itemName[i] + " "+ Integer.toString(ratio[i]) + " %" ,100*i + 50 ,20); } int startAngle =0 ; for(int i=0; i<data.length; i++){ g.setColor(color[i]); g.fillArc(100,80,250,250, startAngle, arcAngle[i]); startAngle += arcAngle[i]; } } } }
UTF-8
Java
2,711
java
PieChart.java
Java
[]
null
[]
//명품 Java Programming ch12 Q011 681p //draw Pie Chart import java.awt.*; import java.awt.event.*; import javax.swing.*; public class PieChart extends JFrame{ private String [] itemName = {"apple", "cherry", "strawberry", "prune"}; private JTextField [] tf = new JTextField [4]; private int [] data = {0,0,0,0}; private int [] arcAngle = new int[4]; private Color [] color = {Color.red, Color.blue, Color.magenta, Color.orange}; private ChartPanel chartPanel = new ChartPanel(); private int [] ratio = {0,0,0,0}; public PieChart(){ setTitle("Pie Chart"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); getContentPane().add(new InputPanel(), BorderLayout.NORTH); getContentPane().add(chartPanel, BorderLayout.CENTER); setSize(500,400); setVisible(true); drawChart(); } public static void main(String[] args){ new PieChart(); } public void drawChart(){ int sum=0; for(int i=0; i< data.length; i++){ data[i] = Integer.parseInt(tf[i].getText()); sum+=data[i]; } if(sum==0) return; for(int i=0; i< data.length; i++){ ratio[i] = (int)Math.round((double)data[i]/(double)sum*100); arcAngle[i] = (int)Math.round(360*(double)data[i]/(double)sum); } chartPanel.repaint(); } private class InputPanel extends JPanel{ private MyActionListener listener = new MyActionListener(); public InputPanel(){ setLayout(new FlowLayout()); setBackground(Color.LIGHT_GRAY); for(int i=0; i<data.length; i++){ add(new JLabel(itemName[i])); tf[i] = new JTextField("0", 5); tf[i].addActionListener(listener); add(tf[i]); } } } class MyActionListener implements ActionListener{ @Override public void actionPerformed(ActionEvent e){ JTextField t = (JTextField)e.getSource(); //textfield에 입력한 값이 정수인지를 판단한다. 정수가 아닐경우 0으로 setText하고 리턴. int k; try{ k = Integer.parseInt(t.getText()); }catch(NumberFormatException ex){ t.setText("0"); return; } drawChart(); } } private class ChartPanel extends JPanel{ public void paintComponent(Graphics g){ super.paintComponent(g); for(int i=0; i<data.length; i++){ g.setColor(color[i]); g.drawString(itemName[i] + " "+ Integer.toString(ratio[i]) + " %" ,100*i + 50 ,20); } int startAngle =0 ; for(int i=0; i<data.length; i++){ g.setColor(color[i]); g.fillArc(100,80,250,250, startAngle, arcAngle[i]); startAngle += arcAngle[i]; } } } }
2,711
0.598642
0.576009
98
26.040817
21.20306
91
false
false
0
0
0
0
0
0
0.816327
false
false
6
d2c59e57550837ab5504cc9516f0e34309fe20e7
154,618,883,246
c62f0fee09610dc82066f4f014f3f2c32405e235
/pipeline/src/main/java/com/hartwig/pipeline/Configuration.java
f4c3bd11ec05dd3add38bc0d791f705fffea3fc0
[ "MIT" ]
permissive
heuermh/hartwigmedical-pipeline2
https://github.com/heuermh/hartwigmedical-pipeline2
458d7f0ae1180ec70d8f5dcf6107e7cf6149a269
3e138900d5460de545137ea4fc6346b6547c84e4
refs/heads/master
2020-03-21T15:55:28.861000
2018-06-21T20:39:26
2018-06-21T20:39:26
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hartwig.pipeline; import java.util.Map; import org.immutables.value.Value; @Value.Immutable public interface Configuration { enum Flavour { GATK4, ADAM } @Value.Default default Flavour flavour() { return Flavour.ADAM; } String sparkMaster(); String patientDirectory(); String patientName(); String referenceGenomePath(); Map<String, String> sparkProperties(); @Value.Default default boolean persistIntermediateResults() { return false; } static ImmutableConfiguration.Builder builder() { return ImmutableConfiguration.builder(); } }
UTF-8
Java
657
java
Configuration.java
Java
[]
null
[]
package com.hartwig.pipeline; import java.util.Map; import org.immutables.value.Value; @Value.Immutable public interface Configuration { enum Flavour { GATK4, ADAM } @Value.Default default Flavour flavour() { return Flavour.ADAM; } String sparkMaster(); String patientDirectory(); String patientName(); String referenceGenomePath(); Map<String, String> sparkProperties(); @Value.Default default boolean persistIntermediateResults() { return false; } static ImmutableConfiguration.Builder builder() { return ImmutableConfiguration.builder(); } }
657
0.660578
0.659056
38
16.289474
16.099865
53
false
false
0
0
0
0
0
0
0.342105
false
false
6
8f5cd432043a720cf1bc2ac0f8fd2036e1a36df5
29,626,684,471,604
cd9ce9b656d9594cf5a19df4ad50b5c9f5aff624
/src/test/java/lz/testDesignMode/strategy/GivenGreenLight.java
3eab654373d7285fb8067a9641623ecce1463659
[]
no_license
zzlzlizhen/javaDesignMode
https://github.com/zzlzlizhen/javaDesignMode
2b7f23ecc7c93ea305f93abd52fadae4ac85f277
bfa7b08b8c56487275120ad6ea5e2cbe9c5bdf5e
refs/heads/master
2021-01-13T10:18:47.578000
2016-12-16T10:08:47
2016-12-16T10:08:47
76,628,662
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package lz.testDesignMode.strategy; /** * @author lizhen_pc * 求吴国太开绿灯放行 *123 */ public class GivenGreenLight implements Strategy { public void operate() { System.out.println("求吴国太开个绿灯,放行"); } }
UTF-8
Java
280
java
GivenGreenLight.java
Java
[ { "context": "age lz.testDesignMode.strategy;\r\n\r\n/**\r\n * @author lizhen_pc\r\n * 求吴国太开绿灯放行\r\n *123\r\n */\r\npublic class GivenGree", "end": 79, "score": 0.9996487498283386, "start": 70, "tag": "USERNAME", "value": "lizhen_pc" } ]
null
[]
/** * */ package lz.testDesignMode.strategy; /** * @author lizhen_pc * 求吴国太开绿灯放行 *123 */ public class GivenGreenLight implements Strategy { public void operate() { System.out.println("求吴国太开个绿灯,放行"); } }
280
0.6
0.5875
19
10.631579
14.640285
50
false
false
0
0
0
0
0
0
0.421053
false
false
6
ca10f2eaf97524a98b9add3696de63b8e22f9505
39,135,742,005,207
c3fd7da24e990c047b55cd0380861d3170fa5a96
/src/main/java/com/weather/WeatherApi/util/GlobalExceptionHandler.java
5fa9b9d257012b9a49715c65533a1d010ed400a9
[]
no_license
sats17/Java-WeatherAppSystemLayer
https://github.com/sats17/Java-WeatherAppSystemLayer
8cff71f97aa1f436577f53410d75e0be6c730598
b4f9e3b5504ad88066ce186177f136a4a9f90cbc
refs/heads/master
2020-11-26T15:13:01.953000
2020-04-25T17:23:01
2020-04-25T17:23:01
229,118,210
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.weather.WeatherApi.util; import java.util.Date; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; import com.weather.WeatherApi.exceptions.CityNotFoundException; import com.weather.WeatherApi.exceptions.DefaultException; import com.weather.WeatherApi.exceptions.WeatherNotFoundException; @ControllerAdvice public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { @ExceptionHandler(CityNotFoundException.class) public static final ResponseEntity<ExceptionResponse> handleGlobalException(CityNotFoundException ex, WebRequest req) { ExceptionResponse exceptionResponse = new ExceptionResponse(new Date(), ex.getMessage(), req.getDescription(false), HttpStatus.NOT_FOUND.getReasonPhrase()); return new ResponseEntity<ExceptionResponse>(exceptionResponse, HttpStatus.NOT_FOUND); } @ExceptionHandler(WeatherNotFoundException.class) public static final ResponseEntity<ExceptionResponse> handleWeatherNotFoundException(WeatherNotFoundException ex, WebRequest req) { ExceptionResponse exceptionResponse = new ExceptionResponse(new Date(), ex.getMessage(), req.getDescription(false), HttpStatus.NOT_FOUND.getReasonPhrase()); return new ResponseEntity<ExceptionResponse>(exceptionResponse, HttpStatus.NOT_FOUND); } @ExceptionHandler(DefaultException.class) public static final ResponseEntity<ExceptionResponse> handleDefaultException(DefaultException ex, WebRequest req) { ExceptionResponse exceptionResponse = new ExceptionResponse(new Date(), ex.getMessage(), req.getDescription(false), HttpStatus.NOT_ACCEPTABLE.getReasonPhrase()); return new ResponseEntity<ExceptionResponse>(exceptionResponse, HttpStatus.NOT_ACCEPTABLE); } // @ExceptionHandler(InvalidAuthentication.class) // public final ResponseEntity<ExceptionResponse> handleInvalidAuthentication(InvalidAuthentication ex, WebRequest req) { // // ExceptionResponse exceptionResponse = new ExceptionResponse(new Date(), ex.getMessage(), // // req.getDescription(false), HttpStatus.UNAUTHORIZED.getReasonPhrase()); // // return new ResponseEntity<ExceptionResponse>(exceptionResponse, HttpStatus.UNAUTHORIZED); // // } // // @ExceptionHandler(UnauthorizedException.class) // public final ResponseEntity<ExceptionResponse> handleUnathorizedException(UnauthorizedException ex, WebRequest req) { // // ExceptionResponse exceptionResponse = new ExceptionResponse(new Date(), ex.getMessage(), // // req.getDescription(false), HttpStatus.FORBIDDEN.getReasonPhrase()); // // return new ResponseEntity<ExceptionResponse>(exceptionResponse, HttpStatus.FORBIDDEN); // // } }
UTF-8
Java
2,934
java
GlobalExceptionHandler.java
Java
[]
null
[]
package com.weather.WeatherApi.util; import java.util.Date; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; import com.weather.WeatherApi.exceptions.CityNotFoundException; import com.weather.WeatherApi.exceptions.DefaultException; import com.weather.WeatherApi.exceptions.WeatherNotFoundException; @ControllerAdvice public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { @ExceptionHandler(CityNotFoundException.class) public static final ResponseEntity<ExceptionResponse> handleGlobalException(CityNotFoundException ex, WebRequest req) { ExceptionResponse exceptionResponse = new ExceptionResponse(new Date(), ex.getMessage(), req.getDescription(false), HttpStatus.NOT_FOUND.getReasonPhrase()); return new ResponseEntity<ExceptionResponse>(exceptionResponse, HttpStatus.NOT_FOUND); } @ExceptionHandler(WeatherNotFoundException.class) public static final ResponseEntity<ExceptionResponse> handleWeatherNotFoundException(WeatherNotFoundException ex, WebRequest req) { ExceptionResponse exceptionResponse = new ExceptionResponse(new Date(), ex.getMessage(), req.getDescription(false), HttpStatus.NOT_FOUND.getReasonPhrase()); return new ResponseEntity<ExceptionResponse>(exceptionResponse, HttpStatus.NOT_FOUND); } @ExceptionHandler(DefaultException.class) public static final ResponseEntity<ExceptionResponse> handleDefaultException(DefaultException ex, WebRequest req) { ExceptionResponse exceptionResponse = new ExceptionResponse(new Date(), ex.getMessage(), req.getDescription(false), HttpStatus.NOT_ACCEPTABLE.getReasonPhrase()); return new ResponseEntity<ExceptionResponse>(exceptionResponse, HttpStatus.NOT_ACCEPTABLE); } // @ExceptionHandler(InvalidAuthentication.class) // public final ResponseEntity<ExceptionResponse> handleInvalidAuthentication(InvalidAuthentication ex, WebRequest req) { // // ExceptionResponse exceptionResponse = new ExceptionResponse(new Date(), ex.getMessage(), // // req.getDescription(false), HttpStatus.UNAUTHORIZED.getReasonPhrase()); // // return new ResponseEntity<ExceptionResponse>(exceptionResponse, HttpStatus.UNAUTHORIZED); // // } // // @ExceptionHandler(UnauthorizedException.class) // public final ResponseEntity<ExceptionResponse> handleUnathorizedException(UnauthorizedException ex, WebRequest req) { // // ExceptionResponse exceptionResponse = new ExceptionResponse(new Date(), ex.getMessage(), // // req.getDescription(false), HttpStatus.FORBIDDEN.getReasonPhrase()); // // return new ResponseEntity<ExceptionResponse>(exceptionResponse, HttpStatus.FORBIDDEN); // // } }
2,934
0.820382
0.820382
73
39.19178
41.585251
132
false
false
0
0
0
0
0
0
1.424658
false
false
6
951704ca1fb58d43e078939f342f619de319f31a
38,723,425,186,611
1730a76946b11b118638bcd520e0f39d9fa4bc1f
/src/com/ss/firstwk/mon/pattern/RunPattern.java
27b241d05fac592c60f28502dbfe3a511ca72380
[]
no_license
lexinelson/SS_Training_Tasks
https://github.com/lexinelson/SS_Training_Tasks
080804472529e351586421b0030226a89b26b564
e771b7e8719ea642856ce7f7d21ec2d1ecba32bb
refs/heads/master
2023-03-23T22:17:09.774000
2021-03-15T21:12:11
2021-03-15T21:12:11
346,065,588
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Week 1 - Day 1 - Pattern Task */ package com.ss.firstwk.mon.pattern; /** * Print Pattern and CenterPattern in Console * @author Lexi Nelson * */ public class RunPattern { /** Main Method - array of patterns then print * @param args */ public static void main(String[] args) { Pattern[] pat = new Pattern[3]; pat[0] = new Pattern(4, 6); pat[1] = new CenterPattern(4); pat[2] = new Pattern(4, false); for (Pattern pattern : pat) { pattern.printPattern(); } } }
UTF-8
Java
499
java
RunPattern.java
Java
[ { "context": "nt Pattern and CenterPattern in Console\n * @author Lexi Nelson\n *\n */\npublic class RunPattern {\n\n\t/** Main Metho", "end": 150, "score": 0.9998452067375183, "start": 139, "tag": "NAME", "value": "Lexi Nelson" } ]
null
[]
/** * Week 1 - Day 1 - Pattern Task */ package com.ss.firstwk.mon.pattern; /** * Print Pattern and CenterPattern in Console * @author <NAME> * */ public class RunPattern { /** Main Method - array of patterns then print * @param args */ public static void main(String[] args) { Pattern[] pat = new Pattern[3]; pat[0] = new Pattern(4, 6); pat[1] = new CenterPattern(4); pat[2] = new Pattern(4, false); for (Pattern pattern : pat) { pattern.printPattern(); } } }
494
0.627254
0.607214
27
17.481482
16.102381
47
false
false
0
0
0
0
0
0
1.111111
false
false
6
8c9b63710b447c1a847d4dd098476b241f155eb5
39,067,022,534,210
56b0ddb9a1de9b0c8401d8779e916b98dfd02a41
/src/main/java/com/pawan/algorithms/dp/done/Bytelandian.java
c4ee07053579f275e55675234fb0e8441fdf60ec
[]
no_license
pawan2087/algorithms
https://github.com/pawan2087/algorithms
4663970bf5fa8f280de3a86e5f4b18ced21faba9
c1052d240e406af2b9ebea9be7fb81dd4fd7a6b5
refs/heads/master
2021-01-19T10:22:34.914000
2017-09-25T14:02:31
2017-09-25T14:02:31
87,856,398
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.pawan.algorithms.dp.done; import java.util.*; /** * Created by pawan.s on 9/11/2017. */ //http://www.spoj.com/problems/COINS/ public class Bytelandian { static Map<Integer, Long> dp = new HashMap<Integer, Long>(); public static void main(String[] args) { int n = 18; System.out.format("The doller price = %d", func(n)); } static long func(int n) { if(n<=0) { return 0; } if(dp.containsKey(n)) { return dp.get(n); } long aux = func(n/2) + func(n/3) + func(n/4); if(aux>n) { dp.put(n, aux); } else { dp.put(n, new Long(n)); } return dp.get(n); } }
UTF-8
Java
723
java
Bytelandian.java
Java
[ { "context": "s.dp.done;\n\nimport java.util.*;\n\n/**\n * Created by pawan.s on 9/11/2017.\n */\n//http://www.spoj.com/problems/", "end": 85, "score": 0.9989514350891113, "start": 78, "tag": "USERNAME", "value": "pawan.s" } ]
null
[]
package com.pawan.algorithms.dp.done; import java.util.*; /** * Created by pawan.s on 9/11/2017. */ //http://www.spoj.com/problems/COINS/ public class Bytelandian { static Map<Integer, Long> dp = new HashMap<Integer, Long>(); public static void main(String[] args) { int n = 18; System.out.format("The doller price = %d", func(n)); } static long func(int n) { if(n<=0) { return 0; } if(dp.containsKey(n)) { return dp.get(n); } long aux = func(n/2) + func(n/3) + func(n/4); if(aux>n) { dp.put(n, aux); } else { dp.put(n, new Long(n)); } return dp.get(n); } }
723
0.496542
0.477178
35
19.657143
17.883659
64
false
false
0
0
0
0
0
0
0.457143
false
false
6
40afcfefd6834ab622183bf9c55284961253290c
37,254,546,353,469
f9d9d2d4c8909ee68e3f3fe5b9344395cdec713d
/ssm/src/main/java/com/hand/util/FormData.java
63373b96630e2a86b595e85a15da072985b0dd86
[]
no_license
Burgges/SSM-Shiro-JsGrid
https://github.com/Burgges/SSM-Shiro-JsGrid
5ce619cf510f7b494605fa8c07f978fe947181d7
f498c90909d1a5dbeb989e8e67bbe44ee919981e
refs/heads/master
2021-08-26T07:29:52.876000
2017-11-22T09:15:56
2017-11-22T09:15:56
111,653,686
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hand.util; import com.hand.model.Permission; import java.util.ArrayList; /** * Created by Nick on 2017/10/10. * */ public class FormData { private ArrayList<Permission> permissions; public ArrayList<Permission> getPermissions() { return permissions; } public void setPermissions(ArrayList<Permission> permissions) { this.permissions = permissions; } }
UTF-8
Java
408
java
FormData.java
Java
[ { "context": "n;\n\nimport java.util.ArrayList;\n\n/**\n * Created by Nick on 2017/10/10.\n *\n */\npublic class FormData {\n ", "end": 110, "score": 0.9804670214653015, "start": 106, "tag": "NAME", "value": "Nick" } ]
null
[]
package com.hand.util; import com.hand.model.Permission; import java.util.ArrayList; /** * Created by Nick on 2017/10/10. * */ public class FormData { private ArrayList<Permission> permissions; public ArrayList<Permission> getPermissions() { return permissions; } public void setPermissions(ArrayList<Permission> permissions) { this.permissions = permissions; } }
408
0.696078
0.676471
21
18.428572
19.901115
67
false
false
0
0
0
0
0
0
0.285714
false
false
6
49b2990a0df755fb914e1a13a4c7fc27e882585e
37,340,445,697,352
c6eb61d60f7616caf0f30555bb6a228506759235
/FmDataReporter/src/commons/bean/DataType.java
3ad543e1ef78a128c1ae3a2e9c726164191da0f6
[]
no_license
clarkccc/connector
https://github.com/clarkccc/connector
205a6e7a32b85085d452b542d7e2fcd63326b142
ab6646e07c916861ec7686a7df1c8e1aced35ae6
refs/heads/master
2016-03-22T13:39:03.698000
2014-09-15T07:18:58
2014-09-15T07:18:58
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package commons.bean; public enum DataType { RTCM2,RTCM3,CMP,NOVATEL,TRIMBLE,LEICA; }
UTF-8
Java
88
java
DataType.java
Java
[]
null
[]
package commons.bean; public enum DataType { RTCM2,RTCM3,CMP,NOVATEL,TRIMBLE,LEICA; }
88
0.772727
0.75
3
28
26.191601
63
false
false
0
0
0
0
0
0
2.333333
false
false
6
80bfeddb2ac58bb2acd848e5179aacc88a43cb21
35,390,530,560,391
1817097e77240c5bc872728e1eeca63833b96ae3
/src/main/java/models/FlashCard.java
272471c3051fb8c80e4a31a9b663e130b45304dc
[]
no_license
gembly278/FlashCards
https://github.com/gembly278/FlashCards
97a83dd983d204a46eb53e4dd5fcdf5bb485169d
ec7d30a3a835be0d6e77abae9ff280f93d3e206a
refs/heads/master
2018-01-14T11:32:19.517000
2017-07-23T04:50:24
2017-07-23T04:50:24
95,513,292
0
0
null
false
2017-06-27T03:26:59
2017-06-27T03:22:34
2017-06-27T03:22:34
2017-06-27T03:26:59
0
0
0
0
null
null
null
package models; /** * Created by Gemma on 2/07/2017. * A Class to contain both sides of a flashcard */ public class FlashCard { private CardSide cardSide = CardSide.LEARNINGLANGUAGE; //Default is the language the user is learning public void flip(){ if(cardSide.getValue() == 0){ cardSide = CardSide.NATIVELANGUAGE; } else { cardSide = CardSide.LEARNINGLANGUAGE; } } public CardSide getCardSide() { return cardSide; } }
UTF-8
Java
503
java
FlashCard.java
Java
[ { "context": "package models;\n\n/**\n * Created by Gemma on 2/07/2017.\n * A Class to contain both sides of", "end": 40, "score": 0.9800585508346558, "start": 35, "tag": "NAME", "value": "Gemma" } ]
null
[]
package models; /** * Created by Gemma on 2/07/2017. * A Class to contain both sides of a flashcard */ public class FlashCard { private CardSide cardSide = CardSide.LEARNINGLANGUAGE; //Default is the language the user is learning public void flip(){ if(cardSide.getValue() == 0){ cardSide = CardSide.NATIVELANGUAGE; } else { cardSide = CardSide.LEARNINGLANGUAGE; } } public CardSide getCardSide() { return cardSide; } }
503
0.624254
0.60835
22
21.863636
24.608379
105
false
false
0
0
0
0
0
0
0.227273
false
false
6
e2179d68e59e3c026a8df6de1c6385233457a726
25,924,422,623,195
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/28/28_9c23710871b148eeb969d7663f014fdcb79834ca/Database/28_9c23710871b148eeb969d7663f014fdcb79834ca_Database_s.java
c52696d0ba92963c38ddeb40d5251aeb031fba31
[]
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
/* * Copyright 2011 Brian S O'Neill * * 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.cojen.tupl; import java.io.Closeable; import java.io.File; import java.io.FileNotFoundException; import java.io.InterruptedIOException; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.concurrent.locks.Lock; import static org.cojen.tupl.Node.*; /** * * * @author Brian S O'Neill */ public final class Database implements Closeable { private static final int DEFAULT_CACHED_NODES = 1000; private static final int ENCODING_VERSION = 20111111; private static final int I_ENCODING_VERSION = 0; private static final int I_ROOT_PAGE_ID = I_ENCODING_VERSION + 4; private static final int I_TRANSACTION_ID = I_ROOT_PAGE_ID + 8; private static final int I_REDO_LOG_ID = I_TRANSACTION_ID + 8; private static final int HEADER_SIZE = I_REDO_LOG_ID + 8; private static final byte KEY_TYPE_INDEX_NAME = 0; private static final byte KEY_TYPE_INDEX_ID = 1; private static final int REGISTRY_ID = 0, REGISTRY_KEY_MAP_ID = 1, MAX_RESERVED_ID = 255; final DurabilityMode mDurabilityMode; final long mDefaultLockTimeoutNanos; final LockManager mLockManager; final RedoLog mRedoLog; final PageStore mPageStore; private final BufferPool mSpareBufferPool; private final Latch mCacheLatch; private final int mMaxCachedNodeCount; private int mCachedNodeCount; private Node mMostRecentlyUsed; private Node mLeastRecentlyUsed; private final Lock mSharedCommitLock; // Is either CACHED_DIRTY_0 or CACHED_DIRTY_1. Access is guarded by commit lock. private byte mCommitState; // The root tree, which maps tree ids to other tree root node ids. private final Tree mRegistry; // Maps tree name keys to ids. private final Tree mRegistryKeyMap; // Maps tree names to open trees. private final Map<byte[], Tree> mOpenTrees; private final Map<Long, Tree> mOpenTreesById; private final Object mTxnIdLock = new Object(); // The following fields are guarded by mTxnIdLock. private long mTxnId; private UndoLog mTopUndoLog; private final Object mCheckpointLock = new Object(); public static Database open(DatabaseConfig config) throws IOException { return new Database(config); } private Database(DatabaseConfig config) throws IOException { File baseFile = config.mBaseFile; if (baseFile == null) { throw new IllegalArgumentException("No base file provided"); } if (baseFile.isDirectory()) { throw new IllegalArgumentException("Base file is a directory: " + baseFile); } int minCache = config.mMinCache; int maxCache = config.mMaxCache; if (maxCache == 0) { maxCache = minCache; if (maxCache == 0) { minCache = maxCache = DEFAULT_CACHED_NODES; } } if (minCache > maxCache) { throw new IllegalArgumentException ("Minimum cached node count exceeds maximum count: " + minCache + " > " + maxCache); } if (maxCache < 3) { // One is needed for the root node, and at least two nodes are // required for eviction code to function correctly. It always // assumes that the least recently used node points to a valid, // more recently used node. throw new IllegalArgumentException ("Maximum cached node count is too small: " + maxCache); } mCacheLatch = new Latch(); mMaxCachedNodeCount = maxCache - 1; // less one for root mDurabilityMode = config.mDurabilityMode; mDefaultLockTimeoutNanos = config.mLockTimeoutNanos; mLockManager = new LockManager(mDefaultLockTimeoutNanos); String basePath = baseFile.getPath(); File file0 = new File(basePath + ".db.0"); File file1 = new File(basePath + ".db.1"); if (config.mPageSize <= 0) { mPageStore = new DualFilePageStore(file0, file1, config.mReadOnly); } else { mPageStore = new DualFilePageStore(file0, file1, config.mReadOnly, config.mPageSize); } try { int spareBufferCount = Runtime.getRuntime().availableProcessors(); mSpareBufferPool = new BufferPool(mPageStore.pageSize(), spareBufferCount); mSharedCommitLock = mPageStore.sharedCommitLock(); mSharedCommitLock.lock(); try { mCommitState = CACHED_DIRTY_0; } finally { mSharedCommitLock.unlock(); } byte[] header = new byte[HEADER_SIZE]; mPageStore.readExtraCommitData(header); mRegistry = new Tree(this, REGISTRY_ID, null, null, loadRegistryRoot(header)); mOpenTrees = new TreeMap<byte[], Tree>(KeyComparator.THE); mOpenTreesById = new HashMap<Long, Tree>(); synchronized (mTxnIdLock) { mTxnId = DataIO.readLong(header, I_TRANSACTION_ID); } long redoLogId = DataIO.readLong(header, I_REDO_LOG_ID); // Initialized, but not open yet. mRedoLog = new RedoLog(baseFile, redoLogId); // Pre-allocate nodes. They are automatically added to the usage // list, and so nothing special needs to be done to allow them to // get used. Since the initial state is clean, evicting these nodes // does nothing. try { for (int i=minCache; --i>0; ) { // less one for root allocLatchedNode().releaseExclusive(); } } catch (OutOfMemoryError e) { mMostRecentlyUsed = null; mLeastRecentlyUsed = null; throw new OutOfMemoryError ("Unable to allocate the minimum required number of cached nodes: " + minCache); } // Open mRegistryKeyMap. { byte[] encodedRootId = mRegistry.get(Transaction.BOGUS, Utils.EMPTY_BYTES); Node rootNode; if (encodedRootId == null) { // Create a new empty leaf node. rootNode = new Node(mPageStore.pageSize(), true); } else { rootNode = new Node(mPageStore.pageSize(), false); rootNode.read(this, DataIO.readLong(encodedRootId, 0)); } mRegistryKeyMap = new Tree (this, REGISTRY_KEY_MAP_ID, Utils.EMPTY_BYTES, null, rootNode); } if (redoReplay()) { // Make sure old redo log is deleted. Process might have exited // before last checkpoint could delete it. mRedoLog.deleteOldFile(redoLogId - 1); // Checkpoint now to ensure all old redo log entries are durable. checkpoint(true); if (mRedoLog.isReplayMode()) { // Last checkpoint was interrupted, so apply next log file too. redoReplay(); checkpoint(true); } } } catch (Throwable e) { try { close(); } catch (IOException e2) { // Ignore. } throw Utils.rethrow(e); } } private boolean redoReplay() throws IOException { long redoTxnId = mRedoLog.replay(this); if (redoTxnId == 0) { return false; } synchronized (mTxnIdLock) { // Subtract for modulo comparison. if (mTxnId == 0 || (redoTxnId - mTxnId) > 0) { mTxnId = redoTxnId; } } return true; } /** * Returns the given named index, creating it if necessary. */ public Index openIndex(byte[] name) throws IOException { return openIndex(name.clone(), true); } /** * Returns the given named index, creating it if necessary. Name is UTF-8 * encoded. */ public Index openIndex(String name) throws IOException { return openIndex(name.getBytes("UTF-8"), true); } public Transaction newTransaction() { return doNewTransaction(mDurabilityMode); } public Transaction newTransaction(DurabilityMode durabilityMode) { return doNewTransaction(durabilityMode == null ? mDurabilityMode : durabilityMode); } private Transaction doNewTransaction(DurabilityMode durabilityMode) { return new Transaction (this, durabilityMode, LockMode.UPGRADABLE_READ, mDefaultLockTimeoutNanos); } /** * Caller must hold commit lock. This ensures that highest transaction id * is persisted correctly by checkpoint. * * @param txnId pass zero to select a transaction id * @return non-zero transaction id */ long register(UndoLog undo, long txnId) { synchronized (mTxnIdLock) { UndoLog top = mTopUndoLog; if (top != null) { undo.mPrev = top; top.mNext = undo; } mTopUndoLog = undo; while (txnId == 0) { txnId = ++mTxnId; } return txnId; } } /** * Caller must hold commit lock. This ensures that highest transaction id * is persisted correctly by checkpoint. * * @return non-zero transaction id */ long nextTransactionId() { long txnId; do { synchronized (mTxnIdLock) { txnId = ++mTxnId; } } while (txnId == 0); return txnId; } void unregister(UndoLog log) { synchronized (mTxnIdLock) { UndoLog prev = log.mPrev; UndoLog next = log.mNext; if (prev != null) { prev.mNext = next; // Keep previous link, to allow concurrent commit to follow // links of detached UndoLogs. //log.mPrev = null; } if (next != null) { next.mPrev = prev; log.mNext = null; } else if (log == mTopUndoLog) { mTopUndoLog = prev; } } } /** * Returns an index by its identifier, returning null if not found. * * @throws IllegalArgumentException if id is zero */ public Index indexById(long id) throws IOException { if (id >= REGISTRY_ID && id <= MAX_RESERVED_ID) { throw new IllegalArgumentException("Invalid id: " + id); } Index index; final Lock commitLock = sharedCommitLock(); commitLock.lock(); try { synchronized (mOpenTrees) { Tree tree = mOpenTreesById.get(id); if (tree != null) { return tree; } } byte[] idKey = new byte[9]; idKey[0] = KEY_TYPE_INDEX_ID; DataIO.writeLong(idKey, 1, id); byte[] name = mRegistryKeyMap.get(null, idKey); if (name == null) { return null; } index = openIndex(name, false); } catch (Throwable e) { throw Utils.closeOnFailure(this, e); } finally { commitLock.unlock(); } if (index == null) { // Registry needs to be repaired to fix this. throw new DatabaseException("Unable to find index in registry"); } return index; } /** * Allows access to internal indexes which can use the redo log. */ Index anyIndexById(long id) throws IOException { if (id == REGISTRY_KEY_MAP_ID) { return mRegistryKeyMap; } return indexById(id); } /** * Preallocates pages for use later. */ public void preallocate(long bytes) throws IOException { int pageSize = pageSize(); long pageCount = (bytes + pageSize - 1) / pageSize; if (pageCount <= 0) { return; } // Assume DualFilePageStore is in use, so preallocate over two commits. long firstCount = pageCount / 2; pageCount -= firstCount; final byte firstCommitState; mPageStore.sharedCommitLock().lock(); try { firstCommitState = mCommitState; mPageStore.preallocate(firstCount); } finally { mPageStore.sharedCommitLock().unlock(); } checkpoint(true); if (pageCount <= 0) { return; } mPageStore.sharedCommitLock().lock(); try { while (mCommitState == firstCommitState) { // Another commit snuck in. Upgradable lock is not used, so // unlock, commit and retry. mPageStore.sharedCommitLock().unlock(); checkpoint(true); mPageStore.sharedCommitLock().lock(); } mPageStore.preallocate(pageCount); } finally { mPageStore.sharedCommitLock().unlock(); } checkpoint(true); } /** * Flushes, but does not sync, all non-flushed transactions. Transactions * committed with {@link DurabilityMode#NO_FLUSH no-flush} effectively * become {@link DurabilityMode#NO_SYNC no-sync} durable. */ public void flush() throws IOException { mRedoLog.flush(); } /** * Persists all non-flushed and non-sync'd transactions. Transactions * committed with {@link DurabilityMode#NO_FLUSH no-flush} and {@link * DurabilityMode#NO_SYNC no-sync} effectively become {@link * DurabilityMode#SYNC sync} durable. */ public void sync() throws IOException { mRedoLog.sync(); } /** * Durably sync and checkpoint all changes to the database. In addition to * ensuring that all transactions are durable, checkpointing ensures that * non-transactional modifications are durable. */ public void checkpoint() throws IOException { checkpoint(false); } /** * Closes the database, ensuring durability of committed transactions. No * checkpoint is performed by this method, and so non-transactional * modifications can be lost. */ @Override public void close() throws IOException { if (mRedoLog != null) { mRedoLog.close(); } if (mPageStore != null) { mPageStore.close(); } } /** * Loads the root registry node, or creates one if store is new. Root node * is not eligible for eviction. */ private Node loadRegistryRoot(byte[] header) throws IOException { int version = DataIO.readInt(header, I_ENCODING_VERSION); if (version != 0) { if (version != ENCODING_VERSION) { throw new CorruptPageStoreException("Unknown encoding version: " + version); } long rootId = DataIO.readLong(header, I_ROOT_PAGE_ID); if (rootId != 0) { Node root = new Node(pageSize(), false); root.read(this, rootId); return root; } } // Assume store is new and return a new empty leaf node. return new Node(pageSize(), true); } private Index openIndex(byte[] name, boolean create) throws IOException { final Lock commitLock = sharedCommitLock(); commitLock.lock(); try { synchronized (mOpenTrees) { Tree tree = mOpenTrees.get(name); if (tree != null) { return tree; } } byte[] nameKey = newKey(KEY_TYPE_INDEX_NAME, name); byte[] treeIdBytes = mRegistryKeyMap.get(null, nameKey); long treeId; if (treeIdBytes != null) { treeId = DataIO.readLong(treeIdBytes, 0); } else if (!create) { return null; } else synchronized (mOpenTrees) { treeIdBytes = mRegistryKeyMap.get(null, nameKey); if (treeIdBytes != null) { treeId = DataIO.readLong(treeIdBytes, 0); } else { treeIdBytes = new byte[8]; do { treeId = Utils.randomId(REGISTRY_ID, MAX_RESERVED_ID); DataIO.writeLong(treeIdBytes, 0, treeId); } while (!mRegistry.insert(Transaction.BOGUS, treeIdBytes, Utils.EMPTY_BYTES)); if (!mRegistryKeyMap.insert(null, nameKey, treeIdBytes)) { mRegistry.delete(Transaction.BOGUS, treeIdBytes); throw new DatabaseException("Unable to insert index name"); } byte[] idKey = newKey(KEY_TYPE_INDEX_ID, treeIdBytes); if (!mRegistryKeyMap.insert(null, idKey, name)) { mRegistryKeyMap.delete(null, nameKey); mRegistry.delete(Transaction.BOGUS, treeIdBytes); throw new DatabaseException("Unable to insert index id"); } } } byte[] encodedRootId = mRegistry.get(Transaction.BOGUS, treeIdBytes); Node rootNode; if (encodedRootId == null || encodedRootId.length == 0) { // Create a new empty leaf node. rootNode = new Node(pageSize(), true); } else { rootNode = new Node(pageSize(), false); rootNode.read(this, DataIO.readLong(encodedRootId, 0)); } synchronized (mOpenTrees) { Tree tree = mOpenTrees.get(name); if (tree == null) { tree = new Tree(this, treeId, treeIdBytes, name, rootNode); mOpenTrees.put(name, tree); mOpenTreesById.put(treeId, tree); } return tree; } } catch (Throwable e) { throw Utils.closeOnFailure(this, e); } finally { commitLock.unlock(); } } private static byte[] newKey(byte type, byte[] payload) { byte[] key = new byte[1 + payload.length]; key[0] = type; System.arraycopy(payload, 0, key, 1, payload.length); return key; } /** * Returns the fixed size of all pages in the store, in bytes. */ int pageSize() { return mPageStore.pageSize(); } /** * Access the shared commit lock, which prevents commits while held. */ Lock sharedCommitLock() { return mSharedCommitLock; } /** * Returns a new or recycled Node instance, latched exclusively, with an id * of zero and a clean state. */ Node allocLatchedNode() throws IOException { mCacheLatch.acquireExclusiveUnfair(); try { int max = mMaxCachedNodeCount; if (mCachedNodeCount < max) { Node node = new Node(pageSize(), false); node.acquireExclusiveUnfair(); mCachedNodeCount++; if ((node.mLessUsed = mMostRecentlyUsed) == null) { mLeastRecentlyUsed = node; } else { mMostRecentlyUsed.mMoreUsed = node; } mMostRecentlyUsed = node; return node; } do { Node node = mLeastRecentlyUsed; (mLeastRecentlyUsed = node.mMoreUsed).mLessUsed = null; node.mMoreUsed = null; (node.mLessUsed = mMostRecentlyUsed).mMoreUsed = node; mMostRecentlyUsed = node; if (node.tryAcquireExclusiveUnfair()) { if (node.evict(this)) { // Return with latch still held. return node; } else { node.releaseExclusive(); } } } while (--max > 0); } finally { mCacheLatch.releaseExclusive(); } // FIXME: Throw a better exception. Also, try all nodes again, but with // stronger latch request before giving up. throw new IllegalStateException("Cache is full"); } /** * Returns a new reserved node, latched exclusively and marked dirty. Caller * must hold commit lock. */ Node newDirtyNode() throws IOException { Node node = allocLatchedNode(); node.mId = mPageStore.reservePage(); node.mCachedState = mCommitState; return node; } /** * Caller must hold commit lock and any latch on node. */ boolean shouldMarkDirty(Node node) { return node.mCachedState != mCommitState && node.mId != Node.STUB_ID; } /** * Caller must hold commit lock and exclusive latch on node. Method does * nothing if node is already dirty. Latch is never released by this method, * even if an exception is thrown. * * @return true if just made dirty and id changed */ boolean markDirty(Tree tree, Node node) throws IOException { if (node.mCachedState == mCommitState || node.mId == Node.STUB_ID) { return false; } else { doMarkDirty(tree, node); return true; } } /** * Caller must hold commit lock and exclusive latch on node. Method does * nothing if node is already dirty. Latch is never released by this method, * even if an exception is thrown. */ void markUndoLogDirty(Node node) throws IOException { if (node.mCachedState != mCommitState) { long oldId = node.mId; long newId = mPageStore.reservePage(); mPageStore.deletePage(oldId); node.write(this); node.mId = newId; node.mCachedState = mCommitState; } } /** * Caller must hold commit lock and exclusive latch on node. Method must * not be called if node is already dirty. Latch is never released by this * method, even if an exception is thrown. */ void doMarkDirty(Tree tree, Node node) throws IOException { long oldId = node.mId; long newId = mPageStore.reservePage(); if (oldId != 0) { mPageStore.deletePage(oldId); } if (node.mCachedState != CACHED_CLEAN) { node.write(this); } if (node == tree.mRoot && tree.mIdBytes != null) { byte[] newEncodedId = new byte[8]; DataIO.writeLong(newEncodedId, 0, newId); mRegistry.store(Transaction.BOGUS, tree.mIdBytes, newEncodedId); } node.mId = newId; node.mCachedState = mCommitState; } /** * Similar to markDirty method except no new page is reserved, and old page * is not immediately deleted. Caller must hold commit lock and exclusive * latch on node. Latch is never released by this method, even if an * exception is thrown. */ void prepareToDelete(Node node) throws IOException { // Hello. My name is igo Montoya. You killed my father. Prepare to die. byte state = node.mCachedState; if (state != CACHED_CLEAN && state != mCommitState) { node.write(this); } } /** * Caller must hold commit lock and exclusive latch on node. Latch is * never released by this method, even if an exception is thrown. */ void deleteNode(Node node) throws IOException { deletePage(node.mId, node.mCachedState); node.mId = 0; // FIXME: child node array should be recycled node.mChildNodes = null; // When node is re-allocated, it will be evicted. Ensure that eviction // doesn't write anything. node.mCachedState = CACHED_CLEAN; // Indicate that node is least recently used, allowing it to be // re-allocated immediately without evicting another node. mCacheLatch.acquireExclusiveUnfair(); try { Node lessUsed = node.mLessUsed; if (lessUsed != null) { Node moreUsed = node.mMoreUsed; if ((lessUsed.mMoreUsed = moreUsed) == null) { mMostRecentlyUsed = lessUsed; } else { moreUsed.mLessUsed = lessUsed; } node.mLessUsed = null; (node.mMoreUsed = mLeastRecentlyUsed).mLessUsed = node; mLeastRecentlyUsed = node; } } finally { mCacheLatch.releaseExclusive(); } } /** * Caller must hold commit lock. */ void deletePage(long id, int cachedState) throws IOException { if (id != 0) { if (cachedState == mCommitState) { // Newly reserved page was never used, so recycle it. mPageStore.recyclePage(id); } else { // Old data must survive until after checkpoint. mPageStore.deletePage(id); } } } /** * Indicate that non-root node is most recently used. Root node is not * managed in usage list and cannot be evicted. */ void used(Node node) { // Because this method can be a bottleneck, don't wait for exclusive // latch. If node is popular, it will get more chances to be identified // as most recently used. This strategy works well enough because cache // eviction is always a best-guess approach. if (mCacheLatch.tryAcquireExclusiveUnfair()) { Node moreUsed = node.mMoreUsed; if (moreUsed != null) { Node lessUsed = node.mLessUsed; if ((moreUsed.mLessUsed = lessUsed) == null) { mLeastRecentlyUsed = moreUsed; } else { lessUsed.mMoreUsed = moreUsed; } node.mMoreUsed = null; (node.mLessUsed = mMostRecentlyUsed).mMoreUsed = node; mMostRecentlyUsed = node; } mCacheLatch.releaseExclusive(); } } byte[] removeSpareBuffer() throws InterruptedIOException { return mSpareBufferPool.remove(); } void addSpareBuffer(byte[] buffer) { mSpareBufferPool.add(buffer); } void readPage(long id, byte[] page) throws IOException { mPageStore.readPage(id, page); } void writeReservedPage(long id, byte[] page) throws IOException { mPageStore.writeReservedPage(id, page); } private void checkpoint(boolean force) throws IOException { // Checkpoint lock ensures consistent state between page store and logs. synchronized (mCheckpointLock) { final Node root = mRegistry.mRoot; // Commit lock must be acquired first, to prevent deadlock. mPageStore.exclusiveCommitLock().lock(); root.acquireSharedUnfair(); if (!force && root.mCachedState == CACHED_CLEAN) { // Root is clean, so nothing to do. root.releaseShared(); mPageStore.exclusiveCommitLock().unlock(); return; } final long redoLogId; try { redoLogId = mRedoLog.openNewFile(); } catch (IOException e) { root.releaseShared(); mPageStore.exclusiveCommitLock().unlock(); throw e; } mPageStore.commit(new PageStore.CommitCallback() { @Override public byte[] prepare() throws IOException { return flush(redoLogId); } }); // Note: The delete step can get skipped if process exits at this // point. File is deleted again when database is re-opened. mRedoLog.deleteOldFile(redoLogId); } } /** * Method is invoked with exclusive commit lock and shared root node latch held. */ private byte[] flush(final long redoLogId) throws IOException { // Snapshot of all open trees. Tree[] trees; synchronized (mOpenTrees) { trees = mOpenTrees.values().toArray(new Tree[mOpenTrees.size()]); } final long txnId = mTxnId.get(); /* FIXME: This code does not properly account for concurrent splits. Dirty nodes might not get written into the commit, and this has also been observed: java.lang.AssertionError: Split child is not already marked dirty at org.cojen.tupl.TreeNode.insertSplitChildRef(TreeNode.java:1178) at org.cojen.tupl.TreeCursor.finishSplit(TreeCursor.java:1647) at org.cojen.tupl.TreeCursor.finishSplit(TreeCursor.java:1640) at org.cojen.tupl.TreeCursor.store(TreeCursor.java:969) at org.cojen.tupl.TreeCursor.store(TreeCursor.java:746) at org.cojen.tupl.FullCursor.store(FullCursor.java:114) at org.cojen.tupl.TreeNodeTest.testInsert(TreeNodeTest.java:135) at org.cojen.tupl.TreeNodeTest.main(TreeNodeTest.java:107) A cursor based approach instead of breadth-first traversal might help. */ final Node root = mRegistry.mRoot; final long rootId = root.mId; final int stateToFlush = mCommitState; mCommitState = (byte) (CACHED_DIRTY_0 + ((stateToFlush - CACHED_DIRTY_0) ^ 1)); mPageStore.exclusiveCommitLock().unlock(); // Gather all nodes to flush. List<DirtyNode> dirtyList = new ArrayList<DirtyNode>(Math.min(1000, mMaxCachedNodeCount)); mRegistry.gatherDirtyNodes(dirtyList, stateToFlush); mRegistryKeyMap.mRoot.acquireSharedUnfair(); mRegistryKeyMap.gatherDirtyNodes(dirtyList, stateToFlush); for (Tree tree : trees) { tree.mRoot.acquireSharedUnfair(); tree.gatherDirtyNodes(dirtyList, stateToFlush); } // Sort nodes by id, which helps make writes more sequentially ordered. Collections.sort(dirtyList); // Now write out all the dirty nodes. Some of them will have already // been concurrently written out, so check again. for (int mi=0; mi<dirtyList.size(); mi++) { Node node = dirtyList.get(mi).mNode; dirtyList.set(mi, null); node.acquireExclusiveUnfair(); if (node.mCachedState != stateToFlush) { // Was already evicted. node.releaseExclusive(); } else { node.mCachedState = CACHED_CLEAN; node.downgrade(); try { node.write(this); } finally { node.releaseShared(); } } } byte[] header = new byte[HEADER_SIZE]; DataIO.writeInt(header, I_ENCODING_VERSION, ENCODING_VERSION); DataIO.writeLong(header, I_ROOT_PAGE_ID, rootId); DataIO.writeLong(header, I_TRANSACTION_ID, txnId); // Add one to redoLogId, indicating the active log id. DataIO.writeLong(header, I_REDO_LOG_ID, redoLogId + 1); return header; } }
UTF-8
Java
34,271
java
28_9c23710871b148eeb969d7663f014fdcb79834ca_Database_s.java
Java
[ { "context": " /*\r\n * Copyright 2011 Brian S O'Neill\r\n *\r\n * Licensed under the Apache License, Ver", "end": 40, "score": 0.9998690485954285, "start": 25, "tag": "NAME", "value": "Brian S O'Neill" }, { "context": "ojen.tupl.Node.*;\r\n \r\n /**\r\n * \r\n *\r\n * @autho...
null
[]
/* * Copyright 2011 <NAME> * * 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.cojen.tupl; import java.io.Closeable; import java.io.File; import java.io.FileNotFoundException; import java.io.InterruptedIOException; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.concurrent.locks.Lock; import static org.cojen.tupl.Node.*; /** * * * @author <NAME> */ public final class Database implements Closeable { private static final int DEFAULT_CACHED_NODES = 1000; private static final int ENCODING_VERSION = 20111111; private static final int I_ENCODING_VERSION = 0; private static final int I_ROOT_PAGE_ID = I_ENCODING_VERSION + 4; private static final int I_TRANSACTION_ID = I_ROOT_PAGE_ID + 8; private static final int I_REDO_LOG_ID = I_TRANSACTION_ID + 8; private static final int HEADER_SIZE = I_REDO_LOG_ID + 8; private static final byte KEY_TYPE_INDEX_NAME = 0; private static final byte KEY_TYPE_INDEX_ID = 1; private static final int REGISTRY_ID = 0, REGISTRY_KEY_MAP_ID = 1, MAX_RESERVED_ID = 255; final DurabilityMode mDurabilityMode; final long mDefaultLockTimeoutNanos; final LockManager mLockManager; final RedoLog mRedoLog; final PageStore mPageStore; private final BufferPool mSpareBufferPool; private final Latch mCacheLatch; private final int mMaxCachedNodeCount; private int mCachedNodeCount; private Node mMostRecentlyUsed; private Node mLeastRecentlyUsed; private final Lock mSharedCommitLock; // Is either CACHED_DIRTY_0 or CACHED_DIRTY_1. Access is guarded by commit lock. private byte mCommitState; // The root tree, which maps tree ids to other tree root node ids. private final Tree mRegistry; // Maps tree name keys to ids. private final Tree mRegistryKeyMap; // Maps tree names to open trees. private final Map<byte[], Tree> mOpenTrees; private final Map<Long, Tree> mOpenTreesById; private final Object mTxnIdLock = new Object(); // The following fields are guarded by mTxnIdLock. private long mTxnId; private UndoLog mTopUndoLog; private final Object mCheckpointLock = new Object(); public static Database open(DatabaseConfig config) throws IOException { return new Database(config); } private Database(DatabaseConfig config) throws IOException { File baseFile = config.mBaseFile; if (baseFile == null) { throw new IllegalArgumentException("No base file provided"); } if (baseFile.isDirectory()) { throw new IllegalArgumentException("Base file is a directory: " + baseFile); } int minCache = config.mMinCache; int maxCache = config.mMaxCache; if (maxCache == 0) { maxCache = minCache; if (maxCache == 0) { minCache = maxCache = DEFAULT_CACHED_NODES; } } if (minCache > maxCache) { throw new IllegalArgumentException ("Minimum cached node count exceeds maximum count: " + minCache + " > " + maxCache); } if (maxCache < 3) { // One is needed for the root node, and at least two nodes are // required for eviction code to function correctly. It always // assumes that the least recently used node points to a valid, // more recently used node. throw new IllegalArgumentException ("Maximum cached node count is too small: " + maxCache); } mCacheLatch = new Latch(); mMaxCachedNodeCount = maxCache - 1; // less one for root mDurabilityMode = config.mDurabilityMode; mDefaultLockTimeoutNanos = config.mLockTimeoutNanos; mLockManager = new LockManager(mDefaultLockTimeoutNanos); String basePath = baseFile.getPath(); File file0 = new File(basePath + ".db.0"); File file1 = new File(basePath + ".db.1"); if (config.mPageSize <= 0) { mPageStore = new DualFilePageStore(file0, file1, config.mReadOnly); } else { mPageStore = new DualFilePageStore(file0, file1, config.mReadOnly, config.mPageSize); } try { int spareBufferCount = Runtime.getRuntime().availableProcessors(); mSpareBufferPool = new BufferPool(mPageStore.pageSize(), spareBufferCount); mSharedCommitLock = mPageStore.sharedCommitLock(); mSharedCommitLock.lock(); try { mCommitState = CACHED_DIRTY_0; } finally { mSharedCommitLock.unlock(); } byte[] header = new byte[HEADER_SIZE]; mPageStore.readExtraCommitData(header); mRegistry = new Tree(this, REGISTRY_ID, null, null, loadRegistryRoot(header)); mOpenTrees = new TreeMap<byte[], Tree>(KeyComparator.THE); mOpenTreesById = new HashMap<Long, Tree>(); synchronized (mTxnIdLock) { mTxnId = DataIO.readLong(header, I_TRANSACTION_ID); } long redoLogId = DataIO.readLong(header, I_REDO_LOG_ID); // Initialized, but not open yet. mRedoLog = new RedoLog(baseFile, redoLogId); // Pre-allocate nodes. They are automatically added to the usage // list, and so nothing special needs to be done to allow them to // get used. Since the initial state is clean, evicting these nodes // does nothing. try { for (int i=minCache; --i>0; ) { // less one for root allocLatchedNode().releaseExclusive(); } } catch (OutOfMemoryError e) { mMostRecentlyUsed = null; mLeastRecentlyUsed = null; throw new OutOfMemoryError ("Unable to allocate the minimum required number of cached nodes: " + minCache); } // Open mRegistryKeyMap. { byte[] encodedRootId = mRegistry.get(Transaction.BOGUS, Utils.EMPTY_BYTES); Node rootNode; if (encodedRootId == null) { // Create a new empty leaf node. rootNode = new Node(mPageStore.pageSize(), true); } else { rootNode = new Node(mPageStore.pageSize(), false); rootNode.read(this, DataIO.readLong(encodedRootId, 0)); } mRegistryKeyMap = new Tree (this, REGISTRY_KEY_MAP_ID, Utils.EMPTY_BYTES, null, rootNode); } if (redoReplay()) { // Make sure old redo log is deleted. Process might have exited // before last checkpoint could delete it. mRedoLog.deleteOldFile(redoLogId - 1); // Checkpoint now to ensure all old redo log entries are durable. checkpoint(true); if (mRedoLog.isReplayMode()) { // Last checkpoint was interrupted, so apply next log file too. redoReplay(); checkpoint(true); } } } catch (Throwable e) { try { close(); } catch (IOException e2) { // Ignore. } throw Utils.rethrow(e); } } private boolean redoReplay() throws IOException { long redoTxnId = mRedoLog.replay(this); if (redoTxnId == 0) { return false; } synchronized (mTxnIdLock) { // Subtract for modulo comparison. if (mTxnId == 0 || (redoTxnId - mTxnId) > 0) { mTxnId = redoTxnId; } } return true; } /** * Returns the given named index, creating it if necessary. */ public Index openIndex(byte[] name) throws IOException { return openIndex(name.clone(), true); } /** * Returns the given named index, creating it if necessary. Name is UTF-8 * encoded. */ public Index openIndex(String name) throws IOException { return openIndex(name.getBytes("UTF-8"), true); } public Transaction newTransaction() { return doNewTransaction(mDurabilityMode); } public Transaction newTransaction(DurabilityMode durabilityMode) { return doNewTransaction(durabilityMode == null ? mDurabilityMode : durabilityMode); } private Transaction doNewTransaction(DurabilityMode durabilityMode) { return new Transaction (this, durabilityMode, LockMode.UPGRADABLE_READ, mDefaultLockTimeoutNanos); } /** * Caller must hold commit lock. This ensures that highest transaction id * is persisted correctly by checkpoint. * * @param txnId pass zero to select a transaction id * @return non-zero transaction id */ long register(UndoLog undo, long txnId) { synchronized (mTxnIdLock) { UndoLog top = mTopUndoLog; if (top != null) { undo.mPrev = top; top.mNext = undo; } mTopUndoLog = undo; while (txnId == 0) { txnId = ++mTxnId; } return txnId; } } /** * Caller must hold commit lock. This ensures that highest transaction id * is persisted correctly by checkpoint. * * @return non-zero transaction id */ long nextTransactionId() { long txnId; do { synchronized (mTxnIdLock) { txnId = ++mTxnId; } } while (txnId == 0); return txnId; } void unregister(UndoLog log) { synchronized (mTxnIdLock) { UndoLog prev = log.mPrev; UndoLog next = log.mNext; if (prev != null) { prev.mNext = next; // Keep previous link, to allow concurrent commit to follow // links of detached UndoLogs. //log.mPrev = null; } if (next != null) { next.mPrev = prev; log.mNext = null; } else if (log == mTopUndoLog) { mTopUndoLog = prev; } } } /** * Returns an index by its identifier, returning null if not found. * * @throws IllegalArgumentException if id is zero */ public Index indexById(long id) throws IOException { if (id >= REGISTRY_ID && id <= MAX_RESERVED_ID) { throw new IllegalArgumentException("Invalid id: " + id); } Index index; final Lock commitLock = sharedCommitLock(); commitLock.lock(); try { synchronized (mOpenTrees) { Tree tree = mOpenTreesById.get(id); if (tree != null) { return tree; } } byte[] idKey = new byte[9]; idKey[0] = KEY_TYPE_INDEX_ID; DataIO.writeLong(idKey, 1, id); byte[] name = mRegistryKeyMap.get(null, idKey); if (name == null) { return null; } index = openIndex(name, false); } catch (Throwable e) { throw Utils.closeOnFailure(this, e); } finally { commitLock.unlock(); } if (index == null) { // Registry needs to be repaired to fix this. throw new DatabaseException("Unable to find index in registry"); } return index; } /** * Allows access to internal indexes which can use the redo log. */ Index anyIndexById(long id) throws IOException { if (id == REGISTRY_KEY_MAP_ID) { return mRegistryKeyMap; } return indexById(id); } /** * Preallocates pages for use later. */ public void preallocate(long bytes) throws IOException { int pageSize = pageSize(); long pageCount = (bytes + pageSize - 1) / pageSize; if (pageCount <= 0) { return; } // Assume DualFilePageStore is in use, so preallocate over two commits. long firstCount = pageCount / 2; pageCount -= firstCount; final byte firstCommitState; mPageStore.sharedCommitLock().lock(); try { firstCommitState = mCommitState; mPageStore.preallocate(firstCount); } finally { mPageStore.sharedCommitLock().unlock(); } checkpoint(true); if (pageCount <= 0) { return; } mPageStore.sharedCommitLock().lock(); try { while (mCommitState == firstCommitState) { // Another commit snuck in. Upgradable lock is not used, so // unlock, commit and retry. mPageStore.sharedCommitLock().unlock(); checkpoint(true); mPageStore.sharedCommitLock().lock(); } mPageStore.preallocate(pageCount); } finally { mPageStore.sharedCommitLock().unlock(); } checkpoint(true); } /** * Flushes, but does not sync, all non-flushed transactions. Transactions * committed with {@link DurabilityMode#NO_FLUSH no-flush} effectively * become {@link DurabilityMode#NO_SYNC no-sync} durable. */ public void flush() throws IOException { mRedoLog.flush(); } /** * Persists all non-flushed and non-sync'd transactions. Transactions * committed with {@link DurabilityMode#NO_FLUSH no-flush} and {@link * DurabilityMode#NO_SYNC no-sync} effectively become {@link * DurabilityMode#SYNC sync} durable. */ public void sync() throws IOException { mRedoLog.sync(); } /** * Durably sync and checkpoint all changes to the database. In addition to * ensuring that all transactions are durable, checkpointing ensures that * non-transactional modifications are durable. */ public void checkpoint() throws IOException { checkpoint(false); } /** * Closes the database, ensuring durability of committed transactions. No * checkpoint is performed by this method, and so non-transactional * modifications can be lost. */ @Override public void close() throws IOException { if (mRedoLog != null) { mRedoLog.close(); } if (mPageStore != null) { mPageStore.close(); } } /** * Loads the root registry node, or creates one if store is new. Root node * is not eligible for eviction. */ private Node loadRegistryRoot(byte[] header) throws IOException { int version = DataIO.readInt(header, I_ENCODING_VERSION); if (version != 0) { if (version != ENCODING_VERSION) { throw new CorruptPageStoreException("Unknown encoding version: " + version); } long rootId = DataIO.readLong(header, I_ROOT_PAGE_ID); if (rootId != 0) { Node root = new Node(pageSize(), false); root.read(this, rootId); return root; } } // Assume store is new and return a new empty leaf node. return new Node(pageSize(), true); } private Index openIndex(byte[] name, boolean create) throws IOException { final Lock commitLock = sharedCommitLock(); commitLock.lock(); try { synchronized (mOpenTrees) { Tree tree = mOpenTrees.get(name); if (tree != null) { return tree; } } byte[] nameKey = newKey(KEY_TYPE_INDEX_NAME, name); byte[] treeIdBytes = mRegistryKeyMap.get(null, nameKey); long treeId; if (treeIdBytes != null) { treeId = DataIO.readLong(treeIdBytes, 0); } else if (!create) { return null; } else synchronized (mOpenTrees) { treeIdBytes = mRegistryKeyMap.get(null, nameKey); if (treeIdBytes != null) { treeId = DataIO.readLong(treeIdBytes, 0); } else { treeIdBytes = new byte[8]; do { treeId = Utils.randomId(REGISTRY_ID, MAX_RESERVED_ID); DataIO.writeLong(treeIdBytes, 0, treeId); } while (!mRegistry.insert(Transaction.BOGUS, treeIdBytes, Utils.EMPTY_BYTES)); if (!mRegistryKeyMap.insert(null, nameKey, treeIdBytes)) { mRegistry.delete(Transaction.BOGUS, treeIdBytes); throw new DatabaseException("Unable to insert index name"); } byte[] idKey = newKey(KEY_TYPE_INDEX_ID, treeIdBytes); if (!mRegistryKeyMap.insert(null, idKey, name)) { mRegistryKeyMap.delete(null, nameKey); mRegistry.delete(Transaction.BOGUS, treeIdBytes); throw new DatabaseException("Unable to insert index id"); } } } byte[] encodedRootId = mRegistry.get(Transaction.BOGUS, treeIdBytes); Node rootNode; if (encodedRootId == null || encodedRootId.length == 0) { // Create a new empty leaf node. rootNode = new Node(pageSize(), true); } else { rootNode = new Node(pageSize(), false); rootNode.read(this, DataIO.readLong(encodedRootId, 0)); } synchronized (mOpenTrees) { Tree tree = mOpenTrees.get(name); if (tree == null) { tree = new Tree(this, treeId, treeIdBytes, name, rootNode); mOpenTrees.put(name, tree); mOpenTreesById.put(treeId, tree); } return tree; } } catch (Throwable e) { throw Utils.closeOnFailure(this, e); } finally { commitLock.unlock(); } } private static byte[] newKey(byte type, byte[] payload) { byte[] key = new byte[1 + payload.length]; key[0] = type; System.arraycopy(payload, 0, key, 1, payload.length); return key; } /** * Returns the fixed size of all pages in the store, in bytes. */ int pageSize() { return mPageStore.pageSize(); } /** * Access the shared commit lock, which prevents commits while held. */ Lock sharedCommitLock() { return mSharedCommitLock; } /** * Returns a new or recycled Node instance, latched exclusively, with an id * of zero and a clean state. */ Node allocLatchedNode() throws IOException { mCacheLatch.acquireExclusiveUnfair(); try { int max = mMaxCachedNodeCount; if (mCachedNodeCount < max) { Node node = new Node(pageSize(), false); node.acquireExclusiveUnfair(); mCachedNodeCount++; if ((node.mLessUsed = mMostRecentlyUsed) == null) { mLeastRecentlyUsed = node; } else { mMostRecentlyUsed.mMoreUsed = node; } mMostRecentlyUsed = node; return node; } do { Node node = mLeastRecentlyUsed; (mLeastRecentlyUsed = node.mMoreUsed).mLessUsed = null; node.mMoreUsed = null; (node.mLessUsed = mMostRecentlyUsed).mMoreUsed = node; mMostRecentlyUsed = node; if (node.tryAcquireExclusiveUnfair()) { if (node.evict(this)) { // Return with latch still held. return node; } else { node.releaseExclusive(); } } } while (--max > 0); } finally { mCacheLatch.releaseExclusive(); } // FIXME: Throw a better exception. Also, try all nodes again, but with // stronger latch request before giving up. throw new IllegalStateException("Cache is full"); } /** * Returns a new reserved node, latched exclusively and marked dirty. Caller * must hold commit lock. */ Node newDirtyNode() throws IOException { Node node = allocLatchedNode(); node.mId = mPageStore.reservePage(); node.mCachedState = mCommitState; return node; } /** * Caller must hold commit lock and any latch on node. */ boolean shouldMarkDirty(Node node) { return node.mCachedState != mCommitState && node.mId != Node.STUB_ID; } /** * Caller must hold commit lock and exclusive latch on node. Method does * nothing if node is already dirty. Latch is never released by this method, * even if an exception is thrown. * * @return true if just made dirty and id changed */ boolean markDirty(Tree tree, Node node) throws IOException { if (node.mCachedState == mCommitState || node.mId == Node.STUB_ID) { return false; } else { doMarkDirty(tree, node); return true; } } /** * Caller must hold commit lock and exclusive latch on node. Method does * nothing if node is already dirty. Latch is never released by this method, * even if an exception is thrown. */ void markUndoLogDirty(Node node) throws IOException { if (node.mCachedState != mCommitState) { long oldId = node.mId; long newId = mPageStore.reservePage(); mPageStore.deletePage(oldId); node.write(this); node.mId = newId; node.mCachedState = mCommitState; } } /** * Caller must hold commit lock and exclusive latch on node. Method must * not be called if node is already dirty. Latch is never released by this * method, even if an exception is thrown. */ void doMarkDirty(Tree tree, Node node) throws IOException { long oldId = node.mId; long newId = mPageStore.reservePage(); if (oldId != 0) { mPageStore.deletePage(oldId); } if (node.mCachedState != CACHED_CLEAN) { node.write(this); } if (node == tree.mRoot && tree.mIdBytes != null) { byte[] newEncodedId = new byte[8]; DataIO.writeLong(newEncodedId, 0, newId); mRegistry.store(Transaction.BOGUS, tree.mIdBytes, newEncodedId); } node.mId = newId; node.mCachedState = mCommitState; } /** * Similar to markDirty method except no new page is reserved, and old page * is not immediately deleted. Caller must hold commit lock and exclusive * latch on node. Latch is never released by this method, even if an * exception is thrown. */ void prepareToDelete(Node node) throws IOException { // Hello. My name is <NAME>. You killed my father. Prepare to die. byte state = node.mCachedState; if (state != CACHED_CLEAN && state != mCommitState) { node.write(this); } } /** * Caller must hold commit lock and exclusive latch on node. Latch is * never released by this method, even if an exception is thrown. */ void deleteNode(Node node) throws IOException { deletePage(node.mId, node.mCachedState); node.mId = 0; // FIXME: child node array should be recycled node.mChildNodes = null; // When node is re-allocated, it will be evicted. Ensure that eviction // doesn't write anything. node.mCachedState = CACHED_CLEAN; // Indicate that node is least recently used, allowing it to be // re-allocated immediately without evicting another node. mCacheLatch.acquireExclusiveUnfair(); try { Node lessUsed = node.mLessUsed; if (lessUsed != null) { Node moreUsed = node.mMoreUsed; if ((lessUsed.mMoreUsed = moreUsed) == null) { mMostRecentlyUsed = lessUsed; } else { moreUsed.mLessUsed = lessUsed; } node.mLessUsed = null; (node.mMoreUsed = mLeastRecentlyUsed).mLessUsed = node; mLeastRecentlyUsed = node; } } finally { mCacheLatch.releaseExclusive(); } } /** * Caller must hold commit lock. */ void deletePage(long id, int cachedState) throws IOException { if (id != 0) { if (cachedState == mCommitState) { // Newly reserved page was never used, so recycle it. mPageStore.recyclePage(id); } else { // Old data must survive until after checkpoint. mPageStore.deletePage(id); } } } /** * Indicate that non-root node is most recently used. Root node is not * managed in usage list and cannot be evicted. */ void used(Node node) { // Because this method can be a bottleneck, don't wait for exclusive // latch. If node is popular, it will get more chances to be identified // as most recently used. This strategy works well enough because cache // eviction is always a best-guess approach. if (mCacheLatch.tryAcquireExclusiveUnfair()) { Node moreUsed = node.mMoreUsed; if (moreUsed != null) { Node lessUsed = node.mLessUsed; if ((moreUsed.mLessUsed = lessUsed) == null) { mLeastRecentlyUsed = moreUsed; } else { lessUsed.mMoreUsed = moreUsed; } node.mMoreUsed = null; (node.mLessUsed = mMostRecentlyUsed).mMoreUsed = node; mMostRecentlyUsed = node; } mCacheLatch.releaseExclusive(); } } byte[] removeSpareBuffer() throws InterruptedIOException { return mSpareBufferPool.remove(); } void addSpareBuffer(byte[] buffer) { mSpareBufferPool.add(buffer); } void readPage(long id, byte[] page) throws IOException { mPageStore.readPage(id, page); } void writeReservedPage(long id, byte[] page) throws IOException { mPageStore.writeReservedPage(id, page); } private void checkpoint(boolean force) throws IOException { // Checkpoint lock ensures consistent state between page store and logs. synchronized (mCheckpointLock) { final Node root = mRegistry.mRoot; // Commit lock must be acquired first, to prevent deadlock. mPageStore.exclusiveCommitLock().lock(); root.acquireSharedUnfair(); if (!force && root.mCachedState == CACHED_CLEAN) { // Root is clean, so nothing to do. root.releaseShared(); mPageStore.exclusiveCommitLock().unlock(); return; } final long redoLogId; try { redoLogId = mRedoLog.openNewFile(); } catch (IOException e) { root.releaseShared(); mPageStore.exclusiveCommitLock().unlock(); throw e; } mPageStore.commit(new PageStore.CommitCallback() { @Override public byte[] prepare() throws IOException { return flush(redoLogId); } }); // Note: The delete step can get skipped if process exits at this // point. File is deleted again when database is re-opened. mRedoLog.deleteOldFile(redoLogId); } } /** * Method is invoked with exclusive commit lock and shared root node latch held. */ private byte[] flush(final long redoLogId) throws IOException { // Snapshot of all open trees. Tree[] trees; synchronized (mOpenTrees) { trees = mOpenTrees.values().toArray(new Tree[mOpenTrees.size()]); } final long txnId = mTxnId.get(); /* FIXME: This code does not properly account for concurrent splits. Dirty nodes might not get written into the commit, and this has also been observed: java.lang.AssertionError: Split child is not already marked dirty at org.cojen.tupl.TreeNode.insertSplitChildRef(TreeNode.java:1178) at org.cojen.tupl.TreeCursor.finishSplit(TreeCursor.java:1647) at org.cojen.tupl.TreeCursor.finishSplit(TreeCursor.java:1640) at org.cojen.tupl.TreeCursor.store(TreeCursor.java:969) at org.cojen.tupl.TreeCursor.store(TreeCursor.java:746) at org.cojen.tupl.FullCursor.store(FullCursor.java:114) at org.cojen.tupl.TreeNodeTest.testInsert(TreeNodeTest.java:135) at org.cojen.tupl.TreeNodeTest.main(TreeNodeTest.java:107) A cursor based approach instead of breadth-first traversal might help. */ final Node root = mRegistry.mRoot; final long rootId = root.mId; final int stateToFlush = mCommitState; mCommitState = (byte) (CACHED_DIRTY_0 + ((stateToFlush - CACHED_DIRTY_0) ^ 1)); mPageStore.exclusiveCommitLock().unlock(); // Gather all nodes to flush. List<DirtyNode> dirtyList = new ArrayList<DirtyNode>(Math.min(1000, mMaxCachedNodeCount)); mRegistry.gatherDirtyNodes(dirtyList, stateToFlush); mRegistryKeyMap.mRoot.acquireSharedUnfair(); mRegistryKeyMap.gatherDirtyNodes(dirtyList, stateToFlush); for (Tree tree : trees) { tree.mRoot.acquireSharedUnfair(); tree.gatherDirtyNodes(dirtyList, stateToFlush); } // Sort nodes by id, which helps make writes more sequentially ordered. Collections.sort(dirtyList); // Now write out all the dirty nodes. Some of them will have already // been concurrently written out, so check again. for (int mi=0; mi<dirtyList.size(); mi++) { Node node = dirtyList.get(mi).mNode; dirtyList.set(mi, null); node.acquireExclusiveUnfair(); if (node.mCachedState != stateToFlush) { // Was already evicted. node.releaseExclusive(); } else { node.mCachedState = CACHED_CLEAN; node.downgrade(); try { node.write(this); } finally { node.releaseShared(); } } } byte[] header = new byte[HEADER_SIZE]; DataIO.writeInt(header, I_ENCODING_VERSION, ENCODING_VERSION); DataIO.writeLong(header, I_ROOT_PAGE_ID, rootId); DataIO.writeLong(header, I_TRANSACTION_ID, txnId); // Add one to redoLogId, indicating the active log id. DataIO.writeLong(header, I_REDO_LOG_ID, redoLogId + 1); return header; } }
34,248
0.536897
0.533396
944
34.302967
25.724611
100
false
false
0
0
0
0
0
0
0.519068
false
false
6
e1ac1620f5819a19b3fbe8d07157e378522b46a5
26,121,991,136,417
353e83bb3f900f5454262fc67993020fdb0bbd8c
/src/java/Main/Main.java
f2e54ed3bb1d0c304d950d7cade31adb20bab921
[]
no_license
tatsujb/TP05-Formulaire-2
https://github.com/tatsujb/TP05-Formulaire-2
5b663da10363250aea7681f622218a2b0c809ffd
d5b4cd8af13cffab2b4420a68ec6e4036e43ae74
refs/heads/master
2021-01-21T18:33:56.120000
2017-05-23T14:54:52
2017-05-23T14:54:52
92,058,939
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import Bean.Utilisateur; import DAO.UtilisateurDAO; import java.sql.SQLException; public class Main { public static void main(String[] args) throws SQLException { UtilisateurDAO utilisateur = new UtilisateurDAO(); utilisateur.create(new Utilisateur(0, "lct@hotmail.fr", "12345", "paul")); } }
UTF-8
Java
321
java
Main.java
Java
[ { "context": ");\n utilisateur.create(new Utilisateur(0, \"lct@hotmail.fr\", \"12345\", \"paul\"));\n }\n}\n", "end": 291, "score": 0.9999250769615173, "start": 277, "tag": "EMAIL", "value": "lct@hotmail.fr" }, { "context": "te(new Utilisateur(0, \"lct@hotmail.fr\", \"12345...
null
[]
import Bean.Utilisateur; import DAO.UtilisateurDAO; import java.sql.SQLException; public class Main { public static void main(String[] args) throws SQLException { UtilisateurDAO utilisateur = new UtilisateurDAO(); utilisateur.create(new Utilisateur(0, "<EMAIL>", "12345", "paul")); } }
314
0.707165
0.688474
12
25.666666
27.016457
82
false
false
0
0
0
0
0
0
0.666667
false
false
6
5a17f9b2d2001c2fe8c607852f2512a5820ba053
506,806,210,189
5b0106e12584517236e0824ec46a3665b5054db2
/src/main/java/cat/itb/videogamegestion/repositories/UserRepository.java
03c2dbbb56ae1dbf9291db6fe81fa1caa3678b75
[]
no_license
hachi22/videogame_gestion
https://github.com/hachi22/videogame_gestion
2415d2e6b5ed193bb506b793b786bb33806af2a4
bfcd66fe90e9519543e1d180f1af068ab95c12ad
refs/heads/master
2023-04-11T05:14:16.084000
2021-04-29T22:21:52
2021-04-29T22:21:52
360,573,644
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cat.itb.videogamegestion.repositories; import cat.itb.videogamegestion.models.UserObject; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface UserRepository extends CrudRepository<UserObject,String> { }
UTF-8
Java
308
java
UserRepository.java
Java
[]
null
[]
package cat.itb.videogamegestion.repositories; import cat.itb.videogamegestion.models.UserObject; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface UserRepository extends CrudRepository<UserObject,String> { }
308
0.834416
0.834416
9
32.222221
27.454115
75
false
false
0
0
0
0
0
0
0.555556
false
false
6
695009fe2f8636c49d50e0d54e5547b280134ea7
10,161,892,685,250
7ad1d9c2fac44ec4f2819f5696445204e93a331c
/src/main/java/com/luo/miaosha/dao/MiaoshaOrderMapper.java
696b2e65abe737481bfc8a190008ca94e5003d5b
[]
no_license
luolili/bf
https://github.com/luolili/bf
3a78742201267836d0850b0aafffefaaa838798a
1ffdb8f22fc6872e27236096ab0449a8b6ec0633
refs/heads/master
2022-07-02T18:51:56.389000
2019-11-04T11:44:14
2019-11-04T11:44:14
212,019,138
0
0
null
false
2022-06-17T02:33:49
2019-10-01T05:28:43
2019-11-04T11:47:47
2022-06-17T02:33:48
64
0
0
3
Java
false
false
package com.luo.miaosha.dao; import com.luo.miaosha.domain.MiaoshaOrder; import com.luo.miaosha.domain.MiaoshaUser; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; @Mapper public interface MiaoshaOrderMapper { @Select("select * from miaosha_order where id = #{id}") MiaoshaOrder getById(@Param("id") Integer id); @Select("select * from miaosha_order where user_id = #{userId} and goods_id=#{goodsId}") MiaoshaOrder getByUserIdGoodsId(@Param("userId") Integer userId, @Param("goodsId") Integer goodsId); }
UTF-8
Java
613
java
MiaoshaOrderMapper.java
Java
[]
null
[]
package com.luo.miaosha.dao; import com.luo.miaosha.domain.MiaoshaOrder; import com.luo.miaosha.domain.MiaoshaUser; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; @Mapper public interface MiaoshaOrderMapper { @Select("select * from miaosha_order where id = #{id}") MiaoshaOrder getById(@Param("id") Integer id); @Select("select * from miaosha_order where user_id = #{userId} and goods_id=#{goodsId}") MiaoshaOrder getByUserIdGoodsId(@Param("userId") Integer userId, @Param("goodsId") Integer goodsId); }
613
0.75367
0.75367
19
31.263159
30.973404
104
false
false
0
0
0
0
0
0
0.473684
false
false
6
97b6594af13cc61d56da917def10ab68611bdfbe
18,889,266,174,937
02ca54e3fc3e89869cc75846808ba374b7efcd84
/src/Arrays/PrefixSumPart1.java
89124a05b070946ffe0b337c663cb8e40877c765
[]
no_license
Bishalj/Practice
https://github.com/Bishalj/Practice
bb3ddb4c54d3767aedce0992e74917deee88fe79
cb44a2b11f2b3e5ba8d73980e5428b00dc0d368b
refs/heads/master
2020-10-01T10:56:08.786000
2020-09-07T17:50:49
2020-09-07T17:50:49
114,151,419
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Arrays; public class PrefixSumPart1 { static int summationArray[]; static { int arr[] = {7,-6,-4,2,20,-1,0,7}; storeSummationOfValuesInArray(arr); } private static void storeSummationOfValuesInArray(int[] arr) { summationArray = new int[arr.length]; int sumOfArrayData = 0; for(int i=0; i<arr.length; i++){ sumOfArrayData += arr[i]; summationArray[i] = sumOfArrayData; } } public static void main(String[] args) { int startRange = 3; int endRange = 7; System.out.println(getSummationOfArrayDataBetweenTheRanges(startRange, endRange)); } private static int getSummationOfArrayDataBetweenTheRanges(int startRange, int endRange) { for(int data : summationArray) System.out.print(data + " "); System.out.println(); int previousIndexValue = 0; if(startRange > 0) previousIndexValue = summationArray[startRange -1]; return summationArray[endRange] - previousIndexValue; } }
UTF-8
Java
1,083
java
PrefixSumPart1.java
Java
[]
null
[]
package Arrays; public class PrefixSumPart1 { static int summationArray[]; static { int arr[] = {7,-6,-4,2,20,-1,0,7}; storeSummationOfValuesInArray(arr); } private static void storeSummationOfValuesInArray(int[] arr) { summationArray = new int[arr.length]; int sumOfArrayData = 0; for(int i=0; i<arr.length; i++){ sumOfArrayData += arr[i]; summationArray[i] = sumOfArrayData; } } public static void main(String[] args) { int startRange = 3; int endRange = 7; System.out.println(getSummationOfArrayDataBetweenTheRanges(startRange, endRange)); } private static int getSummationOfArrayDataBetweenTheRanges(int startRange, int endRange) { for(int data : summationArray) System.out.print(data + " "); System.out.println(); int previousIndexValue = 0; if(startRange > 0) previousIndexValue = summationArray[startRange -1]; return summationArray[endRange] - previousIndexValue; } }
1,083
0.617729
0.602031
39
26.76923
25.072676
94
false
false
0
0
0
0
0
0
0.692308
false
false
6
5af116313f6cb13a7fa4a555747952c4f2bb7e98
15,109,694,948,942
312fce6c392eafaf2cf14e8ea3d8ec5a6e15ede1
/src/serendipitytranslator/mainWindow/PluginDownloader.java
5acc1231fd02632797003295c3de711e364a1e84
[]
no_license
fugazza/SerendipityTranslator
https://github.com/fugazza/SerendipityTranslator
6991bbdcb3ac7a68eb266cd944ed31e3ce731384
2943ebbdabef4fd75d9e199eaa5932f0c148c17d
refs/heads/master
2020-06-03T11:13:22.338000
2013-12-31T21:46:03
2013-12-31T21:46:03
2,796,823
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package serendipitytranslator.mainWindow; import ajgl.utils.ajglTools; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import javax.swing.JOptionPane; /** * * @author Vláďa */ public class PluginDownloader implements Runnable { PluginList pluginList; PropertyChangeSupport propertyChange; boolean stop = false; public PluginDownloader(PluginList pluginList) { this.pluginList = pluginList; this.propertyChange = new PropertyChangeSupport(this); } public void addPropertyChangeListener(PropertyChangeListener listener) { propertyChange.addPropertyChangeListener(listener); } public void run() { int count = 0; propertyChange.firePropertyChange("workStarted", null, "Download of plugins started - checking internet connetion."); if (ajglTools.checkInternetConnection()) { for (Plugin plugin : pluginList) { if (stop || Thread.interrupted()) { break; } propertyChange.firePropertyChange("pluginDowloadStarted", null, plugin.getName()); plugin.downloadFilelist(); plugin.downloadFiles(); propertyChange.firePropertyChange("pluginDowloaded", null, new Integer(++count)); //Thread.yield(); } } else { JOptionPane.showMessageDialog(null, "You are not connected to internet, plugins can not be downloaded!","Internet connection failed",JOptionPane.WARNING_MESSAGE); } propertyChange.firePropertyChange("workFinished", null, pluginList); } public void stop() { stop = true; } }
UTF-8
Java
1,858
java
PluginDownloader.java
Java
[ { "context": "import javax.swing.JOptionPane;\n\n/**\n *\n * @author Vláďa\n */\npublic class PluginDownloader implements Runn", "end": 312, "score": 0.9998478889465332, "start": 307, "tag": "NAME", "value": "Vláďa" } ]
null
[]
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package serendipitytranslator.mainWindow; import ajgl.utils.ajglTools; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import javax.swing.JOptionPane; /** * * @author Vláďa */ public class PluginDownloader implements Runnable { PluginList pluginList; PropertyChangeSupport propertyChange; boolean stop = false; public PluginDownloader(PluginList pluginList) { this.pluginList = pluginList; this.propertyChange = new PropertyChangeSupport(this); } public void addPropertyChangeListener(PropertyChangeListener listener) { propertyChange.addPropertyChangeListener(listener); } public void run() { int count = 0; propertyChange.firePropertyChange("workStarted", null, "Download of plugins started - checking internet connetion."); if (ajglTools.checkInternetConnection()) { for (Plugin plugin : pluginList) { if (stop || Thread.interrupted()) { break; } propertyChange.firePropertyChange("pluginDowloadStarted", null, plugin.getName()); plugin.downloadFilelist(); plugin.downloadFiles(); propertyChange.firePropertyChange("pluginDowloaded", null, new Integer(++count)); //Thread.yield(); } } else { JOptionPane.showMessageDialog(null, "You are not connected to internet, plugins can not be downloaded!","Internet connection failed",JOptionPane.WARNING_MESSAGE); } propertyChange.firePropertyChange("workFinished", null, pluginList); } public void stop() { stop = true; } }
1,858
0.642241
0.641703
56
32.142857
34.300369
174
false
false
0
0
0
0
0
0
0.678571
false
false
6
48f4e8ec77df449a4046a75795d2588f129b878c
6,674,379,226,400
00c99f919437f420e76726623aee8f62a390aa1d
/java/cbcb/kmulus/allpairs/comparison/PrimeRot.java
9d32054a088ef42d1295d9a587bdacab081a12f5
[]
no_license
biocloud/k-mulus
https://github.com/biocloud/k-mulus
4458092ac057db34623bab3626b7cd7bae810e23
5135702323ad733c009f9ffdfca2533fe61f90ad
refs/heads/master
2020-06-04T03:04:07.330000
2011-08-18T20:24:48
2011-08-18T20:24:48
2,226,203
3
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package cbcb.kmulus.allpairs.comparison; import java.util.ArrayList; import java.util.List; /** * Implementation of the prime-rot algorithm which produces unique groupings within a set. These * groupings are unique in that over all groups, each pair of items are found in the same group * exactly once. * * This algorithm works optimally on sets of size p^2 + p + 1, where p is a prime number. * As p^2 + p + 1 is the exact capacity for this algorithm, in sub-optimal cases p will be chosen as * the smallest possible prime number such that p^2 + p + 1 >= set size. * * @author CH Albach */ public abstract class PrimeRot implements ExhaustiveUniqueGrouper { /** The size of the input set of items. */ private long numItems; /** The prime number associated with the algorithm. */ protected int p; /** The exponent of the prime number. */ protected int k; /** The order of the projective plane (p^power). */ protected int n; public PrimeRot(long numItems, int p, int k, int n) { this.numItems = numItems; this.p = p; this.k = k; this.n = n; } public long getNumItems() { return numItems; } public long getNumGroups() { return n + 1; } public int getP() { return p; } public int getK() { return k; } public int getN() { return n; } public static PrimeRot generatePrimeRot(long numItems, int p) { return new ClassicalPlaneRot(numItems, p); } /** * Determine the smallest order projective plane which can fit the desired input set size. The * order of this plane may be p^k where p is prime and k is an integer. Planes where k=1 are * called Classical projective planes or Desarguesian^2. If such a plane is optimal, this method * returns a {@link ClassicalPlaneRot} implementation of {@link PrimeRot}. * * TODO(CH): Planes of other powers should create a {@link NonclassicalPlaneRot} implementation. */ public static PrimeRot generatePrimeRot(long numItems) { List<Integer> primes = new ArrayList<Integer>(); int prime = 1; int p, k, n; /*Compute the smallest possible classical projective plane.*/ while(prime * prime + prime + 1 < numItems) { do { prime++; } while(!isPrime(prime, primes)); primes.add(prime); } /*Store the classical plane data.*/ p = prime; k = 1; n = prime; return new ClassicalPlaneRot(numItems, p); //System.out.println("p: " + p + ", k: " + k + ", n: " + n); //System.out.println("classical capacity: " + (n*n + n + 1)); /*TODO put in a terminating condition for orders which have a capacity * within a certain distance of numItems */ /* See if there are any 'tighter fitting' non-classical planes. * * If p^2k + p^k + 1 >= numItems, where p is a prime and k is an integer; * for each prime, the lowest value of k is FLOOR[ logp(numItems-1)/2 ]. * (This can be derived from p^2k + p^k + 1 <= numItems) */ /*Compute the reusable numerator of the exponent.*/ /*double expNum = Math.log(numItems-1)/2; for(Integer primeFactor : primes) { /*Compute the lowest possible order allowed by numItems.*/ /*int exp = (int)( expNum / Math.log(primeFactor) ); int order = (int)Math.pow(primeFactor, exp); /*Increment the exponent until the plane can fit numItems.*/ /*while(order * order + order + 1 < numItems) { /*Determine subsequent powers.*/ /*order *= primeFactor; exp++; } /*If this order beats out the old one, use it. Careful of overflow.*/ /*if(order > 0 && order < n) { p = primeFactor; k = exp; n = order; } } if(k == 1) { return new ClassicalPlaneRot(numItems, p); } else { return new NonclassicalPlaneRot(numItems, p, k, n); }*/ } /** * Map out internal ids such that placement for the algorithm is optimal. * Assuming that the input is zero based and is complete from 0 - numItems * * Eventually this could take into account the size of each item. */ protected abstract void initializeIids(); /** * Uses the prime-rot algorithm to calculate the groups to which the ID * belongs. */ public abstract long[] getGroups(long id); /** * Given a list of preceding prime numbers, determines if p is prime. */ private static boolean isPrime(int p, List<Integer> primeList) { // TODO: Use a better method of primality testing. int lim = (int)Math.sqrt(p); for(int prime : primeList) { if(prime > lim) break; if(p % prime == 0) { return false; } } return true; } }
UTF-8
Java
4,709
java
PrimeRot.java
Java
[ { "context": "uch that p^2 + p + 1 >= set size.\r\n * \r\n * @author CH Albach\r\n */\r\npublic abstract class PrimeRot implements E", "end": 615, "score": 0.9996991753578186, "start": 606, "tag": "NAME", "value": "CH Albach" } ]
null
[]
package cbcb.kmulus.allpairs.comparison; import java.util.ArrayList; import java.util.List; /** * Implementation of the prime-rot algorithm which produces unique groupings within a set. These * groupings are unique in that over all groups, each pair of items are found in the same group * exactly once. * * This algorithm works optimally on sets of size p^2 + p + 1, where p is a prime number. * As p^2 + p + 1 is the exact capacity for this algorithm, in sub-optimal cases p will be chosen as * the smallest possible prime number such that p^2 + p + 1 >= set size. * * @author <NAME> */ public abstract class PrimeRot implements ExhaustiveUniqueGrouper { /** The size of the input set of items. */ private long numItems; /** The prime number associated with the algorithm. */ protected int p; /** The exponent of the prime number. */ protected int k; /** The order of the projective plane (p^power). */ protected int n; public PrimeRot(long numItems, int p, int k, int n) { this.numItems = numItems; this.p = p; this.k = k; this.n = n; } public long getNumItems() { return numItems; } public long getNumGroups() { return n + 1; } public int getP() { return p; } public int getK() { return k; } public int getN() { return n; } public static PrimeRot generatePrimeRot(long numItems, int p) { return new ClassicalPlaneRot(numItems, p); } /** * Determine the smallest order projective plane which can fit the desired input set size. The * order of this plane may be p^k where p is prime and k is an integer. Planes where k=1 are * called Classical projective planes or Desarguesian^2. If such a plane is optimal, this method * returns a {@link ClassicalPlaneRot} implementation of {@link PrimeRot}. * * TODO(CH): Planes of other powers should create a {@link NonclassicalPlaneRot} implementation. */ public static PrimeRot generatePrimeRot(long numItems) { List<Integer> primes = new ArrayList<Integer>(); int prime = 1; int p, k, n; /*Compute the smallest possible classical projective plane.*/ while(prime * prime + prime + 1 < numItems) { do { prime++; } while(!isPrime(prime, primes)); primes.add(prime); } /*Store the classical plane data.*/ p = prime; k = 1; n = prime; return new ClassicalPlaneRot(numItems, p); //System.out.println("p: " + p + ", k: " + k + ", n: " + n); //System.out.println("classical capacity: " + (n*n + n + 1)); /*TODO put in a terminating condition for orders which have a capacity * within a certain distance of numItems */ /* See if there are any 'tighter fitting' non-classical planes. * * If p^2k + p^k + 1 >= numItems, where p is a prime and k is an integer; * for each prime, the lowest value of k is FLOOR[ logp(numItems-1)/2 ]. * (This can be derived from p^2k + p^k + 1 <= numItems) */ /*Compute the reusable numerator of the exponent.*/ /*double expNum = Math.log(numItems-1)/2; for(Integer primeFactor : primes) { /*Compute the lowest possible order allowed by numItems.*/ /*int exp = (int)( expNum / Math.log(primeFactor) ); int order = (int)Math.pow(primeFactor, exp); /*Increment the exponent until the plane can fit numItems.*/ /*while(order * order + order + 1 < numItems) { /*Determine subsequent powers.*/ /*order *= primeFactor; exp++; } /*If this order beats out the old one, use it. Careful of overflow.*/ /*if(order > 0 && order < n) { p = primeFactor; k = exp; n = order; } } if(k == 1) { return new ClassicalPlaneRot(numItems, p); } else { return new NonclassicalPlaneRot(numItems, p, k, n); }*/ } /** * Map out internal ids such that placement for the algorithm is optimal. * Assuming that the input is zero based and is complete from 0 - numItems * * Eventually this could take into account the size of each item. */ protected abstract void initializeIids(); /** * Uses the prime-rot algorithm to calculate the groups to which the ID * belongs. */ public abstract long[] getGroups(long id); /** * Given a list of preceding prime numbers, determines if p is prime. */ private static boolean isPrime(int p, List<Integer> primeList) { // TODO: Use a better method of primality testing. int lim = (int)Math.sqrt(p); for(int prime : primeList) { if(prime > lim) break; if(p % prime == 0) { return false; } } return true; } }
4,706
0.629645
0.624124
170
25.700001
27.906958
100
false
false
0
0
0
0
0
0
2.064706
false
false
6
0d2f7b7bf67fc65287106bb2d73780430aa83a20
4,449,586,175,520
2643fd58dc4dfffa4fbd05499d78f6247a381a08
/core/src/test/java/com/prudential/core/common/ErrorCodeTest.java
00779465bea645faa521d5963d026fd18031158f
[]
no_license
ankitsaxena0108/Configurator
https://github.com/ankitsaxena0108/Configurator
b75771ef55ec8f8487b7920ad9f3e7c1fd2949bf
8cf751472b08fe322bbd666c40f1b3ccb1a6d898
refs/heads/master
2020-03-26T07:49:32.575000
2018-08-16T13:27:31
2018-08-16T13:27:31
144,672,872
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.prudential.core.common; import org.junit.*; import static org.junit.Assert.*; /** * The class <code>ErrorCodeTest</code> contains tests for the class <code>{@link ErrorCode}</code>. * * @generatedBy CodePro at 4/4/18 2:45 PM * @author nrusingh.mishra * @version $Revision: 1.0 $ */ public class ErrorCodeTest { /** * Run the ErrorCode(String,String) constructor test. * * @throws Exception * * @generatedBy CodePro at 4/4/18 2:45 PM */ @Test public void testErrorCode_1() throws Exception { String errorCode = "1000"; String logMessage = "Server side error, Contact Administrator"; ErrorCode result = new ErrorCode(errorCode, logMessage); // add additional test code here assertNotNull(result); assertEquals("1000", result.getErrorCode()); assertEquals("Server side error, Contact Administrator", result.getLogMessage()); } /** * Run the String getErrorCode() method test. * * @throws Exception * * @generatedBy CodePro at 4/4/18 2:45 PM */ @Test public void testGetErrorCode_1() throws Exception { ErrorCode fixture = new ErrorCode("1000", "Server side error, Contact Administrator"); String result = fixture.getErrorCode(); // add additional test code here assertEquals("1000", result); } /** * Run the String getLogMessage() method test. * * @throws Exception * * @generatedBy CodePro at 4/4/18 2:45 PM */ @Test public void testGetLogMessage_1() throws Exception { ErrorCode fixture = new ErrorCode("1000", "Server side error, Contact Administrator"); String result = fixture.getLogMessage(); // add additional test code here assertEquals("Server side error, Contact Administrator", result); } /** * Perform pre-test initialization. * * @throws Exception * if the initialization fails for some reason * * @generatedBy CodePro at 4/4/18 2:45 PM */ @Before public void setUp() throws Exception { // add additional set up code here } /** * Perform post-test clean-up. * * @throws Exception * if the clean-up fails for some reason * * @generatedBy CodePro at 4/4/18 2:45 PM */ @After public void tearDown() throws Exception { // Add additional tear down code here } /** * Launch the test. * * @param args the command line arguments * * @generatedBy CodePro at 4/4/18 2:45 PM */ public static void main(String[] args) { new org.junit.runner.JUnitCore().run(ErrorCodeTest.class); } }
UTF-8
Java
2,472
java
ErrorCodeTest.java
Java
[ { "context": " @generatedBy CodePro at 4/4/18 2:45 PM\n * @author nrusingh.mishra\n * @version $Revision: 1.0 $\n */\npublic class Err", "end": 268, "score": 0.9810751676559448, "start": 253, "tag": "USERNAME", "value": "nrusingh.mishra" } ]
null
[]
package com.prudential.core.common; import org.junit.*; import static org.junit.Assert.*; /** * The class <code>ErrorCodeTest</code> contains tests for the class <code>{@link ErrorCode}</code>. * * @generatedBy CodePro at 4/4/18 2:45 PM * @author nrusingh.mishra * @version $Revision: 1.0 $ */ public class ErrorCodeTest { /** * Run the ErrorCode(String,String) constructor test. * * @throws Exception * * @generatedBy CodePro at 4/4/18 2:45 PM */ @Test public void testErrorCode_1() throws Exception { String errorCode = "1000"; String logMessage = "Server side error, Contact Administrator"; ErrorCode result = new ErrorCode(errorCode, logMessage); // add additional test code here assertNotNull(result); assertEquals("1000", result.getErrorCode()); assertEquals("Server side error, Contact Administrator", result.getLogMessage()); } /** * Run the String getErrorCode() method test. * * @throws Exception * * @generatedBy CodePro at 4/4/18 2:45 PM */ @Test public void testGetErrorCode_1() throws Exception { ErrorCode fixture = new ErrorCode("1000", "Server side error, Contact Administrator"); String result = fixture.getErrorCode(); // add additional test code here assertEquals("1000", result); } /** * Run the String getLogMessage() method test. * * @throws Exception * * @generatedBy CodePro at 4/4/18 2:45 PM */ @Test public void testGetLogMessage_1() throws Exception { ErrorCode fixture = new ErrorCode("1000", "Server side error, Contact Administrator"); String result = fixture.getLogMessage(); // add additional test code here assertEquals("Server side error, Contact Administrator", result); } /** * Perform pre-test initialization. * * @throws Exception * if the initialization fails for some reason * * @generatedBy CodePro at 4/4/18 2:45 PM */ @Before public void setUp() throws Exception { // add additional set up code here } /** * Perform post-test clean-up. * * @throws Exception * if the clean-up fails for some reason * * @generatedBy CodePro at 4/4/18 2:45 PM */ @After public void tearDown() throws Exception { // Add additional tear down code here } /** * Launch the test. * * @param args the command line arguments * * @generatedBy CodePro at 4/4/18 2:45 PM */ public static void main(String[] args) { new org.junit.runner.JUnitCore().run(ErrorCodeTest.class); } }
2,472
0.679612
0.649676
109
21.688074
22.615938
100
false
false
0
0
0
0
0
0
1.247706
false
false
6
12b59450bcc3880232276cdb4f77231ec17778a7
5,085,241,339,940
689cdf772da9f871beee7099ab21cd244005bfb2
/classes/com/android/dazhihui/ui/screen/e.java
7e83b1a5ae826c82a76250b1da6259cf012eae19
[]
no_license
waterwitness/dazhihui
https://github.com/waterwitness/dazhihui
9353fd5e22821cb5026921ce22d02ca53af381dc
ad1f5a966ddd92bc2ac8c886eb2060d20cf610b3
refs/heads/master
2020-05-29T08:54:50.751000
2016-10-08T08:09:46
2016-10-08T08:09:46
70,314,359
2
4
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.android.dazhihui.ui.screen; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.TextUtils; import android.view.View; import android.widget.Toast; import com.android.dazhihui.a.b.h; import com.android.dazhihui.a.b.i; import com.android.dazhihui.a.b.j; import com.android.dazhihui.g; import com.android.dazhihui.ui.model.IRequestAdapterListener; import com.android.dazhihui.ui.model.RequestAdapter; import com.android.dazhihui.ui.widget.k; import com.android.dazhihui.ui.widget.m; public abstract class e extends Fragment implements i, IRequestAdapterListener { protected Bundle mBundle; protected int mFragmentId; protected y mLookFace; protected e mNext; protected e mPrevious; protected RequestAdapter mRequestAdapter = new f(this); public void beforeHidden() { this.mRequestAdapter.stop(); } public void changeLookFace(y paramy) { if ((paramy != null) && (paramy != this.mLookFace)) { this.mLookFace = paramy; } } public void clearRequest() { this.mRequestAdapter.clearRequest(); } public Bundle getBundle() { return this.mBundle; } public int getFragmentId() { return this.mFragmentId; } public e getNext() { return this.mNext; } public e getPrevious() { return this.mPrevious; } public View getScroolView() { return null; } public void handleResponse(h paramh, j paramj) {} public void handleTimeout(h paramh) {} public void loadMoreData() {} public void netException(h paramh, Exception paramException) {} public void onBackPressed() { beforeHidden(); } public void onDestroy() { this.mRequestAdapter.destory(); super.onDestroy(); } public void onHiddenChanged(boolean paramBoolean) { super.onHiddenChanged(paramBoolean); } public void onPulledrefresh(boolean paramBoolean) {} public void onResume() { setLookFace(); if ((isVisible()) && (getUserVisibleHint())) { this.mRequestAdapter.startAutoRequestPeriod(); } super.onResume(); } public void onStop() { this.mRequestAdapter.stop(); super.onStop(); } public void promptTrade(String paramString1, String paramString2, String paramString3, String paramString4, m paramm1, m paramm2, m paramm3) { k localk = new k(); if (!TextUtils.isEmpty(paramString1)) { localk.a(paramString1); } localk.b(paramString2); if (!TextUtils.isEmpty(paramString3)) { localk.b(paramString3, paramm1); } if (!TextUtils.isEmpty(paramString4)) { localk.a(paramString4, paramm2); } if (paramm3 != null) { localk.a(paramm3); } localk.a(getActivity()); } public void refresh() {} public void registRequestListener(h paramh) { this.mRequestAdapter.registRequestListener(paramh); } public void removeRequest(h paramh) { this.mRequestAdapter.removeRequest(paramh); } public void sendRequest(h paramh) { this.mRequestAdapter.sendRequest(paramh); } public void setAutoRequest(h paramh) { this.mRequestAdapter.setAutoRequest(paramh); } public void setAutoRequestPeriod(long paramLong) { this.mRequestAdapter.setAutoRequestPeriod(paramLong); } public void setBundle(Bundle paramBundle) { this.mBundle = paramBundle; } public void setFragmentId(int paramInt) { this.mFragmentId = paramInt; } public void setLookFace() { y localy = g.a().b(); if ((localy != null) && (localy != this.mLookFace)) { changeLookFace(localy); this.mLookFace = localy; } } public void setNext(e parame) { this.mNext = parame; } public void setPrevious(e parame) { this.mPrevious = parame; } public void setSubFragmentIndex(int paramInt1, int paramInt2) {} public void setUserVisibleHint(boolean paramBoolean) { super.setUserVisibleHint(paramBoolean); if (paramBoolean) { setLookFace(); this.mRequestAdapter.startAutoRequestPeriod(); return; } this.mRequestAdapter.stop(); } public void show() { setLookFace(); this.mRequestAdapter.startAutoRequestPeriod(); } public void showShortToast(int paramInt) { if (getActivity() == null) { return; } Toast.makeText(getActivity(), getString(paramInt), 0).show(); } public void showShortToast(String paramString) { if (getActivity() == null) { return; } Toast.makeText(getActivity(), paramString, 0).show(); } public void startAutoRequestPeriod() { this.mRequestAdapter.startAutoRequestPeriod(); } } /* Location: E:\apk\dazhihui2\classes-dex2jar.jar!\com\android\dazhihui\ui\screen\e.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
UTF-8
Java
4,875
java
e.java
Java
[]
null
[]
package com.android.dazhihui.ui.screen; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.TextUtils; import android.view.View; import android.widget.Toast; import com.android.dazhihui.a.b.h; import com.android.dazhihui.a.b.i; import com.android.dazhihui.a.b.j; import com.android.dazhihui.g; import com.android.dazhihui.ui.model.IRequestAdapterListener; import com.android.dazhihui.ui.model.RequestAdapter; import com.android.dazhihui.ui.widget.k; import com.android.dazhihui.ui.widget.m; public abstract class e extends Fragment implements i, IRequestAdapterListener { protected Bundle mBundle; protected int mFragmentId; protected y mLookFace; protected e mNext; protected e mPrevious; protected RequestAdapter mRequestAdapter = new f(this); public void beforeHidden() { this.mRequestAdapter.stop(); } public void changeLookFace(y paramy) { if ((paramy != null) && (paramy != this.mLookFace)) { this.mLookFace = paramy; } } public void clearRequest() { this.mRequestAdapter.clearRequest(); } public Bundle getBundle() { return this.mBundle; } public int getFragmentId() { return this.mFragmentId; } public e getNext() { return this.mNext; } public e getPrevious() { return this.mPrevious; } public View getScroolView() { return null; } public void handleResponse(h paramh, j paramj) {} public void handleTimeout(h paramh) {} public void loadMoreData() {} public void netException(h paramh, Exception paramException) {} public void onBackPressed() { beforeHidden(); } public void onDestroy() { this.mRequestAdapter.destory(); super.onDestroy(); } public void onHiddenChanged(boolean paramBoolean) { super.onHiddenChanged(paramBoolean); } public void onPulledrefresh(boolean paramBoolean) {} public void onResume() { setLookFace(); if ((isVisible()) && (getUserVisibleHint())) { this.mRequestAdapter.startAutoRequestPeriod(); } super.onResume(); } public void onStop() { this.mRequestAdapter.stop(); super.onStop(); } public void promptTrade(String paramString1, String paramString2, String paramString3, String paramString4, m paramm1, m paramm2, m paramm3) { k localk = new k(); if (!TextUtils.isEmpty(paramString1)) { localk.a(paramString1); } localk.b(paramString2); if (!TextUtils.isEmpty(paramString3)) { localk.b(paramString3, paramm1); } if (!TextUtils.isEmpty(paramString4)) { localk.a(paramString4, paramm2); } if (paramm3 != null) { localk.a(paramm3); } localk.a(getActivity()); } public void refresh() {} public void registRequestListener(h paramh) { this.mRequestAdapter.registRequestListener(paramh); } public void removeRequest(h paramh) { this.mRequestAdapter.removeRequest(paramh); } public void sendRequest(h paramh) { this.mRequestAdapter.sendRequest(paramh); } public void setAutoRequest(h paramh) { this.mRequestAdapter.setAutoRequest(paramh); } public void setAutoRequestPeriod(long paramLong) { this.mRequestAdapter.setAutoRequestPeriod(paramLong); } public void setBundle(Bundle paramBundle) { this.mBundle = paramBundle; } public void setFragmentId(int paramInt) { this.mFragmentId = paramInt; } public void setLookFace() { y localy = g.a().b(); if ((localy != null) && (localy != this.mLookFace)) { changeLookFace(localy); this.mLookFace = localy; } } public void setNext(e parame) { this.mNext = parame; } public void setPrevious(e parame) { this.mPrevious = parame; } public void setSubFragmentIndex(int paramInt1, int paramInt2) {} public void setUserVisibleHint(boolean paramBoolean) { super.setUserVisibleHint(paramBoolean); if (paramBoolean) { setLookFace(); this.mRequestAdapter.startAutoRequestPeriod(); return; } this.mRequestAdapter.stop(); } public void show() { setLookFace(); this.mRequestAdapter.startAutoRequestPeriod(); } public void showShortToast(int paramInt) { if (getActivity() == null) { return; } Toast.makeText(getActivity(), getString(paramInt), 0).show(); } public void showShortToast(String paramString) { if (getActivity() == null) { return; } Toast.makeText(getActivity(), paramString, 0).show(); } public void startAutoRequestPeriod() { this.mRequestAdapter.startAutoRequestPeriod(); } } /* Location: E:\apk\dazhihui2\classes-dex2jar.jar!\com\android\dazhihui\ui\screen\e.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
4,875
0.667487
0.660923
233
19.927038
20.602488
142
false
false
0
0
0
0
0
0
0.360515
false
false
6
743227d1e986fa033584aca7e2799c72a80f348e
5,016,521,805,261
499a59dc04d3bac07fbbbda1cbf1e22bb23bf682
/app/src/main/java/org/goldenroute/portfolioclient/ClientContext.java
9d05bbdf5c77124013b87e7f91f1266a3d32cef8
[ "Apache-2.0" ]
permissive
edwardluzi/portfolio-client
https://github.com/edwardluzi/portfolio-client
347c6750d392b120b1e577e0621510a12b3987b1
bb54d8995cc3fb53dd9bc0b5bf1d55e4e4aaf0dc
refs/heads/master
2021-01-21T04:41:13.492000
2016-06-21T11:41:02
2016-06-21T11:41:02
46,850,032
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.goldenroute.portfolioclient; import org.goldenroute.portfolioclient.model.Account; import org.goldenroute.portfolioclient.signin.SignInManager; public class ClientContext { private static ClientContext mInstance = null; public static synchronized ClientContext getInstance() { if (mInstance == null) { mInstance = new ClientContext(); } return mInstance; } private SignInManager mSignInManager; private Account mAccount; public SignInManager getSignInManager() { return mSignInManager; } public void setSignInManager(SignInManager signInManager) { mSignInManager = signInManager; } public Account getAccount() { return mAccount; } public void setAccount(Account account) { mAccount = account; } }
UTF-8
Java
837
java
ClientContext.java
Java
[]
null
[]
package org.goldenroute.portfolioclient; import org.goldenroute.portfolioclient.model.Account; import org.goldenroute.portfolioclient.signin.SignInManager; public class ClientContext { private static ClientContext mInstance = null; public static synchronized ClientContext getInstance() { if (mInstance == null) { mInstance = new ClientContext(); } return mInstance; } private SignInManager mSignInManager; private Account mAccount; public SignInManager getSignInManager() { return mSignInManager; } public void setSignInManager(SignInManager signInManager) { mSignInManager = signInManager; } public Account getAccount() { return mAccount; } public void setAccount(Account account) { mAccount = account; } }
837
0.691756
0.691756
34
23.617647
21.057365
63
false
false
0
0
0
0
0
0
0.352941
false
false
6
f177bba7a15e6aeb355c5addbee51c290873f040
2,783,138,873,384
709d00d130164f63f3428fea483db6d230818540
/redgear/securecraft/BlockSmartObsidian.java
8ec09373b5f60f7030aea4f9f020711c9c080081
[]
no_license
RedGear/RedGear
https://github.com/RedGear/RedGear
0d233bd915d1785820ac9170bc2a4ab3efc26d07
6abb42194929a4a62b0a49c56a8deaa736818ab5
refs/heads/master
2015-08-08T10:48:35.934000
2013-12-25T21:18:08
2013-12-25T21:18:08
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package redgear.securecraft; import net.minecraft.block.material.Material; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import redgear.core.block.BlockSmart; import redgear.core.util.ItemStackUtil; public class BlockSmartObsidian extends BlockSmart { public BlockSmartObsidian(int Id, Material material) { super(Id, material, "smartObsidian"); } @Override public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int i, float f, float g, float t) { ItemStack heldItem = player.getHeldItem(); String owner = getOwner(world, x, y, z); if (heldItem != null && ItemToolChisel.class.isAssignableFrom(heldItem.getItem().getClass())) { if (player.username.equals(owner)) { ItemStackUtil.dropItemStack(world, x, y, z, new ItemStack(this, 1, 0)); world.setBlockToAir(x, y, z); return true; } //else // player.addChatMessage("This block is owned by: " + owner); } return false; } }
UTF-8
Java
1,174
java
BlockSmartObsidian.java
Java
[]
null
[]
package redgear.securecraft; import net.minecraft.block.material.Material; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import redgear.core.block.BlockSmart; import redgear.core.util.ItemStackUtil; public class BlockSmartObsidian extends BlockSmart { public BlockSmartObsidian(int Id, Material material) { super(Id, material, "smartObsidian"); } @Override public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int i, float f, float g, float t) { ItemStack heldItem = player.getHeldItem(); String owner = getOwner(world, x, y, z); if (heldItem != null && ItemToolChisel.class.isAssignableFrom(heldItem.getItem().getClass())) { if (player.username.equals(owner)) { ItemStackUtil.dropItemStack(world, x, y, z, new ItemStack(this, 1, 0)); world.setBlockToAir(x, y, z); return true; } //else // player.addChatMessage("This block is owned by: " + owner); } return false; } }
1,174
0.638842
0.637138
38
29.921053
29.810261
124
false
false
0
0
0
0
0
0
1
false
false
6
5921bee657106b65a576de02a533d5bf91af31da
5,050,881,598,069
53f13378b79553a71229d8febae155a75156fbe0
/zop/zop-platform/src/main/java/com/zop/platform/component/base/service/impl/RoleServiceImpl.java
7e9441c6cdc8b6995f8f9bd24f676dc0a045969f
[]
no_license
wsdlcad123/zop
https://github.com/wsdlcad123/zop
cd07cdcdf9a8e342441fc78d9d6623de8dcca33a
73a8d4f580f70484b29a7ce482fa9fbfa0437574
refs/heads/master
2020-04-08T15:04:40.180000
2018-11-28T08:00:07
2018-11-28T08:00:07
159,464,389
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.zop.platform.component.base.service.impl; import com.zop.platform.component.base.bean.Auth; import com.zop.platform.component.base.bean.Role; import com.zop.platform.component.base.dao.IAuthDAO; import com.zop.platform.component.base.dao.IRoleDAO; import com.zop.platform.component.base.service.IRoleService; import com.zop.utils.util.StringUtil; import java.util.List; public class RoleServiceImpl implements IRoleService { private IRoleDAO roleDAO; private IAuthDAO authDAO; public void setRoleDAO(IRoleDAO roleDAO) { this.roleDAO = roleDAO; } public void setAuthDAO(IAuthDAO authDAO) { this.authDAO = authDAO; } /** * 保存 */ public void save(Role role){ this.roleDAO.save(role); } /** * 更新 */ public void update(Role role){ this.roleDAO.update(role); } /** * 获取 */ public Role get(int id){ Role role = this.roleDAO.get(id); if(role == null){ return null; }else{ if(!StringUtil.isEmpty(role.getAuth_value())) { role.setAuthList(this.authDAO.listInIds(role.getAuth_value())); } } return role; } /** * 删除 * @param id */ public void delete(int id){ this.roleDAO.delete(id); } /** * 列表 */ public List list(String orderby, String ascOrDesc){ return this.roleDAO.list(orderby,ascOrDesc); } }
UTF-8
Java
1,509
java
RoleServiceImpl.java
Java
[]
null
[]
package com.zop.platform.component.base.service.impl; import com.zop.platform.component.base.bean.Auth; import com.zop.platform.component.base.bean.Role; import com.zop.platform.component.base.dao.IAuthDAO; import com.zop.platform.component.base.dao.IRoleDAO; import com.zop.platform.component.base.service.IRoleService; import com.zop.utils.util.StringUtil; import java.util.List; public class RoleServiceImpl implements IRoleService { private IRoleDAO roleDAO; private IAuthDAO authDAO; public void setRoleDAO(IRoleDAO roleDAO) { this.roleDAO = roleDAO; } public void setAuthDAO(IAuthDAO authDAO) { this.authDAO = authDAO; } /** * 保存 */ public void save(Role role){ this.roleDAO.save(role); } /** * 更新 */ public void update(Role role){ this.roleDAO.update(role); } /** * 获取 */ public Role get(int id){ Role role = this.roleDAO.get(id); if(role == null){ return null; }else{ if(!StringUtil.isEmpty(role.getAuth_value())) { role.setAuthList(this.authDAO.listInIds(role.getAuth_value())); } } return role; } /** * 删除 * @param id */ public void delete(int id){ this.roleDAO.delete(id); } /** * 列表 */ public List list(String orderby, String ascOrDesc){ return this.roleDAO.list(orderby,ascOrDesc); } }
1,509
0.603089
0.603089
69
20.594202
19.998056
79
false
false
0
0
0
0
0
0
0.318841
false
false
6
a3be2ecb5a810be166d6cd17ed186e03de2d7386
25,769,803,835,574
06e9c46d547b907cc2d5efe28cdb966bd6b521a5
/src/main/java/com/testassignment/shoppingcart/repository/ProductRepository.java
254325a292bd72bf926cae423ad82d16ca0b0175
[]
no_license
ashishn-assignments/igt-assignment
https://github.com/ashishn-assignments/igt-assignment
487ef2a8bfc0875fe4857f86da2a4582899d26b8
0b6f22ed97d390660b9057e53e7da41f0cd1852e
refs/heads/master
2021-01-20T21:06:43.971000
2017-08-30T11:23:18
2017-08-30T11:23:18
101,750,074
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.testassignment.shoppingcart.repository; import org.springframework.data.mongodb.repository.MongoRepository; import com.testassignment.shoppingcart.domain.Product; /** * Created by ashishn on 08/28/2017. */ public interface ProductRepository extends MongoRepository<Product, String> { }
UTF-8
Java
304
java
ProductRepository.java
Java
[ { "context": "nt.shoppingcart.domain.Product;\n\n/**\n * Created by ashishn on 08/28/2017.\n */\npublic interface ProductReposi", "end": 203, "score": 0.9993773698806763, "start": 196, "tag": "USERNAME", "value": "ashishn" } ]
null
[]
package com.testassignment.shoppingcart.repository; import org.springframework.data.mongodb.repository.MongoRepository; import com.testassignment.shoppingcart.domain.Product; /** * Created by ashishn on 08/28/2017. */ public interface ProductRepository extends MongoRepository<Product, String> { }
304
0.8125
0.786184
12
24.333334
29.075573
77
false
false
0
0
0
0
0
0
0.333333
false
false
6
2ff2e88c9c809e45271b4aec87ddb87800c68530
25,769,803,833,383
3dcbf4da0aedbcaebaa902b96dd149221bb8fb5f
/mbb-platform/pdca/mbb-platform/src/main/java/com/mbb/mbbplatform/domain/RentalExtension.java
da44846b95635db16b8f7b1006bf1024f96a63e7
[]
no_license
bharathichikkala/master
https://github.com/bharathichikkala/master
5d4c594aa8d9fd44d36c58464c9705998ea1a21f
b04c0d2eaf829416232686e63352bd5a88c484eb
refs/heads/master
2023-01-21T13:52:10.502000
2019-09-30T08:36:37
2019-09-30T08:36:37
132,092,849
1
1
null
false
2023-01-19T20:28:47
2018-05-04T05:41:29
2020-07-30T12:52:15
2023-01-19T20:28:47
111,863
0
1
108
JavaScript
false
false
package com.mbb.mbbplatform.domain; import java.time.LocalDate; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table(name = "rentalextension") public class RentalExtension { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private LocalDate extendedDate ; private LocalDate extensionEndDate ; private String invoiceNumber ; private String comments ; private Long days ; private Double price ; @ManyToOne @JoinColumn(name = "rentalProductId") private RentalProducts rentalProductId; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public LocalDate getExtendedDate() { return extendedDate; } public LocalDate getExtensionEndDate() { return extensionEndDate; } public void setExtensionEndDate(LocalDate extensionEndDate) { this.extensionEndDate = extensionEndDate; } public void setExtendedDate(LocalDate extendedDate) { this.extendedDate = extendedDate; } public String getInvoiceNumber() { return invoiceNumber; } public RentalProducts getRentalProductId() { return rentalProductId; } public void setRentalProductId(RentalProducts rentalProductId) { this.rentalProductId = rentalProductId; } public void setInvoiceNumber(String invoiceNumber) { this.invoiceNumber = invoiceNumber; } public String getComments() { return comments; } public void setComments(String comments) { this.comments = comments; } public Long getDays() { return days; } public void setDays(Long days) { this.days = days; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } }
UTF-8
Java
1,875
java
RentalExtension.java
Java
[]
null
[]
package com.mbb.mbbplatform.domain; import java.time.LocalDate; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table(name = "rentalextension") public class RentalExtension { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private LocalDate extendedDate ; private LocalDate extensionEndDate ; private String invoiceNumber ; private String comments ; private Long days ; private Double price ; @ManyToOne @JoinColumn(name = "rentalProductId") private RentalProducts rentalProductId; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public LocalDate getExtendedDate() { return extendedDate; } public LocalDate getExtensionEndDate() { return extensionEndDate; } public void setExtensionEndDate(LocalDate extensionEndDate) { this.extensionEndDate = extensionEndDate; } public void setExtendedDate(LocalDate extendedDate) { this.extendedDate = extendedDate; } public String getInvoiceNumber() { return invoiceNumber; } public RentalProducts getRentalProductId() { return rentalProductId; } public void setRentalProductId(RentalProducts rentalProductId) { this.rentalProductId = rentalProductId; } public void setInvoiceNumber(String invoiceNumber) { this.invoiceNumber = invoiceNumber; } public String getComments() { return comments; } public void setComments(String comments) { this.comments = comments; } public Long getDays() { return days; } public void setDays(Long days) { this.days = days; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } }
1,875
0.754133
0.754133
104
17.028847
17.580286
65
false
false
0
0
0
0
0
0
1.115385
false
false
6
cd0066e4b32d52615038d784d24d8874f36cbd0c
31,447,750,598,291
065c1f648e8dd061a20147ff9c0dbb6b5bc8b9be
/checkstyle_cluster/1490/src_32.java
ef48e2b5bcbce62cc75f0e5fa2a7917b3e231a2d
[]
no_license
martinezmatias/GenPat-data-C3
https://github.com/martinezmatias/GenPat-data-C3
63cfe27efee2946831139747e6c20cf952f1d6f6
b360265a6aa3bb21bd1d64f1fc43c3b37d0da2a4
refs/heads/master
2022-04-25T17:59:03.905000
2020-04-15T14:41:34
2020-04-15T14:41:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.google.checkstyle.test.chapter3filestructure.rule331nowildcard; import java.io.File; import java.io.IOException; import java.util.List; import org.junit.BeforeClass; import org.junit.Test; import com.google.checkstyle.test.base.BaseCheckTestSupport; import com.google.checkstyle.test.base.ConfigurationBuilder; import com.puppycrawl.tools.checkstyle.api.CheckstyleException; import com.puppycrawl.tools.checkstyle.api.Configuration; public class AvoidStarImportTest extends BaseCheckTestSupport{ static ConfigurationBuilder builder; @BeforeClass public static void setConfigurationBuilder() throws CheckstyleException, IOException { builder = new ConfigurationBuilder(new File("src/")); } @Test public void starImportTest() throws IOException, Exception { final String[] expected = { "3: Using the '.*' form of import should be avoided - java.io.*.", "4: Using the '.*' form of import should be avoided - java.lang.*.", "18: Using the '.*' form of import should be avoided - javax.swing.WindowConstants.*.", "19: Using the '.*' form of import should be avoided - javax.swing.WindowConstants.*.", }; Configuration checkConfig = builder.getCheckConfig("AvoidStarImport"); String filePath = builder.getFilePath("AvoidStarImportInput"); Integer[] warnList = builder.getLinesWithWarn(filePath); verify(checkConfig, filePath, expected, warnList); } }
UTF-8
Java
1,516
java
src_32.java
Java
[]
null
[]
package com.google.checkstyle.test.chapter3filestructure.rule331nowildcard; import java.io.File; import java.io.IOException; import java.util.List; import org.junit.BeforeClass; import org.junit.Test; import com.google.checkstyle.test.base.BaseCheckTestSupport; import com.google.checkstyle.test.base.ConfigurationBuilder; import com.puppycrawl.tools.checkstyle.api.CheckstyleException; import com.puppycrawl.tools.checkstyle.api.Configuration; public class AvoidStarImportTest extends BaseCheckTestSupport{ static ConfigurationBuilder builder; @BeforeClass public static void setConfigurationBuilder() throws CheckstyleException, IOException { builder = new ConfigurationBuilder(new File("src/")); } @Test public void starImportTest() throws IOException, Exception { final String[] expected = { "3: Using the '.*' form of import should be avoided - java.io.*.", "4: Using the '.*' form of import should be avoided - java.lang.*.", "18: Using the '.*' form of import should be avoided - javax.swing.WindowConstants.*.", "19: Using the '.*' form of import should be avoided - javax.swing.WindowConstants.*.", }; Configuration checkConfig = builder.getCheckConfig("AvoidStarImport"); String filePath = builder.getFilePath("AvoidStarImportInput"); Integer[] warnList = builder.getLinesWithWarn(filePath); verify(checkConfig, filePath, expected, warnList); } }
1,516
0.711082
0.704485
40
36.875
32.515526
99
false
false
0
0
0
0
0
0
0.65
false
false
6
a052db50fed0b78dbbb739e57238218784fefbb6
19,164,144,077,693
ac09a467d9981f67d346d1a9035d98f234ce38d5
/leetcode/src/main/java/org/leetcode/problems/_000000_FirstUniqueNumber.java
301a48b91e692b1c00b799a5ffef03fad728eb5e
[]
no_license
AlexKokoz/leetcode
https://github.com/AlexKokoz/leetcode
03c9749c97c846c4018295008095ac86ae4951ee
9449593df72d86dadc4c470f1f9698e066632859
refs/heads/master
2023-02-23T13:56:38.978000
2023-02-12T21:21:54
2023-02-12T21:21:54
232,152,255
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.leetcode.problems; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * 30-day Leetcoding Challenge 2020 * * @author Alexandros Kokozidis * */ public class _000000_FirstUniqueNumber { class FirstUnique { Set<Integer> values; Map<Integer, ListNode> nodes; ListNode headBorder; ListNode tailBorder; int size; public FirstUnique(int[] nums) { values = new HashSet<>(); nodes = new HashMap<>(); headBorder = new ListNode(0); tailBorder = new ListNode(0); headBorder.next = tailBorder; tailBorder.prev = headBorder; for (int num : nums) add(num); } public int showFirstUnique() { return size == 0 ? -1 : headBorder.next.value; } public void add(int value) { if (values.contains(value)) { if (nodes.containsKey(value)) { ListNode toBeRemoved = nodes.remove(value); ListNode prev = toBeRemoved.prev; ListNode next = toBeRemoved.next; prev.next = next; next.prev = prev; size--; } } else { values.add(value); ListNode newNode = new ListNode(value); nodes.put(value, newNode); ListNode prev = tailBorder.prev; ListNode next = tailBorder; newNode.prev = prev; prev.next = newNode; newNode.next = next; next.prev = newNode; size++; } } class ListNode { private int value; private ListNode prev; private ListNode next; public ListNode(int value) { this.value = value; } } } }
UTF-8
Java
1,501
java
_000000_FirstUniqueNumber.java
Java
[ { "context": " * 30-day Leetcoding Challenge 2020\n * \n * @author Alexandros Kokozidis\n *\n */\npublic class _000000_FirstUniqueNumber {\n\t", "end": 204, "score": 0.9998843669891357, "start": 184, "tag": "NAME", "value": "Alexandros Kokozidis" } ]
null
[]
package org.leetcode.problems; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * 30-day Leetcoding Challenge 2020 * * @author <NAME> * */ public class _000000_FirstUniqueNumber { class FirstUnique { Set<Integer> values; Map<Integer, ListNode> nodes; ListNode headBorder; ListNode tailBorder; int size; public FirstUnique(int[] nums) { values = new HashSet<>(); nodes = new HashMap<>(); headBorder = new ListNode(0); tailBorder = new ListNode(0); headBorder.next = tailBorder; tailBorder.prev = headBorder; for (int num : nums) add(num); } public int showFirstUnique() { return size == 0 ? -1 : headBorder.next.value; } public void add(int value) { if (values.contains(value)) { if (nodes.containsKey(value)) { ListNode toBeRemoved = nodes.remove(value); ListNode prev = toBeRemoved.prev; ListNode next = toBeRemoved.next; prev.next = next; next.prev = prev; size--; } } else { values.add(value); ListNode newNode = new ListNode(value); nodes.put(value, newNode); ListNode prev = tailBorder.prev; ListNode next = tailBorder; newNode.prev = prev; prev.next = newNode; newNode.next = next; next.prev = newNode; size++; } } class ListNode { private int value; private ListNode prev; private ListNode next; public ListNode(int value) { this.value = value; } } } }
1,487
0.648234
0.637575
72
19.847221
13.642926
49
false
false
0
0
0
0
0
0
2.805556
false
false
6
149c3d5b9217674996f0f60d8aabbc7783b86ecd
24,077,586,683,521
f15d87aea76faaafe71f34fbcdc9d20b6f00c84d
/nlp/src/anluit/nlp/test/rules/SynonymMapTest.java
3f06b340148c54944cb17d09de39a43c80a77ccd
[]
no_license
o9simon/anluit
https://github.com/o9simon/anluit
dadda1c11ae19f5998d23e22c71647f64d0efeef
5aa70cab65fe93965eb9f07016f3f3f65cd9d1ff
refs/heads/master
2021-01-22T09:42:23.642000
2017-04-12T20:01:07
2017-04-12T20:01:07
46,887,332
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package anluit.nlp.test.rules; import anluit.nlp.rules.SynonymMap; import junit.framework.*; public class SynonymMapTest extends TestCase { public void testGetKeySynonymNull() { SynonymMap syn = new SynonymMap(); assertEquals(syn.getKeySynonym(null), null); } public void testGetKeySynonymNotExist() { SynonymMap syn = new SynonymMap(); assertEquals(syn.getKeySynonym("doesnotexist"), "doesnotexist"); } public void testGetKeySynonymExist() { SynonymMap syn = new SynonymMap(); syn.add("click", new String[]{"tap", "press"}); assertEquals(syn.getKeySynonym("tap"), "click"); assertEquals(syn.getKeySynonym("press"), "click"); } }
UTF-8
Java
661
java
SynonymMapTest.java
Java
[]
null
[]
package anluit.nlp.test.rules; import anluit.nlp.rules.SynonymMap; import junit.framework.*; public class SynonymMapTest extends TestCase { public void testGetKeySynonymNull() { SynonymMap syn = new SynonymMap(); assertEquals(syn.getKeySynonym(null), null); } public void testGetKeySynonymNotExist() { SynonymMap syn = new SynonymMap(); assertEquals(syn.getKeySynonym("doesnotexist"), "doesnotexist"); } public void testGetKeySynonymExist() { SynonymMap syn = new SynonymMap(); syn.add("click", new String[]{"tap", "press"}); assertEquals(syn.getKeySynonym("tap"), "click"); assertEquals(syn.getKeySynonym("press"), "click"); } }
661
0.727685
0.727685
25
25.440001
21.350559
66
false
false
0
0
0
0
0
0
1.68
false
false
6
f08ce4b095d4e5b9915910157b298ae8b579e2d6
8,151,847,947,372
81423c9d722b30820a6a893541875fd4d8ffb39f
/src/test/java/net/jodah/failsafe/AsyncFailsafeConfigTest.java
cc503d1932650b3aabfcbdfab98c86f1084d1a6e
[ "Apache-2.0" ]
permissive
eformat/failsafe
https://github.com/eformat/failsafe
63bc7f1909109b7fb40ed08d7ed470c1becd6a4a
1ed27d53652910562fd5f4f0f0930ec4a0cc02a4
refs/heads/master
2021-01-16T20:07:09.432000
2016-09-09T01:24:38
2016-09-09T01:24:38
67,763,603
1
0
null
true
2016-09-09T03:46:16
2016-09-09T03:46:16
2016-09-08T23:12:09
2016-09-09T01:24:41
1,460
0
0
0
null
null
null
package net.jodah.failsafe; import static net.jodah.failsafe.Testing.failures; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.when; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import net.jodah.failsafe.FailsafeConfigTest.ListenerCounter; @Test public class AsyncFailsafeConfigTest { Service service = mock(Service.class); ScheduledExecutorService executor; ListenerCounter abort; ListenerCounter complete; ListenerCounter failedAttempt; ListenerCounter failure; ListenerCounter retriesExceeded; ListenerCounter retry; ListenerCounter success; public interface Service { boolean connect(); } @BeforeMethod void beforeMethod() { executor = Executors.newScheduledThreadPool(2); reset(service); abort = new ListenerCounter(); complete = new ListenerCounter(); failedAttempt = new ListenerCounter(); failure = new ListenerCounter(); retriesExceeded = new ListenerCounter(); retry = new ListenerCounter(); success = new ListenerCounter(); } @AfterMethod void afterMethod() throws Throwable { executor.shutdownNow(); executor.awaitTermination(5, TimeUnit.SECONDS); } <T> AsyncFailsafe<T> registerListeners(AsyncFailsafe<T> failsafe) { failsafe.onAbortAsync(e -> abort.async(1)); failsafe.onAbortAsync((r, e) -> abort.async(2)); failsafe.onAbortAsync((r, e, c) -> abort.async(3)); abort.asyncListeners = 3; failsafe.onCompleteAsync((e, r) -> complete.async(1)); failsafe.onCompleteAsync((e, r, c) -> complete.async(2)); complete.asyncListeners = 2; failsafe.onFailedAttemptAsync(e -> failedAttempt.async(1)); failsafe.onFailedAttemptAsync((r, f) -> failedAttempt.async(2)); failsafe.onFailedAttemptAsync((r, f, c) -> failedAttempt.async(3, c)); failedAttempt.asyncListeners = 3; failsafe.onFailureAsync(e -> failure.async(1)); failsafe.onFailureAsync((r, e) -> failure.async(2)); failsafe.onFailureAsync((r, e, c) -> failure.async(3)); failure.asyncListeners = 3; failsafe.onRetriesExceededAsync(e -> retriesExceeded.async(1)); failsafe.onRetriesExceededAsync((r, f) -> retriesExceeded.async(2)); retriesExceeded.asyncListeners = 2; failsafe.onRetryAsync(e -> retry.async(1)); failsafe.onRetryAsync((r, f) -> retry.async(2)); failsafe.onRetryAsync((r, f, c) -> retry.async(3, c)); retry.asyncListeners = 3; failsafe.onSuccessAsync(r -> success.async(1)); failsafe.onSuccessAsync((r, c) -> success.async(2)); success.asyncListeners = 2; return failsafe; } /** * Asserts that listeners are called the expected number of times for a successful completion. */ public void testListenersForSuccess() throws Throwable { Callable<Boolean> callable = () -> service.connect(); // Given - Fail twice then succeed when(service.connect()).thenThrow(failures(2, new IllegalStateException())).thenReturn(false, false, true); RetryPolicy retryPolicy = new RetryPolicy().retryWhen(false); // When registerListeners(Failsafe.with(retryPolicy).with(executor)).get(callable); // Then abort.assertEquals(0); complete.assertEquals(1); failedAttempt.assertEquals(4); failure.assertEquals(0); retriesExceeded.assertEquals(0); retry.assertEquals(4); success.assertEquals(1); } /** * Asserts that listeners are called the expected number of times for an unhandled failure. */ @SuppressWarnings("unchecked") public void testListenersForUnhandledFailure() throws Throwable { Callable<Boolean> callable = () -> service.connect(); // Given - Fail 2 times then don't match policy when(service.connect()).thenThrow(failures(2, new IllegalStateException())) .thenThrow(IllegalArgumentException.class); RetryPolicy retryPolicy = new RetryPolicy().retryOn(IllegalStateException.class).withMaxRetries(10); // When registerListeners(Failsafe.with(retryPolicy).with(executor)).get(callable); // Then abort.assertEquals(0); complete.assertEquals(1); failedAttempt.assertEquals(3); failure.assertEquals(1); retriesExceeded.assertEquals(0); retry.assertEquals(2); success.assertEquals(0); } /** * Asserts that listeners are called the expected number of times when retries are exceeded. */ public void testListenersForRetriesExceeded() throws Throwable { Callable<Boolean> callable = () -> service.connect(); // Given - Fail 4 times and exceed retries when(service.connect()).thenThrow(failures(10, new IllegalStateException())); RetryPolicy retryPolicy = new RetryPolicy().retryWhen(false).withMaxRetries(3); // When registerListeners(Failsafe.with(retryPolicy).with(executor)).get(callable); // Then abort.assertEquals(0); complete.assertEquals(1); failedAttempt.assertEquals(4); failure.assertEquals(1); retriesExceeded.assertEquals(1); retry.assertEquals(3); success.assertEquals(0); } /** * Asserts that listeners are called the expected number of times for an aborted execution. */ @SuppressWarnings("unchecked") public void testListenersForAbort() throws Throwable { Callable<Boolean> callable = () -> service.connect(); // Given - Fail twice then abort when(service.connect()).thenThrow(failures(3, new IllegalStateException())) .thenThrow(new IllegalArgumentException()); RetryPolicy retryPolicy = new RetryPolicy().abortOn(IllegalArgumentException.class).withMaxRetries(3); // When Asserts.assertThrows(() -> registerListeners(Failsafe.with(retryPolicy).with(executor)).get(callable).get(), ExecutionException.class, IllegalArgumentException.class); // Then abort.assertEquals(1); complete.assertEquals(0); failedAttempt.assertEquals(4); failure.assertEquals(0); retriesExceeded.assertEquals(0); retry.assertEquals(3); success.assertEquals(0); } }
UTF-8
Java
6,297
java
AsyncFailsafeConfigTest.java
Java
[]
null
[]
package net.jodah.failsafe; import static net.jodah.failsafe.Testing.failures; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.when; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import net.jodah.failsafe.FailsafeConfigTest.ListenerCounter; @Test public class AsyncFailsafeConfigTest { Service service = mock(Service.class); ScheduledExecutorService executor; ListenerCounter abort; ListenerCounter complete; ListenerCounter failedAttempt; ListenerCounter failure; ListenerCounter retriesExceeded; ListenerCounter retry; ListenerCounter success; public interface Service { boolean connect(); } @BeforeMethod void beforeMethod() { executor = Executors.newScheduledThreadPool(2); reset(service); abort = new ListenerCounter(); complete = new ListenerCounter(); failedAttempt = new ListenerCounter(); failure = new ListenerCounter(); retriesExceeded = new ListenerCounter(); retry = new ListenerCounter(); success = new ListenerCounter(); } @AfterMethod void afterMethod() throws Throwable { executor.shutdownNow(); executor.awaitTermination(5, TimeUnit.SECONDS); } <T> AsyncFailsafe<T> registerListeners(AsyncFailsafe<T> failsafe) { failsafe.onAbortAsync(e -> abort.async(1)); failsafe.onAbortAsync((r, e) -> abort.async(2)); failsafe.onAbortAsync((r, e, c) -> abort.async(3)); abort.asyncListeners = 3; failsafe.onCompleteAsync((e, r) -> complete.async(1)); failsafe.onCompleteAsync((e, r, c) -> complete.async(2)); complete.asyncListeners = 2; failsafe.onFailedAttemptAsync(e -> failedAttempt.async(1)); failsafe.onFailedAttemptAsync((r, f) -> failedAttempt.async(2)); failsafe.onFailedAttemptAsync((r, f, c) -> failedAttempt.async(3, c)); failedAttempt.asyncListeners = 3; failsafe.onFailureAsync(e -> failure.async(1)); failsafe.onFailureAsync((r, e) -> failure.async(2)); failsafe.onFailureAsync((r, e, c) -> failure.async(3)); failure.asyncListeners = 3; failsafe.onRetriesExceededAsync(e -> retriesExceeded.async(1)); failsafe.onRetriesExceededAsync((r, f) -> retriesExceeded.async(2)); retriesExceeded.asyncListeners = 2; failsafe.onRetryAsync(e -> retry.async(1)); failsafe.onRetryAsync((r, f) -> retry.async(2)); failsafe.onRetryAsync((r, f, c) -> retry.async(3, c)); retry.asyncListeners = 3; failsafe.onSuccessAsync(r -> success.async(1)); failsafe.onSuccessAsync((r, c) -> success.async(2)); success.asyncListeners = 2; return failsafe; } /** * Asserts that listeners are called the expected number of times for a successful completion. */ public void testListenersForSuccess() throws Throwable { Callable<Boolean> callable = () -> service.connect(); // Given - Fail twice then succeed when(service.connect()).thenThrow(failures(2, new IllegalStateException())).thenReturn(false, false, true); RetryPolicy retryPolicy = new RetryPolicy().retryWhen(false); // When registerListeners(Failsafe.with(retryPolicy).with(executor)).get(callable); // Then abort.assertEquals(0); complete.assertEquals(1); failedAttempt.assertEquals(4); failure.assertEquals(0); retriesExceeded.assertEquals(0); retry.assertEquals(4); success.assertEquals(1); } /** * Asserts that listeners are called the expected number of times for an unhandled failure. */ @SuppressWarnings("unchecked") public void testListenersForUnhandledFailure() throws Throwable { Callable<Boolean> callable = () -> service.connect(); // Given - Fail 2 times then don't match policy when(service.connect()).thenThrow(failures(2, new IllegalStateException())) .thenThrow(IllegalArgumentException.class); RetryPolicy retryPolicy = new RetryPolicy().retryOn(IllegalStateException.class).withMaxRetries(10); // When registerListeners(Failsafe.with(retryPolicy).with(executor)).get(callable); // Then abort.assertEquals(0); complete.assertEquals(1); failedAttempt.assertEquals(3); failure.assertEquals(1); retriesExceeded.assertEquals(0); retry.assertEquals(2); success.assertEquals(0); } /** * Asserts that listeners are called the expected number of times when retries are exceeded. */ public void testListenersForRetriesExceeded() throws Throwable { Callable<Boolean> callable = () -> service.connect(); // Given - Fail 4 times and exceed retries when(service.connect()).thenThrow(failures(10, new IllegalStateException())); RetryPolicy retryPolicy = new RetryPolicy().retryWhen(false).withMaxRetries(3); // When registerListeners(Failsafe.with(retryPolicy).with(executor)).get(callable); // Then abort.assertEquals(0); complete.assertEquals(1); failedAttempt.assertEquals(4); failure.assertEquals(1); retriesExceeded.assertEquals(1); retry.assertEquals(3); success.assertEquals(0); } /** * Asserts that listeners are called the expected number of times for an aborted execution. */ @SuppressWarnings("unchecked") public void testListenersForAbort() throws Throwable { Callable<Boolean> callable = () -> service.connect(); // Given - Fail twice then abort when(service.connect()).thenThrow(failures(3, new IllegalStateException())) .thenThrow(new IllegalArgumentException()); RetryPolicy retryPolicy = new RetryPolicy().abortOn(IllegalArgumentException.class).withMaxRetries(3); // When Asserts.assertThrows(() -> registerListeners(Failsafe.with(retryPolicy).with(executor)).get(callable).get(), ExecutionException.class, IllegalArgumentException.class); // Then abort.assertEquals(1); complete.assertEquals(0); failedAttempt.assertEquals(4); failure.assertEquals(0); retriesExceeded.assertEquals(0); retry.assertEquals(3); success.assertEquals(0); } }
6,297
0.720025
0.709544
189
32.317459
26.956457
112
false
false
0
0
0
0
0
0
0.703704
false
false
6
97e7118252ccd9007ba83c36b0fcdb4a57485684
8,529,805,096,620
ab3c23f414cfc3eb2bb9c1f186f418e6f9aca53c
/app/src/main/java/uk/co/qubitssolutions/bharatradios/services/data/radio/HttpJsonReader.java
401bae4ab20451eedfd0f6c02eb5e4fdd7a5856f
[]
no_license
kodebot/bharatradios.droid
https://github.com/kodebot/bharatradios.droid
38c55831665f262d5aa582e8a3d584f5cb09e7a5
9ec5838e4d26944d12aeb756fd22705b46475a8e
refs/heads/master
2022-01-06T20:17:40.180000
2019-05-14T06:28:51
2019-05-14T06:28:51
61,404,646
0
0
null
false
2019-05-14T05:58:09
2016-06-17T21:59:43
2016-06-17T22:00:24
2019-05-14T05:58:08
739
0
0
15
Java
false
false
package uk.co.qubitssolutions.bharatradios.services.data.radio; import android.util.Log; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import javax.net.ssl.HttpsURLConnection; public class HttpJsonReader { public static JSONObject read(String urlString) { URL url; HttpsURLConnection connection = null; JSONObject result = new JSONObject(); try { url = new URL(urlString); connection = (HttpsURLConnection) url.openConnection(); InputStream inputStream = new BufferedInputStream(connection.getInputStream()); String stringResult = readStreamAsString(inputStream); result = new JSONObject(stringResult); } catch (MalformedURLException e) { Log.e("", "Invalid URL"); } catch (IOException e) { Log.e("", "Connection error"); } catch (JSONException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } return result; } private static String readStreamAsString(InputStream inputStream) { StringBuilder stringBuilder = new StringBuilder(); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } String line; try { while ((line = reader.readLine()) != null) { stringBuilder.append(line); stringBuilder.append("\n"); } } catch (IOException e) { e.printStackTrace(); } return stringBuilder.toString(); } }
UTF-8
Java
2,047
java
HttpJsonReader.java
Java
[]
null
[]
package uk.co.qubitssolutions.bharatradios.services.data.radio; import android.util.Log; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import javax.net.ssl.HttpsURLConnection; public class HttpJsonReader { public static JSONObject read(String urlString) { URL url; HttpsURLConnection connection = null; JSONObject result = new JSONObject(); try { url = new URL(urlString); connection = (HttpsURLConnection) url.openConnection(); InputStream inputStream = new BufferedInputStream(connection.getInputStream()); String stringResult = readStreamAsString(inputStream); result = new JSONObject(stringResult); } catch (MalformedURLException e) { Log.e("", "Invalid URL"); } catch (IOException e) { Log.e("", "Connection error"); } catch (JSONException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } return result; } private static String readStreamAsString(InputStream inputStream) { StringBuilder stringBuilder = new StringBuilder(); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } String line; try { while ((line = reader.readLine()) != null) { stringBuilder.append(line); stringBuilder.append("\n"); } } catch (IOException e) { e.printStackTrace(); } return stringBuilder.toString(); } }
2,047
0.621397
0.620909
67
29.552238
21.650743
91
false
false
0
0
0
0
0
0
0.567164
false
false
6
c5e86adc5cf45db0d5ee835d3e0e4aeb54751227
10,591,389,421,298
8bd337b8762797e3659199521c01c90cc1cff675
/SimpleApp/src/main/java/pl/mmarczewski/NowyOdczyt.java
abc89a2b98f91859c6512261b503b122361f9829
[]
no_license
MariuszMarczewski/TDD
https://github.com/MariuszMarczewski/TDD
4bce91f59ea8c2acc8e6e12fb97ec76edb776232
2337380ed654483ea5cf00e1d23ad115dffc8840
refs/heads/master
2021-07-13T09:04:03.837000
2019-08-29T12:24:50
2019-08-29T12:24:50
209,847,059
0
0
null
false
2020-10-13T16:11:15
2019-09-20T17:36:05
2019-09-21T07:07:59
2020-10-13T16:11:13
132
0
0
1
Java
false
false
package pl.mmarczewski; import java.util.*; public class NowyOdczyt { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Podaj liczbę produktów: "); int count = Integer.valueOf(in.nextLine()); List<String> cart = new ArrayList<>(count); for(int i = 0; i < count; i++) { System.out.println("Podaj produkt nr " + (i + 1)); cart.add(in.nextLine()); } System.out.println("Zakupione produkty:"); for(String item: cart) { System.out.println(item); } for(int i = 0; i < cart.size(); i++) { System.out.println(cart.get(i)); } Iterator<String> cartIterator = cart.iterator(); while(cartIterator.hasNext()) { System.out.println(cartIterator.next()); } }
UTF-8
Java
908
java
NowyOdczyt.java
Java
[ { "context": "package pl.mmarczewski;\n\nimport java.util.*;\n\npublic class NowyOdczyt", "end": 19, "score": 0.640316903591156, "start": 11, "tag": "USERNAME", "value": "mmarczew" } ]
null
[]
package pl.mmarczewski; import java.util.*; public class NowyOdczyt { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Podaj liczbę produktów: "); int count = Integer.valueOf(in.nextLine()); List<String> cart = new ArrayList<>(count); for(int i = 0; i < count; i++) { System.out.println("Podaj produkt nr " + (i + 1)); cart.add(in.nextLine()); } System.out.println("Zakupione produkty:"); for(String item: cart) { System.out.println(item); } for(int i = 0; i < cart.size(); i++) { System.out.println(cart.get(i)); } Iterator<String> cartIterator = cart.iterator(); while(cartIterator.hasNext()) { System.out.println(cartIterator.next()); } }
908
0.530905
0.527594
60
14.116667
20.433706
62
false
false
0
0
0
0
0
0
0.283333
false
false
6
b733fe733918f3768a6905f3e58942a7d19c601e
10,368,051,079,438
0db4e6c728c12b37d8851cb090b9edbdc122ac69
/app/src/main/java/com/example/vlada/newsappstage2/NewsDataAdapter.java
28d04bbbf879cf2bb37b5991c955e99e83d1634b
[]
no_license
AlexandruVld/NewsAppStage2
https://github.com/AlexandruVld/NewsAppStage2
aede7bb97d86301733a3d4098fee28b1ab156322
29328d2596ba6bb02aef4f7b93d843c7d3294a61
refs/heads/master
2020-03-19T00:18:31.735000
2018-06-01T08:08:53
2018-06-01T08:08:53
135,470,832
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.vlada.newsappstage2; import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Locale; public class NewsDataAdapter extends ArrayAdapter<NewsData> { public NewsDataAdapter(Context context, List<NewsData> data){ super(context,0, data); } // Returns a list item view that displays information about the news at the given position in the list of news @NonNull @Override public View getView(int position, @Nullable View convertView, @Nullable ViewGroup parent){ // Check if there is an existing list item view (called convertView) that we can reuse, // otherwise, if convertView is null, then inflate a new list item layout. View listItemView = convertView; if (listItemView == null){ listItemView = LayoutInflater.from(getContext()).inflate(R.layout.news_details, parent, false); } // Find the news at the given position in the list of news NewsData actualNews = getItem(position); // Find the TextView with the desired id TextView newsCategory = listItemView.findViewById(R.id.news_category); // Display the current news in the TextView newsCategory.setText(actualNews.getCategory()); // Find the TextView with the desired id TextView newsTitle = listItemView.findViewById(R.id.news_title); // Display the current news in the TextView newsTitle.setText(actualNews.getTitle()); // Find the TextView with the desired id TextView newsAuthor = listItemView.findViewById(R.id.news_author); // Display the current news in the TextView newsAuthor.setText(actualNews.getAuthor()); // Find the TextView with the desired id TextView newsDate = listItemView.findViewById(R.id.news_date); // Extract, format and display the current date SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US); SimpleDateFormat personalDateFormat = new SimpleDateFormat("dd MM,yyyy", Locale.US); try { Date newsWebDate = dateFormat.parse(actualNews.getDate()); String date = personalDateFormat.format(newsWebDate); newsDate.setText(date); } catch (ParseException e){ Log.e("Parsing Error","Error parsing date" + e.getMessage()); e.printStackTrace(); } return listItemView; } }
UTF-8
Java
2,818
java
NewsDataAdapter.java
Java
[]
null
[]
package com.example.vlada.newsappstage2; import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Locale; public class NewsDataAdapter extends ArrayAdapter<NewsData> { public NewsDataAdapter(Context context, List<NewsData> data){ super(context,0, data); } // Returns a list item view that displays information about the news at the given position in the list of news @NonNull @Override public View getView(int position, @Nullable View convertView, @Nullable ViewGroup parent){ // Check if there is an existing list item view (called convertView) that we can reuse, // otherwise, if convertView is null, then inflate a new list item layout. View listItemView = convertView; if (listItemView == null){ listItemView = LayoutInflater.from(getContext()).inflate(R.layout.news_details, parent, false); } // Find the news at the given position in the list of news NewsData actualNews = getItem(position); // Find the TextView with the desired id TextView newsCategory = listItemView.findViewById(R.id.news_category); // Display the current news in the TextView newsCategory.setText(actualNews.getCategory()); // Find the TextView with the desired id TextView newsTitle = listItemView.findViewById(R.id.news_title); // Display the current news in the TextView newsTitle.setText(actualNews.getTitle()); // Find the TextView with the desired id TextView newsAuthor = listItemView.findViewById(R.id.news_author); // Display the current news in the TextView newsAuthor.setText(actualNews.getAuthor()); // Find the TextView with the desired id TextView newsDate = listItemView.findViewById(R.id.news_date); // Extract, format and display the current date SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US); SimpleDateFormat personalDateFormat = new SimpleDateFormat("dd MM,yyyy", Locale.US); try { Date newsWebDate = dateFormat.parse(actualNews.getDate()); String date = personalDateFormat.format(newsWebDate); newsDate.setText(date); } catch (ParseException e){ Log.e("Parsing Error","Error parsing date" + e.getMessage()); e.printStackTrace(); } return listItemView; } }
2,818
0.697658
0.696948
70
39.257141
29.639589
114
false
false
0
0
0
0
0
0
0.7
false
false
6
04f27e494110d975f78f2321f4ae554c4706ce88
3,899,830,327,092
00ee844f2497398031c2393397df798e8e7d57aa
/src/bss/sa/handler/record/SendMsgForLimitInteOrderHandler.java
4b1c71081ea0b2d871f0894a2f8cf13fd1278d2d
[]
no_license
vannel/iom_hbcuc
https://github.com/vannel/iom_hbcuc
1a1f612a855d5b724189f9e758b9313816b85111
980f932dcccaaaf379aac82ba312c7272423bd16
refs/heads/master
2020-02-27T11:25:48.355000
2016-07-26T00:57:11
2016-07-26T00:57:11
63,647,647
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package bss.sa.handler.record; import java.util.Properties; import bss.sa.datastruct.db.Record; public class SendMsgForLimitInteOrderHandler extends AbstractRecordHandler { public void process(Record record, Properties wfProps) throws Exception { dataManager.sendMsgForLimitInteOrder(record.getString("INTE_ORDER_ID")); } }
UTF-8
Java
331
java
SendMsgForLimitInteOrderHandler.java
Java
[]
null
[]
package bss.sa.handler.record; import java.util.Properties; import bss.sa.datastruct.db.Record; public class SendMsgForLimitInteOrderHandler extends AbstractRecordHandler { public void process(Record record, Properties wfProps) throws Exception { dataManager.sendMsgForLimitInteOrder(record.getString("INTE_ORDER_ID")); } }
331
0.81571
0.81571
12
26.666666
30.425684
76
false
false
0
0
0
0
0
0
0.75
false
false
6
2aed66c63e68fdc19331d4307e283a65a26296cc
31,679,678,818,864
aa082f913b563ba32ca584d6f1d5f5683646313b
/src/main/java/com/smart/life/saas/domain/core/driver/DriverRepository.java
7722fd721853a21de655e46ad54898e5c365b671
[]
no_license
oclay1st/Journey
https://github.com/oclay1st/Journey
7de948c667ac59f00b43048c78689c71818a3290
1ffae760f858c454e613db2b9f4b3edd72291c91
refs/heads/master
2023-05-04T03:54:13.117000
2020-06-30T02:54:14
2020-06-30T02:54:14
280,774,088
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.smart.life.saas.domain.core.driver; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import java.util.Optional; public interface DriverRepository { Optional<Driver> findById(Long Id); Page<Driver> findAll(Pageable pageable); Driver save(Driver driver); }
UTF-8
Java
330
java
DriverRepository.java
Java
[]
null
[]
package com.smart.life.saas.domain.core.driver; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import java.util.Optional; public interface DriverRepository { Optional<Driver> findById(Long Id); Page<Driver> findAll(Pageable pageable); Driver save(Driver driver); }
330
0.772727
0.772727
15
21
20.255041
48
false
false
0
0
0
0
0
0
0.466667
false
false
6
d31bf021892127d1d1f9f96625e3dbfdbfab9bd0
31,679,678,821,953
b45ea00ee032de61ad63058c9f42a878c0ea94ea
/ORIENTACAO A OBJETOS/supermercado/src/br/com/supermercado/Hora.java
e994e334c1db19f68139b31ab053cc3b28bcf609
[]
no_license
karinamahi/curso-java-progressivo
https://github.com/karinamahi/curso-java-progressivo
c98a7b6cff16463d75f82eef1d18f0c92253aff7
8d17583b24c9884bcadfb13560814201b91e422c
refs/heads/master
2020-05-25T11:53:37.371000
2014-08-02T16:40:02
2014-08-02T16:40:02
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.supermercado; public class Hora { private int hours; private int minutes; private int seconds; public Hora(int hour, int minute, int second){ if(hours>=0 && hours<24){ this.hours = hour; } else{ throw new IllegalArgumentException("Hora inválida"); } if(minutes>=0 && minutes<60){ this.minutes = minute; } else{ throw new IllegalArgumentException("Minutos inválidos"); } if(seconds>=0 && seconds<60){ this.seconds = second; } else{ throw new IllegalArgumentException("Segundos inválidos"); } } @Override public String toString(){ return String.format("%d:%d:%d", getHour(), getMinute(), getSecond()); } public int getHour(){ return this.hours; } public int getMinute(){ return this.minutes; } public int getSecond(){ return this.seconds; } }
ISO-8859-2
Java
850
java
Hora.java
Java
[]
null
[]
package br.com.supermercado; public class Hora { private int hours; private int minutes; private int seconds; public Hora(int hour, int minute, int second){ if(hours>=0 && hours<24){ this.hours = hour; } else{ throw new IllegalArgumentException("Hora inválida"); } if(minutes>=0 && minutes<60){ this.minutes = minute; } else{ throw new IllegalArgumentException("Minutos inválidos"); } if(seconds>=0 && seconds<60){ this.seconds = second; } else{ throw new IllegalArgumentException("Segundos inválidos"); } } @Override public String toString(){ return String.format("%d:%d:%d", getHour(), getMinute(), getSecond()); } public int getHour(){ return this.hours; } public int getMinute(){ return this.minutes; } public int getSecond(){ return this.seconds; } }
850
0.650531
0.639906
51
15.607843
17.641394
72
false
false
0
0
0
0
0
0
1.921569
false
false
6
f5331a6cef6eefaefd954071d7aa5731b6781db3
6,854,767,856,726
28725f8b30641b62e88ebefe7a398aee24e3b2bf
/lab5/src/lab5/simulator/RunSim.java
16994eed31ed19a4833278ea0ba26b0f0d280dbb
[]
no_license
Racix/lab5
https://github.com/Racix/lab5
4f6ec32d2e29f034fd52b5682893091abdfdc1a6
b8bafb77c5deb660f1fac7cec96f58ee9626be5e
refs/heads/master
2021-02-15T08:30:45.990000
2020-03-11T17:11:15
2020-03-11T17:11:15
244,882,501
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package lab5.simulator; public class RunSim { private SequenceOrder order; private SimState state; private SimView view; private EventQueue queue; public RunSim(SimState state, SequenceOrder order, EventQueue queue, SimView view) { this.state = state; this.order = order; this.queue = queue; this.view = view; } public void run() { view.startPrint(); while(state.isON()) { Event thisEvent = queue.getFEvent(); thisEvent.Execute(order,state); } view.lastPrint(); } }
UTF-8
Java
530
java
RunSim.java
Java
[]
null
[]
package lab5.simulator; public class RunSim { private SequenceOrder order; private SimState state; private SimView view; private EventQueue queue; public RunSim(SimState state, SequenceOrder order, EventQueue queue, SimView view) { this.state = state; this.order = order; this.queue = queue; this.view = view; } public void run() { view.startPrint(); while(state.isON()) { Event thisEvent = queue.getFEvent(); thisEvent.Execute(order,state); } view.lastPrint(); } }
530
0.666038
0.664151
26
18.384615
17.602615
85
false
false
0
0
0
0
0
0
1.923077
false
false
6
b769225e442613bbba9f93293b45f956370fa655
28,037,546,526,073
5c6e8637d85fa38eddd2cb2667df2c1b0e725b98
/superShop-service/src/main/java/com/zss/superShop/manager/RedisManager.java
ad4ba13e038aa3096afa1a8bd0c1d1b60a723adf
[]
no_license
SimonZhuss/superShop
https://github.com/SimonZhuss/superShop
02c746bc06868bd3bc41bd28f50237c4e53e8237
05a013e4d54d24707cc7ab8dd5f440b14aee3d33
refs/heads/master
2020-03-28T00:48:16.700000
2018-09-14T02:13:45
2018-09-14T02:13:45
147,450,930
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.zss.superShop.manager; import java.io.Serializable; import java.util.concurrent.TimeUnit; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.stereotype.Component; /** * Created by qhong on 2018/6/22 16:26 **/ @Component public class RedisManager { @Autowired private RedisTemplate redisTemplate; /** * 删除对应的value * * @param key */ public void remove(final String prefix, final String key) { if (exists(prefix, key)) { String fullKey = prefix + ":" + key; redisTemplate.delete(fullKey); } } /** * 判断缓存中是否有对应的value * * @param key * @return */ public boolean exists(final String prefix, final String key) { String fullKey = prefix + ":" + key; return redisTemplate.hasKey(fullKey); } /** * 读取缓存 * * @param key * @return */ public Object get(final String prefix, final String key) { Object result = null; String fullKey = prefix + ":" + key; ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); result = operations.get(fullKey); return result; } /** * 写入缓存 * @param key * @param value * @return */ public boolean set(final String key, Object value, Long expireTime) { boolean result = false; try { ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); operations.set(key, value); redisTemplate.expire(key, expireTime, TimeUnit.SECONDS); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } /** * 写入缓存 * * @param key * @param value * @return */ public boolean set(final String prefix, final String key, Object value) { boolean result = false; String fullKey = prefix + ":" + key; try { ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); operations.set(fullKey, value); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } /** * 写入缓存 * * @param key * @param value * @return */ public boolean set(final String prefix, final String key, Object value, Long expireTime) { boolean result = false; String fullKey = prefix + ":" + key; try { ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); operations.set(fullKey, value); redisTemplate.expire(fullKey, expireTime, TimeUnit.SECONDS); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } /** * 读取缓存 * * @param key * @return */ public Object get(final String key) { Object result = null; ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); result = operations.get(key); return result; } }
UTF-8
Java
2,896
java
RedisManager.java
Java
[ { "context": "framework.stereotype.Component;\n\n/**\n * Created by qhong on 2018/6/22 16:26\n **/\n@Component\npublic class R", "end": 357, "score": 0.9985015392303467, "start": 352, "tag": "USERNAME", "value": "qhong" } ]
null
[]
package com.zss.superShop.manager; import java.io.Serializable; import java.util.concurrent.TimeUnit; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.stereotype.Component; /** * Created by qhong on 2018/6/22 16:26 **/ @Component public class RedisManager { @Autowired private RedisTemplate redisTemplate; /** * 删除对应的value * * @param key */ public void remove(final String prefix, final String key) { if (exists(prefix, key)) { String fullKey = prefix + ":" + key; redisTemplate.delete(fullKey); } } /** * 判断缓存中是否有对应的value * * @param key * @return */ public boolean exists(final String prefix, final String key) { String fullKey = prefix + ":" + key; return redisTemplate.hasKey(fullKey); } /** * 读取缓存 * * @param key * @return */ public Object get(final String prefix, final String key) { Object result = null; String fullKey = prefix + ":" + key; ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); result = operations.get(fullKey); return result; } /** * 写入缓存 * @param key * @param value * @return */ public boolean set(final String key, Object value, Long expireTime) { boolean result = false; try { ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); operations.set(key, value); redisTemplate.expire(key, expireTime, TimeUnit.SECONDS); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } /** * 写入缓存 * * @param key * @param value * @return */ public boolean set(final String prefix, final String key, Object value) { boolean result = false; String fullKey = prefix + ":" + key; try { ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); operations.set(fullKey, value); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } /** * 写入缓存 * * @param key * @param value * @return */ public boolean set(final String prefix, final String key, Object value, Long expireTime) { boolean result = false; String fullKey = prefix + ":" + key; try { ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); operations.set(fullKey, value); redisTemplate.expire(fullKey, expireTime, TimeUnit.SECONDS); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } /** * 读取缓存 * * @param key * @return */ public Object get(final String key) { Object result = null; ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); result = operations.get(key); return result; } }
2,896
0.682011
0.678116
125
21.591999
22.359999
91
false
false
0
0
0
0
0
0
1.864
false
false
6
d7d54a4fe82f66014d8c881ceaad6676f6ba94b7
3,418,793,990,382
909990cad46c3266b8234054602da385b0454ee7
/app/src/main/java/com/bs/dental/model/ConfirmAutorizeDotNetCheckoutResponse.java
4a67504fee551bbda2c1b6cd1fcded8fc0edc06c
[]
no_license
mmkarimirad/Densyx-android
https://github.com/mmkarimirad/Densyx-android
97ce927597f592cb2f248513a5578de72f8e0452
2161a56a0237eb06ef6aca2b5e5f9e05f314d11a
refs/heads/master
2020-05-31T08:14:06.699000
2019-06-04T10:40:28
2019-06-04T10:40:28
190,181,133
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bs.dental.model; /** * Created by bs-110 on 1/8/2016. */ public class ConfirmAutorizeDotNetCheckoutResponse extends ConfirmPayPalCheckoutResponse { }
UTF-8
Java
165
java
ConfirmAutorizeDotNetCheckoutResponse.java
Java
[ { "context": "package com.bs.dental.model;\n\n/**\n * Created by bs-110 on 1/8/2016.\n */\npublic class ConfirmAutorizeDotN", "end": 54, "score": 0.9992520213127136, "start": 48, "tag": "USERNAME", "value": "bs-110" } ]
null
[]
package com.bs.dental.model; /** * Created by bs-110 on 1/8/2016. */ public class ConfirmAutorizeDotNetCheckoutResponse extends ConfirmPayPalCheckoutResponse { }
165
0.781818
0.727273
7
22.571428
30.297842
90
false
false
0
0
0
0
0
0
0.142857
false
false
6
c380894ac23459b20c7df9f51ff3b36dab1dc341
19,945,828,183,219
bf8cfbd8113c89f3c7a3817d3c9c7d3a2e49d90a
/Java/1ModuloJavaPOO/Ejercicio13.java
1f35ba5f2ccbf177fbfb659b71a0d4d1edfde851
[ "MIT" ]
permissive
kiezmi/BootCamp-FullStack
https://github.com/kiezmi/BootCamp-FullStack
30473332b7bb521d911537abd54ecadefabd40e6
bfa03947d090a91549d46443a1aa90bfe1c0dec9
refs/heads/master
2020-04-08T07:59:06.295000
2018-11-26T12:42:04
2018-11-26T12:42:04
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.EjerciciosJava.ejercicios_1; public class Ejercicio13 { public static void main(String[] args) { //13º Actividad. //Escribe un programa que muestre tres apuestas de la quiniela en tres columnas // para los 14 partidos y el pleno al quince (15 filas) // String equipos[] = {"Valencia", "Barcelona", "Madrid", "Atletico", "Sevilla", "Betis", "Atheli", "Real Sociedad"}; for (int filas = 1; filas < 15; filas++) { System.out.print("Partido " + filas + " |"); for (int columnas = 0; columnas < 3; columnas++) { for (int i = 0; i < 1; i++) { double dato = Math.random() * 3 + 1; switch ((int) dato) { case 1: System.out.print(" 1 | "); break; case 2: System.out.print(" X | "); break; case 3: System.out.print(" 2 | "); break; } } } System.out.println(); } double pleno = Math.random() * 3 + 1; String apuesta15 = ""; switch ((int) pleno) { case 1: apuesta15 = " 1"; break; case 2: apuesta15 = " X"; break; case 3: apuesta15 = " 2"; break; } System.out.println("Pleno al 15: " + apuesta15); } }
UTF-8
Java
1,628
java
Ejercicio13.java
Java
[]
null
[]
package com.EjerciciosJava.ejercicios_1; public class Ejercicio13 { public static void main(String[] args) { //13º Actividad. //Escribe un programa que muestre tres apuestas de la quiniela en tres columnas // para los 14 partidos y el pleno al quince (15 filas) // String equipos[] = {"Valencia", "Barcelona", "Madrid", "Atletico", "Sevilla", "Betis", "Atheli", "Real Sociedad"}; for (int filas = 1; filas < 15; filas++) { System.out.print("Partido " + filas + " |"); for (int columnas = 0; columnas < 3; columnas++) { for (int i = 0; i < 1; i++) { double dato = Math.random() * 3 + 1; switch ((int) dato) { case 1: System.out.print(" 1 | "); break; case 2: System.out.print(" X | "); break; case 3: System.out.print(" 2 | "); break; } } } System.out.println(); } double pleno = Math.random() * 3 + 1; String apuesta15 = ""; switch ((int) pleno) { case 1: apuesta15 = " 1"; break; case 2: apuesta15 = " X"; break; case 3: apuesta15 = " 2"; break; } System.out.println("Pleno al 15: " + apuesta15); } }
1,628
0.395206
0.369392
59
26.542374
24.871412
124
false
false
0
0
0
0
0
0
0.627119
false
false
13
a6f4af5d856962d39892afa4107be92b2ad1edf0
1,451,698,946,652
d4184d83154ad52fc359925f55cf40fecce94041
/design_pattern/src/design_pattern/structural/Proxy.java
9ab1674d6229c031f48724b9e805ffa9ce7a617c
[]
no_license
shadab005/DataStructureAndAlgo
https://github.com/shadab005/DataStructureAndAlgo
8322551d9f04a782852ba2520bc77dc13abe592c
9883105fbf3c785a2f2fc39f6175255a152dcd69
refs/heads/master
2022-05-06T04:44:28.051000
2022-03-12T11:57:01
2022-03-12T11:57:01
92,103,132
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package design_pattern.structural; /* * Proxy is a structural design pattern that lets you provide a substitute or placeholder for another object. * A proxy controls access to the original object, allowing you to perform something * either before or after the request gets through to the original object. * * Type of proxies : * Remote Proxy - * With Remote Proxy, the proxy acts as a local representative for an object that lives in a different JVM. * A method call on the proxy results in the call being transferred over the wire, invoked remotely, * and the result being returned back to the proxy and then to the Client. * In remote proxy you create stub classes at client side to interact over the network with the Skeleton of main service class. * java rmi is a type of remote proxy * * Virtual Proxy - * acts as a representative for an object that may be expensive to create. * The Virtual Proxy often defers the creation of the object until it is needed; the Virtual Proxy * also acts as a surrogate for the object before and while it is being created. * After that, the proxy delegates requests directly to the RealSubject. * * Note : Proxies can be used in case real subject takes time to instantiate (Virtual Proxy), some protection is needed from unwanted access (Protection Proxy), * or hide the fact that the subject in running on remote machines (Remote Proxy). * * * Note: * Adapter provides a different interface to the wrapped object, Proxy provides it with the same interface */ public class Proxy { public static void main(String[] args) { // TODO Auto-generated method stub } }
UTF-8
Java
1,644
java
Proxy.java
Java
[]
null
[]
package design_pattern.structural; /* * Proxy is a structural design pattern that lets you provide a substitute or placeholder for another object. * A proxy controls access to the original object, allowing you to perform something * either before or after the request gets through to the original object. * * Type of proxies : * Remote Proxy - * With Remote Proxy, the proxy acts as a local representative for an object that lives in a different JVM. * A method call on the proxy results in the call being transferred over the wire, invoked remotely, * and the result being returned back to the proxy and then to the Client. * In remote proxy you create stub classes at client side to interact over the network with the Skeleton of main service class. * java rmi is a type of remote proxy * * Virtual Proxy - * acts as a representative for an object that may be expensive to create. * The Virtual Proxy often defers the creation of the object until it is needed; the Virtual Proxy * also acts as a surrogate for the object before and while it is being created. * After that, the proxy delegates requests directly to the RealSubject. * * Note : Proxies can be used in case real subject takes time to instantiate (Virtual Proxy), some protection is needed from unwanted access (Protection Proxy), * or hide the fact that the subject in running on remote machines (Remote Proxy). * * * Note: * Adapter provides a different interface to the wrapped object, Proxy provides it with the same interface */ public class Proxy { public static void main(String[] args) { // TODO Auto-generated method stub } }
1,644
0.754258
0.754258
36
44.666668
45.416592
160
false
false
0
0
0
0
0
0
0.388889
false
false
13
da7845fa155828e892d7743a1673abe51c237155
24,867,860,686,968
314217c2e59bd95c94b85d1a7008dc40697d22cc
/electronicsinitialdata/src/com/electronics/initialdata/constants/ElectronicsInitialDataConstants.java
f056539ae96282daa85caf11241d228aae52d378
[]
no_license
kislushenko/electronics
https://github.com/kislushenko/electronics
19d6400dc0b61a77b81d3452631c8ef74c09cf9a
c1641655cc899fec4503bff8394573af22122547
refs/heads/main
2023-06-27T23:58:03.466000
2021-08-08T12:53:58
2021-08-08T12:53:58
393,751,913
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved. */ package com.electronics.initialdata.constants; /** * Global class for all ElectronicsInitialData constants. */ public final class ElectronicsInitialDataConstants extends GeneratedElectronicsInitialDataConstants { public static final String EXTENSIONNAME = "electronicsinitialdata"; private ElectronicsInitialDataConstants() { //empty } }
UTF-8
Java
434
java
ElectronicsInitialDataConstants.java
Java
[]
null
[]
/* * Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved. */ package com.electronics.initialdata.constants; /** * Global class for all ElectronicsInitialData constants. */ public final class ElectronicsInitialDataConstants extends GeneratedElectronicsInitialDataConstants { public static final String EXTENSIONNAME = "electronicsinitialdata"; private ElectronicsInitialDataConstants() { //empty } }
434
0.790323
0.781106
17
24.529411
32.2383
99
false
false
0
0
0
0
0
0
0.470588
false
false
13
4380faad712c269366dfe6488739f1539a2199a6
12,043,088,301,443
66a0ca1a77cd4d79a4e8849d16f7ec25885b251d
/vertx-service-discovery-features/src/main/java/tech/vision8/vertx/common/config/MainConfig.java
85a2760e7ed71bed12927645ab7b1f5f2e01c586
[]
no_license
vision8tech/vertx-playground
https://github.com/vision8tech/vertx-playground
4b69e9609b3f7345d6f502e791bff3f49fefe51c
fb6de7e936aa90efb3bb2350bbb594c651d55472
refs/heads/master
2020-12-03T00:03:25.798000
2020-10-13T12:27:21
2020-10-13T12:27:21
95,979,674
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package tech.vision8.vertx.common.config; import io.vertx.config.ConfigRetriever; import io.vertx.config.ConfigRetrieverOptions; import io.vertx.config.ConfigStoreOptions; import io.vertx.core.Future; import io.vertx.core.Vertx; import io.vertx.core.json.JsonObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Simplistic main service configuration component. * * @author vision8 */ public class MainConfig { private static MainConfig instance = new MainConfig(); private static final Logger logger = LoggerFactory.getLogger(MainConfig.class); private JsonObject config; private boolean inited; /** * Get the instance of MainConfig. */ public static MainConfig getInstance() { return instance; } /** * Initialize the configuration based on a config file. */ public Future<Void> init(String configFilePath) { return init(Vertx.currentContext().owner(), configFilePath); } /** * Initialize the configuration based on a config file.<br/> * This version expects a provided vertx instance and it is used within the tests * as in that context Vertx.currentContext() does not exist. */ public Future<Void> init(Vertx vertx, String configFilePath) { Future<Void> initConfigFuture = Future.future(); ConfigStoreOptions configStoreOptions = new ConfigStoreOptions(); if (configFilePath != null) { configStoreOptions.setType("file") .setConfig(new JsonObject().put("path", configFilePath)); } ConfigRetriever retriever = ConfigRetriever.create(vertx, new ConfigRetrieverOptions().addStore(configStoreOptions)); retriever.getConfig(ar -> { if (ar.failed()) { logger.error("Error loading config from '{}' file: {}", configFilePath, ar.cause().getMessage()); initConfigFuture.fail(ar.cause()); } else { this.config = ar.result(); inited = true; logger.info("Loaded config from '{}' file.", configFilePath); initConfigFuture.complete(); } }); return initConfigFuture; } /** Get the config object. */ public JsonObject getConfig() { return config; } /** It tells if this component is initialized. */ public boolean isInited() { return inited; } }
UTF-8
Java
2,464
java
MainConfig.java
Java
[ { "context": "ain service configuration component.\n *\n * @author vision8\n */\npublic class MainConfig {\n\n private static", "end": 404, "score": 0.9993598461151123, "start": 397, "tag": "USERNAME", "value": "vision8" } ]
null
[]
package tech.vision8.vertx.common.config; import io.vertx.config.ConfigRetriever; import io.vertx.config.ConfigRetrieverOptions; import io.vertx.config.ConfigStoreOptions; import io.vertx.core.Future; import io.vertx.core.Vertx; import io.vertx.core.json.JsonObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Simplistic main service configuration component. * * @author vision8 */ public class MainConfig { private static MainConfig instance = new MainConfig(); private static final Logger logger = LoggerFactory.getLogger(MainConfig.class); private JsonObject config; private boolean inited; /** * Get the instance of MainConfig. */ public static MainConfig getInstance() { return instance; } /** * Initialize the configuration based on a config file. */ public Future<Void> init(String configFilePath) { return init(Vertx.currentContext().owner(), configFilePath); } /** * Initialize the configuration based on a config file.<br/> * This version expects a provided vertx instance and it is used within the tests * as in that context Vertx.currentContext() does not exist. */ public Future<Void> init(Vertx vertx, String configFilePath) { Future<Void> initConfigFuture = Future.future(); ConfigStoreOptions configStoreOptions = new ConfigStoreOptions(); if (configFilePath != null) { configStoreOptions.setType("file") .setConfig(new JsonObject().put("path", configFilePath)); } ConfigRetriever retriever = ConfigRetriever.create(vertx, new ConfigRetrieverOptions().addStore(configStoreOptions)); retriever.getConfig(ar -> { if (ar.failed()) { logger.error("Error loading config from '{}' file: {}", configFilePath, ar.cause().getMessage()); initConfigFuture.fail(ar.cause()); } else { this.config = ar.result(); inited = true; logger.info("Loaded config from '{}' file.", configFilePath); initConfigFuture.complete(); } }); return initConfigFuture; } /** Get the config object. */ public JsonObject getConfig() { return config; } /** It tells if this component is initialized. */ public boolean isInited() { return inited; } }
2,464
0.637581
0.635958
93
25.494623
26.413837
113
false
false
0
0
0
0
0
0
0.387097
false
false
13
ea3b6ea11873c3db83de83c7dae2942c27510621
12,043,088,304,618
f52840214186fffa97f136fa3d7333484df7166b
/Trees/BST.java
e0b8402801ad0c4c46b0fc979ef348d95802650d
[]
no_license
Shivanibhawsar/JavaExamples
https://github.com/Shivanibhawsar/JavaExamples
c39947ab8689df5266475ba4df624499507817f4
6b0c250be00819d0d206b96612ef617774d15a28
refs/heads/master
2020-05-04T02:09:27.462000
2019-04-28T10:04:20
2019-04-28T10:04:20
178,921,390
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package javaapplication2; import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; /** * * @author ShivaniBhawsar */ class Node{ int data; Node left; Node right; Node(int d){ data = d; left = null; right = null; } int getData(){ return data; } Node getLeft(){ return left; } Node getRight(){ return right; } void setLeft(Node n){ left = n; } void setRight(Node n){ right = n; } } public class BST { public static Node root; BST(){ root = null; } Node insert(int d, Node root){ if(root == null){ root = new Node(d); return root; } else{ if(root.data == d){ return root; } else if(root.data> d){ root.left = insert(d,root.left); } else{ root.right = insert(d,root.right); } } return root; } void inorder(Node root){ if(root == null){ return; }else{ inorder(root.left); System.out.println(root.data); inorder(root.right); } } Node delete(Node root , int d){ Node temp; if(root == null){ return null; } else if(root.data < d){ root.right = delete(root.right,d); } else if(root.data>d){ root.left = delete(root.left,d); } else{ if(root.left!=null && root.right!=null){ temp = FindMax(root.left); System.out.println("temp"+temp.data); root.data = temp.data; root.left = delete(root.left , temp.data); } else{ temp = root; if(root.left == null){ root = root.right; } else if(root.right == null){ root = root.left; } } } return root; } public Node LCA_binarytree(Node root, int a, int b){ Node left,right; if(root == null){ return null; } if(root.data == a || root.data == b){ return root; } else{ left = LCA_binarytree(root.left,a,b); right = LCA_binarytree(root.right ,a,b); if(left!=null && right!=null){ return root; }else if(left!=null){ return left; }else{ return right; } } } int Catalan(int nodes){ if(nodes == 0 || nodes == 1){ return 1; }else{ int count = 0; for(int i=1;i<=nodes;i++){ count += Catalan(i-1)*Catalan(nodes-i); } return count; } } Boolean search(Node root,int data){ if(root==null){ return null; } if(root.data==data){ return true; } else{ if(root.data<data){ return search(root.right,data); } else{ return search(root.left,data); } } } public Node FindMax(Node root){ if(root == null){ return null; }else if(root.right == null){ return root; } else{ root = FindMax(root.right); return root; } } void levelorder(Node root){ Queue<Node> q = new LinkedList<Node>(); q.offer(root); while(!q.isEmpty()){ Node temp = q.remove(); System.out.print(temp.data+" "); if(temp.left!=null){ q.offer(temp.left); }if(temp.right!=null){ q.offer(temp.right); } } } public static void main(String args[]){ BST bs = new BST(); Node root_LCA; root = bs.insert(12, root); root = bs.insert(5, root); root = bs.insert(15, root); root = bs.insert(3, root); root = bs.insert(7, root); root = bs.insert(13, root); root = bs.insert(17, root); root = bs.insert(1, root); root = bs.insert(9, root); bs.inorder(root); System.out.println("levelorder"); System.out.println("search:"+bs.search(root,5)); bs.levelorder(root); System.out.println(root.data); System.out.println("Catalan:"+bs.Catalan(3)); root_LCA = bs.LCA_binarytree(root, 3,7); System.out.println("LCA:"+root_LCA.data); //System.out.println((bs.FindMax(root)).data); root = bs.delete(root , 15); System.out.println(root.right.data); } }
UTF-8
Java
5,277
java
BST.java
Java
[ { "context": "edList;\nimport java.util.Queue;\n\n/**\n *\n * @author ShivaniBhawsar\n */\nclass Node{\n int data;\n Node left;\n ", "end": 326, "score": 0.9998424649238586, "start": 312, "tag": "NAME", "value": "ShivaniBhawsar" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package javaapplication2; import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; /** * * @author ShivaniBhawsar */ class Node{ int data; Node left; Node right; Node(int d){ data = d; left = null; right = null; } int getData(){ return data; } Node getLeft(){ return left; } Node getRight(){ return right; } void setLeft(Node n){ left = n; } void setRight(Node n){ right = n; } } public class BST { public static Node root; BST(){ root = null; } Node insert(int d, Node root){ if(root == null){ root = new Node(d); return root; } else{ if(root.data == d){ return root; } else if(root.data> d){ root.left = insert(d,root.left); } else{ root.right = insert(d,root.right); } } return root; } void inorder(Node root){ if(root == null){ return; }else{ inorder(root.left); System.out.println(root.data); inorder(root.right); } } Node delete(Node root , int d){ Node temp; if(root == null){ return null; } else if(root.data < d){ root.right = delete(root.right,d); } else if(root.data>d){ root.left = delete(root.left,d); } else{ if(root.left!=null && root.right!=null){ temp = FindMax(root.left); System.out.println("temp"+temp.data); root.data = temp.data; root.left = delete(root.left , temp.data); } else{ temp = root; if(root.left == null){ root = root.right; } else if(root.right == null){ root = root.left; } } } return root; } public Node LCA_binarytree(Node root, int a, int b){ Node left,right; if(root == null){ return null; } if(root.data == a || root.data == b){ return root; } else{ left = LCA_binarytree(root.left,a,b); right = LCA_binarytree(root.right ,a,b); if(left!=null && right!=null){ return root; }else if(left!=null){ return left; }else{ return right; } } } int Catalan(int nodes){ if(nodes == 0 || nodes == 1){ return 1; }else{ int count = 0; for(int i=1;i<=nodes;i++){ count += Catalan(i-1)*Catalan(nodes-i); } return count; } } Boolean search(Node root,int data){ if(root==null){ return null; } if(root.data==data){ return true; } else{ if(root.data<data){ return search(root.right,data); } else{ return search(root.left,data); } } } public Node FindMax(Node root){ if(root == null){ return null; }else if(root.right == null){ return root; } else{ root = FindMax(root.right); return root; } } void levelorder(Node root){ Queue<Node> q = new LinkedList<Node>(); q.offer(root); while(!q.isEmpty()){ Node temp = q.remove(); System.out.print(temp.data+" "); if(temp.left!=null){ q.offer(temp.left); }if(temp.right!=null){ q.offer(temp.right); } } } public static void main(String args[]){ BST bs = new BST(); Node root_LCA; root = bs.insert(12, root); root = bs.insert(5, root); root = bs.insert(15, root); root = bs.insert(3, root); root = bs.insert(7, root); root = bs.insert(13, root); root = bs.insert(17, root); root = bs.insert(1, root); root = bs.insert(9, root); bs.inorder(root); System.out.println("levelorder"); System.out.println("search:"+bs.search(root,5)); bs.levelorder(root); System.out.println(root.data); System.out.println("Catalan:"+bs.Catalan(3)); root_LCA = bs.LCA_binarytree(root, 3,7); System.out.println("LCA:"+root_LCA.data); //System.out.println((bs.FindMax(root)).data); root = bs.delete(root , 15); System.out.println(root.right.data); } }
5,277
0.434148
0.429221
234
21.551283
14.933741
79
false
false
0
0
0
0
0
0
0.538462
false
false
13
f5b2b2becdb1228385ac6b648b62ac801b5de30f
33,328,946,255,264
9a6ea6087367965359d644665b8d244982d1b8b6
/src/main/java/X/AnonymousClass3II.java
b4675abe85c054bc4a605f450cfb0190e3ec5b6c
[]
no_license
technocode/com.wa_2.21.2
https://github.com/technocode/com.wa_2.21.2
a3dd842758ff54f207f1640531374d3da132b1d2
3c4b6f3c7bdef7c1523c06d5bd9a90b83acc80f9
refs/heads/master
2023-02-12T11:20:28.666000
2021-01-14T10:22:21
2021-01-14T10:22:21
329,578,591
2
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package X; /* renamed from: X.3II reason: invalid class name */ public final /* synthetic */ class AnonymousClass3II implements AbstractC63602wh { public final /* synthetic */ AbstractC63672wp A00; public /* synthetic */ AnonymousClass3II(AbstractC63672wp r1) { this.A00 = r1; } }
UTF-8
Java
304
java
AnonymousClass3II.java
Java
[]
null
[]
package X; /* renamed from: X.3II reason: invalid class name */ public final /* synthetic */ class AnonymousClass3II implements AbstractC63602wh { public final /* synthetic */ AbstractC63672wp A00; public /* synthetic */ AnonymousClass3II(AbstractC63672wp r1) { this.A00 = r1; } }
304
0.694079
0.615132
10
29.4
29.84024
82
false
false
0
0
0
0
0
0
0.3
false
false
13
00d7c80d41a0b9e6a1402e31a4193de74f0542b0
9,268,539,436,297
657527b04857e196ab8630c32a94c772867ca153
/walletapp/src/walletapp/WalletAccount.java
b52480881129384ba44cff4a1c6b23491a9f43bf
[]
no_license
Nikita8654/Material
https://github.com/Nikita8654/Material
b01ff3df0ede171f9b98719fe8eca53348f6c8b8
8dc1218f0c60074b363b8c00e1619ee10fee7421
refs/heads/master
2021-01-09T12:13:09.603000
2020-02-22T07:07:23
2020-02-22T07:07:23
242,296,437
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package walletapp; import java.util.ArrayList; public class WalletAccount extends UserInfo { private long ACCOUNT_ID; private double ACCOUNT_BALANCE; private banktype Status; private ArrayList<WalletTransaction> TransactionHistory; @Override public void signUp(String username, String password, String phoneno, String loginname, banktype status) throws ShowException { double accountbalance=1000; super.signUp(username, password, phoneno, loginname, status); setACCOUNT_BALANCE(accountbalance); setStatus(status); setACCOUNT_ID(id); } public long getACCOUNT_ID() { return ACCOUNT_ID; } public void setACCOUNT_ID(long aCCOUNT_ID) { ACCOUNT_ID = aCCOUNT_ID; } public double getACCOUNT_BALANCE() { return ACCOUNT_BALANCE; } public void setACCOUNT_BALANCE(double aCCOUNT_BALANCE) { ACCOUNT_BALANCE = aCCOUNT_BALANCE; } public banktype getStatus() { return Status; } public void setStatus(banktype status) { Status = status; } public ArrayList<WalletTransaction> getTransactionHistory() { return TransactionHistory; } public void setTransactionHistory(ArrayList<WalletTransaction> transactionHistory) { TransactionHistory = transactionHistory; } }
UTF-8
Java
1,211
java
WalletAccount.java
Java
[]
null
[]
package walletapp; import java.util.ArrayList; public class WalletAccount extends UserInfo { private long ACCOUNT_ID; private double ACCOUNT_BALANCE; private banktype Status; private ArrayList<WalletTransaction> TransactionHistory; @Override public void signUp(String username, String password, String phoneno, String loginname, banktype status) throws ShowException { double accountbalance=1000; super.signUp(username, password, phoneno, loginname, status); setACCOUNT_BALANCE(accountbalance); setStatus(status); setACCOUNT_ID(id); } public long getACCOUNT_ID() { return ACCOUNT_ID; } public void setACCOUNT_ID(long aCCOUNT_ID) { ACCOUNT_ID = aCCOUNT_ID; } public double getACCOUNT_BALANCE() { return ACCOUNT_BALANCE; } public void setACCOUNT_BALANCE(double aCCOUNT_BALANCE) { ACCOUNT_BALANCE = aCCOUNT_BALANCE; } public banktype getStatus() { return Status; } public void setStatus(banktype status) { Status = status; } public ArrayList<WalletTransaction> getTransactionHistory() { return TransactionHistory; } public void setTransactionHistory(ArrayList<WalletTransaction> transactionHistory) { TransactionHistory = transactionHistory; } }
1,211
0.763832
0.760529
54
21.425926
22.67206
88
false
false
0
0
0
0
0
0
1.5
false
false
13
4a9c5bef768db734c1634b3bbe9006390173d166
30,133,490,607,566
9cb1ad91f76b7aa4e23e4b8536f1b01f6a2825c0
/src/main/java/com/proyecto/flowmanagement/ui/views/forms/ConditionParameterForm.java
c969cc0f62e924c7cc04c4202604dd92559403e6
[ "Unlicense" ]
permissive
Proyecto-Flow-Management/flow-management
https://github.com/Proyecto-Flow-Management/flow-management
3748f9f7d1d0705769cddac8bbf1ff01f4359a7e
b359534ca6a83fec6b2f502206de997d1f94867f
refs/heads/master
2023-03-11T19:44:45.550000
2021-02-26T20:37:29
2021-02-26T20:37:29
289,112,531
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.proyecto.flowmanagement.ui.views.forms; import com.proyecto.flowmanagement.backend.persistence.entity.ConditionParameter; import com.vaadin.flow.component.Component; import com.vaadin.flow.component.Key; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.button.ButtonVariant; import com.vaadin.flow.component.formlayout.FormLayout; import com.vaadin.flow.component.orderedlayout.HorizontalLayout; import com.vaadin.flow.component.textfield.EmailField; import com.vaadin.flow.component.textfield.TextField; public class ConditionParameterForm extends FormLayout { ConditionParameter conditionParameter; TextField fieldText = new TextField("First name"); TextField fieldTypeText = new TextField("Last name"); TextField operatorText = new TextField("Email"); TextField valueText = new TextField("Email"); Button save = new Button("Save"); Button close = new Button("Cancel"); public ConditionParameterForm() { configureElements(); } private void configureElements() { add(fieldText,fieldTypeText,operatorText,valueText,createButtonsLayout()); } private Component createButtonsLayout() { save.addThemeVariants(ButtonVariant.LUMO_PRIMARY); close.addThemeVariants(ButtonVariant.LUMO_TERTIARY); save.addClickShortcut(Key.ENTER); close.addClickShortcut(Key.ESCAPE); save.addClickListener(click -> validateAndSave()); return new HorizontalLayout(save, close); } private void validateAndSave() { if(isValid()) { this.conditionParameter = new ConditionParameter(); this.conditionParameter.setValue(valueText.getValue()); this.conditionParameter.setField(fieldText.getValue()); this.conditionParameter.setFieldType(fieldTypeText.getValue()); this.conditionParameter.setOperator(operatorText.getValue()); } } private boolean isValid() { boolean result = false; if( !fieldText.getValue().isEmpty() && !fieldTypeText.getValue().isEmpty() && !operatorText.getValue().isEmpty() && !valueText.getValue().isEmpty()) result = true; return result; } }
UTF-8
Java
2,276
java
ConditionParameterForm.java
Java
[]
null
[]
package com.proyecto.flowmanagement.ui.views.forms; import com.proyecto.flowmanagement.backend.persistence.entity.ConditionParameter; import com.vaadin.flow.component.Component; import com.vaadin.flow.component.Key; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.button.ButtonVariant; import com.vaadin.flow.component.formlayout.FormLayout; import com.vaadin.flow.component.orderedlayout.HorizontalLayout; import com.vaadin.flow.component.textfield.EmailField; import com.vaadin.flow.component.textfield.TextField; public class ConditionParameterForm extends FormLayout { ConditionParameter conditionParameter; TextField fieldText = new TextField("First name"); TextField fieldTypeText = new TextField("Last name"); TextField operatorText = new TextField("Email"); TextField valueText = new TextField("Email"); Button save = new Button("Save"); Button close = new Button("Cancel"); public ConditionParameterForm() { configureElements(); } private void configureElements() { add(fieldText,fieldTypeText,operatorText,valueText,createButtonsLayout()); } private Component createButtonsLayout() { save.addThemeVariants(ButtonVariant.LUMO_PRIMARY); close.addThemeVariants(ButtonVariant.LUMO_TERTIARY); save.addClickShortcut(Key.ENTER); close.addClickShortcut(Key.ESCAPE); save.addClickListener(click -> validateAndSave()); return new HorizontalLayout(save, close); } private void validateAndSave() { if(isValid()) { this.conditionParameter = new ConditionParameter(); this.conditionParameter.setValue(valueText.getValue()); this.conditionParameter.setField(fieldText.getValue()); this.conditionParameter.setFieldType(fieldTypeText.getValue()); this.conditionParameter.setOperator(operatorText.getValue()); } } private boolean isValid() { boolean result = false; if( !fieldText.getValue().isEmpty() && !fieldTypeText.getValue().isEmpty() && !operatorText.getValue().isEmpty() && !valueText.getValue().isEmpty()) result = true; return result; } }
2,276
0.702988
0.702988
64
34.5625
24.927942
82
false
false
0
0
0
0
0
0
0.59375
false
false
13
91c19dc86d2e97b25fea8dc2735a3fca934b4849
30,399,778,546,851
47746cdfe51b7654d869dac91b3b916750872b9a
/app/src/main/java/com/example/fy/mymusic/application/MusicApplication.java
754f8905688484cb4a50e01fcb377d3042837afb
[]
no_license
YingFan6310/MyMusicPlayer
https://github.com/YingFan6310/MyMusicPlayer
397156b4b68f8222c8386eda9c9f26fde7b76874
106ddf131a4d1f921be1ba35ff1dfbca9fedf9a9
refs/heads/master
2021-08-24T10:40:08.641000
2017-12-09T08:16:12
2017-12-09T08:16:12
113,653,668
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.fy.mymusic.application; import android.app.Application; import com.zhy.http.okhttp.OkHttpUtils; import java.util.concurrent.TimeUnit; import com.example.fy.mymusic.http.HttpInterceptor; import okhttp3.OkHttpClient; /** * 自定义Application */ public class MusicApplication extends Application { @Override public void onCreate() { super.onCreate(); AppCache.init(this); initOkHttpUtils(); } private void initOkHttpUtils() { OkHttpClient okHttpClient = new OkHttpClient.Builder() .connectTimeout(10, TimeUnit.SECONDS) .readTimeout(10, TimeUnit.SECONDS) .writeTimeout(10, TimeUnit.SECONDS) .addInterceptor(new HttpInterceptor()) .build(); OkHttpUtils.initClient(okHttpClient); } }
UTF-8
Java
855
java
MusicApplication.java
Java
[]
null
[]
package com.example.fy.mymusic.application; import android.app.Application; import com.zhy.http.okhttp.OkHttpUtils; import java.util.concurrent.TimeUnit; import com.example.fy.mymusic.http.HttpInterceptor; import okhttp3.OkHttpClient; /** * 自定义Application */ public class MusicApplication extends Application { @Override public void onCreate() { super.onCreate(); AppCache.init(this); initOkHttpUtils(); } private void initOkHttpUtils() { OkHttpClient okHttpClient = new OkHttpClient.Builder() .connectTimeout(10, TimeUnit.SECONDS) .readTimeout(10, TimeUnit.SECONDS) .writeTimeout(10, TimeUnit.SECONDS) .addInterceptor(new HttpInterceptor()) .build(); OkHttpUtils.initClient(okHttpClient); } }
855
0.656066
0.647821
39
20.76923
20.80121
62
false
false
0
0
0
0
0
0
0.358974
false
false
13
8b9fca7b6b1a822a9ec07c9ceb2bd1b02e2aebaa
5,901,285,119,365
7e4962f10f211ea31620afda76d888487974cda4
/demo/src/main/java/jp/co/project/demo/annotation/Sample2Transactional.java
3392ac34a8dde8a92c20f6afac84055171cfe582
[]
no_license
ma-tamu/sample-tx
https://github.com/ma-tamu/sample-tx
5cb457c8602a6fceac06426a156d3252aadab25a
465d42358474bfc0849efa5099ce4c237424bc63
refs/heads/master
2020-09-03T12:50:35.842000
2019-11-04T09:46:28
2019-11-04T09:46:28
219,466,411
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package jp.co.project.demo.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.transaction.annotation.Transactional; @Documented @Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Transactional(transactionManager = "transactionManager", rollbackFor = Exception.class) public @interface Sample2Transactional { }
UTF-8
Java
539
java
Sample2Transactional.java
Java
[]
null
[]
package jp.co.project.demo.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.transaction.annotation.Transactional; @Documented @Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Transactional(transactionManager = "transactionManager", rollbackFor = Exception.class) public @interface Sample2Transactional { }
539
0.833024
0.831169
17
30.705883
24.649937
88
false
false
0
0
0
0
0
0
0.529412
false
false
13
c1e954a326ea8d55b4831131660063939d953df7
5,901,285,120,420
667db10a44a8492b55dd27482fdc40581eda2873
/gleidson/projetos/treinar/src/br/com/treinar/estudo/objeto/Principal.java
42635637a856372be110d127dcf1130e0782f009
[]
no_license
ggmoura/turma-8832
https://github.com/ggmoura/turma-8832
ceb75f2e1b14dfc3d8955fb5f874358b6017ce5f
b75d84d52b53efc93d72c19c48b420ffca13f653
refs/heads/master
2021-01-11T00:21:36.303000
2016-11-10T00:37:44
2016-11-10T00:37:44
70,540,359
0
14
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.treinar.estudo.objeto; public class Principal { public static void main(String[] args) { Cidade cidade = new Cidade(); cidade.nome = "Belo Horizonte"; cidade.populacao = 50000; Estado estado = new Estado(); estado.nome = "Minas Gerais"; estado.sigla = "MG"; estado.qtdMoradores = 46546546; cidade.estado = new Estado(); cidade.estado.nome = "São Paulo"; cidade.estado.sigla = "SP"; cidade.estado.qtdMoradores = 6546546; //estado = null; System.out.println(cidade.estado.nome); } }
UTF-8
Java
578
java
Principal.java
Java
[ { "context": "\t\tCidade cidade = new Cidade();\r\n\t\tcidade.nome = \"Belo Horizonte\";\r\n\t\tcidade.populacao = 50000;\r\n\t\t\r\n\t\tEstado esta", "end": 180, "score": 0.9994903802871704, "start": 166, "tag": "NAME", "value": "Belo Horizonte" }, { "context": "\t\tEstado estado = ...
null
[]
package br.com.treinar.estudo.objeto; public class Principal { public static void main(String[] args) { Cidade cidade = new Cidade(); cidade.nome = "<NAME>"; cidade.populacao = 50000; Estado estado = new Estado(); estado.nome = "Minas Gerais"; estado.sigla = "MG"; estado.qtdMoradores = 46546546; cidade.estado = new Estado(); cidade.estado.nome = "São Paulo"; cidade.estado.sigla = "SP"; cidade.estado.qtdMoradores = 6546546; //estado = null; System.out.println(cidade.estado.nome); } }
570
0.629116
0.594454
28
18.607143
15.575482
41
false
false
0
0
0
0
0
0
2.035714
false
false
13
6d9cdf222c608342dd8308bc39c0b84508ef8bfa
19,370,302,538,958
0830e40d10b02e665646cb4eeda19370595d16f8
/src/test/java/nz/ac/auckland/morc/tests/mock/ContentMockDefinitionBuilderTest.java
28cb5e408689c8894d4bf35d99dc3cdf6addaeb3
[ "MIT" ]
permissive
uoa-group-applications/morc
https://github.com/uoa-group-applications/morc
3d202633f0507a4172807ed2d433e0c3edd4afee
3add6308b1fbfc98187364ac73007c83012ea8ba
refs/heads/master
2020-12-24T14:36:21.247000
2015-07-27T09:38:22
2015-07-27T09:38:22
12,032,304
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package nz.ac.auckland.morc.tests.mock; import nz.ac.auckland.morc.MorcMethods; import nz.ac.auckland.morc.mock.MockDefinition; import nz.ac.auckland.morc.mock.builder.ContentMockDefinitionBuilder; import org.apache.camel.Exchange; import org.apache.camel.impl.DefaultCamelContext; import org.apache.camel.impl.DefaultExchange; import org.junit.Assert; import org.junit.Test; public class ContentMockDefinitionBuilderTest extends Assert implements MorcMethods { @Test public void testBodiesAndHeadersMatchedCorrect() throws Exception { MockDefinition def = new ContentMockDefinitionBuilder("").expectation(text("foo"), headers(header("foo", "1"))) .expectation(text("baz"), headers(header("foo", "2"))) .expectation(text("moo"), headers(header("foo", "3"))) .addRepeatedPredicate(headers(header("aaa", "bbb"))).build(null); assertEquals(3, def.getPredicates().size()); Exchange e = new DefaultExchange(new DefaultCamelContext()); e.getIn().setHeader("aaa", "bbb"); e.getIn().setBody("foo"); e.getIn().setHeader("foo", "1"); assertTrue(def.getPredicates().get(0).matches(e)); e.getIn().setBody("baz"); assertFalse(def.getPredicates().get(0).matches(e)); e.getIn().setBody("baz"); e.getIn().setHeader("foo", "2"); assertTrue(def.getPredicates().get(1).matches(e)); e.getIn().setBody("moo"); e.getIn().setHeader("foo", "3"); assertTrue(def.getPredicates().get(2).matches(e)); } @Test public void testMoreBodiesThanHeaders() throws Exception { MockDefinition def = new ContentMockDefinitionBuilder("").expectation(text("foo"), headers(header("foo", "1"))) .expectation(text("baz")) .expectation(text("moo")) .addRepeatedPredicate(headers(header("aaa", "bbb"))).build(null); assertEquals(3, def.getPredicates().size()); Exchange e = new DefaultExchange(new DefaultCamelContext()); e.getIn().setHeader("foo", "1"); e.getIn().setHeader("aaa", "bbb"); e.getIn().setBody("foo"); assertTrue(def.getPredicates().get(0).matches(e)); e.getIn().setBody("baz"); assertFalse(def.getPredicates().get(0).matches(e)); e.getIn().setBody("baz"); assertTrue(def.getPredicates().get(1).matches(e)); e.getIn().setBody("moo"); assertTrue(def.getPredicates().get(2).matches(e)); } @Test public void testMoreHeadersThanBodies() throws Exception { MockDefinition def = new ContentMockDefinitionBuilder("") .expectation(text("foo"), headers(header("foo", "1"))) .expectation(headers(header("foo", "2"))) .expectation(headers(header("foo", "3"))) .addRepeatedPredicate(headers(header("aaa", "bbb"))).build(null); assertEquals(3, def.getPredicates().size()); Exchange e = new DefaultExchange(new DefaultCamelContext()); e.getIn().setHeader("aaa", "bbb"); e.getIn().setBody("foo"); e.getIn().setHeader("foo", "1"); assertTrue(def.getPredicates().get(0).matches(e)); e.getIn().setBody("baz"); assertFalse(def.getPredicates().get(0).matches(e)); e.getIn().setBody("foo"); e.getIn().setHeader("foo", "2"); assertTrue(def.getPredicates().get(1).matches(e)); e.getIn().setBody("foo"); e.getIn().setHeader("foo", "3"); assertTrue(def.getPredicates().get(2).matches(e)); } @Test public void testBodiesAndHeadersLargeExpectedMessageCount() throws Exception { MockDefinition def = new ContentMockDefinitionBuilder("").expectation(text("foo"), headers(header("foo", "1"))) .expectedMessageCount(3) .addRepeatedPredicate(headers(header("aaa", "bbb"))).build(null); assertEquals(3, def.getPredicates().size()); Exchange e = new DefaultExchange(new DefaultCamelContext()); e.getIn().setHeader("aaa", "bbb"); e.getIn().setBody("foo"); e.getIn().setHeader("foo", "1"); assertTrue(def.getPredicates().get(0).matches(e)); //should accept anything in bodies/headers e.getIn().setBody("notfoo"); e.getIn().setHeader("foo", "2"); assertTrue(def.getPredicates().get(1).matches(e)); assertTrue(def.getPredicates().get(2).matches(e)); } }
UTF-8
Java
4,489
java
ContentMockDefinitionBuilderTest.java
Java
[]
null
[]
package nz.ac.auckland.morc.tests.mock; import nz.ac.auckland.morc.MorcMethods; import nz.ac.auckland.morc.mock.MockDefinition; import nz.ac.auckland.morc.mock.builder.ContentMockDefinitionBuilder; import org.apache.camel.Exchange; import org.apache.camel.impl.DefaultCamelContext; import org.apache.camel.impl.DefaultExchange; import org.junit.Assert; import org.junit.Test; public class ContentMockDefinitionBuilderTest extends Assert implements MorcMethods { @Test public void testBodiesAndHeadersMatchedCorrect() throws Exception { MockDefinition def = new ContentMockDefinitionBuilder("").expectation(text("foo"), headers(header("foo", "1"))) .expectation(text("baz"), headers(header("foo", "2"))) .expectation(text("moo"), headers(header("foo", "3"))) .addRepeatedPredicate(headers(header("aaa", "bbb"))).build(null); assertEquals(3, def.getPredicates().size()); Exchange e = new DefaultExchange(new DefaultCamelContext()); e.getIn().setHeader("aaa", "bbb"); e.getIn().setBody("foo"); e.getIn().setHeader("foo", "1"); assertTrue(def.getPredicates().get(0).matches(e)); e.getIn().setBody("baz"); assertFalse(def.getPredicates().get(0).matches(e)); e.getIn().setBody("baz"); e.getIn().setHeader("foo", "2"); assertTrue(def.getPredicates().get(1).matches(e)); e.getIn().setBody("moo"); e.getIn().setHeader("foo", "3"); assertTrue(def.getPredicates().get(2).matches(e)); } @Test public void testMoreBodiesThanHeaders() throws Exception { MockDefinition def = new ContentMockDefinitionBuilder("").expectation(text("foo"), headers(header("foo", "1"))) .expectation(text("baz")) .expectation(text("moo")) .addRepeatedPredicate(headers(header("aaa", "bbb"))).build(null); assertEquals(3, def.getPredicates().size()); Exchange e = new DefaultExchange(new DefaultCamelContext()); e.getIn().setHeader("foo", "1"); e.getIn().setHeader("aaa", "bbb"); e.getIn().setBody("foo"); assertTrue(def.getPredicates().get(0).matches(e)); e.getIn().setBody("baz"); assertFalse(def.getPredicates().get(0).matches(e)); e.getIn().setBody("baz"); assertTrue(def.getPredicates().get(1).matches(e)); e.getIn().setBody("moo"); assertTrue(def.getPredicates().get(2).matches(e)); } @Test public void testMoreHeadersThanBodies() throws Exception { MockDefinition def = new ContentMockDefinitionBuilder("") .expectation(text("foo"), headers(header("foo", "1"))) .expectation(headers(header("foo", "2"))) .expectation(headers(header("foo", "3"))) .addRepeatedPredicate(headers(header("aaa", "bbb"))).build(null); assertEquals(3, def.getPredicates().size()); Exchange e = new DefaultExchange(new DefaultCamelContext()); e.getIn().setHeader("aaa", "bbb"); e.getIn().setBody("foo"); e.getIn().setHeader("foo", "1"); assertTrue(def.getPredicates().get(0).matches(e)); e.getIn().setBody("baz"); assertFalse(def.getPredicates().get(0).matches(e)); e.getIn().setBody("foo"); e.getIn().setHeader("foo", "2"); assertTrue(def.getPredicates().get(1).matches(e)); e.getIn().setBody("foo"); e.getIn().setHeader("foo", "3"); assertTrue(def.getPredicates().get(2).matches(e)); } @Test public void testBodiesAndHeadersLargeExpectedMessageCount() throws Exception { MockDefinition def = new ContentMockDefinitionBuilder("").expectation(text("foo"), headers(header("foo", "1"))) .expectedMessageCount(3) .addRepeatedPredicate(headers(header("aaa", "bbb"))).build(null); assertEquals(3, def.getPredicates().size()); Exchange e = new DefaultExchange(new DefaultCamelContext()); e.getIn().setHeader("aaa", "bbb"); e.getIn().setBody("foo"); e.getIn().setHeader("foo", "1"); assertTrue(def.getPredicates().get(0).matches(e)); //should accept anything in bodies/headers e.getIn().setBody("notfoo"); e.getIn().setHeader("foo", "2"); assertTrue(def.getPredicates().get(1).matches(e)); assertTrue(def.getPredicates().get(2).matches(e)); } }
4,489
0.615059
0.606817
115
38.034782
28.888069
119
false
false
0
0
0
0
0
0
0.852174
false
false
13
9588ca040dcf13d2cb8dfb70d0aae9e3547fb753
27,436,251,138,368
eee3aeaeb7f9a9bfca0a3cc7f72ec6597bb0a90a
/LunchLocater/app/src/main/java/tbdtech/lunchlocater/venue/Location.java
bf79501bbea089d8211669311292c0c372dfacb4
[]
no_license
rorymcgrath/Lunch-Locator
https://github.com/rorymcgrath/Lunch-Locator
be696b1ee00333f344f2f6e124956a0342e264cd
e0e9eb1e2cb9dbc6a0d2ac58c40af7a1e93c793e
refs/heads/master
2021-01-01T04:43:09.179000
2017-07-21T12:17:45
2017-07-21T12:17:45
97,232,922
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package tbdtech.lunchlocater.venue; import org.json.JSONObject; /** * Created by tliimfee on 7/26/2016. */ public class Location { private double lat; private double lng; public Location(double lat, double lng) { this.lat = lat; this.lng = lng; } public Location(JSONObject geometry) { } public double getLat() { return lat; } public double getLng() { return lng; } public void setLat(double lat) { this.lat = lat; } public void setLng(double lng) { this.lng = lng; } }
UTF-8
Java
652
java
Location.java
Java
[ { "context": "\nimport org.json.JSONObject;\r\n\r\n/**\r\n * Created by tliimfee on 7/26/2016.\r\n */\r\npublic class Location\r\n{\r\n\r\n ", "end": 97, "score": 0.9996636509895325, "start": 89, "tag": "USERNAME", "value": "tliimfee" } ]
null
[]
package tbdtech.lunchlocater.venue; import org.json.JSONObject; /** * Created by tliimfee on 7/26/2016. */ public class Location { private double lat; private double lng; public Location(double lat, double lng) { this.lat = lat; this.lng = lng; } public Location(JSONObject geometry) { } public double getLat() { return lat; } public double getLng() { return lng; } public void setLat(double lat) { this.lat = lat; } public void setLng(double lng) { this.lng = lng; } }
652
0.519939
0.509202
43
13.16279
13.268129
43
false
false
0
0
0
0
0
0
0.255814
false
false
13
ea2e2d23d65748ea69f8f4b0f1d6f7838f6e7c47
18,820,546,691,285
7a5646ca3e3d90ed8963ae2515728c4d91d72691
/src/main/java/br/com/effect/teste/service/TurmaService.java
a86cd7d2615517a60d03762990552b1f38e27f3d
[]
no_license
adrianoftz/projeto-escola-senai
https://github.com/adrianoftz/projeto-escola-senai
d95e529aeb360a3a27c3218894f4ae7522eccfd7
d18781090d3da3f5eeb22427d0b27dec4605d8b0
refs/heads/master
2020-03-26T17:35:53.392000
2018-08-28T00:47:46
2018-08-28T00:47:49
145,170,219
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.effect.teste.service; import br.com.effect.teste.domain.Turma; import br.com.effect.teste.repository.TurmaRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * Service Implementation for managing Turma. */ @Service public class TurmaService { private final Logger log = LoggerFactory.getLogger(TurmaService.class); private final TurmaRepository turmaRepository; public TurmaService(TurmaRepository turmaRepository) { this.turmaRepository = turmaRepository; } /** * Save a turma. * * @param turma the entity to save * @return the persisted entity */ public Turma save(Turma turma) { log.debug("Request to save Turma : {}", turma); return turmaRepository.save(turma); } /** * Get all the turmas. * * @return the list of entities */ @Transactional(readOnly = true) public List<Turma> findAll() { log.debug("Request to get all Turmas"); return turmaRepository.findAll(); } /** * Get one turma by id. * * @param id the id of the entity * @return the entity */ @Transactional(readOnly = true) public Turma findOne(Long id) { log.debug("Request to get Turma : {}", id); return turmaRepository.findOne(id); } /** * Delete the turma by id. * * @param id the id of the entity */ public void delete(Long id) { log.debug("Request to delete Turma : {}", id); turmaRepository.delete(id); } }
UTF-8
Java
1,704
java
TurmaService.java
Java
[]
null
[]
package br.com.effect.teste.service; import br.com.effect.teste.domain.Turma; import br.com.effect.teste.repository.TurmaRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * Service Implementation for managing Turma. */ @Service public class TurmaService { private final Logger log = LoggerFactory.getLogger(TurmaService.class); private final TurmaRepository turmaRepository; public TurmaService(TurmaRepository turmaRepository) { this.turmaRepository = turmaRepository; } /** * Save a turma. * * @param turma the entity to save * @return the persisted entity */ public Turma save(Turma turma) { log.debug("Request to save Turma : {}", turma); return turmaRepository.save(turma); } /** * Get all the turmas. * * @return the list of entities */ @Transactional(readOnly = true) public List<Turma> findAll() { log.debug("Request to get all Turmas"); return turmaRepository.findAll(); } /** * Get one turma by id. * * @param id the id of the entity * @return the entity */ @Transactional(readOnly = true) public Turma findOne(Long id) { log.debug("Request to get Turma : {}", id); return turmaRepository.findOne(id); } /** * Delete the turma by id. * * @param id the id of the entity */ public void delete(Long id) { log.debug("Request to delete Turma : {}", id); turmaRepository.delete(id); } }
1,704
0.637911
0.636737
70
23.342857
20.048431
75
false
false
0
0
0
0
0
0
0.314286
false
false
13
7b29027b8ea2e772f47a1101d25ebe0919a40b4a
18,683,107,749,812
58ffa3c8895442b3a565e8c29d06ec647eaf2c32
/src/main/java/com/ovani4/crudprogram/controller/RegionController.java
9302ea7d826daca586bc5287cd926b014a39ce40
[]
no_license
Ovani4/FirstCrudProgram
https://github.com/Ovani4/FirstCrudProgram
8e5c34e59db9cde8637d7d3dec5817d969dbc77f
14c9ff125994759c11834c3f1e7830097111353e
refs/heads/master
2023-03-30T19:40:18.237000
2021-04-01T11:58:00
2021-04-01T11:58:00
342,402,598
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package main.java.com.ovani4.crudprogram.controller; import main.java.com.ovani4.crudprogram.model.Region; import main.java.com.ovani4.crudprogram.repository.RegionRepository; import main.java.com.ovani4.crudprogram.repository.imp.JavaIORegionRepositoryImpl; import java.util.List; public class RegionController { RegionRepository rr = new JavaIORegionRepositoryImpl(); public List<Region> getAll() { return rr.getAll(); } public Region getById(Integer integer) { return rr.getById(integer); } public Region save(Region region) { return rr.save(region); } public Region update(Region region) { return rr.update(region); } public void deleteById(Integer integer) { rr.deleteById(integer); } }
UTF-8
Java
789
java
RegionController.java
Java
[]
null
[]
package main.java.com.ovani4.crudprogram.controller; import main.java.com.ovani4.crudprogram.model.Region; import main.java.com.ovani4.crudprogram.repository.RegionRepository; import main.java.com.ovani4.crudprogram.repository.imp.JavaIORegionRepositoryImpl; import java.util.List; public class RegionController { RegionRepository rr = new JavaIORegionRepositoryImpl(); public List<Region> getAll() { return rr.getAll(); } public Region getById(Integer integer) { return rr.getById(integer); } public Region save(Region region) { return rr.save(region); } public Region update(Region region) { return rr.update(region); } public void deleteById(Integer integer) { rr.deleteById(integer); } }
789
0.703422
0.698352
36
20.916666
23.241934
82
false
false
0
0
0
0
0
0
0.305556
false
false
13
4d40d3806694d62d33316ff69da8211710841788
29,721,173,700,678
b12185142e5c348c5d44550c8c962738f3256b1e
/app/biz/service-impl/src/main/java/com/onway/car/biz/service/query/CarInfoService.java
f3f899283fcd6497f09a412db473c1b375192421
[]
no_license
StevensGitHub/car
https://github.com/StevensGitHub/car
b274e93454b76b8679e47012a9e225584663ed63
218c1782acea76cbac93ac75e7e13910447161e2
refs/heads/master
2019-01-28T11:47:13.231000
2018-10-18T09:07:15
2018-10-18T09:07:15
98,367,319
0
0
null
false
2017-07-26T02:11:13
2017-07-26T01:56:18
2017-07-26T01:56:18
2017-07-26T02:11:13
0
0
0
0
null
null
null
package com.onway.car.biz.service.query; import com.github.pagehelper.PageInfo; import com.onway.car.common.dal.dataobject.InfoDO; import com.onway.car.common.dal.mybatis.model.CarAutobytel; import com.onway.car.core.car.CarInfo; import java.util.List; import java.util.Map; /** * Created by rog on 2017/4/19. */ public interface CarInfoService { public List<InfoDO> queryCarInfoList(CarInfo info); public int queryCarInfoListCount(CarInfo info); public int updateCarState(String state,String carLicenseNo); public InfoDO selectCarInfoById(int id); public InfoDO queryCarByLisenceNo(String lisenceNo); //增加车辆详情表 int saveCarInfo(com.onway.car.common.dal.mybatis.model.CarInfo carInfo); //资管中心查询已上传资料或未上传资料车辆详情 PageInfo listCarInfo(Map parm, Integer page, Integer rows); PageInfo listCard(Map parm, Integer page, Integer rows); void updateAuottyprl(String remark, String lisenceNo,Integer id); PageInfo listTask(Map parm, Integer page, Integer rows); int changeCarStatus(com.onway.car.common.dal.mybatis.model.CarInfo carInfo); PageInfo queryCarInfoAll(Integer page, Integer rows, Map carBrand); int updateCarInfo(com.onway.car.common.dal.mybatis.model.CarInfo carInfo); }
UTF-8
Java
1,306
java
CarInfoService.java
Java
[ { "context": "til.List;\nimport java.util.Map;\n\n/**\n * Created by rog on 2017/4/19.\n */\npublic interface CarInfoService", "end": 299, "score": 0.9995030164718628, "start": 296, "tag": "USERNAME", "value": "rog" } ]
null
[]
package com.onway.car.biz.service.query; import com.github.pagehelper.PageInfo; import com.onway.car.common.dal.dataobject.InfoDO; import com.onway.car.common.dal.mybatis.model.CarAutobytel; import com.onway.car.core.car.CarInfo; import java.util.List; import java.util.Map; /** * Created by rog on 2017/4/19. */ public interface CarInfoService { public List<InfoDO> queryCarInfoList(CarInfo info); public int queryCarInfoListCount(CarInfo info); public int updateCarState(String state,String carLicenseNo); public InfoDO selectCarInfoById(int id); public InfoDO queryCarByLisenceNo(String lisenceNo); //增加车辆详情表 int saveCarInfo(com.onway.car.common.dal.mybatis.model.CarInfo carInfo); //资管中心查询已上传资料或未上传资料车辆详情 PageInfo listCarInfo(Map parm, Integer page, Integer rows); PageInfo listCard(Map parm, Integer page, Integer rows); void updateAuottyprl(String remark, String lisenceNo,Integer id); PageInfo listTask(Map parm, Integer page, Integer rows); int changeCarStatus(com.onway.car.common.dal.mybatis.model.CarInfo carInfo); PageInfo queryCarInfoAll(Integer page, Integer rows, Map carBrand); int updateCarInfo(com.onway.car.common.dal.mybatis.model.CarInfo carInfo); }
1,306
0.7624
0.7568
44
27.40909
28.336708
80
false
false
0
0
0
0
0
0
0.704545
false
false
13
e22171454e645d9acb35f832c810d8af041b1b15
5,368,709,133,376
7744b38ac4c00bed926137a30014fd92d7fc9214
/lib/src/main/java/com/summer/lib/view/chart/linearchat/bean/viewbean/YV.java
767e980e858de19e1daace7db3a7d85dd71f0852
[]
no_license
canvaser/App
https://github.com/canvaser/App
173b53638231d165e98316262d654ad246cb5af6
c8956766c16677bda1ae42691d958de155a2d0e3
refs/heads/master
2021-01-22T08:47:42.713000
2017-04-19T03:59:44
2017-04-19T03:59:44
81,914,207
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.summer.lib.view.chart.linearchat.bean.viewbean; import com.summer.lib.constant.ValueConstant; /** * Created by ${viwmox} on 2016-11-28. */ public class YV extends ChartItemBean { private int ply = ValueConstant.DIMEN_1 * 3; private int radous = ValueConstant.DIMEN_1 * 5; public int getPly() { return ply; } public void setPly(int ply) { this.ply = ply; } public int getRadous() { return radous; } public void setRadous(int radous) { this.radous = radous; } }
UTF-8
Java
555
java
YV.java
Java
[ { "context": ".lib.constant.ValueConstant;\n\n/**\n * Created by ${viwmox} on 2016-11-28.\n */\npublic class YV extends Chart", "end": 135, "score": 0.9960528612136841, "start": 129, "tag": "USERNAME", "value": "viwmox" } ]
null
[]
package com.summer.lib.view.chart.linearchat.bean.viewbean; import com.summer.lib.constant.ValueConstant; /** * Created by ${viwmox} on 2016-11-28. */ public class YV extends ChartItemBean { private int ply = ValueConstant.DIMEN_1 * 3; private int radous = ValueConstant.DIMEN_1 * 5; public int getPly() { return ply; } public void setPly(int ply) { this.ply = ply; } public int getRadous() { return radous; } public void setRadous(int radous) { this.radous = radous; } }
555
0.623423
0.601802
30
17.5
18.745222
59
false
false
0
0
0
0
0
0
0.266667
false
false
13
1039d6520d6ca6e9dca0d8e2ed766f9f5364f9a7
20,942,260,544,443
b9e3f1435aeaf6a4e5ea825d7ffe71d919338972
/Homework_5/src/Brabus.java
c9985975693fb3e9c091d0b75903536c048e2d13
[]
no_license
popiosifcristian/scoala-informala-homeworks
https://github.com/popiosifcristian/scoala-informala-homeworks
ae38ad1c93d1e778ebbe036eb9a2b04d052df444
d815c6544329a061dd1a63917e265052ad4a60cc
refs/heads/master
2021-01-21T06:30:04.834000
2017-05-03T09:35:43
2017-05-03T09:35:43
81,614,691
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/**This is the Brabus class, child of Mercedess * The Brabus has a higher consumption when the tire size are larger than 16 * @author Pop Iosif Cristian */ public class Brabus extends Mercedes { public Brabus(float availableFuel, String chassisNumber,float fuelTankSize,String fuelType,int tireSize,boolean superSport) { super(availableFuel, chassisNumber,fuelTankSize,fuelType,tireSize,superSport); } @Override public void drive(float distance) { setGearsConsumption(10,11,13,15,17,20); if(getTireSize()>16)//if size of tires is larger than 16 the consumption will be higher setActualConsumption(getActualConsumption()*getTireSize()/10);//a proportional calculation of consume depending on tire size setAvailableFuel(getAvailableFuel()-(getActualConsumption()*distance/100)); setConsumptionCount(getConsumptionCount()+1); setConsumptionPer100Km(getConsumptionPer100Km()+getActualConsumption()); } }
UTF-8
Java
1,003
java
Brabus.java
Java
[ { "context": " when the tire size are larger than 16\r\n * @author Pop Iosif Cristian\r\n */\r\npublic class Brabus extends Mercedes {\r\n ", "end": 156, "score": 0.9998102188110352, "start": 138, "tag": "NAME", "value": "Pop Iosif Cristian" } ]
null
[]
/**This is the Brabus class, child of Mercedess * The Brabus has a higher consumption when the tire size are larger than 16 * @author <NAME> */ public class Brabus extends Mercedes { public Brabus(float availableFuel, String chassisNumber,float fuelTankSize,String fuelType,int tireSize,boolean superSport) { super(availableFuel, chassisNumber,fuelTankSize,fuelType,tireSize,superSport); } @Override public void drive(float distance) { setGearsConsumption(10,11,13,15,17,20); if(getTireSize()>16)//if size of tires is larger than 16 the consumption will be higher setActualConsumption(getActualConsumption()*getTireSize()/10);//a proportional calculation of consume depending on tire size setAvailableFuel(getAvailableFuel()-(getActualConsumption()*distance/100)); setConsumptionCount(getConsumptionCount()+1); setConsumptionPer100Km(getConsumptionPer100Km()+getActualConsumption()); } }
991
0.730808
0.700897
19
50.789474
41.595268
136
false
false
0
0
0
0
0
0
1.157895
false
false
13
182219f45accd66e9287fbdcc23a0a0fe7202708
4,587,025,087,050
c051d315eab6c3798b9e6c13676478199a024b27
/src/main/java/com/suhailkandanur/eopi/ch15/BSTP15_1.java
5081cade895c669d76fd3efacfbd1d14f1063cbf
[]
no_license
ksuhail7/ElementsOfProgrammingInterviews
https://github.com/ksuhail7/ElementsOfProgrammingInterviews
5754df4c2e985481c648bcca78658f4d7f04b609
ffe78b6de5319bc0147ecdac13938462945f4591
refs/heads/master
2022-05-26T00:32:20.709000
2022-05-04T05:39:50
2022-05-04T05:39:50
72,382,741
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.suhailkandanur.eopi.ch15; import com.suhailkandanur.eopi.util.TreeNode; /** * Created by suhail on 2016-11-03. */ public class BSTP15_1 { public static boolean isBST(TreeNode root) { if(root == null) return true; TreeNode leftNode = root.getLeft(); TreeNode rightNode = root.getRight(); if(leftNode != null) { if(root.getData() < leftNode.getData()) return false; } if(rightNode != null) { if(root.getData() > rightNode.getData()) return false; } return isBST(leftNode) && isBST(rightNode); } public static TreeNode createBST(int[] array) { TreeNode root = null; for (int i = 0; i < array.length; i++) { int data = array[i]; root = createBST(root, data); } return root; } private static TreeNode createBST(TreeNode root, int value) { if (root == null) { root = new TreeNode(value); } else if(root.getData() > value) { root.setLeft(createBST(root.getLeft(), value)); } else if(root.getData() <= value) { root.setRight(createBST(root.getRight(), value)); } return root; } public static void DFS(TreeNode root) { if(root == null) return; DFS(root.getLeft()); DFS(root.getRight()); System.out.println(root.getData()); } public static void BFS(TreeNode root) { if (root == null) { return; } BFS(root.getLeft()); System.out.println(root.getData()); BFS(root.getRight()); } }
UTF-8
Java
1,694
java
BSTP15_1.java
Java
[ { "context": "ailkandanur.eopi.util.TreeNode;\n\n/**\n * Created by suhail on 2016-11-03.\n */\npublic class BSTP15_1 {\n\n p", "end": 110, "score": 0.9949197769165039, "start": 104, "tag": "USERNAME", "value": "suhail" } ]
null
[]
package com.suhailkandanur.eopi.ch15; import com.suhailkandanur.eopi.util.TreeNode; /** * Created by suhail on 2016-11-03. */ public class BSTP15_1 { public static boolean isBST(TreeNode root) { if(root == null) return true; TreeNode leftNode = root.getLeft(); TreeNode rightNode = root.getRight(); if(leftNode != null) { if(root.getData() < leftNode.getData()) return false; } if(rightNode != null) { if(root.getData() > rightNode.getData()) return false; } return isBST(leftNode) && isBST(rightNode); } public static TreeNode createBST(int[] array) { TreeNode root = null; for (int i = 0; i < array.length; i++) { int data = array[i]; root = createBST(root, data); } return root; } private static TreeNode createBST(TreeNode root, int value) { if (root == null) { root = new TreeNode(value); } else if(root.getData() > value) { root.setLeft(createBST(root.getLeft(), value)); } else if(root.getData() <= value) { root.setRight(createBST(root.getRight(), value)); } return root; } public static void DFS(TreeNode root) { if(root == null) return; DFS(root.getLeft()); DFS(root.getRight()); System.out.println(root.getData()); } public static void BFS(TreeNode root) { if (root == null) { return; } BFS(root.getLeft()); System.out.println(root.getData()); BFS(root.getRight()); } }
1,694
0.530697
0.522432
66
24.666666
18.951559
65
false
false
0
0
0
0
0
0
0.454545
false
false
13
0397692b2c53d3609ea525fa4e4c9783c8b44717
4,587,025,086,685
9faee5b031a6fbf3a88b19806ab1e3457645b623
/src/main/java/com/example/demo/mapper/SimpleMapper.java
a36be51f22f2a1d921707b7a04fbc2ec4f7ad1aa
[]
no_license
John-0xFFFFFF/springboot-test
https://github.com/John-0xFFFFFF/springboot-test
0f656658874f2f8edabe18492674516accaf6f81
0df9bdf815be94eeb2a8c6c353712395ad6e2a1f
refs/heads/master
2020-06-09T21:31:04.057000
2019-06-24T13:27:11
2019-06-24T13:27:11
193,509,579
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.demo.mapper; //一些简单的数据库查询 /** import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.SelectKey; import org.apache.ibatis.annotations.Update; @Mapper public interface SimpleMapper { //从用户密码表中抽取某昵称的密码的md5 @Select("select password from users where nickname=#{nickname}") public String getPwdViaNickname(String nickname); //新增用户名、密码到表中 @Insert("insert into users(uid,nickname,password) " + "values (#{uid},#{nickname},#{password})") @SelectKey(keyProperty="uid" ,resultType=String.class ,before=true, statement="select replace(uuid(),'-','')") public int addNewUser(String nickname,String password); } 全部改写xml **/
UTF-8
Java
845
java
SimpleMapper.java
Java
[]
null
[]
package com.example.demo.mapper; //一些简单的数据库查询 /** import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.SelectKey; import org.apache.ibatis.annotations.Update; @Mapper public interface SimpleMapper { //从用户密码表中抽取某昵称的密码的md5 @Select("select password from users where nickname=#{nickname}") public String getPwdViaNickname(String nickname); //新增用户名、密码到表中 @Insert("insert into users(uid,nickname,password) " + "values (#{uid},#{nickname},#{password})") @SelectKey(keyProperty="uid" ,resultType=String.class ,before=true, statement="select replace(uuid(),'-','')") public int addNewUser(String nickname,String password); } 全部改写xml **/
845
0.7654
0.764089
26
28.346153
22.562635
68
false
false
0
0
0
0
0
0
1.153846
false
false
13
17cdb34022bed4766c137a76828a8bb5a22e2937
8,942,121,925,521
a7420a6f203a38730dfbea2c659bfadfa79c63cb
/CharAndBoolean/src/com/timbuchalka/Main.java
af3bc57defaff1f4c511256bb2ae4ecc0d256684
[]
no_license
venkat4541/JavaPrograms
https://github.com/venkat4541/JavaPrograms
99f3423f0d8f2529d08efcc9536aef6c3f4b6fde
5ef46514523a811704d20e7a9565f6207f8a98d1
refs/heads/master
2021-01-20T04:32:57.576000
2017-03-04T22:51:04
2017-03-04T22:51:04
83,842,742
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.timbuchalka; public class Main { public static void main(String[] args) { char sample = '\u00A9'; System.out.println(sample); boolean bool = false; System.out.println(bool); } }
UTF-8
Java
221
java
Main.java
Java
[]
null
[]
package com.timbuchalka; public class Main { public static void main(String[] args) { char sample = '\u00A9'; System.out.println(sample); boolean bool = false; System.out.println(bool); } }
221
0.628959
0.615385
12
17.416666
14.840589
44
false
false
0
0
0
0
0
0
0.75
false
false
13
1b52247dfbfbce5728438714d3410b8aa1bb9f17
17,763,984,780,842
6aa245b523b22862d74bdc39d8eee0630fc562b7
/DesignPatterns/Strategy/EatBreakfast.java
d15a03f02d0767736773c7d226daf5cf3720e8f0
[]
no_license
chenshuaiyu/StudyNotes
https://github.com/chenshuaiyu/StudyNotes
9342776a00ec9c87e2b5a4877e0747cede820a2b
bc6a030ed2b501d962d854c8b4e7f76150217b20
refs/heads/master
2018-10-10T08:17:39.069000
2018-09-29T14:20:19
2018-09-29T14:20:19
113,152,309
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Strategy; class EatBreakfast implements EatStrategy { @Override public void eatMeal() { System.out.println("吃早饭"); } }
UTF-8
Java
155
java
EatBreakfast.java
Java
[]
null
[]
package Strategy; class EatBreakfast implements EatStrategy { @Override public void eatMeal() { System.out.println("吃早饭"); } }
155
0.651007
0.651007
9
15.555555
15.056273
43
false
false
0
0
0
0
0
0
0.222222
false
false
13
bc0ddcda3ae8eed309c337c176c9de5e3aaf8261
5,720,896,490,064
aa5d2ef56eb63878654192df6dda72f2170eeb83
/app/src/main/java/jomedia/com/rssnewsfeed/data/repository/NewsRepositoryImpl.java
7232ac859030242fb6f00eb255e51d47d0fb2b83
[]
no_license
vladislove80/RssNewsFeed
https://github.com/vladislove80/RssNewsFeed
10068615601429b779bddd719f0c170b01d2fdea
e926e158b1a182cfe7a0a0bbcfd6a3b412d8b9cb
refs/heads/master
2021-01-19T11:54:14.357000
2019-01-14T16:31:11
2019-01-14T16:31:11
68,955,363
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package jomedia.com.rssnewsfeed.data.repository; import android.content.Context; import android.os.Handler; import android.os.Looper; import android.support.annotation.NonNull; import java.util.concurrent.ExecutorService; import jomedia.com.rssnewsfeed.data.api.RestApi; import jomedia.com.rssnewsfeed.data.api.RestManager; import jomedia.com.rssnewsfeed.data.callback.NewsCallback; import jomedia.com.rssnewsfeed.data.executor.TaskExecutor; import jomedia.com.rssnewsfeed.data.models.NewsFeedResponse; import jomedia.com.rssnewsfeed.data.db.DatabaseSource; import jomedia.com.rssnewsfeed.data.db.DatabaseSourceImpl; import jomedia.com.rssnewsfeed.data.tasks.GetNewsTask; import jomedia.com.rssnewsfeed.utils.Utils; public class NewsRepositoryImpl implements NewsRepository { private final RestApi restApi; private final DatabaseSource diskDataSource; private final ExecutorService executorService; private final Handler mainUiHandler; public NewsRepositoryImpl(@NonNull Context context) { restApi = new RestManager().provideRestApi(Utils.BASE_URL); diskDataSource = new DatabaseSourceImpl(context); TaskExecutor taskExecutor = new TaskExecutor(); executorService = taskExecutor.getThreadPoolExecutor(); mainUiHandler = new Handler(Looper.getMainLooper()); } @NonNull @Override public void getNewsItems(@NonNull NewsCallback<NewsFeedResponse> callback, @NonNull String link, @NonNull String category) { executorService.execute(new GetNewsTask(diskDataSource, restApi, mainUiHandler, callback, link, category)); } }
UTF-8
Java
1,610
java
NewsRepositoryImpl.java
Java
[]
null
[]
package jomedia.com.rssnewsfeed.data.repository; import android.content.Context; import android.os.Handler; import android.os.Looper; import android.support.annotation.NonNull; import java.util.concurrent.ExecutorService; import jomedia.com.rssnewsfeed.data.api.RestApi; import jomedia.com.rssnewsfeed.data.api.RestManager; import jomedia.com.rssnewsfeed.data.callback.NewsCallback; import jomedia.com.rssnewsfeed.data.executor.TaskExecutor; import jomedia.com.rssnewsfeed.data.models.NewsFeedResponse; import jomedia.com.rssnewsfeed.data.db.DatabaseSource; import jomedia.com.rssnewsfeed.data.db.DatabaseSourceImpl; import jomedia.com.rssnewsfeed.data.tasks.GetNewsTask; import jomedia.com.rssnewsfeed.utils.Utils; public class NewsRepositoryImpl implements NewsRepository { private final RestApi restApi; private final DatabaseSource diskDataSource; private final ExecutorService executorService; private final Handler mainUiHandler; public NewsRepositoryImpl(@NonNull Context context) { restApi = new RestManager().provideRestApi(Utils.BASE_URL); diskDataSource = new DatabaseSourceImpl(context); TaskExecutor taskExecutor = new TaskExecutor(); executorService = taskExecutor.getThreadPoolExecutor(); mainUiHandler = new Handler(Looper.getMainLooper()); } @NonNull @Override public void getNewsItems(@NonNull NewsCallback<NewsFeedResponse> callback, @NonNull String link, @NonNull String category) { executorService.execute(new GetNewsTask(diskDataSource, restApi, mainUiHandler, callback, link, category)); } }
1,610
0.791925
0.791925
40
39.25
29.841038
128
false
false
0
0
0
0
0
0
0.8
false
false
13
f5d5f48ad3fefc8c0c71af5acbfe8d1186d55d07
26,431,228,796,773
1427d5ff0aabb1a13472dae831ba28c9dc276c2a
/src/test/java/co/com/sofka/gymmanagement/usecase/fitnessgym/CreateFitnessGymTest.java
c52290e3dbe4c43cd66c06292d18064e49abc6fe
[]
no_license
joe-watson-sbf/gym-management-DDD
https://github.com/joe-watson-sbf/gym-management-DDD
98479628b31fe696fd76d1c8b0f1b1d17664ffe4
2ff0e6cd7207d1b9431068605b72215ccd9398e6
refs/heads/master
2023-09-03T05:40:23.258000
2021-10-02T11:29:53
2021-10-02T11:29:53
412,242,821
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package co.com.sofka.gymmanagement.usecase; import co.com.sofka.business.generic.UseCaseHandler; import co.com.sofka.business.repository.DomainEventRepository; import co.com.sofka.business.support.RequestCommand; import co.com.sofka.gymmanagement.domain.fitnessgym.command.CreateFitnessGym; import co.com.sofka.gymmanagement.domain.fitnessgym.event.FitnessGymCreated; import co.com.sofka.gymmanagement.domain.fitnessgym.value.Description; import co.com.sofka.gymmanagement.domain.fitnessgym.value.FitnessGymId; import co.com.sofka.gymmanagement.domain.shared.valueobject.Address; import co.com.sofka.gymmanagement.domain.shared.valueobject.Email; import co.com.sofka.gymmanagement.domain.shared.valueobject.Name; import co.com.sofka.gymmanagement.domain.shared.valueobject.PhoneNumber; import co.com.sofka.gymmanagement.usecase.fitnessgym.Create; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import static org.junit.jupiter.api.Assertions.assertEquals; @ExtendWith(MockitoExtension.class) public class CreateFitnessGymTest { @Mock private DomainEventRepository repository; @Test void createGym(){ var command = new CreateFitnessGym( new FitnessGymId("1919"), new Name("JOE FITNESS"), new Email("admin@joefitness.com"), new PhoneNumber("3048989999"), new Address("Calle 12"), new Description("The best Fitness GYM...") ); var myUseCaseCreateGym = new Create(); var events = UseCaseHandler.getInstance() .syncExecutor(myUseCaseCreateGym, new RequestCommand<>(command)) .orElseThrow() .getDomainEvents(); var event = (FitnessGymCreated) events.get(0); // BUSINESS NAME'S VERIFICATION assertEquals("JOE FITNESS", event.getName().value()); // BUSINESS EMAIL'S VERIFICATION assertEquals("admin@joefitness.com", event.getEmail().value()); // BUSINESS DESCRIPTION'S VERIFICATION assertEquals("The best Fitness GYM...", event.getDescription().value()); } }
UTF-8
Java
2,231
java
CreateFitnessGymTest.java
Java
[ { "context": "w FitnessGymId(\"1919\"),\n new Name(\"JOE FITNESS\"),\n new Email(\"admin@joefitness.co", "end": 1358, "score": 0.9998572468757629, "start": 1347, "tag": "NAME", "value": "JOE FITNESS" }, { "context": "w Name(\"JOE FITNESS\"),\n ...
null
[]
package co.com.sofka.gymmanagement.usecase; import co.com.sofka.business.generic.UseCaseHandler; import co.com.sofka.business.repository.DomainEventRepository; import co.com.sofka.business.support.RequestCommand; import co.com.sofka.gymmanagement.domain.fitnessgym.command.CreateFitnessGym; import co.com.sofka.gymmanagement.domain.fitnessgym.event.FitnessGymCreated; import co.com.sofka.gymmanagement.domain.fitnessgym.value.Description; import co.com.sofka.gymmanagement.domain.fitnessgym.value.FitnessGymId; import co.com.sofka.gymmanagement.domain.shared.valueobject.Address; import co.com.sofka.gymmanagement.domain.shared.valueobject.Email; import co.com.sofka.gymmanagement.domain.shared.valueobject.Name; import co.com.sofka.gymmanagement.domain.shared.valueobject.PhoneNumber; import co.com.sofka.gymmanagement.usecase.fitnessgym.Create; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import static org.junit.jupiter.api.Assertions.assertEquals; @ExtendWith(MockitoExtension.class) public class CreateFitnessGymTest { @Mock private DomainEventRepository repository; @Test void createGym(){ var command = new CreateFitnessGym( new FitnessGymId("1919"), new Name("<NAME>"), new Email("<EMAIL>"), new PhoneNumber("3048989999"), new Address("Calle 12"), new Description("The best Fitness GYM...") ); var myUseCaseCreateGym = new Create(); var events = UseCaseHandler.getInstance() .syncExecutor(myUseCaseCreateGym, new RequestCommand<>(command)) .orElseThrow() .getDomainEvents(); var event = (FitnessGymCreated) events.get(0); // BUSINESS NAME'S VERIFICATION assertEquals("<NAME>", event.getName().value()); // BUSINESS EMAIL'S VERIFICATION assertEquals("<EMAIL>", event.getEmail().value()); // BUSINESS DESCRIPTION'S VERIFICATION assertEquals("The best Fitness GYM...", event.getDescription().value()); } }
2,195
0.717167
0.709547
60
36.183334
26.703615
80
false
false
0
0
0
0
0
0
0.583333
false
false
13
4a2be7489c1f039ede2169d98204c5f7834c6b14
35,476,429,877,457
ceb69a6042aa2c1807de5d2a3aa9052ed7649a07
/Game.java
571730ff31360ae2f6ca7d71266210b50bb7b65b
[]
no_license
gmcavalheiro/DarkDungeon
https://github.com/gmcavalheiro/DarkDungeon
e086e1e07e9761c600d85d62b562f75ab403355f
c73707721a9e7ea36306524328234dcb79e12d9b
refs/heads/master
2021-01-20T04:55:00.597000
2014-02-25T18:16:48
2014-02-25T18:16:48
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package dungeon; import java.util.ArrayList; public class Game implements EntityHost { ArrayList<Drawable> drawables; ArrayList<Entity> entities; public Player player; public Dungeon dungeon; public Game(){ player = new Player(); dungeon = new Dungeon(); entities = new ArrayList<Entity>(); loadEntities(); } private void loadEntities(){ entities.add(dungeon); entities.add(player); entities.add(new Door(5, 5)); } @Override public ArrayList<Entity> collectEntities() { for(int i = 0; i < entities.size(); i++){ Entity entity = entities.get(i); if(entity instanceof EntityHost){ for(Entity e: ((EntityHost) entity).collectEntities()){ if(!entities.contains(e)){ Entity ent = e; entities.add(ent); } } } } return entities; } }
UTF-8
Java
829
java
Game.java
Java
[]
null
[]
package dungeon; import java.util.ArrayList; public class Game implements EntityHost { ArrayList<Drawable> drawables; ArrayList<Entity> entities; public Player player; public Dungeon dungeon; public Game(){ player = new Player(); dungeon = new Dungeon(); entities = new ArrayList<Entity>(); loadEntities(); } private void loadEntities(){ entities.add(dungeon); entities.add(player); entities.add(new Door(5, 5)); } @Override public ArrayList<Entity> collectEntities() { for(int i = 0; i < entities.size(); i++){ Entity entity = entities.get(i); if(entity instanceof EntityHost){ for(Entity e: ((EntityHost) entity).collectEntities()){ if(!entities.contains(e)){ Entity ent = e; entities.add(ent); } } } } return entities; } }
829
0.642943
0.639324
47
16.638298
15.638776
63
false
false
0
0
0
0
0
0
2.340425
false
false
13
833eb561f66a2439d31b29af0c09f87fd6a34648
6,219,112,693,767
42ce17f5adff8c9a24276a2e26303ebfeb6f46e4
/jira-portfolio-src/com/radiantminds/roadmap/common/data/entities/releases/SchedulingRelease.java
2d6ac133d671f95fd566052b4785578d7eddacf0
[ "Apache-2.0" ]
permissive
tied/jira-5
https://github.com/tied/jira-5
1ffea0533cee2cbf351eda5a9f28380e893baa99
e7369b9092d730ca7c25622da8da6d2a80973316
refs/heads/master
2020-03-11T12:50:11.014000
2018-04-04T11:19:00
2018-04-04T11:19:00
130,008,681
1
0
null
true
2018-04-18T05:30:56
2018-04-18T05:30:55
2018-04-04T11:19:10
2018-04-04T11:19:09
13,530
0
0
0
null
false
null
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) ansi // Source File Name: SchedulingRelease.java package com.radiantminds.roadmap.common.data.entities.releases; import com.atlassian.rm.jpo.scheduling.util.IIdentifiable; import com.google.common.base.Optional; public interface SchedulingRelease extends IIdentifiable { public abstract Optional getFixedEndDate(); public abstract Optional getFixedStartDate(); public abstract Optional getDeltaStartDate(); public abstract Boolean getIsLaterRelease(); }
UTF-8
Java
633
java
SchedulingRelease.java
Java
[ { "context": "// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.\n// Jad home page: http://www.kpdus.com/jad.html\n", "end": 61, "score": 0.9996496438980103, "start": 45, "tag": "NAME", "value": "Pavel Kouznetsov" } ]
null
[]
// Decompiled by Jad v1.5.8g. Copyright 2001 <NAME>. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) ansi // Source File Name: SchedulingRelease.java package com.radiantminds.roadmap.common.data.entities.releases; import com.atlassian.rm.jpo.scheduling.util.IIdentifiable; import com.google.common.base.Optional; public interface SchedulingRelease extends IIdentifiable { public abstract Optional getFixedEndDate(); public abstract Optional getFixedStartDate(); public abstract Optional getDeltaStartDate(); public abstract Boolean getIsLaterRelease(); }
623
0.777251
0.764613
22
27.772728
24.224203
63
false
false
0
0
0
0
0
0
0.318182
false
false
13
6ff99f371df973a78fbfa9bba7536b8671ba7564
4,999,341,981,559
2fbb920555d82dc6fdadc129749acf6c632fb7d4
/gdsap-adminconsole-webroot/src/main/java/uk/co/quidos/adminconsole/web/PassportController.java
774297cc6148caefbd92771e62a987ffe7e143e9
[ "Apache-2.0" ]
permissive
ZhangPeng1990/crm
https://github.com/ZhangPeng1990/crm
3cd31b6a121418c47032979354af0886a236a0cf
c5b176718924c024a13cc6ceccb2e737e70cedd3
refs/heads/master
2020-06-05T18:25:41.600000
2015-04-29T10:38:01
2015-04-29T10:38:01
34,787,517
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package uk.co.quidos.adminconsole.web; import java.io.UnsupportedEncodingException; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import uk.co.quidos.common.util.exception.UserException; import uk.co.quidos.common.util.web.ServerInfo; import uk.co.quidos.gdsap.framework.authority.Admin; import uk.co.quidos.gdsap.framework.authority.services.AdminServiceMgr; import uk.co.quidos.gdsap.framework.user.enums.UserStatus; @Controller @RequestMapping("/passport") public class PassportController extends BaseController { @Autowired AdminServiceMgr adminServiceMgr; @RequestMapping("/index") public String index(HttpServletRequest request, ModelMap model) { if (ServerInfo.isAjax(request)) { return "/login_dialog"; } return "/login"; } @RequestMapping("/login") public ModelAndView login(@RequestParam("username")String username, @RequestParam("password") String password, HttpServletRequest request) { if(username == null || username.equals("") || password == null || password.equals("")){ return new ModelAndView("login", "error", getMessage("msg.login.failure")); } try { Admin user = adminServiceMgr.login(username, password); if (user != null && UserStatus.Active.equals(user.getUserStatus())) { request.getSession().setAttribute(Constants.AUTHENTICATION_KEY, user); String backToUrl = request.getParameter("backToUrl"); if (backToUrl == null || backToUrl.trim().length() == 0) { backToUrl = "/"; } else { try { backToUrl = java.net.URLDecoder.decode(backToUrl, "UTF-8"); } catch (UnsupportedEncodingException e) { return new ModelAndView("login", "error", getMessage("msg.login.failure")); } } System.out.println("backToUrl: " + backToUrl); return new ModelAndView("redirect:"+backToUrl); } } catch (UserException e1) { return new ModelAndView("login", "error", getMessage("msg.login.failure")); } return new ModelAndView("login", "error", getMessage("msg.login.failure")); } @RequestMapping("/logout") public ModelAndView logout(HttpServletRequest request) { request.getSession().removeAttribute(Constants.AUTHENTICATION_KEY); return new ModelAndView("/login"); } }
UTF-8
Java
2,643
java
PassportController.java
Java
[]
null
[]
package uk.co.quidos.adminconsole.web; import java.io.UnsupportedEncodingException; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import uk.co.quidos.common.util.exception.UserException; import uk.co.quidos.common.util.web.ServerInfo; import uk.co.quidos.gdsap.framework.authority.Admin; import uk.co.quidos.gdsap.framework.authority.services.AdminServiceMgr; import uk.co.quidos.gdsap.framework.user.enums.UserStatus; @Controller @RequestMapping("/passport") public class PassportController extends BaseController { @Autowired AdminServiceMgr adminServiceMgr; @RequestMapping("/index") public String index(HttpServletRequest request, ModelMap model) { if (ServerInfo.isAjax(request)) { return "/login_dialog"; } return "/login"; } @RequestMapping("/login") public ModelAndView login(@RequestParam("username")String username, @RequestParam("password") String password, HttpServletRequest request) { if(username == null || username.equals("") || password == null || password.equals("")){ return new ModelAndView("login", "error", getMessage("msg.login.failure")); } try { Admin user = adminServiceMgr.login(username, password); if (user != null && UserStatus.Active.equals(user.getUserStatus())) { request.getSession().setAttribute(Constants.AUTHENTICATION_KEY, user); String backToUrl = request.getParameter("backToUrl"); if (backToUrl == null || backToUrl.trim().length() == 0) { backToUrl = "/"; } else { try { backToUrl = java.net.URLDecoder.decode(backToUrl, "UTF-8"); } catch (UnsupportedEncodingException e) { return new ModelAndView("login", "error", getMessage("msg.login.failure")); } } System.out.println("backToUrl: " + backToUrl); return new ModelAndView("redirect:"+backToUrl); } } catch (UserException e1) { return new ModelAndView("login", "error", getMessage("msg.login.failure")); } return new ModelAndView("login", "error", getMessage("msg.login.failure")); } @RequestMapping("/logout") public ModelAndView logout(HttpServletRequest request) { request.getSession().removeAttribute(Constants.AUTHENTICATION_KEY); return new ModelAndView("/login"); } }
2,643
0.709799
0.708664
77
32.350651
30.477484
141
false
false
0
0
0
0
0
0
2.220779
false
false
13
9c91e9e074246cfbf5b4f184f028500c311729c2
20,873,541,060,797
a930b5cdcf40df4adc911c1affd0824f98683796
/Encontro30/psgspringboot/src/main/java/com/example/demo/repository/IFuncionarioRepository.java
f6de87ac36e84338513178d63c73ca2b63fb8eb7
[]
no_license
albertoborges44/AtividadesAvaliativasPSGH3
https://github.com/albertoborges44/AtividadesAvaliativasPSGH3
59719d66ddd892ec9f88cdf6d11ce39129f72116
abaf1dfce2465524b5b684deb8128327c2335e66
refs/heads/main
2023-08-26T08:06:02.215000
2021-10-29T21:29:59
2021-10-29T21:29:59
411,482,740
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.demo.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import com.example.demo.model.Funcionario; import com.example.demo.model.Produto; public interface IFuncionarioRepository extends JpaRepository<Funcionario, Integer> { @Query(value = "SELECT MAX(FuncionarioID) AS MAXID from funcionario f", nativeQuery = true) Integer findByFuncionarioIdMax(); List<Funcionario> findByFuncionarioIdGreaterThan(int num); List<Funcionario>findByFuncionarioIdBetween(int start, int fim); }
UTF-8
Java
631
java
IFuncionarioRepository.java
Java
[]
null
[]
package com.example.demo.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import com.example.demo.model.Funcionario; import com.example.demo.model.Produto; public interface IFuncionarioRepository extends JpaRepository<Funcionario, Integer> { @Query(value = "SELECT MAX(FuncionarioID) AS MAXID from funcionario f", nativeQuery = true) Integer findByFuncionarioIdMax(); List<Funcionario> findByFuncionarioIdGreaterThan(int num); List<Funcionario>findByFuncionarioIdBetween(int start, int fim); }
631
0.787639
0.787639
20
29.549999
30.503237
92
false
false
0
0
0
0
0
0
0.95
false
false
13