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
1e7709076d67c6217131d72f02c066a3a5314ffd
24,747,601,605,571
621e4b2cb2e153790c5ebc8380c08bba563713ac
/src/main/java/com/demoapp/controller/AppDirectStubController.java
a86c3aa7c853100b47217d265662dab7c63da784
[]
no_license
pjlacharite/demoApp
https://github.com/pjlacharite/demoApp
dbac96a746facd4427d78fcaee0da524132d516c
30e9f54792137f1052177b63e2415010c56e8f6b
refs/heads/master
2021-01-12T13:01:13.138000
2016-10-04T17:07:42
2016-10-04T17:07:42
69,402,717
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.demoapp.controller; import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; import static org.springframework.web.bind.annotation.RequestMethod.GET; @Controller public class AppDirectStubController { private static final Logger LOGGER = Logger.getLogger(AppDirectStubController.class); /** * Allows local tests by calling http://localhost:8080/subscription/create?eventUrl=http://localhost:8080/test-create * @return String */ @RequestMapping(value = "/test-create", method = GET, produces = APPLICATION_JSON_VALUE) @ResponseBody public String test() { return "{ \"type\": \"SUBSCRIPTION_ORDER\",\n" + " \"marketplace\": {\n" + " \"baseUrl\": \"https://www.acme.com\",\n" + " \"partner\": \"APPDIRECT\"\n" + " },\n" + " \"creator\": {\n" + " \"address\": {\n" + " \"firstName\": \"Sample\",\n" + " \"fullName\": \"Sample Tester\",\n" + " \"lastName\": \"Tester\"\n" + " },\n" + " \"email\": \"sampletester@testco.com\",\n" + " \"firstName\": \"Sample\",\n" + " \"language\": \"en\",\n" + " \"lastName\": \"Tester\",\n" + " \"locale\": \"en_US\",\n" + " \"openId\": \"https://www.acme.com/openid/id/211aa367-f53b-4606-8887-80a381e0ef69\",\n" + " \"uuid\": \"211aa369-f53b-4606-8887-80a361e0ef66\"\n" + " },\n" + " \"payload\": {\n" + " \"company\": {\n" + " \"country\": \"US\",\n" + " \"name\": \"Sample Testing co.\",\n" + " \"uuid\": \"bd58b532-323b-4627-a828-57729489b27b\",\n" + " \"website\": \"www.testerco.com\"\n" + " },\n" + " \"order\": {\n" + " \"editionCode\": \"FREE\",\n" + " \"pricingDuration\": \"MONTHLY\"\n" + " }\n" + " }\n" + " }"; } /** * Allows local tests by calling http://localhost:8080/subscription/change?eventUrl=http://localhost:8080/test-change * @return String */ @RequestMapping(value = "/test-change", method = GET, produces = APPLICATION_JSON_VALUE) @ResponseBody public String change() { return "{\n" + " \"type\": \"SUBSCRIPTION_CHANGE\",\n" + " \"marketplace\": {\n" + " \"baseUrl\": \"https://www.acme.com\",\n" + " \"partner\": \"APPDIRECT\"\n" + " },\n" + " \"creator\": {\n" + " \"address\": {\n" + " \"city\": \"San Jose\",\n" + " \"country\": \"US\",\n" + " \"firstName\": \"Test\",\n" + " \"fullName\": \"Test User\",\n" + " \"lastName\": \"User\",\n" + " \"state\": \"CA\",\n" + " \"street1\": \"1 Main St\",\n" + " \"zip\": \"95131\"\n" + " },\n" + " \"email\": \"testuser@testco.com\",\n" + " \"firstName\": \"Test\",\n" + " \"language\": \"en\",\n" + " \"lastName\": \"User\",\n" + " \"locale\": \"en_US\",\n" + " \"openId\": \"https://www.acme.com/openid/id/7f59aad1-85cd-4c04-b35b-906ee53acc71\",\n" + " \"uuid\": \"7f59aad1-85cd-4c04-b35b-906ee53acc71\"\n" + " },\n" + " \"payload\": {\n" + " \"account\": {\n" + " \"accountIdentifier\": \"a3f72246-5377-4d92-8bdc-b1b6b450c55c\",\n" + " \"status\": \"ACTIVE\"\n" + " },\n" + " \"order\": {\n" + " \"editionCode\": \"DME\",\n" + " \"pricingDuration\": \"DAILY\",\n" + " \"item\": {\n" + " \"quantity\": \"0\",\n" + " \"unit\": \"GIGABYTE\"\n" + " }\n" + " }\n" + " }\n" + "}\n" + "\n"; } /** * Allows local tests by calling http://localhost:8080/subscription/notice?eventUrl=http://localhost:8080/test-notice * @return String */ @RequestMapping(value = "/test-notice", method = GET, produces = APPLICATION_JSON_VALUE) @ResponseBody public String notice() { return "{\n" + " \"type\": \"SUBSCRIPTION_NOTICE\",\n" + " \"marketplace\": {\n" + " \"baseUrl\": \"https://www.acme.com\",\n" + " \"partner\": \"APPDIRECT\"\n" + " },\n" + " \"payload\": {\n" + " \"account\": {\n" + " \"accountIdentifier\": \"a3f72246-5377-4d92-8bdc-b1b6b450c55c\",\n" + " \"status\": \"ACTIVE\"\n" + " },\n" + " \"notice\": { \"type\": \"CLOSED\" }\n" + " }\n" + "}\n"; } /** * Allows local tests by calling http://localhost:8080/subscription/cancel?eventUrl=http://localhost:8080/test-cancel * @return String */ @RequestMapping(value = "/test-cancel", method = GET, produces = APPLICATION_JSON_VALUE) @ResponseBody public String cancel() { return "{\n" + " \"type\": \"SUBSCRIPTION_CANCEL\",\n" + " \"marketplace\": {\n" + " \"baseUrl\": \"https://www.acme.com\",\n" + " \"partner\": \"APPDIRECT\"\n" + " },\n" + " \"creator\": {\n" + " \"address\": {\n" + " \"city\": \"Sommerville\",\n" + " \"country\": \"US\",\n" + " \"firstName\": \"Test\",\n" + " \"fullName\": \"Test User\",\n" + " \"lastName\": \"User\",\n" + " \"phone\": \"5305556465\",\n" + " \"state\": \"MA\",\n" + " \"street1\": \"55 Grove St\",\n" + " \"zip\": \"02144\"\n" + " },\n" + " \"email\": \"testuser@testco.com\",\n" + " \"firstName\": \"Test\",\n" + " \"language\": \"en\",\n" + " \"lastName\": \"User\",\n" + " \"locale\": \"en_US\",\n" + " \"openId\": \"https://www.acme.com/openid/id/d124bf8b-0b0b-40d3-831b-b7f5a514d487\",\n" + " \"uuid\": \"d124bf8b-0b0b-40d3-831b-b7f5a514d487\"\n" + " },\n" + " \"payload\": {\n" + " \"account\": {\n" + " \"accountIdentifier\": \"a3f72246-5377-4d92-8bdc-b1b6b450c55c\",\n" + " \"status\": \"ACTIVE\"\n" + " }\n" + " }\n" + "}"; } }
UTF-8
Java
7,849
java
AppDirectStubController.java
Java
[ { "context": "\\n\" +\n \" \\\"firstName\\\": \\\"Sample\\\",\\n\" +\n \" \\\"fullName\\\": ", "end": 1230, "score": 0.9540448188781738, "start": 1224, "tag": "NAME", "value": "Sample" }, { "context": ",\\n\" +\n \" \\\"fullName\\\": \\\"Sample Tester\\\",\\n\" +\n \" \\\"lastName\\\": ", "end": 1295, "score": 0.9851567149162292, "start": 1282, "tag": "NAME", "value": "Sample Tester" }, { "context": ",\\n\" +\n \" \\\"lastName\\\": \\\"Tester\\\"\\n\" +\n \" },\\n\" +\n ", "end": 1353, "score": 0.9218502044677734, "start": 1347, "tag": "NAME", "value": "Tester" }, { "context": " },\\n\" +\n \" \\\"email\\\": \\\"sampletester@testco.com\\\",\\n\" +\n \" \\\"firstName\\\": \\", "end": 1455, "score": 0.9998041391372681, "start": 1432, "tag": "EMAIL", "value": "sampletester@testco.com" }, { "context": "\",\\n\" +\n \" \\\"firstName\\\": \\\"Sample\\\",\\n\" +\n \" \\\"language\\\": \\\"", "end": 1512, "score": 0.9713932275772095, "start": 1506, "tag": "NAME", "value": "Sample" }, { "context": "\\\",\\n\" +\n \" \\\"lastName\\\": \\\"Tester\\\",\\n\" +\n \" \\\"locale\\\": \\\"en", "end": 1620, "score": 0.8497036695480347, "start": 1614, "tag": "NAME", "value": "Tester" }, { "context": "US\\\",\\n\" +\n \" \\\"name\\\": \\\"Sample Testing co.\\\",\\n\" +\n \" \\\"uuid\\\": \\\"b", "end": 2106, "score": 0.7074289321899414, "start": 2089, "tag": "NAME", "value": "Sample Testing co" }, { "context": "\",\\n\" +\n \" \\\"firstName\\\": \\\"Test\\\",\\n\" +\n \" \\\"fullName\\\": \\\"", "end": 3373, "score": 0.8194975256919861, "start": 3369, "tag": "NAME", "value": "Test" }, { "context": "\\\",\\n\" +\n \" \\\"fullName\\\": \\\"Test User\\\",\\n\" +\n \" \\\"lastName\\\": \\\"", "end": 3432, "score": 0.9484911561012268, "start": 3423, "tag": "NAME", "value": "Test User" }, { "context": "\\\",\\n\" +\n \" \\\"lastName\\\": \\\"User\\\",\\n\" +\n \" \\\"state\\\": \\\"CA\\", "end": 3486, "score": 0.9323345422744751, "start": 3482, "tag": "NAME", "value": "User" }, { "context": " },\\n\" +\n \" \\\"email\\\": \\\"testuser@testco.com\\\",\\n\" +\n \" \\\"firstName\\\": \\\"T", "end": 3737, "score": 0.9997637867927551, "start": 3718, "tag": "EMAIL", "value": "testuser@testco.com" }, { "context": "m\\\",\\n\" +\n \" \\\"firstName\\\": \\\"Test\\\",\\n\" +\n \" \\\"language\\\": \\\"en", "end": 3790, "score": 0.7694326639175415, "start": 3786, "tag": "NAME", "value": "Test" }, { "context": "en\\\",\\n\" +\n \" \\\"lastName\\\": \\\"User\\\",\\n\" +\n \" \\\"locale\\\": \\\"en_U", "end": 3892, "score": 0.8997779488563538, "start": 3888, "tag": "NAME", "value": "User" }, { "context": " \" \\\"accountIdentifier\\\": \\\"a3f72246-5377-4d92-8bdc-b1b6b450c55c\\\",\\n\" +\n \" \\\"status\\\": \\\"ACTIVE", "end": 4347, "score": 0.9993764758110046, "start": 4307, "tag": "KEY", "value": "a3f72246-5377-4d92-8bdc-b1b6b450c55c\\\",\\" }, { "context": " \" \\\"accountIdentifier\\\": \\\"a3f72246-5377-4d92-8bdc-b1b6b450c55c\\\",\\n\" +\n \" \\\"status\\\": \\\"", "end": 5636, "score": 0.999420166015625, "start": 5602, "tag": "KEY", "value": "a3f72246-5377-4d92-8bdc-b1b6b450c5" }, { "context": "\",\\n\" +\n \" \\\"firstName\\\": \\\"Test\\\",\\n\" +\n \" \\\"fullName\\\": \\\"", "end": 6672, "score": 0.9465222954750061, "start": 6668, "tag": "NAME", "value": "Test" }, { "context": "\\\",\\n\" +\n \" \\\"fullName\\\": \\\"Test User\\\",\\n\" +\n \" \\\"lastName\\\": \\\"User", "end": 6731, "score": 0.8360787034034729, "start": 6722, "tag": "NAME", "value": "Test User" }, { "context": "\\\",\\n\" +\n \" \\\"lastName\\\": \\\"User\\\",\\n\" +\n \" \\\"phone\\\": \\\"530", "end": 6785, "score": 0.8149592280387878, "start": 6781, "tag": "NAME", "value": "User" }, { "context": " },\\n\" +\n \" \\\"email\\\": \\\"testuser@testco.com\\\",\\n\" +\n \" \\\"firstName\\\": \\\"T", "end": 7095, "score": 0.99978107213974, "start": 7076, "tag": "EMAIL", "value": "testuser@testco.com" }, { "context": "m\\\",\\n\" +\n \" \\\"firstName\\\": \\\"Test\\\",\\n\" +\n \" \\\"language\\\": \\\"en", "end": 7148, "score": 0.8611301183700562, "start": 7144, "tag": "NAME", "value": "Test" }, { "context": "en\\\",\\n\" +\n \" \\\"lastName\\\": \\\"User\\\",\\n\" +\n \" \\\"locale\\\": \\\"en_U", "end": 7250, "score": 0.6836014986038208, "start": 7246, "tag": "NAME", "value": "User" }, { "context": " \" \\\"uuid\\\": \\\"d124bf8b-0b0b-40d3-831b-b7f5a514d487\\\"\\n\" +\n \" },\\n\" +\n ", "end": 7482, "score": 0.747149646282196, "start": 7477, "tag": "KEY", "value": "831b-" }, { "context": " \" \\\"uuid\\\": \\\"d124bf8b-0b0b-40d3-831b-b7f5a514d487\\\"\\n\" +\n \" },\\n\" +\n ", "end": 7494, "score": 0.7989747524261475, "start": 7483, "tag": "KEY", "value": "7f5a514d487" }, { "context": " \" \\\"accountIdentifier\\\": \\\"a3f72246-5377-4d92-8bdc-b1b6b450c55c\\\",\\n\" +\n \" \\\"status\\\": \\\"ACTIVE", "end": 7705, "score": 0.9992004632949829, "start": 7665, "tag": "KEY", "value": "a3f72246-5377-4d92-8bdc-b1b6b450c55c\\\",\\" } ]
null
[]
package com.demoapp.controller; import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; import static org.springframework.web.bind.annotation.RequestMethod.GET; @Controller public class AppDirectStubController { private static final Logger LOGGER = Logger.getLogger(AppDirectStubController.class); /** * Allows local tests by calling http://localhost:8080/subscription/create?eventUrl=http://localhost:8080/test-create * @return String */ @RequestMapping(value = "/test-create", method = GET, produces = APPLICATION_JSON_VALUE) @ResponseBody public String test() { return "{ \"type\": \"SUBSCRIPTION_ORDER\",\n" + " \"marketplace\": {\n" + " \"baseUrl\": \"https://www.acme.com\",\n" + " \"partner\": \"APPDIRECT\"\n" + " },\n" + " \"creator\": {\n" + " \"address\": {\n" + " \"firstName\": \"Sample\",\n" + " \"fullName\": \"<NAME>\",\n" + " \"lastName\": \"Tester\"\n" + " },\n" + " \"email\": \"<EMAIL>\",\n" + " \"firstName\": \"Sample\",\n" + " \"language\": \"en\",\n" + " \"lastName\": \"Tester\",\n" + " \"locale\": \"en_US\",\n" + " \"openId\": \"https://www.acme.com/openid/id/211aa367-f53b-4606-8887-80a381e0ef69\",\n" + " \"uuid\": \"211aa369-f53b-4606-8887-80a361e0ef66\"\n" + " },\n" + " \"payload\": {\n" + " \"company\": {\n" + " \"country\": \"US\",\n" + " \"name\": \"<NAME>.\",\n" + " \"uuid\": \"bd58b532-323b-4627-a828-57729489b27b\",\n" + " \"website\": \"www.testerco.com\"\n" + " },\n" + " \"order\": {\n" + " \"editionCode\": \"FREE\",\n" + " \"pricingDuration\": \"MONTHLY\"\n" + " }\n" + " }\n" + " }"; } /** * Allows local tests by calling http://localhost:8080/subscription/change?eventUrl=http://localhost:8080/test-change * @return String */ @RequestMapping(value = "/test-change", method = GET, produces = APPLICATION_JSON_VALUE) @ResponseBody public String change() { return "{\n" + " \"type\": \"SUBSCRIPTION_CHANGE\",\n" + " \"marketplace\": {\n" + " \"baseUrl\": \"https://www.acme.com\",\n" + " \"partner\": \"APPDIRECT\"\n" + " },\n" + " \"creator\": {\n" + " \"address\": {\n" + " \"city\": \"San Jose\",\n" + " \"country\": \"US\",\n" + " \"firstName\": \"Test\",\n" + " \"fullName\": \"<NAME>\",\n" + " \"lastName\": \"User\",\n" + " \"state\": \"CA\",\n" + " \"street1\": \"1 Main St\",\n" + " \"zip\": \"95131\"\n" + " },\n" + " \"email\": \"<EMAIL>\",\n" + " \"firstName\": \"Test\",\n" + " \"language\": \"en\",\n" + " \"lastName\": \"User\",\n" + " \"locale\": \"en_US\",\n" + " \"openId\": \"https://www.acme.com/openid/id/7f59aad1-85cd-4c04-b35b-906ee53acc71\",\n" + " \"uuid\": \"7f59aad1-85cd-4c04-b35b-906ee53acc71\"\n" + " },\n" + " \"payload\": {\n" + " \"account\": {\n" + " \"accountIdentifier\": \"<KEY>n" + " \"status\": \"ACTIVE\"\n" + " },\n" + " \"order\": {\n" + " \"editionCode\": \"DME\",\n" + " \"pricingDuration\": \"DAILY\",\n" + " \"item\": {\n" + " \"quantity\": \"0\",\n" + " \"unit\": \"GIGABYTE\"\n" + " }\n" + " }\n" + " }\n" + "}\n" + "\n"; } /** * Allows local tests by calling http://localhost:8080/subscription/notice?eventUrl=http://localhost:8080/test-notice * @return String */ @RequestMapping(value = "/test-notice", method = GET, produces = APPLICATION_JSON_VALUE) @ResponseBody public String notice() { return "{\n" + " \"type\": \"SUBSCRIPTION_NOTICE\",\n" + " \"marketplace\": {\n" + " \"baseUrl\": \"https://www.acme.com\",\n" + " \"partner\": \"APPDIRECT\"\n" + " },\n" + " \"payload\": {\n" + " \"account\": {\n" + " \"accountIdentifier\": \"<KEY>5c\",\n" + " \"status\": \"ACTIVE\"\n" + " },\n" + " \"notice\": { \"type\": \"CLOSED\" }\n" + " }\n" + "}\n"; } /** * Allows local tests by calling http://localhost:8080/subscription/cancel?eventUrl=http://localhost:8080/test-cancel * @return String */ @RequestMapping(value = "/test-cancel", method = GET, produces = APPLICATION_JSON_VALUE) @ResponseBody public String cancel() { return "{\n" + " \"type\": \"SUBSCRIPTION_CANCEL\",\n" + " \"marketplace\": {\n" + " \"baseUrl\": \"https://www.acme.com\",\n" + " \"partner\": \"APPDIRECT\"\n" + " },\n" + " \"creator\": {\n" + " \"address\": {\n" + " \"city\": \"Sommerville\",\n" + " \"country\": \"US\",\n" + " \"firstName\": \"Test\",\n" + " \"fullName\": \"<NAME>\",\n" + " \"lastName\": \"User\",\n" + " \"phone\": \"5305556465\",\n" + " \"state\": \"MA\",\n" + " \"street1\": \"55 Grove St\",\n" + " \"zip\": \"02144\"\n" + " },\n" + " \"email\": \"<EMAIL>\",\n" + " \"firstName\": \"Test\",\n" + " \"language\": \"en\",\n" + " \"lastName\": \"User\",\n" + " \"locale\": \"en_US\",\n" + " \"openId\": \"https://www.acme.com/openid/id/d124bf8b-0b0b-40d3-831b-b7f5a514d487\",\n" + " \"uuid\": \"d124bf8b-0b0b-40d3-831b-b7f5a514d487\"\n" + " },\n" + " \"payload\": {\n" + " \"account\": {\n" + " \"accountIdentifier\": \"<KEY>n" + " \"status\": \"ACTIVE\"\n" + " }\n" + " }\n" + "}"; } }
7,686
0.372149
0.337623
170
45.176472
26.909075
121
false
false
0
0
0
0
0
0
0.505882
false
false
4
d364f61786c7931fc10c2335f610bbeee7b63fcf
17,600,776,026,366
6c24ce36b03fa725c36fb58afcffb55e183a622a
/src/com/esprit/services/ProductService.java
e91da3d2aa0b6a63fe88fc16563a2efac57420ab
[ "Apache-2.0" ]
permissive
sadek-selmi/BaskaltyMobilePIDEV
https://github.com/sadek-selmi/BaskaltyMobilePIDEV
eab99b401daa4ec4b70208e9485feb2ebe072e77
9a221190c22c0bd66fe5d15f92a74c4d829022cc
refs/heads/master
2023-05-13T19:05:08.810000
2020-06-06T16:29:28
2020-06-06T16:29:28
269,474,141
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.esprit.services; import com.codename1.components.ToastBar; import com.codename1.io.CharArrayReader; import com.codename1.io.ConnectionRequest; import com.codename1.io.JSONParser; import com.codename1.io.NetworkEvent; import com.codename1.io.NetworkManager; import com.codename1.ui.Dialog; import com.codename1.ui.FontImage; import com.codename1.ui.events.ActionListener; import com.codename1.ui.util.Resources; import com.codename1.uikit.cleanmodern.AfficherMesProduitsForm; import com.esprit.entities.Product; import com.esprit.entities.User; import com.esprit.utils.DataSource; import com.esprit.utils.Statics; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * * @author benha */ public class ProductService { private ConnectionRequest request; private boolean responseResult; ArrayList<Product> products = new ArrayList<>(); public ProductService() { request = DataSource.getInstance().getRequest(); } public boolean addProduct(Product p) { String url = Statics.BASE_URL + "/products/add?name=" + p.getName() + "&price=" + p.getPrice() + "&image=" + p.getImage() + "&description=" + p.getDescription() + "&reference=" + p.getReference() + "&quantite=" + p.getQuantity()+"&iduser="+User.connectedUser.getId(); request.setUrl(url); request.addResponseListener(new ActionListener<NetworkEvent>() { @Override public void actionPerformed(NetworkEvent evt) { responseResult = request.getResponseCode() == 200; // Code HTTP 200 OK request.removeResponseListener(this); } }); NetworkManager.getInstance().addToQueueAndWait(request); return responseResult; } public ArrayList<Product> parseProducts(String jsonText) { try { JSONParser jp = new JSONParser(); Map<String, Object> tasksListJson = jp.parseJSON(new CharArrayReader(jsonText.toCharArray())); List<Map<String, Object>> list = (List<Map<String, Object>>) tasksListJson.get("root"); for (Map<String, Object> obj : list) { int id = (int) Float.parseFloat(obj.get("id").toString()); String name = obj.get("name").toString(); int quantity = (int) Float.parseFloat(obj.get("quantite").toString()); String reference = obj.get("reference").toString(); String description = obj.get("description").toString(); String image = obj.get("image").toString(); int price = (int) Float.parseFloat(obj.get("price").toString()); products.add(new Product(id, quantity, name, reference, description, price, image)); } } catch (IOException ex) { } return products; } public boolean SearchProduct(int id) { String url = Statics.BASE_URL + "/products/find/" + id; request.setUrl(url); request.setPost(false); request.addResponseListener(new ActionListener<NetworkEvent>() { @Override public void actionPerformed(NetworkEvent evt) { responseResult = request.getResponseCode() == 200; request.removeResponseListener(this); } }); NetworkManager.getInstance().addToQueueAndWait(request); return responseResult; } public ArrayList<Product> searchProduct2(int id) { String url = Statics.BASE_URL + "/products/find/" + id; request.setUrl(url); request.setPost(false); request.addResponseListener(new ActionListener<NetworkEvent>() { @Override public void actionPerformed(NetworkEvent evt) { products = parseProducts(new String(request.getResponseData())); request.removeResponseListener(this); } }); NetworkManager.getInstance().addToQueueAndWait(request); return products; } public ArrayList<Product> getProductsById(int id_user) { String url = Statics.BASE_URL + "/products/getByUser/"+id_user; request.setUrl(url); request.setPost(false); request.addResponseListener(new ActionListener<NetworkEvent>() { @Override public void actionPerformed(NetworkEvent evt) { products = parseProducts(new String(request.getResponseData())); request.removeResponseListener(this); } }); NetworkManager.getInstance().addToQueueAndWait(request); return products; } public ArrayList<Product> getAllProducts() { String url = Statics.BASE_URL + "/products/all"; request.setUrl(url); request.setPost(false); request.addResponseListener(new ActionListener<NetworkEvent>() { @Override public void actionPerformed(NetworkEvent evt) { products = parseProducts(new String(request.getResponseData())); request.removeResponseListener(this); } }); NetworkManager.getInstance().addToQueueAndWait(request); return products; } public ArrayList<Product> parseProductDetails(String json) { ArrayList<Product> listTasks = new ArrayList<>(); try { JSONParser j = new JSONParser(); Map<String, Object> articles = j.parseJSON(new CharArrayReader(json.toCharArray())); List<Map<String, Object>> list = (List<Map<String, Object>>) articles.get("root"); for (Map<String, Object> obj : list) { Product pro = new Product(); int id = (int) Float.parseFloat(obj.get("id").toString()); pro.setId((int) id); pro.setImage((String) obj.get("name")); pro.setDescription((String) obj.get("description")); pro.setReference((String) obj.get("reference")); pro.setImage((String) obj.get("image")); pro.setPrice((int) Float.parseFloat(obj.get("price").toString())); pro.setQuantity((int) Float.parseFloat(obj.get("quantite").toString())); System.out.println(pro.toString()); listTasks.add(pro); } } catch (IOException ex) { } System.out.println(listTasks); return listTasks; } /* public ArrayList<Product> SearchProduct (int id) { //ArrayList<Product> pdetails = new ArrayList<>(); String url = Statics.BASE_URL + "/products/find/"+id; request.setUrl(url); request.addResponseListener(new ActionListener<NetworkEvent>() { @Override public void actionPerformed(NetworkEvent evt) { // ProductService ser = new ProductService(); products = parseProductDetails(new String(request.getResponseData())); request.removeResponseListener(this); } }); NetworkManager.getInstance().addToQueueAndWait(request); return products; }*/ /* public ArrayList<Product> SearchProduct(int id) { String url = Statics.BASE_URL + "/products/find/"+id; request.setUrl(url); request.setPost(false); request.addResponseListener(new ActionListener<NetworkEvent>() { @Override public void actionPerformed(NetworkEvent evt) { products = parseProducts(new String(request.getResponseData())); request.removeResponseListener(this); } }); NetworkManager.getInstance().addToQueueAndWait(request); return products; }*/ public void DeleteProduct (int id) { String url = Statics.BASE_URL + "/products/delete?id="+id; request.setUrl(url); request.setPost(true); request.addResponseListener(new ActionListener<NetworkEvent>() { @Override public void actionPerformed(NetworkEvent evt) { if (responseResult = request.getResponseCode() == 200) { request.removeResponseListener(this); ToastBar.showMessage("Product deleted Successfully !",FontImage.MATERIAL_DONE, 5); } else { ToastBar.showMessage("Error,Try again !",FontImage.MATERIAL_ERROR, 5); } } }); NetworkManager.getInstance().addToQueueAndWait(request); } public boolean UpdateProduct(int id,String name,int price,String description,String reference,int quantity) { String url = Statics.BASE_URL + "/products/edit?id=" + id + "&name=" + name + "&price=" + price + "&description=" + description + "&reference=" + reference + "&quantite=" + quantity; request.setUrl(url); request.addResponseListener(new ActionListener<NetworkEvent>() { @Override public void actionPerformed(NetworkEvent evt) { responseResult = request.getResponseCode() == 200; // Code HTTP 200 OK request.removeResponseListener(this); } }); NetworkManager.getInstance().addToQueueAndWait(request); return responseResult; } }
UTF-8
Java
9,668
java
ProductService.java
Java
[ { "context": "til.List;\nimport java.util.Map;\n\n/**\n *\n * @author benha\n */\npublic class ProductService {\n\n private Co", "end": 936, "score": 0.9964743256568909, "start": 931, "tag": "USERNAME", "value": "benha" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.esprit.services; import com.codename1.components.ToastBar; import com.codename1.io.CharArrayReader; import com.codename1.io.ConnectionRequest; import com.codename1.io.JSONParser; import com.codename1.io.NetworkEvent; import com.codename1.io.NetworkManager; import com.codename1.ui.Dialog; import com.codename1.ui.FontImage; import com.codename1.ui.events.ActionListener; import com.codename1.ui.util.Resources; import com.codename1.uikit.cleanmodern.AfficherMesProduitsForm; import com.esprit.entities.Product; import com.esprit.entities.User; import com.esprit.utils.DataSource; import com.esprit.utils.Statics; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * * @author benha */ public class ProductService { private ConnectionRequest request; private boolean responseResult; ArrayList<Product> products = new ArrayList<>(); public ProductService() { request = DataSource.getInstance().getRequest(); } public boolean addProduct(Product p) { String url = Statics.BASE_URL + "/products/add?name=" + p.getName() + "&price=" + p.getPrice() + "&image=" + p.getImage() + "&description=" + p.getDescription() + "&reference=" + p.getReference() + "&quantite=" + p.getQuantity()+"&iduser="+User.connectedUser.getId(); request.setUrl(url); request.addResponseListener(new ActionListener<NetworkEvent>() { @Override public void actionPerformed(NetworkEvent evt) { responseResult = request.getResponseCode() == 200; // Code HTTP 200 OK request.removeResponseListener(this); } }); NetworkManager.getInstance().addToQueueAndWait(request); return responseResult; } public ArrayList<Product> parseProducts(String jsonText) { try { JSONParser jp = new JSONParser(); Map<String, Object> tasksListJson = jp.parseJSON(new CharArrayReader(jsonText.toCharArray())); List<Map<String, Object>> list = (List<Map<String, Object>>) tasksListJson.get("root"); for (Map<String, Object> obj : list) { int id = (int) Float.parseFloat(obj.get("id").toString()); String name = obj.get("name").toString(); int quantity = (int) Float.parseFloat(obj.get("quantite").toString()); String reference = obj.get("reference").toString(); String description = obj.get("description").toString(); String image = obj.get("image").toString(); int price = (int) Float.parseFloat(obj.get("price").toString()); products.add(new Product(id, quantity, name, reference, description, price, image)); } } catch (IOException ex) { } return products; } public boolean SearchProduct(int id) { String url = Statics.BASE_URL + "/products/find/" + id; request.setUrl(url); request.setPost(false); request.addResponseListener(new ActionListener<NetworkEvent>() { @Override public void actionPerformed(NetworkEvent evt) { responseResult = request.getResponseCode() == 200; request.removeResponseListener(this); } }); NetworkManager.getInstance().addToQueueAndWait(request); return responseResult; } public ArrayList<Product> searchProduct2(int id) { String url = Statics.BASE_URL + "/products/find/" + id; request.setUrl(url); request.setPost(false); request.addResponseListener(new ActionListener<NetworkEvent>() { @Override public void actionPerformed(NetworkEvent evt) { products = parseProducts(new String(request.getResponseData())); request.removeResponseListener(this); } }); NetworkManager.getInstance().addToQueueAndWait(request); return products; } public ArrayList<Product> getProductsById(int id_user) { String url = Statics.BASE_URL + "/products/getByUser/"+id_user; request.setUrl(url); request.setPost(false); request.addResponseListener(new ActionListener<NetworkEvent>() { @Override public void actionPerformed(NetworkEvent evt) { products = parseProducts(new String(request.getResponseData())); request.removeResponseListener(this); } }); NetworkManager.getInstance().addToQueueAndWait(request); return products; } public ArrayList<Product> getAllProducts() { String url = Statics.BASE_URL + "/products/all"; request.setUrl(url); request.setPost(false); request.addResponseListener(new ActionListener<NetworkEvent>() { @Override public void actionPerformed(NetworkEvent evt) { products = parseProducts(new String(request.getResponseData())); request.removeResponseListener(this); } }); NetworkManager.getInstance().addToQueueAndWait(request); return products; } public ArrayList<Product> parseProductDetails(String json) { ArrayList<Product> listTasks = new ArrayList<>(); try { JSONParser j = new JSONParser(); Map<String, Object> articles = j.parseJSON(new CharArrayReader(json.toCharArray())); List<Map<String, Object>> list = (List<Map<String, Object>>) articles.get("root"); for (Map<String, Object> obj : list) { Product pro = new Product(); int id = (int) Float.parseFloat(obj.get("id").toString()); pro.setId((int) id); pro.setImage((String) obj.get("name")); pro.setDescription((String) obj.get("description")); pro.setReference((String) obj.get("reference")); pro.setImage((String) obj.get("image")); pro.setPrice((int) Float.parseFloat(obj.get("price").toString())); pro.setQuantity((int) Float.parseFloat(obj.get("quantite").toString())); System.out.println(pro.toString()); listTasks.add(pro); } } catch (IOException ex) { } System.out.println(listTasks); return listTasks; } /* public ArrayList<Product> SearchProduct (int id) { //ArrayList<Product> pdetails = new ArrayList<>(); String url = Statics.BASE_URL + "/products/find/"+id; request.setUrl(url); request.addResponseListener(new ActionListener<NetworkEvent>() { @Override public void actionPerformed(NetworkEvent evt) { // ProductService ser = new ProductService(); products = parseProductDetails(new String(request.getResponseData())); request.removeResponseListener(this); } }); NetworkManager.getInstance().addToQueueAndWait(request); return products; }*/ /* public ArrayList<Product> SearchProduct(int id) { String url = Statics.BASE_URL + "/products/find/"+id; request.setUrl(url); request.setPost(false); request.addResponseListener(new ActionListener<NetworkEvent>() { @Override public void actionPerformed(NetworkEvent evt) { products = parseProducts(new String(request.getResponseData())); request.removeResponseListener(this); } }); NetworkManager.getInstance().addToQueueAndWait(request); return products; }*/ public void DeleteProduct (int id) { String url = Statics.BASE_URL + "/products/delete?id="+id; request.setUrl(url); request.setPost(true); request.addResponseListener(new ActionListener<NetworkEvent>() { @Override public void actionPerformed(NetworkEvent evt) { if (responseResult = request.getResponseCode() == 200) { request.removeResponseListener(this); ToastBar.showMessage("Product deleted Successfully !",FontImage.MATERIAL_DONE, 5); } else { ToastBar.showMessage("Error,Try again !",FontImage.MATERIAL_ERROR, 5); } } }); NetworkManager.getInstance().addToQueueAndWait(request); } public boolean UpdateProduct(int id,String name,int price,String description,String reference,int quantity) { String url = Statics.BASE_URL + "/products/edit?id=" + id + "&name=" + name + "&price=" + price + "&description=" + description + "&reference=" + reference + "&quantite=" + quantity; request.setUrl(url); request.addResponseListener(new ActionListener<NetworkEvent>() { @Override public void actionPerformed(NetworkEvent evt) { responseResult = request.getResponseCode() == 200; // Code HTTP 200 OK request.removeResponseListener(this); } }); NetworkManager.getInstance().addToQueueAndWait(request); return responseResult; } }
9,668
0.604779
0.601469
264
35.621212
29.293455
116
false
false
0
0
0
0
0
0
0.57197
false
false
4
11a1300125113af79e0f5a48b46d4b1ef807b0ff
15,556,371,546,866
7db7fff249bedccebea9a6d27a11bde046b7b11c
/06_vsebovalniki/07_obratSlovarja/Test03.java
18fbe54d27cfa00bdf3bad6b73241707b647d395
[]
no_license
bl4ko/java_programming
https://github.com/bl4ko/java_programming
acca46aa565ef18c633fdd7b1c5b9119252b8844
5cf88c17a841b7e7eb11ba02b94b3bf971b8fc50
refs/heads/master
2023-07-13T03:53:38.788000
2021-08-25T17:38:21
2021-08-25T17:38:21
362,529,919
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.*; public class Test03 { public static void main(String[] args) { Map<String, String> slovar = Map.of( "deska", "board", "dobiti", "get", "doseci", "get", "nacin", "way", "odbor", "board", "pot", "way", "prispeti", "get", "risati", "draw", "tabla", "board", "vleci", "draw" ); Map<String, Set<String>> obrat = ObratSlovarja.obrni(slovar); izpisi(obrat); } private static <V, K> void izpisi(Map<V, Set<K>> slovar) { Map<V, Set<K>> novi = new TreeMap<>(slovar); for (V v: novi.keySet()) { novi.put(v, new TreeSet<>(slovar.get(v))); } for (V v: novi.keySet()) { System.out.printf("%s -> %s%n", v, novi.get(v)); } } }
UTF-8
Java
907
java
Test03.java
Java
[]
null
[]
import java.util.*; public class Test03 { public static void main(String[] args) { Map<String, String> slovar = Map.of( "deska", "board", "dobiti", "get", "doseci", "get", "nacin", "way", "odbor", "board", "pot", "way", "prispeti", "get", "risati", "draw", "tabla", "board", "vleci", "draw" ); Map<String, Set<String>> obrat = ObratSlovarja.obrni(slovar); izpisi(obrat); } private static <V, K> void izpisi(Map<V, Set<K>> slovar) { Map<V, Set<K>> novi = new TreeMap<>(slovar); for (V v: novi.keySet()) { novi.put(v, new TreeSet<>(slovar.get(v))); } for (V v: novi.keySet()) { System.out.printf("%s -> %s%n", v, novi.get(v)); } } }
907
0.428886
0.426681
31
28.225807
19.035976
69
false
false
0
0
0
0
0
0
1.096774
false
false
4
94bf23887603e8ac713711d7f98e7167287fdc99
20,864,951,174,003
94528515b0544aba0258601d53b28fd337a8b204
/hadoop-benchmarks/src/main/java/pegasus/pagerank/MinMaxInfo.java
7a103f549681b907af5ff24ef33ab5fc459e59ee
[]
no_license
harshavardhana/KVCBench
https://github.com/harshavardhana/KVCBench
6f801c0830c1d48ee40e3ba460ef6bdd12597324
b7c0a91e0a74ca22d2f5b6279b36cb96079b8d16
refs/heads/master
2020-06-23T22:52:34.170000
2017-03-09T10:41:30
2017-03-09T10:41:30
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pegasus.pagerank; public class MinMaxInfo { public double min; public double max; }
UTF-8
Java
101
java
MinMaxInfo.java
Java
[]
null
[]
package pegasus.pagerank; public class MinMaxInfo { public double min; public double max; }
101
0.722772
0.722772
6
15.833333
10.915076
25
false
false
0
0
0
0
0
0
0.5
false
false
4
3b97fd51523206bbb8988e6a4ecb78a95b5f6aa5
28,681,791,667,712
666fbed7e646eb41e321d75834af698bbdc859aa
/src/sundaySch/students/StudentsController.java
7c07d493f9167c47f8454da111c38aac74c40195
[]
no_license
Cosmosha/SundaySchoolSystem-Demo
https://github.com/Cosmosha/SundaySchoolSystem-Demo
827c722b43e811eab869df8a65c252189a1bd48e
919d4d32d67ba3c869df3a68ea7b178a56e3353c
refs/heads/master
2020-04-19T15:00:14.625000
2019-01-30T02:06:13
2019-01-30T02:06:13
168,261,240
1
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 sundaySch.students; import com.jfoenix.controls.JFXButton; import com.jfoenix.controls.JFXComboBox; import com.jfoenix.controls.JFXDatePicker; import com.jfoenix.controls.JFXTextField; import com.jfoenix.controls.JFXTreeTableColumn; import com.jfoenix.controls.JFXTreeTableView; import com.jfoenix.controls.RecursiveTreeItem; import com.jfoenix.controls.datamodels.treetable.RecursiveTreeObject; import javafx.fxml.FXML; import javafx.scene.control.MenuBar; import javafx.scene.control.ProgressIndicator; import java.net.URL; import java.time.LocalDate; import java.util.ResourceBundle; import java.util.function.Predicate; import javafx.animation.KeyFrame; import javafx.animation.KeyValue; import javafx.animation.Timeline; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.Initializable; import javafx.scene.control.Alert; import javafx.scene.control.TreeItem; import javafx.scene.control.TreeTableColumn; import javafx.util.Callback; import javafx.util.Duration; import sundaySch.util.Utility; /** * FXML Controller class * * @author cosmos hagan */ public class StudentsController implements Initializable { @FXML private MenuBar menuTab; @FXML private JFXTreeTableView<User> treeview; @FXML private JFXComboBox<String> genderCB; @FXML private JFXDatePicker dobTxt; @FXML private JFXTextField mothersTxt, mothersNumTxt, fathersNumTxt, fathersTxt; @FXML private JFXComboBox<String> classCB; @FXML private JFXComboBox<String> schoolCB; @FXML private JFXTextField nameSchTxt, phoneTxt, residenceTxt,searchTxt, nameTxt; @FXML private JFXButton clearButtn, deleteButton, saveButtn; @FXML private ProgressIndicator prog; @FXML private JFXButton editButton; ObservableList<String>gender = FXCollections.observableArrayList("Male", "Female"); ObservableList<String>schlist = FXCollections.observableArrayList("Tertiary", "Secondary", "Primary"); ObservableList<String>classlist = FXCollections.observableArrayList("Senior Class", "Junior Class", "Class 5&6", "Class 3&4","Class 1&2","Beginners Class"); Utility handler; private void treeView() { JFXTreeTableColumn<User, String> sID = new JFXTreeTableColumn<>("Student ID"); sID.setPrefWidth(150); sID.setCellValueFactory(new Callback<TreeTableColumn.CellDataFeatures<User, String>, ObservableValue<String>>() { @Override public ObservableValue<String> call(TreeTableColumn.CellDataFeatures<User, String> param) { return param.getValue().getValue().sID; } }); JFXTreeTableColumn<User, String> tName = new JFXTreeTableColumn<>("Name"); tName.setPrefWidth(150); tName.setCellValueFactory(new Callback<TreeTableColumn.CellDataFeatures<User, String>, ObservableValue<String>>() { @Override public ObservableValue<String> call(TreeTableColumn.CellDataFeatures<User, String> param) { return param.getValue().getValue().Name; } }); JFXTreeTableColumn<User, String> genderCol = new JFXTreeTableColumn<>("Gender"); genderCol.setPrefWidth(150); genderCol.setCellValueFactory(new Callback<TreeTableColumn.CellDataFeatures<User, String>, ObservableValue<String>>() { @Override public ObservableValue<String> call(TreeTableColumn.CellDataFeatures<User, String> param) { return param.getValue().getValue().Gender; } }); JFXTreeTableColumn<User, String> DOB = new JFXTreeTableColumn<>("Date Of Birth"); DOB.setPrefWidth(150); DOB.setCellValueFactory(new Callback<TreeTableColumn.CellDataFeatures<User, String>, ObservableValue<String>>() { @Override public ObservableValue<String> call(TreeTableColumn.CellDataFeatures<User, String> param) { return param.getValue().getValue().DOB; } }); JFXTreeTableColumn<User, String> mothersNamCol = new JFXTreeTableColumn<>("Mother's Name"); mothersNamCol.setPrefWidth(150); mothersNamCol.setCellValueFactory(new Callback<TreeTableColumn.CellDataFeatures<User, String>, ObservableValue<String>>() { @Override public ObservableValue<String> call(TreeTableColumn.CellDataFeatures<User, String> param) { return param.getValue().getValue().MothersName; } }); JFXTreeTableColumn<User, String> mothersNumCol = new JFXTreeTableColumn<>("Mother's Number"); mothersNumCol.setPrefWidth(150); mothersNumCol.setCellValueFactory(new Callback<TreeTableColumn.CellDataFeatures<User, String>, ObservableValue<String>>() { @Override public ObservableValue<String> call(TreeTableColumn.CellDataFeatures<User, String> param) { return param.getValue().getValue().MothersNumb; } }); JFXTreeTableColumn<User, String> fatherNamCol = new JFXTreeTableColumn<>("Father's Name"); fatherNamCol.setPrefWidth(150); fatherNamCol.setCellValueFactory(new Callback<TreeTableColumn.CellDataFeatures<User, String>, ObservableValue<String>>() { @Override public ObservableValue<String> call(TreeTableColumn.CellDataFeatures<User, String> param) { return param.getValue().getValue().FathersName; } }); JFXTreeTableColumn<User, String> fathersNumCol = new JFXTreeTableColumn<>("Father's Number"); fathersNumCol.setPrefWidth(150); fathersNumCol.setCellValueFactory(new Callback<TreeTableColumn.CellDataFeatures<User, String>, ObservableValue<String>>() { @Override public ObservableValue<String> call(TreeTableColumn.CellDataFeatures<User, String> param) { return param.getValue().getValue().FathersNum; } }); JFXTreeTableColumn<User, String> residenceCol = new JFXTreeTableColumn<>("Residence"); residenceCol.setPrefWidth(150); residenceCol.setCellValueFactory(new Callback<TreeTableColumn.CellDataFeatures<User, String>, ObservableValue<String>>() { @Override public ObservableValue<String> call(TreeTableColumn.CellDataFeatures<User, String> param) { return param.getValue().getValue().Residence; } }); JFXTreeTableColumn<User, String> classCol = new JFXTreeTableColumn<>("Class"); classCol.setPrefWidth(150); classCol.setCellValueFactory(new Callback<TreeTableColumn.CellDataFeatures<User, String>, ObservableValue<String>>() { @Override public ObservableValue<String> call(TreeTableColumn.CellDataFeatures<User, String> param) { return param.getValue().getValue().Class; } }); JFXTreeTableColumn<User, String> schoolCol = new JFXTreeTableColumn<>("School"); schoolCol.setPrefWidth(150); schoolCol.setCellValueFactory(new Callback<TreeTableColumn.CellDataFeatures<User, String>, ObservableValue<String>>() { @Override public ObservableValue<String> call(TreeTableColumn.CellDataFeatures<User, String> param) { return param.getValue().getValue().School; } }); JFXTreeTableColumn<User, String> numCol = new JFXTreeTableColumn<>("Phone Number"); numCol.setPrefWidth(150); numCol.setCellValueFactory(new Callback<TreeTableColumn.CellDataFeatures<User, String>, ObservableValue<String>>() { @Override public ObservableValue<String> call(TreeTableColumn.CellDataFeatures<User, String> param) { return param.getValue().getValue().Number; } }); ObservableList<User> users = FXCollections.observableArrayList(); users.add(new User("ST001","Pricilla Arthur", "Female", "03/04/2002", "Sarah Arthur", "0247580432", "Ebenezer Arthur", "0547845213", "Effia-Kuma", "Senior Class", "Senior High", "Fijai","0240784563")); users.add(new User("ST002","Joycelyn Ackon", "Female", "23/10/2002", "Hannah Ackon", "0247580432", "Ernest Ackon", "0547845213", "WestLine", "Senior Class", "Senior High", "Secko","0240784563")); // final TreeItem<User> root = new RecursiveTreeItem<User>(users, RecursiveTreeObject::getChildren); final TreeItem<User> root = new RecursiveTreeItem<User>(users,RecursiveTreeObject::getChildren); treeview.getColumns().setAll(sID,tName, genderCol, DOB, mothersNamCol, mothersNumCol, fatherNamCol, fathersNumCol, residenceCol, classCol, schoolCol, numCol); treeview.setRoot(root); treeview.setShowRoot(false); searchTxt.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { treeview.setPredicate(new Predicate<TreeItem<User>>() { @Override public boolean test(TreeItem<User> user) { Boolean flag = user.getValue().Name.getValue().contains(newValue)|| user.getValue().Class.getValue().contains(newValue)||user.getValue().Gender.getValue().contains(newValue)|| user.getValue().School.getValue().contains(newValue) || user.getValue().Residence.getValue().contains(newValue)|| user.getValue().DOB.getValue().contains(newValue) ; return flag; } }); } }); } @FXML private void editButton(ActionEvent event) { } private void combobox(){ genderCB.setItems(gender); schoolCB.setItems(schlist); classCB.setItems(classlist); } class User extends RecursiveTreeObject<User> { StringProperty sID; StringProperty Name; StringProperty Gender; StringProperty DOB; StringProperty MothersName; StringProperty MothersNumb ; StringProperty FathersName; StringProperty FathersNum; StringProperty Residence; StringProperty Class; StringProperty School; StringProperty NameSch; StringProperty Number; public User(String sID,String Name, String Gender, String DOB, String MothersName, String MothersNumb,String FathersName, String FathersNum, String Residence, String Class, String School, String NameSch, String Number) { this.sID = new SimpleStringProperty(sID); this.Name = new SimpleStringProperty(Name); this.Gender = new SimpleStringProperty(Gender); this.DOB = new SimpleStringProperty(DOB); this.MothersName = new SimpleStringProperty(MothersName); this.MothersNumb = new SimpleStringProperty(MothersNumb ); this.FathersName = new SimpleStringProperty(FathersName); this.FathersNum = new SimpleStringProperty(FathersNum); this.Residence = new SimpleStringProperty(Residence); this.Class = new SimpleStringProperty(Class); this.School = new SimpleStringProperty(School); this.NameSch = new SimpleStringProperty(NameSch); this.Number = new SimpleStringProperty(Number); } } @FXML private void deleteButton(ActionEvent event) { } @FXML void clearButton(ActionEvent event) { } @FXML void saveButton(ActionEvent event) { add(); } void add(){ Timeline timeline = new Timeline(); KeyValue key1 = new KeyValue(prog.progressProperty(), 0.01); KeyFrame frame1 = new KeyFrame(Duration.millis(550), key1); KeyValue key2 = new KeyValue(prog.progressProperty(), 1); KeyFrame frame2 = new KeyFrame(Duration.seconds(1), key2); prog.setVisible(true); timeline.getKeyFrames().addAll(frame1,frame2); timeline.play(); String tID ="ST001"; String name = nameTxt.getText(); String genda = genderCB.getValue(); LocalDate dob = dobTxt.getValue(); String stat = schoolCB.getValue(); String claz = classCB.getValue(); String resid = residenceTxt.getText(); String sch = nameSchTxt.getText(); String phone = phoneTxt.getText(); String mother = mothersTxt.getText(); String motherNum = mothersNumTxt.getText(); String father = fathersTxt.getText(); String fatherNum = fathersNumTxt.getText(); Boolean flag = (name.isEmpty() || genda.isEmpty() || genda.isEmpty() || resid.isEmpty() || mother.isEmpty()|| motherNum.isEmpty()|| father.isEmpty()|| fatherNum.isEmpty() || phone.isEmpty()||stat.isEmpty()|| claz.isEmpty()||sch.isEmpty()); if(flag){ Alert alert = new Alert(Alert.AlertType.ERROR); alert.setHeaderText(null); alert.setContentText("Please Enter in all fields"); alert.showAndWait(); return; } String st= "INSERT INTO student VALUES ("+ "'" +tID+"'," + "'" +name+"'," + "'" +genda+ "'," + "'" +dob+ "'," + "'" +mother+ "'," + "'" +motherNum+ "'," + "'" +father+ "'," + "'" +fatherNum+ "'," + "'" +resid+ "'," + "'" +stat+ "'," + "'" +sch+ "'," + "'" +claz+ "'," + "'" +phone+ "'" + ")"; System.out.println(st); if(handler.execAction(st)){ timeline.setOnFinished(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setHeaderText(null); alert.setContentText("Saved"); alert.show(); } }); }else{ timeline.setOnFinished(e->{ Alert alert = new Alert(Alert.AlertType.ERROR); alert.setHeaderText(null); alert.setContentText("Failed"); alert.show(); prog.setVisible(false); }); } } @Override public void initialize(URL url, ResourceBundle rb) { // TODO LocalDate da = LocalDate.now(); dobTxt.setValue(da); combobox(); prog.setVisible(false); treeView(); } void progress(){ prog.setVisible(true); Timeline timeline = new Timeline(); KeyValue key1 = new KeyValue(prog.progressProperty(), 0.01); KeyFrame frame1 = new KeyFrame(Duration.millis(550), key1); KeyValue key2 = new KeyValue(prog.progressProperty(), 1); KeyFrame frame2 = new KeyFrame(Duration.seconds(1), key2); timeline.getKeyFrames().addAll(frame1,frame2); timeline.play(); if(nameTxt.getText().equals("Cosmos")){ timeline.setOnFinished(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setHeaderText(null); alert.setContentText("Saved"); alert.show(); } }); }else{ timeline.setOnFinished(e->{ Alert alert = new Alert(Alert.AlertType.ERROR); alert.setHeaderText(null); alert.setContentText("Failed"); alert.show(); prog.setVisible(false); }); } } }
UTF-8
Java
16,691
java
StudentsController.java
Java
[ { "context": "ility;\n\n/**\n * FXML Controller class\n *\n * @author cosmos hagan\n */\npublic class StudentsController implements Ini", "end": 1548, "score": 0.9776926040649414, "start": 1536, "tag": "NAME", "value": "cosmos hagan" }, { "context": "ArrayList();\n users.add(new User(\"ST001\",\"Pricilla Arthur\", \"Female\", \"03/04/2002\", \"Sarah Arthur\", \"024758", "end": 8526, "score": 0.9999008774757385, "start": 8511, "tag": "NAME", "value": "Pricilla Arthur" }, { "context": "T001\",\"Pricilla Arthur\", \"Female\", \"03/04/2002\", \"Sarah Arthur\", \"0247580432\", \"Ebenezer Arthur\", \"0547845213\", ", "end": 8566, "score": 0.9999022483825684, "start": 8554, "tag": "NAME", "value": "Sarah Arthur" }, { "context": "le\", \"03/04/2002\", \"Sarah Arthur\", \"0247580432\", \"Ebenezer Arthur\", \"0547845213\", \"Effia-Kuma\", \"Senior Class\", \"Se", "end": 8599, "score": 0.999899685382843, "start": 8584, "tag": "NAME", "value": "Ebenezer Arthur" }, { "context": ", \"0247580432\", \"Ebenezer Arthur\", \"0547845213\", \"Effia-Kuma\", \"Senior Class\", \"Senior High\", \"Fijai\",\"0240784", "end": 8627, "score": 0.9973078966140747, "start": 8617, "tag": "NAME", "value": "Effia-Kuma" }, { "context": "240784563\"));\n users.add(new User(\"ST002\",\"Joycelyn Ackon\", \"Female\", \"23/10/2002\", \"Hannah Ackon\", \"024758", "end": 8735, "score": 0.999891459941864, "start": 8721, "tag": "NAME", "value": "Joycelyn Ackon" }, { "context": "ST002\",\"Joycelyn Ackon\", \"Female\", \"23/10/2002\", \"Hannah Ackon\", \"0247580432\", \"Ernest Ackon\", \"0547845213\", \"We", "end": 8775, "score": 0.9998916387557983, "start": 8763, "tag": "NAME", "value": "Hannah Ackon" }, { "context": "le\", \"23/10/2002\", \"Hannah Ackon\", \"0247580432\", \"Ernest Ackon\", \"0547845213\", \"WestLine\", \"Senior Class\", \"Seni", "end": 8805, "score": 0.9998909831047058, "start": 8793, "tag": "NAME", "value": "Ernest Ackon" } ]
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 sundaySch.students; import com.jfoenix.controls.JFXButton; import com.jfoenix.controls.JFXComboBox; import com.jfoenix.controls.JFXDatePicker; import com.jfoenix.controls.JFXTextField; import com.jfoenix.controls.JFXTreeTableColumn; import com.jfoenix.controls.JFXTreeTableView; import com.jfoenix.controls.RecursiveTreeItem; import com.jfoenix.controls.datamodels.treetable.RecursiveTreeObject; import javafx.fxml.FXML; import javafx.scene.control.MenuBar; import javafx.scene.control.ProgressIndicator; import java.net.URL; import java.time.LocalDate; import java.util.ResourceBundle; import java.util.function.Predicate; import javafx.animation.KeyFrame; import javafx.animation.KeyValue; import javafx.animation.Timeline; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.Initializable; import javafx.scene.control.Alert; import javafx.scene.control.TreeItem; import javafx.scene.control.TreeTableColumn; import javafx.util.Callback; import javafx.util.Duration; import sundaySch.util.Utility; /** * FXML Controller class * * @author <NAME> */ public class StudentsController implements Initializable { @FXML private MenuBar menuTab; @FXML private JFXTreeTableView<User> treeview; @FXML private JFXComboBox<String> genderCB; @FXML private JFXDatePicker dobTxt; @FXML private JFXTextField mothersTxt, mothersNumTxt, fathersNumTxt, fathersTxt; @FXML private JFXComboBox<String> classCB; @FXML private JFXComboBox<String> schoolCB; @FXML private JFXTextField nameSchTxt, phoneTxt, residenceTxt,searchTxt, nameTxt; @FXML private JFXButton clearButtn, deleteButton, saveButtn; @FXML private ProgressIndicator prog; @FXML private JFXButton editButton; ObservableList<String>gender = FXCollections.observableArrayList("Male", "Female"); ObservableList<String>schlist = FXCollections.observableArrayList("Tertiary", "Secondary", "Primary"); ObservableList<String>classlist = FXCollections.observableArrayList("Senior Class", "Junior Class", "Class 5&6", "Class 3&4","Class 1&2","Beginners Class"); Utility handler; private void treeView() { JFXTreeTableColumn<User, String> sID = new JFXTreeTableColumn<>("Student ID"); sID.setPrefWidth(150); sID.setCellValueFactory(new Callback<TreeTableColumn.CellDataFeatures<User, String>, ObservableValue<String>>() { @Override public ObservableValue<String> call(TreeTableColumn.CellDataFeatures<User, String> param) { return param.getValue().getValue().sID; } }); JFXTreeTableColumn<User, String> tName = new JFXTreeTableColumn<>("Name"); tName.setPrefWidth(150); tName.setCellValueFactory(new Callback<TreeTableColumn.CellDataFeatures<User, String>, ObservableValue<String>>() { @Override public ObservableValue<String> call(TreeTableColumn.CellDataFeatures<User, String> param) { return param.getValue().getValue().Name; } }); JFXTreeTableColumn<User, String> genderCol = new JFXTreeTableColumn<>("Gender"); genderCol.setPrefWidth(150); genderCol.setCellValueFactory(new Callback<TreeTableColumn.CellDataFeatures<User, String>, ObservableValue<String>>() { @Override public ObservableValue<String> call(TreeTableColumn.CellDataFeatures<User, String> param) { return param.getValue().getValue().Gender; } }); JFXTreeTableColumn<User, String> DOB = new JFXTreeTableColumn<>("Date Of Birth"); DOB.setPrefWidth(150); DOB.setCellValueFactory(new Callback<TreeTableColumn.CellDataFeatures<User, String>, ObservableValue<String>>() { @Override public ObservableValue<String> call(TreeTableColumn.CellDataFeatures<User, String> param) { return param.getValue().getValue().DOB; } }); JFXTreeTableColumn<User, String> mothersNamCol = new JFXTreeTableColumn<>("Mother's Name"); mothersNamCol.setPrefWidth(150); mothersNamCol.setCellValueFactory(new Callback<TreeTableColumn.CellDataFeatures<User, String>, ObservableValue<String>>() { @Override public ObservableValue<String> call(TreeTableColumn.CellDataFeatures<User, String> param) { return param.getValue().getValue().MothersName; } }); JFXTreeTableColumn<User, String> mothersNumCol = new JFXTreeTableColumn<>("Mother's Number"); mothersNumCol.setPrefWidth(150); mothersNumCol.setCellValueFactory(new Callback<TreeTableColumn.CellDataFeatures<User, String>, ObservableValue<String>>() { @Override public ObservableValue<String> call(TreeTableColumn.CellDataFeatures<User, String> param) { return param.getValue().getValue().MothersNumb; } }); JFXTreeTableColumn<User, String> fatherNamCol = new JFXTreeTableColumn<>("Father's Name"); fatherNamCol.setPrefWidth(150); fatherNamCol.setCellValueFactory(new Callback<TreeTableColumn.CellDataFeatures<User, String>, ObservableValue<String>>() { @Override public ObservableValue<String> call(TreeTableColumn.CellDataFeatures<User, String> param) { return param.getValue().getValue().FathersName; } }); JFXTreeTableColumn<User, String> fathersNumCol = new JFXTreeTableColumn<>("Father's Number"); fathersNumCol.setPrefWidth(150); fathersNumCol.setCellValueFactory(new Callback<TreeTableColumn.CellDataFeatures<User, String>, ObservableValue<String>>() { @Override public ObservableValue<String> call(TreeTableColumn.CellDataFeatures<User, String> param) { return param.getValue().getValue().FathersNum; } }); JFXTreeTableColumn<User, String> residenceCol = new JFXTreeTableColumn<>("Residence"); residenceCol.setPrefWidth(150); residenceCol.setCellValueFactory(new Callback<TreeTableColumn.CellDataFeatures<User, String>, ObservableValue<String>>() { @Override public ObservableValue<String> call(TreeTableColumn.CellDataFeatures<User, String> param) { return param.getValue().getValue().Residence; } }); JFXTreeTableColumn<User, String> classCol = new JFXTreeTableColumn<>("Class"); classCol.setPrefWidth(150); classCol.setCellValueFactory(new Callback<TreeTableColumn.CellDataFeatures<User, String>, ObservableValue<String>>() { @Override public ObservableValue<String> call(TreeTableColumn.CellDataFeatures<User, String> param) { return param.getValue().getValue().Class; } }); JFXTreeTableColumn<User, String> schoolCol = new JFXTreeTableColumn<>("School"); schoolCol.setPrefWidth(150); schoolCol.setCellValueFactory(new Callback<TreeTableColumn.CellDataFeatures<User, String>, ObservableValue<String>>() { @Override public ObservableValue<String> call(TreeTableColumn.CellDataFeatures<User, String> param) { return param.getValue().getValue().School; } }); JFXTreeTableColumn<User, String> numCol = new JFXTreeTableColumn<>("Phone Number"); numCol.setPrefWidth(150); numCol.setCellValueFactory(new Callback<TreeTableColumn.CellDataFeatures<User, String>, ObservableValue<String>>() { @Override public ObservableValue<String> call(TreeTableColumn.CellDataFeatures<User, String> param) { return param.getValue().getValue().Number; } }); ObservableList<User> users = FXCollections.observableArrayList(); users.add(new User("ST001","<NAME>", "Female", "03/04/2002", "<NAME>", "0247580432", "<NAME>", "0547845213", "Effia-Kuma", "Senior Class", "Senior High", "Fijai","0240784563")); users.add(new User("ST002","<NAME>", "Female", "23/10/2002", "<NAME>", "0247580432", "<NAME>", "0547845213", "WestLine", "Senior Class", "Senior High", "Secko","0240784563")); // final TreeItem<User> root = new RecursiveTreeItem<User>(users, RecursiveTreeObject::getChildren); final TreeItem<User> root = new RecursiveTreeItem<User>(users,RecursiveTreeObject::getChildren); treeview.getColumns().setAll(sID,tName, genderCol, DOB, mothersNamCol, mothersNumCol, fatherNamCol, fathersNumCol, residenceCol, classCol, schoolCol, numCol); treeview.setRoot(root); treeview.setShowRoot(false); searchTxt.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { treeview.setPredicate(new Predicate<TreeItem<User>>() { @Override public boolean test(TreeItem<User> user) { Boolean flag = user.getValue().Name.getValue().contains(newValue)|| user.getValue().Class.getValue().contains(newValue)||user.getValue().Gender.getValue().contains(newValue)|| user.getValue().School.getValue().contains(newValue) || user.getValue().Residence.getValue().contains(newValue)|| user.getValue().DOB.getValue().contains(newValue) ; return flag; } }); } }); } @FXML private void editButton(ActionEvent event) { } private void combobox(){ genderCB.setItems(gender); schoolCB.setItems(schlist); classCB.setItems(classlist); } class User extends RecursiveTreeObject<User> { StringProperty sID; StringProperty Name; StringProperty Gender; StringProperty DOB; StringProperty MothersName; StringProperty MothersNumb ; StringProperty FathersName; StringProperty FathersNum; StringProperty Residence; StringProperty Class; StringProperty School; StringProperty NameSch; StringProperty Number; public User(String sID,String Name, String Gender, String DOB, String MothersName, String MothersNumb,String FathersName, String FathersNum, String Residence, String Class, String School, String NameSch, String Number) { this.sID = new SimpleStringProperty(sID); this.Name = new SimpleStringProperty(Name); this.Gender = new SimpleStringProperty(Gender); this.DOB = new SimpleStringProperty(DOB); this.MothersName = new SimpleStringProperty(MothersName); this.MothersNumb = new SimpleStringProperty(MothersNumb ); this.FathersName = new SimpleStringProperty(FathersName); this.FathersNum = new SimpleStringProperty(FathersNum); this.Residence = new SimpleStringProperty(Residence); this.Class = new SimpleStringProperty(Class); this.School = new SimpleStringProperty(School); this.NameSch = new SimpleStringProperty(NameSch); this.Number = new SimpleStringProperty(Number); } } @FXML private void deleteButton(ActionEvent event) { } @FXML void clearButton(ActionEvent event) { } @FXML void saveButton(ActionEvent event) { add(); } void add(){ Timeline timeline = new Timeline(); KeyValue key1 = new KeyValue(prog.progressProperty(), 0.01); KeyFrame frame1 = new KeyFrame(Duration.millis(550), key1); KeyValue key2 = new KeyValue(prog.progressProperty(), 1); KeyFrame frame2 = new KeyFrame(Duration.seconds(1), key2); prog.setVisible(true); timeline.getKeyFrames().addAll(frame1,frame2); timeline.play(); String tID ="ST001"; String name = nameTxt.getText(); String genda = genderCB.getValue(); LocalDate dob = dobTxt.getValue(); String stat = schoolCB.getValue(); String claz = classCB.getValue(); String resid = residenceTxt.getText(); String sch = nameSchTxt.getText(); String phone = phoneTxt.getText(); String mother = mothersTxt.getText(); String motherNum = mothersNumTxt.getText(); String father = fathersTxt.getText(); String fatherNum = fathersNumTxt.getText(); Boolean flag = (name.isEmpty() || genda.isEmpty() || genda.isEmpty() || resid.isEmpty() || mother.isEmpty()|| motherNum.isEmpty()|| father.isEmpty()|| fatherNum.isEmpty() || phone.isEmpty()||stat.isEmpty()|| claz.isEmpty()||sch.isEmpty()); if(flag){ Alert alert = new Alert(Alert.AlertType.ERROR); alert.setHeaderText(null); alert.setContentText("Please Enter in all fields"); alert.showAndWait(); return; } String st= "INSERT INTO student VALUES ("+ "'" +tID+"'," + "'" +name+"'," + "'" +genda+ "'," + "'" +dob+ "'," + "'" +mother+ "'," + "'" +motherNum+ "'," + "'" +father+ "'," + "'" +fatherNum+ "'," + "'" +resid+ "'," + "'" +stat+ "'," + "'" +sch+ "'," + "'" +claz+ "'," + "'" +phone+ "'" + ")"; System.out.println(st); if(handler.execAction(st)){ timeline.setOnFinished(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setHeaderText(null); alert.setContentText("Saved"); alert.show(); } }); }else{ timeline.setOnFinished(e->{ Alert alert = new Alert(Alert.AlertType.ERROR); alert.setHeaderText(null); alert.setContentText("Failed"); alert.show(); prog.setVisible(false); }); } } @Override public void initialize(URL url, ResourceBundle rb) { // TODO LocalDate da = LocalDate.now(); dobTxt.setValue(da); combobox(); prog.setVisible(false); treeView(); } void progress(){ prog.setVisible(true); Timeline timeline = new Timeline(); KeyValue key1 = new KeyValue(prog.progressProperty(), 0.01); KeyFrame frame1 = new KeyFrame(Duration.millis(550), key1); KeyValue key2 = new KeyValue(prog.progressProperty(), 1); KeyFrame frame2 = new KeyFrame(Duration.seconds(1), key2); timeline.getKeyFrames().addAll(frame1,frame2); timeline.play(); if(nameTxt.getText().equals("Cosmos")){ timeline.setOnFinished(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setHeaderText(null); alert.setContentText("Saved"); alert.show(); } }); }else{ timeline.setOnFinished(e->{ Alert alert = new Alert(Alert.AlertType.ERROR); alert.setHeaderText(null); alert.setContentText("Failed"); alert.show(); prog.setVisible(false); }); } } }
16,641
0.622911
0.613384
426
38.180752
40.153202
367
false
false
0
0
0
0
0
0
0.884977
false
false
4
50c5acdd2a3ddffa652bfc802693a9d9617161ec
28,681,791,668,097
5109211de8b7e7713b34750ccf915e79e3e7662c
/app/src/main/java/com/maskedgeek/androidinterviewprep/recyclerview/RecyclerViewActivity.java
db4efa210fafd679864331bd0fbbfd270161c597
[]
no_license
sumitkrnitjsr/AndroidInterviewPrep
https://github.com/sumitkrnitjsr/AndroidInterviewPrep
21495e0bb68c51c249bbbd6df1f06b2659691f1e
e7a5e87d5e1e427c2aedd1ce807029a3d2964d7d
refs/heads/main
2023-05-12T15:23:16.368000
2021-05-30T21:47:04
2021-05-30T21:47:04
355,686,272
0
0
null
false
2021-05-30T21:47:05
2021-04-07T21:26:31
2021-05-27T16:33:03
2021-05-30T21:47:05
6,196
0
0
0
Java
false
false
package com.maskedgeek.androidinterviewprep.recyclerview; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.LinearLayout; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.maskedgeek.androidinterviewprep.MainActivity; import com.maskedgeek.androidinterviewprep.R; import com.maskedgeek.androidinterviewprep.customview.CustomViewActivity; import com.maskedgeek.androidinterviewprep.fragment.MainFragmentActivity; import com.maskedgeek.androidinterviewprep.fragment.backstack.FragmentBackStackActivity; import com.maskedgeek.androidinterviewprep.pageradapters.ActivityPagerAdapter; import com.maskedgeek.androidinterviewprep.touchevent.TouchEventActivity; import java.util.ArrayList; public class RecyclerViewActivity extends AppCompatActivity implements AdapterActivityCommunicationInterface{ private String TAG = RecyclerViewActivity.class.getSimpleName(); private ArrayList<String> list = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState){ // Same as constructor // inject dependencies super.onCreate(savedInstanceState); Log.d(TAG, " onCreate "); // call finish() here to skip onPause() and onStop() and directly call onDestroy() setContentView(R.layout.activity_recyclerview); RecyclerView recyclerView = findViewById(R.id.recyclerview); for(int i = 0;i < 100;i++){ String var = Integer.toString(i) + Integer.toString(i + 1) + Integer.toString(i + 2); list.add(var); } recyclerView.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false)); recyclerView.setAdapter(new RecyclerViewAdapter(list, this)); } @Override protected void onStart(){ // activity becomes visible // Good place to check Permissions, LoginStatus, Network UI Update data super.onStart(); Log.d(TAG, " onStart "); } @Override public void onRestoreInstanceState(Bundle savedInstanceState) { // called only when there is a saved instance that is previously saved by using onSaveInstanceState() Log.d(TAG, " onRestoreInstanceState "); } @Override protected void onResume(){ // activity starts being interactive super.onResume(); Log.d(TAG, " onResume "); } @Override public void onSaveInstanceState(Bundle state){ // method is used to store data before pausing the activity. Log.d(TAG, " onSavedInstanceState "); super.onSaveInstanceState(state); } @Override protected void onPause(){ // activity is partially visible and stops interaction super.onPause(); Log.d(TAG, " onPause "); // Next activity starts their onCreate here, the system is not in a hurry to stop this activity } @Override protected void onStop() { // Activity not visible super.onStop(); Log.d(TAG, " onStop "); } @Override protected void onRestart(){ super.onRestart(); Log.d(TAG, " onRestart "); } @Override protected void onDestroy(){ super.onDestroy(); Log.d(TAG, " onDestroy "); } @Override public void onBackPressed(){ Log.d(TAG, " onBackPressed "); super.onBackPressed(); } @Override public void onClick(int position) { Toast.makeText(this, list.get(position) + " clicked", Toast.LENGTH_SHORT).show(); } }
UTF-8
Java
3,706
java
RecyclerViewActivity.java
Java
[]
null
[]
package com.maskedgeek.androidinterviewprep.recyclerview; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.LinearLayout; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.maskedgeek.androidinterviewprep.MainActivity; import com.maskedgeek.androidinterviewprep.R; import com.maskedgeek.androidinterviewprep.customview.CustomViewActivity; import com.maskedgeek.androidinterviewprep.fragment.MainFragmentActivity; import com.maskedgeek.androidinterviewprep.fragment.backstack.FragmentBackStackActivity; import com.maskedgeek.androidinterviewprep.pageradapters.ActivityPagerAdapter; import com.maskedgeek.androidinterviewprep.touchevent.TouchEventActivity; import java.util.ArrayList; public class RecyclerViewActivity extends AppCompatActivity implements AdapterActivityCommunicationInterface{ private String TAG = RecyclerViewActivity.class.getSimpleName(); private ArrayList<String> list = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState){ // Same as constructor // inject dependencies super.onCreate(savedInstanceState); Log.d(TAG, " onCreate "); // call finish() here to skip onPause() and onStop() and directly call onDestroy() setContentView(R.layout.activity_recyclerview); RecyclerView recyclerView = findViewById(R.id.recyclerview); for(int i = 0;i < 100;i++){ String var = Integer.toString(i) + Integer.toString(i + 1) + Integer.toString(i + 2); list.add(var); } recyclerView.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false)); recyclerView.setAdapter(new RecyclerViewAdapter(list, this)); } @Override protected void onStart(){ // activity becomes visible // Good place to check Permissions, LoginStatus, Network UI Update data super.onStart(); Log.d(TAG, " onStart "); } @Override public void onRestoreInstanceState(Bundle savedInstanceState) { // called only when there is a saved instance that is previously saved by using onSaveInstanceState() Log.d(TAG, " onRestoreInstanceState "); } @Override protected void onResume(){ // activity starts being interactive super.onResume(); Log.d(TAG, " onResume "); } @Override public void onSaveInstanceState(Bundle state){ // method is used to store data before pausing the activity. Log.d(TAG, " onSavedInstanceState "); super.onSaveInstanceState(state); } @Override protected void onPause(){ // activity is partially visible and stops interaction super.onPause(); Log.d(TAG, " onPause "); // Next activity starts their onCreate here, the system is not in a hurry to stop this activity } @Override protected void onStop() { // Activity not visible super.onStop(); Log.d(TAG, " onStop "); } @Override protected void onRestart(){ super.onRestart(); Log.d(TAG, " onRestart "); } @Override protected void onDestroy(){ super.onDestroy(); Log.d(TAG, " onDestroy "); } @Override public void onBackPressed(){ Log.d(TAG, " onBackPressed "); super.onBackPressed(); } @Override public void onClick(int position) { Toast.makeText(this, list.get(position) + " clicked", Toast.LENGTH_SHORT).show(); } }
3,706
0.692661
0.691042
113
31.796461
28.390812
110
false
false
0
0
0
0
0
0
0.584071
false
false
4
4907c405496027bdad1a05fa01c7aaa9b83b5264
10,136,122,838,310
00f0d4bcdbaa7c390ffe9146907ee17202b32eb7
/src/leetcode/N151_200/N165_CompareVersionNumbers.java
4a2a53f820eb40bce8d32659da6b9073fdcd5b6e
[]
no_license
wsquan171/leetcode
https://github.com/wsquan171/leetcode
f7fd5f9cb7cfe266b85c592c6310c2a078960d7d
f0575f3ae2974c897a6408c3b8457299a5cb8f2a
refs/heads/master
2018-10-16T15:23:36.102000
2018-09-23T04:51:05
2018-09-23T04:51:05
133,767,282
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Compare two version numbers version1 and version2. * If version1 > version2 return 1; * if version1 < version2 return -1; * otherwise return 0. * * You may assume that the version strings are non-empty * and contain only digits and the . character. * * The . character does not represent a decimal point * and is used to separate number sequences. * * For instance, 2.5 is not "two and a half" or "half way to version three", * it is the fifth second-level revision of the second first-level revision. * * Example 1: * Input: version1 = "0.1", version2 = "1.1" * Output: -1 * * Example 2: * Input: version1 = "1.0.1", version2 = "1" * Output: 1 * * Example 3: * Input: version1 = "7.5.2.4", version2 = "7.5.3" * Output: -1 */ package leetcode.N151_200; public class N165_CompareVersionNumbers { public int compareVersion(String version1, String version2) { if(version1 == null && version2 == null) return 0; if(version1 == null) return -1; if(version2 == null) return 1; int len1 = version1.length(); int len2 = version2.length(); int i = 0, j = 0; int start1 = 0, start2 = 0; while(i < len1 || j < len2) { while(i < len1 && version1.charAt(i) != '.') i++; while(j < len2 && version2.charAt(j) != '.') j++; long ver1 = start1 > len1 ? 0 : Long.parseLong(version1.substring(start1, i)); long ver2 = start2 > len2 ? 0 : Long.parseLong(version2.substring(start2, j)); if(ver1 < ver2) return -1; else if(ver2 < ver1) return 1; start1 = ++i; start2 = ++j; } return 0; } }
UTF-8
Java
1,783
java
N165_CompareVersionNumbers.java
Java
[]
null
[]
/** * Compare two version numbers version1 and version2. * If version1 > version2 return 1; * if version1 < version2 return -1; * otherwise return 0. * * You may assume that the version strings are non-empty * and contain only digits and the . character. * * The . character does not represent a decimal point * and is used to separate number sequences. * * For instance, 2.5 is not "two and a half" or "half way to version three", * it is the fifth second-level revision of the second first-level revision. * * Example 1: * Input: version1 = "0.1", version2 = "1.1" * Output: -1 * * Example 2: * Input: version1 = "1.0.1", version2 = "1" * Output: 1 * * Example 3: * Input: version1 = "7.5.2.4", version2 = "7.5.3" * Output: -1 */ package leetcode.N151_200; public class N165_CompareVersionNumbers { public int compareVersion(String version1, String version2) { if(version1 == null && version2 == null) return 0; if(version1 == null) return -1; if(version2 == null) return 1; int len1 = version1.length(); int len2 = version2.length(); int i = 0, j = 0; int start1 = 0, start2 = 0; while(i < len1 || j < len2) { while(i < len1 && version1.charAt(i) != '.') i++; while(j < len2 && version2.charAt(j) != '.') j++; long ver1 = start1 > len1 ? 0 : Long.parseLong(version1.substring(start1, i)); long ver2 = start2 > len2 ? 0 : Long.parseLong(version2.substring(start2, j)); if(ver1 < ver2) return -1; else if(ver2 < ver1) return 1; start1 = ++i; start2 = ++j; } return 0; } }
1,783
0.553001
0.500841
64
26.859375
22.23164
90
false
false
0
0
0
0
0
0
0.796875
false
false
4
0b59334d3737b469ff5cc2967aeee9357f4223cc
6,330,781,822,277
25d393ca3d2cc8b86dccaa73b39a499db9c5baf1
/components/apimgt/org.wso2.carbon.apimgt.rest.api.admin.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/admin/v1/AlertSubscriptionsApiService.java
ae65b0f7b28df9004a1f8f0b1921fd64f4d9d31a
[ "Apache-2.0" ]
permissive
sanjeewa-malalgoda/carbon-apimgt
https://github.com/sanjeewa-malalgoda/carbon-apimgt
9b4a43c9382467ff62ad2b1f897d73d97d6173fe
ac7d821c23f61f5af748673f248056d9d5108b97
refs/heads/master
2022-11-30T04:07:15.048000
2022-11-22T03:26:30
2022-11-22T03:26:30
32,058,716
1
1
Apache-2.0
true
2022-11-22T04:38:54
2015-03-12T05:24:41
2022-11-15T03:16:41
2022-11-22T04:38:48
188,832
1
1
0
JavaScript
false
false
package org.wso2.carbon.apimgt.rest.api.admin.v1; import org.apache.cxf.jaxrs.ext.MessageContext; import org.wso2.carbon.apimgt.api.APIManagementException; import org.wso2.carbon.apimgt.rest.api.admin.v1.dto.AlertsSubscriptionDTO; import org.wso2.carbon.apimgt.rest.api.admin.v1.dto.BotDetectionAlertSubscriptionDTO; import javax.ws.rs.core.Response; public interface AlertSubscriptionsApiService { public Response getBotDetectionAlertSubscriptions(MessageContext messageContext) throws APIManagementException; public Response getSubscribedAlertTypes(MessageContext messageContext) throws APIManagementException; public Response subscribeForBotDetectionAlerts(BotDetectionAlertSubscriptionDTO botDetectionAlertSubscriptionDTO, MessageContext messageContext) throws APIManagementException; public Response subscribeToAlerts(AlertsSubscriptionDTO alertsSubscriptionDTO, MessageContext messageContext) throws APIManagementException; public Response unsubscribeAllAlerts(MessageContext messageContext) throws APIManagementException; public Response unsubscribeFromBotDetectionAlerts(String uuid, MessageContext messageContext) throws APIManagementException; }
UTF-8
Java
1,204
java
AlertSubscriptionsApiService.java
Java
[]
null
[]
package org.wso2.carbon.apimgt.rest.api.admin.v1; import org.apache.cxf.jaxrs.ext.MessageContext; import org.wso2.carbon.apimgt.api.APIManagementException; import org.wso2.carbon.apimgt.rest.api.admin.v1.dto.AlertsSubscriptionDTO; import org.wso2.carbon.apimgt.rest.api.admin.v1.dto.BotDetectionAlertSubscriptionDTO; import javax.ws.rs.core.Response; public interface AlertSubscriptionsApiService { public Response getBotDetectionAlertSubscriptions(MessageContext messageContext) throws APIManagementException; public Response getSubscribedAlertTypes(MessageContext messageContext) throws APIManagementException; public Response subscribeForBotDetectionAlerts(BotDetectionAlertSubscriptionDTO botDetectionAlertSubscriptionDTO, MessageContext messageContext) throws APIManagementException; public Response subscribeToAlerts(AlertsSubscriptionDTO alertsSubscriptionDTO, MessageContext messageContext) throws APIManagementException; public Response unsubscribeAllAlerts(MessageContext messageContext) throws APIManagementException; public Response unsubscribeFromBotDetectionAlerts(String uuid, MessageContext messageContext) throws APIManagementException; }
1,204
0.854651
0.848837
26
45.307693
54.567368
181
false
false
0
0
0
0
0
0
0.576923
false
false
4
de55207daa5b5aa875f784f2edfdfa3b8186eab8
26,508,538,160,617
c77fdaae357eb8a131a114c21c6d5ecf5c04d49f
/jiabian-dao/src/main/java/com/jiabian/dao/basic/SysUserMapper.java
12c7f0848c14b75bcfc8bbc2fec32913b34f2cfc
[]
no_license
RenYongliang/jiabian-parent
https://github.com/RenYongliang/jiabian-parent
9b6af4e2d84d597f733cd7c0f99af5f80a608411
1df2425633446ffd4ae16670e69d46d119ff237d
refs/heads/master
2020-03-25T15:06:50.398000
2018-08-13T16:46:07
2018-08-13T16:46:16
143,867,728
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * SysUserMapper.java * Copyright(C) 20xx-2015 xxxxxx��˾ * All rights reserved. * ----------------------------------------------- * 2016-12-21 Created */ package com.jiabian.dao.basic; import java.util.List; import org.apache.ibatis.annotations.Param; import com.jiabian.base.PagesModel; import com.jiabian.beans.basic.SysUser; import com.jiabian.beans.basic.SysUserQueryHelper; import com.jiabian.sys.sysuser.request.SysUserReq; import com.jiabian.sys.sysuser.response.SysUserResp; public interface SysUserMapper { int countByExample(SysUserQueryHelper example); int deleteByExample(SysUserQueryHelper example); int deleteByPrimaryKey(Long suserId); int insert(SysUser record); int insertSelective(SysUser record); List<SysUser> selectByExample(SysUserQueryHelper example); SysUser selectByPrimaryKey(Long suserId); int updateByExampleSelective(@Param("record") SysUser record, @Param("example") SysUserQueryHelper example); int updateByExample(@Param("record") SysUser record, @Param("example") SysUserQueryHelper example); int updateByPrimaryKeySelective(SysUser record); int updateByPrimaryKey(SysUser record); /** * 分页查询 * @param pagesModel * @return */ List<SysUserResp> selectforPageByParam(PagesModel<SysUserReq,SysUserResp> pagesModel); Integer countforPageByParam(PagesModel<SysUserReq,SysUserResp> pagesModel); /** * 批量修改删除状态 * @param isDel * @param ids * @param sysUserReq * @return */ int updateIsDelForeach(@Param("isDel") Integer isDel,@Param("ids") String[] ids,@Param("sysUserReq") SysUserReq sysUserReq); /** * 根据id查询系统用户信息 * @param suserId * @return */ SysUserResp selectUserandRole(Long suserId); /** * * (根据地区查询相应区域的区域经理) * com.jiabian.dao.basic * 方法名:selectSysUserByDistrict * 创建人:彭振锋 * 时间:2016年12月22日-下午4:30:45 * @param sysUserReq * @return List<SysUserResp> * @exception * @since 1.0.0 */ List<SysUserResp> selectSysUserByDistrict(SysUserReq sysUserReq); /** * * (查询客服人员列表) * com.jiabian.dao.basic * 方法名:selectSereviceList * 创建人:彭振锋 * 时间:2016年12月28日-下午1:36:00 * @return List<SysUserResp> * @exception * @since 1.0.0 */ List<SysUserResp> selectSereviceList(SysUserReq sysUserReq); /** * * 分页查询推广人员业绩 * com.jiabian.dao.basic * 方法名:selectGeneralize * 创建人:李文凯 * 时间:2016年12月29日-下午7:22:59 * @param pagesModel * @return List<SysUserResp> * @exception * @since 1.0.0 */ List<SysUserResp> selectGeneralize(PagesModel<SysUserReq, SysUserResp> pagesModel); SysUserResp selectPerformance(Long suserId); Integer countGeneralize(PagesModel<SysUserReq, SysUserResp> pagesModel); /** * * 查询推广员信息 * com.jiabian.dao.basic * 方法名:selectSysUserInfoByInvitationCode * 创建人:李文凯 * 时间:2016年12月30日-下午6:02:58 * @param invitationCode * @return SysUserResp * @exception * @since 1.0.0 */ SysUserResp selectSysUserInfoByInvitationCode(String invitationCode); }
UTF-8
Java
3,581
java
SysUserMapper.java
Java
[ { "context": " \r\n * 方法名:selectSysUserByDistrict\r\n * 创建人:彭振锋 \r\n * 时间:2016年12月22日-下午4:30:45 \r\n * @param", "end": 1983, "score": 0.9997866749763489, "start": 1980, "tag": "NAME", "value": "彭振锋" }, { "context": "basic \r\n * 方法名:selectSereviceList\r\n * 创建人:彭振锋 \r\n * 时间:2016年12月28日-下午1:36:00 \r\n * @retur", "end": 2321, "score": 0.9998160004615784, "start": 2318, "tag": "NAME", "value": "彭振锋" }, { "context": "o.basic \r\n * 方法名:selectGeneralize\r\n * 创建人:李文凯\r\n * 时间:2016年12月29日-下午7:22:59 \r\n * @param ", "end": 2622, "score": 0.999815046787262, "start": 2619, "tag": "NAME", "value": "李文凯" }, { "context": " * 方法名:selectSysUserInfoByInvitationCode\r\n\t * 创建人:李文凯\r\n\t * 时间:2016年12月30日-下午6:02:58 \r\n\t * @param invita", "end": 3098, "score": 0.9998130202293396, "start": 3095, "tag": "NAME", "value": "李文凯" } ]
null
[]
/* * SysUserMapper.java * Copyright(C) 20xx-2015 xxxxxx��˾ * All rights reserved. * ----------------------------------------------- * 2016-12-21 Created */ package com.jiabian.dao.basic; import java.util.List; import org.apache.ibatis.annotations.Param; import com.jiabian.base.PagesModel; import com.jiabian.beans.basic.SysUser; import com.jiabian.beans.basic.SysUserQueryHelper; import com.jiabian.sys.sysuser.request.SysUserReq; import com.jiabian.sys.sysuser.response.SysUserResp; public interface SysUserMapper { int countByExample(SysUserQueryHelper example); int deleteByExample(SysUserQueryHelper example); int deleteByPrimaryKey(Long suserId); int insert(SysUser record); int insertSelective(SysUser record); List<SysUser> selectByExample(SysUserQueryHelper example); SysUser selectByPrimaryKey(Long suserId); int updateByExampleSelective(@Param("record") SysUser record, @Param("example") SysUserQueryHelper example); int updateByExample(@Param("record") SysUser record, @Param("example") SysUserQueryHelper example); int updateByPrimaryKeySelective(SysUser record); int updateByPrimaryKey(SysUser record); /** * 分页查询 * @param pagesModel * @return */ List<SysUserResp> selectforPageByParam(PagesModel<SysUserReq,SysUserResp> pagesModel); Integer countforPageByParam(PagesModel<SysUserReq,SysUserResp> pagesModel); /** * 批量修改删除状态 * @param isDel * @param ids * @param sysUserReq * @return */ int updateIsDelForeach(@Param("isDel") Integer isDel,@Param("ids") String[] ids,@Param("sysUserReq") SysUserReq sysUserReq); /** * 根据id查询系统用户信息 * @param suserId * @return */ SysUserResp selectUserandRole(Long suserId); /** * * (根据地区查询相应区域的区域经理) * com.jiabian.dao.basic * 方法名:selectSysUserByDistrict * 创建人:彭振锋 * 时间:2016年12月22日-下午4:30:45 * @param sysUserReq * @return List<SysUserResp> * @exception * @since 1.0.0 */ List<SysUserResp> selectSysUserByDistrict(SysUserReq sysUserReq); /** * * (查询客服人员列表) * com.jiabian.dao.basic * 方法名:selectSereviceList * 创建人:彭振锋 * 时间:2016年12月28日-下午1:36:00 * @return List<SysUserResp> * @exception * @since 1.0.0 */ List<SysUserResp> selectSereviceList(SysUserReq sysUserReq); /** * * 分页查询推广人员业绩 * com.jiabian.dao.basic * 方法名:selectGeneralize * 创建人:李文凯 * 时间:2016年12月29日-下午7:22:59 * @param pagesModel * @return List<SysUserResp> * @exception * @since 1.0.0 */ List<SysUserResp> selectGeneralize(PagesModel<SysUserReq, SysUserResp> pagesModel); SysUserResp selectPerformance(Long suserId); Integer countGeneralize(PagesModel<SysUserReq, SysUserResp> pagesModel); /** * * 查询推广员信息 * com.jiabian.dao.basic * 方法名:selectSysUserInfoByInvitationCode * 创建人:李文凯 * 时间:2016年12月30日-下午6:02:58 * @param invitationCode * @return SysUserResp * @exception * @since 1.0.0 */ SysUserResp selectSysUserInfoByInvitationCode(String invitationCode); }
3,581
0.642424
0.618788
128
23.796875
24.641922
128
false
false
0
0
0
0
0
0
0.429688
false
false
4
f5fc951bcb76fa2cd2fd7c1770c5e7ad10d8f340
29,154,238,053,499
cf7477f25a82454b80fc5e9d7c4b88f8ef76fa0f
/OIS-Ue1-SchausbergerL-Vers-1/src/at/fhooe/mc/vis/DrawingTest.java
8664dc3ec9a53d8d3feb171d273c992e7f3420bf
[]
no_license
lauli/location_based_systems
https://github.com/lauli/location_based_systems
f0751e73c31bb940bcae5d4aa1751bd537f0ed63
389462d8d959137200e334f7f33b0b8f9fda9d9b
refs/heads/master
2021-07-06T01:14:23.288000
2017-09-25T23:09:33
2017-09-25T23:09:33
104,810,894
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package at.fhooe.mc.vis; import javax.swing.border.Border; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; /** * Created by laureenschausberger on 05.04.17. */ public class DrawingTest extends WindowAdapter implements ActionListener { Frame mFrame = new Frame(); DrawingPanel mDrawingPanel = new DrawingPanel(); public static void main(String[] _args) { DrawingTest test = new DrawingTest(); } public DrawingTest() { mFrame.setSize(600, 400); mFrame.addWindowListener(this); Panel panel = new Panel(); panel.setBackground(Color.darkGray); Panel buttonPanel = new Panel(); buttonPanel.setBackground(Color.darkGray); Button button = new Button(); button.setLabel("Draw"); button.addActionListener(this); buttonPanel.add(button, BorderLayout.CENTER); BorderLayout borderLayout = new BorderLayout(); panel.setLayout(borderLayout); mDrawingPanel.setBackground(Color.darkGray); mDrawingPanel.setBounds(0,0,600,350); panel.add(mDrawingPanel, BorderLayout.CENTER); panel.add(buttonPanel, BorderLayout.SOUTH); mFrame.add(panel); mFrame.setVisible(true); } @Override public void actionPerformed(ActionEvent _e) { //mDrawingPanel.getGraphics().drawRect(50,50,50,50); int xPoly[] = {50, 100, 100, 75, 50, 50}; int yPoly[] = {50, 50, 100, 125, 100, 50}; Polygon poly = new Polygon(xPoly, yPoly, xPoly.length); //mDrawingPanel.drawHouse(poly); } @Override public void windowClosing(WindowEvent _e) { super.windowClosing(_e); System.exit(0); } }
UTF-8
Java
1,820
java
DrawingTest.java
Java
[ { "context": "ort java.awt.event.WindowEvent;\n\n/**\n * Created by laureenschausberger on 05.04.17.\n */\npublic class DrawingTest extends", "end": 262, "score": 0.9926307797431946, "start": 243, "tag": "USERNAME", "value": "laureenschausberger" } ]
null
[]
package at.fhooe.mc.vis; import javax.swing.border.Border; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; /** * Created by laureenschausberger on 05.04.17. */ public class DrawingTest extends WindowAdapter implements ActionListener { Frame mFrame = new Frame(); DrawingPanel mDrawingPanel = new DrawingPanel(); public static void main(String[] _args) { DrawingTest test = new DrawingTest(); } public DrawingTest() { mFrame.setSize(600, 400); mFrame.addWindowListener(this); Panel panel = new Panel(); panel.setBackground(Color.darkGray); Panel buttonPanel = new Panel(); buttonPanel.setBackground(Color.darkGray); Button button = new Button(); button.setLabel("Draw"); button.addActionListener(this); buttonPanel.add(button, BorderLayout.CENTER); BorderLayout borderLayout = new BorderLayout(); panel.setLayout(borderLayout); mDrawingPanel.setBackground(Color.darkGray); mDrawingPanel.setBounds(0,0,600,350); panel.add(mDrawingPanel, BorderLayout.CENTER); panel.add(buttonPanel, BorderLayout.SOUTH); mFrame.add(panel); mFrame.setVisible(true); } @Override public void actionPerformed(ActionEvent _e) { //mDrawingPanel.getGraphics().drawRect(50,50,50,50); int xPoly[] = {50, 100, 100, 75, 50, 50}; int yPoly[] = {50, 50, 100, 125, 100, 50}; Polygon poly = new Polygon(xPoly, yPoly, xPoly.length); //mDrawingPanel.drawHouse(poly); } @Override public void windowClosing(WindowEvent _e) { super.windowClosing(_e); System.exit(0); } }
1,820
0.654945
0.623077
65
27
21.192886
74
false
false
0
0
0
0
0
0
0.876923
false
false
4
b741ce37fb0ee2dfd28acdaa11eb4f2b5daae111
6,734,508,750,399
2f4c2a642847d402d93f7ee747e7284681cf98a4
/bankproxy/common/model/src/main/java/com/che001/bankproxy/v1/common/model/util/conversion/MoneyConverter.java
bdfc9f39d7782bd6ce33f05eed63a648270d4b1e
[]
no_license
zhulishuang/DylanDemo
https://github.com/zhulishuang/DylanDemo
0dc949ee6e5731a2216c4a446f85490ab8f671ff
e7a95f1ffea0f58ec1a529d76d38ce30a2abfd96
refs/heads/master
2016-08-08T18:08:29.777000
2016-03-22T03:21:45
2016-03-22T03:21:45
54,436,595
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.che001.bankproxy.v1.common.model.util.conversion; import com.che001.bankproxy.v1.common.model.Money; /** * @author clark.gao */ public class MoneyConverter { /** * Convert from a two decimal currency value to internal representation * * @param value * external string value * @return internal representation */ public static Money fromExternal(String value) { return NumberConverter.fromExternal(value); } /** * Convert from internal currency to two decimal string value * * @param value * internal long value * @return the external representation */ public static String toExternal(Money value) { return NumberConverter.toExternal(value); } }
UTF-8
Java
787
java
MoneyConverter.java
Java
[ { "context": ".bankproxy.v1.common.model.Money;\n\n\n/**\n * @author clark.gao\n */\npublic class MoneyConverter {\n\n /**\n *", "end": 140, "score": 0.9917569160461426, "start": 131, "tag": "USERNAME", "value": "clark.gao" } ]
null
[]
package com.che001.bankproxy.v1.common.model.util.conversion; import com.che001.bankproxy.v1.common.model.Money; /** * @author clark.gao */ public class MoneyConverter { /** * Convert from a two decimal currency value to internal representation * * @param value * external string value * @return internal representation */ public static Money fromExternal(String value) { return NumberConverter.fromExternal(value); } /** * Convert from internal currency to two decimal string value * * @param value * internal long value * @return the external representation */ public static String toExternal(Money value) { return NumberConverter.toExternal(value); } }
787
0.64676
0.636595
32
23.59375
22.972618
75
false
false
0
0
0
0
0
0
0.125
false
false
4
e524cd37f32de0518e6d7d62ccb1bab811681d06
22,505,628,666,854
123ab2d8cc67cb0c63864360ee82810adfd3bcb6
/MinMaxTestCajaNegra.java
1123dc6628e483b32a081dfa424666bfb81f723b
[]
no_license
marinammp/Tarea-de-Prueba-de-Software
https://github.com/marinammp/Tarea-de-Prueba-de-Software
2a3535686af30d46c8e5c793e3f40cfa2a8cd73b
c468e538f896cc2d29895ff13f3f112bf63dbf07
refs/heads/master
2021-01-24T07:42:09.814000
2017-06-05T21:52:04
2017-06-05T21:52:04
93,351,974
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertNull; import org.junit.Test; public class MinMaxTestCajaNegra { @Test public void testArrayDeDatosVacio() { int[] datos={}; assertNull(MinMax.minMax(datos)); } @Test public void tesConDatos() { int[] datos= {1,2,3}; int[] resultados={1,3}; assertArrayEquals(resultados,MinMax.minMax(datos)); } @Test public void tesConDatosNegativos() { int[] datos= {-1,-6,3}; int[] resultados={-6,3}; assertArrayEquals(resultados,MinMax.minMax(datos)); } }
UTF-8
Java
570
java
MinMaxTestCajaNegra.java
Java
[]
null
[]
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertNull; import org.junit.Test; public class MinMaxTestCajaNegra { @Test public void testArrayDeDatosVacio() { int[] datos={}; assertNull(MinMax.minMax(datos)); } @Test public void tesConDatos() { int[] datos= {1,2,3}; int[] resultados={1,3}; assertArrayEquals(resultados,MinMax.minMax(datos)); } @Test public void tesConDatosNegativos() { int[] datos= {-1,-6,3}; int[] resultados={-6,3}; assertArrayEquals(resultados,MinMax.minMax(datos)); } }
570
0.694737
0.677193
30
18
17.706873
53
false
false
0
0
0
0
0
0
1.733333
false
false
4
d173aca39d4706cdf6c37fa405089ca019d1b8e7
22,505,628,666,463
9b4110097a5cd3c6ff942ec451b6003833741458
/app_mvvm_livedata/src/main/java/com/example/app_mvvm_livedata/http/WXSSlSocketFactory.java
e8b7589e658bf8d507767d4ef20686289444cc3f
[]
no_license
wang-xiong/WxApp
https://github.com/wang-xiong/WxApp
e3dbb71dfe219b62ba753e8a6b9423ca20a2124c
3ed301ee7c2dd1e2485eb4d95f68f7dce59971c4
refs/heads/master
2020-03-25T04:38:40.474000
2019-05-30T02:52:49
2019-05-30T02:52:49
143,405,847
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.app_mvvm_livedata.http; import android.content.Context; import java.io.InputStream; import java.security.KeyStore; import java.security.SecureRandom; import java.security.cert.Certificate; import java.security.cert.CertificateFactory; import java.util.Arrays; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; public class WXSSlSocketFactory { private SSLSocketFactory mSslSocketFactory; private X509TrustManager mTrustManager; private Context mContext; private boolean mCaptureAble; //能否抓包,true为可以抓包;false为不能抓包 public WXSSlSocketFactory(Context context) { this(context, false); } public WXSSlSocketFactory(Context context, boolean captureAble) { this.mContext = context.getApplicationContext(); this.mCaptureAble = captureAble; initData(); } private void initData() { if (mCaptureAble) { initCustomSSLSocketFactory(); } else { initDefaultSSLSocketFactory(); } } private void initCustomSSLSocketFactory() { InputStream rootCerInputStream = null; try { //服务端的证书验证 rootCerInputStream = mContext.getAssets().open("wx_server.crt"); //构造CertificateFactory对象 CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); //通过certificateFactory对象获得Certificate对象 Certificate certificate = certificateFactory.generateCertificate(rootCerInputStream); //创建KeyStore对象 KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null); //将Certificate对象存到KeyStore对象中 keyStore.setCertificateEntry("wx_server.cer", certificate); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); //利用KeyStore初始化TrustManagerFactory对象 trustManagerFactory.init(keyStore); //通过TrustManagerFactory对象获得trustManagers; TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); if (1 != trustManagers.length || !(trustManagers[0] instanceof X509TrustManager)) { throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers)); } //java平台添加客户端的证书 //KeyStore clientKeyStore = KeyStore.getInstance(KeyStore.getDefaultType()); //clientKeyStore.load(application.getApplicationContext().getAssets().open("wx_client.jks"), "123456".toCharArray()); //KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); //keyManagerFactory.init(keyStore, "123456".toCharArray()); //KeyManager[] keyManagers = keyManagerFactory.getKeyManagers(); //Android添加客户端的证书 KeyStore clientKeyStore = KeyStore.getInstance("BKS"); clientKeyStore.load(mContext.getAssets().open("wx_client.bks"), "123456".toCharArray()); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, "123456".toCharArray()); KeyManager[] keyManagers = keyManagerFactory.getKeyManagers(); //构造SSLContext对象 SSLContext sslContext = SSLContext.getInstance("TLS"); //利用trustManagers初始化SSLContext对象 sslContext.init(keyManagers, trustManagers, new SecureRandom()); //得到我们需要的SSLSocketFactory mSslSocketFactory = sslContext.getSocketFactory(); //得到我们需要的X509TrustManager对象 mTrustManager = (X509TrustManager) trustManagers[0]; } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } finally { if (rootCerInputStream != null) { try { rootCerInputStream.close(); } catch (Exception ex) { ex.printStackTrace(); } } } } private void initDefaultSSLSocketFactory() { try { TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init((KeyStore) null); TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); if (1 != trustManagers.length || !(trustManagers[0] instanceof X509TrustManager)) { throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers)); } SSLContext sslDefaultContext = SSLContext.getInstance("TLS"); sslDefaultContext.init(null, trustManagers, null); mSslSocketFactory = sslDefaultContext.getSocketFactory(); mTrustManager = (X509TrustManager) trustManagers[0]; } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } // 获取这个SSLSocketFactory public SSLSocketFactory getSSLSocketFactory() { if (mSslSocketFactory == null) { initData(); } return mSslSocketFactory; } // 获取TrustManager public X509TrustManager getTrustManager() { if (mTrustManager == null) { initData(); } return mTrustManager; } }
UTF-8
Java
5,911
java
WXSSlSocketFactory.java
Java
[]
null
[]
package com.example.app_mvvm_livedata.http; import android.content.Context; import java.io.InputStream; import java.security.KeyStore; import java.security.SecureRandom; import java.security.cert.Certificate; import java.security.cert.CertificateFactory; import java.util.Arrays; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; public class WXSSlSocketFactory { private SSLSocketFactory mSslSocketFactory; private X509TrustManager mTrustManager; private Context mContext; private boolean mCaptureAble; //能否抓包,true为可以抓包;false为不能抓包 public WXSSlSocketFactory(Context context) { this(context, false); } public WXSSlSocketFactory(Context context, boolean captureAble) { this.mContext = context.getApplicationContext(); this.mCaptureAble = captureAble; initData(); } private void initData() { if (mCaptureAble) { initCustomSSLSocketFactory(); } else { initDefaultSSLSocketFactory(); } } private void initCustomSSLSocketFactory() { InputStream rootCerInputStream = null; try { //服务端的证书验证 rootCerInputStream = mContext.getAssets().open("wx_server.crt"); //构造CertificateFactory对象 CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); //通过certificateFactory对象获得Certificate对象 Certificate certificate = certificateFactory.generateCertificate(rootCerInputStream); //创建KeyStore对象 KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null); //将Certificate对象存到KeyStore对象中 keyStore.setCertificateEntry("wx_server.cer", certificate); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); //利用KeyStore初始化TrustManagerFactory对象 trustManagerFactory.init(keyStore); //通过TrustManagerFactory对象获得trustManagers; TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); if (1 != trustManagers.length || !(trustManagers[0] instanceof X509TrustManager)) { throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers)); } //java平台添加客户端的证书 //KeyStore clientKeyStore = KeyStore.getInstance(KeyStore.getDefaultType()); //clientKeyStore.load(application.getApplicationContext().getAssets().open("wx_client.jks"), "123456".toCharArray()); //KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); //keyManagerFactory.init(keyStore, "123456".toCharArray()); //KeyManager[] keyManagers = keyManagerFactory.getKeyManagers(); //Android添加客户端的证书 KeyStore clientKeyStore = KeyStore.getInstance("BKS"); clientKeyStore.load(mContext.getAssets().open("wx_client.bks"), "123456".toCharArray()); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, "123456".toCharArray()); KeyManager[] keyManagers = keyManagerFactory.getKeyManagers(); //构造SSLContext对象 SSLContext sslContext = SSLContext.getInstance("TLS"); //利用trustManagers初始化SSLContext对象 sslContext.init(keyManagers, trustManagers, new SecureRandom()); //得到我们需要的SSLSocketFactory mSslSocketFactory = sslContext.getSocketFactory(); //得到我们需要的X509TrustManager对象 mTrustManager = (X509TrustManager) trustManagers[0]; } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } finally { if (rootCerInputStream != null) { try { rootCerInputStream.close(); } catch (Exception ex) { ex.printStackTrace(); } } } } private void initDefaultSSLSocketFactory() { try { TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init((KeyStore) null); TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); if (1 != trustManagers.length || !(trustManagers[0] instanceof X509TrustManager)) { throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers)); } SSLContext sslDefaultContext = SSLContext.getInstance("TLS"); sslDefaultContext.init(null, trustManagers, null); mSslSocketFactory = sslDefaultContext.getSocketFactory(); mTrustManager = (X509TrustManager) trustManagers[0]; } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } // 获取这个SSLSocketFactory public SSLSocketFactory getSSLSocketFactory() { if (mSslSocketFactory == null) { initData(); } return mSslSocketFactory; } // 获取TrustManager public X509TrustManager getTrustManager() { if (mTrustManager == null) { initData(); } return mTrustManager; } }
5,911
0.663149
0.653122
139
39.899281
31.82151
129
false
false
0
0
0
0
0
0
0.597122
false
false
4
945f4efee108da1f862175b0399e2202d76dce7a
29,807,073,065,231
c7a15a307af709c875c9bff0dff80c04f0140b90
/p000o/C1335.java
0e61e5ac57828d4a015c2bd9f5d62bf71e91028f
[]
no_license
officialwedevgames/testing
https://github.com/officialwedevgames/testing
4b0af18ddd8c92b73ef73b35710598f759b8f4b6
56b12e1374bce2635c8021eba0c799c9b9bf32b1
refs/heads/master
2019-03-20T02:43:56.562000
2018-07-04T05:34:49
2018-07-04T05:34:49
123,827,836
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package p000o; class C1335 extends az { C1335(int i, int i2, int i3) { this.ܕ = (short) 275; C0406.f3003.f8225.mo686(this, 0); this.Ą.putShort((short) i2); C0406.f3003.f8225.mo686(this, 1); this.Ą.putShort((short) i); C0406.f3003.f8225.mo686(this, 2); this.Ą.putInt(i3); C0406.f3003.f8225.mo685(this); } }
UTF-8
Java
383
java
C1335.java
Java
[]
null
[]
package p000o; class C1335 extends az { C1335(int i, int i2, int i3) { this.ܕ = (short) 275; C0406.f3003.f8225.mo686(this, 0); this.Ą.putShort((short) i2); C0406.f3003.f8225.mo686(this, 1); this.Ą.putShort((short) i); C0406.f3003.f8225.mo686(this, 2); this.Ą.putInt(i3); C0406.f3003.f8225.mo685(this); } }
383
0.564644
0.350923
14
26.071428
14.547775
41
false
false
0
0
0
0
0
0
1
false
false
4
383b339d00f3df1670b05acda6f25ac16f6ffe57
10,273,561,819,143
e6b087ae131cb1a6bc799740cb0012598bed1e32
/src/main/java/com/kjz/www/coin/controller/base/CoinTransferRecordController.java
f5f4e34f0e3e40fe3119f5d987f227e9c5132539
[]
no_license
xeonye/smartContract
https://github.com/xeonye/smartContract
5f9f72caef3028101ce99ece2ec0c57f9cc0b0d0
1864c95c561c8258f1bd66384a61444f42b8042a
refs/heads/master
2020-03-10T01:10:14.881000
2018-04-11T13:06:57
2018-04-11T13:06:57
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.kjz.www.coin.controller.base; import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.alibaba.fastjson.JSON; import com.kjz.www.coin.domain.CoinTransferRecord; import com.kjz.www.coin.service.ICoinTransferRecordService; import com.kjz.www.coin.vo.CoinTransferRecordVo; import com.kjz.www.coin.vo.CoinTransferRecordVoFont; import com.kjz.www.common.WebResponse; import com.kjz.www.utils.UserUtils; import com.kjz.www.utils.vo.UserCookie; @Controller @RequestMapping("/coinTransferRecord") public class CoinTransferRecordController { @Autowired protected WebResponse webResponse; @Resource protected UserUtils userUtils; @Resource protected ICoinTransferRecordService coinTransferRecordService; @RequestMapping(value = "/addOrEditCoinTransferRecord", method = RequestMethod.POST, produces = "application/json;charset=UTF-8") @ResponseBody public WebResponse addOrEditCoinTransferRecord(HttpServletRequest request, HttpServletResponse response, HttpSession session, String coinTransferRecordId, @RequestParam(required = false) String currentWallet, @RequestParam(required = false) String targetWallet, @RequestParam(required = false) String currentAccount, @RequestParam(required = false) String targetAccount, @RequestParam(required = false) String taskTime, @RequestParam(required = false) String coinType, @RequestParam(required = false) String coinNum, @RequestParam(required = false) String state, @RequestParam(required = false) String transferMoney, @RequestParam(required = false) String minerMoney, @RequestParam(required = false) String cnyMoney, @RequestParam(required = false) String usdMoney, @RequestParam(required = false) String transfer, @RequestParam(required = false) String isart, @RequestParam(required = false) String tbStatus) { if (coinTransferRecordId == null || coinTransferRecordId.length() == 0) { return this.addCoinTransferRecord(request, response, session, currentWallet, targetWallet, currentAccount, targetAccount, taskTime, coinType, coinNum, state, transferMoney, minerMoney, cnyMoney, usdMoney, transfer, isart); } else { return this.editCoinTransferRecord(request, response, session, coinTransferRecordId, currentWallet, targetWallet, currentAccount, targetAccount, taskTime, coinType, coinNum, state, transferMoney, minerMoney, cnyMoney, usdMoney, transfer, isart, tbStatus); } } @RequestMapping(value = "/addCoinTransferRecord", method = RequestMethod.POST, produces = "application/json;charset=UTF-8") @ResponseBody public WebResponse addCoinTransferRecord(HttpServletRequest request, HttpServletResponse response, HttpSession session, String currentWallet, String targetWallet, String currentAccount, String targetAccount, String taskTime, String coinType, String coinNum, String state, String transferMoney, String minerMoney, String cnyMoney, String usdMoney, String transfer, String isart) { Object data = null; String statusMsg = ""; Integer statusCode = 200; Map<String, String> paramMap = new HashMap<String, String>(); paramMap.put("currentWallet", currentWallet); paramMap.put("targetWallet", targetWallet); paramMap.put("currentAccount", currentAccount); paramMap.put("targetAccount", targetAccount); paramMap.put("taskTime", taskTime); paramMap.put("coinType", coinType); paramMap.put("coinNum", coinNum); paramMap.put("state", state); paramMap.put("transferMoney", transferMoney); paramMap.put("minerMoney", minerMoney); paramMap.put("cnyMoney", cnyMoney); paramMap.put("usdMoney", usdMoney); paramMap.put("transfer", transfer); paramMap.put("isart", isart); data = paramMap; if (currentWallet == null || "".equals(currentWallet.trim()) || targetWallet == null || "".equals(targetWallet.trim()) || currentAccount == null || "".equals(currentAccount.trim()) || targetAccount == null || "".equals(targetAccount.trim()) || taskTime == null || "".equals(taskTime.trim()) || coinType == null || "".equals(coinType.trim()) || coinNum == null || "".equals(coinNum.trim()) || state == null || "".equals(state.trim()) || transferMoney == null || "".equals(transferMoney.trim()) || minerMoney == null || "".equals(minerMoney.trim()) || cnyMoney == null || "".equals(cnyMoney.trim()) || usdMoney == null || "".equals(usdMoney.trim()) || transfer == null || "".equals(transfer.trim()) || isart == null || "".equals(isart.trim())) { statusMsg = " 参数为空错误!!!!"; statusCode = 201; return webResponse.getWebResponse(statusCode, statusMsg, data); } if (currentWallet.length() > 64 || targetWallet.length() > 64 || currentAccount.length() > 32 || targetAccount.length() > 32 || taskTime.length() > 19 || coinType.length() > 64 || state.length() > 80 || transfer.length() > 200 || isart.length() > 50) { statusMsg = " 参数长度过长错误!!!"; statusCode = 201; return webResponse.getWebResponse(statusCode, statusMsg, data); } String tbStatus = "normal"; CoinTransferRecord coinTransferRecord = new CoinTransferRecord(); UserCookie userCookie = this.userUtils.getLoginUser(request, response, session); if (userCookie == null) { statusMsg = "请登录!"; statusCode = 201; data = statusMsg; return webResponse.getWebResponse(statusCode, statusMsg, data); } boolean isAdd = true; return this.addOrEditCoinTransferRecord(request, response, session, data, coinTransferRecord,currentWallet,targetWallet,currentAccount,targetAccount,taskTime,coinType,coinNum,state,transferMoney,minerMoney,cnyMoney,usdMoney,transfer,isart,tbStatus, isAdd); } @RequestMapping(value = "/editCoinTransferRecord", method = RequestMethod.POST, produces = "application/json;charset=UTF-8") @ResponseBody public WebResponse editCoinTransferRecord(HttpServletRequest request, HttpServletResponse response, HttpSession session, String coinTransferRecordId, @RequestParam(required = false) String currentWallet, @RequestParam(required = false) String targetWallet, @RequestParam(required = false) String currentAccount, @RequestParam(required = false) String targetAccount, @RequestParam(required = false) String taskTime, @RequestParam(required = false) String coinType, @RequestParam(required = false) String coinNum, @RequestParam(required = false) String state, @RequestParam(required = false) String transferMoney, @RequestParam(required = false) String minerMoney, @RequestParam(required = false) String cnyMoney, @RequestParam(required = false) String usdMoney, @RequestParam(required = false) String transfer, @RequestParam(required = false) String isart, @RequestParam(required = false) String tbStatus) { Object data = null; String statusMsg = ""; Integer statusCode = 200; Map<String, String> paramMap = new HashMap<String, String>(); paramMap.put("coinTransferRecordId", coinTransferRecordId); paramMap.put("currentWallet", currentWallet); paramMap.put("targetWallet", targetWallet); paramMap.put("currentAccount", currentAccount); paramMap.put("targetAccount", targetAccount); paramMap.put("taskTime", taskTime); paramMap.put("coinType", coinType); paramMap.put("coinNum", coinNum); paramMap.put("state", state); paramMap.put("transferMoney", transferMoney); paramMap.put("minerMoney", minerMoney); paramMap.put("cnyMoney", cnyMoney); paramMap.put("usdMoney", usdMoney); paramMap.put("transfer", transfer); paramMap.put("isart", isart); paramMap.put("tbStatus", tbStatus); data = paramMap; if (coinTransferRecordId == null || "".equals(coinTransferRecordId.trim())) { statusMsg = "未获得主键参数错误!!!"; statusCode = 201; return webResponse.getWebResponse(statusCode, statusMsg, data); } Integer coinTransferRecordIdNumeri = coinTransferRecordId.matches("^[0-9]*$") ? Integer.parseInt(coinTransferRecordId) : 0; if (coinTransferRecordIdNumeri == 0) { statusMsg = "主键不为数字错误!!!"; statusCode = 201; return webResponse.getWebResponse(statusCode, statusMsg, data); } CoinTransferRecordVo coinTransferRecordVo = this.coinTransferRecordService.getById(coinTransferRecordIdNumeri); CoinTransferRecord coinTransferRecord = new CoinTransferRecord(); BeanUtils.copyProperties(coinTransferRecordVo, coinTransferRecord); UserCookie userCookie = this.userUtils.getLoginUser(request, response, session); if (userCookie == null) { statusMsg = "请登录!"; statusCode = 201; data = statusMsg; return webResponse.getWebResponse(statusCode, statusMsg, data); } boolean isAdd = false; return this.addOrEditCoinTransferRecord(request, response, session, data, coinTransferRecord,currentWallet,targetWallet,currentAccount,targetAccount,taskTime,coinType,coinNum,state,transferMoney,minerMoney,cnyMoney,usdMoney,transfer,isart,tbStatus, isAdd); } private WebResponse addOrEditCoinTransferRecord(HttpServletRequest request, HttpServletResponse response, HttpSession session, Object data, CoinTransferRecord coinTransferRecord, String currentWallet, String targetWallet, String currentAccount, String targetAccount, String taskTime, String coinType, String coinNum, String state, String transferMoney, String minerMoney, String cnyMoney, String usdMoney, String transfer, String isart, String tbStatus, boolean isAdd) { String statusMsg = ""; Integer statusCode = 200; if (currentWallet != null && !("".equals(currentWallet.trim()))) { if(currentWallet.length() > 64) { statusMsg = " 参数长度过长错误,currentWallet"; statusCode = 201; return webResponse.getWebResponse(statusCode, statusMsg, data); } coinTransferRecord.setCurrentWallet(currentWallet); } if (targetWallet != null && !("".equals(targetWallet.trim()))) { if(targetWallet.length() > 64) { statusMsg = " 参数长度过长错误,targetWallet"; statusCode = 201; return webResponse.getWebResponse(statusCode, statusMsg, data); } coinTransferRecord.setTargetWallet(targetWallet); } if (currentAccount != null && !("".equals(currentAccount.trim()))) { if(currentAccount.length() > 32) { statusMsg = " 参数长度过长错误,currentAccount"; statusCode = 201; return webResponse.getWebResponse(statusCode, statusMsg, data); } coinTransferRecord.setCurrentAccount(currentAccount); } if (targetAccount != null && !("".equals(targetAccount.trim()))) { if(targetAccount.length() > 32) { statusMsg = " 参数长度过长错误,targetAccount"; statusCode = 201; return webResponse.getWebResponse(statusCode, statusMsg, data); } coinTransferRecord.setTargetAccount(targetAccount); } if (taskTime != null && !("".equals(taskTime.trim()))) { if(taskTime.length() > 19) { statusMsg = " 参数长度过长错误,taskTime"; statusCode = 201; return webResponse.getWebResponse(statusCode, statusMsg, data); } coinTransferRecord.setTaskTime(taskTime); } if (coinType != null && !("".equals(coinType.trim()))) { if(coinType.length() > 64) { statusMsg = " 参数长度过长错误,coinType"; statusCode = 201; return webResponse.getWebResponse(statusCode, statusMsg, data); } coinTransferRecord.setCoinType(coinType); } BigDecimal coinNumNumeri = new BigDecimal(0); if (coinNum != null && !("".equals(coinNum.trim()))) { if (!coinNum.matches("^[0-9].*$")) { statusMsg = " 参数数字型错误!!!不能为0,coinNum"; statusCode = 201; return webResponse.getWebResponse(statusCode, statusMsg, data); } coinNumNumeri = new BigDecimal(coinNum); coinTransferRecord.setCoinNum(coinNumNumeri); } if (state != null && !("".equals(state.trim()))) { if(state.length() > 80) { statusMsg = " 参数长度过长错误,state"; statusCode = 201; return webResponse.getWebResponse(statusCode, statusMsg, data); } coinTransferRecord.setState(state); } BigDecimal transferMoneyNumeri = new BigDecimal(0); if (transferMoney != null && !("".equals(transferMoney.trim()))) { if (!transferMoney.matches("^[0-9].*$")) { statusMsg = " 参数数字型错误!!!不能为0,transferMoney"; statusCode = 201; return webResponse.getWebResponse(statusCode, statusMsg, data); } transferMoneyNumeri = new BigDecimal(transferMoney); coinTransferRecord.setTransferMoney(transferMoneyNumeri); } BigDecimal minerMoneyNumeri = new BigDecimal(0); if (minerMoney != null && !("".equals(minerMoney.trim()))) { if (!minerMoney.matches("^[0-9].*$")) { statusMsg = " 参数数字型错误!!!不能为0,minerMoney"; statusCode = 201; return webResponse.getWebResponse(statusCode, statusMsg, data); } minerMoneyNumeri = new BigDecimal(minerMoney); coinTransferRecord.setMinerMoney(minerMoneyNumeri); } BigDecimal cnyMoneyNumeri = new BigDecimal(0); if (cnyMoney != null && !("".equals(cnyMoney.trim()))) { if (!cnyMoney.matches("^[0-9].*$")) { statusMsg = " 参数数字型错误!!!不能为0,cnyMoney"; statusCode = 201; return webResponse.getWebResponse(statusCode, statusMsg, data); } cnyMoneyNumeri = new BigDecimal(cnyMoney); coinTransferRecord.setCnyMoney(cnyMoneyNumeri); } BigDecimal usdMoneyNumeri = new BigDecimal(0); if (usdMoney != null && !("".equals(usdMoney.trim()))) { if (!usdMoney.matches("^[0-9].*$")) { statusMsg = " 参数数字型错误!!!不能为0,usdMoney"; statusCode = 201; return webResponse.getWebResponse(statusCode, statusMsg, data); } usdMoneyNumeri = new BigDecimal(usdMoney); coinTransferRecord.setUsdMoney(usdMoneyNumeri); } if (transfer != null && !("".equals(transfer.trim()))) { if(transfer.length() > 200) { statusMsg = " 参数长度过长错误,transfer"; statusCode = 201; return webResponse.getWebResponse(statusCode, statusMsg, data); } coinTransferRecord.setTransfer(transfer); } if (isart != null && !("".equals(isart.trim()))) { if(isart.length() > 50) { statusMsg = " 参数长度过长错误,isart"; statusCode = 201; return webResponse.getWebResponse(statusCode, statusMsg, data); } coinTransferRecord.setIsart(isart); } if (tbStatus != null && !("".equals(tbStatus.trim()))) { if(tbStatus.length() > 50) { statusMsg = " 参数长度过长错误,tbStatus"; statusCode = 201; return webResponse.getWebResponse(statusCode, statusMsg, data); } coinTransferRecord.setTbStatus(tbStatus); } if (isAdd) { this.coinTransferRecordService.insert(coinTransferRecord); if (coinTransferRecord.getCoinTransferRecordId() > 0) { statusMsg = "成功插入!!!"; } else { statusCode = 202; statusMsg = "insert false"; } return webResponse.getWebResponse(statusCode, statusMsg, data); } int num = this.coinTransferRecordService.update(coinTransferRecord); if (num > 0) { statusMsg = "成功修改!!!"; } else { statusCode = 202; statusMsg = "update false"; } return webResponse.getWebResponse(statusCode, statusMsg, data); } @RequestMapping(value = "/getCoinTransferRecordById", produces = "application/json;charset=UTF-8") @ResponseBody public WebResponse getCoinTransferRecordById(String coinTransferRecordId) { Object data = coinTransferRecordId; Integer statusCode = 200; String statusMsg = ""; if (coinTransferRecordId == null || coinTransferRecordId.length() == 0 || coinTransferRecordId.length() > 11) { statusMsg = "参数为空或参数过长错误!!!"; statusCode = 201; return webResponse.getWebResponse(statusCode, statusMsg, data); } Integer coinTransferRecordIdNumNumeri = coinTransferRecordId.matches("^[0-9]*$") ? Integer.parseInt(coinTransferRecordId) : 0; if (coinTransferRecordIdNumNumeri == 0 ) { statusMsg = "参数数字型错误!!!"; statusCode = 201; return webResponse.getWebResponse(statusCode, statusMsg, data); } CoinTransferRecordVo coinTransferRecordVo = this.coinTransferRecordService.getById(coinTransferRecordIdNumNumeri); if (coinTransferRecordVo != null && coinTransferRecordVo.getCoinTransferRecordId() > 0) { data = coinTransferRecordVo; statusMsg = "获取单条数据成功!!!"; } else { statusCode = 202; statusMsg = "no record!!!"; } return webResponse.getWebResponse(statusCode, statusMsg, data); } @RequestMapping(value = "/getOneCoinTransferRecord", method = RequestMethod.POST, produces = "application/json;charset=UTF-8") @ResponseBody public WebResponse getOneCoinTransferRecord(@RequestParam(defaultValue = "正常", required = false) String tbStatus) { LinkedHashMap<String, String> condition = new LinkedHashMap<String, String>(); condition.put("tb_status='" + tbStatus + "'", ""); CoinTransferRecordVo coinTransferRecordVo = this.coinTransferRecordService.getOne(condition); Object data = null; String statusMsg = ""; if (coinTransferRecordVo != null && coinTransferRecordVo.getCoinTransferRecordId() > 0) { data = coinTransferRecordVo; statusMsg = "根据条件获取单条数据成功!!!"; } else { statusMsg = "no record!!!"; } return webResponse.getWebResponse(statusMsg, data); } @RequestMapping(value = "/getCoinTransferRecordList", method = RequestMethod.POST, produces = "application/json;charset=UTF-8") @ResponseBody public WebResponse getCoinTransferRecordList(HttpServletRequest request, HttpServletResponse response, HttpSession session, @RequestParam(defaultValue = "1", required = false) Integer pageNo, @RequestParam(defaultValue = "10", required = false) Integer pageSize, @RequestParam(defaultValue = "正常", required = false) String tbStatus, @RequestParam(required = false) String keyword, @RequestParam(defaultValue = "coin_transfer_record_id", required = false) String order, @RequestParam(defaultValue = "desc", required = false) String desc ) { Object data = null; String statusMsg = ""; int statusCode = 200; LinkedHashMap<String, String> condition = new LinkedHashMap<String, String>(); if (tbStatus != null && tbStatus.length() > 0) { condition.put("tb_status='" + tbStatus + "'", "and"); } if (keyword != null && keyword.length() > 0) { StringBuffer buf = new StringBuffer(); buf.append("("); buf.append("current_wallet like '%").append(keyword).append("%'"); buf.append(" or "); buf.append("target_wallet like '%").append(keyword).append("%'"); buf.append(" or "); buf.append("current_account like '%").append(keyword).append("%'"); buf.append(" or "); buf.append("target_account like '%").append(keyword).append("%'"); buf.append(" or "); buf.append("task_time like '%").append(keyword).append("%'"); buf.append(" or "); buf.append("coin_type like '%").append(keyword).append("%'"); buf.append(" or "); buf.append("state like '%").append(keyword).append("%'"); buf.append(" or "); buf.append("transfer like '%").append(keyword).append("%'"); buf.append(" or "); buf.append("isArt like '%").append(keyword).append("%'"); buf.append(")"); condition.put(buf.toString(), "and"); } String field = null; if (condition.size() > 0) { condition.put(condition.entrySet().iterator().next().getKey(), ""); } int count = this.coinTransferRecordService.getCount(condition, field); if (order != null && order.length() > 0 & "desc".equals(desc)) { order = order + " desc"; } List<CoinTransferRecordVo> list = this.coinTransferRecordService.getList(condition, pageNo, pageSize, order, field); Map<Object, Object> map = new HashMap<Object, Object>(); map.put("total", count); int size = list.size(); if (size > 0) { List<CoinTransferRecordVoFont> listFont = new ArrayList<CoinTransferRecordVoFont>(); CoinTransferRecordVo vo; CoinTransferRecordVoFont voFont = new CoinTransferRecordVoFont(); for (int i = 0; i < size; i++) { vo = list.get(i); BeanUtils.copyProperties(vo, voFont); listFont.add(voFont); voFont = new CoinTransferRecordVoFont(); } map.put("list", listFont); data = map; statusMsg = "根据条件获取分页数据成功!!!"; } else { map.put("list", list); data = map; statusCode = 202; statusMsg = "no record!!!"; return webResponse.getWebResponse(statusCode, statusMsg, data); } return webResponse.getWebResponse(statusCode, statusMsg, data); } @RequestMapping(value = "/getAdminCoinTransferRecordList", method = RequestMethod.POST, produces = "application/json;charset=UTF-8") @ResponseBody public String getAdminCoinTransferRecordList(HttpServletRequest request, HttpServletResponse response, HttpSession session, @RequestParam(defaultValue = "1", required = false) Integer pageNo, @RequestParam(defaultValue = "10", required = false) Integer pageSize, @RequestParam(defaultValue = "正常", required = false) String tbStatus, @RequestParam(required = false) String keyword, @RequestParam(defaultValue = "coin_transfer_record_id", required = false) String order, @RequestParam(defaultValue = "desc", required = false) String desc ) { Object data = null; String statusMsg = ""; int statusCode = 200; LinkedHashMap<String, String> condition = new LinkedHashMap<String, String>(); UserCookie userCookie = this.userUtils.getLoginUser(request, response, session); if (userCookie == null) { statusMsg = "请登录!"; statusCode = 201; data = statusMsg; return JSON.toJSONString(data); } if (tbStatus != null && tbStatus.length() > 0) { condition.put("tb_status='" + tbStatus + "'", "and"); } if (keyword != null && keyword.length() > 0) { StringBuffer buf = new StringBuffer(); buf.append("("); buf.append("current_wallet like '%").append(keyword).append("%'"); buf.append(" or "); buf.append("target_wallet like '%").append(keyword).append("%'"); buf.append(" or "); buf.append("current_account like '%").append(keyword).append("%'"); buf.append(" or "); buf.append("target_account like '%").append(keyword).append("%'"); buf.append(" or "); buf.append("task_time like '%").append(keyword).append("%'"); buf.append(" or "); buf.append("coin_type like '%").append(keyword).append("%'"); buf.append(" or "); buf.append("state like '%").append(keyword).append("%'"); buf.append(" or "); buf.append("transfer like '%").append(keyword).append("%'"); buf.append(" or "); buf.append("isArt like '%").append(keyword).append("%'"); buf.append(")"); condition.put(buf.toString(), "and"); } String field = null; if (condition.size() > 0) { condition.put(condition.entrySet().iterator().next().getKey(), ""); } int count = this.coinTransferRecordService.getCount(condition, field); if (order != null && order.length() > 0 & "desc".equals(desc)) { order = order + " desc"; } List<CoinTransferRecordVo> list = this.coinTransferRecordService.getList(condition, pageNo, pageSize, order, field); Map<Object, Object> map = new HashMap<Object, Object>(); map.put("total", count); int size = list.size(); if (size > 0) { map.put("list", list); data = map; statusMsg = "根据条件获取分页数据成功!!!"; } else { map.put("list", list); data = map; statusCode = 202; statusMsg = "no record!!!"; } return JSON.toJSONString(data); } @RequestMapping(value = "/delCoinTransferRecord", method = RequestMethod.POST, produces = "application/json;charset=UTF-8") @ResponseBody public WebResponse delCoinTransferRecord(int id) { int num = this.coinTransferRecordService.delBySign(id);; Object data = null; String statusMsg = ""; if (num > 0) { statusMsg = "成功删除!!!"; } else { statusMsg = "no record!!!"; } return webResponse.getWebResponse(statusMsg, data); } }
UTF-8
Java
24,916
java
CoinTransferRecordController.java
Java
[]
null
[]
package com.kjz.www.coin.controller.base; import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.alibaba.fastjson.JSON; import com.kjz.www.coin.domain.CoinTransferRecord; import com.kjz.www.coin.service.ICoinTransferRecordService; import com.kjz.www.coin.vo.CoinTransferRecordVo; import com.kjz.www.coin.vo.CoinTransferRecordVoFont; import com.kjz.www.common.WebResponse; import com.kjz.www.utils.UserUtils; import com.kjz.www.utils.vo.UserCookie; @Controller @RequestMapping("/coinTransferRecord") public class CoinTransferRecordController { @Autowired protected WebResponse webResponse; @Resource protected UserUtils userUtils; @Resource protected ICoinTransferRecordService coinTransferRecordService; @RequestMapping(value = "/addOrEditCoinTransferRecord", method = RequestMethod.POST, produces = "application/json;charset=UTF-8") @ResponseBody public WebResponse addOrEditCoinTransferRecord(HttpServletRequest request, HttpServletResponse response, HttpSession session, String coinTransferRecordId, @RequestParam(required = false) String currentWallet, @RequestParam(required = false) String targetWallet, @RequestParam(required = false) String currentAccount, @RequestParam(required = false) String targetAccount, @RequestParam(required = false) String taskTime, @RequestParam(required = false) String coinType, @RequestParam(required = false) String coinNum, @RequestParam(required = false) String state, @RequestParam(required = false) String transferMoney, @RequestParam(required = false) String minerMoney, @RequestParam(required = false) String cnyMoney, @RequestParam(required = false) String usdMoney, @RequestParam(required = false) String transfer, @RequestParam(required = false) String isart, @RequestParam(required = false) String tbStatus) { if (coinTransferRecordId == null || coinTransferRecordId.length() == 0) { return this.addCoinTransferRecord(request, response, session, currentWallet, targetWallet, currentAccount, targetAccount, taskTime, coinType, coinNum, state, transferMoney, minerMoney, cnyMoney, usdMoney, transfer, isart); } else { return this.editCoinTransferRecord(request, response, session, coinTransferRecordId, currentWallet, targetWallet, currentAccount, targetAccount, taskTime, coinType, coinNum, state, transferMoney, minerMoney, cnyMoney, usdMoney, transfer, isart, tbStatus); } } @RequestMapping(value = "/addCoinTransferRecord", method = RequestMethod.POST, produces = "application/json;charset=UTF-8") @ResponseBody public WebResponse addCoinTransferRecord(HttpServletRequest request, HttpServletResponse response, HttpSession session, String currentWallet, String targetWallet, String currentAccount, String targetAccount, String taskTime, String coinType, String coinNum, String state, String transferMoney, String minerMoney, String cnyMoney, String usdMoney, String transfer, String isart) { Object data = null; String statusMsg = ""; Integer statusCode = 200; Map<String, String> paramMap = new HashMap<String, String>(); paramMap.put("currentWallet", currentWallet); paramMap.put("targetWallet", targetWallet); paramMap.put("currentAccount", currentAccount); paramMap.put("targetAccount", targetAccount); paramMap.put("taskTime", taskTime); paramMap.put("coinType", coinType); paramMap.put("coinNum", coinNum); paramMap.put("state", state); paramMap.put("transferMoney", transferMoney); paramMap.put("minerMoney", minerMoney); paramMap.put("cnyMoney", cnyMoney); paramMap.put("usdMoney", usdMoney); paramMap.put("transfer", transfer); paramMap.put("isart", isart); data = paramMap; if (currentWallet == null || "".equals(currentWallet.trim()) || targetWallet == null || "".equals(targetWallet.trim()) || currentAccount == null || "".equals(currentAccount.trim()) || targetAccount == null || "".equals(targetAccount.trim()) || taskTime == null || "".equals(taskTime.trim()) || coinType == null || "".equals(coinType.trim()) || coinNum == null || "".equals(coinNum.trim()) || state == null || "".equals(state.trim()) || transferMoney == null || "".equals(transferMoney.trim()) || minerMoney == null || "".equals(minerMoney.trim()) || cnyMoney == null || "".equals(cnyMoney.trim()) || usdMoney == null || "".equals(usdMoney.trim()) || transfer == null || "".equals(transfer.trim()) || isart == null || "".equals(isart.trim())) { statusMsg = " 参数为空错误!!!!"; statusCode = 201; return webResponse.getWebResponse(statusCode, statusMsg, data); } if (currentWallet.length() > 64 || targetWallet.length() > 64 || currentAccount.length() > 32 || targetAccount.length() > 32 || taskTime.length() > 19 || coinType.length() > 64 || state.length() > 80 || transfer.length() > 200 || isart.length() > 50) { statusMsg = " 参数长度过长错误!!!"; statusCode = 201; return webResponse.getWebResponse(statusCode, statusMsg, data); } String tbStatus = "normal"; CoinTransferRecord coinTransferRecord = new CoinTransferRecord(); UserCookie userCookie = this.userUtils.getLoginUser(request, response, session); if (userCookie == null) { statusMsg = "请登录!"; statusCode = 201; data = statusMsg; return webResponse.getWebResponse(statusCode, statusMsg, data); } boolean isAdd = true; return this.addOrEditCoinTransferRecord(request, response, session, data, coinTransferRecord,currentWallet,targetWallet,currentAccount,targetAccount,taskTime,coinType,coinNum,state,transferMoney,minerMoney,cnyMoney,usdMoney,transfer,isart,tbStatus, isAdd); } @RequestMapping(value = "/editCoinTransferRecord", method = RequestMethod.POST, produces = "application/json;charset=UTF-8") @ResponseBody public WebResponse editCoinTransferRecord(HttpServletRequest request, HttpServletResponse response, HttpSession session, String coinTransferRecordId, @RequestParam(required = false) String currentWallet, @RequestParam(required = false) String targetWallet, @RequestParam(required = false) String currentAccount, @RequestParam(required = false) String targetAccount, @RequestParam(required = false) String taskTime, @RequestParam(required = false) String coinType, @RequestParam(required = false) String coinNum, @RequestParam(required = false) String state, @RequestParam(required = false) String transferMoney, @RequestParam(required = false) String minerMoney, @RequestParam(required = false) String cnyMoney, @RequestParam(required = false) String usdMoney, @RequestParam(required = false) String transfer, @RequestParam(required = false) String isart, @RequestParam(required = false) String tbStatus) { Object data = null; String statusMsg = ""; Integer statusCode = 200; Map<String, String> paramMap = new HashMap<String, String>(); paramMap.put("coinTransferRecordId", coinTransferRecordId); paramMap.put("currentWallet", currentWallet); paramMap.put("targetWallet", targetWallet); paramMap.put("currentAccount", currentAccount); paramMap.put("targetAccount", targetAccount); paramMap.put("taskTime", taskTime); paramMap.put("coinType", coinType); paramMap.put("coinNum", coinNum); paramMap.put("state", state); paramMap.put("transferMoney", transferMoney); paramMap.put("minerMoney", minerMoney); paramMap.put("cnyMoney", cnyMoney); paramMap.put("usdMoney", usdMoney); paramMap.put("transfer", transfer); paramMap.put("isart", isart); paramMap.put("tbStatus", tbStatus); data = paramMap; if (coinTransferRecordId == null || "".equals(coinTransferRecordId.trim())) { statusMsg = "未获得主键参数错误!!!"; statusCode = 201; return webResponse.getWebResponse(statusCode, statusMsg, data); } Integer coinTransferRecordIdNumeri = coinTransferRecordId.matches("^[0-9]*$") ? Integer.parseInt(coinTransferRecordId) : 0; if (coinTransferRecordIdNumeri == 0) { statusMsg = "主键不为数字错误!!!"; statusCode = 201; return webResponse.getWebResponse(statusCode, statusMsg, data); } CoinTransferRecordVo coinTransferRecordVo = this.coinTransferRecordService.getById(coinTransferRecordIdNumeri); CoinTransferRecord coinTransferRecord = new CoinTransferRecord(); BeanUtils.copyProperties(coinTransferRecordVo, coinTransferRecord); UserCookie userCookie = this.userUtils.getLoginUser(request, response, session); if (userCookie == null) { statusMsg = "请登录!"; statusCode = 201; data = statusMsg; return webResponse.getWebResponse(statusCode, statusMsg, data); } boolean isAdd = false; return this.addOrEditCoinTransferRecord(request, response, session, data, coinTransferRecord,currentWallet,targetWallet,currentAccount,targetAccount,taskTime,coinType,coinNum,state,transferMoney,minerMoney,cnyMoney,usdMoney,transfer,isart,tbStatus, isAdd); } private WebResponse addOrEditCoinTransferRecord(HttpServletRequest request, HttpServletResponse response, HttpSession session, Object data, CoinTransferRecord coinTransferRecord, String currentWallet, String targetWallet, String currentAccount, String targetAccount, String taskTime, String coinType, String coinNum, String state, String transferMoney, String minerMoney, String cnyMoney, String usdMoney, String transfer, String isart, String tbStatus, boolean isAdd) { String statusMsg = ""; Integer statusCode = 200; if (currentWallet != null && !("".equals(currentWallet.trim()))) { if(currentWallet.length() > 64) { statusMsg = " 参数长度过长错误,currentWallet"; statusCode = 201; return webResponse.getWebResponse(statusCode, statusMsg, data); } coinTransferRecord.setCurrentWallet(currentWallet); } if (targetWallet != null && !("".equals(targetWallet.trim()))) { if(targetWallet.length() > 64) { statusMsg = " 参数长度过长错误,targetWallet"; statusCode = 201; return webResponse.getWebResponse(statusCode, statusMsg, data); } coinTransferRecord.setTargetWallet(targetWallet); } if (currentAccount != null && !("".equals(currentAccount.trim()))) { if(currentAccount.length() > 32) { statusMsg = " 参数长度过长错误,currentAccount"; statusCode = 201; return webResponse.getWebResponse(statusCode, statusMsg, data); } coinTransferRecord.setCurrentAccount(currentAccount); } if (targetAccount != null && !("".equals(targetAccount.trim()))) { if(targetAccount.length() > 32) { statusMsg = " 参数长度过长错误,targetAccount"; statusCode = 201; return webResponse.getWebResponse(statusCode, statusMsg, data); } coinTransferRecord.setTargetAccount(targetAccount); } if (taskTime != null && !("".equals(taskTime.trim()))) { if(taskTime.length() > 19) { statusMsg = " 参数长度过长错误,taskTime"; statusCode = 201; return webResponse.getWebResponse(statusCode, statusMsg, data); } coinTransferRecord.setTaskTime(taskTime); } if (coinType != null && !("".equals(coinType.trim()))) { if(coinType.length() > 64) { statusMsg = " 参数长度过长错误,coinType"; statusCode = 201; return webResponse.getWebResponse(statusCode, statusMsg, data); } coinTransferRecord.setCoinType(coinType); } BigDecimal coinNumNumeri = new BigDecimal(0); if (coinNum != null && !("".equals(coinNum.trim()))) { if (!coinNum.matches("^[0-9].*$")) { statusMsg = " 参数数字型错误!!!不能为0,coinNum"; statusCode = 201; return webResponse.getWebResponse(statusCode, statusMsg, data); } coinNumNumeri = new BigDecimal(coinNum); coinTransferRecord.setCoinNum(coinNumNumeri); } if (state != null && !("".equals(state.trim()))) { if(state.length() > 80) { statusMsg = " 参数长度过长错误,state"; statusCode = 201; return webResponse.getWebResponse(statusCode, statusMsg, data); } coinTransferRecord.setState(state); } BigDecimal transferMoneyNumeri = new BigDecimal(0); if (transferMoney != null && !("".equals(transferMoney.trim()))) { if (!transferMoney.matches("^[0-9].*$")) { statusMsg = " 参数数字型错误!!!不能为0,transferMoney"; statusCode = 201; return webResponse.getWebResponse(statusCode, statusMsg, data); } transferMoneyNumeri = new BigDecimal(transferMoney); coinTransferRecord.setTransferMoney(transferMoneyNumeri); } BigDecimal minerMoneyNumeri = new BigDecimal(0); if (minerMoney != null && !("".equals(minerMoney.trim()))) { if (!minerMoney.matches("^[0-9].*$")) { statusMsg = " 参数数字型错误!!!不能为0,minerMoney"; statusCode = 201; return webResponse.getWebResponse(statusCode, statusMsg, data); } minerMoneyNumeri = new BigDecimal(minerMoney); coinTransferRecord.setMinerMoney(minerMoneyNumeri); } BigDecimal cnyMoneyNumeri = new BigDecimal(0); if (cnyMoney != null && !("".equals(cnyMoney.trim()))) { if (!cnyMoney.matches("^[0-9].*$")) { statusMsg = " 参数数字型错误!!!不能为0,cnyMoney"; statusCode = 201; return webResponse.getWebResponse(statusCode, statusMsg, data); } cnyMoneyNumeri = new BigDecimal(cnyMoney); coinTransferRecord.setCnyMoney(cnyMoneyNumeri); } BigDecimal usdMoneyNumeri = new BigDecimal(0); if (usdMoney != null && !("".equals(usdMoney.trim()))) { if (!usdMoney.matches("^[0-9].*$")) { statusMsg = " 参数数字型错误!!!不能为0,usdMoney"; statusCode = 201; return webResponse.getWebResponse(statusCode, statusMsg, data); } usdMoneyNumeri = new BigDecimal(usdMoney); coinTransferRecord.setUsdMoney(usdMoneyNumeri); } if (transfer != null && !("".equals(transfer.trim()))) { if(transfer.length() > 200) { statusMsg = " 参数长度过长错误,transfer"; statusCode = 201; return webResponse.getWebResponse(statusCode, statusMsg, data); } coinTransferRecord.setTransfer(transfer); } if (isart != null && !("".equals(isart.trim()))) { if(isart.length() > 50) { statusMsg = " 参数长度过长错误,isart"; statusCode = 201; return webResponse.getWebResponse(statusCode, statusMsg, data); } coinTransferRecord.setIsart(isart); } if (tbStatus != null && !("".equals(tbStatus.trim()))) { if(tbStatus.length() > 50) { statusMsg = " 参数长度过长错误,tbStatus"; statusCode = 201; return webResponse.getWebResponse(statusCode, statusMsg, data); } coinTransferRecord.setTbStatus(tbStatus); } if (isAdd) { this.coinTransferRecordService.insert(coinTransferRecord); if (coinTransferRecord.getCoinTransferRecordId() > 0) { statusMsg = "成功插入!!!"; } else { statusCode = 202; statusMsg = "insert false"; } return webResponse.getWebResponse(statusCode, statusMsg, data); } int num = this.coinTransferRecordService.update(coinTransferRecord); if (num > 0) { statusMsg = "成功修改!!!"; } else { statusCode = 202; statusMsg = "update false"; } return webResponse.getWebResponse(statusCode, statusMsg, data); } @RequestMapping(value = "/getCoinTransferRecordById", produces = "application/json;charset=UTF-8") @ResponseBody public WebResponse getCoinTransferRecordById(String coinTransferRecordId) { Object data = coinTransferRecordId; Integer statusCode = 200; String statusMsg = ""; if (coinTransferRecordId == null || coinTransferRecordId.length() == 0 || coinTransferRecordId.length() > 11) { statusMsg = "参数为空或参数过长错误!!!"; statusCode = 201; return webResponse.getWebResponse(statusCode, statusMsg, data); } Integer coinTransferRecordIdNumNumeri = coinTransferRecordId.matches("^[0-9]*$") ? Integer.parseInt(coinTransferRecordId) : 0; if (coinTransferRecordIdNumNumeri == 0 ) { statusMsg = "参数数字型错误!!!"; statusCode = 201; return webResponse.getWebResponse(statusCode, statusMsg, data); } CoinTransferRecordVo coinTransferRecordVo = this.coinTransferRecordService.getById(coinTransferRecordIdNumNumeri); if (coinTransferRecordVo != null && coinTransferRecordVo.getCoinTransferRecordId() > 0) { data = coinTransferRecordVo; statusMsg = "获取单条数据成功!!!"; } else { statusCode = 202; statusMsg = "no record!!!"; } return webResponse.getWebResponse(statusCode, statusMsg, data); } @RequestMapping(value = "/getOneCoinTransferRecord", method = RequestMethod.POST, produces = "application/json;charset=UTF-8") @ResponseBody public WebResponse getOneCoinTransferRecord(@RequestParam(defaultValue = "正常", required = false) String tbStatus) { LinkedHashMap<String, String> condition = new LinkedHashMap<String, String>(); condition.put("tb_status='" + tbStatus + "'", ""); CoinTransferRecordVo coinTransferRecordVo = this.coinTransferRecordService.getOne(condition); Object data = null; String statusMsg = ""; if (coinTransferRecordVo != null && coinTransferRecordVo.getCoinTransferRecordId() > 0) { data = coinTransferRecordVo; statusMsg = "根据条件获取单条数据成功!!!"; } else { statusMsg = "no record!!!"; } return webResponse.getWebResponse(statusMsg, data); } @RequestMapping(value = "/getCoinTransferRecordList", method = RequestMethod.POST, produces = "application/json;charset=UTF-8") @ResponseBody public WebResponse getCoinTransferRecordList(HttpServletRequest request, HttpServletResponse response, HttpSession session, @RequestParam(defaultValue = "1", required = false) Integer pageNo, @RequestParam(defaultValue = "10", required = false) Integer pageSize, @RequestParam(defaultValue = "正常", required = false) String tbStatus, @RequestParam(required = false) String keyword, @RequestParam(defaultValue = "coin_transfer_record_id", required = false) String order, @RequestParam(defaultValue = "desc", required = false) String desc ) { Object data = null; String statusMsg = ""; int statusCode = 200; LinkedHashMap<String, String> condition = new LinkedHashMap<String, String>(); if (tbStatus != null && tbStatus.length() > 0) { condition.put("tb_status='" + tbStatus + "'", "and"); } if (keyword != null && keyword.length() > 0) { StringBuffer buf = new StringBuffer(); buf.append("("); buf.append("current_wallet like '%").append(keyword).append("%'"); buf.append(" or "); buf.append("target_wallet like '%").append(keyword).append("%'"); buf.append(" or "); buf.append("current_account like '%").append(keyword).append("%'"); buf.append(" or "); buf.append("target_account like '%").append(keyword).append("%'"); buf.append(" or "); buf.append("task_time like '%").append(keyword).append("%'"); buf.append(" or "); buf.append("coin_type like '%").append(keyword).append("%'"); buf.append(" or "); buf.append("state like '%").append(keyword).append("%'"); buf.append(" or "); buf.append("transfer like '%").append(keyword).append("%'"); buf.append(" or "); buf.append("isArt like '%").append(keyword).append("%'"); buf.append(")"); condition.put(buf.toString(), "and"); } String field = null; if (condition.size() > 0) { condition.put(condition.entrySet().iterator().next().getKey(), ""); } int count = this.coinTransferRecordService.getCount(condition, field); if (order != null && order.length() > 0 & "desc".equals(desc)) { order = order + " desc"; } List<CoinTransferRecordVo> list = this.coinTransferRecordService.getList(condition, pageNo, pageSize, order, field); Map<Object, Object> map = new HashMap<Object, Object>(); map.put("total", count); int size = list.size(); if (size > 0) { List<CoinTransferRecordVoFont> listFont = new ArrayList<CoinTransferRecordVoFont>(); CoinTransferRecordVo vo; CoinTransferRecordVoFont voFont = new CoinTransferRecordVoFont(); for (int i = 0; i < size; i++) { vo = list.get(i); BeanUtils.copyProperties(vo, voFont); listFont.add(voFont); voFont = new CoinTransferRecordVoFont(); } map.put("list", listFont); data = map; statusMsg = "根据条件获取分页数据成功!!!"; } else { map.put("list", list); data = map; statusCode = 202; statusMsg = "no record!!!"; return webResponse.getWebResponse(statusCode, statusMsg, data); } return webResponse.getWebResponse(statusCode, statusMsg, data); } @RequestMapping(value = "/getAdminCoinTransferRecordList", method = RequestMethod.POST, produces = "application/json;charset=UTF-8") @ResponseBody public String getAdminCoinTransferRecordList(HttpServletRequest request, HttpServletResponse response, HttpSession session, @RequestParam(defaultValue = "1", required = false) Integer pageNo, @RequestParam(defaultValue = "10", required = false) Integer pageSize, @RequestParam(defaultValue = "正常", required = false) String tbStatus, @RequestParam(required = false) String keyword, @RequestParam(defaultValue = "coin_transfer_record_id", required = false) String order, @RequestParam(defaultValue = "desc", required = false) String desc ) { Object data = null; String statusMsg = ""; int statusCode = 200; LinkedHashMap<String, String> condition = new LinkedHashMap<String, String>(); UserCookie userCookie = this.userUtils.getLoginUser(request, response, session); if (userCookie == null) { statusMsg = "请登录!"; statusCode = 201; data = statusMsg; return JSON.toJSONString(data); } if (tbStatus != null && tbStatus.length() > 0) { condition.put("tb_status='" + tbStatus + "'", "and"); } if (keyword != null && keyword.length() > 0) { StringBuffer buf = new StringBuffer(); buf.append("("); buf.append("current_wallet like '%").append(keyword).append("%'"); buf.append(" or "); buf.append("target_wallet like '%").append(keyword).append("%'"); buf.append(" or "); buf.append("current_account like '%").append(keyword).append("%'"); buf.append(" or "); buf.append("target_account like '%").append(keyword).append("%'"); buf.append(" or "); buf.append("task_time like '%").append(keyword).append("%'"); buf.append(" or "); buf.append("coin_type like '%").append(keyword).append("%'"); buf.append(" or "); buf.append("state like '%").append(keyword).append("%'"); buf.append(" or "); buf.append("transfer like '%").append(keyword).append("%'"); buf.append(" or "); buf.append("isArt like '%").append(keyword).append("%'"); buf.append(")"); condition.put(buf.toString(), "and"); } String field = null; if (condition.size() > 0) { condition.put(condition.entrySet().iterator().next().getKey(), ""); } int count = this.coinTransferRecordService.getCount(condition, field); if (order != null && order.length() > 0 & "desc".equals(desc)) { order = order + " desc"; } List<CoinTransferRecordVo> list = this.coinTransferRecordService.getList(condition, pageNo, pageSize, order, field); Map<Object, Object> map = new HashMap<Object, Object>(); map.put("total", count); int size = list.size(); if (size > 0) { map.put("list", list); data = map; statusMsg = "根据条件获取分页数据成功!!!"; } else { map.put("list", list); data = map; statusCode = 202; statusMsg = "no record!!!"; } return JSON.toJSONString(data); } @RequestMapping(value = "/delCoinTransferRecord", method = RequestMethod.POST, produces = "application/json;charset=UTF-8") @ResponseBody public WebResponse delCoinTransferRecord(int id) { int num = this.coinTransferRecordService.delBySign(id);; Object data = null; String statusMsg = ""; if (num > 0) { statusMsg = "成功删除!!!"; } else { statusMsg = "no record!!!"; } return webResponse.getWebResponse(statusMsg, data); } }
24,916
0.701811
0.693292
513
45.360622
75.487762
912
false
false
0
0
0
0
0
0
3.672515
false
false
4
3b771569c4340fe346f311a705a76d9d1e92935d
22,531,398,502,437
07567d1b051d679c203d63b7feaa3429f4599862
/RoverMelange/src-gen/rover/raspirovermt/raspirover/Action.java
3d13a9b3dedf3dc85987782add025b361e89c185
[]
no_license
tdegueul/gemoc-pirover
https://github.com/tdegueul/gemoc-pirover
1bce59c253de235a2a594f5b2ea96c1632100099
b786281099b0cc76f292a0a7f9218c4b8e02cae8
refs/heads/master
2020-04-05T13:00:34.008000
2017-10-10T14:15:57
2017-10-10T14:15:57
95,002,463
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** */ package rover.raspirovermt.raspirover; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Action</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link rover.raspirovermt.raspirover.Action#getAssociatedPin <em>Associated Pin</em>}</li> * </ul> * * @see rover.raspirovermt.raspirover.RaspiroverPackage#getAction() * @model abstract="true" * @generated */ public interface Action extends Statement { /** * Returns the value of the '<em><b>Associated Pin</b></em>' reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Associated Pin</em>' reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Associated Pin</em>' reference. * @see #setAssociatedPin(Pin) * @see rover.raspirovermt.raspirover.RaspiroverPackage#getAction_AssociatedPin() * @model * @generated */ Pin getAssociatedPin(); /** * Sets the value of the '{@link rover.raspirovermt.raspirover.Action#getAssociatedPin <em>Associated Pin</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Associated Pin</em>' reference. * @see #getAssociatedPin() * @generated */ void setAssociatedPin(Pin value); } // Action
UTF-8
Java
1,381
java
Action.java
Java
[]
null
[]
/** */ package rover.raspirovermt.raspirover; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Action</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link rover.raspirovermt.raspirover.Action#getAssociatedPin <em>Associated Pin</em>}</li> * </ul> * * @see rover.raspirovermt.raspirover.RaspiroverPackage#getAction() * @model abstract="true" * @generated */ public interface Action extends Statement { /** * Returns the value of the '<em><b>Associated Pin</b></em>' reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Associated Pin</em>' reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Associated Pin</em>' reference. * @see #setAssociatedPin(Pin) * @see rover.raspirovermt.raspirover.RaspiroverPackage#getAction_AssociatedPin() * @model * @generated */ Pin getAssociatedPin(); /** * Sets the value of the '{@link rover.raspirovermt.raspirover.Action#getAssociatedPin <em>Associated Pin</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Associated Pin</em>' reference. * @see #getAssociatedPin() * @generated */ void setAssociatedPin(Pin value); } // Action
1,381
0.648805
0.648805
49
27.183674
29.29768
124
false
false
0
0
0
0
0
0
0.571429
false
false
4
3927d4f5efb141b654e8bf406097f17fcdd3802e
23,459,111,432,766
c64b32c7c0ec56747a55e93415e4d2b4be0a1c9e
/app/src/main/java/elsys/exert/com/exert/activities/tasks/TaskActivity.java
b7b401d62c8776cdf2e5be166194348125daef75
[]
no_license
jobs-elsys/Jobche.bg
https://github.com/jobs-elsys/Jobche.bg
61c3c54b4c14494179fc0cae42cf48323e2209b1
c609d4f1c36d27916ff6dde00c66414a6d4be08f
refs/heads/master
2018-09-11T00:27:49.207000
2018-06-05T12:44:14
2018-06-05T12:44:14
126,154,010
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package elsys.exert.com.exert.activities.tasks; import android.provider.ContactsContract; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import elsys.exert.com.exert.R; import elsys.exert.com.exert.models.tasks.Task; import elsys.exert.com.exert.models.users.UserInformation; public class TaskActivity extends AppCompatActivity { private static final String TAG = "TaskActivity"; private TextView tvLocation; private TextView tvDate; private TextView tvMoney; private TextView tvDescription; private TextView tvRecruiter; private Button btnApply; final UserInformation user = new UserInformation(); Task task; private DatabaseReference databaseUsers = FirebaseDatabase.getInstance().getReference("Users"); private DatabaseReference databaseTasksAppliers = FirebaseDatabase.getInstance().getReference("Tasks"); private FirebaseAuth mAuth = FirebaseAuth.getInstance(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_task); task = (Task) getIntent().getSerializableExtra("Task"); tvLocation = (TextView) findViewById(R.id.tv_taskLocation); tvDate = (TextView) findViewById(R.id.tv_taskDate); tvMoney = (TextView) findViewById(R.id.tv_taskMoney); tvDescription = (TextView) findViewById(R.id.tv_taskDescription); tvRecruiter = (TextView) findViewById(R.id.tv_taskRecruiter); btnApply = (Button) findViewById(R.id.btn_apply); android.support.v7.widget.Toolbar toolbar = findViewById(R.id.toolbar); TextView mTitle = toolbar.findViewById(R.id.toolbar_title); toolbar.setTitle(""); setSupportActionBar(toolbar); getSupportActionBar().setDisplayShowHomeEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); startDataListeners(); startClickListeners(); tvLocation.setText(task.getLocation()); tvDate.setText(task.getDate()); tvMoney.setText(String.valueOf(task.getMoney())); tvDescription.setText(task.getDescription()); } private void startDataListeners(){ databaseUsers.child(task.getUploaderUID()).child("firstName").addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { try { if (dataSnapshot.getValue() != null) { try { user.setFirstName(dataSnapshot.getValue(String.class)); } catch (Exception e) { e.printStackTrace(); } } else { Log.e(TAG, " it's null."); } } catch (Exception e) { e.printStackTrace(); } } @Override public void onCancelled(DatabaseError databaseError) { Log.e("onCancelled", " cancelled"); } }); databaseUsers.child(task.getUploaderUID()).child("lastName").addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { try { if (dataSnapshot.getValue() != null) { try { user.setLastName(dataSnapshot.getValue(String.class)); String name = user.getFirstName() + " " + user.getLastName(); tvRecruiter.setText(name); } catch (Exception e) { e.printStackTrace(); } } else { Log.e(TAG, " it's null."); } } catch (Exception e) { e.printStackTrace(); } } @Override public void onCancelled(DatabaseError databaseError) { Log.e("onCancelled", " cancelled"); } }); } private void startClickListeners(){ btnApply.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d(TAG, task.taskIDget() + " I hope this works"); databaseTasksAppliers.child(task.taskIDget()) .child("appliers") .child(mAuth.getCurrentUser().getUid()) .setValue("true"); databaseUsers.child(mAuth.getCurrentUser().getUid()) .child("participatingTasks") .child(task.taskIDget()) .setValue("true"); Toast.makeText(TaskActivity.this, "You successfuly applied for the task!", Toast.LENGTH_LONG) .show(); } }); } @Override public boolean onOptionsItemSelected(android.view.MenuItem item) { int id = item.getItemId(); if(id == android.R.id.home) { this.finish(); } return super.onOptionsItemSelected(item); } }
UTF-8
Java
5,761
java
TaskActivity.java
Java
[]
null
[]
package elsys.exert.com.exert.activities.tasks; import android.provider.ContactsContract; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import elsys.exert.com.exert.R; import elsys.exert.com.exert.models.tasks.Task; import elsys.exert.com.exert.models.users.UserInformation; public class TaskActivity extends AppCompatActivity { private static final String TAG = "TaskActivity"; private TextView tvLocation; private TextView tvDate; private TextView tvMoney; private TextView tvDescription; private TextView tvRecruiter; private Button btnApply; final UserInformation user = new UserInformation(); Task task; private DatabaseReference databaseUsers = FirebaseDatabase.getInstance().getReference("Users"); private DatabaseReference databaseTasksAppliers = FirebaseDatabase.getInstance().getReference("Tasks"); private FirebaseAuth mAuth = FirebaseAuth.getInstance(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_task); task = (Task) getIntent().getSerializableExtra("Task"); tvLocation = (TextView) findViewById(R.id.tv_taskLocation); tvDate = (TextView) findViewById(R.id.tv_taskDate); tvMoney = (TextView) findViewById(R.id.tv_taskMoney); tvDescription = (TextView) findViewById(R.id.tv_taskDescription); tvRecruiter = (TextView) findViewById(R.id.tv_taskRecruiter); btnApply = (Button) findViewById(R.id.btn_apply); android.support.v7.widget.Toolbar toolbar = findViewById(R.id.toolbar); TextView mTitle = toolbar.findViewById(R.id.toolbar_title); toolbar.setTitle(""); setSupportActionBar(toolbar); getSupportActionBar().setDisplayShowHomeEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); startDataListeners(); startClickListeners(); tvLocation.setText(task.getLocation()); tvDate.setText(task.getDate()); tvMoney.setText(String.valueOf(task.getMoney())); tvDescription.setText(task.getDescription()); } private void startDataListeners(){ databaseUsers.child(task.getUploaderUID()).child("firstName").addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { try { if (dataSnapshot.getValue() != null) { try { user.setFirstName(dataSnapshot.getValue(String.class)); } catch (Exception e) { e.printStackTrace(); } } else { Log.e(TAG, " it's null."); } } catch (Exception e) { e.printStackTrace(); } } @Override public void onCancelled(DatabaseError databaseError) { Log.e("onCancelled", " cancelled"); } }); databaseUsers.child(task.getUploaderUID()).child("lastName").addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { try { if (dataSnapshot.getValue() != null) { try { user.setLastName(dataSnapshot.getValue(String.class)); String name = user.getFirstName() + " " + user.getLastName(); tvRecruiter.setText(name); } catch (Exception e) { e.printStackTrace(); } } else { Log.e(TAG, " it's null."); } } catch (Exception e) { e.printStackTrace(); } } @Override public void onCancelled(DatabaseError databaseError) { Log.e("onCancelled", " cancelled"); } }); } private void startClickListeners(){ btnApply.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d(TAG, task.taskIDget() + " I hope this works"); databaseTasksAppliers.child(task.taskIDget()) .child("appliers") .child(mAuth.getCurrentUser().getUid()) .setValue("true"); databaseUsers.child(mAuth.getCurrentUser().getUid()) .child("participatingTasks") .child(task.taskIDget()) .setValue("true"); Toast.makeText(TaskActivity.this, "You successfuly applied for the task!", Toast.LENGTH_LONG) .show(); } }); } @Override public boolean onOptionsItemSelected(android.view.MenuItem item) { int id = item.getItemId(); if(id == android.R.id.home) { this.finish(); } return super.onOptionsItemSelected(item); } }
5,761
0.591564
0.591217
154
36.409092
27.020102
127
false
false
0
0
0
0
0
0
0.519481
false
false
4
3fb699075da3a0ee1935b0f7972d0eff9461cd8d
8,126,078,142,982
b181fec2af5fe0f8b97bb0cb77048adbb95794fe
/src/Main.java
de1bfb9b3229d2d6527a1d95f9892a396d1eea90
[]
no_license
Luk3s/wordpress-offline-reading
https://github.com/Luk3s/wordpress-offline-reading
e2309b0b54532825b4b5bcb2697726cde1d7b2fb
214174bf3c778ffde6ba095983b95cc584bf3cee
refs/heads/master
2021-01-23T21:42:32.429000
2015-01-01T19:02:57
2015-01-01T19:02:57
28,691,166
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.File; import java.io.IOException; public class Main { public static void main(String[] args) throws IOException { // Input data String aboutTheAuthorURL = "http://erasmusinstirling.altervista.org/author/erasmusinstirling/"; // ToChange String howToReachOneArticleUrlUsingCss = ".entry-title a"; // ToChange WordpressOfflineReading.createUrlsListFile(aboutTheAuthorURL, howToReachOneArticleUrlUsingCss); WordpressOfflineReading.saveAllTheArticles(new File(System.getProperty("user.dir") + "/list.txt")); } }
UTF-8
Java
557
java
Main.java
Java
[ { "context": "= \"http://erasmusinstirling.altervista.org/author/erasmusinstirling/\";\t\t// ToChange\n\t\tString howToReachOneArticleUrlU", "end": 243, "score": 0.9961593747138977, "start": 226, "tag": "USERNAME", "value": "erasmusinstirling" } ]
null
[]
import java.io.File; import java.io.IOException; public class Main { public static void main(String[] args) throws IOException { // Input data String aboutTheAuthorURL = "http://erasmusinstirling.altervista.org/author/erasmusinstirling/"; // ToChange String howToReachOneArticleUrlUsingCss = ".entry-title a"; // ToChange WordpressOfflineReading.createUrlsListFile(aboutTheAuthorURL, howToReachOneArticleUrlUsingCss); WordpressOfflineReading.saveAllTheArticles(new File(System.getProperty("user.dir") + "/list.txt")); } }
557
0.75763
0.75763
18
29.944445
39.798759
110
false
false
0
0
0
0
0
0
1.722222
false
false
4
67036c78a8c94eca1998076b6291d799814c3de3
30,288,109,410,954
fc5785c90a28de6b7dac8393b9bbfa2a4155d177
/src/smartcall/Test.java
526b7aa08bf65c289b2805f907d1f2cb7eeb47f1
[]
no_license
scaperow/SIPTest
https://github.com/scaperow/SIPTest
e5e29ac52ce176b4ac391caa73677798e444263c
d5c03802bd19fe2c3c266daadb0d485eb73bd346
refs/heads/master
2020-04-06T07:08:49.645000
2018-03-07T04:47:12
2018-03-07T04:47:12
124,180,578
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package smartcall; import java.io.IOException; import java.util.Enumeration; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.sip.*; public class Test { public static void main(String[] args){ //System.out.print("sdfsdfsd"); //int value = System.in.read(); SoftPhone sp = new SoftPhone(); try { sp.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } class SoftPhone extends javax.servlet.sip.SipServlet{ protected void doRegister(SipServletRequest request){ request.createResponse(488); } } class SoftConfig implements ServletConfig{ @Override public String getInitParameter(String arg0) { // TODO Auto-generated method stub return null; } @Override public Enumeration getInitParameterNames() { // TODO Auto-generated method stub return null; } @Override public ServletContext getServletContext() { // TODO Auto-generated method stub ServletContext context = new ServletContext(); return null; } @Override public String getServletName() { // TODO Auto-generated method stub return null; } } class SoftContext implements ServletContext{ }
UTF-8
Java
1,261
java
Test.java
Java
[]
null
[]
package smartcall; import java.io.IOException; import java.util.Enumeration; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.sip.*; public class Test { public static void main(String[] args){ //System.out.print("sdfsdfsd"); //int value = System.in.read(); SoftPhone sp = new SoftPhone(); try { sp.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } class SoftPhone extends javax.servlet.sip.SipServlet{ protected void doRegister(SipServletRequest request){ request.createResponse(488); } } class SoftConfig implements ServletConfig{ @Override public String getInitParameter(String arg0) { // TODO Auto-generated method stub return null; } @Override public Enumeration getInitParameterNames() { // TODO Auto-generated method stub return null; } @Override public ServletContext getServletContext() { // TODO Auto-generated method stub ServletContext context = new ServletContext(); return null; } @Override public String getServletName() { // TODO Auto-generated method stub return null; } } class SoftContext implements ServletContext{ }
1,261
0.731166
0.727994
61
19.672131
17.372223
55
false
false
0
0
0
0
0
0
1.327869
false
false
4
a574d275ee28f23c7b3a8a0695aa64e787f98dd5
34,282,428,984,149
ae642b36ba414e8b52d6981d851707d5faaafec2
/src/main/java/com/challenge/easy/SockMerchant.java
7036bba8f5d5f6ff7c8c9f6ba7097c6bf9801b86
[ "Apache-2.0" ]
permissive
jorgelizandro/coding-challenges
https://github.com/jorgelizandro/coding-challenges
da3f791e76610ad05a760db5f1cac3d6a4f7259e
4c38d7dcd13cbea920bedf629a5f19c60b78dd4f
refs/heads/master
2020-03-24T16:28:32.462000
2019-10-18T13:15:15
2019-10-18T13:15:15
142,826,053
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.challenge.easy; import java.util.Arrays; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; public class SockMerchant { private SockMerchant() { } static int sockMerchant(int n, int[] arr) { if (arr == null || arr.length == 0) { return -1; } Map<Integer, Long> countMap = Arrays.stream(arr) .boxed() .collect(Collectors.groupingByConcurrent(Function.identity(), Collectors.counting())); Long pairTotal = countMap.values().stream() .map(a -> (Long)(a/2)) .reduce(0L, Long::sum); return pairTotal.intValue(); } public static void main(final String... args) { System.out.println("The socks pair count is:"); System.out.println(sockMerchant(7, new int[]{1, 2, 1, 2, 1, 3, 2})); //2 System.out.println(sockMerchant(9, new int[]{10, 20, 20, 10, 10, 30, 50, 10, 20})); //3 } }
UTF-8
Java
1,020
java
SockMerchant.java
Java
[]
null
[]
package com.challenge.easy; import java.util.Arrays; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; public class SockMerchant { private SockMerchant() { } static int sockMerchant(int n, int[] arr) { if (arr == null || arr.length == 0) { return -1; } Map<Integer, Long> countMap = Arrays.stream(arr) .boxed() .collect(Collectors.groupingByConcurrent(Function.identity(), Collectors.counting())); Long pairTotal = countMap.values().stream() .map(a -> (Long)(a/2)) .reduce(0L, Long::sum); return pairTotal.intValue(); } public static void main(final String... args) { System.out.println("The socks pair count is:"); System.out.println(sockMerchant(7, new int[]{1, 2, 1, 2, 1, 3, 2})); //2 System.out.println(sockMerchant(9, new int[]{10, 20, 20, 10, 10, 30, 50, 10, 20})); //3 } }
1,020
0.568627
0.536274
35
28.142857
27.016548
102
false
false
0
0
0
0
0
0
0.971429
false
false
4
d7a204ac05a555b84d14194ea50bdda64d061c20
15,324,443,369,721
c4150a9322eb805db170c500ddff60160c49c986
/src/main/java/service/ServiceBusController.java
dd889e9ebf1f221abbd64479af19d89584c2645e
[]
no_license
petlurinavyasree/entertainmentdiscovery
https://github.com/petlurinavyasree/entertainmentdiscovery
53c61824abedc4a73a04830af972f2049abf16e0
f78f1377bbf34c8ffcb84c9a784f1c7bff131d8d
refs/heads/master
2021-01-24T04:02:13.523000
2018-03-05T01:36:50
2018-03-05T01:36:50
122,919,081
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package service; import facebook.FacebookController; import lastfm.LastFmController; import model.facebook.FacebookResponse; import model.lastfm.ArtistData; import model.movie.MovieTitle; import model.service.ServiceResponse; import movie.RelatedMoviesController; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; @RestController public class ServiceBusController { private static final String template = "Hello, %s!"; private final AtomicLong counter = new AtomicLong(); private final SimpleDateFormat simpleFormat = new SimpleDateFormat("dd-MM-yyyy"); private final SimpleDateFormat requiredFormat = new SimpleDateFormat("yyyy-MM-dd"); private final LastFmController lastFmController; private final FacebookController facebookController; private final ServiceResponseController serviceResponseController; private final RelatedMoviesController relatedMoviesController; public ServiceBusController() { this.lastFmController = new LastFmController(); this.facebookController = new FacebookController(); this.serviceResponseController = new ServiceResponseController(); this.relatedMoviesController = new RelatedMoviesController(); } @CrossOrigin(origins = "http://localhost:63342") @RequestMapping("/discover") public ServiceResponse discoverEntertainment(@RequestParam(value="name", defaultValue="World") String name, @RequestParam(value="startDate", defaultValue="01-01-2008") String startDate, @RequestParam(value="endDate", defaultValue="01-01-2018") String endDate, @RequestParam(value="accessToken")String accessToken) throws ParseException { //String accesstoken = "EAACEdEose0cBALZBdKH7oxDqXPXFGoLyBg55OhW3p1Jw4SCMjPkWUTjxQ7tYfaBRpZAeov57Ojx1sOSB9Hxm6rQjLMfTLVpS5rqxwCd1b2MDHZC5zyHJA6iLh3MyJkfhGVkJ4HWTo2yJWvwscNIYBbVZB1HQUDK6mKVb6CzIXcW17SwR2idPSGx1aC9FsdwneAS7qnpQJgZDZD\n"; FacebookResponse response = facebookController.getFacebookData(accessToken); String startDateFormated = requiredFormat.format(simpleFormat.parse(startDate)); List<ArtistData> artistData = lastFmController.getRelatedMusicInfo(response.getArtistData(), startDate, endDate); Map<String, List<MovieTitle>> relatedMovies = relatedMoviesController.getRelatedMovies(response.getMovieData(),startDate,endDate); return serviceResponseController.createServiceResponse(artistData, relatedMovies); } }
UTF-8
Java
2,924
java
ServiceBusController.java
Java
[ { "context": " ParseException {\n //String accesstoken = \"EAACEdEose0cBALZBdKH7oxDqXPXFGoLyBg55OhW3p1Jw4SCMjPkWUTjxQ7tYfaBRpZAeov57Ojx1sOSB9Hxm6rQjLMfTLVpS5rqxwCd1b2MDHZC5zyHJA6iLh3MyJkfhGVkJ4HWTo2yJWvwscNIYBbVZB1HQUDK6mKVb6CzIXcW17SwR2idPSGx1aC9FsdwneAS7qnpQJgZDZD\\n\";\n\n\n FacebookResponse response = facebookC", "end": 2385, "score": 0.99840247631073, "start": 2176, "tag": "KEY", "value": "EAACEdEose0cBALZBdKH7oxDqXPXFGoLyBg55OhW3p1Jw4SCMjPkWUTjxQ7tYfaBRpZAeov57Ojx1sOSB9Hxm6rQjLMfTLVpS5rqxwCd1b2MDHZC5zyHJA6iLh3MyJkfhGVkJ4HWTo2yJWvwscNIYBbVZB1HQUDK6mKVb6CzIXcW17SwR2idPSGx1aC9FsdwneAS7qnpQJgZDZD\\n" } ]
null
[]
package service; import facebook.FacebookController; import lastfm.LastFmController; import model.facebook.FacebookResponse; import model.lastfm.ArtistData; import model.movie.MovieTitle; import model.service.ServiceResponse; import movie.RelatedMoviesController; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; @RestController public class ServiceBusController { private static final String template = "Hello, %s!"; private final AtomicLong counter = new AtomicLong(); private final SimpleDateFormat simpleFormat = new SimpleDateFormat("dd-MM-yyyy"); private final SimpleDateFormat requiredFormat = new SimpleDateFormat("yyyy-MM-dd"); private final LastFmController lastFmController; private final FacebookController facebookController; private final ServiceResponseController serviceResponseController; private final RelatedMoviesController relatedMoviesController; public ServiceBusController() { this.lastFmController = new LastFmController(); this.facebookController = new FacebookController(); this.serviceResponseController = new ServiceResponseController(); this.relatedMoviesController = new RelatedMoviesController(); } @CrossOrigin(origins = "http://localhost:63342") @RequestMapping("/discover") public ServiceResponse discoverEntertainment(@RequestParam(value="name", defaultValue="World") String name, @RequestParam(value="startDate", defaultValue="01-01-2008") String startDate, @RequestParam(value="endDate", defaultValue="01-01-2018") String endDate, @RequestParam(value="accessToken")String accessToken) throws ParseException { //String accesstoken = "<KEY>"; FacebookResponse response = facebookController.getFacebookData(accessToken); String startDateFormated = requiredFormat.format(simpleFormat.parse(startDate)); List<ArtistData> artistData = lastFmController.getRelatedMusicInfo(response.getArtistData(), startDate, endDate); Map<String, List<MovieTitle>> relatedMovies = relatedMoviesController.getRelatedMovies(response.getMovieData(),startDate,endDate); return serviceResponseController.createServiceResponse(artistData, relatedMovies); } }
2,720
0.7671
0.749658
57
50.298244
45.528076
243
false
false
0
0
0
0
207
0.070793
0.842105
false
false
4
8396c31363b4f2eec9b874c788af21cbcf341f5a
19,275,813,226,828
050717a204ef8c7c420b7bb5a0baea73aaf548f5
/app/src/main/java/com/aixinwu/axw/activity/Buy.java
41eb1fb1639f77f8aa17699ba9a558f22ec9c3f9
[ "Apache-2.0" ]
permissive
lionelee/AixinwuApp
https://github.com/lionelee/AixinwuApp
f7154f4bec0070ef20fd492b91b6177a14a76b92
70ce48701fdce8c0482e6612d41e079ce0737438
refs/heads/master
2021-09-14T01:44:28.749000
2018-05-07T11:11:10
2018-05-07T11:11:10
106,914,027
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.aixinwu.axw.activity; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.TypedValue; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.aixinwu.axw.R; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.commons.io.IOUtils; import org.json.JSONArray; import org.json.simple.JSONObject; import com.aixinwu.axw.database.Sqlite; import com.aixinwu.axw.tools.GlobalParameterApplication; import com.aixinwu.axw.tools.NetInfo; import com.nostra13.universalimageloader.core.ImageLoader; import de.hdodenhof.circleimageview.CircleImageView; /** * Created by liangyuding on 2016/4/15. */ public class Buy extends AppCompatActivity{ private String surl = GlobalParameterApplication.getSurl(); private String MyToken = GlobalParameterApplication.getToken(); private int itemID; private int OwnerID; private String Desc; private int Price; private String Picset; private String ownerName; private String picId; private String description; private String imgUrl; private ArrayList<String> comment_texts = new ArrayList<>(); private ArrayList<String> comment_times = new ArrayList<>(); private TextView textView1; private TextView textView2; private TextView textView3; private LinearLayout commentsubmit; private TextView tv_comm; private TextView button2; private String[] picts; private List<String> pic_list = new ArrayList<>(); private TextView Caption; private String _caption; private LinearLayout pictures; private LinearLayout relativeLayoutCollect; private ImageView iv_collect; private TextView tv_collect; private boolean flag = false; private int paddingBottom = 0; private Sqlite userDbHelper = new Sqlite(this); private CircleImageView headProtrait; TypedValue typedValue = new TypedValue(); @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_buy); Toolbar toolbar = (Toolbar) findViewById(R.id.buy_toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowTitleEnabled(false); getTheme().resolveAttribute(R.attr.colorAccent, typedValue, true); final Intent intent=getIntent(); Bundle out = intent.getExtras(); itemID=(int)out.get("itemId"); _caption = out.getString("caption"); picId = out.getString("pic_url"); description = out.getString("description"); pictures = (LinearLayout) findViewById(R.id.pics); button2=(TextView)findViewById(R.id.chat); textView1 = (TextView)findViewById(R.id.ownerid); textView2 = (TextView)findViewById(R.id.desc); textView3 = (TextView)findViewById(R.id.price3); commentsubmit = (LinearLayout) findViewById(R.id.commentsubmit); tv_comm = (TextView) findViewById(R.id.tv_comm); headProtrait = (CircleImageView) findViewById(R.id.img_activity_product); Caption = (TextView)findViewById(R.id.caption); Caption.setText(_caption); button2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (GlobalParameterApplication.getLogin_status()==0){ Intent intent3 = new Intent(Buy.this, LoginActivity.class); startActivityForResult(intent3,0); overridePendingTransition(R.anim.slide_in_right, R.anim.scale_fade_out); } else { Intent intent2 = new Intent(Buy.this,Chattoother.class); intent2.putExtra("itemID",itemID); intent2.putExtra("To",OwnerID); intent2.putExtra("ToName",ownerName); intent2.putExtra("imgUrl", imgUrl); startActivityForResult(intent2,1); overridePendingTransition(R.anim.slide_in_right, R.anim.scale_fade_out); } } }); commentsubmit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(Buy.this, Comment.class); intent.putExtra("itemID",itemID); intent.putStringArrayListExtra("comment_texts",comment_texts); intent.putStringArrayListExtra("comment_times",comment_times); startActivityForResult(intent,2); overridePendingTransition(R.anim.slide_in_right, R.anim.scale_fade_out); } }); new Thread(new Runnable() { @Override public void run() { SQLiteDatabase db = userDbHelper.getWritableDatabase(); Cursor cursor = db.rawQuery("select * from AXWcollect where itemId = " + itemID + " and userName = '" + GlobalParameterApplication.getUser_name() + "'", null); while (cursor.moveToNext()) { flag = true; break; } cursor.close(); db.close(); if(NetInfo.checkNetwork(Buy.this)){ GetInfo(itemID); GetComments(); HashMap<String,String> usrInfo = ChatList.getUserName("" + OwnerID); ownerName = usrInfo.get("usrName"); imgUrl = usrInfo.get("img"); picts = Picset.split(","); pic_list.clear(); for (int i = 0; i < picts.length; i++){ pic_list.add(GlobalParameterApplication.imgSurl+picts[i]); } } Message msg=new Message(); msg.what=2310231; nhandler.sendMessage(msg); } }).start(); iv_collect = (ImageView) findViewById(R.id.iv_collect); tv_collect = (TextView) findViewById(R.id.tv_collect); relativeLayoutCollect = (LinearLayout) findViewById(R.id.relativeCollect); relativeLayoutCollect.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(flag){ try { SQLiteDatabase db = userDbHelper.getWritableDatabase(); db.execSQL("delete from AXWcollect where itemId = " + itemID +" and userName='"+GlobalParameterApplication.getUser_name()+"'"); db.close(); flag = false; iv_collect.setImageResource(R.drawable.ic_star); tv_collect.setTextColor(getResources().getColor(R.color.gray)); tv_collect.setText("收藏"); }catch (Throwable e){ e.printStackTrace(); } }else{ try { SQLiteDatabase db = userDbHelper.getWritableDatabase(); db.execSQL("insert into AXWcollect(itemId,userName,type,desc,picUrl,price) values(" +itemID+",'"+GlobalParameterApplication.getUser_name() + "','" + _caption + "','" + description + "','" + picId + "',"+Price+")"); db.close(); flag = true; iv_collect.setImageResource(R.drawable.ic_stared); tv_collect.setTextColor(getResources().getColor(typedValue.resourceId)); tv_collect.setText("已收藏"); }catch (Throwable e){ e.printStackTrace(); } } } }); } Handler nhandler = new Handler(){ public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case 2310231: paddingBottom = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,8,getResources().getDisplayMetrics()); if(flag){ iv_collect.setImageResource(R.drawable.ic_stared); tv_collect.setTextColor(getResources().getColor(typedValue.resourceId)); tv_collect.setText("已收藏"); } textView1.setText(ownerName); textView2.setText(Desc); textView3.setText("价格:¥"+Price); tv_comm.setText(comment_texts.size()+"留言"); if (imgUrl != null && !imgUrl.equals("")) ImageLoader.getInstance().displayImage(GlobalParameterApplication.imgSurl+imgUrl, headProtrait); if(Picset != null && !Picset.equals("")){ for (int i = 0; i < pic_list.size(); ++i){ ImageView img = new ImageView(Buy.this); img.setPadding(0,0,0,paddingBottom); img.setScaleType(ImageView.ScaleType.CENTER_INSIDE); LinearLayout.LayoutParams imgLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT); ImageLoader.getInstance().displayImage(pic_list.get(i),img); img.setLayoutParams(imgLayoutParams); pictures.addView(img,imgLayoutParams); } } break; } } }; public void GetInfo(int itemID) { try { URL url = new URL(surl + "/item_get"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type","application/json"); JSONObject data = new JSONObject(); JSONObject iteminfo = new JSONObject(); iteminfo.put("ID",itemID); data.put("itemInfo",iteminfo); conn.getOutputStream().write(data.toJSONString().getBytes()); String ostr = IOUtils.toString(conn.getInputStream()); org.json.JSONObject outjson = new org.json.JSONObject(ostr); OwnerID = outjson.getJSONObject("itemInfo").getInt("ownerID"); Desc = outjson.getJSONObject("itemInfo").getString("description"); Price = outjson.getJSONObject("itemInfo").getInt("estimatedPriceByUser"); Picset = outjson.getJSONObject("itemInfo").getString("images"); } catch (Exception e) { e.printStackTrace(); } } public void GetComments(){ try { URL url = new URL(surl + "/item_get_comment"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type","application/json"); JSONObject data = new JSONObject(); data.put("token",MyToken); JSONObject comment = new JSONObject(); comment.put("itemID",itemID); data.put("comment",comment); conn.getOutputStream().write(data.toJSONString().getBytes()); String ostr = IOUtils.toString(conn.getInputStream()); org.json.JSONObject outjson = new org.json.JSONObject(ostr); JSONArray result=outjson.getJSONArray("comment"); org.json.JSONObject outt=null; comment_texts.clear(); comment_times.clear(); for (int i = 0; i < result.length();i++){ outt=result.getJSONObject(i); comment_texts.add(outt.getString("content")); comment_times.add(outt.getString("created")); } } catch (Exception e) { e.printStackTrace(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case android.R.id.home: onBackPressed(); default:break; } return super.onOptionsItemSelected(item); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if(requestCode == 2 && resultCode == RESULT_OK){ comment_texts = data.getStringArrayListExtra("comment_texts"); comment_times = data.getStringArrayListExtra("comment_times"); tv_comm.setText(comment_texts.size()+"留言"); } } @Override public void onBackPressed() { finish(); overridePendingTransition(R.anim.scale_fade_in, R.anim.slide_out_bottom); super.onBackPressed(); } }
UTF-8
Java
13,380
java
Buy.java
Java
[ { "context": "ircleimageview.CircleImageView;\n\n/**\n * Created by liangyuding on 2016/4/15.\n */\npublic class Buy extends AppCom", "end": 1047, "score": 0.9996463656425476, "start": 1036, "tag": "USERNAME", "value": "liangyuding" }, { "context": "D);\n intent2.putExtra(\"ToName\",ownerName);\n intent2.putExtra(\"imgUr", "end": 4318, "score": 0.7010349035263062, "start": 4313, "tag": "NAME", "value": "owner" }, { "context": "ID);\n ownerName = usrInfo.get(\"usrName\");\n imgUrl = usrInfo.get(\"", "end": 5937, "score": 0.6357494592666626, "start": 5934, "tag": "USERNAME", "value": "usr" }, { "context": " = new JSONObject();\n data.put(\"token\",MyToken);\n JSONObject comment = new JSONO", "end": 11662, "score": 0.45441222190856934, "start": 11660, "tag": "KEY", "value": "My" } ]
null
[]
package com.aixinwu.axw.activity; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.TypedValue; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.aixinwu.axw.R; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.commons.io.IOUtils; import org.json.JSONArray; import org.json.simple.JSONObject; import com.aixinwu.axw.database.Sqlite; import com.aixinwu.axw.tools.GlobalParameterApplication; import com.aixinwu.axw.tools.NetInfo; import com.nostra13.universalimageloader.core.ImageLoader; import de.hdodenhof.circleimageview.CircleImageView; /** * Created by liangyuding on 2016/4/15. */ public class Buy extends AppCompatActivity{ private String surl = GlobalParameterApplication.getSurl(); private String MyToken = GlobalParameterApplication.getToken(); private int itemID; private int OwnerID; private String Desc; private int Price; private String Picset; private String ownerName; private String picId; private String description; private String imgUrl; private ArrayList<String> comment_texts = new ArrayList<>(); private ArrayList<String> comment_times = new ArrayList<>(); private TextView textView1; private TextView textView2; private TextView textView3; private LinearLayout commentsubmit; private TextView tv_comm; private TextView button2; private String[] picts; private List<String> pic_list = new ArrayList<>(); private TextView Caption; private String _caption; private LinearLayout pictures; private LinearLayout relativeLayoutCollect; private ImageView iv_collect; private TextView tv_collect; private boolean flag = false; private int paddingBottom = 0; private Sqlite userDbHelper = new Sqlite(this); private CircleImageView headProtrait; TypedValue typedValue = new TypedValue(); @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_buy); Toolbar toolbar = (Toolbar) findViewById(R.id.buy_toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowTitleEnabled(false); getTheme().resolveAttribute(R.attr.colorAccent, typedValue, true); final Intent intent=getIntent(); Bundle out = intent.getExtras(); itemID=(int)out.get("itemId"); _caption = out.getString("caption"); picId = out.getString("pic_url"); description = out.getString("description"); pictures = (LinearLayout) findViewById(R.id.pics); button2=(TextView)findViewById(R.id.chat); textView1 = (TextView)findViewById(R.id.ownerid); textView2 = (TextView)findViewById(R.id.desc); textView3 = (TextView)findViewById(R.id.price3); commentsubmit = (LinearLayout) findViewById(R.id.commentsubmit); tv_comm = (TextView) findViewById(R.id.tv_comm); headProtrait = (CircleImageView) findViewById(R.id.img_activity_product); Caption = (TextView)findViewById(R.id.caption); Caption.setText(_caption); button2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (GlobalParameterApplication.getLogin_status()==0){ Intent intent3 = new Intent(Buy.this, LoginActivity.class); startActivityForResult(intent3,0); overridePendingTransition(R.anim.slide_in_right, R.anim.scale_fade_out); } else { Intent intent2 = new Intent(Buy.this,Chattoother.class); intent2.putExtra("itemID",itemID); intent2.putExtra("To",OwnerID); intent2.putExtra("ToName",ownerName); intent2.putExtra("imgUrl", imgUrl); startActivityForResult(intent2,1); overridePendingTransition(R.anim.slide_in_right, R.anim.scale_fade_out); } } }); commentsubmit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(Buy.this, Comment.class); intent.putExtra("itemID",itemID); intent.putStringArrayListExtra("comment_texts",comment_texts); intent.putStringArrayListExtra("comment_times",comment_times); startActivityForResult(intent,2); overridePendingTransition(R.anim.slide_in_right, R.anim.scale_fade_out); } }); new Thread(new Runnable() { @Override public void run() { SQLiteDatabase db = userDbHelper.getWritableDatabase(); Cursor cursor = db.rawQuery("select * from AXWcollect where itemId = " + itemID + " and userName = '" + GlobalParameterApplication.getUser_name() + "'", null); while (cursor.moveToNext()) { flag = true; break; } cursor.close(); db.close(); if(NetInfo.checkNetwork(Buy.this)){ GetInfo(itemID); GetComments(); HashMap<String,String> usrInfo = ChatList.getUserName("" + OwnerID); ownerName = usrInfo.get("usrName"); imgUrl = usrInfo.get("img"); picts = Picset.split(","); pic_list.clear(); for (int i = 0; i < picts.length; i++){ pic_list.add(GlobalParameterApplication.imgSurl+picts[i]); } } Message msg=new Message(); msg.what=2310231; nhandler.sendMessage(msg); } }).start(); iv_collect = (ImageView) findViewById(R.id.iv_collect); tv_collect = (TextView) findViewById(R.id.tv_collect); relativeLayoutCollect = (LinearLayout) findViewById(R.id.relativeCollect); relativeLayoutCollect.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(flag){ try { SQLiteDatabase db = userDbHelper.getWritableDatabase(); db.execSQL("delete from AXWcollect where itemId = " + itemID +" and userName='"+GlobalParameterApplication.getUser_name()+"'"); db.close(); flag = false; iv_collect.setImageResource(R.drawable.ic_star); tv_collect.setTextColor(getResources().getColor(R.color.gray)); tv_collect.setText("收藏"); }catch (Throwable e){ e.printStackTrace(); } }else{ try { SQLiteDatabase db = userDbHelper.getWritableDatabase(); db.execSQL("insert into AXWcollect(itemId,userName,type,desc,picUrl,price) values(" +itemID+",'"+GlobalParameterApplication.getUser_name() + "','" + _caption + "','" + description + "','" + picId + "',"+Price+")"); db.close(); flag = true; iv_collect.setImageResource(R.drawable.ic_stared); tv_collect.setTextColor(getResources().getColor(typedValue.resourceId)); tv_collect.setText("已收藏"); }catch (Throwable e){ e.printStackTrace(); } } } }); } Handler nhandler = new Handler(){ public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case 2310231: paddingBottom = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,8,getResources().getDisplayMetrics()); if(flag){ iv_collect.setImageResource(R.drawable.ic_stared); tv_collect.setTextColor(getResources().getColor(typedValue.resourceId)); tv_collect.setText("已收藏"); } textView1.setText(ownerName); textView2.setText(Desc); textView3.setText("价格:¥"+Price); tv_comm.setText(comment_texts.size()+"留言"); if (imgUrl != null && !imgUrl.equals("")) ImageLoader.getInstance().displayImage(GlobalParameterApplication.imgSurl+imgUrl, headProtrait); if(Picset != null && !Picset.equals("")){ for (int i = 0; i < pic_list.size(); ++i){ ImageView img = new ImageView(Buy.this); img.setPadding(0,0,0,paddingBottom); img.setScaleType(ImageView.ScaleType.CENTER_INSIDE); LinearLayout.LayoutParams imgLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT); ImageLoader.getInstance().displayImage(pic_list.get(i),img); img.setLayoutParams(imgLayoutParams); pictures.addView(img,imgLayoutParams); } } break; } } }; public void GetInfo(int itemID) { try { URL url = new URL(surl + "/item_get"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type","application/json"); JSONObject data = new JSONObject(); JSONObject iteminfo = new JSONObject(); iteminfo.put("ID",itemID); data.put("itemInfo",iteminfo); conn.getOutputStream().write(data.toJSONString().getBytes()); String ostr = IOUtils.toString(conn.getInputStream()); org.json.JSONObject outjson = new org.json.JSONObject(ostr); OwnerID = outjson.getJSONObject("itemInfo").getInt("ownerID"); Desc = outjson.getJSONObject("itemInfo").getString("description"); Price = outjson.getJSONObject("itemInfo").getInt("estimatedPriceByUser"); Picset = outjson.getJSONObject("itemInfo").getString("images"); } catch (Exception e) { e.printStackTrace(); } } public void GetComments(){ try { URL url = new URL(surl + "/item_get_comment"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type","application/json"); JSONObject data = new JSONObject(); data.put("token",MyToken); JSONObject comment = new JSONObject(); comment.put("itemID",itemID); data.put("comment",comment); conn.getOutputStream().write(data.toJSONString().getBytes()); String ostr = IOUtils.toString(conn.getInputStream()); org.json.JSONObject outjson = new org.json.JSONObject(ostr); JSONArray result=outjson.getJSONArray("comment"); org.json.JSONObject outt=null; comment_texts.clear(); comment_times.clear(); for (int i = 0; i < result.length();i++){ outt=result.getJSONObject(i); comment_texts.add(outt.getString("content")); comment_times.add(outt.getString("created")); } } catch (Exception e) { e.printStackTrace(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case android.R.id.home: onBackPressed(); default:break; } return super.onOptionsItemSelected(item); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if(requestCode == 2 && resultCode == RESULT_OK){ comment_texts = data.getStringArrayListExtra("comment_texts"); comment_times = data.getStringArrayListExtra("comment_times"); tv_comm.setText(comment_texts.size()+"留言"); } } @Override public void onBackPressed() { finish(); overridePendingTransition(R.anim.scale_fade_in, R.anim.slide_out_bottom); super.onBackPressed(); } }
13,380
0.585481
0.581061
314
41.509556
29.910614
238
false
false
0
0
0
0
0
0
0.834395
false
false
4
4eb28d7e81b7eeeac7e6ef842adb0b6d82a34ffb
20,590,073,283,184
1eabf8d99ed1bf70ddb3119b9bc0ec2388a4ae75
/dspace-api/src/main/java/org/dspace/orcid/consumer/OrcidQueueConsumer.java
d177e61607f111d5c7b7042818ec61862c0733c0
[ "BSD-3-Clause", "LGPL-2.0-or-later", "EPL-1.0", "LicenseRef-scancode-unicode", "LGPL-2.1-or-later", "CDDL-1.0", "MIT", "LicenseRef-scancode-unicode-icu-58", "MPL-1.0", "W3C", "GPL-1.0-or-later", "Apache-2.0", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
CICBA/DSpace
https://github.com/CICBA/DSpace
c849eedd4cda37460a9023418d5c26214af48bf5
932845a833c345a2c76aa8b80a53c37ba0b3890a
refs/heads/master
2023-08-18T02:29:20.835000
2023-08-10T17:09:57
2023-08-10T17:09:57
23,224,860
5
8
BSD-3-Clause
true
2023-08-04T14:49:59
2014-08-22T12:39:27
2022-10-04T16:40:59
2023-08-04T14:49:58
167,076
2
4
3
Java
false
false
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.orcid.consumer; import static java.util.Arrays.asList; import static java.util.Comparator.comparing; import static java.util.Comparator.naturalOrder; import static java.util.Comparator.nullsFirst; import static org.apache.commons.collections.CollectionUtils.isNotEmpty; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.commons.lang3.StringUtils; import org.dspace.content.DSpaceObject; import org.dspace.content.Item; import org.dspace.content.MetadataFieldName; import org.dspace.content.Relationship; import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.service.ItemService; import org.dspace.content.service.RelationshipService; import org.dspace.core.Context; import org.dspace.event.Consumer; import org.dspace.event.Event; import org.dspace.orcid.OrcidHistory; import org.dspace.orcid.OrcidOperation; import org.dspace.orcid.factory.OrcidServiceFactory; import org.dspace.orcid.model.OrcidEntityType; import org.dspace.orcid.model.factory.OrcidProfileSectionFactory; import org.dspace.orcid.service.OrcidHistoryService; import org.dspace.orcid.service.OrcidProfileSectionFactoryService; import org.dspace.orcid.service.OrcidQueueService; import org.dspace.orcid.service.OrcidSynchronizationService; import org.dspace.orcid.service.OrcidTokenService; import org.dspace.profile.OrcidProfileSyncPreference; import org.dspace.services.ConfigurationService; import org.dspace.services.factory.DSpaceServicesFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The consumer to fill the ORCID queue. The addition to the queue is made for * all archived items that meet one of these conditions: * <ul> * <li>are profiles already linked to orcid that have some modified sections to * be synchronized (based on the preferences set by the user)</li> * <li>are publications/fundings related to profile items linked to orcid (based * on the preferences set by the user)</li> * * </ul> * * @author Luca Giamminonni (luca.giamminonni at 4science.it) * */ public class OrcidQueueConsumer implements Consumer { private static final Logger LOGGER = LoggerFactory.getLogger(OrcidQueueConsumer.class); private OrcidQueueService orcidQueueService; private OrcidHistoryService orcidHistoryService; private OrcidTokenService orcidTokenService; private OrcidSynchronizationService orcidSynchronizationService; private ItemService itemService; private OrcidProfileSectionFactoryService profileSectionFactoryService; private ConfigurationService configurationService; private RelationshipService relationshipService; private List<UUID> alreadyConsumedItems = new ArrayList<>(); @Override public void initialize() throws Exception { OrcidServiceFactory orcidServiceFactory = OrcidServiceFactory.getInstance(); this.orcidQueueService = orcidServiceFactory.getOrcidQueueService(); this.orcidHistoryService = orcidServiceFactory.getOrcidHistoryService(); this.orcidSynchronizationService = orcidServiceFactory.getOrcidSynchronizationService(); this.orcidTokenService = orcidServiceFactory.getOrcidTokenService(); this.profileSectionFactoryService = orcidServiceFactory.getOrcidProfileSectionFactoryService(); this.configurationService = DSpaceServicesFactory.getInstance().getConfigurationService(); this.relationshipService = ContentServiceFactory.getInstance().getRelationshipService(); this.itemService = ContentServiceFactory.getInstance().getItemService(); } @Override public void consume(Context context, Event event) throws Exception { if (isOrcidSynchronizationDisabled()) { return; } DSpaceObject dso = event.getSubject(context); if (!(dso instanceof Item)) { return; } Item item = (Item) dso; if (!item.isArchived()) { return; } if (alreadyConsumedItems.contains(item.getID())) { return; } context.turnOffAuthorisationSystem(); try { consumeItem(context, item); } finally { context.restoreAuthSystemState(); } } /** * Consume the item if it is a profile or an ORCID entity. */ private void consumeItem(Context context, Item item) throws SQLException { String entityType = itemService.getEntityTypeLabel(item); if (entityType == null) { return; } if (OrcidEntityType.isValidEntityType(entityType)) { consumeEntity(context, item); } else if (entityType.equals(getProfileType())) { consumeProfile(context, item); } alreadyConsumedItems.add(item.getID()); } /** * Search for all related items to the given entity and create a new ORCID queue * record if one of this is a profile linked with ORCID and the entity item must * be synchronized with ORCID. */ private void consumeEntity(Context context, Item entity) throws SQLException { List<Item> relatedItems = findAllRelatedItems(context, entity); for (Item relatedItem : relatedItems) { if (isNotProfileItem(relatedItem) || isNotLinkedToOrcid(context, relatedItem)) { continue; } if (shouldNotBeSynchronized(relatedItem, entity) || isAlreadyQueued(context, relatedItem, entity)) { continue; } orcidQueueService.create(context, relatedItem, entity); } } private List<Item> findAllRelatedItems(Context context, Item entity) throws SQLException { return relationshipService.findByItem(context, entity).stream() .map(relationship -> getRelatedItem(entity, relationship)) .collect(Collectors.toList()); } private Item getRelatedItem(Item item, Relationship relationship) { return item.equals(relationship.getLeftItem()) ? relationship.getRightItem() : relationship.getLeftItem(); } /** * If the given profile item is linked with ORCID recalculate all the ORCID * queue records of the configured profile sections that can be synchronized. */ private void consumeProfile(Context context, Item item) throws SQLException { if (isNotLinkedToOrcid(context, item)) { return; } for (OrcidProfileSectionFactory factory : getAllProfileSectionFactories(item)) { String sectionType = factory.getProfileSectionType().name(); orcidQueueService.deleteByEntityAndRecordType(context, item, sectionType); if (isProfileSectionSynchronizationDisabled(context, item, factory)) { continue; } List<String> signatures = factory.getMetadataSignatures(context, item); List<OrcidHistory> historyRecords = findSuccessfullyOrcidHistoryRecords(context, item, sectionType); createInsertionRecordForNewSignatures(context, item, historyRecords, factory, signatures); createDeletionRecordForNoMorePresentSignatures(context, item, historyRecords, factory, signatures); } } private boolean isProfileSectionSynchronizationDisabled(Context context, Item item, OrcidProfileSectionFactory factory) { List<OrcidProfileSyncPreference> preferences = this.orcidSynchronizationService.getProfilePreferences(item); return !preferences.contains(factory.getSynchronizationPreference()); } /** * Add new INSERTION record in the ORCID queue based on the metadata signatures * calculated from the current item state. */ private void createInsertionRecordForNewSignatures(Context context, Item item, List<OrcidHistory> historyRecords, OrcidProfileSectionFactory factory, List<String> signatures) throws SQLException { String sectionType = factory.getProfileSectionType().name(); for (String signature : signatures) { if (isNotAlreadySynchronized(historyRecords, signature)) { String description = factory.getDescription(context, item, signature); orcidQueueService.createProfileInsertionRecord(context, item, description, sectionType, signature); } } } /** * Add new DELETION records in the ORCID queue for metadata signature presents * in the ORCID history no more present in the metadata signatures calculated * from the current item state. */ private void createDeletionRecordForNoMorePresentSignatures(Context context, Item profile, List<OrcidHistory> historyRecords, OrcidProfileSectionFactory factory, List<String> signatures) throws SQLException { String sectionType = factory.getProfileSectionType().name(); for (OrcidHistory historyRecord : historyRecords) { String storedSignature = historyRecord.getMetadata(); String putCode = historyRecord.getPutCode(); String description = historyRecord.getDescription(); if (signatures.contains(storedSignature) || isAlreadyDeleted(historyRecords, historyRecord)) { continue; } if (StringUtils.isBlank(putCode)) { LOGGER.warn("The orcid history record with id {} should have a not blank put code", historyRecord.getID()); continue; } orcidQueueService.createProfileDeletionRecord(context, profile, description, sectionType, storedSignature, putCode); } } private List<OrcidHistory> findSuccessfullyOrcidHistoryRecords(Context context, Item item, String sectionType) throws SQLException { return orcidHistoryService.findSuccessfullyRecordsByEntityAndType(context, item, sectionType); } private boolean isNotAlreadySynchronized(List<OrcidHistory> records, String signature) { return getLastOperation(records, signature) .map(operation -> operation == OrcidOperation.DELETE) .orElse(Boolean.TRUE); } private boolean isAlreadyDeleted(List<OrcidHistory> records, OrcidHistory historyRecord) { if (historyRecord.getOperation() == OrcidOperation.DELETE) { return true; } return findDeletedHistoryRecordsBySignature(records, historyRecord.getMetadata()) .anyMatch(record -> record.getTimestamp().after(historyRecord.getTimestamp())); } private Stream<OrcidHistory> findDeletedHistoryRecordsBySignature(List<OrcidHistory> records, String signature) { return records.stream() .filter(record -> signature.equals(record.getMetadata())) .filter(record -> record.getOperation() == OrcidOperation.DELETE); } private Optional<OrcidOperation> getLastOperation(List<OrcidHistory> records, String signature) { return records.stream() .filter(record -> signature.equals(record.getMetadata())) .sorted(comparing(OrcidHistory::getTimestamp, nullsFirst(naturalOrder())).reversed()) .map(OrcidHistory::getOperation) .findFirst(); } private boolean isAlreadyQueued(Context context, Item profileItem, Item entity) throws SQLException { return isNotEmpty(orcidQueueService.findByProfileItemAndEntity(context, profileItem, entity)); } private boolean isNotLinkedToOrcid(Context context, Item profileItemItem) { return hasNotOrcidAccessToken(context, profileItemItem) || getMetadataValue(profileItemItem, "person.identifier.orcid") == null; } private boolean hasNotOrcidAccessToken(Context context, Item profileItemItem) { return orcidTokenService.findByProfileItem(context, profileItemItem) == null; } private boolean shouldNotBeSynchronized(Item profileItem, Item entity) { return !orcidSynchronizationService.isSynchronizationAllowed(profileItem, entity); } private boolean isNotProfileItem(Item profileItemItem) { return !getProfileType().equals(itemService.getEntityTypeLabel(profileItemItem)); } private String getMetadataValue(Item item, String metadataField) { return itemService.getMetadataFirstValue(item, new MetadataFieldName(metadataField), Item.ANY); } private List<OrcidProfileSectionFactory> getAllProfileSectionFactories(Item item) { return this.profileSectionFactoryService.findByPreferences(asList(OrcidProfileSyncPreference.values())); } private String getProfileType() { return configurationService.getProperty("researcher-profile.entity-type", "Person"); } private boolean isOrcidSynchronizationDisabled() { return !configurationService.getBooleanProperty("orcid.synchronization-enabled", true); } @Override public void end(Context context) throws Exception { alreadyConsumedItems.clear(); } @Override public void finish(Context context) throws Exception { // nothing to do } }
UTF-8
Java
13,486
java
OrcidQueueConsumer.java
Java
[ { "context": "s set by the user)</li>\n * \n * </ul>\n *\n * @author Luca Giamminonni (luca.giamminonni at 4science.it)\n *\n */\npublic c", "end": 2375, "score": 0.9998732209205627, "start": 2359, "tag": "NAME", "value": "Luca Giamminonni" } ]
null
[]
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.orcid.consumer; import static java.util.Arrays.asList; import static java.util.Comparator.comparing; import static java.util.Comparator.naturalOrder; import static java.util.Comparator.nullsFirst; import static org.apache.commons.collections.CollectionUtils.isNotEmpty; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.commons.lang3.StringUtils; import org.dspace.content.DSpaceObject; import org.dspace.content.Item; import org.dspace.content.MetadataFieldName; import org.dspace.content.Relationship; import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.service.ItemService; import org.dspace.content.service.RelationshipService; import org.dspace.core.Context; import org.dspace.event.Consumer; import org.dspace.event.Event; import org.dspace.orcid.OrcidHistory; import org.dspace.orcid.OrcidOperation; import org.dspace.orcid.factory.OrcidServiceFactory; import org.dspace.orcid.model.OrcidEntityType; import org.dspace.orcid.model.factory.OrcidProfileSectionFactory; import org.dspace.orcid.service.OrcidHistoryService; import org.dspace.orcid.service.OrcidProfileSectionFactoryService; import org.dspace.orcid.service.OrcidQueueService; import org.dspace.orcid.service.OrcidSynchronizationService; import org.dspace.orcid.service.OrcidTokenService; import org.dspace.profile.OrcidProfileSyncPreference; import org.dspace.services.ConfigurationService; import org.dspace.services.factory.DSpaceServicesFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The consumer to fill the ORCID queue. The addition to the queue is made for * all archived items that meet one of these conditions: * <ul> * <li>are profiles already linked to orcid that have some modified sections to * be synchronized (based on the preferences set by the user)</li> * <li>are publications/fundings related to profile items linked to orcid (based * on the preferences set by the user)</li> * * </ul> * * @author <NAME> (luca.giamminonni at 4science.it) * */ public class OrcidQueueConsumer implements Consumer { private static final Logger LOGGER = LoggerFactory.getLogger(OrcidQueueConsumer.class); private OrcidQueueService orcidQueueService; private OrcidHistoryService orcidHistoryService; private OrcidTokenService orcidTokenService; private OrcidSynchronizationService orcidSynchronizationService; private ItemService itemService; private OrcidProfileSectionFactoryService profileSectionFactoryService; private ConfigurationService configurationService; private RelationshipService relationshipService; private List<UUID> alreadyConsumedItems = new ArrayList<>(); @Override public void initialize() throws Exception { OrcidServiceFactory orcidServiceFactory = OrcidServiceFactory.getInstance(); this.orcidQueueService = orcidServiceFactory.getOrcidQueueService(); this.orcidHistoryService = orcidServiceFactory.getOrcidHistoryService(); this.orcidSynchronizationService = orcidServiceFactory.getOrcidSynchronizationService(); this.orcidTokenService = orcidServiceFactory.getOrcidTokenService(); this.profileSectionFactoryService = orcidServiceFactory.getOrcidProfileSectionFactoryService(); this.configurationService = DSpaceServicesFactory.getInstance().getConfigurationService(); this.relationshipService = ContentServiceFactory.getInstance().getRelationshipService(); this.itemService = ContentServiceFactory.getInstance().getItemService(); } @Override public void consume(Context context, Event event) throws Exception { if (isOrcidSynchronizationDisabled()) { return; } DSpaceObject dso = event.getSubject(context); if (!(dso instanceof Item)) { return; } Item item = (Item) dso; if (!item.isArchived()) { return; } if (alreadyConsumedItems.contains(item.getID())) { return; } context.turnOffAuthorisationSystem(); try { consumeItem(context, item); } finally { context.restoreAuthSystemState(); } } /** * Consume the item if it is a profile or an ORCID entity. */ private void consumeItem(Context context, Item item) throws SQLException { String entityType = itemService.getEntityTypeLabel(item); if (entityType == null) { return; } if (OrcidEntityType.isValidEntityType(entityType)) { consumeEntity(context, item); } else if (entityType.equals(getProfileType())) { consumeProfile(context, item); } alreadyConsumedItems.add(item.getID()); } /** * Search for all related items to the given entity and create a new ORCID queue * record if one of this is a profile linked with ORCID and the entity item must * be synchronized with ORCID. */ private void consumeEntity(Context context, Item entity) throws SQLException { List<Item> relatedItems = findAllRelatedItems(context, entity); for (Item relatedItem : relatedItems) { if (isNotProfileItem(relatedItem) || isNotLinkedToOrcid(context, relatedItem)) { continue; } if (shouldNotBeSynchronized(relatedItem, entity) || isAlreadyQueued(context, relatedItem, entity)) { continue; } orcidQueueService.create(context, relatedItem, entity); } } private List<Item> findAllRelatedItems(Context context, Item entity) throws SQLException { return relationshipService.findByItem(context, entity).stream() .map(relationship -> getRelatedItem(entity, relationship)) .collect(Collectors.toList()); } private Item getRelatedItem(Item item, Relationship relationship) { return item.equals(relationship.getLeftItem()) ? relationship.getRightItem() : relationship.getLeftItem(); } /** * If the given profile item is linked with ORCID recalculate all the ORCID * queue records of the configured profile sections that can be synchronized. */ private void consumeProfile(Context context, Item item) throws SQLException { if (isNotLinkedToOrcid(context, item)) { return; } for (OrcidProfileSectionFactory factory : getAllProfileSectionFactories(item)) { String sectionType = factory.getProfileSectionType().name(); orcidQueueService.deleteByEntityAndRecordType(context, item, sectionType); if (isProfileSectionSynchronizationDisabled(context, item, factory)) { continue; } List<String> signatures = factory.getMetadataSignatures(context, item); List<OrcidHistory> historyRecords = findSuccessfullyOrcidHistoryRecords(context, item, sectionType); createInsertionRecordForNewSignatures(context, item, historyRecords, factory, signatures); createDeletionRecordForNoMorePresentSignatures(context, item, historyRecords, factory, signatures); } } private boolean isProfileSectionSynchronizationDisabled(Context context, Item item, OrcidProfileSectionFactory factory) { List<OrcidProfileSyncPreference> preferences = this.orcidSynchronizationService.getProfilePreferences(item); return !preferences.contains(factory.getSynchronizationPreference()); } /** * Add new INSERTION record in the ORCID queue based on the metadata signatures * calculated from the current item state. */ private void createInsertionRecordForNewSignatures(Context context, Item item, List<OrcidHistory> historyRecords, OrcidProfileSectionFactory factory, List<String> signatures) throws SQLException { String sectionType = factory.getProfileSectionType().name(); for (String signature : signatures) { if (isNotAlreadySynchronized(historyRecords, signature)) { String description = factory.getDescription(context, item, signature); orcidQueueService.createProfileInsertionRecord(context, item, description, sectionType, signature); } } } /** * Add new DELETION records in the ORCID queue for metadata signature presents * in the ORCID history no more present in the metadata signatures calculated * from the current item state. */ private void createDeletionRecordForNoMorePresentSignatures(Context context, Item profile, List<OrcidHistory> historyRecords, OrcidProfileSectionFactory factory, List<String> signatures) throws SQLException { String sectionType = factory.getProfileSectionType().name(); for (OrcidHistory historyRecord : historyRecords) { String storedSignature = historyRecord.getMetadata(); String putCode = historyRecord.getPutCode(); String description = historyRecord.getDescription(); if (signatures.contains(storedSignature) || isAlreadyDeleted(historyRecords, historyRecord)) { continue; } if (StringUtils.isBlank(putCode)) { LOGGER.warn("The orcid history record with id {} should have a not blank put code", historyRecord.getID()); continue; } orcidQueueService.createProfileDeletionRecord(context, profile, description, sectionType, storedSignature, putCode); } } private List<OrcidHistory> findSuccessfullyOrcidHistoryRecords(Context context, Item item, String sectionType) throws SQLException { return orcidHistoryService.findSuccessfullyRecordsByEntityAndType(context, item, sectionType); } private boolean isNotAlreadySynchronized(List<OrcidHistory> records, String signature) { return getLastOperation(records, signature) .map(operation -> operation == OrcidOperation.DELETE) .orElse(Boolean.TRUE); } private boolean isAlreadyDeleted(List<OrcidHistory> records, OrcidHistory historyRecord) { if (historyRecord.getOperation() == OrcidOperation.DELETE) { return true; } return findDeletedHistoryRecordsBySignature(records, historyRecord.getMetadata()) .anyMatch(record -> record.getTimestamp().after(historyRecord.getTimestamp())); } private Stream<OrcidHistory> findDeletedHistoryRecordsBySignature(List<OrcidHistory> records, String signature) { return records.stream() .filter(record -> signature.equals(record.getMetadata())) .filter(record -> record.getOperation() == OrcidOperation.DELETE); } private Optional<OrcidOperation> getLastOperation(List<OrcidHistory> records, String signature) { return records.stream() .filter(record -> signature.equals(record.getMetadata())) .sorted(comparing(OrcidHistory::getTimestamp, nullsFirst(naturalOrder())).reversed()) .map(OrcidHistory::getOperation) .findFirst(); } private boolean isAlreadyQueued(Context context, Item profileItem, Item entity) throws SQLException { return isNotEmpty(orcidQueueService.findByProfileItemAndEntity(context, profileItem, entity)); } private boolean isNotLinkedToOrcid(Context context, Item profileItemItem) { return hasNotOrcidAccessToken(context, profileItemItem) || getMetadataValue(profileItemItem, "person.identifier.orcid") == null; } private boolean hasNotOrcidAccessToken(Context context, Item profileItemItem) { return orcidTokenService.findByProfileItem(context, profileItemItem) == null; } private boolean shouldNotBeSynchronized(Item profileItem, Item entity) { return !orcidSynchronizationService.isSynchronizationAllowed(profileItem, entity); } private boolean isNotProfileItem(Item profileItemItem) { return !getProfileType().equals(itemService.getEntityTypeLabel(profileItemItem)); } private String getMetadataValue(Item item, String metadataField) { return itemService.getMetadataFirstValue(item, new MetadataFieldName(metadataField), Item.ANY); } private List<OrcidProfileSectionFactory> getAllProfileSectionFactories(Item item) { return this.profileSectionFactoryService.findByPreferences(asList(OrcidProfileSyncPreference.values())); } private String getProfileType() { return configurationService.getProperty("researcher-profile.entity-type", "Person"); } private boolean isOrcidSynchronizationDisabled() { return !configurationService.getBooleanProperty("orcid.synchronization-enabled", true); } @Override public void end(Context context) throws Exception { alreadyConsumedItems.clear(); } @Override public void finish(Context context) throws Exception { // nothing to do } }
13,476
0.715705
0.715409
358
36.670391
35.117088
117
false
false
0
0
0
0
0
0
0.581006
false
false
4
c1d6f33a63d2d600d0503bac1bb766ae7db62bee
3,118,146,313,809
a498267df5c672da259f2810e41830bec1d47adf
/mobile/src/main/java/com/alexstyl/specialdates/ui/widget/LetterPainter.java
38156f6170fce944b2f7304a955e2deedd15facf
[ "MIT" ]
permissive
danybony/Memento-Namedays
https://github.com/danybony/Memento-Namedays
9f0fcf6db52e223250d752c31a667fe5e758a334
1bf6030d1cd418a5aae6f6e0d88d617c312bf7aa
refs/heads/master
2021-01-17T23:05:56.966000
2016-09-06T22:22:12
2016-09-06T22:22:12
68,078,712
1
0
null
true
2016-09-13T08:29:17
2016-09-13T05:55:13
2016-09-13T05:55:14
2016-09-13T07:32:33
1,043
0
0
0
Java
null
null
package com.alexstyl.specialdates.ui.widget; import android.content.res.Resources; import com.alexstyl.specialdates.R; public class LetterPainter { /** * The different color variants to draw */ private static final int[] mVariants = { R.color.avatar_variant_1, R.color.avatar_variant_2, R.color.avatar_variant_3, R.color.avatar_variant_4, R.color.avatar_variant_5, }; private static final int VARIANT_COUNT; static { VARIANT_COUNT = mVariants.length; } public static int getVariant(Resources res, int i) { if (i < 0) { i = i * (-1); } if (i >= VARIANT_COUNT) { i = (i % VARIANT_COUNT); if (i >= VARIANT_COUNT) { i = i / VARIANT_COUNT; } } return res.getColor(mVariants[i]); } }
UTF-8
Java
901
java
LetterPainter.java
Java
[ { "context": "package com.alexstyl.specialdates.ui.widget;\n\nimport android.content.r", "end": 20, "score": 0.9081815481185913, "start": 16, "tag": "USERNAME", "value": "styl" }, { "context": "import android.content.res.Resources;\n\nimport com.alexstyl.specialdates.R;\n\npublic class LetterPainter {\n\n ", "end": 104, "score": 0.8175121545791626, "start": 96, "tag": "USERNAME", "value": "alexstyl" } ]
null
[]
package com.alexstyl.specialdates.ui.widget; import android.content.res.Resources; import com.alexstyl.specialdates.R; public class LetterPainter { /** * The different color variants to draw */ private static final int[] mVariants = { R.color.avatar_variant_1, R.color.avatar_variant_2, R.color.avatar_variant_3, R.color.avatar_variant_4, R.color.avatar_variant_5, }; private static final int VARIANT_COUNT; static { VARIANT_COUNT = mVariants.length; } public static int getVariant(Resources res, int i) { if (i < 0) { i = i * (-1); } if (i >= VARIANT_COUNT) { i = (i % VARIANT_COUNT); if (i >= VARIANT_COUNT) { i = i / VARIANT_COUNT; } } return res.getColor(mVariants[i]); } }
901
0.537181
0.529412
39
22.076923
17.722048
56
false
false
0
0
0
0
0
0
0.410256
false
false
4
a438be5df9280e688140e26c7c6e95dc7b2d87c0
36,850,819,417,367
80afe5d514471b5c570d918562f1c7c7d3488cf6
/lesson10/src/Bai13/Test.java
ea402b4d14e490892154a8e213263df987e541af
[]
no_license
DuyToi140299/JavaWeb-Programimng
https://github.com/DuyToi140299/JavaWeb-Programimng
2129d6dc4acb5b7de072ce0266ba768f8dda6b1b
34fa17b840c32c305efa21a6dc451c8379ec2a71
refs/heads/master
2023-06-10T01:53:27.765000
2023-05-31T09:09:11
2023-05-31T09:09:11
171,900,709
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 Bai13; /** * * @author Admin */ public class Test { public static void main(String[] args) { HinhBinhHanh obj1 = new HinhBinhHanh(); obj1.input(); System.out.println(obj1.chuVi()); System.out.println(obj1.dienTich()); HinhChuNhat obj3 = new HinhChuNhat(); obj3.input(); System.out.println(obj3.chuVi()); System.out.println(obj3.dienTich()); } }
UTF-8
Java
638
java
Test.java
Java
[ { "context": " the editor.\n */\npackage Bai13;\n\n/**\n *\n * @author Admin\n */\npublic class Test {\n public static void ma", "end": 224, "score": 0.9611018300056458, "start": 219, "tag": "USERNAME", "value": "Admin" } ]
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 Bai13; /** * * @author Admin */ public class Test { public static void main(String[] args) { HinhBinhHanh obj1 = new HinhBinhHanh(); obj1.input(); System.out.println(obj1.chuVi()); System.out.println(obj1.dienTich()); HinhChuNhat obj3 = new HinhChuNhat(); obj3.input(); System.out.println(obj3.chuVi()); System.out.println(obj3.dienTich()); } }
638
0.609718
0.594044
26
23.538462
21.417517
79
false
false
0
0
0
0
0
0
0.461538
false
false
4
d5d45237ef0e8f07d2801745084f75b093b7a2d6
592,705,549,032
5bbb7b33bdb79c37aec6b0c6ba3a71e87ba718ae
/src/main/java/org/pergamum/battlesnek/api/Request.java
d1ea00601cfb5385e609b5ac80ce0afb5f551dfc
[]
no_license
GeoffreyPeart/Battlesnek
https://github.com/GeoffreyPeart/Battlesnek
77be078a477443d176a5f5da2676eff8221f772d
81061a0c16a98ca8cdabf44f684caf37e53c05f2
refs/heads/master
2023-08-12T10:40:37.911000
2021-10-06T03:58:56
2021-10-06T03:58:56
349,770,269
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.pergamum.battlesnek.api; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; @Data @Slf4j @AllArgsConstructor @NoArgsConstructor public class Request { private Game game; private int turn; private Board board; private Battlesnake you; }
UTF-8
Java
324
java
Request.java
Java
[]
null
[]
package org.pergamum.battlesnek.api; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; @Data @Slf4j @AllArgsConstructor @NoArgsConstructor public class Request { private Game game; private int turn; private Board board; private Battlesnake you; }
324
0.811728
0.802469
17
18.058823
11.623863
36
false
false
0
0
0
0
0
0
0.764706
false
false
4
e60f2b0d0cd0f9be872e2d5326e9c18fc6ba09bb
38,371,237,829,551
2aa887e6d5f4f76633ea4d94ab1cded57bb57516
/src/main/java/com/vpoesmann/soutien/Cochon.java
97da55cb34f2f2047cd1dcecef5a33b29bf0e347
[ "MIT" ]
permissive
vpoesmann-bts/coursJava
https://github.com/vpoesmann-bts/coursJava
761701cdd140294f751afb24c3842591b7187dec
a194891e4e892812caa7b4e692bd19785c11c61a
refs/heads/main
2023-03-17T02:44:57.727000
2021-03-12T10:20:31
2021-03-12T10:20:31
346,974,966
0
0
MIT
false
2021-03-12T09:15:21
2021-03-12T07:11:08
2021-03-12T07:11:11
2021-03-12T09:15:21
5
0
0
0
null
false
false
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.vpoesmann.soutien; /** * * @author sogeking */ public class Cochon { private String prenom; private int taille; private int age; public Cochon(String prenom, int taille, int age) { this.prenom = prenom; this.taille = taille; this.age = age; } public String getPrenom() { return prenom; } public void attaquer() { System.out.println(prenom + " attaque !"); } }
UTF-8
Java
644
java
Cochon.java
Java
[ { "context": "\npackage com.vpoesmann.soutien;\n\n/**\n *\n * @author sogeking\n */\npublic class Cochon {\n private String pren", "end": 243, "score": 0.9995663166046143, "start": 235, "tag": "USERNAME", "value": "sogeking" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.vpoesmann.soutien; /** * * @author sogeking */ public class Cochon { private String prenom; private int taille; private int age; public Cochon(String prenom, int taille, int age) { this.prenom = prenom; this.taille = taille; this.age = age; } public String getPrenom() { return prenom; } public void attaquer() { System.out.println(prenom + " attaque !"); } }
644
0.625776
0.625776
30
20.466667
19.869127
79
false
false
0
0
0
0
0
0
0.466667
false
false
4
bf8a9fdfaabce8321c060f05edbea6d43823372d
10,230,612,154,401
6cdca38020300e1b9e5eaffe5c5f72009d53be95
/app/src/main/java/com/fastbuyapp/omar/fastbuy/TutorialAdapter.java
48f8ef680b5b91a05d5bcb37b8384f3ebf947f0d
[]
no_license
antver/FastBuy
https://github.com/antver/FastBuy
7cb4069321c1f0f882c26a2effda58efef9e3bcd
e757e1c9918204a1509e866a611fb164713d28ef
refs/heads/master
2023-01-03T18:51:36.120000
2020-11-02T13:59:34
2020-11-02T13:59:34
285,624,569
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.fastbuyapp.omar.fastbuy; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.fastbuyapp.omar.fastbuy.entidades.Tutorial_Item; import java.util.List; public class TutorialAdapter extends RecyclerView.Adapter<TutorialAdapter.TutorialViewHolder> { private List<Tutorial_Item> tutorialItems; public TutorialAdapter(List<Tutorial_Item> tutorialItems) { this.tutorialItems = tutorialItems; } @NonNull @Override public TutorialViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { return new TutorialViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_tutorial, parent, false)); } @Override public void onBindViewHolder(@NonNull TutorialViewHolder holder, int position) { holder.setTutorialData(tutorialItems.get(position)); } @Override public int getItemCount() { return tutorialItems.size(); } class TutorialViewHolder extends RecyclerView.ViewHolder{ private ImageView imagenTuto; public TutorialViewHolder(@NonNull View itemView) { super(itemView); imagenTuto = (ImageView) itemView.findViewById(R.id.imgTutorial); } void setTutorialData(Tutorial_Item tutorial_item){ imagenTuto.setImageResource(tutorial_item.getImagen()); } } }
UTF-8
Java
1,532
java
TutorialAdapter.java
Java
[]
null
[]
package com.fastbuyapp.omar.fastbuy; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.fastbuyapp.omar.fastbuy.entidades.Tutorial_Item; import java.util.List; public class TutorialAdapter extends RecyclerView.Adapter<TutorialAdapter.TutorialViewHolder> { private List<Tutorial_Item> tutorialItems; public TutorialAdapter(List<Tutorial_Item> tutorialItems) { this.tutorialItems = tutorialItems; } @NonNull @Override public TutorialViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { return new TutorialViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_tutorial, parent, false)); } @Override public void onBindViewHolder(@NonNull TutorialViewHolder holder, int position) { holder.setTutorialData(tutorialItems.get(position)); } @Override public int getItemCount() { return tutorialItems.size(); } class TutorialViewHolder extends RecyclerView.ViewHolder{ private ImageView imagenTuto; public TutorialViewHolder(@NonNull View itemView) { super(itemView); imagenTuto = (ImageView) itemView.findViewById(R.id.imgTutorial); } void setTutorialData(Tutorial_Item tutorial_item){ imagenTuto.setImageResource(tutorial_item.getImagen()); } } }
1,532
0.731071
0.731071
51
29.039215
30.682409
127
false
false
0
0
0
0
0
0
0.431373
false
false
4
240f9999e97e52404727eaa8eff9275c95fc16b9
17,136,919,544,822
6adee814df902144d3d1b6a1790754d4420947e5
/src/test/java/RockPaperScissorsAppTest.java
447146120f106f7ee83931fe79c99b37fea30c2c
[]
no_license
mklgallegos/rock-paper-scissors
https://github.com/mklgallegos/rock-paper-scissors
49a37404376e7336c76ff418c20f71eed401fc78
27c53a03f21bde326b36401fa8e88e37a7aec074
refs/heads/master
2018-01-10T11:23:05.016000
2016-02-11T01:43:42
2016-02-11T01:43:42
51,458,361
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
//import JUnit import org.junit.*; import static org.junit.Assert.*; public class RockPaperScissorsAppTest { @Test public void detectTie_returnsTrueforTie_true() { RockPaperScissorsApp rockPaperScissorsApp = new RockPaperScissorsApp(); assertEquals(true, rockPaperScissorsApp.detectTie("rock","rock")); } @Test public void detectTie_returnsTrueforTie_false() { RockPaperScissorsApp rockPaperScissorsApp = new RockPaperScissorsApp(); assertEquals(false, rockPaperScissorsApp.detectTie("rock","paper")); } @Test public void rockPaperScissors_returnsTrueforRockScissors_true() { RockPaperScissorsApp rockPaperScissorsApp = new RockPaperScissorsApp(); assertEquals(true, rockPaperScissorsApp.rockPaperScissors("rockscissors")); } @Test public void rockPaperScissors_returnsFalseforRockPaper_false() { RockPaperScissorsApp rockPaperScissorsApp = new RockPaperScissorsApp(); assertEquals(false, rockPaperScissorsApp.rockPaperScissors("rockpaper")); } @Test public void rockPaperScissors_returnsTrueforPaperRock_true() { RockPaperScissorsApp rockPaperScissorsApp = new RockPaperScissorsApp(); assertEquals(true, rockPaperScissorsApp.rockPaperScissors("paperrock")); } @Test public void rockPaperScissors_returnsTrueforPaperScissors_false() { RockPaperScissorsApp rockPaperScissorsApp = new RockPaperScissorsApp(); assertEquals(false, rockPaperScissorsApp.rockPaperScissors("paperscissors")); } @Test public void rockPaperScissors_returnsTrueforScissorsRock_false() { RockPaperScissorsApp rockPaperScissorsApp = new RockPaperScissorsApp(); assertEquals(false, rockPaperScissorsApp.rockPaperScissors("scissorsrock")); } @Test public void rockPaperScissors_returnsTrueforScissorsPaper_true() { RockPaperScissorsApp rockPaperScissorsApp = new RockPaperScissorsApp(); assertEquals(true, rockPaperScissorsApp.rockPaperScissors("scissorspaper")); } @Test public void generateMove_returnsRockPaperOrScissors_rockpaperOrscissors() { RockPaperScissorsApp rockPaperScissorsApp = new RockPaperScissorsApp(); String computerMove = rockPaperScissorsApp.generateMove(); assertEquals(true, computerMove instanceof String); } } // import org.fluentlenium.adapter.FluentTest; // import org.junit.ClassRule; // import org.junit.Test; // import org.openqa.selenium.WebDriver; // import org.openqa.selenium.htmlunit.HtmlUnitDriver; // import static org.assertj.core.api.Assertions.assertThat; // public class AppTest extends FluentTest { // public WebDriver webDriver = new HtmlUnitDriver(); // public WebDriver getDefaultDriver() { // return webDriver; // } // @ClassRule // public static ServerRule server = new ServerRule(); // @Test // public void rootTest() { // goTo("http://localhost:4567/"); // assertThat(pageSource()).contains("Leap year detector"); // } // @Test // public void isALeapYear() { // goTo("http://localhost:4567"); // fill("#year").with("2004"); // submit(".btn"); // assertThat(pageSource()).contains("2004 is a leap year!"); // } // @Test // public void isNotALeapYear() { // goTo("http://localhost:4567"); // fill("#year").with("2003"); // submit(".btn"); // assertThat(pageSource()).contains("2003 is not a leap year!"); // } // }
UTF-8
Java
3,358
java
RockPaperScissorsAppTest.java
Java
[]
null
[]
//import JUnit import org.junit.*; import static org.junit.Assert.*; public class RockPaperScissorsAppTest { @Test public void detectTie_returnsTrueforTie_true() { RockPaperScissorsApp rockPaperScissorsApp = new RockPaperScissorsApp(); assertEquals(true, rockPaperScissorsApp.detectTie("rock","rock")); } @Test public void detectTie_returnsTrueforTie_false() { RockPaperScissorsApp rockPaperScissorsApp = new RockPaperScissorsApp(); assertEquals(false, rockPaperScissorsApp.detectTie("rock","paper")); } @Test public void rockPaperScissors_returnsTrueforRockScissors_true() { RockPaperScissorsApp rockPaperScissorsApp = new RockPaperScissorsApp(); assertEquals(true, rockPaperScissorsApp.rockPaperScissors("rockscissors")); } @Test public void rockPaperScissors_returnsFalseforRockPaper_false() { RockPaperScissorsApp rockPaperScissorsApp = new RockPaperScissorsApp(); assertEquals(false, rockPaperScissorsApp.rockPaperScissors("rockpaper")); } @Test public void rockPaperScissors_returnsTrueforPaperRock_true() { RockPaperScissorsApp rockPaperScissorsApp = new RockPaperScissorsApp(); assertEquals(true, rockPaperScissorsApp.rockPaperScissors("paperrock")); } @Test public void rockPaperScissors_returnsTrueforPaperScissors_false() { RockPaperScissorsApp rockPaperScissorsApp = new RockPaperScissorsApp(); assertEquals(false, rockPaperScissorsApp.rockPaperScissors("paperscissors")); } @Test public void rockPaperScissors_returnsTrueforScissorsRock_false() { RockPaperScissorsApp rockPaperScissorsApp = new RockPaperScissorsApp(); assertEquals(false, rockPaperScissorsApp.rockPaperScissors("scissorsrock")); } @Test public void rockPaperScissors_returnsTrueforScissorsPaper_true() { RockPaperScissorsApp rockPaperScissorsApp = new RockPaperScissorsApp(); assertEquals(true, rockPaperScissorsApp.rockPaperScissors("scissorspaper")); } @Test public void generateMove_returnsRockPaperOrScissors_rockpaperOrscissors() { RockPaperScissorsApp rockPaperScissorsApp = new RockPaperScissorsApp(); String computerMove = rockPaperScissorsApp.generateMove(); assertEquals(true, computerMove instanceof String); } } // import org.fluentlenium.adapter.FluentTest; // import org.junit.ClassRule; // import org.junit.Test; // import org.openqa.selenium.WebDriver; // import org.openqa.selenium.htmlunit.HtmlUnitDriver; // import static org.assertj.core.api.Assertions.assertThat; // public class AppTest extends FluentTest { // public WebDriver webDriver = new HtmlUnitDriver(); // public WebDriver getDefaultDriver() { // return webDriver; // } // @ClassRule // public static ServerRule server = new ServerRule(); // @Test // public void rootTest() { // goTo("http://localhost:4567/"); // assertThat(pageSource()).contains("Leap year detector"); // } // @Test // public void isALeapYear() { // goTo("http://localhost:4567"); // fill("#year").with("2004"); // submit(".btn"); // assertThat(pageSource()).contains("2004 is a leap year!"); // } // @Test // public void isNotALeapYear() { // goTo("http://localhost:4567"); // fill("#year").with("2003"); // submit(".btn"); // assertThat(pageSource()).contains("2003 is not a leap year!"); // } // }
3,358
0.734961
0.726623
102
31.931372
29.614603
81
false
false
0
0
0
0
0
0
0.5
false
false
4
55f4ee899bcae76ee05fb6fd5d9b16d38a4c5fde
27,659,589,415,187
512397a9abaeae96735983596c0024c702d7d172
/src/main/java/com/zj/system/dao/impl/WeekAttendDaoImpl.java
ac872fb5a65b2c4823f5038a9e3c470b62e31c5d
[]
no_license
zhuangwentao/shop-server
https://github.com/zhuangwentao/shop-server
01da792724eacbfbccb0565eae074cac1edf26f4
14faf8bccdedea61779c135bb4e7df324b9d9c75
refs/heads/master
2017-10-30T15:34:09.963000
2016-07-26T07:53:47
2016-07-26T07:53:47
64,199,829
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.zj.system.dao.impl; import com.zj.common.persistence.impl.BaseDaoImpl; import com.zj.common.web.PageResult; import com.zj.system.dao.WeekAttendDao; import com.zj.system.entity.WeekAttend; import com.zj.system.utils.DateUtil; import org.springframework.stereotype.Repository; import java.util.ArrayList; import java.util.List; /** * 作者:钱剑锋 * 时间:4/12/2016 */ @Repository public class WeekAttendDaoImpl extends BaseDaoImpl<WeekAttend> implements WeekAttendDao { @Override public WeekAttend getWeekAttend(WeekAttend wa) { String hql = "from WeekAttend where employeeid = '"+ wa.getEmployeeid() +"' and monday = '"+ wa.getMonday() +"' and sunday = '"+ wa.getSunday() +"'"; List<WeekAttend> l = this.query(hql,null); if (l != null && l.size() > 0) { return l.get(0); } return null; } @Override public PageResult<WeekAttend> findWeekAttendForPage(Integer currentPage, Integer pageSize, WeekAttend weekAttend) { String start = DateUtil.dateToString(DateUtil.getThisMonday(DateUtil.stringToDate(weekAttend.getMonday(),"yyyy-MM-dd")),"yyyy-MM-dd"); String end = DateUtil.dateToString(DateUtil.getThisSunday(DateUtil.stringToDate(weekAttend.getSunday(),"yyyy-MM-dd")),"yyyy-MM-dd"); String sql = "select wa.shop_id,wa.monday,wa.sunday,sum(wa.money) from week_attend wa,shop_employee se where wa.employeeid = se.employeeid and se.employeetype = '2' and wa.shop_id like '%"+ weekAttend.getShopId() +"%' and wa.monday >= '"+ start +"' and wa.sunday <= '"+ end +"' group by wa.shop_id,wa.monday"; String sqlCount = "select count(*) from week_attend wa,shop_employee se where wa.employeeid = se.employeeid and se.employeetype = '2' and wa.shop_id like '%"+ weekAttend.getShopId() +"%' and wa.monday >= '"+ start +"' and wa.sunday <= '"+ end +"' group by wa.shop_id,wa.monday"; PageResult<Object[]> list = this.nativeQuerySQLObject(sql, sqlCount, null, currentPage, pageSize); PageResult<WeekAttend> result = new PageResult<WeekAttend>(); //封装结果数据 result.setCurrentIndex(list.getCurrentIndex()); result.setCurrentPage(list.getCurrentPage()); result.setPageSize(list.getPageSize()); result.setTotalCount(list.getTotalCount()); result.setTotalPage(list.getTotalPage()); List<WeekAttend> weekAttends = new ArrayList<WeekAttend>(); if(list.getContent().size() != 0 && list.getContent().get(0) !=null) { WeekAttend wa = null; for (Object[] ob : list.getContent()) { wa = new WeekAttend(); wa.setShopId(ob[0].toString()); wa.setMonday(ob[1].toString()); wa.setSunday(ob[2].toString()); wa.setMoney(Double.parseDouble(ob[3].toString())); weekAttends.add(wa); } } result.setContent(weekAttends); return result; } @Override public List<WeekAttend> findDetail(WeekAttend weekAttend) { String start = DateUtil.dateToString(DateUtil.getThisMonday(DateUtil.stringToDate(weekAttend.getMonday(),"yyyy-MM-dd")),"yyyy-MM-dd"); String end = DateUtil.dateToString(DateUtil.getThisSunday(DateUtil.stringToDate(weekAttend.getSunday(),"yyyy-MM-dd")),"yyyy-MM-dd"); String sql = "select wa.shop_id,wa.employeeid,wa.monday,wa.sunday,wa.money,wa.minute,wa.per_money,se.name from week_attend wa,shop_employee se where wa.employeeid = se.employeeid and se.employeetype = '2' and wa.shop_id like '%"+ weekAttend.getShopId() +"%' and wa.monday >= '"+ start +"' and wa.sunday <= '"+ end +"'"; List l = this.nativeQuerySQLToQuery(sql,null).getResultList(); List<WeekAttend> weekAttends = null; if (l != null && l.size() > 0) { weekAttends = new ArrayList<WeekAttend>(); Object[] ob; WeekAttend wa; for (Object o : l) { ob = (Object[])o; wa = new WeekAttend(); wa.setShopId(ob[0].toString()); wa.setEmployeeid(ob[1].toString()); wa.setMonday(ob[2].toString()); wa.setSunday(ob[3].toString()); wa.setMoney(Double.parseDouble(ob[4].toString())); wa.setMinute(Double.parseDouble(ob[5].toString())); wa.setPerMoney(Double.parseDouble(ob[6].toString())); wa.setEmployeeName(ob[7].toString()); weekAttends.add(wa); } } return weekAttends; } }
UTF-8
Java
4,685
java
WeekAttendDaoImpl.java
Java
[ { "context": ".ArrayList;\r\nimport java.util.List;\r\n\r\n/**\r\n * 作者:钱剑锋\r\n * 时间:4/12/2016\r\n */\r\n@Repository\r\npublic class ", "end": 367, "score": 0.9125694036483765, "start": 364, "tag": "NAME", "value": "钱剑锋" } ]
null
[]
package com.zj.system.dao.impl; import com.zj.common.persistence.impl.BaseDaoImpl; import com.zj.common.web.PageResult; import com.zj.system.dao.WeekAttendDao; import com.zj.system.entity.WeekAttend; import com.zj.system.utils.DateUtil; import org.springframework.stereotype.Repository; import java.util.ArrayList; import java.util.List; /** * 作者:钱剑锋 * 时间:4/12/2016 */ @Repository public class WeekAttendDaoImpl extends BaseDaoImpl<WeekAttend> implements WeekAttendDao { @Override public WeekAttend getWeekAttend(WeekAttend wa) { String hql = "from WeekAttend where employeeid = '"+ wa.getEmployeeid() +"' and monday = '"+ wa.getMonday() +"' and sunday = '"+ wa.getSunday() +"'"; List<WeekAttend> l = this.query(hql,null); if (l != null && l.size() > 0) { return l.get(0); } return null; } @Override public PageResult<WeekAttend> findWeekAttendForPage(Integer currentPage, Integer pageSize, WeekAttend weekAttend) { String start = DateUtil.dateToString(DateUtil.getThisMonday(DateUtil.stringToDate(weekAttend.getMonday(),"yyyy-MM-dd")),"yyyy-MM-dd"); String end = DateUtil.dateToString(DateUtil.getThisSunday(DateUtil.stringToDate(weekAttend.getSunday(),"yyyy-MM-dd")),"yyyy-MM-dd"); String sql = "select wa.shop_id,wa.monday,wa.sunday,sum(wa.money) from week_attend wa,shop_employee se where wa.employeeid = se.employeeid and se.employeetype = '2' and wa.shop_id like '%"+ weekAttend.getShopId() +"%' and wa.monday >= '"+ start +"' and wa.sunday <= '"+ end +"' group by wa.shop_id,wa.monday"; String sqlCount = "select count(*) from week_attend wa,shop_employee se where wa.employeeid = se.employeeid and se.employeetype = '2' and wa.shop_id like '%"+ weekAttend.getShopId() +"%' and wa.monday >= '"+ start +"' and wa.sunday <= '"+ end +"' group by wa.shop_id,wa.monday"; PageResult<Object[]> list = this.nativeQuerySQLObject(sql, sqlCount, null, currentPage, pageSize); PageResult<WeekAttend> result = new PageResult<WeekAttend>(); //封装结果数据 result.setCurrentIndex(list.getCurrentIndex()); result.setCurrentPage(list.getCurrentPage()); result.setPageSize(list.getPageSize()); result.setTotalCount(list.getTotalCount()); result.setTotalPage(list.getTotalPage()); List<WeekAttend> weekAttends = new ArrayList<WeekAttend>(); if(list.getContent().size() != 0 && list.getContent().get(0) !=null) { WeekAttend wa = null; for (Object[] ob : list.getContent()) { wa = new WeekAttend(); wa.setShopId(ob[0].toString()); wa.setMonday(ob[1].toString()); wa.setSunday(ob[2].toString()); wa.setMoney(Double.parseDouble(ob[3].toString())); weekAttends.add(wa); } } result.setContent(weekAttends); return result; } @Override public List<WeekAttend> findDetail(WeekAttend weekAttend) { String start = DateUtil.dateToString(DateUtil.getThisMonday(DateUtil.stringToDate(weekAttend.getMonday(),"yyyy-MM-dd")),"yyyy-MM-dd"); String end = DateUtil.dateToString(DateUtil.getThisSunday(DateUtil.stringToDate(weekAttend.getSunday(),"yyyy-MM-dd")),"yyyy-MM-dd"); String sql = "select wa.shop_id,wa.employeeid,wa.monday,wa.sunday,wa.money,wa.minute,wa.per_money,se.name from week_attend wa,shop_employee se where wa.employeeid = se.employeeid and se.employeetype = '2' and wa.shop_id like '%"+ weekAttend.getShopId() +"%' and wa.monday >= '"+ start +"' and wa.sunday <= '"+ end +"'"; List l = this.nativeQuerySQLToQuery(sql,null).getResultList(); List<WeekAttend> weekAttends = null; if (l != null && l.size() > 0) { weekAttends = new ArrayList<WeekAttend>(); Object[] ob; WeekAttend wa; for (Object o : l) { ob = (Object[])o; wa = new WeekAttend(); wa.setShopId(ob[0].toString()); wa.setEmployeeid(ob[1].toString()); wa.setMonday(ob[2].toString()); wa.setSunday(ob[3].toString()); wa.setMoney(Double.parseDouble(ob[4].toString())); wa.setMinute(Double.parseDouble(ob[5].toString())); wa.setPerMoney(Double.parseDouble(ob[6].toString())); wa.setEmployeeName(ob[7].toString()); weekAttends.add(wa); } } return weekAttends; } }
4,685
0.617186
0.611386
88
50.897728
60.021786
327
false
false
0
0
0
0
0
0
0.965909
false
false
4
0a53eb1cb9b8b059356061b31b70d6096a1f994b
21,268,678,057,456
9043849a03d0070fceea7cd39c4d5200d02d68b7
/src/main/java/controllers/SaladController.java
127bef337d15a1558ff840424d67d3b812e317d8
[]
no_license
YuliaMelnyk/HollyOrder
https://github.com/YuliaMelnyk/HollyOrder
0dba3217a70466f3bdc8b198f81b48c3c721e92c
9137a66c316d5f68ed506e70492e3c6d7e139b08
refs/heads/master
2023-05-31T19:50:23.918000
2021-06-18T20:06:55
2021-06-18T20:06:55
332,882,031
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package controllers; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.control.ScrollPane; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.input.MouseEvent; import login.Main; import model.CartItem; import services.ProductService; import java.io.IOException; import java.net.URL; import java.sql.Timestamp; import java.util.ResourceBundle; /** * The type Salad controller. * class controller for page salad.fxml * * @author yuliiamelnik on 11/2/21 * @project HollyOrder */ public class SaladController extends BaseController implements Initializable, GeneralController { /** * The Quantity label tun. */ @FXML Label quantityLabelTun, /** * The Quantity label oc. */ quantityLabelOc, /** * The Quantity label ces. */ quantityLabelCes, /** * The Quantity label pr. */ quantityLabelPr; /** * The Price tuna. */ @FXML Label priceTuna, /** * The Price t ces. */ priceTCes, /** * The Price oc. */ priceOc, /** * The Price pr. */ pricePr; /** * The Tuna name. */ @FXML Label tunaName, /** * The Ces name. */ cesName, /** * The Oct name. */ octName, /** * The Prim name. */ primName; /** * The Scroll pane. */ @FXML ScrollPane scrollPane; @FXML private TableView<CartItem> cartTable; @FXML private TableColumn<CartItem, Long> id; @FXML private TableColumn<CartItem, Timestamp> timestamp; @FXML private TableColumn<CartItem, Double> totalPrice; private ProductService service = new ProductService(); @Override public void initialize(URL location, ResourceBundle resources) { try { addCartElements(scrollPane); addToOrder(cartTable, id, timestamp, totalPrice); clickOnRowTableOrder(cartTable); } catch (IOException e) { e.printStackTrace(); } } /** * On back to menu. * click on Image Back * * @param event the event * @throws IOException the io exception */ @FXML public void onBackToMenu(MouseEvent event) throws IOException { Parent parent = FXMLLoader.load(getClass().getResource("/home.fxml")); Scene scene = new Scene(parent); scene.getStylesheets().add(getClass().getResource("/styles/homeStyle.css").toExternalForm()); Main.getPrimaryStage().setScene(scene); } /** * On cart tun. * add to Cart Tuna Salad * * @param event the event * @throws IOException the io exception */ @FXML public void onCartTun(MouseEvent event) throws IOException { service.getProduct(tunaName.getText(), Integer.parseInt(quantityLabelTun.getText())); addCartElements(scrollPane); } /** * On cart oc. * add to Cart Octopus Salad * * @param event the event * @throws IOException the io exception */ @FXML public void onCartOc(MouseEvent event) throws IOException { service.getProduct(octName.getText(), Integer.parseInt(quantityLabelOc.getText())); addCartElements(scrollPane); } /** * On cart ces. * add to Cart Cesar Salad * * @param event the event * @throws IOException the io exception */ @FXML public void onCartCes(MouseEvent event) throws IOException { service.getProduct(cesName.getText(), Integer.parseInt(quantityLabelCes.getText())); addCartElements(scrollPane); } /** * On cart pr. * add to Cart Primavera Salad * * @param event the event * @throws IOException the io exception */ @FXML public void onCartPr(MouseEvent event) throws IOException { service.getProduct(primName.getText(), Integer.parseInt(quantityLabelPr.getText())); addCartElements(scrollPane); } /** * On plus click tun. * plus quantity of Tuna Salad * * @param event the event */ @FXML public void onPlusClickTun(MouseEvent event) { onPlus(quantityLabelTun); } /** * On minus click tun. * minus quantity of Tuna Salad * * @param event the event */ @FXML public void onMinusClickTun(MouseEvent event) { onMinus(quantityLabelTun); } /** * On plus oc. * plus quantity of Octopus Salad * * @param event the event */ @FXML public void onPlusOc(MouseEvent event) { onPlus(quantityLabelOc); } /** * On minus oc. * minus quantity of Octopus Salad * * @param event the event */ @FXML public void onMinusOc(MouseEvent event) { onMinus(quantityLabelOc); } /** * On minus ces. * minus quantity of Cesar Salad * * @param event the event */ @FXML public void onMinusCes(MouseEvent event) { onMinus(quantityLabelCes); } /** * On plus ces. * plus quantity of Cesar Salad * * @param event the event */ @FXML public void onPlusCes(MouseEvent event) { onPlus(quantityLabelCes); } /** * On minus pr. * minus quantity of Primavera Salad * * @param event the event */ @FXML public void onMinusPr(MouseEvent event) { onMinus(quantityLabelPr); } /** * On plus pr. * plus quantity of Primavera Salad * * @param event the event */ @FXML public void onPlusPr(MouseEvent event) { onPlus(quantityLabelPr); } }
UTF-8
Java
5,831
java
SaladController.java
Java
[ { "context": "class controller for page salad.fxml\n *\n * @author yuliiamelnik on 11/2/21\n * @project HollyOrder\n */\n\npublic cla", "end": 645, "score": 0.9991763234138489, "start": 633, "tag": "USERNAME", "value": "yuliiamelnik" } ]
null
[]
package controllers; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.control.ScrollPane; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.input.MouseEvent; import login.Main; import model.CartItem; import services.ProductService; import java.io.IOException; import java.net.URL; import java.sql.Timestamp; import java.util.ResourceBundle; /** * The type Salad controller. * class controller for page salad.fxml * * @author yuliiamelnik on 11/2/21 * @project HollyOrder */ public class SaladController extends BaseController implements Initializable, GeneralController { /** * The Quantity label tun. */ @FXML Label quantityLabelTun, /** * The Quantity label oc. */ quantityLabelOc, /** * The Quantity label ces. */ quantityLabelCes, /** * The Quantity label pr. */ quantityLabelPr; /** * The Price tuna. */ @FXML Label priceTuna, /** * The Price t ces. */ priceTCes, /** * The Price oc. */ priceOc, /** * The Price pr. */ pricePr; /** * The Tuna name. */ @FXML Label tunaName, /** * The Ces name. */ cesName, /** * The Oct name. */ octName, /** * The Prim name. */ primName; /** * The Scroll pane. */ @FXML ScrollPane scrollPane; @FXML private TableView<CartItem> cartTable; @FXML private TableColumn<CartItem, Long> id; @FXML private TableColumn<CartItem, Timestamp> timestamp; @FXML private TableColumn<CartItem, Double> totalPrice; private ProductService service = new ProductService(); @Override public void initialize(URL location, ResourceBundle resources) { try { addCartElements(scrollPane); addToOrder(cartTable, id, timestamp, totalPrice); clickOnRowTableOrder(cartTable); } catch (IOException e) { e.printStackTrace(); } } /** * On back to menu. * click on Image Back * * @param event the event * @throws IOException the io exception */ @FXML public void onBackToMenu(MouseEvent event) throws IOException { Parent parent = FXMLLoader.load(getClass().getResource("/home.fxml")); Scene scene = new Scene(parent); scene.getStylesheets().add(getClass().getResource("/styles/homeStyle.css").toExternalForm()); Main.getPrimaryStage().setScene(scene); } /** * On cart tun. * add to Cart Tuna Salad * * @param event the event * @throws IOException the io exception */ @FXML public void onCartTun(MouseEvent event) throws IOException { service.getProduct(tunaName.getText(), Integer.parseInt(quantityLabelTun.getText())); addCartElements(scrollPane); } /** * On cart oc. * add to Cart Octopus Salad * * @param event the event * @throws IOException the io exception */ @FXML public void onCartOc(MouseEvent event) throws IOException { service.getProduct(octName.getText(), Integer.parseInt(quantityLabelOc.getText())); addCartElements(scrollPane); } /** * On cart ces. * add to Cart Cesar Salad * * @param event the event * @throws IOException the io exception */ @FXML public void onCartCes(MouseEvent event) throws IOException { service.getProduct(cesName.getText(), Integer.parseInt(quantityLabelCes.getText())); addCartElements(scrollPane); } /** * On cart pr. * add to Cart Primavera Salad * * @param event the event * @throws IOException the io exception */ @FXML public void onCartPr(MouseEvent event) throws IOException { service.getProduct(primName.getText(), Integer.parseInt(quantityLabelPr.getText())); addCartElements(scrollPane); } /** * On plus click tun. * plus quantity of Tuna Salad * * @param event the event */ @FXML public void onPlusClickTun(MouseEvent event) { onPlus(quantityLabelTun); } /** * On minus click tun. * minus quantity of Tuna Salad * * @param event the event */ @FXML public void onMinusClickTun(MouseEvent event) { onMinus(quantityLabelTun); } /** * On plus oc. * plus quantity of Octopus Salad * * @param event the event */ @FXML public void onPlusOc(MouseEvent event) { onPlus(quantityLabelOc); } /** * On minus oc. * minus quantity of Octopus Salad * * @param event the event */ @FXML public void onMinusOc(MouseEvent event) { onMinus(quantityLabelOc); } /** * On minus ces. * minus quantity of Cesar Salad * * @param event the event */ @FXML public void onMinusCes(MouseEvent event) { onMinus(quantityLabelCes); } /** * On plus ces. * plus quantity of Cesar Salad * * @param event the event */ @FXML public void onPlusCes(MouseEvent event) { onPlus(quantityLabelCes); } /** * On minus pr. * minus quantity of Primavera Salad * * @param event the event */ @FXML public void onMinusPr(MouseEvent event) { onMinus(quantityLabelPr); } /** * On plus pr. * plus quantity of Primavera Salad * * @param event the event */ @FXML public void onPlusPr(MouseEvent event) { onPlus(quantityLabelPr); } }
5,831
0.605385
0.604528
272
20.4375
19.88579
101
false
false
0
0
0
0
0
0
0.264706
false
false
4
cdb914d9fc812599b7e747403084fb9070a228a1
2,181,843,399,684
9923233eee9bb6137ff1786ab2abba16dbcc42aa
/app/src/main/java/com/example/movie1/MovieAdapter.java
76f4e06c2f2602265cbb44b07882bb0361a3e469
[]
no_license
Teja243/Movie1
https://github.com/Teja243/Movie1
a7e53723e59ec499b1e156527ed60dfcff4e65a2
5cdcbd977d5dc0c175ad6e4f42d3ff718fb9e433
refs/heads/master
2020-05-27T14:48:07.477000
2019-05-26T10:18:55
2019-05-26T10:18:55
188,667,951
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.movie1; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import org.w3c.dom.Text; import java.util.ArrayList; public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.RecyclerViewHolder> { Context c; ArrayList<JsonData> jsonPOJOs; public final static String Image_URL = "https://image.tmdb.org/t/p/w185"; public MovieAdapter(Context c, ArrayList<JsonData> jsonPOJOs) { this.c = c; this.jsonPOJOs = jsonPOJOs; } @Override public MovieAdapter.RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(c).inflate(R.layout.recycler_activity, parent, false); return new RecyclerViewHolder(view); } @Override public void onBindViewHolder(MovieAdapter.RecyclerViewHolder holder, final int position) { JsonUtils js = new JsonUtils(); String s = js.buildImageUrl(jsonPOJOs.get(position).getPoster_path()).toString(); Glide.with(c).load(s).into(holder.imageView); } @Override public int getItemCount() { return jsonPOJOs.size(); } public class RecyclerViewHolder extends RecyclerView.ViewHolder { ImageView imageView; public RecyclerViewHolder(View itemView) { super(itemView); imageView = (ImageView) itemView.findViewById(R.id.id_recycler_poster); imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int position = getAdapterPosition(); Toast.makeText(c, jsonPOJOs.get(position).getTitle(), Toast.LENGTH_SHORT).show(); Intent intent = new Intent(c, MovieActivity.class); intent.putExtra("BACK_DROP_PATH", jsonPOJOs.get(position).getBackdrop_path()); intent.putExtra("POSTER_PATH", jsonPOJOs.get(position).getPoster_path()); intent.putExtra("O_TITLE", jsonPOJOs.get(position).getOriginal_title()); intent.putExtra("TITLE", jsonPOJOs.get(position).getTitle()); intent.putExtra("RATING", jsonPOJOs.get(position).getVote_average()); intent.putExtra("RELEASE_DATE", jsonPOJOs.get(position).getRelease_date()); intent.putExtra("LANGUAGE", jsonPOJOs.get(position).getOriginal_language()); intent.putExtra("SYNOPSIS", jsonPOJOs.get(position).getOverview()); c.startActivity(intent); } }); } } }
UTF-8
Java
2,914
java
MovieAdapter.java
Java
[]
null
[]
package com.example.movie1; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import org.w3c.dom.Text; import java.util.ArrayList; public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.RecyclerViewHolder> { Context c; ArrayList<JsonData> jsonPOJOs; public final static String Image_URL = "https://image.tmdb.org/t/p/w185"; public MovieAdapter(Context c, ArrayList<JsonData> jsonPOJOs) { this.c = c; this.jsonPOJOs = jsonPOJOs; } @Override public MovieAdapter.RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(c).inflate(R.layout.recycler_activity, parent, false); return new RecyclerViewHolder(view); } @Override public void onBindViewHolder(MovieAdapter.RecyclerViewHolder holder, final int position) { JsonUtils js = new JsonUtils(); String s = js.buildImageUrl(jsonPOJOs.get(position).getPoster_path()).toString(); Glide.with(c).load(s).into(holder.imageView); } @Override public int getItemCount() { return jsonPOJOs.size(); } public class RecyclerViewHolder extends RecyclerView.ViewHolder { ImageView imageView; public RecyclerViewHolder(View itemView) { super(itemView); imageView = (ImageView) itemView.findViewById(R.id.id_recycler_poster); imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int position = getAdapterPosition(); Toast.makeText(c, jsonPOJOs.get(position).getTitle(), Toast.LENGTH_SHORT).show(); Intent intent = new Intent(c, MovieActivity.class); intent.putExtra("BACK_DROP_PATH", jsonPOJOs.get(position).getBackdrop_path()); intent.putExtra("POSTER_PATH", jsonPOJOs.get(position).getPoster_path()); intent.putExtra("O_TITLE", jsonPOJOs.get(position).getOriginal_title()); intent.putExtra("TITLE", jsonPOJOs.get(position).getTitle()); intent.putExtra("RATING", jsonPOJOs.get(position).getVote_average()); intent.putExtra("RELEASE_DATE", jsonPOJOs.get(position).getRelease_date()); intent.putExtra("LANGUAGE", jsonPOJOs.get(position).getOriginal_language()); intent.putExtra("SYNOPSIS", jsonPOJOs.get(position).getOverview()); c.startActivity(intent); } }); } } }
2,914
0.656829
0.65477
76
37.342106
33.108097
101
false
false
0
0
0
0
0
0
0.75
false
false
4
11ca71d3845c989f948548dc8f004d81dcdc488f
2,181,843,396,186
8782061b1e1223488a090f9f3f3b8dfe489e054a
/storeMongoDB/projects/ABCD/aaronp_disruptor/test/10Test.java
5f8448f370261bc380f5f66a6666505a1055f314
[]
no_license
ryosuke-ku/TCS_init
https://github.com/ryosuke-ku/TCS_init
3cb79a46aa217e62d8fff13d600f2a9583df986c
e1207d68bdc9d2f1eed63ef44a672b5a37b45633
refs/heads/master
2020-08-08T18:40:17.929000
2019-10-18T01:06:32
2019-10-18T01:06:32
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public void shouldGetTwoNinesUpperBound() { final long[] INTERVALS = new long[]{ 1, 10, 100, 1000, 10000 }; final Histogram histogram = new Histogram(INTERVALS); for (long i = 1; i < 101; i++) { histogram.addObservation(i); } assertThat(Long.valueOf(histogram.getTwoNinesUpperBound()), is(Long.valueOf(100L))); }
UTF-8
Java
399
java
10Test.java
Java
[]
null
[]
public void shouldGetTwoNinesUpperBound() { final long[] INTERVALS = new long[]{ 1, 10, 100, 1000, 10000 }; final Histogram histogram = new Histogram(INTERVALS); for (long i = 1; i < 101; i++) { histogram.addObservation(i); } assertThat(Long.valueOf(histogram.getTwoNinesUpperBound()), is(Long.valueOf(100L))); }
399
0.568922
0.513784
12
30.916666
29.850903
92
false
false
0
0
0
0
0
0
0.916667
false
false
4
031eff82f0a4f88825bfee18222bddcd18e836e7
27,943,057,287,619
e948ea72b6f721d8af50a326c9081532277d07ff
/src/main/java/oj120_139/Lee_132_Self.java
74f0118f8b11be80180e24f37af6d1f980854e10
[]
no_license
yilak1/LeetCode
https://github.com/yilak1/LeetCode
3a17f2f3ba03002861d11f472a8824de54e9c9a6
e4c9169b03175c825d17a642c56d06016751c8f4
refs/heads/master
2020-12-11T10:53:22.936000
2020-01-14T11:52:39
2020-01-14T11:52:39
233,829,412
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package oj120_139; /** * 分割回文串II,分割字符串,使得每一个子串都是回文串,并且计算最小切割数 * state 前i个字符,最小的分割字符串数。 * function: min(得到多个f[j]取最小值 ,如果j<i 并且 [j+1, i]闭区间的字符串是符文串)+1 * initialValue f[s.length + 1] ,f[0] = 0;//当为空串时,字符串个数为0; * out */ public class Lee_132_Self { //可以把所有的字串都给计算出来是否是回文串,这样复杂度会降低 public boolean isPalindrome(String s, int start, int end){ boolean flag = true; while (start < end){ if (s.charAt(start) == s.charAt(end)){ start++; end--; }else { flag = false; break; } } return flag; } public int minCut(String s) { int[] minStr = new int[s.length() + 1]; minStr[0] = 0; for (int i = 0; i < s.length(); i++){ int min = Integer.MAX_VALUE; for (int j = -1; j < i; j++){ if (isPalindrome(s,j+1, i) && minStr[j + 1] < min){ min = minStr[j + 1]; } } minStr[i + 1] = min + 1; } return minStr[s.length()] - 1; } public static void main(String[] args) { String s = "aab"; Lee_132_Self self = new Lee_132_Self(); System.out.println(self.minCut(s)); } }
UTF-8
Java
1,505
java
Lee_132_Self.java
Java
[]
null
[]
package oj120_139; /** * 分割回文串II,分割字符串,使得每一个子串都是回文串,并且计算最小切割数 * state 前i个字符,最小的分割字符串数。 * function: min(得到多个f[j]取最小值 ,如果j<i 并且 [j+1, i]闭区间的字符串是符文串)+1 * initialValue f[s.length + 1] ,f[0] = 0;//当为空串时,字符串个数为0; * out */ public class Lee_132_Self { //可以把所有的字串都给计算出来是否是回文串,这样复杂度会降低 public boolean isPalindrome(String s, int start, int end){ boolean flag = true; while (start < end){ if (s.charAt(start) == s.charAt(end)){ start++; end--; }else { flag = false; break; } } return flag; } public int minCut(String s) { int[] minStr = new int[s.length() + 1]; minStr[0] = 0; for (int i = 0; i < s.length(); i++){ int min = Integer.MAX_VALUE; for (int j = -1; j < i; j++){ if (isPalindrome(s,j+1, i) && minStr[j + 1] < min){ min = minStr[j + 1]; } } minStr[i + 1] = min + 1; } return minStr[s.length()] - 1; } public static void main(String[] args) { String s = "aab"; Lee_132_Self self = new Lee_132_Self(); System.out.println(self.minCut(s)); } }
1,505
0.471282
0.446105
46
26.630434
18.369822
67
false
false
0
0
0
0
0
0
0.608696
false
false
4
c5d3eef463628862a364e2cbfab8d7fd3cf24b94
7,052,336,319,216
834184ae7fb5fc951ec4ca76d0ab4d74224817a0
/src/main/java/com/nswt/framework/Ajax.java
4fd714e0fc06537dc4998633945fc79220f9e91a
[]
no_license
mipcdn/NswtOldPF
https://github.com/mipcdn/NswtOldPF
3bf9974be6ffbc32b2d52ef2e39adbe495185c7e
fe7be46f12b3874a7f19967c0808870d8e465f5a
refs/heads/master
2020-08-09T16:44:47.585000
2017-01-11T13:26:37
2017-01-11T13:26:37
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.nswt.framework; /** * 继承了Ajax的类允许未登录用户访问,所有前台未登录即能访问的页面对应的后台类都要继承本类 * * @Author NSWT * @Date 2008-12-27 * @Mail nswt@nswt.com.cn */ public class Ajax extends Page { }
GB18030
Java
280
java
Ajax.java
Java
[ { "context": "登录用户访问,所有前台未登录即能访问的页面对应的后台类都要继承本类\r\n * \r\n * @Author NSWT\r\n * @Date 2008-12-27\r\n * @Mail nswt@nswt.com.cn\r\n", "end": 106, "score": 0.9996819496154785, "start": 102, "tag": "USERNAME", "value": "NSWT" }, { "context": "* \r\n * @Author NSWT\r\n * @Date 2008-12-27\r\n * @Mail nswt@nswt.com.cn\r\n */\r\npublic class Ajax extends Page {\r\n\r\n}", "end": 154, "score": 0.99992835521698, "start": 138, "tag": "EMAIL", "value": "nswt@nswt.com.cn" } ]
null
[]
package com.nswt.framework; /** * 继承了Ajax的类允许未登录用户访问,所有前台未登录即能访问的页面对应的后台类都要继承本类 * * @Author NSWT * @Date 2008-12-27 * @Mail <EMAIL> */ public class Ajax extends Page { }
271
0.666667
0.626263
12
14.666667
15.040686
48
false
false
0
0
0
0
0
0
0.083333
false
false
4
514ca841cc9d282aa067f1e507ea901fc709bc84
12,146,167,539,681
18b917f70e68f1bf3b4e4cc219b2102a9b8a8792
/Tally/app/src/main/java/com/hjf/tally/HistoryActivity.java
19a48fe383d414f4376b9682d11101668cbda570
[]
no_license
BloothOfYouth/2018127109_Android
https://github.com/BloothOfYouth/2018127109_Android
2946898e8b9cfc4d1abd6bfb89a1bc0f8b2b7c2b
65fab34b3982d515bfedc87849c058cf476f4276
refs/heads/master
2023-02-06T14:47:36.778000
2020-12-29T06:38:51
2020-12-29T06:38:51
293,481,175
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hjf.tally; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import android.content.DialogInterface; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.TextView; import com.hjf.tally.adapter.AccountAdapter; import com.hjf.tally.bean.AccountBean; import com.hjf.tally.db.DBManager; import com.hjf.tally.utils.CalendarDialog; import java.util.ArrayList; import java.util.Calendar; import java.util.List; public class HistoryActivity extends AppCompatActivity { private TextView timeTv; private ListView historyLv; private AccountAdapter accountAdapter; private List<AccountBean> accountList = new ArrayList<>(); private int year, month; private int selectYearPosition = -1, selectMonthPosition = -1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_history); timeTv = findViewById(R.id.history_tv_time); historyLv = findViewById(R.id.history_lv); accountAdapter = new AccountAdapter(this, accountList); historyLv.setAdapter(accountAdapter); getCurrentTime(); } @Override protected void onResume() { super.onResume(); loadAccountList(); setLvLongClickListener(); } private void setLvLongClickListener() { historyLv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) { AccountBean clickBean = (AccountBean) accountAdapter.getItem(position); //弹出提示用户是否删除的对话框 showDeleteItemDialog(clickBean); return false; } }); } private void showDeleteItemDialog(final AccountBean clickBean) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("提示信息").setMessage("你确定要删除这条记录么?") .setNegativeButton("取消",null) .setPositiveButton("确认", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { //执行删除操作 int click_id = clickBean.getId(); DBManager.deleteOneAccountById(click_id); onResume(); } }); builder.create().show(); //显示对话框 } private void getCurrentTime() { Calendar today = Calendar.getInstance(); year = today.get(Calendar.YEAR); month = today.get(Calendar.MONTH) + 1; setTextOfTimeTv(); } private void loadAccountList() { List<AccountBean> list = DBManager.getAccountByTime(year, month); accountList.clear(); accountList.addAll(list); accountAdapter.notifyDataSetChanged(); } public void onClick(View view) { switch (view.getId()) { case R.id.history_iv_back: finish(); break; case R.id.history_iv_calendar: CalendarDialog calendarDialog = new CalendarDialog(this); calendarDialog.show(); calendarDialog.initCalendar(selectYearPosition, selectMonthPosition); calendarDialog.setDialogSize(); calendarDialog.setOnClickListener(new CalendarDialog.OnClickListener() { @Override public void onClick(int changeYear, int changeMonth, int selectYearPos, int selectMonthPos) { year = changeYear; month = changeMonth; setTextOfTimeTv(); selectYearPosition = selectYearPos; selectMonthPosition = selectMonthPos; List<AccountBean> list = DBManager.getAccountByTime(year, month); accountList.clear(); accountList.addAll(list); accountAdapter.notifyDataSetChanged(); } }); break; } } private void setTextOfTimeTv() { String monthStr = month + ""; if (month < 10) { monthStr = "0" + monthStr; } timeTv.setText(year + "年" + monthStr + "月"); } }
UTF-8
Java
4,654
java
HistoryActivity.java
Java
[]
null
[]
package com.hjf.tally; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import android.content.DialogInterface; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.TextView; import com.hjf.tally.adapter.AccountAdapter; import com.hjf.tally.bean.AccountBean; import com.hjf.tally.db.DBManager; import com.hjf.tally.utils.CalendarDialog; import java.util.ArrayList; import java.util.Calendar; import java.util.List; public class HistoryActivity extends AppCompatActivity { private TextView timeTv; private ListView historyLv; private AccountAdapter accountAdapter; private List<AccountBean> accountList = new ArrayList<>(); private int year, month; private int selectYearPosition = -1, selectMonthPosition = -1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_history); timeTv = findViewById(R.id.history_tv_time); historyLv = findViewById(R.id.history_lv); accountAdapter = new AccountAdapter(this, accountList); historyLv.setAdapter(accountAdapter); getCurrentTime(); } @Override protected void onResume() { super.onResume(); loadAccountList(); setLvLongClickListener(); } private void setLvLongClickListener() { historyLv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) { AccountBean clickBean = (AccountBean) accountAdapter.getItem(position); //弹出提示用户是否删除的对话框 showDeleteItemDialog(clickBean); return false; } }); } private void showDeleteItemDialog(final AccountBean clickBean) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("提示信息").setMessage("你确定要删除这条记录么?") .setNegativeButton("取消",null) .setPositiveButton("确认", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { //执行删除操作 int click_id = clickBean.getId(); DBManager.deleteOneAccountById(click_id); onResume(); } }); builder.create().show(); //显示对话框 } private void getCurrentTime() { Calendar today = Calendar.getInstance(); year = today.get(Calendar.YEAR); month = today.get(Calendar.MONTH) + 1; setTextOfTimeTv(); } private void loadAccountList() { List<AccountBean> list = DBManager.getAccountByTime(year, month); accountList.clear(); accountList.addAll(list); accountAdapter.notifyDataSetChanged(); } public void onClick(View view) { switch (view.getId()) { case R.id.history_iv_back: finish(); break; case R.id.history_iv_calendar: CalendarDialog calendarDialog = new CalendarDialog(this); calendarDialog.show(); calendarDialog.initCalendar(selectYearPosition, selectMonthPosition); calendarDialog.setDialogSize(); calendarDialog.setOnClickListener(new CalendarDialog.OnClickListener() { @Override public void onClick(int changeYear, int changeMonth, int selectYearPos, int selectMonthPos) { year = changeYear; month = changeMonth; setTextOfTimeTv(); selectYearPosition = selectYearPos; selectMonthPosition = selectMonthPos; List<AccountBean> list = DBManager.getAccountByTime(year, month); accountList.clear(); accountList.addAll(list); accountAdapter.notifyDataSetChanged(); } }); break; } } private void setTextOfTimeTv() { String monthStr = month + ""; if (month < 10) { monthStr = "0" + monthStr; } timeTv.setText(year + "年" + monthStr + "月"); } }
4,654
0.602193
0.600877
132
33.545456
25.174652
114
false
false
0
0
0
0
0
0
0.643939
false
false
4
1d0bd9723b645f41947304dfac28a522d12b2452
19,464,791,805,941
83cc8864b2b01d84d1b0a793699c9672b0df562c
/Final Project Java/TestContactList.java
cfb172080f844ecb845dc7525cb09c6443a9750f
[]
no_license
meganwong94/Homework-Files
https://github.com/meganwong94/Homework-Files
3a9e7e46ab4ab92ed4b786b771eb3ed1f89940a3
3d4547318d29983e7a66ede4ae2e8d1f6d26e9de
refs/heads/master
2021-09-03T18:02:19.726000
2018-01-10T23:16:25
2018-01-10T23:16:25
111,034,897
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Tests class ContactList by creating a ContactList object. */ package test; public class TestContactList { public static void main(String[] args) { Contact contact1; contact1 = new Contact(); contact1.userInputContact(); Contact contact2; contact2 = new Contact(); contact2.userInputContact(); ContactList contactList1; contactList1 = new ContactList(); contactList1.addContactToList(contact1); contactList1.addContactToList(contact2); System.out.println(contactList1); System.out.println("Reached end of main()"); } } /* ------ run --------- Reached end of main() --------------------- */
UTF-8
Java
631
java
TestContactList.java
Java
[]
null
[]
/** * Tests class ContactList by creating a ContactList object. */ package test; public class TestContactList { public static void main(String[] args) { Contact contact1; contact1 = new Contact(); contact1.userInputContact(); Contact contact2; contact2 = new Contact(); contact2.userInputContact(); ContactList contactList1; contactList1 = new ContactList(); contactList1.addContactToList(contact1); contactList1.addContactToList(contact2); System.out.println(contactList1); System.out.println("Reached end of main()"); } } /* ------ run --------- Reached end of main() --------------------- */
631
0.681458
0.660856
28
21.535715
16.715012
60
false
false
0
0
0
0
0
0
1.464286
false
false
4
13960fba7c91abaa988b1876ce07a6e02a64f133
17,617,955,917,245
da5cae01bdaca8e469ad8d421d856319cfe40e12
/src/main/java/com/feng/knowlege/atomic/AtomicIntegerDemo1.java
d1fb213a36883d0f267f2e8a6561c338d29d5b97
[]
no_license
IFADA/javaKnowledge
https://github.com/IFADA/javaKnowledge
ced57f5f65f002bc8899c9f83a655e7b8976e8a0
7a909e8165078bf64c0e13d306a17db4dc702318
refs/heads/master
2023-02-03T17:13:08.703000
2023-02-02T12:09:48
2023-02-02T12:09:48
286,013,337
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.feng.knowlege.atomic; import java.util.concurrent.atomic.AtomicInteger; public class AtomicIntegerDemo1 implements Runnable { private static final AtomicInteger atomicInteger = new AtomicInteger(); public static void main(String[] args) throws InterruptedException { AtomicIntegerDemo1 r = new AtomicIntegerDemo1(); Thread t1 = new Thread(r); Thread t2 = new Thread(r); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println("原子"+atomicInteger.get()); System.out.println("普通"+basicCount); } public void incremtAtomic(){ atomicInteger.getAndIncrement(); } private static volatile int basicCount = 0; public void incremBasic(){ basicCount++; } @Override public void run() { for (int i = 0; i <1000 ; i++) { incremtAtomic(); incremBasic(); } } }
UTF-8
Java
960
java
AtomicIntegerDemo1.java
Java
[]
null
[]
package com.feng.knowlege.atomic; import java.util.concurrent.atomic.AtomicInteger; public class AtomicIntegerDemo1 implements Runnable { private static final AtomicInteger atomicInteger = new AtomicInteger(); public static void main(String[] args) throws InterruptedException { AtomicIntegerDemo1 r = new AtomicIntegerDemo1(); Thread t1 = new Thread(r); Thread t2 = new Thread(r); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println("原子"+atomicInteger.get()); System.out.println("普通"+basicCount); } public void incremtAtomic(){ atomicInteger.getAndIncrement(); } private static volatile int basicCount = 0; public void incremBasic(){ basicCount++; } @Override public void run() { for (int i = 0; i <1000 ; i++) { incremtAtomic(); incremBasic(); } } }
960
0.602941
0.587185
39
23.410257
21.530798
77
false
false
0
0
0
0
0
0
0.487179
false
false
4
a2d7659663b08f8147295236a32337a43a192f69
30,305,289,291,018
999930340d5cb8f5015a8be3b7d62a49a88634e4
/app/src/main/java/com/amisrs/gavin/stratdex/controller/AsyncResponse.java
8c5cc85698ad6382d7603c70983a5757c77457dc
[]
no_license
amisrs/StratDex
https://github.com/amisrs/StratDex
bf3043a5e172a0613cac0e26d1abbc95a9c121ce
0dcfe40ff0b7795b18b3958c407814cf0705060a
refs/heads/master
2021-01-16T21:26:24.761000
2016-10-04T02:32:04
2016-10-04T02:32:04
68,459,548
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.amisrs.gavin.stratdex.controller; import com.amisrs.gavin.stratdex.model.DetailsFromSpecies; import com.amisrs.gavin.stratdex.model.PokemonSpecies; import java.util.ArrayList; /** * Created by Gavin on 15/09/2016. */ public interface AsyncResponse { void giveFilledPokemon(PokemonSpecies pokemonSpecies); void updateLoadingMsg(String msg); }
UTF-8
Java
367
java
AsyncResponse.java
Java
[ { "context": "s;\n\nimport java.util.ArrayList;\n\n/**\n * Created by Gavin on 15/09/2016.\n */\npublic interface AsyncResponse", "end": 214, "score": 0.9529378414154053, "start": 209, "tag": "NAME", "value": "Gavin" } ]
null
[]
package com.amisrs.gavin.stratdex.controller; import com.amisrs.gavin.stratdex.model.DetailsFromSpecies; import com.amisrs.gavin.stratdex.model.PokemonSpecies; import java.util.ArrayList; /** * Created by Gavin on 15/09/2016. */ public interface AsyncResponse { void giveFilledPokemon(PokemonSpecies pokemonSpecies); void updateLoadingMsg(String msg); }
367
0.790191
0.768392
14
25.214285
22.583744
58
false
false
0
0
0
0
0
0
0.428571
false
false
4
57bcdfd264f3e29b47b91689c3db1708df7c5b2d
10,290,741,656,924
6e1a436761a145345e73ebca3db79d1c0b11df69
/src/MainForm.java
3cf4001e4fc3358bf5216984ef478c94f9b754f7
[]
no_license
munjalapraveen/Bus
https://github.com/munjalapraveen/Bus
205076520455bfedeb0a07f4e7de4316507e2305
0fa6138cbdfda5ccfc9195c9f6afd72a8e127323
refs/heads/master
2023-02-01T02:06:09.766000
2020-12-18T05:10:58
2020-12-18T05:10:58
319,508,279
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.awt.event.WindowEvent; import javax.swing.JFrame; import javax.swing.JOptionPane; /** * This class is responsible to display all the contents of the MainForm of Bus Management System * This class contains following methods : * * 1. void itemDestinationActionPerformed(java.awt.event.ActionEvent evt) * 2. void itemBusScheduleActionPerformed(java.awt.event.ActionEvent evt) * 3. void itemBusInfoActionPerformed(java.awt.event.ActionEvent evt) * 4. void itmBookingActionPerformed(java.awt.event.ActionEvent evt) * 5. void itemManageBookingActionPerformed(java.awt.event.ActionEvent evt) * 6. void formWindowOpened(java.awt.event.WindowEvent evt) * 7. void menuExitActionPerformed(java.awt.event.ActionEvent evt) * 8. void itemYesActionPerformed(java.awt.event.ActionEvent evt) * 9. void itemUserInfoActionPerformed(java.awt.event.ActionEvent evt) * 10. void itemCustInfoActionPerformed(java.awt.event.ActionEvent evt) * 11. void menuChangePwdActionPerformed(java.awt.event.ActionEvent evt) * 12. void itemBookingLogActionPerformed(java.awt.event.ActionEvent evt) * 13. void itemOpenActionPerformed(java.awt.event.ActionEvent evt) * 14. void menuReportActionPerformed(java.awt.event.ActionEvent evt) * 15. void itemCustLogActionPerformed(java.awt.event.ActionEvent evt) * 16. void itemBusLogActionPerformed(java.awt.event.ActionEvent evt) * 17. void itemUserReportActionPerformed(java.awt.event.ActionEvent evt) * 18. void main(String args) * * In this class Admin is responsible to to CRUD operations on User, Bus and Destination details * Admin is responsible to schedule Bus and manage user activity report * In this class User(Staff) is responsible to do CRUD operations on Customers. * User is also responsible for View and Manage bookings. * In this class Admin/User can see Customer, Booking and Bus log * * @author Mamta Sinha */ public class MainForm extends JFrame { //Constructor for MainForm public MainForm() { initComponents(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { desktop = new javax.swing.JDesktopPane(); lblWelcome = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); lblIMG1 = new javax.swing.JLabel(); lblIMG2 = new javax.swing.JLabel(); menuBar = new javax.swing.JMenuBar(); menuAdmin = new javax.swing.JMenu(); itemUserInfo = new javax.swing.JMenuItem(); itemBusInfo = new javax.swing.JMenuItem(); itemDestination = new javax.swing.JMenuItem(); itemBusSchedule = new javax.swing.JMenuItem(); itemUserReport = new javax.swing.JMenuItem(); menuUser = new javax.swing.JMenu(); itemCustInfo = new javax.swing.JMenuItem(); itmBooking = new javax.swing.JMenuItem(); itemManageBooking = new javax.swing.JMenuItem(); menuReport = new javax.swing.JMenu(); itemBookingLog = new javax.swing.JMenuItem(); itemCustLog = new javax.swing.JMenuItem(); itemBusLog = new javax.swing.JMenuItem(); menuChangePwd = new javax.swing.JMenu(); itemOpen = new javax.swing.JMenuItem(); menuExit = new javax.swing.JMenu(); itemYes = new javax.swing.JMenuItem(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Bus Management System"); addWindowListener(new java.awt.event.WindowAdapter() { public void windowOpened(java.awt.event.WindowEvent evt) { formWindowOpened(evt); } }); desktop.setBackground(new java.awt.Color(255, 255, 255)); lblWelcome.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N lblWelcome.setForeground(new java.awt.Color(204, 255, 255)); lblWelcome.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); lblWelcome.setText("Welcome to Bus Management System"); desktop.add(lblWelcome); lblWelcome.setBounds(430, 30, 540, 90); desktop.add(jLabel1); jLabel1.setBounds(280, 150, 0, 160); lblIMG1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/covid_img_resize.jpg"))); // NOI18N desktop.add(lblIMG1); lblIMG1.setBounds(990, 70, 460, 860); lblIMG2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/covid_img_main.jpg"))); // NOI18N desktop.add(lblIMG2); lblIMG2.setBounds(0, 130, 981, 770); menuBar.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N menuAdmin.setForeground(new java.awt.Color(102, 51, 255)); menuAdmin.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/admin2.jpg"))); // NOI18N menuAdmin.setText("ADMIN"); menuAdmin.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N itemUserInfo.setFont(new java.awt.Font("Segoe UI", 1, 15)); // NOI18N itemUserInfo.setText("User Information"); itemUserInfo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { itemUserInfoActionPerformed(evt); } }); menuAdmin.add(itemUserInfo); itemBusInfo.setFont(new java.awt.Font("Segoe UI", 1, 15)); // NOI18N itemBusInfo.setText("Bus Information"); itemBusInfo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { itemBusInfoActionPerformed(evt); } }); menuAdmin.add(itemBusInfo); itemDestination.setFont(new java.awt.Font("Segoe UI", 1, 15)); // NOI18N itemDestination.setText("Destination Information"); itemDestination.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { itemDestinationActionPerformed(evt); } }); menuAdmin.add(itemDestination); itemBusSchedule.setFont(new java.awt.Font("Segoe UI", 1, 15)); // NOI18N itemBusSchedule.setText("Bus Schedule"); itemBusSchedule.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { itemBusScheduleActionPerformed(evt); } }); menuAdmin.add(itemBusSchedule); itemUserReport.setFont(new java.awt.Font("Segoe UI", 1, 15)); // NOI18N itemUserReport.setText("User Activity Log Report"); itemUserReport.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { itemUserReportActionPerformed(evt); } }); menuAdmin.add(itemUserReport); menuBar.add(menuAdmin); menuUser.setForeground(new java.awt.Color(102, 51, 255)); menuUser.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/user4.png"))); // NOI18N menuUser.setText(" USER "); menuUser.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N itemCustInfo.setFont(new java.awt.Font("Segoe UI", 1, 15)); // NOI18N itemCustInfo.setText("Customer Information"); itemCustInfo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { itemCustInfoActionPerformed(evt); } }); menuUser.add(itemCustInfo); itmBooking.setFont(new java.awt.Font("Segoe UI", 1, 15)); // NOI18N itmBooking.setText("New Booking"); itmBooking.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { itmBookingActionPerformed(evt); } }); menuUser.add(itmBooking); itemManageBooking.setFont(new java.awt.Font("Segoe UI", 1, 15)); // NOI18N itemManageBooking.setText("Manage Booking"); itemManageBooking.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { itemManageBookingActionPerformed(evt); } }); menuUser.add(itemManageBooking); menuBar.add(menuUser); menuReport.setForeground(new java.awt.Color(102, 51, 255)); menuReport.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/report2.png"))); // NOI18N menuReport.setText(" REPORT "); menuReport.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N menuReport.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuReportActionPerformed(evt); } }); itemBookingLog.setFont(new java.awt.Font("Segoe UI", 1, 15)); // NOI18N itemBookingLog.setText("Booking Log"); itemBookingLog.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { itemBookingLogActionPerformed(evt); } }); menuReport.add(itemBookingLog); itemCustLog.setFont(new java.awt.Font("Segoe UI", 1, 15)); // NOI18N itemCustLog.setText("Customer Log"); itemCustLog.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { itemCustLogActionPerformed(evt); } }); menuReport.add(itemCustLog); itemBusLog.setFont(new java.awt.Font("Segoe UI", 1, 15)); // NOI18N itemBusLog.setText("Bus Log"); itemBusLog.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { itemBusLogActionPerformed(evt); } }); menuReport.add(itemBusLog); menuBar.add(menuReport); menuChangePwd.setForeground(new java.awt.Color(102, 51, 255)); menuChangePwd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/p.gif"))); // NOI18N menuChangePwd.setText("CHANGE PASSWORD "); menuChangePwd.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N menuChangePwd.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuChangePwdActionPerformed(evt); } }); itemOpen.setFont(new java.awt.Font("Segoe UI", 1, 15)); // NOI18N itemOpen.setText("Open"); itemOpen.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { itemOpenActionPerformed(evt); } }); menuChangePwd.add(itemOpen); menuBar.add(menuChangePwd); menuExit.setForeground(new java.awt.Color(102, 51, 255)); menuExit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/e.gif"))); // NOI18N menuExit.setText(" EXIT "); menuExit.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N menuExit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuExitActionPerformed(evt); } }); itemYes.setBackground(new java.awt.Color(0, 0, 255)); itemYes.setFont(new java.awt.Font("Segoe UI", 1, 15)); // NOI18N itemYes.setText("Yes"); itemYes.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { itemYesActionPerformed(evt); } }); menuExit.add(itemYes); menuBar.add(menuExit); setJMenuBar(menuBar); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(desktop, javax.swing.GroupLayout.PREFERRED_SIZE, 1468, javax.swing.GroupLayout.PREFERRED_SIZE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(desktop, javax.swing.GroupLayout.PREFERRED_SIZE, 1050, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents /** * This method is an action performed on the DestinationInformation menu item * * @param name - evt * @return - void * * This method creates object for DestinationInformation class which is responsible to add the destination details. */ private void itemDestinationActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemDestinationActionPerformed DestinationInformation m = new DestinationInformation(); desktop.add(m); m.setVisible(true); }//GEN-LAST:event_itemDestinationActionPerformed /** * This method is an action performed on the Bus Schedule menu item * * @param name - evt * @return - void * * This method creates object for BusSchedule class which is responsible for scheduling the Bus */ private void itemBusScheduleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemBusScheduleActionPerformed BusSchedule m = new BusSchedule(); desktop.add(m); m.setVisible(true); }//GEN-LAST:event_itemBusScheduleActionPerformed /** * This method is an action performed on the Bus Information menu item * * @param name - evt * @return - void * * This method creates object for BusInformation class which is responsible for CRUD operations of Bus. */ private void itemBusInfoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemBusInfoActionPerformed BusInformation m = new BusInformation(); desktop.add(m); m.setVisible(true); }//GEN-LAST:event_itemBusInfoActionPerformed /** * This method is an action performed on the Booking menu item * * @param name - evt * @return - void * * This method creates object for Booking class which is responsible for booking ticket for customer by user(staff) */ private void itmBookingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itmBookingActionPerformed Booking m = new Booking(); desktop.add(m); m.setVisible(true); }//GEN-LAST:event_itmBookingActionPerformed /** * This method is an action performed on the Manage Booking menu item * * @param name - evt * @return - void * * This method creates object for ViewBooking class which is responsible to manage already booked tickets and ticket printing */ private void itemManageBookingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemManageBookingActionPerformed ViewBooking m = new ViewBooking(); desktop.add(m); m.setVisible(true); }//GEN-LAST:event_itemManageBookingActionPerformed /** * This method is to open window for Admin/User * * @param name - evt * @return - void */ private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened if (MainClass.strUserType.endsWith("admin") == true) { menuAdmin.setEnabled(true); menuUser.setEnabled(true); } if (MainClass.strUserType.endsWith("user") == true) { menuUser.setEnabled(true); menuAdmin.setEnabled(false); } }//GEN-LAST:event_formWindowOpened /** * This method is an action performed on the Exit menu * * @param name - evt * @return - void */ private void menuExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuExitActionPerformed System.exit(1); }//GEN-LAST:event_menuExitActionPerformed /** * This method is an action performed on the Yes menu item * * @param name - evt * @return - void */ private void itemYesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemYesActionPerformed System.exit(1); }//GEN-LAST:event_itemYesActionPerformed /** * This method is an action performed on the User Information menu item * * @param name - evt * @return - void * * This method creates object for UserInformation class which is responsible for CRUD operations Users */ private void itemUserInfoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemUserInfoActionPerformed UserInformation m = new UserInformation(); desktop.add(m); m.setVisible(true); }//GEN-LAST:event_itemUserInfoActionPerformed /** * This method is an action performed on the Customer Information menu item * * @param name - evt * @return - void * * This method creates object for CustomerInformation class which is responsible for CRUD operations Customers */ private void itemCustInfoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemCustInfoActionPerformed CustomerInformation m = new CustomerInformation(); desktop.add(m); m.setVisible(true); }//GEN-LAST:event_itemCustInfoActionPerformed private void menuChangePwdActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuChangePwdActionPerformed }//GEN-LAST:event_menuChangePwdActionPerformed /** * This method is an action performed on the Booking Log menu item * * @param name - evt * @return - void * * This method creates object for BookingLog class which is responsible generate booking log by entering booking ID. */ private void itemBookingLogActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemBookingLogActionPerformed BookingLog m = new BookingLog(); desktop.add(m); m.setVisible(true); }//GEN-LAST:event_itemBookingLogActionPerformed /** * This method is an action performed on the Open menu item * * @param name - evt * @return - void * * This method creates object for ChangePassword class which is responsible to create new password for Admin/User */ private void itemOpenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemOpenActionPerformed ChangePassword m = new ChangePassword(); desktop.add(m); m.setVisible(true); }//GEN-LAST:event_itemOpenActionPerformed private void menuReportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuReportActionPerformed }//GEN-LAST:event_menuReportActionPerformed /** * This method is an action performed on the Customer Log menu item * * @param name - evt * @return - void * * This method creates object for CustomerLog class which is responsible to generate customer log report by entering customer name. */ private void itemCustLogActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemCustLogActionPerformed CustomerLog m = new CustomerLog(); desktop.add(m); m.setVisible(true); }//GEN-LAST:event_itemCustLogActionPerformed /** * This method is an action performed on the Bus Log menu item * * @param name - evt * @return - void * * This method creates object for BusLog class which is responsible to generate Bus log report by entering Bus Number. */ private void itemBusLogActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemBusLogActionPerformed BusLog m = new BusLog(); desktop.add(m); m.setVisible(true); }//GEN-LAST:event_itemBusLogActionPerformed /** * This method is an action performed on the UserActivityLOgReport menu item * * @param name - evt * @return - void * * This method creates object for UserLogRegsiter class which is responsible to generate maintain admin/user log */ private void itemUserReportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemUserReportActionPerformed UserLogRegsiter m = new UserLogRegsiter(); desktop.add(m); m.setVisible(true); }//GEN-LAST:event_itemUserReportActionPerformed /** * This method is main method where the execution of MainForm page takes place at first * * @param name - args * @return - void */ public static void main(String args[]) { try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new MainForm().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JDesktopPane desktop; private javax.swing.JMenuItem itemBookingLog; private javax.swing.JMenuItem itemBusInfo; private javax.swing.JMenuItem itemBusLog; private javax.swing.JMenuItem itemBusSchedule; private javax.swing.JMenuItem itemCustInfo; private javax.swing.JMenuItem itemCustLog; private javax.swing.JMenuItem itemDestination; private javax.swing.JMenuItem itemManageBooking; private javax.swing.JMenuItem itemOpen; private javax.swing.JMenuItem itemUserInfo; private javax.swing.JMenuItem itemUserReport; private javax.swing.JMenuItem itemYes; private javax.swing.JMenuItem itmBooking; private javax.swing.JLabel jLabel1; private javax.swing.JLabel lblIMG1; private javax.swing.JLabel lblIMG2; private javax.swing.JLabel lblWelcome; private javax.swing.JMenu menuAdmin; private javax.swing.JMenuBar menuBar; private javax.swing.JMenu menuChangePwd; private javax.swing.JMenu menuExit; private javax.swing.JMenu menuReport; private javax.swing.JMenu menuUser; // End of variables declaration//GEN-END:variables }
UTF-8
Java
23,750
java
MainForm.java
Java
[ { "context": " see Customer, Booking and Bus log \n * \n * @author Mamta Sinha\n */\npublic class MainForm extends JFrame {\n //", "end": 1878, "score": 0.9998461008071899, "start": 1867, "tag": "NAME", "value": "Mamta Sinha" } ]
null
[]
import java.awt.event.WindowEvent; import javax.swing.JFrame; import javax.swing.JOptionPane; /** * This class is responsible to display all the contents of the MainForm of Bus Management System * This class contains following methods : * * 1. void itemDestinationActionPerformed(java.awt.event.ActionEvent evt) * 2. void itemBusScheduleActionPerformed(java.awt.event.ActionEvent evt) * 3. void itemBusInfoActionPerformed(java.awt.event.ActionEvent evt) * 4. void itmBookingActionPerformed(java.awt.event.ActionEvent evt) * 5. void itemManageBookingActionPerformed(java.awt.event.ActionEvent evt) * 6. void formWindowOpened(java.awt.event.WindowEvent evt) * 7. void menuExitActionPerformed(java.awt.event.ActionEvent evt) * 8. void itemYesActionPerformed(java.awt.event.ActionEvent evt) * 9. void itemUserInfoActionPerformed(java.awt.event.ActionEvent evt) * 10. void itemCustInfoActionPerformed(java.awt.event.ActionEvent evt) * 11. void menuChangePwdActionPerformed(java.awt.event.ActionEvent evt) * 12. void itemBookingLogActionPerformed(java.awt.event.ActionEvent evt) * 13. void itemOpenActionPerformed(java.awt.event.ActionEvent evt) * 14. void menuReportActionPerformed(java.awt.event.ActionEvent evt) * 15. void itemCustLogActionPerformed(java.awt.event.ActionEvent evt) * 16. void itemBusLogActionPerformed(java.awt.event.ActionEvent evt) * 17. void itemUserReportActionPerformed(java.awt.event.ActionEvent evt) * 18. void main(String args) * * In this class Admin is responsible to to CRUD operations on User, Bus and Destination details * Admin is responsible to schedule Bus and manage user activity report * In this class User(Staff) is responsible to do CRUD operations on Customers. * User is also responsible for View and Manage bookings. * In this class Admin/User can see Customer, Booking and Bus log * * @author <NAME> */ public class MainForm extends JFrame { //Constructor for MainForm public MainForm() { initComponents(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { desktop = new javax.swing.JDesktopPane(); lblWelcome = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); lblIMG1 = new javax.swing.JLabel(); lblIMG2 = new javax.swing.JLabel(); menuBar = new javax.swing.JMenuBar(); menuAdmin = new javax.swing.JMenu(); itemUserInfo = new javax.swing.JMenuItem(); itemBusInfo = new javax.swing.JMenuItem(); itemDestination = new javax.swing.JMenuItem(); itemBusSchedule = new javax.swing.JMenuItem(); itemUserReport = new javax.swing.JMenuItem(); menuUser = new javax.swing.JMenu(); itemCustInfo = new javax.swing.JMenuItem(); itmBooking = new javax.swing.JMenuItem(); itemManageBooking = new javax.swing.JMenuItem(); menuReport = new javax.swing.JMenu(); itemBookingLog = new javax.swing.JMenuItem(); itemCustLog = new javax.swing.JMenuItem(); itemBusLog = new javax.swing.JMenuItem(); menuChangePwd = new javax.swing.JMenu(); itemOpen = new javax.swing.JMenuItem(); menuExit = new javax.swing.JMenu(); itemYes = new javax.swing.JMenuItem(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Bus Management System"); addWindowListener(new java.awt.event.WindowAdapter() { public void windowOpened(java.awt.event.WindowEvent evt) { formWindowOpened(evt); } }); desktop.setBackground(new java.awt.Color(255, 255, 255)); lblWelcome.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N lblWelcome.setForeground(new java.awt.Color(204, 255, 255)); lblWelcome.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); lblWelcome.setText("Welcome to Bus Management System"); desktop.add(lblWelcome); lblWelcome.setBounds(430, 30, 540, 90); desktop.add(jLabel1); jLabel1.setBounds(280, 150, 0, 160); lblIMG1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/covid_img_resize.jpg"))); // NOI18N desktop.add(lblIMG1); lblIMG1.setBounds(990, 70, 460, 860); lblIMG2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/covid_img_main.jpg"))); // NOI18N desktop.add(lblIMG2); lblIMG2.setBounds(0, 130, 981, 770); menuBar.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N menuAdmin.setForeground(new java.awt.Color(102, 51, 255)); menuAdmin.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/admin2.jpg"))); // NOI18N menuAdmin.setText("ADMIN"); menuAdmin.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N itemUserInfo.setFont(new java.awt.Font("Segoe UI", 1, 15)); // NOI18N itemUserInfo.setText("User Information"); itemUserInfo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { itemUserInfoActionPerformed(evt); } }); menuAdmin.add(itemUserInfo); itemBusInfo.setFont(new java.awt.Font("Segoe UI", 1, 15)); // NOI18N itemBusInfo.setText("Bus Information"); itemBusInfo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { itemBusInfoActionPerformed(evt); } }); menuAdmin.add(itemBusInfo); itemDestination.setFont(new java.awt.Font("Segoe UI", 1, 15)); // NOI18N itemDestination.setText("Destination Information"); itemDestination.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { itemDestinationActionPerformed(evt); } }); menuAdmin.add(itemDestination); itemBusSchedule.setFont(new java.awt.Font("Segoe UI", 1, 15)); // NOI18N itemBusSchedule.setText("Bus Schedule"); itemBusSchedule.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { itemBusScheduleActionPerformed(evt); } }); menuAdmin.add(itemBusSchedule); itemUserReport.setFont(new java.awt.Font("Segoe UI", 1, 15)); // NOI18N itemUserReport.setText("User Activity Log Report"); itemUserReport.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { itemUserReportActionPerformed(evt); } }); menuAdmin.add(itemUserReport); menuBar.add(menuAdmin); menuUser.setForeground(new java.awt.Color(102, 51, 255)); menuUser.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/user4.png"))); // NOI18N menuUser.setText(" USER "); menuUser.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N itemCustInfo.setFont(new java.awt.Font("Segoe UI", 1, 15)); // NOI18N itemCustInfo.setText("Customer Information"); itemCustInfo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { itemCustInfoActionPerformed(evt); } }); menuUser.add(itemCustInfo); itmBooking.setFont(new java.awt.Font("Segoe UI", 1, 15)); // NOI18N itmBooking.setText("New Booking"); itmBooking.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { itmBookingActionPerformed(evt); } }); menuUser.add(itmBooking); itemManageBooking.setFont(new java.awt.Font("Segoe UI", 1, 15)); // NOI18N itemManageBooking.setText("Manage Booking"); itemManageBooking.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { itemManageBookingActionPerformed(evt); } }); menuUser.add(itemManageBooking); menuBar.add(menuUser); menuReport.setForeground(new java.awt.Color(102, 51, 255)); menuReport.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/report2.png"))); // NOI18N menuReport.setText(" REPORT "); menuReport.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N menuReport.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuReportActionPerformed(evt); } }); itemBookingLog.setFont(new java.awt.Font("Segoe UI", 1, 15)); // NOI18N itemBookingLog.setText("Booking Log"); itemBookingLog.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { itemBookingLogActionPerformed(evt); } }); menuReport.add(itemBookingLog); itemCustLog.setFont(new java.awt.Font("Segoe UI", 1, 15)); // NOI18N itemCustLog.setText("Customer Log"); itemCustLog.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { itemCustLogActionPerformed(evt); } }); menuReport.add(itemCustLog); itemBusLog.setFont(new java.awt.Font("Segoe UI", 1, 15)); // NOI18N itemBusLog.setText("Bus Log"); itemBusLog.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { itemBusLogActionPerformed(evt); } }); menuReport.add(itemBusLog); menuBar.add(menuReport); menuChangePwd.setForeground(new java.awt.Color(102, 51, 255)); menuChangePwd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/p.gif"))); // NOI18N menuChangePwd.setText("CHANGE PASSWORD "); menuChangePwd.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N menuChangePwd.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuChangePwdActionPerformed(evt); } }); itemOpen.setFont(new java.awt.Font("Segoe UI", 1, 15)); // NOI18N itemOpen.setText("Open"); itemOpen.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { itemOpenActionPerformed(evt); } }); menuChangePwd.add(itemOpen); menuBar.add(menuChangePwd); menuExit.setForeground(new java.awt.Color(102, 51, 255)); menuExit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/e.gif"))); // NOI18N menuExit.setText(" EXIT "); menuExit.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N menuExit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuExitActionPerformed(evt); } }); itemYes.setBackground(new java.awt.Color(0, 0, 255)); itemYes.setFont(new java.awt.Font("Segoe UI", 1, 15)); // NOI18N itemYes.setText("Yes"); itemYes.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { itemYesActionPerformed(evt); } }); menuExit.add(itemYes); menuBar.add(menuExit); setJMenuBar(menuBar); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(desktop, javax.swing.GroupLayout.PREFERRED_SIZE, 1468, javax.swing.GroupLayout.PREFERRED_SIZE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(desktop, javax.swing.GroupLayout.PREFERRED_SIZE, 1050, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents /** * This method is an action performed on the DestinationInformation menu item * * @param name - evt * @return - void * * This method creates object for DestinationInformation class which is responsible to add the destination details. */ private void itemDestinationActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemDestinationActionPerformed DestinationInformation m = new DestinationInformation(); desktop.add(m); m.setVisible(true); }//GEN-LAST:event_itemDestinationActionPerformed /** * This method is an action performed on the Bus Schedule menu item * * @param name - evt * @return - void * * This method creates object for BusSchedule class which is responsible for scheduling the Bus */ private void itemBusScheduleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemBusScheduleActionPerformed BusSchedule m = new BusSchedule(); desktop.add(m); m.setVisible(true); }//GEN-LAST:event_itemBusScheduleActionPerformed /** * This method is an action performed on the Bus Information menu item * * @param name - evt * @return - void * * This method creates object for BusInformation class which is responsible for CRUD operations of Bus. */ private void itemBusInfoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemBusInfoActionPerformed BusInformation m = new BusInformation(); desktop.add(m); m.setVisible(true); }//GEN-LAST:event_itemBusInfoActionPerformed /** * This method is an action performed on the Booking menu item * * @param name - evt * @return - void * * This method creates object for Booking class which is responsible for booking ticket for customer by user(staff) */ private void itmBookingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itmBookingActionPerformed Booking m = new Booking(); desktop.add(m); m.setVisible(true); }//GEN-LAST:event_itmBookingActionPerformed /** * This method is an action performed on the Manage Booking menu item * * @param name - evt * @return - void * * This method creates object for ViewBooking class which is responsible to manage already booked tickets and ticket printing */ private void itemManageBookingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemManageBookingActionPerformed ViewBooking m = new ViewBooking(); desktop.add(m); m.setVisible(true); }//GEN-LAST:event_itemManageBookingActionPerformed /** * This method is to open window for Admin/User * * @param name - evt * @return - void */ private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened if (MainClass.strUserType.endsWith("admin") == true) { menuAdmin.setEnabled(true); menuUser.setEnabled(true); } if (MainClass.strUserType.endsWith("user") == true) { menuUser.setEnabled(true); menuAdmin.setEnabled(false); } }//GEN-LAST:event_formWindowOpened /** * This method is an action performed on the Exit menu * * @param name - evt * @return - void */ private void menuExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuExitActionPerformed System.exit(1); }//GEN-LAST:event_menuExitActionPerformed /** * This method is an action performed on the Yes menu item * * @param name - evt * @return - void */ private void itemYesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemYesActionPerformed System.exit(1); }//GEN-LAST:event_itemYesActionPerformed /** * This method is an action performed on the User Information menu item * * @param name - evt * @return - void * * This method creates object for UserInformation class which is responsible for CRUD operations Users */ private void itemUserInfoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemUserInfoActionPerformed UserInformation m = new UserInformation(); desktop.add(m); m.setVisible(true); }//GEN-LAST:event_itemUserInfoActionPerformed /** * This method is an action performed on the Customer Information menu item * * @param name - evt * @return - void * * This method creates object for CustomerInformation class which is responsible for CRUD operations Customers */ private void itemCustInfoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemCustInfoActionPerformed CustomerInformation m = new CustomerInformation(); desktop.add(m); m.setVisible(true); }//GEN-LAST:event_itemCustInfoActionPerformed private void menuChangePwdActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuChangePwdActionPerformed }//GEN-LAST:event_menuChangePwdActionPerformed /** * This method is an action performed on the Booking Log menu item * * @param name - evt * @return - void * * This method creates object for BookingLog class which is responsible generate booking log by entering booking ID. */ private void itemBookingLogActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemBookingLogActionPerformed BookingLog m = new BookingLog(); desktop.add(m); m.setVisible(true); }//GEN-LAST:event_itemBookingLogActionPerformed /** * This method is an action performed on the Open menu item * * @param name - evt * @return - void * * This method creates object for ChangePassword class which is responsible to create new password for Admin/User */ private void itemOpenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemOpenActionPerformed ChangePassword m = new ChangePassword(); desktop.add(m); m.setVisible(true); }//GEN-LAST:event_itemOpenActionPerformed private void menuReportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuReportActionPerformed }//GEN-LAST:event_menuReportActionPerformed /** * This method is an action performed on the Customer Log menu item * * @param name - evt * @return - void * * This method creates object for CustomerLog class which is responsible to generate customer log report by entering customer name. */ private void itemCustLogActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemCustLogActionPerformed CustomerLog m = new CustomerLog(); desktop.add(m); m.setVisible(true); }//GEN-LAST:event_itemCustLogActionPerformed /** * This method is an action performed on the Bus Log menu item * * @param name - evt * @return - void * * This method creates object for BusLog class which is responsible to generate Bus log report by entering Bus Number. */ private void itemBusLogActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemBusLogActionPerformed BusLog m = new BusLog(); desktop.add(m); m.setVisible(true); }//GEN-LAST:event_itemBusLogActionPerformed /** * This method is an action performed on the UserActivityLOgReport menu item * * @param name - evt * @return - void * * This method creates object for UserLogRegsiter class which is responsible to generate maintain admin/user log */ private void itemUserReportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemUserReportActionPerformed UserLogRegsiter m = new UserLogRegsiter(); desktop.add(m); m.setVisible(true); }//GEN-LAST:event_itemUserReportActionPerformed /** * This method is main method where the execution of MainForm page takes place at first * * @param name - args * @return - void */ public static void main(String args[]) { try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new MainForm().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JDesktopPane desktop; private javax.swing.JMenuItem itemBookingLog; private javax.swing.JMenuItem itemBusInfo; private javax.swing.JMenuItem itemBusLog; private javax.swing.JMenuItem itemBusSchedule; private javax.swing.JMenuItem itemCustInfo; private javax.swing.JMenuItem itemCustLog; private javax.swing.JMenuItem itemDestination; private javax.swing.JMenuItem itemManageBooking; private javax.swing.JMenuItem itemOpen; private javax.swing.JMenuItem itemUserInfo; private javax.swing.JMenuItem itemUserReport; private javax.swing.JMenuItem itemYes; private javax.swing.JMenuItem itmBooking; private javax.swing.JLabel jLabel1; private javax.swing.JLabel lblIMG1; private javax.swing.JLabel lblIMG2; private javax.swing.JLabel lblWelcome; private javax.swing.JMenu menuAdmin; private javax.swing.JMenuBar menuBar; private javax.swing.JMenu menuChangePwd; private javax.swing.JMenu menuExit; private javax.swing.JMenu menuReport; private javax.swing.JMenu menuUser; // End of variables declaration//GEN-END:variables }
23,745
0.664168
0.652632
580
39.946552
33.579842
135
false
false
0
0
0
0
0
0
0.537931
false
false
4
b769fdca14bf7bf46605da91f8c88576eaf763e3
17,609,365,931,251
ccaeddafb73e969c0c2b242dd9625f40a8dfd541
/src/com/d1/helper/SearchListHelper.java
d30ba7894a012539e14444bec40ba7c71a92fd1c
[]
no_license
ACGT/d1
https://github.com/ACGT/d1
1f2e3e1759e34bfb1a730fda28ff90d3a4349531
c661e7c0b2ea1182105c9b155b1740515c6a2f37
refs/heads/master
2021-01-21T20:34:57.056000
2015-10-16T14:10:51
2015-10-16T14:10:51
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.d1.helper; import java.util.ArrayList; import java.util.List; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import org.hibernate.criterion.SimpleExpression; import com.d1.bean.SearchList; import com.d1.bean.SearchListItem; import com.d1.dbcache.core.BaseEntity; import com.d1.util.Tools; /** * 获取搜索条件的工具类 * @author kk */ public class SearchListHelper { /** * 根据分类编号获取搜索条件分组。得到如“像素”“价格”“内存大小”这些搜索基本单位! * @param rackcode * @return */ public static ArrayList<SearchList> getSearchList(String rackcode){ List<SimpleExpression> clist = new ArrayList<SimpleExpression>(); clist.add(Restrictions.eq("searchlist_rackcode", rackcode)); clist.add(Restrictions.eq("searchlist_showflag", new Long(1))); List<Order> olist = new ArrayList<Order>(); olist.add(Order.asc("searchlist_seq")); List<BaseEntity> list = Tools.getManager(SearchList.class).getList(clist, olist, 0, 100); if(list==null||list.size()==0)return null; ArrayList<SearchList> rlist = new ArrayList<SearchList>(); for(BaseEntity b:list){ rlist.add((SearchList)b); } return rlist ; } /** * 根据分类和制定的搜索名称(如像素、价格、材质)获取搜索条件明细列表,参看searchdtl表 * @param rackcode * @param searchlist_name * @return */ public static ArrayList<SearchListItem> getSearchListItems(String rackcode,String searchlist_name){ List<SimpleExpression> clist = new ArrayList<SimpleExpression>(); clist.add(Restrictions.eq("searchdtl_rackcode", rackcode)); clist.add(Restrictions.eq("searchdtl_searchlist_name", searchlist_name)); clist.add(Restrictions.eq("searchdtl_showflag", new Long(1))); List<Order> olist = new ArrayList<Order>(); olist.add(Order.asc("id")); List<BaseEntity> list = Tools.getManager(SearchListItem.class).getList(clist, olist, 0, 100); if(list==null||list.size()==0)return null; ArrayList<SearchListItem> rlist = new ArrayList<SearchListItem>(); for(BaseEntity b:list){ rlist.add((SearchListItem)b); } return rlist ; } /** * 根据分类号获取价格规格的值 * @param code * @return */ public static ArrayList<SearchList> getSearchList_price(String code) { List<SimpleExpression> clist = new ArrayList<SimpleExpression>(); clist.add(Restrictions.eq("searchlist_rackcode", code)); clist.add(Restrictions.eq("searchlist_showflag", new Long(1))); clist.add(Restrictions.like("searchlist_name", "%价格%")); clist.add(Restrictions.ne("searchlist_context", "")); List<Order> olist = new ArrayList<Order>(); olist.add(Order.asc("searchlist_seq")); List<BaseEntity> list = Tools.getManager(SearchList.class).getList(clist, olist, 0, 100); if(list==null||list.size()==0)return null; ArrayList<SearchList> rlist = new ArrayList<SearchList>(); for(BaseEntity b:list){ rlist.add((SearchList)b); } return rlist ; } }
GB18030
Java
3,042
java
SearchListHelper.java
Java
[ { "context": "t com.d1.util.Tools;\n\n/**\n * 获取搜索条件的工具类\n * @author kk\n */\npublic class SearchListHelper {\n\t/**\n\t * 根据分类", "end": 372, "score": 0.998200535774231, "start": 370, "tag": "USERNAME", "value": "kk" } ]
null
[]
package com.d1.helper; import java.util.ArrayList; import java.util.List; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import org.hibernate.criterion.SimpleExpression; import com.d1.bean.SearchList; import com.d1.bean.SearchListItem; import com.d1.dbcache.core.BaseEntity; import com.d1.util.Tools; /** * 获取搜索条件的工具类 * @author kk */ public class SearchListHelper { /** * 根据分类编号获取搜索条件分组。得到如“像素”“价格”“内存大小”这些搜索基本单位! * @param rackcode * @return */ public static ArrayList<SearchList> getSearchList(String rackcode){ List<SimpleExpression> clist = new ArrayList<SimpleExpression>(); clist.add(Restrictions.eq("searchlist_rackcode", rackcode)); clist.add(Restrictions.eq("searchlist_showflag", new Long(1))); List<Order> olist = new ArrayList<Order>(); olist.add(Order.asc("searchlist_seq")); List<BaseEntity> list = Tools.getManager(SearchList.class).getList(clist, olist, 0, 100); if(list==null||list.size()==0)return null; ArrayList<SearchList> rlist = new ArrayList<SearchList>(); for(BaseEntity b:list){ rlist.add((SearchList)b); } return rlist ; } /** * 根据分类和制定的搜索名称(如像素、价格、材质)获取搜索条件明细列表,参看searchdtl表 * @param rackcode * @param searchlist_name * @return */ public static ArrayList<SearchListItem> getSearchListItems(String rackcode,String searchlist_name){ List<SimpleExpression> clist = new ArrayList<SimpleExpression>(); clist.add(Restrictions.eq("searchdtl_rackcode", rackcode)); clist.add(Restrictions.eq("searchdtl_searchlist_name", searchlist_name)); clist.add(Restrictions.eq("searchdtl_showflag", new Long(1))); List<Order> olist = new ArrayList<Order>(); olist.add(Order.asc("id")); List<BaseEntity> list = Tools.getManager(SearchListItem.class).getList(clist, olist, 0, 100); if(list==null||list.size()==0)return null; ArrayList<SearchListItem> rlist = new ArrayList<SearchListItem>(); for(BaseEntity b:list){ rlist.add((SearchListItem)b); } return rlist ; } /** * 根据分类号获取价格规格的值 * @param code * @return */ public static ArrayList<SearchList> getSearchList_price(String code) { List<SimpleExpression> clist = new ArrayList<SimpleExpression>(); clist.add(Restrictions.eq("searchlist_rackcode", code)); clist.add(Restrictions.eq("searchlist_showflag", new Long(1))); clist.add(Restrictions.like("searchlist_name", "%价格%")); clist.add(Restrictions.ne("searchlist_context", "")); List<Order> olist = new ArrayList<Order>(); olist.add(Order.asc("searchlist_seq")); List<BaseEntity> list = Tools.getManager(SearchList.class).getList(clist, olist, 0, 100); if(list==null||list.size()==0)return null; ArrayList<SearchList> rlist = new ArrayList<SearchList>(); for(BaseEntity b:list){ rlist.add((SearchList)b); } return rlist ; } }
3,042
0.714739
0.706629
97
28.237114
26.762327
100
false
false
0
0
0
0
0
0
2.061856
false
false
4
56bf65484e16590671989d8f59ac0c66c3316db8
9,002,251,468,104
e5c888f683c7f7b9c324afa990f47313983efe3e
/app/src/main/java/com/faviotorres/acopiomx/home/ActivityHome.java
acc22176b1d50cb2bc71f9114334fe1a836bfeb0
[ "Apache-2.0" ]
permissive
ingscjoshua/AcopioMX
https://github.com/ingscjoshua/AcopioMX
e4692fb4a0733682a41ded71988308e54b5f7818
362de559762c6f4c24a826376dc462a841f793e6
refs/heads/master
2021-07-05T17:44:23.783000
2017-09-25T20:22:44
2017-09-25T20:22:44
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.faviotorres.acopiomx.home; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.widget.ProgressBar; import com.faviotorres.acopiomx.R; import com.faviotorres.acopiomx.base.BaseActivity; import com.faviotorres.acopiomx.model.Acopio; import java.util.List; import butterknife.BindView; public class ActivityHome extends BaseActivity implements HomeContract.View { @BindView(R.id.toolbar) Toolbar toolbar; @BindView(R.id.progress_bar) ProgressBar progressBar; private Presenter presenter; /* BASE ACTIVITY */ @Override protected int getLayoutId() { return R.layout.activity_home; } @Override public void create() { super.create(); setupToolbar(toolbar, getString(R.string.app_name), false); initialize(); getAcopios(); } /* MAIN */ private void initialize() { presenter = new Presenter(this); } private void getAcopios() { presenter.getAcopios(); } /* HOME CONTRACT VIEW */ @Override public void showProgressBar() { progressBar.setVisibility(View.VISIBLE); } @Override public void hideProgressBar() { progressBar.setVisibility(View.GONE); } @Override public void showError(String message) { longToast(this, message); } @Override public void setupAcopios(List<Acopio> acopios) { Log.d("ACOPIOS", "---> acopios size: "+acopios.size()); for (Acopio acopio: acopios) { Log.d("ACOPIOS", "---> acopios: " + acopio.toString()); } } }
UTF-8
Java
1,640
java
ActivityHome.java
Java
[]
null
[]
package com.faviotorres.acopiomx.home; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.widget.ProgressBar; import com.faviotorres.acopiomx.R; import com.faviotorres.acopiomx.base.BaseActivity; import com.faviotorres.acopiomx.model.Acopio; import java.util.List; import butterknife.BindView; public class ActivityHome extends BaseActivity implements HomeContract.View { @BindView(R.id.toolbar) Toolbar toolbar; @BindView(R.id.progress_bar) ProgressBar progressBar; private Presenter presenter; /* BASE ACTIVITY */ @Override protected int getLayoutId() { return R.layout.activity_home; } @Override public void create() { super.create(); setupToolbar(toolbar, getString(R.string.app_name), false); initialize(); getAcopios(); } /* MAIN */ private void initialize() { presenter = new Presenter(this); } private void getAcopios() { presenter.getAcopios(); } /* HOME CONTRACT VIEW */ @Override public void showProgressBar() { progressBar.setVisibility(View.VISIBLE); } @Override public void hideProgressBar() { progressBar.setVisibility(View.GONE); } @Override public void showError(String message) { longToast(this, message); } @Override public void setupAcopios(List<Acopio> acopios) { Log.d("ACOPIOS", "---> acopios size: "+acopios.size()); for (Acopio acopio: acopios) { Log.d("ACOPIOS", "---> acopios: " + acopio.toString()); } } }
1,640
0.65
0.64939
75
20.866667
20.209789
77
false
false
0
0
0
0
0
0
0.4
false
false
4
1fb62e8ba0aea818242002c7bca870878d354812
25,400,436,603,174
db749993d341db958d139736ee81b0d2e9389fc3
/src/edu/login/Action/LoginAction.java
5fbc31686f76376f3abe7b27832ee96889ca4de3
[]
no_license
jinpanji/pmms
https://github.com/jinpanji/pmms
fbdf3a589e8711e574f46d6640aa663c084c0bab
5a99bec1a5ebe064752e9f74bf168e01a1f38561
refs/heads/master
2021-06-20T12:55:12.808000
2017-06-19T00:49:49
2017-06-19T00:49:49
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.login.Action; import java.sql.ResultSet; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.interceptor.ServletRequestAware; import com.opensymphony.xwork2.ActionSupport; import DBJavaBean.DB; public class LoginAction extends ActionSupport implements ServletRequestAware{ private String userName; private String password; private ResultSet rs=null; private String message=ERROR; private HttpServletRequest request; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public void setServletRequest(HttpServletRequest arg0) { request=arg0; } public void validate(){ if(this.getUserName()==null||this.getUserName().length()==0){ addFieldError("userName", "请输入登陆名字!"); }else { try { DB mysql=new DB(); rs=mysql.selectMess(request,this.getUserName()); if (!rs.next()) { addFieldError("userName", "此用户尚未注册!"); } } catch (Exception e) { e.printStackTrace(); } } if(this.getPassword()==null||this.getPassword().length()==0){ addFieldError("password", "请输入登录密码!"); }else { try { DB mysql=new DB(); rs=mysql.selectMess(request,this.getUserName()); if (rs.next()) { rs=mysql.selectLogin(request,this.getUserName(),this.getPassword()); if (!rs.next()) { addFieldError("password", "登录密码错误!"); } } } catch (Exception e) { e.printStackTrace(); } } } @Override public String execute() throws Exception { DB mysql=new DB(); String add=mysql.addList(request,this.getUserName()); if (add.equals("ok")) { message=SUCCESS; } return message; } }
UTF-8
Java
1,953
java
LoginAction.java
Java
[ { "context": "uest;\r\n\t\r\n\tpublic String getUserName() {\r\n\t\treturn userName;\r\n\t}\r\n\tpublic void setUserName(String userName) {", "end": 529, "score": 0.8195161819458008, "start": 521, "tag": "USERNAME", "value": "userName" }, { "context": " setUserName(String userName) {\r\n\t\tthis.userName = userName;\r\n\t}\r\n\tpublic String getPassword() {\r\n\t\treturn pa", "end": 607, "score": 0.9871562719345093, "start": 599, "tag": "USERNAME", "value": "userName" } ]
null
[]
package edu.login.Action; import java.sql.ResultSet; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.interceptor.ServletRequestAware; import com.opensymphony.xwork2.ActionSupport; import DBJavaBean.DB; public class LoginAction extends ActionSupport implements ServletRequestAware{ private String userName; private String password; private ResultSet rs=null; private String message=ERROR; private HttpServletRequest request; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public void setServletRequest(HttpServletRequest arg0) { request=arg0; } public void validate(){ if(this.getUserName()==null||this.getUserName().length()==0){ addFieldError("userName", "请输入登陆名字!"); }else { try { DB mysql=new DB(); rs=mysql.selectMess(request,this.getUserName()); if (!rs.next()) { addFieldError("userName", "此用户尚未注册!"); } } catch (Exception e) { e.printStackTrace(); } } if(this.getPassword()==null||this.getPassword().length()==0){ addFieldError("password", "请输入登录密码!"); }else { try { DB mysql=new DB(); rs=mysql.selectMess(request,this.getUserName()); if (rs.next()) { rs=mysql.selectLogin(request,this.getUserName(),this.getPassword()); if (!rs.next()) { addFieldError("password", "登录密码错误!"); } } } catch (Exception e) { e.printStackTrace(); } } } @Override public String execute() throws Exception { DB mysql=new DB(); String add=mysql.addList(request,this.getUserName()); if (add.equals("ok")) { message=SUCCESS; } return message; } }
1,953
0.658911
0.655738
78
22.243589
19.684814
78
false
false
0
0
0
0
0
0
2.474359
false
false
4
7db6580daefb410de2c8aa75a9e6ce6699ddea76
807,453,877,407
eb150ca2c399a78641542f9d9ff99375de1b0fb7
/_src/Chapter 3/source_code/cloudstreetmarket-parent/cloudstreetmarket-core/src/main/java/edu/zipcloud/cloudstreetmarket/core/daos/HistoricalIndexRepositoryImpl.java
56e37af59614d9c49a92e36adc3193fb5f2440ed
[ "Apache-2.0" ]
permissive
paullewallencom/spring-978-1-7843-9641-1
https://github.com/paullewallencom/spring-978-1-7843-9641-1
3b2f8659dcace471e0e2016f9f0bffb40b86440b
34a471328e687045ca517da04618c4f5c539a205
refs/heads/main
2023-02-02T09:32:17.901000
2020-12-20T17:12:08
2020-12-20T17:12:08
319,432,015
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.zipcloud.cloudstreetmarket.core.daos; import java.util.Date; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import org.springframework.stereotype.Repository; import edu.zipcloud.cloudstreetmarket.core.entities.HistoricalIndex; import edu.zipcloud.util.DateUtil; @Repository public class HistoricalIndexRepositoryImpl implements HistoricalIndexRepository{ @PersistenceContext private EntityManager em; @Override public Iterable<HistoricalIndex> findIntraDay(String code, Date of) { TypedQuery<HistoricalIndex> sqlQuery = em.createQuery("from HistoricalIndex h where h.index.code = ? and h.fromDate >= ? and h.toDate <= ? ORDER BY h.toDate asc", HistoricalIndex.class); sqlQuery.setParameter(1, code); sqlQuery.setParameter(2, DateUtil.getStartOfDay(of)); sqlQuery.setParameter(3, DateUtil.getEndOfDay(of)); return sqlQuery.getResultList(); } @Override public Iterable<HistoricalIndex> findLastIntraDay(String code) { return findIntraDay(code, findLastHistoric(code).getToDate()); } @Override public HistoricalIndex findLastHistoric(String code){ TypedQuery<HistoricalIndex> sqlQuery = em.createQuery("from HistoricalIndex h where h.index.code = ? ORDER BY h.toDate desc", HistoricalIndex.class); sqlQuery.setParameter(1, code); return sqlQuery.setMaxResults(1).getSingleResult(); } }
UTF-8
Java
1,450
java
HistoricalIndexRepositoryImpl.java
Java
[]
null
[]
package edu.zipcloud.cloudstreetmarket.core.daos; import java.util.Date; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import org.springframework.stereotype.Repository; import edu.zipcloud.cloudstreetmarket.core.entities.HistoricalIndex; import edu.zipcloud.util.DateUtil; @Repository public class HistoricalIndexRepositoryImpl implements HistoricalIndexRepository{ @PersistenceContext private EntityManager em; @Override public Iterable<HistoricalIndex> findIntraDay(String code, Date of) { TypedQuery<HistoricalIndex> sqlQuery = em.createQuery("from HistoricalIndex h where h.index.code = ? and h.fromDate >= ? and h.toDate <= ? ORDER BY h.toDate asc", HistoricalIndex.class); sqlQuery.setParameter(1, code); sqlQuery.setParameter(2, DateUtil.getStartOfDay(of)); sqlQuery.setParameter(3, DateUtil.getEndOfDay(of)); return sqlQuery.getResultList(); } @Override public Iterable<HistoricalIndex> findLastIntraDay(String code) { return findIntraDay(code, findLastHistoric(code).getToDate()); } @Override public HistoricalIndex findLastHistoric(String code){ TypedQuery<HistoricalIndex> sqlQuery = em.createQuery("from HistoricalIndex h where h.index.code = ? ORDER BY h.toDate desc", HistoricalIndex.class); sqlQuery.setParameter(1, code); return sqlQuery.setMaxResults(1).getSingleResult(); } }
1,450
0.776552
0.773103
40
34.25
39.720116
188
false
false
0
0
0
0
0
0
1.4
false
false
4
fcf3b69d8b149cef114de52f76b2e5591f5067be
8,194,797,629,095
f322e0ad7f04fdc3e8112fd0e3f2ec4cb317996b
/src/com/javarush/test/level08/lesson08/task04/Solution.java
845abb60cee861140d04830a9d11c1208307c3e9
[]
no_license
VovanFun/JavaRushHomeWork
https://github.com/VovanFun/JavaRushHomeWork
90c45585a0f6f8dbbe5b8a33ba4685e0996f28dd
9c35449df54bd36b36dd038e19419a7c9fe40d00
refs/heads/master
2021-01-20T20:18:35.254000
2016-07-04T10:29:22
2016-07-04T10:29:22
60,034,681
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.javarush.test.level08.lesson08.task04; import java.util.*; /* Удалить всех людей, родившихся летом Создать словарь (Map<String, Date>) и занести в него десять записей по принципу: «фамилия» - «дата рождения». Удалить из словаря всех людей, родившихся летом. */ public class Solution { public static void main(String[] args) { HashMap<String, Date> map = createMap(); removeAllSummerPeople(map); for (String name : map.keySet()) System.out.println(name); } public static HashMap<String, Date> createMap() { HashMap<String, Date> map = new HashMap<String, Date>(); //напишите тут ваш код map.put("Stallone", new Date("JUNE 1 1980")); map.put("Arnold", new Date("MAY 1 1990")); map.put("Obama", new Date("JULY 1 1990")); map.put("VanDam", new Date("DECEMBER 1 1990")); map.put("VanGoh", new Date("AUGUST 1 1990")); map.put("Vancent", new Date("SEPTEMBER 1 1990")); map.put("Banderos", new Date("NOVEMBER 1 1990")); map.put("Gitler", new Date("OCTOBER 1 1990")); map.put("Worh", new Date("OCTOBER 1 1990")); map.put("Stef", new Date("OCTOBER 1 1990")); return map; } public static void removeAllSummerPeople(HashMap<String, Date> map) { //напишите тут ваш код ArrayList<String> arrayList = new ArrayList<>(); for (Iterator<Map.Entry<String, Date>> iterator = map.entrySet().iterator(); iterator.hasNext() ; ) { Map.Entry<String, Date> pair = iterator.next(); Date value = pair.getValue(); if (value.getMonth() > 4 && value.getMonth() < 8) arrayList.add(pair.getKey()); } for (String s : arrayList) map.remove(s); } }
UTF-8
Java
1,993
java
Solution.java
Java
[ { "context": "\n //напишите тут ваш код\n\n map.put(\"Stallone\", new Date(\"JUNE 1 1980\"));\n map.put(\"Arno", "end": 699, "score": 0.9982452988624573, "start": 691, "tag": "NAME", "value": "Stallone" }, { "context": "lone\", new Date(\"JUNE 1 1980\"));\n map.put(\"Arnold\", new Date(\"MAY 1 1990\"));\n map.put(\"Obama", "end": 751, "score": 0.9990544319152832, "start": 745, "tag": "NAME", "value": "Arnold" }, { "context": "rnold\", new Date(\"MAY 1 1990\"));\n map.put(\"Obama\", new Date(\"JULY 1 1990\"));\n map.put(\"VanD", "end": 801, "score": 0.9985188841819763, "start": 796, "tag": "NAME", "value": "Obama" }, { "context": "bama\", new Date(\"JULY 1 1990\"));\n map.put(\"VanDam\", new Date(\"DECEMBER 1 1990\"));\n map.put(\"", "end": 853, "score": 0.997948169708252, "start": 847, "tag": "NAME", "value": "VanDam" }, { "context": "\", new Date(\"DECEMBER 1 1990\"));\n map.put(\"VanGoh\", new Date(\"AUGUST 1 1990\"));\n map.put(\"Va", "end": 909, "score": 0.9981265068054199, "start": 903, "tag": "NAME", "value": "VanGoh" }, { "context": "oh\", new Date(\"AUGUST 1 1990\"));\n map.put(\"Vancent\", new Date(\"SEPTEMBER 1 1990\"));\n map.put(", "end": 964, "score": 0.9963841438293457, "start": 957, "tag": "NAME", "value": "Vancent" }, { "context": ", new Date(\"SEPTEMBER 1 1990\"));\n map.put(\"Banderos\", new Date(\"NOVEMBER 1 1990\"));\n map.put(\"", "end": 1023, "score": 0.9985026717185974, "start": 1015, "tag": "NAME", "value": "Banderos" }, { "context": "\", new Date(\"NOVEMBER 1 1990\"));\n map.put(\"Gitler\", new Date(\"OCTOBER 1 1990\"));\n map.put(\"W", "end": 1079, "score": 0.9982649683952332, "start": 1073, "tag": "NAME", "value": "Gitler" }, { "context": "r\", new Date(\"OCTOBER 1 1990\"));\n map.put(\"Worh\", new Date(\"OCTOBER 1 1990\"));\n map.put(\"S", "end": 1132, "score": 0.997821033000946, "start": 1128, "tag": "NAME", "value": "Worh" }, { "context": "h\", new Date(\"OCTOBER 1 1990\"));\n map.put(\"Stef\", new Date(\"OCTOBER 1 1990\"));\n return map", "end": 1185, "score": 0.9955289959907532, "start": 1181, "tag": "NAME", "value": "Stef" } ]
null
[]
package com.javarush.test.level08.lesson08.task04; import java.util.*; /* Удалить всех людей, родившихся летом Создать словарь (Map<String, Date>) и занести в него десять записей по принципу: «фамилия» - «дата рождения». Удалить из словаря всех людей, родившихся летом. */ public class Solution { public static void main(String[] args) { HashMap<String, Date> map = createMap(); removeAllSummerPeople(map); for (String name : map.keySet()) System.out.println(name); } public static HashMap<String, Date> createMap() { HashMap<String, Date> map = new HashMap<String, Date>(); //напишите тут ваш код map.put("Stallone", new Date("JUNE 1 1980")); map.put("Arnold", new Date("MAY 1 1990")); map.put("Obama", new Date("JULY 1 1990")); map.put("VanDam", new Date("DECEMBER 1 1990")); map.put("VanGoh", new Date("AUGUST 1 1990")); map.put("Vancent", new Date("SEPTEMBER 1 1990")); map.put("Banderos", new Date("NOVEMBER 1 1990")); map.put("Gitler", new Date("OCTOBER 1 1990")); map.put("Worh", new Date("OCTOBER 1 1990")); map.put("Stef", new Date("OCTOBER 1 1990")); return map; } public static void removeAllSummerPeople(HashMap<String, Date> map) { //напишите тут ваш код ArrayList<String> arrayList = new ArrayList<>(); for (Iterator<Map.Entry<String, Date>> iterator = map.entrySet().iterator(); iterator.hasNext() ; ) { Map.Entry<String, Date> pair = iterator.next(); Date value = pair.getValue(); if (value.getMonth() > 4 && value.getMonth() < 8) arrayList.add(pair.getKey()); } for (String s : arrayList) map.remove(s); } }
1,993
0.593939
0.561983
58
30.293104
27.714685
109
false
false
0
0
0
0
0
0
0.758621
false
false
4
558fefd167189cd1492214960698a6bfe031a4a5
22,273,700,463,377
01767b3590765781b1ef6205fec4d80f4a4d24f9
/src/main/java/student_alexander_shl/homework/lesson_2/level_1/task_1/Task_1.java
9419fdc4b8115dc1fad8b99fdfac2643d4724cab
[]
no_license
ApTyPuk/java_1_monday_2020_online
https://github.com/ApTyPuk/java_1_monday_2020_online
127284d6f58a28862dd2682b62fb5c0237d3e8c0
c16bb3786d00a16ff7a70276b967caebbbc0d476
refs/heads/master
2023-02-04T06:22:19.475000
2020-12-22T00:13:46
2020-12-22T00:13:46
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package student_alexander_shl.homework.lesson_2.level_1.task_1; import teacher.annotations.CodeReview; import java.util.Scanner; @CodeReview(approved = true) class Task_1 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Please enter first number: "); int firstNumber = scanner.nextInt(); System.out.println("Please enter second number: "); int secondNumber = scanner.nextInt(); int sumResult = firstNumber + secondNumber; System.out.println("Sum: " + sumResult); int multiplyResult = firstNumber * secondNumber; System.out.println("Multiply: " + multiplyResult); int subtractionResult = firstNumber - secondNumber; System.out.println("Subtraction: " + subtractionResult); int divisionResult = firstNumber / secondNumber; System.out.println("Division: " + divisionResult); } }
UTF-8
Java
955
java
Task_1.java
Java
[]
null
[]
package student_alexander_shl.homework.lesson_2.level_1.task_1; import teacher.annotations.CodeReview; import java.util.Scanner; @CodeReview(approved = true) class Task_1 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Please enter first number: "); int firstNumber = scanner.nextInt(); System.out.println("Please enter second number: "); int secondNumber = scanner.nextInt(); int sumResult = firstNumber + secondNumber; System.out.println("Sum: " + sumResult); int multiplyResult = firstNumber * secondNumber; System.out.println("Multiply: " + multiplyResult); int subtractionResult = firstNumber - secondNumber; System.out.println("Subtraction: " + subtractionResult); int divisionResult = firstNumber / secondNumber; System.out.println("Division: " + divisionResult); } }
955
0.671204
0.667016
32
28.84375
25.645552
64
false
false
0
0
0
0
0
0
0.5
false
false
4
5d77b1cd79ecd9ba75c25976f5431ffffdfcbe27
32,341,103,758,834
6bf350a4a289a3899a3b1b7714f540148f5406cd
/src/main/java/it/polimi/ingsw/HANDLER/ResourcePerMissedExcommunicationHandler.java
fe3c1fef4182fb80d6dc3aadbd66bd4ce1ab88a8
[]
no_license
michelepapale1996/Lorenzo-il-Magnifico
https://github.com/michelepapale1996/Lorenzo-il-Magnifico
90e1e08e2355e7cf035b382fd6afbc482e100f21
74c83eb157c4afe42496802ec4a5391342e2c347
refs/heads/master
2020-08-02T15:17:47.419000
2017-07-10T09:20:41
2017-07-10T09:20:41
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package it.polimi.ingsw.HANDLER; import java.util.ArrayList; import it.polimi.ingsw.BONUS.AddResourceBonus; import it.polimi.ingsw.BONUS.ADVANCED.PermanentBonus; import it.polimi.ingsw.BONUS.ADVANCED.ResourcePerMissedExcommunicationBonus; import it.polimi.ingsw.GC_15.Player; import it.polimi.ingsw.RESOURCE.Resource; //give a player all the bonus when miss an excommunication public class ResourcePerMissedExcommunicationHandler { public static void handle(Player player){ ArrayList<PermanentBonus> playerBonus = player.getPersonalBoard().getPermanentBonus(); if (playerBonus != null){ for (PermanentBonus permanentBonus : playerBonus) { if (permanentBonus instanceof ResourcePerMissedExcommunicationBonus){ ArrayList<Resource> resources = ((ResourcePerMissedExcommunicationBonus) permanentBonus).getResources(); AddResourceBonus missedExcommunicationBonus = new AddResourceBonus(resources); missedExcommunicationBonus.getImmediateBonus(player); } } } } }
UTF-8
Java
1,027
java
ResourcePerMissedExcommunicationHandler.java
Java
[]
null
[]
package it.polimi.ingsw.HANDLER; import java.util.ArrayList; import it.polimi.ingsw.BONUS.AddResourceBonus; import it.polimi.ingsw.BONUS.ADVANCED.PermanentBonus; import it.polimi.ingsw.BONUS.ADVANCED.ResourcePerMissedExcommunicationBonus; import it.polimi.ingsw.GC_15.Player; import it.polimi.ingsw.RESOURCE.Resource; //give a player all the bonus when miss an excommunication public class ResourcePerMissedExcommunicationHandler { public static void handle(Player player){ ArrayList<PermanentBonus> playerBonus = player.getPersonalBoard().getPermanentBonus(); if (playerBonus != null){ for (PermanentBonus permanentBonus : playerBonus) { if (permanentBonus instanceof ResourcePerMissedExcommunicationBonus){ ArrayList<Resource> resources = ((ResourcePerMissedExcommunicationBonus) permanentBonus).getResources(); AddResourceBonus missedExcommunicationBonus = new AddResourceBonus(resources); missedExcommunicationBonus.getImmediateBonus(player); } } } } }
1,027
0.781889
0.779942
27
36.037037
31.809015
109
false
false
0
0
0
0
0
0
1.814815
false
false
4
ad99ae0ac72622e97ea3b83cae4b9bec2a47b824
25,116,968,747,621
dd3039fee673809ab42b66c9d2621e017f7c8ecb
/main/bread/src/main/java/com/example/team/bread/ingredients/Flour.java
e223e50f734efcd4c6550d164795548155bba79f
[]
no_license
mikexliu/maven-example
https://github.com/mikexliu/maven-example
a684c4937a99a7c0f6aead0e73158940c2980793
ecb6f231f0bc166532f767499f5c8fee275dda92
refs/heads/master
2015-08-09T19:57:21.458000
2014-01-17T06:33:26
2014-01-17T06:33:26
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.team.bread.ingredients; public class Flour { }
UTF-8
Java
69
java
Flour.java
Java
[]
null
[]
package com.example.team.bread.ingredients; public class Flour { }
69
0.768116
0.768116
5
12.8
16.916264
43
false
false
0
0
0
0
0
0
0.2
false
false
4
5713e8bf5ce72085b983833c4f991cbea8f22894
30,107,720,801,750
c2d64a45e7bee3ec4710c12c9f8901eed1e16a2e
/src/main/java/by/htp/epam/cinema/domain/Film.java
e624f6ac63b26998bf7bb53632d34a82c4c3e143
[]
no_license
PatskoArkadzi/HTP_EPAM_cinema
https://github.com/PatskoArkadzi/HTP_EPAM_cinema
ee46326dcd66b69b003f7aa3f8a791e0c99a1300
351a22c80adc64061e607a8ff8efa8fdf2233c69
refs/heads/master
2020-03-25T08:18:11.150000
2018-10-04T21:40:19
2018-10-04T21:40:19
143,606,091
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package by.htp.epam.cinema.domain; /** * Class describing Film entity * * @author Arkadzi Patsko * */ public class Film extends BaseEntity { /** * An unique serial version identifier */ private static final long serialVersionUID = -2248408866984238822L; /** * Film name */ private String filmName; /** * Film description */ private String description; /** * Film posterUrl */ private String posterUrl; /** * Film youTubeVideoId */ private String youTubeVideoId; /** * Constructor without parameters */ private Film() { } /** * @return {@link #filmName} */ public String getFilmName() { return filmName; } /** * @return {@link #description} */ public String getDescription() { return description; } /** * @return {@link #posterUrl} */ public String getPosterUrl() { return posterUrl; } /** * @return {@link #youTubeVideoId} */ public String getYouTubeVideoId() { return youTubeVideoId; } /** * {@inheritDoc} * */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; Film other = (Film) obj; if (getId() != other.getId()) { return false; } if (description == null) { if (other.description != null) return false; } else if (!description.equals(other.description)) return false; if (filmName == null) { if (other.filmName != null) return false; } else if (!filmName.equals(other.filmName)) return false; if (posterUrl == null) { if (other.posterUrl != null) return false; } else if (!posterUrl.equals(other.posterUrl)) return false; if (youTubeVideoId == null) { if (other.youTubeVideoId != null) return false; } else if (!youTubeVideoId.equals(other.youTubeVideoId)) return false; return true; } /** * {@inheritDoc} * */ @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * getId(); result = prime * result + ((description == null) ? 0 : description.hashCode()); result = prime * result + ((filmName == null) ? 0 : filmName.hashCode()); result = prime * result + ((posterUrl == null) ? 0 : posterUrl.hashCode()); result = prime * result + ((youTubeVideoId == null) ? 0 : youTubeVideoId.hashCode()); return result; } /** * {@inheritDoc} * */ @Override public String toString() { return "Film [id=" + getId() + ", filmName=" + filmName + ", description=" + description + ", posterUrl=" + posterUrl + ", youTubeVideoId=" + youTubeVideoId + "]"; } /** * Static method for create inner Builder class object * * @return inner Builder class object */ public static Builder newBuilder() { return new Film().new Builder(); } /** * Inner class for build Film class object * * @author Arkadzi Patsko * */ public class Builder { /** * Constructor without parameters */ private Builder() { } /** * Sets id * * @param id * {@link #id} * @return Builder class object */ public Builder setId(int id) { Film.this.setId(id); return this; } /** * Sets film name * * @param filmName * {@link #filmName} * @return Builder class object */ public Builder setFilmName(String filmName) { Film.this.filmName = filmName; return this; } /** * Sets film description * * @param description * {@link #description} * @return Builder class object */ public Builder setDescription(String description) { Film.this.description = description; return this; } /** * Sets film poster URL. * * @param posterUrl * {@link #posterUrl} * @return Builder class object */ public Builder setPosterUrl(String posterUrl) { Film.this.posterUrl = posterUrl; return this; } /** * Sets film youTube video id. * * @param youTubeVideoId * {@link #youTubeVideoId} * @return Builder class object */ public Builder setYouTubeVideoId(String youTubeVideoId) { Film.this.youTubeVideoId = youTubeVideoId; return this; } /** * @return ready Film class object */ public Film build() { return Film.this; } } }
UTF-8
Java
4,530
java
Film.java
Java
[ { "context": "\r\n * Class describing Film entity\r\n * \r\n * @author Arkadzi Patsko\r\n *\r\n */\r\npublic class Film extends BaseEntity {\r\n\r", "end": 106, "score": 0.9817782640457153, "start": 92, "tag": "NAME", "value": "Arkadzi Patsko" }, { "context": "ass for build Film class object\r\n\t * \r\n\t * @author Arkadzi Patsko\r\n\t *\r\n\t */\r\n\tpublic class Builder {\r\n\r\n\t\t/**\r\n\t\t ", "end": 3045, "score": 0.9998441338539124, "start": 3031, "tag": "NAME", "value": "Arkadzi Patsko" } ]
null
[]
package by.htp.epam.cinema.domain; /** * Class describing Film entity * * @author <NAME> * */ public class Film extends BaseEntity { /** * An unique serial version identifier */ private static final long serialVersionUID = -2248408866984238822L; /** * Film name */ private String filmName; /** * Film description */ private String description; /** * Film posterUrl */ private String posterUrl; /** * Film youTubeVideoId */ private String youTubeVideoId; /** * Constructor without parameters */ private Film() { } /** * @return {@link #filmName} */ public String getFilmName() { return filmName; } /** * @return {@link #description} */ public String getDescription() { return description; } /** * @return {@link #posterUrl} */ public String getPosterUrl() { return posterUrl; } /** * @return {@link #youTubeVideoId} */ public String getYouTubeVideoId() { return youTubeVideoId; } /** * {@inheritDoc} * */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; Film other = (Film) obj; if (getId() != other.getId()) { return false; } if (description == null) { if (other.description != null) return false; } else if (!description.equals(other.description)) return false; if (filmName == null) { if (other.filmName != null) return false; } else if (!filmName.equals(other.filmName)) return false; if (posterUrl == null) { if (other.posterUrl != null) return false; } else if (!posterUrl.equals(other.posterUrl)) return false; if (youTubeVideoId == null) { if (other.youTubeVideoId != null) return false; } else if (!youTubeVideoId.equals(other.youTubeVideoId)) return false; return true; } /** * {@inheritDoc} * */ @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * getId(); result = prime * result + ((description == null) ? 0 : description.hashCode()); result = prime * result + ((filmName == null) ? 0 : filmName.hashCode()); result = prime * result + ((posterUrl == null) ? 0 : posterUrl.hashCode()); result = prime * result + ((youTubeVideoId == null) ? 0 : youTubeVideoId.hashCode()); return result; } /** * {@inheritDoc} * */ @Override public String toString() { return "Film [id=" + getId() + ", filmName=" + filmName + ", description=" + description + ", posterUrl=" + posterUrl + ", youTubeVideoId=" + youTubeVideoId + "]"; } /** * Static method for create inner Builder class object * * @return inner Builder class object */ public static Builder newBuilder() { return new Film().new Builder(); } /** * Inner class for build Film class object * * @author <NAME> * */ public class Builder { /** * Constructor without parameters */ private Builder() { } /** * Sets id * * @param id * {@link #id} * @return Builder class object */ public Builder setId(int id) { Film.this.setId(id); return this; } /** * Sets film name * * @param filmName * {@link #filmName} * @return Builder class object */ public Builder setFilmName(String filmName) { Film.this.filmName = filmName; return this; } /** * Sets film description * * @param description * {@link #description} * @return Builder class object */ public Builder setDescription(String description) { Film.this.description = description; return this; } /** * Sets film poster URL. * * @param posterUrl * {@link #posterUrl} * @return Builder class object */ public Builder setPosterUrl(String posterUrl) { Film.this.posterUrl = posterUrl; return this; } /** * Sets film youTube video id. * * @param youTubeVideoId * {@link #youTubeVideoId} * @return Builder class object */ public Builder setYouTubeVideoId(String youTubeVideoId) { Film.this.youTubeVideoId = youTubeVideoId; return this; } /** * @return ready Film class object */ public Film build() { return Film.this; } } }
4,514
0.582781
0.577263
225
18.133333
18.302399
107
false
false
0
0
0
0
0
0
1.72
false
false
4
c3a7d390728b6ee0c61ae253dbd0134d119d48da
24,386,824,373,326
d2b43cb133145612bbfd26d3f8cf3fb2d24d4959
/src/LogicalOpTable.java
2f1ca062e5a95367d3809b0467555b75fde68d8b
[]
no_license
Itanik/javaLearn
https://github.com/Itanik/javaLearn
ac8307ddf46478b43a4d8fcfe2a0f2124813ccf2
efa28f7871ec7d86af0d3f427906578345abbc96
refs/heads/master
2018-12-05T17:34:55.869000
2018-09-15T15:26:44
2018-09-15T15:26:44
146,700,198
0
0
null
false
2018-09-10T10:04:06
2018-08-30T05:32:31
2018-09-10T09:46:35
2018-09-10T10:04:06
1
0
0
0
Java
false
null
public class LogicalOpTable { public static void main (String[] args) { boolean p,q; System.out.println("P\tQ\tAND\tOR\tXOR\tNOT"); p = true; q = true; System.out.print(b(p) + "\t" + b(q) + "\t"); System.out.print(b(p&q) + "\t" + b(p|q) + "\t"); System.out.println(b(p^q) + "\t" + b(!p)); p = true; q = false; System.out.print(b(p) + "\t" + b(q) + "\t"); System.out.print(b(p&q) + "\t" + b(p|q) + "\t"); System.out.println(b(p^q) + "\t" + b(!p)); p = false; q = true; System.out.print(b(p) + "\t" + b(q) + "\t"); System.out.print(b(p&q) + "\t" + b(p|q) + "\t"); System.out.println(b(p^q) + "\t" + b(!p)); p = false; q = false; System.out.print(b(p) + "\t" + b(q) + "\t"); System.out.print(b(p&q) + "\t" + b(p|q) + "\t"); System.out.println(b(p^q) + "\t" + b(!p)); } private static byte b (boolean bool) { if (bool) return 1; else return 0; } }
UTF-8
Java
891
java
LogicalOpTable.java
Java
[]
null
[]
public class LogicalOpTable { public static void main (String[] args) { boolean p,q; System.out.println("P\tQ\tAND\tOR\tXOR\tNOT"); p = true; q = true; System.out.print(b(p) + "\t" + b(q) + "\t"); System.out.print(b(p&q) + "\t" + b(p|q) + "\t"); System.out.println(b(p^q) + "\t" + b(!p)); p = true; q = false; System.out.print(b(p) + "\t" + b(q) + "\t"); System.out.print(b(p&q) + "\t" + b(p|q) + "\t"); System.out.println(b(p^q) + "\t" + b(!p)); p = false; q = true; System.out.print(b(p) + "\t" + b(q) + "\t"); System.out.print(b(p&q) + "\t" + b(p|q) + "\t"); System.out.println(b(p^q) + "\t" + b(!p)); p = false; q = false; System.out.print(b(p) + "\t" + b(q) + "\t"); System.out.print(b(p&q) + "\t" + b(p|q) + "\t"); System.out.println(b(p^q) + "\t" + b(!p)); } private static byte b (boolean bool) { if (bool) return 1; else return 0; } }
891
0.506173
0.503928
29
29.724138
18.435154
50
false
false
0
0
0
0
0
0
2.517241
false
false
4
492827369f2003e7a79e1e03af81a59567f44807
326,417,559,340
5f68e01820b6ac97debca0147e1a66e179dc9da0
/s2chronos-sastruts-example/src/main/java/org/seasar/chronos/sastruts/example/form/MemberForm.java
0200f584de3a9c516e4db50261361e2cb4578d16
[]
no_license
singletonton/s2chronos
https://github.com/singletonton/s2chronos
5a5e57917e8a43f609e40da9bbd7badb02f05eb5
bdd1c7ddcf9c2f66d90529829f44b84923cb674a
refs/heads/master
2016-08-09T07:09:10.446000
2014-01-18T17:15:51
2014-01-18T17:15:51
47,863,307
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.seasar.chronos.sastruts.example.form; import org.seasar.struts.annotation.EmailType; import org.seasar.struts.annotation.Maxlength; import org.seasar.struts.annotation.Required; public class MemberForm { public Long userId; @Required @Maxlength(maxlength = 255) public String userName; @Required @EmailType public String email; @Maxlength(maxlength = 255) public String lastName; @Maxlength(maxlength = 255) public String firstName; public Integer userStatus; public Long versionNo; public Long targetUserId; public void initialize() { userId = null; userName = null; email = null; lastName = null; firstName = null; userStatus = null; targetUserId = null; versionNo = null; } }
UTF-8
Java
779
java
MemberForm.java
Java
[]
null
[]
package org.seasar.chronos.sastruts.example.form; import org.seasar.struts.annotation.EmailType; import org.seasar.struts.annotation.Maxlength; import org.seasar.struts.annotation.Required; public class MemberForm { public Long userId; @Required @Maxlength(maxlength = 255) public String userName; @Required @EmailType public String email; @Maxlength(maxlength = 255) public String lastName; @Maxlength(maxlength = 255) public String firstName; public Integer userStatus; public Long versionNo; public Long targetUserId; public void initialize() { userId = null; userName = null; email = null; lastName = null; firstName = null; userStatus = null; targetUserId = null; versionNo = null; } }
779
0.702182
0.690629
43
16.11628
14.312475
49
false
false
0
0
0
0
0
0
1.209302
false
false
4
f3fdd3f657778ea927f36cb934cd28b2becf0885
15,350,213,152,602
221ead91f310a1caf41ca596ebee4af026ccb891
/app/src/main/java/com/base/application/baseapplication/utils/DimenUtils.java
82daedb486dab0887d4e02670427678eba90dddf
[]
no_license
JerryCaicos/baseroot
https://github.com/JerryCaicos/baseroot
b36d46d13f61027c9abcc7599407d2cef1f15565
6da758638851610d18a20cb9a6842cc8c8203e14
refs/heads/master
2020-12-02T18:14:28.030000
2018-03-08T08:51:39
2018-03-08T08:51:39
96,501,297
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.base.application.baseapplication.utils; import android.content.Context; import android.util.DisplayMetrics; import android.view.Display; /** * Created by JerryCaicos on 16/1/16. */ public class DimenUtils { /** * @Description: dip转换为px */ public static int dip2px(Context context, float dipValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (dipValue * scale + 0.5f); } /** * 得到当前分辨率 * * @param mContext * @return */ public static float[] getResolution(Context mContext) { DisplayMetrics dm = mContext.getResources().getDisplayMetrics(); float width = dm.widthPixels; float height = dm.heightPixels; float density = dm.density; float[] str = {height, width, density}; return str; } /** * @Description: px转换为dip */ public static int px2dip(Context context, float pxValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (pxValue / scale + 0.5f); } /** * @Description: sp转换为px */ public static int sp2px(Context context, float spValue) { final float fontScale = context.getResources().getDisplayMetrics().scaledDensity; return (int) (spValue * fontScale + 0.5f); } }
UTF-8
Java
1,414
java
DimenUtils.java
Java
[ { "context": "s;\nimport android.view.Display;\n\n/**\n * Created by JerryCaicos on 16/1/16.\n */\npublic class DimenUtils\n{\n\n /*", "end": 180, "score": 0.9980216026306152, "start": 169, "tag": "USERNAME", "value": "JerryCaicos" } ]
null
[]
package com.base.application.baseapplication.utils; import android.content.Context; import android.util.DisplayMetrics; import android.view.Display; /** * Created by JerryCaicos on 16/1/16. */ public class DimenUtils { /** * @Description: dip转换为px */ public static int dip2px(Context context, float dipValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (dipValue * scale + 0.5f); } /** * 得到当前分辨率 * * @param mContext * @return */ public static float[] getResolution(Context mContext) { DisplayMetrics dm = mContext.getResources().getDisplayMetrics(); float width = dm.widthPixels; float height = dm.heightPixels; float density = dm.density; float[] str = {height, width, density}; return str; } /** * @Description: px转换为dip */ public static int px2dip(Context context, float pxValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (pxValue / scale + 0.5f); } /** * @Description: sp转换为px */ public static int sp2px(Context context, float spValue) { final float fontScale = context.getResources().getDisplayMetrics().scaledDensity; return (int) (spValue * fontScale + 0.5f); } }
1,414
0.62301
0.61288
55
24.127274
24.342297
89
false
false
0
0
0
0
0
0
0.381818
false
false
4
f3442296450ccdb9906e227df9685ee7e1427c54
13,073,880,464,967
010812e68a41054fafce519f98a36f41890c1f6a
/src/main/java/com/zjgsu/forum/module/topic/model/Topic.java
700cbe122277be8f61224fbd654d3cfc98a8ce48
[]
no_license
quentinschuman/forum
https://github.com/quentinschuman/forum
8efc6171cc677cb681116540436fafc1f16a3257
6374435a19550428b69970788ffa0ee7acdc9208
refs/heads/master
2020-03-21T13:14:20.769000
2018-07-09T03:02:02
2018-07-09T03:02:02
138,594,722
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.zjgsu.forum.module.topic.model; import com.fasterxml.jackson.annotation.JsonFormat; import com.zjgsu.forum.core.util.Constants; import lombok.Getter; import lombok.Setter; import javax.persistence.*; import java.io.Serializable; import java.util.Date; /** * Created by IntelliJ IDEA. * ProjectName: forum * User: quent * Date: 2018/6/27 * Time: 21:41 */ @Entity @Table(name = "forum_topic") @Getter @Setter public class Topic implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(unique = true,nullable = false) private String title; @Column(columnDefinition = "text") private String content; @Column(nullable = false) @JsonFormat(pattern = Constants.DATETIME_FORMAT) private Date inTime; @JsonFormat(pattern = Constants.DATETIME_FORMAT) @Column(name = "modify_time") private Date modifyTime; @JsonFormat(pattern = Constants.DATETIME_FORMAT) @Column(name = "last_comment_time") private Date lastCommentTime; private Boolean top; private Boolean good; @Column(nullable = false) private Integer view; private Integer userId; @Column(name = "comment_count") private Integer commentCount; private Integer up; private Integer down; @Column(columnDefinition = "text") private String upIds; @Column(columnDefinition = "text") private String downIds; @Column(columnDefinition = "DOUBLE DEFAULT 0.0") private Double weight; private String tag; }
UTF-8
Java
1,557
java
Topic.java
Java
[ { "context": "d by IntelliJ IDEA.\n * ProjectName: forum\n * User: quent\n * Date: 2018/6/27\n * Time: 21:41\n */\n@Entity\n@Ta", "end": 336, "score": 0.9995293617248535, "start": 331, "tag": "USERNAME", "value": "quent" } ]
null
[]
package com.zjgsu.forum.module.topic.model; import com.fasterxml.jackson.annotation.JsonFormat; import com.zjgsu.forum.core.util.Constants; import lombok.Getter; import lombok.Setter; import javax.persistence.*; import java.io.Serializable; import java.util.Date; /** * Created by IntelliJ IDEA. * ProjectName: forum * User: quent * Date: 2018/6/27 * Time: 21:41 */ @Entity @Table(name = "forum_topic") @Getter @Setter public class Topic implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(unique = true,nullable = false) private String title; @Column(columnDefinition = "text") private String content; @Column(nullable = false) @JsonFormat(pattern = Constants.DATETIME_FORMAT) private Date inTime; @JsonFormat(pattern = Constants.DATETIME_FORMAT) @Column(name = "modify_time") private Date modifyTime; @JsonFormat(pattern = Constants.DATETIME_FORMAT) @Column(name = "last_comment_time") private Date lastCommentTime; private Boolean top; private Boolean good; @Column(nullable = false) private Integer view; private Integer userId; @Column(name = "comment_count") private Integer commentCount; private Integer up; private Integer down; @Column(columnDefinition = "text") private String upIds; @Column(columnDefinition = "text") private String downIds; @Column(columnDefinition = "DOUBLE DEFAULT 0.0") private Double weight; private String tag; }
1,557
0.703918
0.695568
71
20.929577
16.859255
55
false
false
0
0
0
0
0
0
0.366197
false
false
4
94360f3d82ed4b662b2bb196497fa7da824574f1
31,482,110,304,241
953659441fb36878c211c7dba3f88f21b00439d2
/JC-HW-lesson 12/src/lviv/lgs/ua/task2/MainApp.java
9bffb116bfc889d09a4aace0cced93b685350a5f
[]
no_license
Stacy-Kucherenko/JAVA-CORE-hw-lesson12
https://github.com/Stacy-Kucherenko/JAVA-CORE-hw-lesson12
b198e6d9bc89051adc342c5f7d9ff1bf2f9acce7
20ccb3fe711b0ca5b41030bd78397dd1ab27c379
refs/heads/master
2023-04-11T15:45:38.894000
2021-04-30T20:52:56
2021-04-30T20:52:56
363,255,825
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package lviv.lgs.ua.task2; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class MainApp { enum Seasons { WINTER, SPRING, SUMMER, FALL; } enum Months { DECEMBER(Seasons.WINTER, 31), JANUARY(Seasons.WINTER, 30), FEBRUARY(Seasons.WINTER, 28), MARCH(Seasons.SPRING, 31), APRIL(Seasons.SPRING, 30), MAY(Seasons.SPRING, 31), JUNE(Seasons.SUMMER, 30), JULY(Seasons.SUMMER, 31), AUGUST(Seasons.SUMMER, 31), SEPTEMBER(Seasons.FALL, 30), OCTOBER(Seasons.FALL, 31), NOVEMBER(Seasons.FALL, 30); Seasons seasons; int days; private Months(Seasons seasons, int days) { this.seasons = seasons; this.days = days; } public Seasons getSeasons() { return seasons; } public int getDays() { return days; } } static void menu() { System.out.println("Натисніть 1, щоб пеевірити чи існує такий місяць "); System.out.println("Натисніть 2, щоб вивести всі місяці які мають таку саму кількість днів "); System.out.println("Натисніть 3, щоб вивести на екран всі місяці які мають меншу кількість днів "); System.out.println("Натисніть 4, щоб вивести на екран всі місяці які мають більшу кількість днів "); System.out.println("Натисніть 5, щоб вивести на екран наступну пору року "); System.out.println("Натисніть 6, щоб вивести на екран попередню пору року"); System.out.println("Натисніть 7, щоб вивести на екран всі місяці які мають парну кількість днів"); System.out.println("Натисніть 8, щоб вивести на екран всі місяці які мають непарну кількість днів"); System.out.println("Натисніть 9, щоб вивести на екран чи введений з консолі місяць має парну кількість днів"); } public static void main(String[] args) { // Months[] mas = Months.values(); ArrayList <Months> arrayMonthList = new ArrayList <Months>(); Scanner sc = new Scanner(System.in); for (Months monthsValue : Months.values()) { arrayMonthList.add(monthsValue); } ArrayList <Seasons> arraySeasonList = new ArrayList <Seasons>(); for (Seasons seasonsValue : Seasons.values()) { arraySeasonList.add(seasonsValue); } while (true) { menu(); switch (sc.next()) { case "1": { System.out.println("Enter month "); sc = new Scanner(System.in); String months = sc.next().toUpperCase(); boolean flag = areMonthsExist(arrayMonthList, months); if (!flag) { System.out.println("Month dosen't exist "); } break; } case "2": { System.out.println("Enter number of days per month "); sc = new Scanner(System.in); int days = sc.nextInt(); boolean flag = false; for (Months m : arrayMonthList) { if (m.getDays() == days) { System.out.println(m); flag = true; } } if (!flag) { System.out.println("Month wich has such number of the days dosen't exist"); } break; } case "3": { System.out.println("Enter number of the days "); sc = new Scanner(System.in); int days = sc.nextInt(); boolean flag = false; for (Months m : arrayMonthList) { if (m.getDays() < days) { System.out.println(m); flag = true; } if (!flag) { System.out.println("Month with less amount of the days dosen't exist"); } break; } } case "4": { System.out.println("Enter number of the days "); sc = new Scanner(System.in); int days = sc.nextInt(); boolean flag = false; for (Months m : arrayMonthList) { if (m.getDays() > days) { System.out.println(m); flag = true; } if (!flag) { System.out.println("Month with bigger amount of the days dosen't exist"); } } } case "5": { System.out.println("Enter season "); sc = new Scanner(System.in); String seasons = sc.nextLine().toUpperCase(); //Seasons[] season = Seasons.values(); Seasons season1 = Seasons.valueOf(seasons); int ordinal = season1.ordinal(); if (ordinal == arraySeasonList.size()) { ordinal = -1; } System.out.println(arraySeasonList.get(ordinal + 1)); } case "6": { System.out.println("Enter season "); sc = new Scanner(System.in); String seasons = sc.nextLine().toUpperCase(); //Seasons[] season = Seasons.values(); Seasons season1 = Seasons.valueOf(seasons); int ordinal = season1.ordinal(); if (ordinal == arraySeasonList.size()-1) { ordinal = 0; } System.out.println(arraySeasonList.get(ordinal - 1)); } case "7": { System.out.println("Months with paired number of days: "); for (Months m : arrayMonthList) { if (m.getDays() % 2 == 0) { System.out.println(m); } } } case "8": { System.out.println("Months with unpaired number of days: "); for (Months m : arrayMonthList) { if (m.getDays() % 2 != 0) { System.out.println(m); } } } case "9": { System.out.println("Enter month "); sc = new Scanner(System.in); String months = sc.next().toUpperCase(); boolean flag = false; for (Months m : arrayMonthList) { if (m.toString().equals(months) && m.getDays() % 2 == 0) { System.out.println("This month has paired number of days "); flag = true; } } if (!flag) { System.out.println("This month has unpaired number of days "); } } } } } private static boolean areMonthsExist(ArrayList<Months> arrayMonthList, String months) { boolean flag = false; for (Months m : arrayMonthList) { if (m.name().equals(months)) { System.out.println("Month is exist "); flag = true; } } return flag; } }
WINDOWS-1251
Java
6,109
java
MainApp.java
Java
[]
null
[]
package lviv.lgs.ua.task2; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class MainApp { enum Seasons { WINTER, SPRING, SUMMER, FALL; } enum Months { DECEMBER(Seasons.WINTER, 31), JANUARY(Seasons.WINTER, 30), FEBRUARY(Seasons.WINTER, 28), MARCH(Seasons.SPRING, 31), APRIL(Seasons.SPRING, 30), MAY(Seasons.SPRING, 31), JUNE(Seasons.SUMMER, 30), JULY(Seasons.SUMMER, 31), AUGUST(Seasons.SUMMER, 31), SEPTEMBER(Seasons.FALL, 30), OCTOBER(Seasons.FALL, 31), NOVEMBER(Seasons.FALL, 30); Seasons seasons; int days; private Months(Seasons seasons, int days) { this.seasons = seasons; this.days = days; } public Seasons getSeasons() { return seasons; } public int getDays() { return days; } } static void menu() { System.out.println("Натисніть 1, щоб пеевірити чи існує такий місяць "); System.out.println("Натисніть 2, щоб вивести всі місяці які мають таку саму кількість днів "); System.out.println("Натисніть 3, щоб вивести на екран всі місяці які мають меншу кількість днів "); System.out.println("Натисніть 4, щоб вивести на екран всі місяці які мають більшу кількість днів "); System.out.println("Натисніть 5, щоб вивести на екран наступну пору року "); System.out.println("Натисніть 6, щоб вивести на екран попередню пору року"); System.out.println("Натисніть 7, щоб вивести на екран всі місяці які мають парну кількість днів"); System.out.println("Натисніть 8, щоб вивести на екран всі місяці які мають непарну кількість днів"); System.out.println("Натисніть 9, щоб вивести на екран чи введений з консолі місяць має парну кількість днів"); } public static void main(String[] args) { // Months[] mas = Months.values(); ArrayList <Months> arrayMonthList = new ArrayList <Months>(); Scanner sc = new Scanner(System.in); for (Months monthsValue : Months.values()) { arrayMonthList.add(monthsValue); } ArrayList <Seasons> arraySeasonList = new ArrayList <Seasons>(); for (Seasons seasonsValue : Seasons.values()) { arraySeasonList.add(seasonsValue); } while (true) { menu(); switch (sc.next()) { case "1": { System.out.println("Enter month "); sc = new Scanner(System.in); String months = sc.next().toUpperCase(); boolean flag = areMonthsExist(arrayMonthList, months); if (!flag) { System.out.println("Month dosen't exist "); } break; } case "2": { System.out.println("Enter number of days per month "); sc = new Scanner(System.in); int days = sc.nextInt(); boolean flag = false; for (Months m : arrayMonthList) { if (m.getDays() == days) { System.out.println(m); flag = true; } } if (!flag) { System.out.println("Month wich has such number of the days dosen't exist"); } break; } case "3": { System.out.println("Enter number of the days "); sc = new Scanner(System.in); int days = sc.nextInt(); boolean flag = false; for (Months m : arrayMonthList) { if (m.getDays() < days) { System.out.println(m); flag = true; } if (!flag) { System.out.println("Month with less amount of the days dosen't exist"); } break; } } case "4": { System.out.println("Enter number of the days "); sc = new Scanner(System.in); int days = sc.nextInt(); boolean flag = false; for (Months m : arrayMonthList) { if (m.getDays() > days) { System.out.println(m); flag = true; } if (!flag) { System.out.println("Month with bigger amount of the days dosen't exist"); } } } case "5": { System.out.println("Enter season "); sc = new Scanner(System.in); String seasons = sc.nextLine().toUpperCase(); //Seasons[] season = Seasons.values(); Seasons season1 = Seasons.valueOf(seasons); int ordinal = season1.ordinal(); if (ordinal == arraySeasonList.size()) { ordinal = -1; } System.out.println(arraySeasonList.get(ordinal + 1)); } case "6": { System.out.println("Enter season "); sc = new Scanner(System.in); String seasons = sc.nextLine().toUpperCase(); //Seasons[] season = Seasons.values(); Seasons season1 = Seasons.valueOf(seasons); int ordinal = season1.ordinal(); if (ordinal == arraySeasonList.size()-1) { ordinal = 0; } System.out.println(arraySeasonList.get(ordinal - 1)); } case "7": { System.out.println("Months with paired number of days: "); for (Months m : arrayMonthList) { if (m.getDays() % 2 == 0) { System.out.println(m); } } } case "8": { System.out.println("Months with unpaired number of days: "); for (Months m : arrayMonthList) { if (m.getDays() % 2 != 0) { System.out.println(m); } } } case "9": { System.out.println("Enter month "); sc = new Scanner(System.in); String months = sc.next().toUpperCase(); boolean flag = false; for (Months m : arrayMonthList) { if (m.toString().equals(months) && m.getDays() % 2 == 0) { System.out.println("This month has paired number of days "); flag = true; } } if (!flag) { System.out.println("This month has unpaired number of days "); } } } } } private static boolean areMonthsExist(ArrayList<Months> arrayMonthList, String months) { boolean flag = false; for (Months m : arrayMonthList) { if (m.name().equals(months)) { System.out.println("Month is exist "); flag = true; } } return flag; } }
6,109
0.62656
0.616221
224
24.044643
26.124834
112
false
false
0
0
0
0
0
0
3.263393
false
false
4
d6030aa944ef064043e0495dda071bcd464820bd
29,119,878,304,256
2f0f12590cace1965ac793b9656e882359c61dea
/app/src/main/java/es/iessaladillo/pedrojoya/pr05/utils/ValidationUtils.java
ffefa838d23e249bcfc9baa7aa8ac79e7f34b47a
[]
no_license
chitaua/MGC-PR05-OrientationChange-Base-master
https://github.com/chitaua/MGC-PR05-OrientationChange-Base-master
0ae756079adeb3e0a4dae5b02e7777e97dea9949
20c42f7a4d3e31547787b5501e4066786efb6d1f
refs/heads/master
2020-04-04T11:59:49.016000
2018-11-02T19:09:13
2018-11-02T19:09:13
155,910,694
0
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package es.iessaladillo.pedrojoya.pr05.utils; import android.text.TextUtils; import android.util.Patterns; // DO NOT TOUCH public class ValidationUtils { private ValidationUtils() { } public static boolean isValidEmail(String email) { return !TextUtils.isEmpty(email) && Patterns.EMAIL_ADDRESS.matcher(email).matches(); } public static boolean isValidPhone(String phoneNumber) { return !TextUtils.isEmpty(phoneNumber) && Patterns.PHONE.matcher(phoneNumber).matches(); } public static boolean isValidUrl(String url) { return !TextUtils.isEmpty(url) && Patterns.WEB_URL.matcher(url).matches(); } }
UTF-8
Java
660
java
ValidationUtils.java
Java
[]
null
[]
package es.iessaladillo.pedrojoya.pr05.utils; import android.text.TextUtils; import android.util.Patterns; // DO NOT TOUCH public class ValidationUtils { private ValidationUtils() { } public static boolean isValidEmail(String email) { return !TextUtils.isEmpty(email) && Patterns.EMAIL_ADDRESS.matcher(email).matches(); } public static boolean isValidPhone(String phoneNumber) { return !TextUtils.isEmpty(phoneNumber) && Patterns.PHONE.matcher(phoneNumber).matches(); } public static boolean isValidUrl(String url) { return !TextUtils.isEmpty(url) && Patterns.WEB_URL.matcher(url).matches(); } }
660
0.710606
0.707576
25
25.4
30.491966
96
false
false
0
0
0
0
0
0
0.24
false
false
4
460cf9b957860403b7f79cb7ee2c0b726ac024d8
12,395,275,647,579
ab5dd110e36708122d10b21705f46f596c0a69d2
/TestProject/src/ClassFirst.java
b4aaabda010fc2cfefaf679312e8f5037f396381
[]
no_license
Barnali7/FirstTest
https://github.com/Barnali7/FirstTest
e8b1b16bf7f799ac9e7366982aed4c732830210e
57c20750b75e03911e872b82c58909d163874de9
refs/heads/master
2022-04-22T13:52:17.354000
2020-04-21T11:23:20
2020-04-21T11:23:20
257,564,402
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class ClassFirst { }
UTF-8
Java
34
java
ClassFirst.java
Java
[]
null
[]
public class ClassFirst { }
34
0.617647
0.617647
3
8.666667
11.556623
25
false
false
0
0
0
0
0
0
0
false
false
4
6e518310fdbc99b1729c847ab72bc95771b2411e
21,457,656,642,267
9ee2c662b6fe2c33881dc41e86b2beec2cea44e5
/src/main/java/outbackv2/dto/FilesDto.java
bee2c71fb16b8cb870954c4218d910d25a1357bb
[]
no_license
jihye0427/Outback
https://github.com/jihye0427/Outback
6b78e15d8e46e2dec3dcb7a1a69d0024f9a92fde
ec0ccc7f7c973a96244fdb39456459c475255b7f
refs/heads/master
2022-12-24T03:36:47.341000
2020-10-08T03:20:39
2020-10-08T03:20:39
295,178,359
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package outbackv2.dto; import lombok.Data; import lombok.NoArgsConstructor; import outbackv2.entity.Files; @NoArgsConstructor @Data public class FilesDto { private String t_text; private String b_text; private String fileName; public Files toEntity() { return Files.builder().t_text(t_text).b_text(b_text).fileName(fileName).build(); } }
UTF-8
Java
396
java
FilesDto.java
Java
[]
null
[]
package outbackv2.dto; import lombok.Data; import lombok.NoArgsConstructor; import outbackv2.entity.Files; @NoArgsConstructor @Data public class FilesDto { private String t_text; private String b_text; private String fileName; public Files toEntity() { return Files.builder().t_text(t_text).b_text(b_text).fileName(fileName).build(); } }
396
0.669192
0.664141
28
12.142858
17.543242
82
false
false
0
0
0
0
0
0
0.857143
false
false
4
cbc522035a43881728f4be51f5d912a710f162b7
2,181,843,423,147
47b2e47d3becd3182fc327cf12387122bce6c90c
/CrossWordGithub/src/eprojectsemii/dlgNewQuestionFinal.java
b9efa268972b5d95f3dbe839190df1fbeef538ef
[]
no_license
fozgee/crossword
https://github.com/fozgee/crossword
1dfb6564788e88f07add01921caad88ea270aac5
feb7857d1f06a56147ad91353f86367704a7d405
refs/heads/master
2021-01-10T18:32:24.195000
2012-11-23T04:00:46
2012-11-23T04:00:46
null
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 eprojectsemii; import data.Questions; import entities.Question; import java.sql.Array; import java.util.ArrayList; import java.util.Arrays; import javax.swing.DefaultListModel; import javax.swing.JOptionPane; /** * * @author Fozg */ public class dlgNewQuestionFinal extends javax.swing.JDialog { /** * Creates new form dlgNewQuestionFinal */ String id; public dlgNewQuestionFinal(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); id = q.createID(cbDifficult.getSelectedIndex(), cbSize.getSelectedIndex()); txtQuestionID.setText(id); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); cbSize = new javax.swing.JComboBox(); pnMain = new javax.swing.JPanel(); jLabel6 = new javax.swing.JLabel(); jPanel1 = new javax.swing.JPanel(); btnCreate = new javax.swing.JButton(); btnCancel = new javax.swing.JButton(); jLabel5 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); btnPreview = new javax.swing.JButton(); jLabel13 = new javax.swing.JLabel(); lbSelect = new javax.swing.JLabel(); cbDifficult = new javax.swing.JComboBox(); jLabel15 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jLabel2 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jPanel2 = new javax.swing.JPanel(); btnCreateHint = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); listAcross = new javax.swing.JList(); jScrollPane2 = new javax.swing.JScrollPane(); listDown = new javax.swing.JList(); jLabel8 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); btnDelAcross = new javax.swing.JButton(); jScrollPane3 = new javax.swing.JScrollPane(); txtHinAcross = new javax.swing.JTextArea(); jScrollPane4 = new javax.swing.JScrollPane(); txtHintDown = new javax.swing.JTextArea(); jLabel10 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); jLabel12 = new javax.swing.JLabel(); brnDelDown = new javax.swing.JButton(); jSeparator1 = new javax.swing.JSeparator(); jLabel14 = new javax.swing.JLabel(); txtTitle = new javax.swing.JTextField(); jLabel16 = new javax.swing.JLabel(); txtQuestionID = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Create question"); setResizable(false); jLabel1.setText("Chose size: "); cbSize.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "4 x 4", "6 x 6", "8 x 8" })); cbSize.setToolTipText(""); cbSize.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cbSizeActionPerformed(evt); } }); javax.swing.GroupLayout pnMainLayout = new javax.swing.GroupLayout(pnMain); pnMain.setLayout(pnMainLayout); pnMainLayout.setHorizontalGroup( pnMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 323, Short.MAX_VALUE) ); pnMainLayout.setVerticalGroup( pnMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 328, Short.MAX_VALUE) ); jLabel6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/createquestion.png"))); // NOI18N btnCreate.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N btnCreate.setText("Create"); btnCreate.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnCreateActionPerformed(evt); } }); btnCancel.setText("Cancel"); btnCancel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnCancelActionPerformed(evt); } }); jLabel5.setFont(new java.awt.Font("Tahoma", 2, 11)); // NOI18N jLabel5.setText("Tips:"); jLabel3.setFont(new java.awt.Font("Tahoma", 2, 11)); // NOI18N jLabel3.setText("- Click a box to enable this box"); jLabel4.setFont(new java.awt.Font("Tahoma", 2, 11)); // NOI18N jLabel4.setText("- Right click to disnable this box"); btnPreview.setText("Preview Code"); btnPreview.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnPreviewActionPerformed(evt); } }); jLabel13.setText("Step 6: Finish"); lbSelect.setText("Select: "); cbDifficult.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Easy", "Normal", "Hard" })); cbDifficult.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cbDifficultActionPerformed(evt); } }); jLabel15.setText("Step 5: Choose difficult"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel4) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 224, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(129, 129, 129) .addComponent(lbSelect))) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(btnPreview) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel15) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(cbDifficult, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel13) .addGap(18, 18, 18) .addComponent(btnCreate, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnCancel, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(15, 15, 15) .addComponent(jLabel4)) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(jLabel3) .addComponent(lbSelect))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 12, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnPreview) .addComponent(btnCreate) .addComponent(btnCancel) .addComponent(jLabel13) .addComponent(cbDifficult, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel15)) .addContainerGap()) ); jButton1.setText("Reset"); jLabel2.setText("Step 2: Design"); jLabel7.setText("Step 3: Create key"); btnCreateHint.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N btnCreateHint.setText("Create Key"); btnCreateHint.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnCreateHintActionPerformed(evt); } }); jScrollPane1.setViewportView(listAcross); jScrollPane2.setViewportView(listDown); jLabel8.setText("Keys across"); jLabel9.setText("Keys down"); btnDelAcross.setText("Delete"); btnDelAcross.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnDelAcrossActionPerformed(evt); } }); txtHinAcross.setColumns(20); txtHinAcross.setRows(5); jScrollPane3.setViewportView(txtHinAcross); txtHintDown.setColumns(20); txtHintDown.setRows(5); jScrollPane4.setViewportView(txtHintDown); jLabel10.setText("Hints across"); jLabel11.setText("Hints down"); jLabel12.setText("Step 4: Insert Hint"); brnDelDown.setText("Delete"); brnDelDown.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { brnDelDownActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addComponent(jLabel8) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 14, Short.MAX_VALUE) .addComponent(btnDelAcross)) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addComponent(btnCreateHint, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel9) .addGap(18, 18, 18) .addComponent(brnDelDown))) .addGap(29, 29, 29) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 340, Short.MAX_VALUE) .addComponent(jScrollPane4) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel10) .addComponent(jLabel11) .addComponent(jLabel12)) .addGap(0, 0, Short.MAX_VALUE)))) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnCreateHint, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel12)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel8) .addComponent(btnDelAcross) .addComponent(jLabel10)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 117, Short.MAX_VALUE) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel11) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)) .addGroup(jPanel2Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(brnDelDown) .addComponent(jLabel9)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 117, Short.MAX_VALUE) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)) .addContainerGap()) ); jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL); jLabel14.setText("Step 1: Chose title:"); jLabel16.setText("Question ID:"); txtQuestionID.setEditable(false); txtQuestionID.setForeground(new java.awt.Color(153, 0, 0)); txtQuestionID.setHorizontalAlignment(javax.swing.JTextField.RIGHT); txtQuestionID.setText("easy-66-001"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel6) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(cbSize, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButton1) .addGap(14, 14, 14)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(pnMain, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(jLabel14) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtTitle) .addGap(8, 8, 8))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 4, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addGap(24, 24, 24) .addComponent(jLabel7) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel16) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtQuestionID, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel14) .addComponent(txtTitle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel7) .addComponent(jLabel16) .addComponent(txtQuestionID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jLabel1) .addComponent(cbSize, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(pnMain, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addComponent(jSeparator1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jLabel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents pnNewQuestion pnq; private int size = 4; //Set kich thuoc cho question private void cbSizeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbSizeActionPerformed id = q.createID(cbDifficult.getSelectedIndex(), cbSize.getSelectedIndex()); txtQuestionID.setText(id); pnq = new pnNewQuestion(); pnMain.removeAll(); pnMain.repaint(); switch (cbSize.getSelectedIndex()) { case 0: size = 4; pnq.setSizexy(4); pnMain.setSize(200, 200); break; case 1: size =6; pnq.setSizexy(6); pnMain.setSize(300, 300); break; case 2: size = 8; pnq.setSizexy(8); pnMain.setSize(400, 400); break; } pnq.Draw(); pnMain.add(pnq); pnq.setVisible(true); pack(); }//GEN-LAST:event_cbSizeActionPerformed private void btnPreviewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPreviewActionPerformed JOptionPane.showMessageDialog(this, pnq.getCode()); }//GEN-LAST:event_btnPreviewActionPerformed private String ArraytoString(String[] a){ String s=""; for (int i=0;i<a.length;i++){ s+= a[i]+";"; } return s; } String[] keywordsAcross; String[] keywordsDown; private void btnCreateHintActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCreateHintActionPerformed keywordsAcross = pnq.getKeywordsAcross(); listAcross.setListData(keywordsAcross); keywordsDown = pnq.getKeywordsDown(); listDown.setListData(keywordsDown); // lbCount.setText("Count: "+pnq.getKeywordcount()+""); }//GEN-LAST:event_btnCreateHintActionPerformed private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed this.setVisible(false); }//GEN-LAST:event_btnCancelActionPerformed // xoa phan tu dang chon o bang Keyword across private void btnDelAcrossActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDelAcrossActionPerformed if (keywordsAcross != null){ lbSelect.setText("Select: " + listAcross.getSelectedIndex()); for (int i=0; i< keywordsAcross.length-1;i++) if(i==listAcross.getSelectedIndex()){ for (int j=i;j<keywordsAcross.length-1;j++) keywordsAcross[j] = keywordsAcross[j+1]; } keywordsAcross[keywordsAcross.length-1]=";"; String abc=""; for (int i=0;i<keywordsAcross.length;i++) { abc +=keywordsAcross[i] +";"; } keywordsAcross = abc.split(";"); listAcross.setListData(keywordsAcross); } }//GEN-LAST:event_btnDelAcrossActionPerformed private void brnDelDownActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_brnDelDownActionPerformed if (keywordsDown!= null){ lbSelect.setText("Select: " + listDown.getSelectedIndex()); for (int i=0; i< keywordsDown.length-1;i++) if(i==listDown.getSelectedIndex()){ for (int j=i;j<keywordsDown.length-1;j++) keywordsDown[j] = keywordsDown[j+1]; } keywordsDown[keywordsDown.length-1]=";"; String abc=""; for (int i=0;i<keywordsDown.length;i++) { abc +=keywordsDown[i] +";"; } keywordsDown= abc.split(";"); listDown.setListData(keywordsDown); } }//GEN-LAST:event_brnDelDownActionPerformed //insert question Questions q = new Questions(); private void btnCreateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCreateActionPerformed String code = pnq.getCode(); String title = txtTitle.getText(); String kwDown = ArraytoString(keywordsDown); String kwAcross = ArraytoString(keywordsAcross); String hintAcross = txtHinAcross.getText(); String hintDown = txtHintDown.getText(); int diff = cbDifficult.getSelectedIndex()+1; q.add(new Question(id, size, title, code, kwAcross, kwDown, hintAcross, hintDown, diff)); // q.add(new Question("ID1f01", 5, "Titsdfle", "3sdfw3d;sfw33", "key1sdfkey2", "sddsfifj", "oadsfidjfij", "hindsf", 34)); // q.add(new Question("id1", 8, "Cau hoi 1", pnq.getCode(), // "a", "b", "c", "d", 1)); // q.add(); }//GEN-LAST:event_btnCreateActionPerformed private void cbDifficultActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbDifficultActionPerformed id = q.createID(cbDifficult.getSelectedIndex(), cbSize.getSelectedIndex()); txtQuestionID.setText(id); }//GEN-LAST:event_cbDifficultActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Windows".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(dlgNewQuestionFinal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(dlgNewQuestionFinal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(dlgNewQuestionFinal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(dlgNewQuestionFinal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { dlgNewQuestionFinal dialog = new dlgNewQuestionFinal(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton brnDelDown; private javax.swing.JButton btnCancel; private javax.swing.JButton btnCreate; private javax.swing.JButton btnCreateHint; private javax.swing.JButton btnDelAcross; private javax.swing.JButton btnPreview; private javax.swing.JComboBox cbDifficult; private javax.swing.JComboBox cbSize; private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel15; private javax.swing.JLabel jLabel16; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JScrollPane jScrollPane4; private javax.swing.JSeparator jSeparator1; private javax.swing.JLabel lbSelect; private javax.swing.JList listAcross; private javax.swing.JList listDown; private javax.swing.JPanel pnMain; private javax.swing.JTextArea txtHinAcross; private javax.swing.JTextArea txtHintDown; private javax.swing.JTextField txtQuestionID; private javax.swing.JTextField txtTitle; // End of variables declaration//GEN-END:variables }
UTF-8
Java
32,017
java
dlgNewQuestionFinal.java
Java
[ { "context": "import javax.swing.JOptionPane;\n\n/**\n *\n * @author Fozg\n */\npublic class dlgNewQuestionFinal extends java", "end": 341, "score": 0.9948799014091492, "start": 337, "tag": "USERNAME", "value": "Fozg" } ]
null
[]
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package eprojectsemii; import data.Questions; import entities.Question; import java.sql.Array; import java.util.ArrayList; import java.util.Arrays; import javax.swing.DefaultListModel; import javax.swing.JOptionPane; /** * * @author Fozg */ public class dlgNewQuestionFinal extends javax.swing.JDialog { /** * Creates new form dlgNewQuestionFinal */ String id; public dlgNewQuestionFinal(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); id = q.createID(cbDifficult.getSelectedIndex(), cbSize.getSelectedIndex()); txtQuestionID.setText(id); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); cbSize = new javax.swing.JComboBox(); pnMain = new javax.swing.JPanel(); jLabel6 = new javax.swing.JLabel(); jPanel1 = new javax.swing.JPanel(); btnCreate = new javax.swing.JButton(); btnCancel = new javax.swing.JButton(); jLabel5 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); btnPreview = new javax.swing.JButton(); jLabel13 = new javax.swing.JLabel(); lbSelect = new javax.swing.JLabel(); cbDifficult = new javax.swing.JComboBox(); jLabel15 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jLabel2 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jPanel2 = new javax.swing.JPanel(); btnCreateHint = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); listAcross = new javax.swing.JList(); jScrollPane2 = new javax.swing.JScrollPane(); listDown = new javax.swing.JList(); jLabel8 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); btnDelAcross = new javax.swing.JButton(); jScrollPane3 = new javax.swing.JScrollPane(); txtHinAcross = new javax.swing.JTextArea(); jScrollPane4 = new javax.swing.JScrollPane(); txtHintDown = new javax.swing.JTextArea(); jLabel10 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); jLabel12 = new javax.swing.JLabel(); brnDelDown = new javax.swing.JButton(); jSeparator1 = new javax.swing.JSeparator(); jLabel14 = new javax.swing.JLabel(); txtTitle = new javax.swing.JTextField(); jLabel16 = new javax.swing.JLabel(); txtQuestionID = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Create question"); setResizable(false); jLabel1.setText("Chose size: "); cbSize.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "4 x 4", "6 x 6", "8 x 8" })); cbSize.setToolTipText(""); cbSize.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cbSizeActionPerformed(evt); } }); javax.swing.GroupLayout pnMainLayout = new javax.swing.GroupLayout(pnMain); pnMain.setLayout(pnMainLayout); pnMainLayout.setHorizontalGroup( pnMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 323, Short.MAX_VALUE) ); pnMainLayout.setVerticalGroup( pnMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 328, Short.MAX_VALUE) ); jLabel6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/createquestion.png"))); // NOI18N btnCreate.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N btnCreate.setText("Create"); btnCreate.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnCreateActionPerformed(evt); } }); btnCancel.setText("Cancel"); btnCancel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnCancelActionPerformed(evt); } }); jLabel5.setFont(new java.awt.Font("Tahoma", 2, 11)); // NOI18N jLabel5.setText("Tips:"); jLabel3.setFont(new java.awt.Font("Tahoma", 2, 11)); // NOI18N jLabel3.setText("- Click a box to enable this box"); jLabel4.setFont(new java.awt.Font("Tahoma", 2, 11)); // NOI18N jLabel4.setText("- Right click to disnable this box"); btnPreview.setText("Preview Code"); btnPreview.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnPreviewActionPerformed(evt); } }); jLabel13.setText("Step 6: Finish"); lbSelect.setText("Select: "); cbDifficult.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Easy", "Normal", "Hard" })); cbDifficult.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cbDifficultActionPerformed(evt); } }); jLabel15.setText("Step 5: Choose difficult"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel4) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 224, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(129, 129, 129) .addComponent(lbSelect))) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(btnPreview) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel15) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(cbDifficult, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel13) .addGap(18, 18, 18) .addComponent(btnCreate, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnCancel, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(15, 15, 15) .addComponent(jLabel4)) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(jLabel3) .addComponent(lbSelect))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 12, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnPreview) .addComponent(btnCreate) .addComponent(btnCancel) .addComponent(jLabel13) .addComponent(cbDifficult, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel15)) .addContainerGap()) ); jButton1.setText("Reset"); jLabel2.setText("Step 2: Design"); jLabel7.setText("Step 3: Create key"); btnCreateHint.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N btnCreateHint.setText("Create Key"); btnCreateHint.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnCreateHintActionPerformed(evt); } }); jScrollPane1.setViewportView(listAcross); jScrollPane2.setViewportView(listDown); jLabel8.setText("Keys across"); jLabel9.setText("Keys down"); btnDelAcross.setText("Delete"); btnDelAcross.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnDelAcrossActionPerformed(evt); } }); txtHinAcross.setColumns(20); txtHinAcross.setRows(5); jScrollPane3.setViewportView(txtHinAcross); txtHintDown.setColumns(20); txtHintDown.setRows(5); jScrollPane4.setViewportView(txtHintDown); jLabel10.setText("Hints across"); jLabel11.setText("Hints down"); jLabel12.setText("Step 4: Insert Hint"); brnDelDown.setText("Delete"); brnDelDown.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { brnDelDownActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addComponent(jLabel8) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 14, Short.MAX_VALUE) .addComponent(btnDelAcross)) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addComponent(btnCreateHint, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel9) .addGap(18, 18, 18) .addComponent(brnDelDown))) .addGap(29, 29, 29) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 340, Short.MAX_VALUE) .addComponent(jScrollPane4) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel10) .addComponent(jLabel11) .addComponent(jLabel12)) .addGap(0, 0, Short.MAX_VALUE)))) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnCreateHint, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel12)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel8) .addComponent(btnDelAcross) .addComponent(jLabel10)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 117, Short.MAX_VALUE) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel11) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)) .addGroup(jPanel2Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(brnDelDown) .addComponent(jLabel9)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 117, Short.MAX_VALUE) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)) .addContainerGap()) ); jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL); jLabel14.setText("Step 1: Chose title:"); jLabel16.setText("Question ID:"); txtQuestionID.setEditable(false); txtQuestionID.setForeground(new java.awt.Color(153, 0, 0)); txtQuestionID.setHorizontalAlignment(javax.swing.JTextField.RIGHT); txtQuestionID.setText("easy-66-001"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel6) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(cbSize, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButton1) .addGap(14, 14, 14)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(pnMain, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(jLabel14) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtTitle) .addGap(8, 8, 8))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 4, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addGap(24, 24, 24) .addComponent(jLabel7) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel16) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtQuestionID, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel14) .addComponent(txtTitle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel7) .addComponent(jLabel16) .addComponent(txtQuestionID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jLabel1) .addComponent(cbSize, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(pnMain, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addComponent(jSeparator1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jLabel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents pnNewQuestion pnq; private int size = 4; //Set kich thuoc cho question private void cbSizeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbSizeActionPerformed id = q.createID(cbDifficult.getSelectedIndex(), cbSize.getSelectedIndex()); txtQuestionID.setText(id); pnq = new pnNewQuestion(); pnMain.removeAll(); pnMain.repaint(); switch (cbSize.getSelectedIndex()) { case 0: size = 4; pnq.setSizexy(4); pnMain.setSize(200, 200); break; case 1: size =6; pnq.setSizexy(6); pnMain.setSize(300, 300); break; case 2: size = 8; pnq.setSizexy(8); pnMain.setSize(400, 400); break; } pnq.Draw(); pnMain.add(pnq); pnq.setVisible(true); pack(); }//GEN-LAST:event_cbSizeActionPerformed private void btnPreviewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPreviewActionPerformed JOptionPane.showMessageDialog(this, pnq.getCode()); }//GEN-LAST:event_btnPreviewActionPerformed private String ArraytoString(String[] a){ String s=""; for (int i=0;i<a.length;i++){ s+= a[i]+";"; } return s; } String[] keywordsAcross; String[] keywordsDown; private void btnCreateHintActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCreateHintActionPerformed keywordsAcross = pnq.getKeywordsAcross(); listAcross.setListData(keywordsAcross); keywordsDown = pnq.getKeywordsDown(); listDown.setListData(keywordsDown); // lbCount.setText("Count: "+pnq.getKeywordcount()+""); }//GEN-LAST:event_btnCreateHintActionPerformed private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed this.setVisible(false); }//GEN-LAST:event_btnCancelActionPerformed // xoa phan tu dang chon o bang Keyword across private void btnDelAcrossActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDelAcrossActionPerformed if (keywordsAcross != null){ lbSelect.setText("Select: " + listAcross.getSelectedIndex()); for (int i=0; i< keywordsAcross.length-1;i++) if(i==listAcross.getSelectedIndex()){ for (int j=i;j<keywordsAcross.length-1;j++) keywordsAcross[j] = keywordsAcross[j+1]; } keywordsAcross[keywordsAcross.length-1]=";"; String abc=""; for (int i=0;i<keywordsAcross.length;i++) { abc +=keywordsAcross[i] +";"; } keywordsAcross = abc.split(";"); listAcross.setListData(keywordsAcross); } }//GEN-LAST:event_btnDelAcrossActionPerformed private void brnDelDownActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_brnDelDownActionPerformed if (keywordsDown!= null){ lbSelect.setText("Select: " + listDown.getSelectedIndex()); for (int i=0; i< keywordsDown.length-1;i++) if(i==listDown.getSelectedIndex()){ for (int j=i;j<keywordsDown.length-1;j++) keywordsDown[j] = keywordsDown[j+1]; } keywordsDown[keywordsDown.length-1]=";"; String abc=""; for (int i=0;i<keywordsDown.length;i++) { abc +=keywordsDown[i] +";"; } keywordsDown= abc.split(";"); listDown.setListData(keywordsDown); } }//GEN-LAST:event_brnDelDownActionPerformed //insert question Questions q = new Questions(); private void btnCreateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCreateActionPerformed String code = pnq.getCode(); String title = txtTitle.getText(); String kwDown = ArraytoString(keywordsDown); String kwAcross = ArraytoString(keywordsAcross); String hintAcross = txtHinAcross.getText(); String hintDown = txtHintDown.getText(); int diff = cbDifficult.getSelectedIndex()+1; q.add(new Question(id, size, title, code, kwAcross, kwDown, hintAcross, hintDown, diff)); // q.add(new Question("ID1f01", 5, "Titsdfle", "3sdfw3d;sfw33", "key1sdfkey2", "sddsfifj", "oadsfidjfij", "hindsf", 34)); // q.add(new Question("id1", 8, "Cau hoi 1", pnq.getCode(), // "a", "b", "c", "d", 1)); // q.add(); }//GEN-LAST:event_btnCreateActionPerformed private void cbDifficultActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbDifficultActionPerformed id = q.createID(cbDifficult.getSelectedIndex(), cbSize.getSelectedIndex()); txtQuestionID.setText(id); }//GEN-LAST:event_cbDifficultActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Windows".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(dlgNewQuestionFinal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(dlgNewQuestionFinal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(dlgNewQuestionFinal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(dlgNewQuestionFinal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { dlgNewQuestionFinal dialog = new dlgNewQuestionFinal(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton brnDelDown; private javax.swing.JButton btnCancel; private javax.swing.JButton btnCreate; private javax.swing.JButton btnCreateHint; private javax.swing.JButton btnDelAcross; private javax.swing.JButton btnPreview; private javax.swing.JComboBox cbDifficult; private javax.swing.JComboBox cbSize; private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel15; private javax.swing.JLabel jLabel16; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JScrollPane jScrollPane4; private javax.swing.JSeparator jSeparator1; private javax.swing.JLabel lbSelect; private javax.swing.JList listAcross; private javax.swing.JList listDown; private javax.swing.JPanel pnMain; private javax.swing.JTextArea txtHinAcross; private javax.swing.JTextArea txtHintDown; private javax.swing.JTextField txtQuestionID; private javax.swing.JTextField txtTitle; // End of variables declaration//GEN-END:variables }
32,017
0.627229
0.614517
612
51.315361
37.224373
180
false
false
0
0
0
0
0
0
0.75
false
false
4
ce338a766b47cd5c9917eedec31c679579cf0be7
2,834,678,427,682
c56ae27209c45169827245c80e3c177d1d200b74
/src/simplegraphlibrary/ConnectivityAlgorithmsTest.java
3c91102ee047a3926852092d9f6923cf733f1900
[]
no_license
permin/SimpleGraphLibrary
https://github.com/permin/SimpleGraphLibrary
f1f2e53f21a8a57b15f9d046077a78456d4564b0
1be448d5a1572e8fd24a8a73eab09e3be6841f82
refs/heads/master
2020-07-15T08:13:48.978000
2016-11-24T15:25:10
2016-11-24T15:25:10
73,967,286
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package simplegraphlibrary; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import simplegraphlibrary.DigraphTraversals.AbstractVisitor; import simplegraphlibrary.TestUtils.RandomSimpleDigraphGenerator; import simplegraphlibrary.TestUtils.RandomSimpleDigraphGenerator.SelfLoops; import static junit.framework.TestCase.assertEquals; import static org.hamcrest.core.IsCollectionContaining.hasItems; import static org.junit.Assert.assertThat; /** * Created by permin on 16/11/2016. */ public class ConnectivityAlgorithmsTest { @Test public void findStronglyConnectedComponents() { for (int test = 0; test < 1000; ++test) { Random randomGenerator = new Random(); int verticesNumber = randomGenerator.nextInt(20); for (double edgeProbability : Arrays.asList(0.0, 0.03, 0.1, 0.3, 0.5, 0.7, 1.0)) { RandomSimpleDigraphGenerator generator = new RandomSimpleDigraphGenerator(edgeProbability, SelfLoops.FORBIDDEN); Digraph digraph = generator.generate(verticesNumber); Partition<Integer> stronglyConnectedComponents = ConnectivityAlgorithms.findStronglyConnectedComponents(digraph); boolean isReachable[][] = new boolean[verticesNumber][verticesNumber]; for (int v = 0; v < verticesNumber; ++v) { int finalV = v; DigraphTraversals.traverseInDepthFirstSearchOrder(v, digraph, new AbstractVisitor() { @Override public void discoverVertex(int vertex) { isReachable[finalV][vertex] = true; } }); } for (int v = 0; v < verticesNumber; ++v) { for (int v2 = 0; v2 < verticesNumber; ++v2) { boolean inOneConnectedComponent = isReachable[v][v2] && isReachable[v2][v]; assertEquals(inOneConnectedComponent, stronglyConnectedComponents.groupIndex(v) == stronglyConnectedComponents.groupIndex(v2)); } } } } } @Test public void contractGraphTest() { VerticesPartition verticesPartition = null; Digraph digraph = null; { DigraphBuilder builder = DigraphBuilders.adjacencyListsDigraphBuilder(); builder.setVerticesNumber(5); builder.addEdge(0, 2); builder.addEdge(0, 3); builder.addEdge(1, 0); digraph = builder.build(); } { VerticesPartition.Builder partitionBuilder = new VerticesPartition.Builder(); int firstGroup = partitionBuilder.createNewGroup(); int secondGroup = partitionBuilder.createNewGroup(); int thirdGroup = partitionBuilder.createNewGroup(); partitionBuilder.addToGroup(firstGroup, 0); partitionBuilder.addToGroup(firstGroup, 2); partitionBuilder.addToGroup(firstGroup, 3); partitionBuilder.addToGroup(secondGroup, 1); partitionBuilder.addToGroup(thirdGroup, 4); verticesPartition = partitionBuilder.build(); } Digraph contractedDigraph = ConnectivityAlgorithms.contractDigraph(digraph, verticesPartition); assertEquals(contractedDigraph.verticesNumber(), 3); assertThat(contractedDigraph.allEdges(), hasItems(new Digraph.Edge(1, 0))); List<Digraph.Edge> edges = new ArrayList<Digraph.Edge>(); for (Digraph.Edge edge : contractedDigraph.allEdges()) { edges.add(edge); } assertEquals(edges.size(), 1); } }
UTF-8
Java
3,418
java
ConnectivityAlgorithmsTest.java
Java
[ { "context": "ic org.junit.Assert.assertThat;\n\n/**\n * Created by permin on 16/11/2016.\n */\npublic class ConnectivityAlgor", "end": 545, "score": 0.9994158744812012, "start": 539, "tag": "USERNAME", "value": "permin" } ]
null
[]
package simplegraphlibrary; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import simplegraphlibrary.DigraphTraversals.AbstractVisitor; import simplegraphlibrary.TestUtils.RandomSimpleDigraphGenerator; import simplegraphlibrary.TestUtils.RandomSimpleDigraphGenerator.SelfLoops; import static junit.framework.TestCase.assertEquals; import static org.hamcrest.core.IsCollectionContaining.hasItems; import static org.junit.Assert.assertThat; /** * Created by permin on 16/11/2016. */ public class ConnectivityAlgorithmsTest { @Test public void findStronglyConnectedComponents() { for (int test = 0; test < 1000; ++test) { Random randomGenerator = new Random(); int verticesNumber = randomGenerator.nextInt(20); for (double edgeProbability : Arrays.asList(0.0, 0.03, 0.1, 0.3, 0.5, 0.7, 1.0)) { RandomSimpleDigraphGenerator generator = new RandomSimpleDigraphGenerator(edgeProbability, SelfLoops.FORBIDDEN); Digraph digraph = generator.generate(verticesNumber); Partition<Integer> stronglyConnectedComponents = ConnectivityAlgorithms.findStronglyConnectedComponents(digraph); boolean isReachable[][] = new boolean[verticesNumber][verticesNumber]; for (int v = 0; v < verticesNumber; ++v) { int finalV = v; DigraphTraversals.traverseInDepthFirstSearchOrder(v, digraph, new AbstractVisitor() { @Override public void discoverVertex(int vertex) { isReachable[finalV][vertex] = true; } }); } for (int v = 0; v < verticesNumber; ++v) { for (int v2 = 0; v2 < verticesNumber; ++v2) { boolean inOneConnectedComponent = isReachable[v][v2] && isReachable[v2][v]; assertEquals(inOneConnectedComponent, stronglyConnectedComponents.groupIndex(v) == stronglyConnectedComponents.groupIndex(v2)); } } } } } @Test public void contractGraphTest() { VerticesPartition verticesPartition = null; Digraph digraph = null; { DigraphBuilder builder = DigraphBuilders.adjacencyListsDigraphBuilder(); builder.setVerticesNumber(5); builder.addEdge(0, 2); builder.addEdge(0, 3); builder.addEdge(1, 0); digraph = builder.build(); } { VerticesPartition.Builder partitionBuilder = new VerticesPartition.Builder(); int firstGroup = partitionBuilder.createNewGroup(); int secondGroup = partitionBuilder.createNewGroup(); int thirdGroup = partitionBuilder.createNewGroup(); partitionBuilder.addToGroup(firstGroup, 0); partitionBuilder.addToGroup(firstGroup, 2); partitionBuilder.addToGroup(firstGroup, 3); partitionBuilder.addToGroup(secondGroup, 1); partitionBuilder.addToGroup(thirdGroup, 4); verticesPartition = partitionBuilder.build(); } Digraph contractedDigraph = ConnectivityAlgorithms.contractDigraph(digraph, verticesPartition); assertEquals(contractedDigraph.verticesNumber(), 3); assertThat(contractedDigraph.allEdges(), hasItems(new Digraph.Edge(1, 0))); List<Digraph.Edge> edges = new ArrayList<Digraph.Edge>(); for (Digraph.Edge edge : contractedDigraph.allEdges()) { edges.add(edge); } assertEquals(edges.size(), 1); } }
3,418
0.695143
0.679052
87
38.298851
29.251236
121
false
false
0
0
0
0
0
0
0.896552
false
false
4
9e6185b7704d2f823fd9f0668f67d928eeaecf0d
2,834,678,426,826
61fea3d3281a454ca9caa741b81b2978e8cb2c1f
/Ex_1205/src/ex_override/Dog.java
7de2c8f0269baf772f30c3cefb3380f467345ed8
[]
no_license
inayun/java_study
https://github.com/inayun/java_study
c48d9fb52cd1f583bb3b37af738ed3e962d2e52a
a46ec90e138586ac5e29a22db6497d27fc1bf336
refs/heads/master
2021-08-31T17:27:41.769000
2017-12-22T07:44:15
2017-12-22T07:44:15
111,745,809
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ex_override; public class Dog extends Animal{ String nose = "Èİ¢"; }
WINDOWS-1252
Java
87
java
Dog.java
Java
[]
null
[]
package ex_override; public class Dog extends Animal{ String nose = "Èİ¢"; }
87
0.674699
0.674699
7
10.857142
12.44908
32
false
false
0
0
0
0
0
0
0.571429
false
false
4
eed18417c641dc74e7082f59c95859861e350f34
31,052,613,606,308
539f3e4323220df9768ea193e77337aed340d60c
/src/main/java/com/directorymonitor/listener/ConnectionHandler.java
9a3d14106cc37dfbcc699a0f4afc54c4d9fd6478
[]
no_license
rohanshrimal/directorymonitor
https://github.com/rohanshrimal/directorymonitor
c642839a63b794c9497528be03b07188e6dab882
bf82a5f6bda8eb7ea320a045cb38e7c2e8ad5b33
refs/heads/master
2022-12-23T04:16:09.746000
2019-09-11T17:58:09
2019-09-11T17:58:09
207,873,995
0
0
null
false
2022-12-16T08:54:05
2019-09-11T17:56:48
2019-11-27T10:45:47
2022-12-16T08:54:02
26,545
0
0
7
HTML
false
false
package com.directorymonitor.listener; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; public class ConnectionHandler implements ServletContextListener { Connection con; public void contextDestroyed(ServletContextEvent sce) { try { if(con != null) con.close(); } catch (SQLException e) { System.out.println("ERROR: Not able to close Database connection."); } } public void contextInitialized(ServletContextEvent sce) { connection(sce); } public void connection(ServletContextEvent sce){ try { Class.forName("com.mysql.jdbc.Driver"); System.out.println("SUCCESS: Driver loaded successfully"); } catch (ClassNotFoundException ex) { System.out.println("ERROR: SQLDriver not loaded successfully."); } try { con = DriverManager.getConnection("jdbc:mysql://localhost:3307/directorymonitor?useSSL=false&requireSSL=false","root","root"); sce.getServletContext().setAttribute("datacon",con); System.out.println("SUCCESS: Database connected successfully."); } catch (SQLException ex) { ex.printStackTrace(); System.out.println("ERROR: Connection establishment failed."); } } }
UTF-8
Java
1,398
java
ConnectionHandler.java
Java
[]
null
[]
package com.directorymonitor.listener; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; public class ConnectionHandler implements ServletContextListener { Connection con; public void contextDestroyed(ServletContextEvent sce) { try { if(con != null) con.close(); } catch (SQLException e) { System.out.println("ERROR: Not able to close Database connection."); } } public void contextInitialized(ServletContextEvent sce) { connection(sce); } public void connection(ServletContextEvent sce){ try { Class.forName("com.mysql.jdbc.Driver"); System.out.println("SUCCESS: Driver loaded successfully"); } catch (ClassNotFoundException ex) { System.out.println("ERROR: SQLDriver not loaded successfully."); } try { con = DriverManager.getConnection("jdbc:mysql://localhost:3307/directorymonitor?useSSL=false&requireSSL=false","root","root"); sce.getServletContext().setAttribute("datacon",con); System.out.println("SUCCESS: Database connected successfully."); } catch (SQLException ex) { ex.printStackTrace(); System.out.println("ERROR: Connection establishment failed."); } } }
1,398
0.676681
0.67382
43
31.511627
29.537813
135
false
false
0
0
0
0
0
0
0.906977
false
false
4
c17dd3f54f5eca9748c01f65965bdcc5a5cb64df
13,812,614,895,171
89ce13475ed5f71e5c392f3400c27b1e1f1cd8f6
/src/main/java/com/finalproject/BankApplication/model/Account.java
bce350d7072aaff41134be7c8c52eea5ebba8719
[]
no_license
cheuwami/BankApplication
https://github.com/cheuwami/BankApplication
ff5e546531995b50e4359579c69eae8ad615c50d
bddce0f76aa7cb4c42717b25067b765194d4df81
refs/heads/main
2023-03-05T21:58:25.867000
2021-02-21T11:45:53
2021-02-21T11:45:53
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.finalproject.BankApplication.model; import lombok.Data; import javax.persistence.*; import java.util.HashSet; import java.util.Set; @Entity @Data @Table public class Account extends BaseEntity{ private String account_number; @ManyToOne @JoinColumn(name="client_id") private Client client; @OneToOne(targetEntity = Credential.class, cascade = CascadeType.ALL) private Credential credential; @Column() private long balance; @OneToOne(targetEntity = Loan.class, cascade = CascadeType.ALL) private Loan loan; @Enumerated(EnumType.STRING) private Status account_status; }
UTF-8
Java
637
java
Account.java
Java
[]
null
[]
package com.finalproject.BankApplication.model; import lombok.Data; import javax.persistence.*; import java.util.HashSet; import java.util.Set; @Entity @Data @Table public class Account extends BaseEntity{ private String account_number; @ManyToOne @JoinColumn(name="client_id") private Client client; @OneToOne(targetEntity = Credential.class, cascade = CascadeType.ALL) private Credential credential; @Column() private long balance; @OneToOne(targetEntity = Loan.class, cascade = CascadeType.ALL) private Loan loan; @Enumerated(EnumType.STRING) private Status account_status; }
637
0.731554
0.731554
32
18.90625
19.514994
73
false
false
0
0
0
0
0
0
0.40625
false
false
4
70c2b0de6c524089c3c6c5d306512725944c909a
13,812,614,893,712
fa68567e500eec39ad83768b5f53a3f9b28e2383
/core/sorcer-platform/src/main/java/sorcer/core/exertion/ObjectTask.java
92dfe32e06aad1dd2685bf098f6e91b27bef5a89
[ "Apache-2.0" ]
permissive
fryciemat/SORCER
https://github.com/fryciemat/SORCER
e2aab878e431b0e6526099028bf80ec814462b47
9a1d549fd1f0e4a42eb679e2776de55436cb20b6
refs/heads/master
2019-03-20T13:03:03.785000
2015-01-17T16:41:48
2015-01-17T16:41:48
29,397,229
0
0
null
true
2015-01-17T16:34:20
2015-01-17T16:34:19
2015-01-13T17:42:05
2015-01-15T02:22:25
256,859
0
0
0
null
null
null
/* * Copyright 2012 the original author or authors. * Copyright 2012 SorcerSoft.org. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package sorcer.core.exertion; import net.jini.core.transaction.Transaction; import sorcer.core.context.ServiceContext; import sorcer.core.invoker.MethodInvoker; import sorcer.core.signature.ObjectSignature; import sorcer.service.*; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.rmi.RemoteException; import java.util.List; import static sorcer.eo.operator.provider; /** * The SORCER object task extending the basic task implementation {@link Task}. * * @author Mike Sobolewski */ @SuppressWarnings("rawtypes") public class ObjectTask extends Task { static final long serialVersionUID = 1793342047789581449L; public ObjectTask() { } public ObjectTask(String name) { super(name); } public ObjectTask(String name, Signature... signatures) { super(name); for (Signature s : signatures) { if (s instanceof ObjectSignature) addSignature(s); } } public ObjectTask(String name, String description, Signature signature) throws SignatureException { super(name); if (signature instanceof ObjectSignature) addSignature(signature); else throw new SignatureException("Object task requires ObjectSignature: " + signature); if (((ObjectSignature)signature).getEvaluator() == null) try { ((ObjectSignature)signature).createEvaluator(); } catch (Exception e) { e.printStackTrace(); throw new SignatureException(e); } this.description = description; } public ObjectTask(String name, Signature signature, Context context) throws SignatureException { this(name, signature); this.dataContext = (ServiceContext) context; } public ObjectTask(Signature signature, Context context) throws SignatureException { addSignature(signature); this.dataContext = (ServiceContext) context; } @SuppressWarnings("unchecked") public Task doTask(Transaction txn) throws ExertionException, SignatureException, RemoteException { MethodInvoker evaluator = null; ObjectSignature os = (ObjectSignature) getProcessSignature(); dataContext.setCurrentSelector(os.getSelector()); dataContext.setCurrentPrefix(os.getPrefix()); try { if (dataContext.getArgs() != null) os.setArgs(dataContext.getArgs()); if (dataContext.getParameterTypes() != null) os.setParameterTypes(dataContext.getParameterTypes()); evaluator = ((ObjectSignature) getProcessSignature()) .getEvaluator(); Object result = null; if (evaluator == null) { // create a provider of this object signature Object prv = provider(os); Object target = os.getTarget(); if (target != null) { if (target instanceof Method) { result = invokeMethod((Method)target, os); } else { evaluator = new MethodInvoker(target, os.getSelector()); } } else { evaluator = new MethodInvoker(prv, os.getSelector()); } } if (os.getReturnPath() != null) dataContext.setReturnPath(os.getReturnPath()); if (result == null) { if (getArgs() == null && os.getParameterTypes() == null) { // assume this task context is used by the signature's // provider if (dataContext != null) { if (scope != null && scope.size() > 0) { appendScope(); } evaluator .setParameterTypes(new Class[] { Context.class }); evaluator.setContext(dataContext); } } else if (dataContext.getArgsPath() != null) { evaluator .setArgs(getParameterTypes(), (Object[]) getArgs()); } // evaluator.setParameters(context); result = evaluator.evaluate(); } if (result instanceof Context) { Signature.ReturnPath rp = dataContext.getReturnPath(); if (rp != null) { if (((Context) result).getValue(rp.path) != null) { dataContext.setReturnValue(((Context) result).getValue(rp.path)); } else if (rp.argPaths != null && rp.argPaths.length > 0) { Context out = dataContext.getSubcontext(rp.argPaths); dataContext.setReturnValue(out); } } else { dataContext.append((Context)result); } } else { dataContext.setReturnValue(result); } } catch (Throwable e) { e.printStackTrace(); dataContext.reportException(e); if (e instanceof Exception) setStatus(FAILED); else setStatus(ERROR); } setStatus(DONE); if (evaluator != null) dataContext.appendTrace(evaluator.toString()); else dataContext.appendTrace(os.toString()); return this; } private Object invokeMethod(Method method, ObjectSignature os) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, ContextException, SignatureException { Object[] args = os.getArgs(); Class<?>[] argTypes = os.getParameterTypes(); Object result = null; if (args != null) { result = method.invoke(null, args); } else if (argTypes != null && argTypes.length == 1 && args == null) { result = method.invoke(null, new Object[] { null }); } else { result = method.invoke(null, (Object[])null); } return result; } private void appendScope() throws ContextException { if (scope != null) { List<String> paths = dataContext.getPaths(); for (String path : paths) { if (dataContext.getValue(path) == Context.none) { dataContext.putValue(path, scope.getValue(path)); } } } } public Object getArgs() throws ContextException { return dataContext.getArgs(); } public Class[] getParameterTypes() throws ContextException { return dataContext.getParameterTypes(); } }
UTF-8
Java
6,141
java
ObjectTask.java
Java
[ { "context": "ic task implementation {@link Task}.\n *\n * @author Mike Sobolewski\n */\n@SuppressWarnings(\"rawtypes\")\npublic class Ob", "end": 1187, "score": 0.998613178730011, "start": 1172, "tag": "NAME", "value": "Mike Sobolewski" } ]
null
[]
/* * Copyright 2012 the original author or authors. * Copyright 2012 SorcerSoft.org. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package sorcer.core.exertion; import net.jini.core.transaction.Transaction; import sorcer.core.context.ServiceContext; import sorcer.core.invoker.MethodInvoker; import sorcer.core.signature.ObjectSignature; import sorcer.service.*; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.rmi.RemoteException; import java.util.List; import static sorcer.eo.operator.provider; /** * The SORCER object task extending the basic task implementation {@link Task}. * * @author <NAME> */ @SuppressWarnings("rawtypes") public class ObjectTask extends Task { static final long serialVersionUID = 1793342047789581449L; public ObjectTask() { } public ObjectTask(String name) { super(name); } public ObjectTask(String name, Signature... signatures) { super(name); for (Signature s : signatures) { if (s instanceof ObjectSignature) addSignature(s); } } public ObjectTask(String name, String description, Signature signature) throws SignatureException { super(name); if (signature instanceof ObjectSignature) addSignature(signature); else throw new SignatureException("Object task requires ObjectSignature: " + signature); if (((ObjectSignature)signature).getEvaluator() == null) try { ((ObjectSignature)signature).createEvaluator(); } catch (Exception e) { e.printStackTrace(); throw new SignatureException(e); } this.description = description; } public ObjectTask(String name, Signature signature, Context context) throws SignatureException { this(name, signature); this.dataContext = (ServiceContext) context; } public ObjectTask(Signature signature, Context context) throws SignatureException { addSignature(signature); this.dataContext = (ServiceContext) context; } @SuppressWarnings("unchecked") public Task doTask(Transaction txn) throws ExertionException, SignatureException, RemoteException { MethodInvoker evaluator = null; ObjectSignature os = (ObjectSignature) getProcessSignature(); dataContext.setCurrentSelector(os.getSelector()); dataContext.setCurrentPrefix(os.getPrefix()); try { if (dataContext.getArgs() != null) os.setArgs(dataContext.getArgs()); if (dataContext.getParameterTypes() != null) os.setParameterTypes(dataContext.getParameterTypes()); evaluator = ((ObjectSignature) getProcessSignature()) .getEvaluator(); Object result = null; if (evaluator == null) { // create a provider of this object signature Object prv = provider(os); Object target = os.getTarget(); if (target != null) { if (target instanceof Method) { result = invokeMethod((Method)target, os); } else { evaluator = new MethodInvoker(target, os.getSelector()); } } else { evaluator = new MethodInvoker(prv, os.getSelector()); } } if (os.getReturnPath() != null) dataContext.setReturnPath(os.getReturnPath()); if (result == null) { if (getArgs() == null && os.getParameterTypes() == null) { // assume this task context is used by the signature's // provider if (dataContext != null) { if (scope != null && scope.size() > 0) { appendScope(); } evaluator .setParameterTypes(new Class[] { Context.class }); evaluator.setContext(dataContext); } } else if (dataContext.getArgsPath() != null) { evaluator .setArgs(getParameterTypes(), (Object[]) getArgs()); } // evaluator.setParameters(context); result = evaluator.evaluate(); } if (result instanceof Context) { Signature.ReturnPath rp = dataContext.getReturnPath(); if (rp != null) { if (((Context) result).getValue(rp.path) != null) { dataContext.setReturnValue(((Context) result).getValue(rp.path)); } else if (rp.argPaths != null && rp.argPaths.length > 0) { Context out = dataContext.getSubcontext(rp.argPaths); dataContext.setReturnValue(out); } } else { dataContext.append((Context)result); } } else { dataContext.setReturnValue(result); } } catch (Throwable e) { e.printStackTrace(); dataContext.reportException(e); if (e instanceof Exception) setStatus(FAILED); else setStatus(ERROR); } setStatus(DONE); if (evaluator != null) dataContext.appendTrace(evaluator.toString()); else dataContext.appendTrace(os.toString()); return this; } private Object invokeMethod(Method method, ObjectSignature os) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, ContextException, SignatureException { Object[] args = os.getArgs(); Class<?>[] argTypes = os.getParameterTypes(); Object result = null; if (args != null) { result = method.invoke(null, args); } else if (argTypes != null && argTypes.length == 1 && args == null) { result = method.invoke(null, new Object[] { null }); } else { result = method.invoke(null, (Object[])null); } return result; } private void appendScope() throws ContextException { if (scope != null) { List<String> paths = dataContext.getPaths(); for (String path : paths) { if (dataContext.getValue(path) == Context.none) { dataContext.putValue(path, scope.getValue(path)); } } } } public Object getArgs() throws ContextException { return dataContext.getArgs(); } public Class[] getParameterTypes() throws ContextException { return dataContext.getParameterTypes(); } }
6,132
0.696466
0.69093
206
28.81068
22.897154
100
false
false
0
0
0
0
0
0
2.747573
false
false
4
50a75093a6c1a1bd15a44469ac260c41f30978d6
2,628,520,039,414
be164ac6cc3629f43e1c0da92b0c79d8e0799e90
/java/source/com/vmail/model/base/AcGb0901PayComponentTrendVsVoToolsBase.java
de13004dcb368f71c475500c32b487fa056f274c
[]
no_license
pabplanalp/pvmail
https://github.com/pabplanalp/pvmail
da51b664e17f60dfae9f64764d23e2e150adad10
06e75afc0181a416146bd351d37a4045e8656fc4
refs/heads/master
2019-04-20T14:12:17.573000
2013-07-19T19:22:31
2013-07-19T19:22:31
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * AUTO GENERATED - DO NOT EDIT */ package com.vmail.model.base; import com.jwApps.collection.*; import com.jwApps.servlet.ScServletData; import com.jwApps.servlet.command.ScCommand; import com.jwApps.servlet.control.*; import com.jwApps.servlet.field.*; import com.jwApps.servlet.utility.ScFormatter; import com.jwApps.time.*; import com.jwApps.unit.*; import com.jwApps.utility.*; import com.vmail.model.AcGb0901PayComponentTrendVsVo; import com.vmail.model.AcGb0901PayComponentTrendVsVoValidator; import com.vmail.model.core.AcAbstractModelTools; import com.vmail.utility.AcComparator; import com.vmail.utility.AcComparatorNullsLower; import com.vmail.utility.AcTimeZoneUtility; /** * Miscellaneous tools for use with the model. */ public abstract class AcGb0901PayComponentTrendVsVoToolsBase extends AcAbstractModelTools implements AcGb0901PayComponentTrendVsVoConstantsIF { //################################################## //# adaptor (firstResultUtcDt) //##################################################// public ScExportAdaptorIF getFirstResultUtcDtAdaptor() { return FirstResultUtcDtAdaptor; } private static final ScExportAdaptorIF FirstResultUtcDtAdaptor = newFirstResultUtcDtAdaptor(); private static ScExportAdaptorIF newFirstResultUtcDtAdaptor() { return new ScExportAdaptorIF() { public Object getValue(Object model) { return ((AcGb0901PayComponentTrendVsVo)model).getFirstResultUtcDt(); } public Object getExportValue(Object model) { return getValue(model); } public void setValue(Object model, Object value) { ((AcGb0901PayComponentTrendVsVo)model).setFirstResultUtcDt((JwDate)value); } }; } //################################################## //# adaptor (maxPay) //##################################################// public ScExportAdaptorIF getMaxPayAdaptor() { return MaxPayAdaptor; } private static final ScExportAdaptorIF MaxPayAdaptor = newMaxPayAdaptor(); private static ScExportAdaptorIF newMaxPayAdaptor() { return new ScExportAdaptorIF() { public Object getValue(Object model) { return ((AcGb0901PayComponentTrendVsVo)model).getMaxPay(); } public Object getExportValue(Object model) { return getValue(model); } public void setValue(Object model, Object value) { ((AcGb0901PayComponentTrendVsVo)model).setMaxPay((JwMoney)value); } }; } //################################################## //# adaptor (expectedNetPay) //##################################################// public ScExportAdaptorIF getExpectedNetPayAdaptor() { return ExpectedNetPayAdaptor; } private static final ScExportAdaptorIF ExpectedNetPayAdaptor = newExpectedNetPayAdaptor(); private static ScExportAdaptorIF newExpectedNetPayAdaptor() { return new ScExportAdaptorIF() { public Object getValue(Object model) { return ((AcGb0901PayComponentTrendVsVo)model).getExpectedNetPay(); } public Object getExportValue(Object model) { return getValue(model); } public void setValue(Object model, Object value) { ((AcGb0901PayComponentTrendVsVo)model).setExpectedNetPay((JwMoney)value); } }; } //################################################## //# adaptor (actualNetPay) //##################################################// public ScExportAdaptorIF getActualNetPayAdaptor() { return ActualNetPayAdaptor; } private static final ScExportAdaptorIF ActualNetPayAdaptor = newActualNetPayAdaptor(); private static ScExportAdaptorIF newActualNetPayAdaptor() { return new ScExportAdaptorIF() { public Object getValue(Object model) { return ((AcGb0901PayComponentTrendVsVo)model).getActualNetPay(); } public Object getExportValue(Object model) { return getValue(model); } public void setValue(Object model, Object value) { ((AcGb0901PayComponentTrendVsVo)model).setActualNetPay((JwMoney)value); } }; } //################################################## //# adaptor (webKey) //##################################################// public JwAdaptorIF getWebKeyAdaptor() { return WebKeyAdaptor; } private static final JwAdaptorIF WebKeyAdaptor = newWebKeyAdaptor(); private static JwAdaptorIF newWebKeyAdaptor() { return new JwAdaptorIF() { public Object getValue(Object model) { return ((AcGb0901PayComponentTrendVsVo)model).getWebKey(); } public void setValue(Object model, Object value) { ((AcGb0901PayComponentTrendVsVo)model).setWebKey((String)value); } }; } //################################################## //# comparator (firstResultUtcDt) //##################################################// public JwComparator<AcGb0901PayComponentTrendVsVo> getFirstResultUtcDtComparator() { return FirstResultUtcDtComparator; } protected static final JwComparator<AcGb0901PayComponentTrendVsVo> FirstResultUtcDtComparator = newFirstResultUtcDtComparator(); protected static JwComparator<AcGb0901PayComponentTrendVsVo> newFirstResultUtcDtComparator() { return new AcComparator<AcGb0901PayComponentTrendVsVo>() { public int compare(AcGb0901PayComponentTrendVsVo o1, AcGb0901PayComponentTrendVsVo o2) { return c(o1.getFirstResultUtcDt(), o2.getFirstResultUtcDt()); } }; } //################################################## //# comparator, nulls lower (firstResultUtcDt) //##################################################// public JwComparator<AcGb0901PayComponentTrendVsVo> getFirstResultUtcDtComparatorNullsLower() { return FirstResultUtcDtComparatorNullsLower; } protected static final JwComparator<AcGb0901PayComponentTrendVsVo> FirstResultUtcDtComparatorNullsLower = newFirstResultUtcDtComparatorNullsLower(); protected static JwComparator<AcGb0901PayComponentTrendVsVo> newFirstResultUtcDtComparatorNullsLower() { return new AcComparatorNullsLower<AcGb0901PayComponentTrendVsVo>() { public int compare(AcGb0901PayComponentTrendVsVo o1, AcGb0901PayComponentTrendVsVo o2) { return c(o1.getFirstResultUtcDt(), o2.getFirstResultUtcDt()); } }; } //################################################## //# comparator (maxPay) //##################################################// public JwComparator<AcGb0901PayComponentTrendVsVo> getMaxPayComparator() { return MaxPayComparator; } protected static final JwComparator<AcGb0901PayComponentTrendVsVo> MaxPayComparator = newMaxPayComparator(); protected static JwComparator<AcGb0901PayComponentTrendVsVo> newMaxPayComparator() { return new AcComparator<AcGb0901PayComponentTrendVsVo>() { public int compare(AcGb0901PayComponentTrendVsVo o1, AcGb0901PayComponentTrendVsVo o2) { return c(o1.getMaxPay(), o2.getMaxPay()); } }; } //################################################## //# comparator, nulls lower (maxPay) //##################################################// public JwComparator<AcGb0901PayComponentTrendVsVo> getMaxPayComparatorNullsLower() { return MaxPayComparatorNullsLower; } protected static final JwComparator<AcGb0901PayComponentTrendVsVo> MaxPayComparatorNullsLower = newMaxPayComparatorNullsLower(); protected static JwComparator<AcGb0901PayComponentTrendVsVo> newMaxPayComparatorNullsLower() { return new AcComparatorNullsLower<AcGb0901PayComponentTrendVsVo>() { public int compare(AcGb0901PayComponentTrendVsVo o1, AcGb0901PayComponentTrendVsVo o2) { return c(o1.getMaxPay(), o2.getMaxPay()); } }; } //################################################## //# comparator (expectedNetPay) //##################################################// public JwComparator<AcGb0901PayComponentTrendVsVo> getExpectedNetPayComparator() { return ExpectedNetPayComparator; } protected static final JwComparator<AcGb0901PayComponentTrendVsVo> ExpectedNetPayComparator = newExpectedNetPayComparator(); protected static JwComparator<AcGb0901PayComponentTrendVsVo> newExpectedNetPayComparator() { return new AcComparator<AcGb0901PayComponentTrendVsVo>() { public int compare(AcGb0901PayComponentTrendVsVo o1, AcGb0901PayComponentTrendVsVo o2) { return c(o1.getExpectedNetPay(), o2.getExpectedNetPay()); } }; } //################################################## //# comparator, nulls lower (expectedNetPay) //##################################################// public JwComparator<AcGb0901PayComponentTrendVsVo> getExpectedNetPayComparatorNullsLower() { return ExpectedNetPayComparatorNullsLower; } protected static final JwComparator<AcGb0901PayComponentTrendVsVo> ExpectedNetPayComparatorNullsLower = newExpectedNetPayComparatorNullsLower(); protected static JwComparator<AcGb0901PayComponentTrendVsVo> newExpectedNetPayComparatorNullsLower() { return new AcComparatorNullsLower<AcGb0901PayComponentTrendVsVo>() { public int compare(AcGb0901PayComponentTrendVsVo o1, AcGb0901PayComponentTrendVsVo o2) { return c(o1.getExpectedNetPay(), o2.getExpectedNetPay()); } }; } //################################################## //# comparator (actualNetPay) //##################################################// public JwComparator<AcGb0901PayComponentTrendVsVo> getActualNetPayComparator() { return ActualNetPayComparator; } protected static final JwComparator<AcGb0901PayComponentTrendVsVo> ActualNetPayComparator = newActualNetPayComparator(); protected static JwComparator<AcGb0901PayComponentTrendVsVo> newActualNetPayComparator() { return new AcComparator<AcGb0901PayComponentTrendVsVo>() { public int compare(AcGb0901PayComponentTrendVsVo o1, AcGb0901PayComponentTrendVsVo o2) { return c(o1.getActualNetPay(), o2.getActualNetPay()); } }; } //################################################## //# comparator, nulls lower (actualNetPay) //##################################################// public JwComparator<AcGb0901PayComponentTrendVsVo> getActualNetPayComparatorNullsLower() { return ActualNetPayComparatorNullsLower; } protected static final JwComparator<AcGb0901PayComponentTrendVsVo> ActualNetPayComparatorNullsLower = newActualNetPayComparatorNullsLower(); protected static JwComparator<AcGb0901PayComponentTrendVsVo> newActualNetPayComparatorNullsLower() { return new AcComparatorNullsLower<AcGb0901PayComponentTrendVsVo>() { public int compare(AcGb0901PayComponentTrendVsVo o1, AcGb0901PayComponentTrendVsVo o2) { return c(o1.getActualNetPay(), o2.getActualNetPay()); } }; } //################################################## //# new columns (firstResultUtcDt) //##################################################// public ScGridColumn<AcGb0901PayComponentTrendVsVo> newFirstResultUtcDtColumn() { return newFirstResultUtcDtColumn("First Result Utc Dt"); } public ScGridColumn<AcGb0901PayComponentTrendVsVo> newFirstResultUtcDtColumn(Object label) { ScGridColumn<AcGb0901PayComponentTrendVsVo> e; e = new ScGridColumn<AcGb0901PayComponentTrendVsVo>(); e.setTitle(label); e.setCell(getFirstResultUtcDtAdaptor()); e.setComparator(getFirstResultUtcDtComparator()); return e; } public ScGridColumn<AcGb0901PayComponentTrendVsVo> newFirstResultUtcDtColumnLink(ScCommand c) { return newFirstResultUtcDtColumnLink(c, false); } public ScGridColumn<AcGb0901PayComponentTrendVsVo> newFirstResultUtcDtColumnLink(ScCommand c, boolean openNewWindow) { ScGridColumn<AcGb0901PayComponentTrendVsVo> e; e = newFirstResultUtcDtColumn(); e.setCell(newFirstResultUtcDtCommandControl(c, openNewWindow)); return e; } public ScGridColumn<AcGb0901PayComponentTrendVsVo> newFirstResultUtcDtColumnLink(String label, ScCommand c) { return newFirstResultUtcDtColumnLink(label, c, false); } public ScGridColumn<AcGb0901PayComponentTrendVsVo> newFirstResultUtcDtColumnLink(String label, ScCommand c, boolean openNewWindow) { ScGridColumn<AcGb0901PayComponentTrendVsVo> e; e = newFirstResultUtcDtColumn(label); e.setCell(newFirstResultUtcDtCommandControl(c, openNewWindow)); return e; } public ScAbstractCommandControl newFirstResultUtcDtCommandControl(ScCommand c) { return newFirstResultUtcDtCommandControl("First Result Utc Dt", c); } public ScAbstractCommandControl newFirstResultUtcDtCommandControl(ScCommand c, boolean openNewWindow) { return newFirstResultUtcDtCommandControl("First Result Utc Dt", c, openNewWindow); } public ScAbstractCommandControl newFirstResultUtcDtCommandControl(String label, ScCommand c) { return newFirstResultUtcDtCommandControl(label, c, false); } public ScAbstractCommandControl newFirstResultUtcDtCommandControl(String label, ScCommand c, boolean openNewWindow) { ScWebKeyLink k = new ScWebKeyLink(); k.setLabel(label); k.setValue(getFirstResultUtcDtAdaptor()); k.setCommand(c); k.setOpenNewWindow(openNewWindow); return k; } //################################################## //# new columns (maxPay) //##################################################// public ScGridColumn<AcGb0901PayComponentTrendVsVo> newMaxPayColumn() { return newMaxPayColumn("Max Pay"); } public ScGridColumn<AcGb0901PayComponentTrendVsVo> newMaxPayColumn(Object label) { ScGridColumn<AcGb0901PayComponentTrendVsVo> e; e = new ScGridColumn<AcGb0901PayComponentTrendVsVo>(); e.setTitle(label); e.setCell(getMaxPayAdaptor()); e.setComparator(getMaxPayComparator()); return e; } public ScGridColumn<AcGb0901PayComponentTrendVsVo> newMaxPayColumnLink(ScCommand c) { return newMaxPayColumnLink(c, false); } public ScGridColumn<AcGb0901PayComponentTrendVsVo> newMaxPayColumnLink(ScCommand c, boolean openNewWindow) { ScGridColumn<AcGb0901PayComponentTrendVsVo> e; e = newMaxPayColumn(); e.setCell(newMaxPayCommandControl(c, openNewWindow)); return e; } public ScGridColumn<AcGb0901PayComponentTrendVsVo> newMaxPayColumnLink(String label, ScCommand c) { return newMaxPayColumnLink(label, c, false); } public ScGridColumn<AcGb0901PayComponentTrendVsVo> newMaxPayColumnLink(String label, ScCommand c, boolean openNewWindow) { ScGridColumn<AcGb0901PayComponentTrendVsVo> e; e = newMaxPayColumn(label); e.setCell(newMaxPayCommandControl(c, openNewWindow)); return e; } public ScAbstractCommandControl newMaxPayCommandControl(ScCommand c) { return newMaxPayCommandControl("Max Pay", c); } public ScAbstractCommandControl newMaxPayCommandControl(ScCommand c, boolean openNewWindow) { return newMaxPayCommandControl("Max Pay", c, openNewWindow); } public ScAbstractCommandControl newMaxPayCommandControl(String label, ScCommand c) { return newMaxPayCommandControl(label, c, false); } public ScAbstractCommandControl newMaxPayCommandControl(String label, ScCommand c, boolean openNewWindow) { ScWebKeyLink k = new ScWebKeyLink(); k.setLabel(label); k.setValue(getMaxPayAdaptor()); k.setCommand(c); k.setOpenNewWindow(openNewWindow); return k; } //################################################## //# new columns (expectedNetPay) //##################################################// public ScGridColumn<AcGb0901PayComponentTrendVsVo> newExpectedNetPayColumn() { return newExpectedNetPayColumn("Expected Net Pay"); } public ScGridColumn<AcGb0901PayComponentTrendVsVo> newExpectedNetPayColumn(Object label) { ScGridColumn<AcGb0901PayComponentTrendVsVo> e; e = new ScGridColumn<AcGb0901PayComponentTrendVsVo>(); e.setTitle(label); e.setCell(getExpectedNetPayAdaptor()); e.setComparator(getExpectedNetPayComparator()); return e; } public ScGridColumn<AcGb0901PayComponentTrendVsVo> newExpectedNetPayColumnLink(ScCommand c) { return newExpectedNetPayColumnLink(c, false); } public ScGridColumn<AcGb0901PayComponentTrendVsVo> newExpectedNetPayColumnLink(ScCommand c, boolean openNewWindow) { ScGridColumn<AcGb0901PayComponentTrendVsVo> e; e = newExpectedNetPayColumn(); e.setCell(newExpectedNetPayCommandControl(c, openNewWindow)); return e; } public ScGridColumn<AcGb0901PayComponentTrendVsVo> newExpectedNetPayColumnLink(String label, ScCommand c) { return newExpectedNetPayColumnLink(label, c, false); } public ScGridColumn<AcGb0901PayComponentTrendVsVo> newExpectedNetPayColumnLink(String label, ScCommand c, boolean openNewWindow) { ScGridColumn<AcGb0901PayComponentTrendVsVo> e; e = newExpectedNetPayColumn(label); e.setCell(newExpectedNetPayCommandControl(c, openNewWindow)); return e; } public ScAbstractCommandControl newExpectedNetPayCommandControl(ScCommand c) { return newExpectedNetPayCommandControl("Expected Net Pay", c); } public ScAbstractCommandControl newExpectedNetPayCommandControl(ScCommand c, boolean openNewWindow) { return newExpectedNetPayCommandControl("Expected Net Pay", c, openNewWindow); } public ScAbstractCommandControl newExpectedNetPayCommandControl(String label, ScCommand c) { return newExpectedNetPayCommandControl(label, c, false); } public ScAbstractCommandControl newExpectedNetPayCommandControl(String label, ScCommand c, boolean openNewWindow) { ScWebKeyLink k = new ScWebKeyLink(); k.setLabel(label); k.setValue(getExpectedNetPayAdaptor()); k.setCommand(c); k.setOpenNewWindow(openNewWindow); return k; } //################################################## //# new columns (actualNetPay) //##################################################// public ScGridColumn<AcGb0901PayComponentTrendVsVo> newActualNetPayColumn() { return newActualNetPayColumn("Actual Net Pay"); } public ScGridColumn<AcGb0901PayComponentTrendVsVo> newActualNetPayColumn(Object label) { ScGridColumn<AcGb0901PayComponentTrendVsVo> e; e = new ScGridColumn<AcGb0901PayComponentTrendVsVo>(); e.setTitle(label); e.setCell(getActualNetPayAdaptor()); e.setComparator(getActualNetPayComparator()); return e; } public ScGridColumn<AcGb0901PayComponentTrendVsVo> newActualNetPayColumnLink(ScCommand c) { return newActualNetPayColumnLink(c, false); } public ScGridColumn<AcGb0901PayComponentTrendVsVo> newActualNetPayColumnLink(ScCommand c, boolean openNewWindow) { ScGridColumn<AcGb0901PayComponentTrendVsVo> e; e = newActualNetPayColumn(); e.setCell(newActualNetPayCommandControl(c, openNewWindow)); return e; } public ScGridColumn<AcGb0901PayComponentTrendVsVo> newActualNetPayColumnLink(String label, ScCommand c) { return newActualNetPayColumnLink(label, c, false); } public ScGridColumn<AcGb0901PayComponentTrendVsVo> newActualNetPayColumnLink(String label, ScCommand c, boolean openNewWindow) { ScGridColumn<AcGb0901PayComponentTrendVsVo> e; e = newActualNetPayColumn(label); e.setCell(newActualNetPayCommandControl(c, openNewWindow)); return e; } public ScAbstractCommandControl newActualNetPayCommandControl(ScCommand c) { return newActualNetPayCommandControl("Actual Net Pay", c); } public ScAbstractCommandControl newActualNetPayCommandControl(ScCommand c, boolean openNewWindow) { return newActualNetPayCommandControl("Actual Net Pay", c, openNewWindow); } public ScAbstractCommandControl newActualNetPayCommandControl(String label, ScCommand c) { return newActualNetPayCommandControl(label, c, false); } public ScAbstractCommandControl newActualNetPayCommandControl(String label, ScCommand c, boolean openNewWindow) { ScWebKeyLink k = new ScWebKeyLink(); k.setLabel(label); k.setValue(getActualNetPayAdaptor()); k.setCommand(c); k.setOpenNewWindow(openNewWindow); return k; } //################################################## //# fields //##################################################// public ScDateField newFirstResultUtcDtField() { return newFirstResultUtcDtField("First Result Utc Dt"); } public ScDateField newFirstResultUtcDtField(String label) { ScDateField e; e = new ScDateField(); e.setValueAdaptor(getFirstResultUtcDtAdaptor()); e.setLabel(label); e.setValidator(AcGb0901PayComponentTrendVsVoValidator.instance.getFirstResultUtcDtValidator()); return e; } public ScMoneyField newMaxPayField() { return newMaxPayField("Max Pay"); } public ScMoneyField newMaxPayField(String label) { ScMoneyField e; e = new ScMoneyField(); e.setValueAdaptor(getMaxPayAdaptor()); e.setLabel(label); e.setValidator(AcGb0901PayComponentTrendVsVoValidator.instance.getMaxPayValidator()); return e; } public ScMoneyField newExpectedNetPayField() { return newExpectedNetPayField("Expected Net Pay"); } public ScMoneyField newExpectedNetPayField(String label) { ScMoneyField e; e = new ScMoneyField(); e.setValueAdaptor(getExpectedNetPayAdaptor()); e.setLabel(label); e.setValidator(AcGb0901PayComponentTrendVsVoValidator.instance.getExpectedNetPayValidator()); return e; } public ScMoneyField newActualNetPayField() { return newActualNetPayField("Actual Net Pay"); } public ScMoneyField newActualNetPayField(String label) { ScMoneyField e; e = new ScMoneyField(); e.setValueAdaptor(getActualNetPayAdaptor()); e.setLabel(label); e.setValidator(AcGb0901PayComponentTrendVsVoValidator.instance.getActualNetPayValidator()); return e; } //################################################## //# images //##################################################// //################################################## //# texts //##################################################// public ScText newFirstResultUtcDtText() { return newFirstResultUtcDtText("First Result Utc Dt"); } public ScText newFirstResultUtcDtText(String label) { ScText e; e = new ScText(); e.setValue(getFirstResultUtcDtAdaptor()); e.setLabel(label); return e; } public ScText newFirstResultUtcDtBoldText() { return newFirstResultUtcDtBoldText("First Result Utc Dt"); } public ScText newFirstResultUtcDtBoldText(String label) { ScText e; e = newFirstResultUtcDtText(label); e.setBold(); return e; } public ScMoneyText newMaxPayText() { return newMaxPayText("Max Pay"); } public ScMoneyText newMaxPayText(String label) { ScMoneyText e; e = new ScMoneyText(); e.setValue(getMaxPayAdaptor()); e.setLabel(label); return e; } public ScMoneyText newMaxPayBoldText() { return newMaxPayBoldText("Max Pay"); } public ScMoneyText newMaxPayBoldText(String label) { ScMoneyText e; e = newMaxPayText(label); e.setBold(); return e; } public ScMoneyText newExpectedNetPayText() { return newExpectedNetPayText("Expected Net Pay"); } public ScMoneyText newExpectedNetPayText(String label) { ScMoneyText e; e = new ScMoneyText(); e.setValue(getExpectedNetPayAdaptor()); e.setLabel(label); return e; } public ScMoneyText newExpectedNetPayBoldText() { return newExpectedNetPayBoldText("Expected Net Pay"); } public ScMoneyText newExpectedNetPayBoldText(String label) { ScMoneyText e; e = newExpectedNetPayText(label); e.setBold(); return e; } public ScMoneyText newActualNetPayText() { return newActualNetPayText("Actual Net Pay"); } public ScMoneyText newActualNetPayText(String label) { ScMoneyText e; e = new ScMoneyText(); e.setValue(getActualNetPayAdaptor()); e.setLabel(label); return e; } public ScMoneyText newActualNetPayBoldText() { return newActualNetPayBoldText("Actual Net Pay"); } public ScMoneyText newActualNetPayBoldText(String label) { ScMoneyText e; e = newActualNetPayText(label); e.setBold(); return e; } //################################################## //# web key //##################################################// public static String getWebKey(JwDate firstResultUtcDt) { return AcGb0901PayComponentTrendVsVoPk.createPk(firstResultUtcDt).getWebKey(); } public static JwDate getFirstResultUtcDtFromWebKey(String webKey) { if ( webKey == null ) return null; return AcGb0901PayComponentTrendVsVoPk.createWebKey(webKey).getFirstResultUtcDt(); } public static JwList<JwDate> getFirstResultUtcDtsFromWebKeys(JwList<String> webKeys) { JwList<JwDate> v = new JwList<JwDate>(); if ( webKeys == null ) return v; if ( webKeys.isEmpty() ) return v; for ( String e : webKeys ) v.add(getFirstResultUtcDtFromWebKey(e)); return v; } //################################################## //# link column //##################################################// public ScGridColumnContainer<AcGb0901PayComponentTrendVsVo> newColumnLink() { ScGridColumnContainer<AcGb0901PayComponentTrendVsVo> e; e = new ScGridColumnContainer<AcGb0901PayComponentTrendVsVo>(); return e; } }
UTF-8
Java
27,951
java
AcGb0901PayComponentTrendVsVoToolsBase.java
Java
[]
null
[]
/** * AUTO GENERATED - DO NOT EDIT */ package com.vmail.model.base; import com.jwApps.collection.*; import com.jwApps.servlet.ScServletData; import com.jwApps.servlet.command.ScCommand; import com.jwApps.servlet.control.*; import com.jwApps.servlet.field.*; import com.jwApps.servlet.utility.ScFormatter; import com.jwApps.time.*; import com.jwApps.unit.*; import com.jwApps.utility.*; import com.vmail.model.AcGb0901PayComponentTrendVsVo; import com.vmail.model.AcGb0901PayComponentTrendVsVoValidator; import com.vmail.model.core.AcAbstractModelTools; import com.vmail.utility.AcComparator; import com.vmail.utility.AcComparatorNullsLower; import com.vmail.utility.AcTimeZoneUtility; /** * Miscellaneous tools for use with the model. */ public abstract class AcGb0901PayComponentTrendVsVoToolsBase extends AcAbstractModelTools implements AcGb0901PayComponentTrendVsVoConstantsIF { //################################################## //# adaptor (firstResultUtcDt) //##################################################// public ScExportAdaptorIF getFirstResultUtcDtAdaptor() { return FirstResultUtcDtAdaptor; } private static final ScExportAdaptorIF FirstResultUtcDtAdaptor = newFirstResultUtcDtAdaptor(); private static ScExportAdaptorIF newFirstResultUtcDtAdaptor() { return new ScExportAdaptorIF() { public Object getValue(Object model) { return ((AcGb0901PayComponentTrendVsVo)model).getFirstResultUtcDt(); } public Object getExportValue(Object model) { return getValue(model); } public void setValue(Object model, Object value) { ((AcGb0901PayComponentTrendVsVo)model).setFirstResultUtcDt((JwDate)value); } }; } //################################################## //# adaptor (maxPay) //##################################################// public ScExportAdaptorIF getMaxPayAdaptor() { return MaxPayAdaptor; } private static final ScExportAdaptorIF MaxPayAdaptor = newMaxPayAdaptor(); private static ScExportAdaptorIF newMaxPayAdaptor() { return new ScExportAdaptorIF() { public Object getValue(Object model) { return ((AcGb0901PayComponentTrendVsVo)model).getMaxPay(); } public Object getExportValue(Object model) { return getValue(model); } public void setValue(Object model, Object value) { ((AcGb0901PayComponentTrendVsVo)model).setMaxPay((JwMoney)value); } }; } //################################################## //# adaptor (expectedNetPay) //##################################################// public ScExportAdaptorIF getExpectedNetPayAdaptor() { return ExpectedNetPayAdaptor; } private static final ScExportAdaptorIF ExpectedNetPayAdaptor = newExpectedNetPayAdaptor(); private static ScExportAdaptorIF newExpectedNetPayAdaptor() { return new ScExportAdaptorIF() { public Object getValue(Object model) { return ((AcGb0901PayComponentTrendVsVo)model).getExpectedNetPay(); } public Object getExportValue(Object model) { return getValue(model); } public void setValue(Object model, Object value) { ((AcGb0901PayComponentTrendVsVo)model).setExpectedNetPay((JwMoney)value); } }; } //################################################## //# adaptor (actualNetPay) //##################################################// public ScExportAdaptorIF getActualNetPayAdaptor() { return ActualNetPayAdaptor; } private static final ScExportAdaptorIF ActualNetPayAdaptor = newActualNetPayAdaptor(); private static ScExportAdaptorIF newActualNetPayAdaptor() { return new ScExportAdaptorIF() { public Object getValue(Object model) { return ((AcGb0901PayComponentTrendVsVo)model).getActualNetPay(); } public Object getExportValue(Object model) { return getValue(model); } public void setValue(Object model, Object value) { ((AcGb0901PayComponentTrendVsVo)model).setActualNetPay((JwMoney)value); } }; } //################################################## //# adaptor (webKey) //##################################################// public JwAdaptorIF getWebKeyAdaptor() { return WebKeyAdaptor; } private static final JwAdaptorIF WebKeyAdaptor = newWebKeyAdaptor(); private static JwAdaptorIF newWebKeyAdaptor() { return new JwAdaptorIF() { public Object getValue(Object model) { return ((AcGb0901PayComponentTrendVsVo)model).getWebKey(); } public void setValue(Object model, Object value) { ((AcGb0901PayComponentTrendVsVo)model).setWebKey((String)value); } }; } //################################################## //# comparator (firstResultUtcDt) //##################################################// public JwComparator<AcGb0901PayComponentTrendVsVo> getFirstResultUtcDtComparator() { return FirstResultUtcDtComparator; } protected static final JwComparator<AcGb0901PayComponentTrendVsVo> FirstResultUtcDtComparator = newFirstResultUtcDtComparator(); protected static JwComparator<AcGb0901PayComponentTrendVsVo> newFirstResultUtcDtComparator() { return new AcComparator<AcGb0901PayComponentTrendVsVo>() { public int compare(AcGb0901PayComponentTrendVsVo o1, AcGb0901PayComponentTrendVsVo o2) { return c(o1.getFirstResultUtcDt(), o2.getFirstResultUtcDt()); } }; } //################################################## //# comparator, nulls lower (firstResultUtcDt) //##################################################// public JwComparator<AcGb0901PayComponentTrendVsVo> getFirstResultUtcDtComparatorNullsLower() { return FirstResultUtcDtComparatorNullsLower; } protected static final JwComparator<AcGb0901PayComponentTrendVsVo> FirstResultUtcDtComparatorNullsLower = newFirstResultUtcDtComparatorNullsLower(); protected static JwComparator<AcGb0901PayComponentTrendVsVo> newFirstResultUtcDtComparatorNullsLower() { return new AcComparatorNullsLower<AcGb0901PayComponentTrendVsVo>() { public int compare(AcGb0901PayComponentTrendVsVo o1, AcGb0901PayComponentTrendVsVo o2) { return c(o1.getFirstResultUtcDt(), o2.getFirstResultUtcDt()); } }; } //################################################## //# comparator (maxPay) //##################################################// public JwComparator<AcGb0901PayComponentTrendVsVo> getMaxPayComparator() { return MaxPayComparator; } protected static final JwComparator<AcGb0901PayComponentTrendVsVo> MaxPayComparator = newMaxPayComparator(); protected static JwComparator<AcGb0901PayComponentTrendVsVo> newMaxPayComparator() { return new AcComparator<AcGb0901PayComponentTrendVsVo>() { public int compare(AcGb0901PayComponentTrendVsVo o1, AcGb0901PayComponentTrendVsVo o2) { return c(o1.getMaxPay(), o2.getMaxPay()); } }; } //################################################## //# comparator, nulls lower (maxPay) //##################################################// public JwComparator<AcGb0901PayComponentTrendVsVo> getMaxPayComparatorNullsLower() { return MaxPayComparatorNullsLower; } protected static final JwComparator<AcGb0901PayComponentTrendVsVo> MaxPayComparatorNullsLower = newMaxPayComparatorNullsLower(); protected static JwComparator<AcGb0901PayComponentTrendVsVo> newMaxPayComparatorNullsLower() { return new AcComparatorNullsLower<AcGb0901PayComponentTrendVsVo>() { public int compare(AcGb0901PayComponentTrendVsVo o1, AcGb0901PayComponentTrendVsVo o2) { return c(o1.getMaxPay(), o2.getMaxPay()); } }; } //################################################## //# comparator (expectedNetPay) //##################################################// public JwComparator<AcGb0901PayComponentTrendVsVo> getExpectedNetPayComparator() { return ExpectedNetPayComparator; } protected static final JwComparator<AcGb0901PayComponentTrendVsVo> ExpectedNetPayComparator = newExpectedNetPayComparator(); protected static JwComparator<AcGb0901PayComponentTrendVsVo> newExpectedNetPayComparator() { return new AcComparator<AcGb0901PayComponentTrendVsVo>() { public int compare(AcGb0901PayComponentTrendVsVo o1, AcGb0901PayComponentTrendVsVo o2) { return c(o1.getExpectedNetPay(), o2.getExpectedNetPay()); } }; } //################################################## //# comparator, nulls lower (expectedNetPay) //##################################################// public JwComparator<AcGb0901PayComponentTrendVsVo> getExpectedNetPayComparatorNullsLower() { return ExpectedNetPayComparatorNullsLower; } protected static final JwComparator<AcGb0901PayComponentTrendVsVo> ExpectedNetPayComparatorNullsLower = newExpectedNetPayComparatorNullsLower(); protected static JwComparator<AcGb0901PayComponentTrendVsVo> newExpectedNetPayComparatorNullsLower() { return new AcComparatorNullsLower<AcGb0901PayComponentTrendVsVo>() { public int compare(AcGb0901PayComponentTrendVsVo o1, AcGb0901PayComponentTrendVsVo o2) { return c(o1.getExpectedNetPay(), o2.getExpectedNetPay()); } }; } //################################################## //# comparator (actualNetPay) //##################################################// public JwComparator<AcGb0901PayComponentTrendVsVo> getActualNetPayComparator() { return ActualNetPayComparator; } protected static final JwComparator<AcGb0901PayComponentTrendVsVo> ActualNetPayComparator = newActualNetPayComparator(); protected static JwComparator<AcGb0901PayComponentTrendVsVo> newActualNetPayComparator() { return new AcComparator<AcGb0901PayComponentTrendVsVo>() { public int compare(AcGb0901PayComponentTrendVsVo o1, AcGb0901PayComponentTrendVsVo o2) { return c(o1.getActualNetPay(), o2.getActualNetPay()); } }; } //################################################## //# comparator, nulls lower (actualNetPay) //##################################################// public JwComparator<AcGb0901PayComponentTrendVsVo> getActualNetPayComparatorNullsLower() { return ActualNetPayComparatorNullsLower; } protected static final JwComparator<AcGb0901PayComponentTrendVsVo> ActualNetPayComparatorNullsLower = newActualNetPayComparatorNullsLower(); protected static JwComparator<AcGb0901PayComponentTrendVsVo> newActualNetPayComparatorNullsLower() { return new AcComparatorNullsLower<AcGb0901PayComponentTrendVsVo>() { public int compare(AcGb0901PayComponentTrendVsVo o1, AcGb0901PayComponentTrendVsVo o2) { return c(o1.getActualNetPay(), o2.getActualNetPay()); } }; } //################################################## //# new columns (firstResultUtcDt) //##################################################// public ScGridColumn<AcGb0901PayComponentTrendVsVo> newFirstResultUtcDtColumn() { return newFirstResultUtcDtColumn("First Result Utc Dt"); } public ScGridColumn<AcGb0901PayComponentTrendVsVo> newFirstResultUtcDtColumn(Object label) { ScGridColumn<AcGb0901PayComponentTrendVsVo> e; e = new ScGridColumn<AcGb0901PayComponentTrendVsVo>(); e.setTitle(label); e.setCell(getFirstResultUtcDtAdaptor()); e.setComparator(getFirstResultUtcDtComparator()); return e; } public ScGridColumn<AcGb0901PayComponentTrendVsVo> newFirstResultUtcDtColumnLink(ScCommand c) { return newFirstResultUtcDtColumnLink(c, false); } public ScGridColumn<AcGb0901PayComponentTrendVsVo> newFirstResultUtcDtColumnLink(ScCommand c, boolean openNewWindow) { ScGridColumn<AcGb0901PayComponentTrendVsVo> e; e = newFirstResultUtcDtColumn(); e.setCell(newFirstResultUtcDtCommandControl(c, openNewWindow)); return e; } public ScGridColumn<AcGb0901PayComponentTrendVsVo> newFirstResultUtcDtColumnLink(String label, ScCommand c) { return newFirstResultUtcDtColumnLink(label, c, false); } public ScGridColumn<AcGb0901PayComponentTrendVsVo> newFirstResultUtcDtColumnLink(String label, ScCommand c, boolean openNewWindow) { ScGridColumn<AcGb0901PayComponentTrendVsVo> e; e = newFirstResultUtcDtColumn(label); e.setCell(newFirstResultUtcDtCommandControl(c, openNewWindow)); return e; } public ScAbstractCommandControl newFirstResultUtcDtCommandControl(ScCommand c) { return newFirstResultUtcDtCommandControl("First Result Utc Dt", c); } public ScAbstractCommandControl newFirstResultUtcDtCommandControl(ScCommand c, boolean openNewWindow) { return newFirstResultUtcDtCommandControl("First Result Utc Dt", c, openNewWindow); } public ScAbstractCommandControl newFirstResultUtcDtCommandControl(String label, ScCommand c) { return newFirstResultUtcDtCommandControl(label, c, false); } public ScAbstractCommandControl newFirstResultUtcDtCommandControl(String label, ScCommand c, boolean openNewWindow) { ScWebKeyLink k = new ScWebKeyLink(); k.setLabel(label); k.setValue(getFirstResultUtcDtAdaptor()); k.setCommand(c); k.setOpenNewWindow(openNewWindow); return k; } //################################################## //# new columns (maxPay) //##################################################// public ScGridColumn<AcGb0901PayComponentTrendVsVo> newMaxPayColumn() { return newMaxPayColumn("Max Pay"); } public ScGridColumn<AcGb0901PayComponentTrendVsVo> newMaxPayColumn(Object label) { ScGridColumn<AcGb0901PayComponentTrendVsVo> e; e = new ScGridColumn<AcGb0901PayComponentTrendVsVo>(); e.setTitle(label); e.setCell(getMaxPayAdaptor()); e.setComparator(getMaxPayComparator()); return e; } public ScGridColumn<AcGb0901PayComponentTrendVsVo> newMaxPayColumnLink(ScCommand c) { return newMaxPayColumnLink(c, false); } public ScGridColumn<AcGb0901PayComponentTrendVsVo> newMaxPayColumnLink(ScCommand c, boolean openNewWindow) { ScGridColumn<AcGb0901PayComponentTrendVsVo> e; e = newMaxPayColumn(); e.setCell(newMaxPayCommandControl(c, openNewWindow)); return e; } public ScGridColumn<AcGb0901PayComponentTrendVsVo> newMaxPayColumnLink(String label, ScCommand c) { return newMaxPayColumnLink(label, c, false); } public ScGridColumn<AcGb0901PayComponentTrendVsVo> newMaxPayColumnLink(String label, ScCommand c, boolean openNewWindow) { ScGridColumn<AcGb0901PayComponentTrendVsVo> e; e = newMaxPayColumn(label); e.setCell(newMaxPayCommandControl(c, openNewWindow)); return e; } public ScAbstractCommandControl newMaxPayCommandControl(ScCommand c) { return newMaxPayCommandControl("Max Pay", c); } public ScAbstractCommandControl newMaxPayCommandControl(ScCommand c, boolean openNewWindow) { return newMaxPayCommandControl("Max Pay", c, openNewWindow); } public ScAbstractCommandControl newMaxPayCommandControl(String label, ScCommand c) { return newMaxPayCommandControl(label, c, false); } public ScAbstractCommandControl newMaxPayCommandControl(String label, ScCommand c, boolean openNewWindow) { ScWebKeyLink k = new ScWebKeyLink(); k.setLabel(label); k.setValue(getMaxPayAdaptor()); k.setCommand(c); k.setOpenNewWindow(openNewWindow); return k; } //################################################## //# new columns (expectedNetPay) //##################################################// public ScGridColumn<AcGb0901PayComponentTrendVsVo> newExpectedNetPayColumn() { return newExpectedNetPayColumn("Expected Net Pay"); } public ScGridColumn<AcGb0901PayComponentTrendVsVo> newExpectedNetPayColumn(Object label) { ScGridColumn<AcGb0901PayComponentTrendVsVo> e; e = new ScGridColumn<AcGb0901PayComponentTrendVsVo>(); e.setTitle(label); e.setCell(getExpectedNetPayAdaptor()); e.setComparator(getExpectedNetPayComparator()); return e; } public ScGridColumn<AcGb0901PayComponentTrendVsVo> newExpectedNetPayColumnLink(ScCommand c) { return newExpectedNetPayColumnLink(c, false); } public ScGridColumn<AcGb0901PayComponentTrendVsVo> newExpectedNetPayColumnLink(ScCommand c, boolean openNewWindow) { ScGridColumn<AcGb0901PayComponentTrendVsVo> e; e = newExpectedNetPayColumn(); e.setCell(newExpectedNetPayCommandControl(c, openNewWindow)); return e; } public ScGridColumn<AcGb0901PayComponentTrendVsVo> newExpectedNetPayColumnLink(String label, ScCommand c) { return newExpectedNetPayColumnLink(label, c, false); } public ScGridColumn<AcGb0901PayComponentTrendVsVo> newExpectedNetPayColumnLink(String label, ScCommand c, boolean openNewWindow) { ScGridColumn<AcGb0901PayComponentTrendVsVo> e; e = newExpectedNetPayColumn(label); e.setCell(newExpectedNetPayCommandControl(c, openNewWindow)); return e; } public ScAbstractCommandControl newExpectedNetPayCommandControl(ScCommand c) { return newExpectedNetPayCommandControl("Expected Net Pay", c); } public ScAbstractCommandControl newExpectedNetPayCommandControl(ScCommand c, boolean openNewWindow) { return newExpectedNetPayCommandControl("Expected Net Pay", c, openNewWindow); } public ScAbstractCommandControl newExpectedNetPayCommandControl(String label, ScCommand c) { return newExpectedNetPayCommandControl(label, c, false); } public ScAbstractCommandControl newExpectedNetPayCommandControl(String label, ScCommand c, boolean openNewWindow) { ScWebKeyLink k = new ScWebKeyLink(); k.setLabel(label); k.setValue(getExpectedNetPayAdaptor()); k.setCommand(c); k.setOpenNewWindow(openNewWindow); return k; } //################################################## //# new columns (actualNetPay) //##################################################// public ScGridColumn<AcGb0901PayComponentTrendVsVo> newActualNetPayColumn() { return newActualNetPayColumn("Actual Net Pay"); } public ScGridColumn<AcGb0901PayComponentTrendVsVo> newActualNetPayColumn(Object label) { ScGridColumn<AcGb0901PayComponentTrendVsVo> e; e = new ScGridColumn<AcGb0901PayComponentTrendVsVo>(); e.setTitle(label); e.setCell(getActualNetPayAdaptor()); e.setComparator(getActualNetPayComparator()); return e; } public ScGridColumn<AcGb0901PayComponentTrendVsVo> newActualNetPayColumnLink(ScCommand c) { return newActualNetPayColumnLink(c, false); } public ScGridColumn<AcGb0901PayComponentTrendVsVo> newActualNetPayColumnLink(ScCommand c, boolean openNewWindow) { ScGridColumn<AcGb0901PayComponentTrendVsVo> e; e = newActualNetPayColumn(); e.setCell(newActualNetPayCommandControl(c, openNewWindow)); return e; } public ScGridColumn<AcGb0901PayComponentTrendVsVo> newActualNetPayColumnLink(String label, ScCommand c) { return newActualNetPayColumnLink(label, c, false); } public ScGridColumn<AcGb0901PayComponentTrendVsVo> newActualNetPayColumnLink(String label, ScCommand c, boolean openNewWindow) { ScGridColumn<AcGb0901PayComponentTrendVsVo> e; e = newActualNetPayColumn(label); e.setCell(newActualNetPayCommandControl(c, openNewWindow)); return e; } public ScAbstractCommandControl newActualNetPayCommandControl(ScCommand c) { return newActualNetPayCommandControl("Actual Net Pay", c); } public ScAbstractCommandControl newActualNetPayCommandControl(ScCommand c, boolean openNewWindow) { return newActualNetPayCommandControl("Actual Net Pay", c, openNewWindow); } public ScAbstractCommandControl newActualNetPayCommandControl(String label, ScCommand c) { return newActualNetPayCommandControl(label, c, false); } public ScAbstractCommandControl newActualNetPayCommandControl(String label, ScCommand c, boolean openNewWindow) { ScWebKeyLink k = new ScWebKeyLink(); k.setLabel(label); k.setValue(getActualNetPayAdaptor()); k.setCommand(c); k.setOpenNewWindow(openNewWindow); return k; } //################################################## //# fields //##################################################// public ScDateField newFirstResultUtcDtField() { return newFirstResultUtcDtField("First Result Utc Dt"); } public ScDateField newFirstResultUtcDtField(String label) { ScDateField e; e = new ScDateField(); e.setValueAdaptor(getFirstResultUtcDtAdaptor()); e.setLabel(label); e.setValidator(AcGb0901PayComponentTrendVsVoValidator.instance.getFirstResultUtcDtValidator()); return e; } public ScMoneyField newMaxPayField() { return newMaxPayField("Max Pay"); } public ScMoneyField newMaxPayField(String label) { ScMoneyField e; e = new ScMoneyField(); e.setValueAdaptor(getMaxPayAdaptor()); e.setLabel(label); e.setValidator(AcGb0901PayComponentTrendVsVoValidator.instance.getMaxPayValidator()); return e; } public ScMoneyField newExpectedNetPayField() { return newExpectedNetPayField("Expected Net Pay"); } public ScMoneyField newExpectedNetPayField(String label) { ScMoneyField e; e = new ScMoneyField(); e.setValueAdaptor(getExpectedNetPayAdaptor()); e.setLabel(label); e.setValidator(AcGb0901PayComponentTrendVsVoValidator.instance.getExpectedNetPayValidator()); return e; } public ScMoneyField newActualNetPayField() { return newActualNetPayField("Actual Net Pay"); } public ScMoneyField newActualNetPayField(String label) { ScMoneyField e; e = new ScMoneyField(); e.setValueAdaptor(getActualNetPayAdaptor()); e.setLabel(label); e.setValidator(AcGb0901PayComponentTrendVsVoValidator.instance.getActualNetPayValidator()); return e; } //################################################## //# images //##################################################// //################################################## //# texts //##################################################// public ScText newFirstResultUtcDtText() { return newFirstResultUtcDtText("First Result Utc Dt"); } public ScText newFirstResultUtcDtText(String label) { ScText e; e = new ScText(); e.setValue(getFirstResultUtcDtAdaptor()); e.setLabel(label); return e; } public ScText newFirstResultUtcDtBoldText() { return newFirstResultUtcDtBoldText("First Result Utc Dt"); } public ScText newFirstResultUtcDtBoldText(String label) { ScText e; e = newFirstResultUtcDtText(label); e.setBold(); return e; } public ScMoneyText newMaxPayText() { return newMaxPayText("Max Pay"); } public ScMoneyText newMaxPayText(String label) { ScMoneyText e; e = new ScMoneyText(); e.setValue(getMaxPayAdaptor()); e.setLabel(label); return e; } public ScMoneyText newMaxPayBoldText() { return newMaxPayBoldText("Max Pay"); } public ScMoneyText newMaxPayBoldText(String label) { ScMoneyText e; e = newMaxPayText(label); e.setBold(); return e; } public ScMoneyText newExpectedNetPayText() { return newExpectedNetPayText("Expected Net Pay"); } public ScMoneyText newExpectedNetPayText(String label) { ScMoneyText e; e = new ScMoneyText(); e.setValue(getExpectedNetPayAdaptor()); e.setLabel(label); return e; } public ScMoneyText newExpectedNetPayBoldText() { return newExpectedNetPayBoldText("Expected Net Pay"); } public ScMoneyText newExpectedNetPayBoldText(String label) { ScMoneyText e; e = newExpectedNetPayText(label); e.setBold(); return e; } public ScMoneyText newActualNetPayText() { return newActualNetPayText("Actual Net Pay"); } public ScMoneyText newActualNetPayText(String label) { ScMoneyText e; e = new ScMoneyText(); e.setValue(getActualNetPayAdaptor()); e.setLabel(label); return e; } public ScMoneyText newActualNetPayBoldText() { return newActualNetPayBoldText("Actual Net Pay"); } public ScMoneyText newActualNetPayBoldText(String label) { ScMoneyText e; e = newActualNetPayText(label); e.setBold(); return e; } //################################################## //# web key //##################################################// public static String getWebKey(JwDate firstResultUtcDt) { return AcGb0901PayComponentTrendVsVoPk.createPk(firstResultUtcDt).getWebKey(); } public static JwDate getFirstResultUtcDtFromWebKey(String webKey) { if ( webKey == null ) return null; return AcGb0901PayComponentTrendVsVoPk.createWebKey(webKey).getFirstResultUtcDt(); } public static JwList<JwDate> getFirstResultUtcDtsFromWebKeys(JwList<String> webKeys) { JwList<JwDate> v = new JwList<JwDate>(); if ( webKeys == null ) return v; if ( webKeys.isEmpty() ) return v; for ( String e : webKeys ) v.add(getFirstResultUtcDtFromWebKey(e)); return v; } //################################################## //# link column //##################################################// public ScGridColumnContainer<AcGb0901PayComponentTrendVsVo> newColumnLink() { ScGridColumnContainer<AcGb0901PayComponentTrendVsVo> e; e = new ScGridColumnContainer<AcGb0901PayComponentTrendVsVo>(); return e; } }
27,951
0.622232
0.605202
863
31.388182
32.646622
152
false
false
0
0
0
0
0
0
0.418308
false
false
4
8c592a69f41da5f226ff1278b5df1896aa27caea
23,510,650,981,462
657afb17baeaeb0257586225a479f2cc6d52d929
/src/main/java/comt/test/method/reference/StringSort.java
fc628f7a34b0c52e9ca3a6b651b1299d6ed2f441
[]
no_license
rakeshpriyad/java-8-tutoriol
https://github.com/rakeshpriyad/java-8-tutoriol
b2dc60793b51ff022c1a38a68b5058ca0ef2f066
76ec79e0d9d9df04111c587c6a7540025be92edf
refs/heads/master
2021-01-02T22:53:43.215000
2018-05-13T06:28:26
2018-05-13T06:28:26
99,413,808
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package comt.test.method.reference; class StringSort { public int stringSortMethod(String a, String b) { return a.compareTo(b); } }
UTF-8
Java
155
java
StringSort.java
Java
[]
null
[]
package comt.test.method.reference; class StringSort { public int stringSortMethod(String a, String b) { return a.compareTo(b); } }
155
0.651613
0.651613
6
24.166666
18.114605
53
false
false
0
0
0
0
0
0
0.5
false
false
4
a4e64b8e72a31b1756de872d3a998aae3b479d71
3,702,261,863,373
bc507f5793e8340459d53af0495f74e9b2c7fb9e
/Vue.java
2985bf3e630708f826eb5364e8ff0054b0b79a66
[ "Apache-2.0" ]
permissive
SowahCore/KamisaJOJO
https://github.com/SowahCore/KamisaJOJO
a8b5f40a370af2ebc45bd73d524bdf1663f9e315
624784a5b2cef17e28720409da3a685c497f6019
refs/heads/main
2023-03-12T04:13:10.988000
2021-02-24T20:05:56
2021-02-24T20:05:56
342,019,579
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.*; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Vue extends JFrame { protected Model model; // panels protected JPanel pTout; protected JPanel pSousTout; protected JPanel pBouton; //bouton protected JButton[][] tabBouton; //menu protected JMenuBar barMenu; protected JMenu menu; protected JMenuItem mNouvellePartie; protected JMenuItem mAPropos; public Vue(Model model) { this.model = model; initAttribut(); creerMenu(); creerJeu(); pack(); setVisible(true); setResizable(false); setTitle("KamisaJOJO"); setIconImage(Toolkit.getDefaultToolkit().getImage("Images/logo.png")); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); } public void initAttribut(){ barMenu = new JMenuBar(); menu = new JMenu("Option"); mNouvellePartie = new JMenuItem("Nouvelle Partie"); mAPropos = new JMenuItem("À Propos"); initGrille(); } public void creerJeu(){ pTout = new JPanel(); pSousTout = new JPanel(); pBouton = new JPanel(); pSousTout.setLayout(new BoxLayout(pSousTout, BoxLayout.Y_AXIS)); pBouton.setLayout(new GridLayout(8,8)); pSousTout.add(pBouton); pTout.add(pSousTout); for (JButton[] listeBouton : this.tabBouton) { for (JButton btn : listeBouton) { pBouton.add(btn); } } setContentPane(pTout); } public void initGrille(){ tabBouton = new JButton[8][8]; for(int i = 0; i < 8; i++){ for (int j = 0; j < 8; j++) { tabBouton[i][j] = new JButton(); tabBouton[i][j].setPreferredSize(new Dimension(64, 64)); tabBouton[i][j].setBorder(BorderFactory.createEmptyBorder()); // tabBouton[i][j].setBackground(Color.decode(model.COULEURS[i][j])); } } } public void creerMenu(){ barMenu.add(menu); menu.add(mNouvellePartie); menu.addSeparator(); menu.add(mAPropos); setJMenuBar(barMenu); } public void setMenuControler(ActionListener listener){ mNouvellePartie.addActionListener(listener); mAPropos.addActionListener(listener); } public void setButtonControler(ActionListener listener){ for(int i = 0; i < 8; i++){ for (int j = 0; j < 8; j++) { tabBouton[i][j].addActionListener(listener); } } } public void creerDialog(String msg){ JOptionPane dialog = new JOptionPane(); dialog.showMessageDialog(this, msg); JDialog fenDialog = dialog.createDialog(this, msg); } public JButton getBouton(int i, int j) { return tabBouton[i][j]; } public JMenuItem getNouvellePartie() { return mNouvellePartie; } public JMenuItem getAPropos() { return mAPropos; } }
UTF-8
Java
2,593
java
Vue.java
Java
[]
null
[]
import java.util.*; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Vue extends JFrame { protected Model model; // panels protected JPanel pTout; protected JPanel pSousTout; protected JPanel pBouton; //bouton protected JButton[][] tabBouton; //menu protected JMenuBar barMenu; protected JMenu menu; protected JMenuItem mNouvellePartie; protected JMenuItem mAPropos; public Vue(Model model) { this.model = model; initAttribut(); creerMenu(); creerJeu(); pack(); setVisible(true); setResizable(false); setTitle("KamisaJOJO"); setIconImage(Toolkit.getDefaultToolkit().getImage("Images/logo.png")); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); } public void initAttribut(){ barMenu = new JMenuBar(); menu = new JMenu("Option"); mNouvellePartie = new JMenuItem("Nouvelle Partie"); mAPropos = new JMenuItem("À Propos"); initGrille(); } public void creerJeu(){ pTout = new JPanel(); pSousTout = new JPanel(); pBouton = new JPanel(); pSousTout.setLayout(new BoxLayout(pSousTout, BoxLayout.Y_AXIS)); pBouton.setLayout(new GridLayout(8,8)); pSousTout.add(pBouton); pTout.add(pSousTout); for (JButton[] listeBouton : this.tabBouton) { for (JButton btn : listeBouton) { pBouton.add(btn); } } setContentPane(pTout); } public void initGrille(){ tabBouton = new JButton[8][8]; for(int i = 0; i < 8; i++){ for (int j = 0; j < 8; j++) { tabBouton[i][j] = new JButton(); tabBouton[i][j].setPreferredSize(new Dimension(64, 64)); tabBouton[i][j].setBorder(BorderFactory.createEmptyBorder()); // tabBouton[i][j].setBackground(Color.decode(model.COULEURS[i][j])); } } } public void creerMenu(){ barMenu.add(menu); menu.add(mNouvellePartie); menu.addSeparator(); menu.add(mAPropos); setJMenuBar(barMenu); } public void setMenuControler(ActionListener listener){ mNouvellePartie.addActionListener(listener); mAPropos.addActionListener(listener); } public void setButtonControler(ActionListener listener){ for(int i = 0; i < 8; i++){ for (int j = 0; j < 8; j++) { tabBouton[i][j].addActionListener(listener); } } } public void creerDialog(String msg){ JOptionPane dialog = new JOptionPane(); dialog.showMessageDialog(this, msg); JDialog fenDialog = dialog.createDialog(this, msg); } public JButton getBouton(int i, int j) { return tabBouton[i][j]; } public JMenuItem getNouvellePartie() { return mNouvellePartie; } public JMenuItem getAPropos() { return mAPropos; } }
2,593
0.692901
0.686728
118
20.966103
18.389814
73
false
false
0
0
0
0
0
0
1.991525
false
false
4
b6a129e441e450b1e7dfa7e866a05bd3d71fbca8
26,353,919,398,448
e240e994b40a4e972f691876327f93dd37a39bde
/src/test/java/com/auth0/jwt/JWTVerifierRsa256Test.java
485954ce9c5883542e446ab9e9fa56aa36253eab
[ "MIT" ]
permissive
twtkthh2008/java-jwt
https://github.com/twtkthh2008/java-jwt
19d6bc19b28e58f42b315bdd163a115f7832e353
217af05d16d62e462f5fa4456c090c1af9e1a51e
refs/heads/master
2021-01-15T12:09:19.008000
2016-08-24T01:36:33
2016-08-24T01:36:49
68,508,390
0
1
null
true
2016-09-18T08:40:46
2016-09-18T08:40:46
2016-09-18T08:15:41
2016-09-17T06:54:15
239
0
0
0
null
null
null
package com.auth0.jwt; import com.auth0.jwt.pem.X509CertUtils; import org.apache.commons.codec.binary.Base64; import org.junit.Test; import java.io.File; import java.nio.file.Files; import java.security.PublicKey; import java.security.SignatureException; import java.security.cert.X509Certificate; import java.util.HashMap; import java.util.Map; import static com.auth0.jwt.pem.PemReader.readPublicKey; import static junit.framework.TestCase.assertNotNull; /** * RS256 Verification Checks */ public class JWTVerifierRsa256Test { private final static String RESOURCES_DIR = "src/test/resources/auth0-pem/"; private final static String MISMATCHED_RESOURCES_DIR = "src/test/resources/test-pem/"; private final static String PUBLIC_KEY_PEM_FILENAME = "key.pem"; private final static String MISMATCHED_PUBLIC_KEY_PEM_FILENAME = "test-auth0.pem"; /** * Here we pass in a public key that does not correspond to the private key that was used to sign the JWT Token */ @Test(expected = SignatureException.class) public void shouldFailOnInvalidSignature() throws Exception { final String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6IlFVTkVRelZCTXpoRk1FVTNRMFZGTURJNFFqYzROakJDTkRSQ1JFRkNSalkzUWpnMFJEVXlOZyJ9" + "." + "eyJyb2xlcyI6WyJST0xFX0FETUlOIl0sInVzZXJfaWQiOiJhdXRoMHw1NzcxMGU5ZDE0MWIwN2YyMmU3NDNhYzciLCJlbWFpbCI6ImFyY3NlbGRvbit0cm5AZ21haWwuY29tIiwiZW1haWxfdmVyaWZpZWQiOnRydWUsImlzcyI6Imh0dHBzOi8vYWppbG9uMS5hdXRoMC5jb20vIiwic3ViIjoiYXV0aDB8NTc3MTBlOWQxNDFiMDdmMjJlNzQzYWM3IiwiYXVkIjoibm5ld1NobHBHVDFBbkZpY1ExUGlKWXdheENuejE4eUIiLCJleHAiOjE0Njc3MDk5OTMsImlhdCI6MTQ2NzY3Mzk5M30" + "." + "gQML78V8H6WN3MSN1QhrFG4AxNTdFChPBQxrnuqPF0iBvf35v_z9oDzTERaPBDWFHzWT17h0ADxpl7tCIo43k0FoFie6RHa5j82iHnOKPhcqM5hArfKDYk3G5gc30lVmFiMm8PX8WKzDExygLqXZVnIzfB-EmcJWW_2fLiFEMpNC8KDTBVAiyds_n5kiGmW6F_QpLt11af3BDy71tg2fuqkyJE6pEHd1HsTHNCFQzWt7GevVB0HouJS099p6GphsH3kIhmAvHp5j267uYv49sndiUaLq7bL6GZnzv8dhzgQlucHvNaIZ6m6m6n4t43cjUxSrO0ZP9Crv9NBDJme0cA"; final PublicKey publicKey = readPublicKey(MISMATCHED_RESOURCES_DIR + MISMATCHED_PUBLIC_KEY_PEM_FILENAME); assertNotNull(publicKey); new JWTVerifier(publicKey, "audience").verifySignature(token.split("\\."), Algorithm.RS256); } /** * Here we pass in a public key that correctly corresponds to the private key that was used to sign the JWT Token */ @Test public void shouldVerifySignature() throws Exception { final String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6IlFVTkVRelZCTXpoRk1FVTNRMFZGTURJNFFqYzROakJDTkRSQ1JFRkNSalkzUWpnMFJEVXlOZyJ9" + "." + "eyJyb2xlcyI6WyJST0xFX0FETUlOIl0sInVzZXJfaWQiOiJhdXRoMHw1NzcxMGU5ZDE0MWIwN2YyMmU3NDNhYzciLCJlbWFpbCI6ImFyY3NlbGRvbit0cm5AZ21haWwuY29tIiwiZW1haWxfdmVyaWZpZWQiOnRydWUsImlzcyI6Imh0dHBzOi8vYWppbG9uMS5hdXRoMC5jb20vIiwic3ViIjoiYXV0aDB8NTc3MTBlOWQxNDFiMDdmMjJlNzQzYWM3IiwiYXVkIjoibm5ld1NobHBHVDFBbkZpY1ExUGlKWXdheENuejE4eUIiLCJleHAiOjE0Njc3MDk5OTMsImlhdCI6MTQ2NzY3Mzk5M30" + "." + "gQML78V8H6WN3MSN1QhrFG4AxNTdFChPBQxrnuqPF0iBvf35v_z9oDzTERaPBDWFHzWT17h0ADxpl7tCIo43k0FoFie6RHa5j82iHnOKPhcqM5hArfKDYk3G5gc30lVmFiMm8PX8WKzDExygLqXZVnIzfB-EmcJWW_2fLiFEMpNC8KDTBVAiyds_n5kiGmW6F_QpLt11af3BDy71tg2fuqkyJE6pEHd1HsTHNCFQzWt7GevVB0HouJS099p6GphsH3kIhmAvHp5j267uYv49sndiUaLq7bL6GZnzv8dhzgQlucHvNaIZ6m6m6n4t43cjUxSrO0ZP9Crv9NBDJme0cA"; final PublicKey publicKey = readPublicKey(RESOURCES_DIR + PUBLIC_KEY_PEM_FILENAME); assertNotNull(publicKey); new JWTVerifier(publicKey, "audience").verifySignature(token.split("\\."), Algorithm.RS256); } /** * Here we modify the signature on an otherwise legal JWT Token and check verification using the correct Public Key fails */ @Test(expected = SignatureException.class) public void shouldFailOnInvalidJWTTokenSignature() throws Exception { final String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6IlFVTkVRelZCTXpoRk1FVTNRMFZGTURJNFFqYzROakJDTkRSQ1JFRkNSalkzUWpnMFJEVXlOZyJ9" + "." + "eyJyb2xlcyI6WyJST0xFX0FETUlOIl0sInVzZXJfaWQiOiJhdXRoMHw1NzcxMGU5ZDE0MWIwN2YyMmU3NDNhYzciLCJlbWFpbCI6ImFyY3NlbGRvbit0cm5AZ21haWwuY29tIiwiZW1haWxfdmVyaWZpZWQiOnRydWUsImlzcyI6Imh0dHBzOi8vYWppbG9uMS5hdXRoMC5jb20vIiwic3ViIjoiYXV0aDB8NTc3MTBlOWQxNDFiMDdmMjJlNzQzYWM3IiwiYXVkIjoibm5ld1NobHBHVDFBbkZpY1ExUGlKWXdheENuejE4eUIiLCJleHAiOjE0Njc3MDk5OTMsImlhdCI6MTQ2NzY3Mzk5M30" + "." + "XXXXX8V8H6WN3MSN1QhrFG4AxNTdFChPBQxrnuqPF0iBvf35v_z9oDzTERaPBDWFHzWT17h0ADxpl7tCIo43k0FoFie6RHa5j82iHnOKPhcqM5hArfKDYk3G5gc30lVmFiMm8PX8WKzDExygLqXZVnIzfB-EmcJWW_2fLiFEMpNC8KDTBVAiyds_n5kiGmW6F_QpLt11af3BDy71tg2fuqkyJE6pEHd1HsTHNCFQzWt7GevVB0HouJS099p6GphsH3kIhmAvHp5j267uYv49sndiUaLq7bL6GZnzv8dhzgQlucHvNaIZ6m6m6n4t43cjUxSrO0ZP9Crv9NBDJme0cA"; final PublicKey publicKey = readPublicKey(RESOURCES_DIR + PUBLIC_KEY_PEM_FILENAME); assertNotNull(publicKey); new JWTVerifier(publicKey, "audience").verifySignature(token.split("\\."), Algorithm.RS256); } /** * Here we modify the payload section on an otherwise legal JWT Token and check verification using the correct Public Key and * unaltered JWT signature (which now doesn't match the payload) fails */ @Test(expected = SignatureException.class) public void shouldFailOnInvalidJWTTokenPayload() throws Exception { final String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6IlFVTkVRelZCTXpoRk1FVTNRMFZGTURJNFFqYzROakJDTkRSQ1JFRkNSalkzUWpnMFJEVXlOZyJ9" + "." + "XXXXX2xlcyI6WyJST0xFX0FETUlOIl0sInVzZXJfaWQiOiJhdXRoMHw1NzcxMGU5ZDE0MWIwN2YyMmU3NDNhYzciLCJlbWFpbCI6ImFyY3NlbGRvbit0cm5AZ21haWwuY29tIiwiZW1haWxfdmVyaWZpZWQiOnRydWUsImlzcyI6Imh0dHBzOi8vYWppbG9uMS5hdXRoMC5jb20vIiwic3ViIjoiYXV0aDB8NTc3MTBlOWQxNDFiMDdmMjJlNzQzYWM3IiwiYXVkIjoibm5ld1NobHBHVDFBbkZpY1ExUGlKWXdheENuejE4eUIiLCJleHAiOjE0Njc3MDk5OTMsImlhdCI6MTQ2NzY3Mzk5M30" + "." + "gQML78V8H6WN3MSN1QhrFG4AxNTdFChPBQxrnuqPF0iBvf35v_z9oDzTERaPBDWFHzWT17h0ADxpl7tCIo43k0FoFie6RHa5j82iHnOKPhcqM5hArfKDYk3G5gc30lVmFiMm8PX8WKzDExygLqXZVnIzfB-EmcJWW_2fLiFEMpNC8KDTBVAiyds_n5kiGmW6F_QpLt11af3BDy71tg2fuqkyJE6pEHd1HsTHNCFQzWt7GevVB0HouJS099p6GphsH3kIhmAvHp5j267uYv49sndiUaLq7bL6GZnzv8dhzgQlucHvNaIZ6m6m6n4t43cjUxSrO0ZP9Crv9NBDJme0cA"; final PublicKey publicKey = readPublicKey(RESOURCES_DIR + PUBLIC_KEY_PEM_FILENAME); assertNotNull(publicKey); new JWTVerifier(publicKey, "audience").verifySignature(token.split("\\."), Algorithm.RS256); } @Test(expected = IllegalStateException.class) public void shouldFailWithJwtThaHasTamperedAlgorithm() throws Exception { final File file = new File(RESOURCES_DIR + PUBLIC_KEY_PEM_FILENAME); final byte[] data = Files.readAllBytes(file.toPath()); JWTSigner signer = new JWTSigner(data); Map<String, Object> claims = new HashMap<>(); claims.put("sub", "userid"); JWTSigner.Options options = new JWTSigner.Options(); options.setAlgorithm(Algorithm.HS256); String jwt = signer.sign(claims, options); new JWTVerifier(data).verify(jwt); final PublicKey publicKey = readPublicKey(RESOURCES_DIR + PUBLIC_KEY_PEM_FILENAME); new JWTVerifier(publicKey).verify(jwt); } }
UTF-8
Java
7,410
java
JWTVerifierRsa256Test.java
Java
[ { "context": " throws Exception {\n final String token = \"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6IlFVTkVRelZCTXpoRk1FVTNRMFZGTURJNFFqYzROakJDTkRSQ1JFRkNSalkzUWpnMFJEVXlOZyJ9\" +\n \".\" +\n \"eyJyb2x", "end": 1262, "score": 0.9997610449790955, "start": 1142, "tag": "KEY", "value": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6IlFVTkVRelZCTXpoRk1FVTNRMFZGTURJNFFqYzROakJDTkRSQ1JFRkNSalkzUWpnMFJEVXlOZyJ9" }, { "context": "XlOZyJ9\" +\n \".\" +\n \"eyJyb2xlcyI6WyJST0xFX0FETUlOIl0sInVzZXJfaWQiOiJhdXRoMHw1NzcxMGU5ZDE0MWIwN2YyMmU3NDNhYzciLCJlbWFpbCI6ImFyY3NlbGRvbit0cm5AZ21haWwuY29tIiwiZW1haWxfdmVyaWZpZWQiOnRydWUsImlzcyI6Imh0dHBzOi8vYWppbG9uMS5hdXRoMC5jb20vIiwic3ViIjoiYXV0aDB8NTc3MTBlOWQxNDFiMDdmMjJlNzQzYWM3IiwiYXVkIjoibm5ld1NobHBHVDFBbkZpY1ExUGlKWXdheENuejE4eUIiLCJleHAiOjE0Njc3MDk5OTMsImlhdCI6MTQ2NzY3Mzk5M30\" +\n \".\" +\n \"gQML78V8", "end": 1669, "score": 0.9986550211906433, "start": 1305, "tag": "KEY", "value": "eyJyb2xlcyI6WyJST0xFX0FETUlOIl0sInVzZXJfaWQiOiJhdXRoMHw1NzcxMGU5ZDE0MWIwN2YyMmU3NDNhYzciLCJlbWFpbCI6ImFyY3NlbGRvbit0cm5AZ21haWwuY29tIiwiZW1haWxfdmVyaWZpZWQiOnRydWUsImlzcyI6Imh0dHBzOi8vYWppbG9uMS5hdXRoMC5jb20vIiwic3ViIjoiYXV0aDB8NTc3MTBlOWQxNDFiMDdmMjJlNzQzYWM3IiwiYXVkIjoibm5ld1NobHBHVDFBbkZpY1ExUGlKWXdheENuejE4eUIiLCJleHAiOjE0Njc3MDk5OTMsImlhdCI6MTQ2NzY3Mzk5M30\"" }, { "context": "MDk5OTMsImlhdCI6MTQ2NzY3Mzk5M30\" +\n \".\" +\n \"gQML78V8H6WN3MSN1QhrFG4AxNTdFC", "end": 1691, "score": 0.9603862166404724, "start": 1688, "tag": "KEY", "value": "\".\"" }, { "context": "Mzk5M30\" +\n \".\" +\n \"gQML78V8H6WN3MSN1QhrFG4AxNTdFChPBQxrnuqPF0iBvf35v_z9oDzTERaPBDWFHzWT17h0ADxpl7tCIo43k0FoFie6RHa5j82iHnOKPhcqM5hArfKDYk3G5gc30lVmFiMm8PX8WKzDExygLqXZVnIzfB-EmcJWW_2fLiFEMpNC8KDTBVAiyds_n5kiGmW6F_QpLt11af3BDy71tg2fuqkyJE6pEHd1HsTHNCFQzWt7GevVB0HouJS099p6GphsH3kIhmAvHp5j267uYv49sndiUaLq7bL6GZnzv8dhzgQlucHvNaIZ6m6m6n4t43cjUxSrO0ZP9Crv9NBDJme0cA\";\n final PublicKey publicKey = readPublicK", "end": 2053, "score": 0.9989487528800964, "start": 1711, "tag": "KEY", "value": "gQML78V8H6WN3MSN1QhrFG4AxNTdFChPBQxrnuqPF0iBvf35v_z9oDzTERaPBDWFHzWT17h0ADxpl7tCIo43k0FoFie6RHa5j82iHnOKPhcqM5hArfKDYk3G5gc30lVmFiMm8PX8WKzDExygLqXZVnIzfB-EmcJWW_2fLiFEMpNC8KDTBVAiyds_n5kiGmW6F_QpLt11af3BDy71tg2fuqkyJE6pEHd1HsTHNCFQzWt7GevVB0HouJS099p6GphsH3kIhmAvHp5j267uYv49sndiUaLq7bL6GZnzv8dhzgQlucHvNaIZ6m6m6n4t43cjUxSrO0ZP9Crv9NBDJme0cA" }, { "context": " throws Exception {\n final String token = \"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6IlFVTkVRelZCTXpoRk1FVTNRMFZGTURJNFFqYzROakJDTkRSQ1JFRkNSalkzUWpnMFJEVXlOZyJ9\" +\n \".\" +\n \"eyJyb2x", "end": 2665, "score": 0.9349790811538696, "start": 2545, "tag": "KEY", "value": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6IlFVTkVRelZCTXpoRk1FVTNRMFZGTURJNFFqYzROakJDTkRSQ1JFRkNSalkzUWpnMFJEVXlOZyJ9" }, { "context": "XlOZyJ9\" +\n \".\" +\n \"eyJyb2xlcyI6WyJST0xFX0FETUlOIl0sInVzZXJfaWQiOiJhdXRoMHw1NzcxMGU5ZDE0MWIwN2YyMmU3NDNhYzciLCJlbWFpbCI6ImFyY3NlbGRvbit0cm5AZ21haWwuY29tIiwiZW1haWxfdmVyaWZpZWQiOnRydWUsImlzcyI6Imh0dHBzOi8vYWppbG9uMS5hdXRoMC5jb20vIiwic3ViIjoiYXV0aDB8NTc3MTBlOWQxNDFiMDdmMjJlNzQzYWM3IiwiYXVkIjoibm5ld1NobHBHVDFBbkZpY1ExUGlKWXdheENuejE4eUIiLCJleHAiOjE0Njc3MDk5OTMsImlhdCI6MTQ2NzY3Mzk5M30\" +\n \".\" +\n \"gQML78V", "end": 3071, "score": 0.9996083378791809, "start": 2708, "tag": "KEY", "value": "eyJyb2xlcyI6WyJST0xFX0FETUlOIl0sInVzZXJfaWQiOiJhdXRoMHw1NzcxMGU5ZDE0MWIwN2YyMmU3NDNhYzciLCJlbWFpbCI6ImFyY3NlbGRvbit0cm5AZ21haWwuY29tIiwiZW1haWxfdmVyaWZpZWQiOnRydWUsImlzcyI6Imh0dHBzOi8vYWppbG9uMS5hdXRoMC5jb20vIiwic3ViIjoiYXV0aDB8NTc3MTBlOWQxNDFiMDdmMjJlNzQzYWM3IiwiYXVkIjoibm5ld1NobHBHVDFBbkZpY1ExUGlKWXdheENuejE4eUIiLCJleHAiOjE0Njc3MDk5OTMsImlhdCI6MTQ2NzY3Mzk5M30" }, { "context": "Mzk5M30\" +\n \".\" +\n \"gQML78V8H6WN3MSN1QhrFG4AxNTdFChPBQxrnuqPF0iBvf35v_z9oDzTERaPBDWFHzWT17h0ADxpl7tCIo43k0FoFie6RHa5j82iHnOKPhcqM5hArfKDYk3G5gc30lVmFiMm8PX8WKzDExygLqXZVnIzfB-EmcJWW_2fLiFEMpNC8KDTBVAiyds_n5kiGmW6F_QpLt11af3BDy71tg2fuqkyJE6pEHd1HsTHNCFQzWt7GevVB0HouJS099p6GphsH3kIhmAvHp5j267uYv49sndiUaLq7bL6GZnzv8dhzgQlucHvNaIZ6m6m6n4t43cjUxSrO0ZP9Crv9NBDJme0cA\";\n final PublicKey publicKey = readPublicK", "end": 3456, "score": 0.9852893948554993, "start": 3114, "tag": "KEY", "value": "gQML78V8H6WN3MSN1QhrFG4AxNTdFChPBQxrnuqPF0iBvf35v_z9oDzTERaPBDWFHzWT17h0ADxpl7tCIo43k0FoFie6RHa5j82iHnOKPhcqM5hArfKDYk3G5gc30lVmFiMm8PX8WKzDExygLqXZVnIzfB-EmcJWW_2fLiFEMpNC8KDTBVAiyds_n5kiGmW6F_QpLt11af3BDy71tg2fuqkyJE6pEHd1HsTHNCFQzWt7GevVB0HouJS099p6GphsH3kIhmAvHp5j267uYv49sndiUaLq7bL6GZnzv8dhzgQlucHvNaIZ6m6m6n4t43cjUxSrO0ZP9Crv9NBDJme0cA" }, { "context": " throws Exception {\n final String token = \"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6IlFVTkVRelZCTXpoRk1FVTNRMFZGTURJNFFqYzROakJDTkRSQ1JFRkNSalkzUWpnMFJEVXlOZyJ9\" +\n \".\" +\n \"eyJyb2x", "end": 4106, "score": 0.9996607899665833, "start": 3986, "tag": "KEY", "value": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6IlFVTkVRelZCTXpoRk1FVTNRMFZGTURJNFFqYzROakJDTkRSQ1JFRkNSalkzUWpnMFJEVXlOZyJ9" }, { "context": "XlOZyJ9\" +\n \".\" +\n \"eyJyb2xlcyI6WyJST0xFX0FETUlOIl0sInVzZXJfaWQiOiJhdXRoMHw1NzcxMGU5ZDE0MWIwN2YyMmU3NDNhYzciLCJlbWFpbCI6ImFyY3NlbGRvbit0cm5AZ21haWwuY29tIiwiZW1haWxfdmVyaWZpZWQiOnRydWUsImlzcyI6Imh0dHBzOi8vYWppbG9uMS5hdXRoMC5jb20vIiwic3ViIjoiYXV0aDB8NTc3MTBlOWQxNDFiMDdmMjJlNzQzYWM3IiwiYXVkIjoibm5ld1NobHBHVDFBbkZpY1ExUGlKWXdheENuejE4eUIiLCJleHAiOjE0Njc3MDk5OTMsImlhdCI6MTQ2NzY3Mzk5M30\" +\n \".\" +\n \"XXXXX8V", "end": 4512, "score": 0.9996596574783325, "start": 4149, "tag": "KEY", "value": "eyJyb2xlcyI6WyJST0xFX0FETUlOIl0sInVzZXJfaWQiOiJhdXRoMHw1NzcxMGU5ZDE0MWIwN2YyMmU3NDNhYzciLCJlbWFpbCI6ImFyY3NlbGRvbit0cm5AZ21haWwuY29tIiwiZW1haWxfdmVyaWZpZWQiOnRydWUsImlzcyI6Imh0dHBzOi8vYWppbG9uMS5hdXRoMC5jb20vIiwic3ViIjoiYXV0aDB8NTc3MTBlOWQxNDFiMDdmMjJlNzQzYWM3IiwiYXVkIjoibm5ld1NobHBHVDFBbkZpY1ExUGlKWXdheENuejE4eUIiLCJleHAiOjE0Njc3MDk5OTMsImlhdCI6MTQ2NzY3Mzk5M30" }, { "context": "Mzk5M30\" +\n \".\" +\n \"XXXXX8V8H6WN3MSN1QhrFG4AxNTdFChPBQxrnuqPF0iBvf35v_z9oDzTERaPBDWFHzWT17h0ADxpl7tCIo43k0FoFie6RHa5j82iHnOKPhcqM5hArfKDYk3G5gc30lVmFiMm8PX8WKzDExygLqXZVnIzfB-EmcJWW_2fLiFEMpNC8KDTBVAiyds_n5kiGmW6F_QpLt11af3BDy71tg2fuqkyJE6pEHd1HsTHNCFQzWt7GevVB0HouJS099p6GphsH3kIhmAvHp5j267uYv49sndiUaLq7bL6GZnzv8dhzgQlucHvNaIZ6m6m6n4t43cjUxSrO0ZP9Crv9NBDJme0cA\";\n final PublicKey publicKey = readPublicK", "end": 4897, "score": 0.9992973208427429, "start": 4555, "tag": "KEY", "value": "XXXXX8V8H6WN3MSN1QhrFG4AxNTdFChPBQxrnuqPF0iBvf35v_z9oDzTERaPBDWFHzWT17h0ADxpl7tCIo43k0FoFie6RHa5j82iHnOKPhcqM5hArfKDYk3G5gc30lVmFiMm8PX8WKzDExygLqXZVnIzfB-EmcJWW_2fLiFEMpNC8KDTBVAiyds_n5kiGmW6F_QpLt11af3BDy71tg2fuqkyJE6pEHd1HsTHNCFQzWt7GevVB0HouJS099p6GphsH3kIhmAvHp5j267uYv49sndiUaLq7bL6GZnzv8dhzgQlucHvNaIZ6m6m6n4t43cjUxSrO0ZP9Crv9NBDJme0cA" }, { "context": " throws Exception {\n final String token = \"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6IlFVTkVRelZCTXpoRk1FVTNRMFZGTURJNFFqYzROakJDTkRSQ1JFRkNSalkzUWpnMFJEVXlOZyJ9\" +\n \".\" +\n \"XXXXX2x", "end": 5624, "score": 0.9997702836990356, "start": 5504, "tag": "KEY", "value": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6IlFVTkVRelZCTXpoRk1FVTNRMFZGTURJNFFqYzROakJDTkRSQ1JFRkNSalkzUWpnMFJEVXlOZyJ9" }, { "context": "XlOZyJ9\" +\n \".\" +\n \"XXXXX2xlcyI6WyJST0xFX0FETUlOIl0sInVzZXJfaWQiOiJhdXRoMHw1NzcxMGU5ZDE0MWIwN2YyMmU3NDNhYzciLCJlbWFpbCI6ImFyY3NlbGRvbit0cm5AZ21haWwuY29tIiwiZW1haWxfdmVyaWZpZWQiOnRydWUsImlzcyI6Imh0dHBzOi8vYWppbG9uMS5hdXRoMC5jb20vIiwic3ViIjoiYXV0aDB8NTc3MTBlOWQxNDFiMDdmMjJlNzQzYWM3IiwiYXVkIjoibm5ld1NobHBHVDFBbkZpY1ExUGlKWXdheENuejE4eUIiLCJleHAiOjE0Njc3MDk5OTMsImlhdCI6MTQ2NzY3Mzk5M30\" +\n \".\" +\n \"gQML78V8H6", "end": 6033, "score": 0.9980008602142334, "start": 5667, "tag": "KEY", "value": "XXXXX2xlcyI6WyJST0xFX0FETUlOIl0sInVzZXJfaWQiOiJhdXRoMHw1NzcxMGU5ZDE0MWIwN2YyMmU3NDNhYzciLCJlbWFpbCI6ImFyY3NlbGRvbit0cm5AZ21haWwuY29tIiwiZW1haWxfdmVyaWZpZWQiOnRydWUsImlzcyI6Imh0dHBzOi8vYWppbG9uMS5hdXRoMC5jb20vIiwic3ViIjoiYXV0aDB8NTc3MTBlOWQxNDFiMDdmMjJlNzQzYWM3IiwiYXVkIjoibm5ld1NobHBHVDFBbkZpY1ExUGlKWXdheENuejE4eUIiLCJleHAiOjE0Njc3MDk5OTMsImlhdCI6MTQ2NzY3Mzk5M30\" +" }, { "context": "MDk5OTMsImlhdCI6MTQ2NzY3Mzk5M30\" +\n \".\" +\n \"gQML78V8H6WN3MSN1QhrFG4AxNTdFChP", "end": 6055, "score": 0.7833581566810608, "start": 6050, "tag": "KEY", "value": "\".\" +" }, { "context": "Mzk5M30\" +\n \".\" +\n \"gQML78V8H6WN3MSN1QhrFG4AxNTdFChPBQxrnuqPF0iBvf35v_z9oDzTERaPBDWFHzWT17h0ADxpl7tCIo43k0FoFie6RHa5j82iHnOKPhcqM5hArfKDYk3G5gc30lVmFiMm8PX8WKzDExygLqXZVnIzfB-EmcJWW_2fLiFEMpNC8KDTBVAiyds_n5kiGmW6F_QpLt11af3BDy71tg2fuqkyJE6pEHd1HsTHNCFQzWt7GevVB0HouJS099p6GphsH3kIhmAvHp5j267uYv49sndiUaLq7bL6GZnzv8dhzgQlucHvNaIZ6m6m6n4t43cjUxSrO0ZP9Crv9NBDJme0cA\";\n final PublicKey publicKey = readPublicK", "end": 6415, "score": 0.9979597926139832, "start": 6073, "tag": "KEY", "value": "gQML78V8H6WN3MSN1QhrFG4AxNTdFChPBQxrnuqPF0iBvf35v_z9oDzTERaPBDWFHzWT17h0ADxpl7tCIo43k0FoFie6RHa5j82iHnOKPhcqM5hArfKDYk3G5gc30lVmFiMm8PX8WKzDExygLqXZVnIzfB-EmcJWW_2fLiFEMpNC8KDTBVAiyds_n5kiGmW6F_QpLt11af3BDy71tg2fuqkyJE6pEHd1HsTHNCFQzWt7GevVB0HouJS099p6GphsH3kIhmAvHp5j267uYv49sndiUaLq7bL6GZnzv8dhzgQlucHvNaIZ6m6m6n4t43cjUxSrO0ZP9Crv9NBDJme0cA" } ]
null
[]
package com.auth0.jwt; import com.auth0.jwt.pem.X509CertUtils; import org.apache.commons.codec.binary.Base64; import org.junit.Test; import java.io.File; import java.nio.file.Files; import java.security.PublicKey; import java.security.SignatureException; import java.security.cert.X509Certificate; import java.util.HashMap; import java.util.Map; import static com.auth0.jwt.pem.PemReader.readPublicKey; import static junit.framework.TestCase.assertNotNull; /** * RS256 Verification Checks */ public class JWTVerifierRsa256Test { private final static String RESOURCES_DIR = "src/test/resources/auth0-pem/"; private final static String MISMATCHED_RESOURCES_DIR = "src/test/resources/test-pem/"; private final static String PUBLIC_KEY_PEM_FILENAME = "key.pem"; private final static String MISMATCHED_PUBLIC_KEY_PEM_FILENAME = "test-auth0.pem"; /** * Here we pass in a public key that does not correspond to the private key that was used to sign the JWT Token */ @Test(expected = SignatureException.class) public void shouldFailOnInvalidSignature() throws Exception { final String token = "<KEY>" + "." + "<KEY> + "." + "<KEY>"; final PublicKey publicKey = readPublicKey(MISMATCHED_RESOURCES_DIR + MISMATCHED_PUBLIC_KEY_PEM_FILENAME); assertNotNull(publicKey); new JWTVerifier(publicKey, "audience").verifySignature(token.split("\\."), Algorithm.RS256); } /** * Here we pass in a public key that correctly corresponds to the private key that was used to sign the JWT Token */ @Test public void shouldVerifySignature() throws Exception { final String token = "<KEY>" + "." + "<KEY>" + "." + "<KEY>"; final PublicKey publicKey = readPublicKey(RESOURCES_DIR + PUBLIC_KEY_PEM_FILENAME); assertNotNull(publicKey); new JWTVerifier(publicKey, "audience").verifySignature(token.split("\\."), Algorithm.RS256); } /** * Here we modify the signature on an otherwise legal JWT Token and check verification using the correct Public Key fails */ @Test(expected = SignatureException.class) public void shouldFailOnInvalidJWTTokenSignature() throws Exception { final String token = "<KEY>" + "." + "<KEY>" + "." + "<KEY>"; final PublicKey publicKey = readPublicKey(RESOURCES_DIR + PUBLIC_KEY_PEM_FILENAME); assertNotNull(publicKey); new JWTVerifier(publicKey, "audience").verifySignature(token.split("\\."), Algorithm.RS256); } /** * Here we modify the payload section on an otherwise legal JWT Token and check verification using the correct Public Key and * unaltered JWT signature (which now doesn't match the payload) fails */ @Test(expected = SignatureException.class) public void shouldFailOnInvalidJWTTokenPayload() throws Exception { final String token = "<KEY>" + "." + "<KEY> "." + "<KEY>"; final PublicKey publicKey = readPublicKey(RESOURCES_DIR + PUBLIC_KEY_PEM_FILENAME); assertNotNull(publicKey); new JWTVerifier(publicKey, "audience").verifySignature(token.split("\\."), Algorithm.RS256); } @Test(expected = IllegalStateException.class) public void shouldFailWithJwtThaHasTamperedAlgorithm() throws Exception { final File file = new File(RESOURCES_DIR + PUBLIC_KEY_PEM_FILENAME); final byte[] data = Files.readAllBytes(file.toPath()); JWTSigner signer = new JWTSigner(data); Map<String, Object> claims = new HashMap<>(); claims.put("sub", "userid"); JWTSigner.Options options = new JWTSigner.Options(); options.setAlgorithm(Algorithm.HS256); String jwt = signer.sign(claims, options); new JWTVerifier(data).verify(jwt); final PublicKey publicKey = readPublicKey(RESOURCES_DIR + PUBLIC_KEY_PEM_FILENAME); new JWTVerifier(publicKey).verify(jwt); } }
4,166
0.803104
0.734413
105
69.561905
95.57225
383
false
false
0
0
0
0
363
0.396761
0.52381
false
false
4
cd75061d7c764df43f58fff5d394c289281353df
28,896,539,986,108
14072812b17313b1a324453d33512ef9107866fc
/MobilePurchaseSystem/src/com/cg/mps/DTO/Mobile.java
fd5b69431c87db31169c1ca0e7504a520e61bd82
[]
no_license
amity333/sql
https://github.com/amity333/sql
5fc9a5bf1fcc18dec671cdb8c26e538b7a93f271
8c39c4947662be3b84eece274c75d2894936ba20
refs/heads/master
2020-06-23T11:30:33.149000
2019-08-04T19:18:09
2019-08-04T19:18:09
198,610,207
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cg.mps.DTO; public class Mobile { int mobId; String name; int price; int quant; public Mobile() { super(); // TODO Auto-generated constructor stub } public Mobile(int mobId, String name, int price, int quant) { super(); this.mobId = mobId; this.name = name; this.price = price; this.quant = quant; } @Override public String toString() { return "Mobile [mobId=" + mobId + ", name=" + name + ", price=" + price + ", quant=" + quant + "]"; } public int getMobId() { return mobId; } public void setMobId(int mobId) { this.mobId = mobId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public int getQuant() { return quant; } public void setQuant(int quant) { this.quant = quant; } }
UTF-8
Java
951
java
Mobile.java
Java
[]
null
[]
package com.cg.mps.DTO; public class Mobile { int mobId; String name; int price; int quant; public Mobile() { super(); // TODO Auto-generated constructor stub } public Mobile(int mobId, String name, int price, int quant) { super(); this.mobId = mobId; this.name = name; this.price = price; this.quant = quant; } @Override public String toString() { return "Mobile [mobId=" + mobId + ", name=" + name + ", price=" + price + ", quant=" + quant + "]"; } public int getMobId() { return mobId; } public void setMobId(int mobId) { this.mobId = mobId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public int getQuant() { return quant; } public void setQuant(int quant) { this.quant = quant; } }
951
0.602524
0.602524
49
17.408163
15.092799
73
false
false
0
0
0
0
0
0
1.816326
false
false
4
c2cf5cb0e07bc766e3a0d34f05358b7227e52810
17,489,106,898,952
114843d130feeb59f13f908503d37e9182926614
/src/lk/ijse/mountCalvary/controller/student/profile/CompetitionForStudentController.java
681666b1b8a59ae654001ea223a927aea1c8ec4a
[]
no_license
PandukaNandara/Mount
https://github.com/PandukaNandara/Mount
c5133c700348b7f60089987ef4301ea1cd4021be
fa5009cbfc825b36d194c177063e98d7da878047
refs/heads/master
2021-07-13T06:48:29.521000
2020-05-18T13:25:50
2020-05-18T13:25:50
135,074,895
0
0
null
false
2020-05-18T13:25:52
2018-05-27T19:19:47
2019-07-10T16:10:42
2020-05-18T13:25:50
27,922
0
0
0
null
false
false
package lk.ijse.mountCalvary.controller.student.profile; import com.jfoenix.controls.JFXButton; import com.jfoenix.controls.JFXComboBox; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.layout.VBox; import lk.ijse.mountCalvary.business.BOFactory; import lk.ijse.mountCalvary.business.custom.ParticipationBO; import lk.ijse.mountCalvary.controller.SuperController; import lk.ijse.mountCalvary.tool.*; import lk.ijse.mountCalvary.model.ParticipationDTO; import lk.ijse.mountCalvary.model.StudentDTO; import net.sf.jasperreports.engine.*; import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource; import java.io.InputStream; import java.net.URL; import java.util.Date; import java.util.HashMap; import java.util.ResourceBundle; public final class CompetitionForStudentController extends SuperController implements Initializable { private static JasperReport competitionReport; @FXML protected VBox competitionForStudent; @FXML protected TableView<ParticipationDTO> tblParticipation; @FXML protected TableColumn<ParticipationDTO, String> colCompetition; @FXML protected TableColumn<ParticipationDTO, Date> colDate; @FXML protected TableColumn<ParticipationDTO, String> colActivity; @FXML protected TableColumn<ParticipationDTO, String> colEvent; @FXML protected TableColumn<ParticipationDTO, String> colResult; @FXML protected JFXComboBox<?> cboxCompetition; @FXML protected JFXComboBox<?> cboxActivity; @FXML protected TableColumn<ParticipationDTO, String> colPerformance; @FXML private JFXButton btPrint; private StudentProfileController studentProfileController; private ParticipationBO participationBOImpl; private StudentDTO selectedStudent; @Override public void initialize(URL location, ResourceBundle resources) { GlobalBoolean.setLock(false); ButtonFireForEnterSetter.setGlobalEventHandler(competitionForStudent); colActivity.setCellValueFactory(new PropertyValueFactory<>("activityName")); colCompetition.setCellValueFactory(new PropertyValueFactory<>("competitionName")); colDate.setCellValueFactory(new PropertyValueFactory<>("date")); colEvent.setCellValueFactory(new PropertyValueFactory<>("eventName")); colPerformance.setCellValueFactory(new PropertyValueFactory<>("performance")); colResult.setCellValueFactory(new PropertyValueFactory<>("result")); participationBOImpl = BOFactory.getInstance().getBO(BOFactory.BOType.PARTICIPATION); } @FXML private void btPrint_onAction(ActionEvent actionEvent) { if (selectedStudent != null) { try { if (competitionReport == null) { InputStream resourceAsStream = getClass().getResourceAsStream("/lk/ijse/mountCalvary/report/student/CompetitionForStudentReport.jrxml"); competitionReport = JasperCompileManager.compileReport(resourceAsStream); } JRBeanCollectionDataSource competition = new JRBeanCollectionDataSource(tblParticipation.getItems()); HashMap map = new HashMap(); map.put("StudentID", selectedStudent.getSID()); map.put("StudentName", selectedStudent.getSName()); map.put("Competition", competition); JasperPrint jasperPrint = JasperFillManager.fillReport(competitionReport, map, new JREmptyDataSource()); Reporter.showReport(jasperPrint, "Competition for student"); } catch (Exception e) { callLogger(e); } } else { OptionPane.showErrorAtSide("Please select a student to print."); } } @FXML void cboxActivity_onAction(ActionEvent event) { } @FXML void cboxCompetition_onAction(ActionEvent event) { } public VBox getCompetitionForStudent_controller() { return competitionForStudent; } public void setCompetitionForStudent_controller(VBox competitionForStudent_controller) { this.competitionForStudent = competitionForStudent_controller; } public void init(StudentProfileController studentProfileController) { this.studentProfileController = studentProfileController; } protected void insertStudent(StudentDTO student) { try { selectedStudent = student; ObservableList<ParticipationDTO> achievement = participationBOImpl.getCompetitionAndAchievementOfThisStudent(student.getSID()); tblParticipation.getItems().setAll(achievement); Common.clearSortOrder(tblParticipation); } catch (Exception e) { callLogger(e); } } }
UTF-8
Java
4,993
java
CompetitionForStudentController.java
Java
[]
null
[]
package lk.ijse.mountCalvary.controller.student.profile; import com.jfoenix.controls.JFXButton; import com.jfoenix.controls.JFXComboBox; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.layout.VBox; import lk.ijse.mountCalvary.business.BOFactory; import lk.ijse.mountCalvary.business.custom.ParticipationBO; import lk.ijse.mountCalvary.controller.SuperController; import lk.ijse.mountCalvary.tool.*; import lk.ijse.mountCalvary.model.ParticipationDTO; import lk.ijse.mountCalvary.model.StudentDTO; import net.sf.jasperreports.engine.*; import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource; import java.io.InputStream; import java.net.URL; import java.util.Date; import java.util.HashMap; import java.util.ResourceBundle; public final class CompetitionForStudentController extends SuperController implements Initializable { private static JasperReport competitionReport; @FXML protected VBox competitionForStudent; @FXML protected TableView<ParticipationDTO> tblParticipation; @FXML protected TableColumn<ParticipationDTO, String> colCompetition; @FXML protected TableColumn<ParticipationDTO, Date> colDate; @FXML protected TableColumn<ParticipationDTO, String> colActivity; @FXML protected TableColumn<ParticipationDTO, String> colEvent; @FXML protected TableColumn<ParticipationDTO, String> colResult; @FXML protected JFXComboBox<?> cboxCompetition; @FXML protected JFXComboBox<?> cboxActivity; @FXML protected TableColumn<ParticipationDTO, String> colPerformance; @FXML private JFXButton btPrint; private StudentProfileController studentProfileController; private ParticipationBO participationBOImpl; private StudentDTO selectedStudent; @Override public void initialize(URL location, ResourceBundle resources) { GlobalBoolean.setLock(false); ButtonFireForEnterSetter.setGlobalEventHandler(competitionForStudent); colActivity.setCellValueFactory(new PropertyValueFactory<>("activityName")); colCompetition.setCellValueFactory(new PropertyValueFactory<>("competitionName")); colDate.setCellValueFactory(new PropertyValueFactory<>("date")); colEvent.setCellValueFactory(new PropertyValueFactory<>("eventName")); colPerformance.setCellValueFactory(new PropertyValueFactory<>("performance")); colResult.setCellValueFactory(new PropertyValueFactory<>("result")); participationBOImpl = BOFactory.getInstance().getBO(BOFactory.BOType.PARTICIPATION); } @FXML private void btPrint_onAction(ActionEvent actionEvent) { if (selectedStudent != null) { try { if (competitionReport == null) { InputStream resourceAsStream = getClass().getResourceAsStream("/lk/ijse/mountCalvary/report/student/CompetitionForStudentReport.jrxml"); competitionReport = JasperCompileManager.compileReport(resourceAsStream); } JRBeanCollectionDataSource competition = new JRBeanCollectionDataSource(tblParticipation.getItems()); HashMap map = new HashMap(); map.put("StudentID", selectedStudent.getSID()); map.put("StudentName", selectedStudent.getSName()); map.put("Competition", competition); JasperPrint jasperPrint = JasperFillManager.fillReport(competitionReport, map, new JREmptyDataSource()); Reporter.showReport(jasperPrint, "Competition for student"); } catch (Exception e) { callLogger(e); } } else { OptionPane.showErrorAtSide("Please select a student to print."); } } @FXML void cboxActivity_onAction(ActionEvent event) { } @FXML void cboxCompetition_onAction(ActionEvent event) { } public VBox getCompetitionForStudent_controller() { return competitionForStudent; } public void setCompetitionForStudent_controller(VBox competitionForStudent_controller) { this.competitionForStudent = competitionForStudent_controller; } public void init(StudentProfileController studentProfileController) { this.studentProfileController = studentProfileController; } protected void insertStudent(StudentDTO student) { try { selectedStudent = student; ObservableList<ParticipationDTO> achievement = participationBOImpl.getCompetitionAndAchievementOfThisStudent(student.getSID()); tblParticipation.getItems().setAll(achievement); Common.clearSortOrder(tblParticipation); } catch (Exception e) { callLogger(e); } } }
4,993
0.726617
0.726617
139
34.920864
32.705368
156
false
false
0
0
0
0
64
0.012818
0.57554
false
false
4
23dd8a26c36c7b8da863aa5666ebc185dedce301
13,065,290,577,581
00561c2363dd99192753b7cd955fc8acc6875fe3
/src/main/java/org/java/homework/Task_37/Deserialization.java
86cadaf9ce47667d87daa494f4c7010c21f30264
[]
no_license
DaryaIvasyuk253/maventest
https://github.com/DaryaIvasyuk253/maventest
5e7ff98fa56944f38d7a9ef77272c4d11b6583aa
2638ab46c674380bb32cf4bcc505c76352acdb55
refs/heads/master
2020-03-13T09:19:41.578000
2018-06-05T18:49:02
2018-06-05T18:49:02
131,061,938
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.java.homework.Task_37; import org.java.homework.Task_34.Employee; import org.java.homework.Task_34.Gender; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.*; public class Deserialization { public static void main(String[] args) { String path = "C:\\Users\\Asus\\IdeaProjects\\maventest\\src\\main\\resources\\input.csv"; createEmployees(path).stream().forEach(System.out::println); } public static List<Employee> createEmployees(String path) { List<String> readText = new ArrayList<>(); List<Employee> employees = new LinkedList<>(); String[] line; try (BufferedReader bufferedReader = new BufferedReader(new FileReader(path))) { String currentLine; while ((currentLine = bufferedReader.readLine()) != null){ line = currentLine.split(","); readText.addAll(Arrays.asList(line)); Employee newEmployee = new Employee(readText.get(0), Long.parseLong(readText.get(1)), Integer.parseInt(readText.get(2)), Gender.valueOf(readText.get(3)), Boolean.parseBoolean(readText.get(4))); employees.add(newEmployee); readText.clear(); } } catch (IOException e) { e.printStackTrace(); employees = Collections.emptyList(); } return employees; } }
UTF-8
Java
1,452
java
Deserialization.java
Java
[ { "context": "ing[] args) {\n String path = \"C:\\\\Users\\\\Asus\\\\IdeaProjects\\\\maventest\\\\src\\\\main\\\\resources\\\\i", "end": 342, "score": 0.8096866011619568, "start": 340, "tag": "NAME", "value": "us" } ]
null
[]
package org.java.homework.Task_37; import org.java.homework.Task_34.Employee; import org.java.homework.Task_34.Gender; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.*; public class Deserialization { public static void main(String[] args) { String path = "C:\\Users\\Asus\\IdeaProjects\\maventest\\src\\main\\resources\\input.csv"; createEmployees(path).stream().forEach(System.out::println); } public static List<Employee> createEmployees(String path) { List<String> readText = new ArrayList<>(); List<Employee> employees = new LinkedList<>(); String[] line; try (BufferedReader bufferedReader = new BufferedReader(new FileReader(path))) { String currentLine; while ((currentLine = bufferedReader.readLine()) != null){ line = currentLine.split(","); readText.addAll(Arrays.asList(line)); Employee newEmployee = new Employee(readText.get(0), Long.parseLong(readText.get(1)), Integer.parseInt(readText.get(2)), Gender.valueOf(readText.get(3)), Boolean.parseBoolean(readText.get(4))); employees.add(newEmployee); readText.clear(); } } catch (IOException e) { e.printStackTrace(); employees = Collections.emptyList(); } return employees; } }
1,452
0.626722
0.619146
37
38.243244
30.422613
131
false
false
0
0
0
0
0
0
0.702703
false
false
4
99a9db3afac28ad1e24d835d95d77ac63f990668
11,974,368,833,325
f6d2e2d93a8a8993ecfbf424f13f86d6cf8ed2ec
/ocs_admin/src/main/java/com/rong/admin/controller/BaseController.java
7cf737ed51b9031c893cdcbffe2e2097c7fca2c9
[]
no_license
moutainhigh/ocs
https://github.com/moutainhigh/ocs
a5671a80338ed50f890b8b40235b39a8ffa1e877
c7567c33615aa1b83ac2a5da34cc530913bdce39
refs/heads/master
2021-10-27T05:39:44.669000
2019-04-16T10:18:16
2019-04-16T10:18:16
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * 后台控制器基类 */ package com.rong.admin.controller; import java.lang.reflect.Field; import com.jfinal.core.Controller; import com.rong.common.bean.MyConst; import com.rong.persist.model.SystemAdmin; public class BaseController extends Controller { public static int pageSize = 10; public Field serviceField = null; public Field getService() { if (serviceField != null) { return serviceField; } Field[] fields = this.getClass().getDeclaredFields(); for (Field field : fields) { if ("service".equals(field.getName())) { serviceField = field; serviceField.setAccessible(true); break; } } return serviceField; } public String path() { String name = this.getClass().getSimpleName(); name = name.substring(0, name.indexOf("Controller")); name = Character.toLowerCase(name.charAt(0)) + name.substring(1); return "/views/" + name; } public SystemAdmin getUser(){ SystemAdmin u = (SystemAdmin) getSessionAttr(MyConst.SESSION_KEY); return u; } public boolean isAdmin(){ SystemAdmin u = (SystemAdmin) getSessionAttr(MyConst.SESSION_KEY); if(u.getRole().equals("admin")){ return true; } return false; } }
UTF-8
Java
1,236
java
BaseController.java
Java
[]
null
[]
/** * 后台控制器基类 */ package com.rong.admin.controller; import java.lang.reflect.Field; import com.jfinal.core.Controller; import com.rong.common.bean.MyConst; import com.rong.persist.model.SystemAdmin; public class BaseController extends Controller { public static int pageSize = 10; public Field serviceField = null; public Field getService() { if (serviceField != null) { return serviceField; } Field[] fields = this.getClass().getDeclaredFields(); for (Field field : fields) { if ("service".equals(field.getName())) { serviceField = field; serviceField.setAccessible(true); break; } } return serviceField; } public String path() { String name = this.getClass().getSimpleName(); name = name.substring(0, name.indexOf("Controller")); name = Character.toLowerCase(name.charAt(0)) + name.substring(1); return "/views/" + name; } public SystemAdmin getUser(){ SystemAdmin u = (SystemAdmin) getSessionAttr(MyConst.SESSION_KEY); return u; } public boolean isAdmin(){ SystemAdmin u = (SystemAdmin) getSessionAttr(MyConst.SESSION_KEY); if(u.getRole().equals("admin")){ return true; } return false; } }
1,236
0.669394
0.665303
50
22.440001
19.983152
68
false
false
0
0
0
0
0
0
1.86
false
false
4
682df0973847d4824e4b16a195d483f893345481
19,593,640,873,380
e07a1429abe596c5334effa422779da077735819
/src/main/java/com/infernalwhaler/testproject/exceptions/CustomExceptionHandler.java
250d45e83e2d329cf61992beaff4e647d96eb942
[]
no_license
ExileNoir/testProjectSpring
https://github.com/ExileNoir/testProjectSpring
93a1a8cc290d333175169964d3ed7b6ac08a3760
74aad280bc402d15ea170cd2e14c775579866a21
refs/heads/main
2023-08-17T02:09:57.218000
2021-10-05T09:41:33
2021-10-05T09:41:33
399,141,177
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.infernalwhaler.testproject.exceptions; import org.springframework.context.support.DefaultMessageSourceResolvable; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; import java.time.LocalDateTime; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import static org.springframework.http.HttpStatus.BAD_REQUEST; import static org.springframework.http.HttpStatus.NOT_FOUND; /** * Custom Exception Handler * * @author sDeseure * @project TestProject * @date 22/08/2021 */ @ControllerAdvice public class CustomExceptionHandler extends ResponseEntityExceptionHandler { @Override @ResponseStatus(BAD_REQUEST) public ResponseEntity<Object> handleMethodArgumentNotValid(final MethodArgumentNotValidException ex, final HttpHeaders httpHeaders, final HttpStatus httpStatus, WebRequest request) { final CustomErrorResponse errorResponse = new CustomErrorResponse(); errorResponse.setStatusCode(httpStatus.value()); errorResponse.setTimestamp(LocalDateTime.now()); errorResponse.setMessage(ex.getMessage()); errorResponse.setDescription(request.getDescription(false)); final List<String> errorMessages = ex .getBindingResult() .getFieldErrors() .stream() .map(DefaultMessageSourceResolvable::getDefaultMessage) .collect(Collectors.toList()); final Map<String, Object> body = new LinkedHashMap<>(); body.put("Timestamp", errorResponse.getTimestamp()); body.put("status", errorResponse.getStatusCode()); body.put("errors", errorMessages); return new ResponseEntity<>(body, BAD_REQUEST); } @ExceptionHandler(AccountNotFoundException.class) public ResponseEntity<CustomErrorResponse> accountNotFoundException(final AccountNotFoundException ex, final WebRequest request) { final CustomErrorResponse errorResponse = new CustomErrorResponse(); errorResponse.setStatusCode(NOT_FOUND.value()); errorResponse.setTimestamp(LocalDateTime.now()); errorResponse.setMessage(ex.getMessage()); errorResponse.setDescription(request.getDescription(false)); return new ResponseEntity<>(errorResponse, NOT_FOUND); } @ExceptionHandler(BadCredentialsException.class) public ResponseEntity<CustomErrorResponse> badCredentialException(final BadCredentialsException ex, final WebRequest request) { final CustomErrorResponse errorResponse = new CustomErrorResponse(); errorResponse.setStatusCode(BAD_REQUEST.value()); errorResponse.setTimestamp(LocalDateTime.now()); errorResponse.setMessage(ex.getMessage()); errorResponse.setDescription(request.getDescription(false)); return new ResponseEntity<>(errorResponse, BAD_REQUEST); } }
UTF-8
Java
3,468
java
CustomExceptionHandler.java
Java
[ { "context": "ND;\n\n/**\n * Custom Exception Handler\n *\n * @author sDeseure\n * @project TestProject\n * @date 22/08/2021\n */\n\n", "end": 1080, "score": 0.9997241497039795, "start": 1072, "tag": "USERNAME", "value": "sDeseure" } ]
null
[]
package com.infernalwhaler.testproject.exceptions; import org.springframework.context.support.DefaultMessageSourceResolvable; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; import java.time.LocalDateTime; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import static org.springframework.http.HttpStatus.BAD_REQUEST; import static org.springframework.http.HttpStatus.NOT_FOUND; /** * Custom Exception Handler * * @author sDeseure * @project TestProject * @date 22/08/2021 */ @ControllerAdvice public class CustomExceptionHandler extends ResponseEntityExceptionHandler { @Override @ResponseStatus(BAD_REQUEST) public ResponseEntity<Object> handleMethodArgumentNotValid(final MethodArgumentNotValidException ex, final HttpHeaders httpHeaders, final HttpStatus httpStatus, WebRequest request) { final CustomErrorResponse errorResponse = new CustomErrorResponse(); errorResponse.setStatusCode(httpStatus.value()); errorResponse.setTimestamp(LocalDateTime.now()); errorResponse.setMessage(ex.getMessage()); errorResponse.setDescription(request.getDescription(false)); final List<String> errorMessages = ex .getBindingResult() .getFieldErrors() .stream() .map(DefaultMessageSourceResolvable::getDefaultMessage) .collect(Collectors.toList()); final Map<String, Object> body = new LinkedHashMap<>(); body.put("Timestamp", errorResponse.getTimestamp()); body.put("status", errorResponse.getStatusCode()); body.put("errors", errorMessages); return new ResponseEntity<>(body, BAD_REQUEST); } @ExceptionHandler(AccountNotFoundException.class) public ResponseEntity<CustomErrorResponse> accountNotFoundException(final AccountNotFoundException ex, final WebRequest request) { final CustomErrorResponse errorResponse = new CustomErrorResponse(); errorResponse.setStatusCode(NOT_FOUND.value()); errorResponse.setTimestamp(LocalDateTime.now()); errorResponse.setMessage(ex.getMessage()); errorResponse.setDescription(request.getDescription(false)); return new ResponseEntity<>(errorResponse, NOT_FOUND); } @ExceptionHandler(BadCredentialsException.class) public ResponseEntity<CustomErrorResponse> badCredentialException(final BadCredentialsException ex, final WebRequest request) { final CustomErrorResponse errorResponse = new CustomErrorResponse(); errorResponse.setStatusCode(BAD_REQUEST.value()); errorResponse.setTimestamp(LocalDateTime.now()); errorResponse.setMessage(ex.getMessage()); errorResponse.setDescription(request.getDescription(false)); return new ResponseEntity<>(errorResponse, BAD_REQUEST); } }
3,468
0.764418
0.762111
80
42.325001
34.305531
186
false
false
0
0
0
0
0
0
0.675
false
false
4
95bc70218269dd1918cae09a5991bb833d971bcb
3,470,333,626,058
5d5368161bb86a62eca2d1fe3a80e9cb81f5a16d
/src/beans/Photo.java
794a96c2d5bf9ed379c3b338c3a794b2a9258a09
[]
no_license
patricklatorre/WEBAPDE_MP
https://github.com/patricklatorre/WEBAPDE_MP
b23ad95039d87fe0ff6be91322bf154b83024183
4eeef0e089a43b4305636895310825ea52e4976d
refs/heads/master
2021-06-23T16:48:38.990000
2017-08-14T17:05:16
2017-08-14T17:05:16
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package beans; import java.io.Serializable; public class Photo implements Serializable { public static final String TABLE_NAME = "photos"; public static final String COLUMN_IDPHOTO = "idphoto"; public static final String COLUMN_PHOTO = "photo"; private int idphoto; private String photo; public Photo() { } public Photo(String photo) { this.photo = photo; } public String getIdphoto() { return photo; } public void setIdphoto(int idphoto) { this.idphoto = idphoto; } public String getPhoto() { return photo; } public void setPhoto(String photo) { this.photo = photo; } }
UTF-8
Java
619
java
Photo.java
Java
[]
null
[]
package beans; import java.io.Serializable; public class Photo implements Serializable { public static final String TABLE_NAME = "photos"; public static final String COLUMN_IDPHOTO = "idphoto"; public static final String COLUMN_PHOTO = "photo"; private int idphoto; private String photo; public Photo() { } public Photo(String photo) { this.photo = photo; } public String getIdphoto() { return photo; } public void setIdphoto(int idphoto) { this.idphoto = idphoto; } public String getPhoto() { return photo; } public void setPhoto(String photo) { this.photo = photo; } }
619
0.696284
0.696284
37
15.72973
16.700296
55
false
false
0
0
0
0
0
0
1.324324
false
false
4
7618d3f7df3f6fc577e06d432ea70b8399612570
4,372,276,766,003
4803f366e6f14b6f0979b04e8321783bf837ecce
/app/src/main/java/com/Phone/Recording/InOutCallRec/DeletingFileService.java
381d5bdfb6abe62b9d053aba7cce2ab4031648b1
[]
no_license
HeenaNautiyal/InOutCallRecording
https://github.com/HeenaNautiyal/InOutCallRecording
8b63e6434e37293781e3dfca5e95fccf22d02f70
12bfade53194c08b7f3c21b12841a48be06d7250
refs/heads/master
2020-03-22T15:37:11.480000
2018-07-09T09:48:41
2018-07-09T09:48:41
140,264,638
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.Phone.Recording.InOutCallRec; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.Handler; import android.os.IBinder; import android.text.format.DateFormat; import android.util.Log; import android.widget.Toast; import java.io.File; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.Timer; import java.util.TimerTask; /** * Created by Caritas-Heena on 27-11-2017. */ public class DeletingFileService extends Service { private int Service_Delay_Minutes; Context ctx=this; /** indicates how to behave if the service is killed */ int KeepFiles = 500; /** interface for clients that bind */ IBinder mBinder; /** indicates whether onRebind should be used */ boolean mAllowRebind; GenClass g = new GenClass(ctx); /** Called when the service is being created. */ @Override public void onCreate() { doToast(); } private void doToast() { final Handler handler= new Handler(); handler.postDelayed(new Runnable(){ @Override public void run() { Service_Delay_Minutes=60000 * 10000; // TODO Auto-generated method stub DeleteFiles(); handler.postDelayed(this, Service_Delay_Minutes); } }, 1000); } private Boolean DeleteFiles() { String ArrFileNameAndDate[][]; String ArrSortedFileName[]; long LastModified = 0; Boolean isDone = false; int Counter = 0; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //Date Modified_1 , Modified_2; long Modified_1 , Modified_2; int GreaterIndex = 0; try { File AudioDir = new File(GlobalVariables.GetAudioSavingPath()); File[] files = AudioDir.listFiles(); //region VALIDATION if (files == null) { return null; } if (files.length == 0) { return null; } //endregion g.DeleteSmallSizeFiles(); ArrFileNameAndDate = new String[files.length][2]; ArrSortedFileName = new String[files.length]; //region READING ALL FILE NAME FROM DIRECTORY INTO ARRAY & DELETING THOSE FILES WHICH ARE LESS THEN 100 KB for (File f : AudioDir.listFiles()) { if (f.isFile()) { LastModified = f.lastModified(); ArrFileNameAndDate[Counter][0] = f.getName(); ArrFileNameAndDate[Counter][1] = LastModified + ""; ArrSortedFileName[Counter] = ArrFileNameAndDate[Counter][0]; Counter = Counter + 1; } } //endregion //region SORTING ARRAY BY DATE Ascending Order A-Z int LastIndex; for(int i=0;i<ArrFileNameAndDate.length;i++){ LastIndex=-1; Modified_1 = Long.parseLong(ArrFileNameAndDate[i][1]); //ArrSortedFileName[i] = ArrFileNameAndDate[i][0]; for(int j=i+1;j<ArrFileNameAndDate.length;j++) { if (ArrFileNameAndDate[j][0].trim().length() > 0) { Modified_2 = Long.parseLong(ArrFileNameAndDate[j][1]); if (Modified_2<Modified_1) { ArrSortedFileName[i] = ArrFileNameAndDate[j][0]; LastIndex = j; } } } if(LastIndex!=-1) ArrFileNameAndDate[LastIndex][0] = ""; } //endregion //region DELETING FILES for (File f : AudioDir.listFiles()) { if (f.isFile()) { for(int i=0;i<(ArrSortedFileName.length-KeepFiles); i++){ if(ArrSortedFileName[i].equals(f.getName())){ ArrSortedFileName[i] = ArrSortedFileName[i]; f.delete(); } } } } //endregion } catch (Exception e) { Log.e("DeleteFiles()", e.toString()); } finally { return isDone; } } /** The service is starting, due to a call to startService() */ @Override public int onStartCommand(Intent intent, int flags, int startId) { // Let it continue running until it is stopped. return START_STICKY; } /** A client is binding to the service with bindService() */ @Override public IBinder onBind(Intent intent) { return null; } /** Called when The service is no longer used and is being destroyed */ @Override public void onDestroy() { super.onDestroy(); Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show(); } }
UTF-8
Java
5,045
java
DeletingFileService.java
Java
[ { "context": "er;\nimport java.util.TimerTask;\n\n/**\n * Created by Caritas-Heena on 27-11-2017.\n */\n\npublic class DeletingFileServ", "end": 470, "score": 0.9995903968811035, "start": 457, "tag": "NAME", "value": "Caritas-Heena" } ]
null
[]
package com.Phone.Recording.InOutCallRec; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.Handler; import android.os.IBinder; import android.text.format.DateFormat; import android.util.Log; import android.widget.Toast; import java.io.File; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.Timer; import java.util.TimerTask; /** * Created by Caritas-Heena on 27-11-2017. */ public class DeletingFileService extends Service { private int Service_Delay_Minutes; Context ctx=this; /** indicates how to behave if the service is killed */ int KeepFiles = 500; /** interface for clients that bind */ IBinder mBinder; /** indicates whether onRebind should be used */ boolean mAllowRebind; GenClass g = new GenClass(ctx); /** Called when the service is being created. */ @Override public void onCreate() { doToast(); } private void doToast() { final Handler handler= new Handler(); handler.postDelayed(new Runnable(){ @Override public void run() { Service_Delay_Minutes=60000 * 10000; // TODO Auto-generated method stub DeleteFiles(); handler.postDelayed(this, Service_Delay_Minutes); } }, 1000); } private Boolean DeleteFiles() { String ArrFileNameAndDate[][]; String ArrSortedFileName[]; long LastModified = 0; Boolean isDone = false; int Counter = 0; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //Date Modified_1 , Modified_2; long Modified_1 , Modified_2; int GreaterIndex = 0; try { File AudioDir = new File(GlobalVariables.GetAudioSavingPath()); File[] files = AudioDir.listFiles(); //region VALIDATION if (files == null) { return null; } if (files.length == 0) { return null; } //endregion g.DeleteSmallSizeFiles(); ArrFileNameAndDate = new String[files.length][2]; ArrSortedFileName = new String[files.length]; //region READING ALL FILE NAME FROM DIRECTORY INTO ARRAY & DELETING THOSE FILES WHICH ARE LESS THEN 100 KB for (File f : AudioDir.listFiles()) { if (f.isFile()) { LastModified = f.lastModified(); ArrFileNameAndDate[Counter][0] = f.getName(); ArrFileNameAndDate[Counter][1] = LastModified + ""; ArrSortedFileName[Counter] = ArrFileNameAndDate[Counter][0]; Counter = Counter + 1; } } //endregion //region SORTING ARRAY BY DATE Ascending Order A-Z int LastIndex; for(int i=0;i<ArrFileNameAndDate.length;i++){ LastIndex=-1; Modified_1 = Long.parseLong(ArrFileNameAndDate[i][1]); //ArrSortedFileName[i] = ArrFileNameAndDate[i][0]; for(int j=i+1;j<ArrFileNameAndDate.length;j++) { if (ArrFileNameAndDate[j][0].trim().length() > 0) { Modified_2 = Long.parseLong(ArrFileNameAndDate[j][1]); if (Modified_2<Modified_1) { ArrSortedFileName[i] = ArrFileNameAndDate[j][0]; LastIndex = j; } } } if(LastIndex!=-1) ArrFileNameAndDate[LastIndex][0] = ""; } //endregion //region DELETING FILES for (File f : AudioDir.listFiles()) { if (f.isFile()) { for(int i=0;i<(ArrSortedFileName.length-KeepFiles); i++){ if(ArrSortedFileName[i].equals(f.getName())){ ArrSortedFileName[i] = ArrSortedFileName[i]; f.delete(); } } } } //endregion } catch (Exception e) { Log.e("DeleteFiles()", e.toString()); } finally { return isDone; } } /** The service is starting, due to a call to startService() */ @Override public int onStartCommand(Intent intent, int flags, int startId) { // Let it continue running until it is stopped. return START_STICKY; } /** A client is binding to the service with bindService() */ @Override public IBinder onBind(Intent intent) { return null; } /** Called when The service is no longer used and is being destroyed */ @Override public void onDestroy() { super.onDestroy(); Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show(); } }
5,045
0.541725
0.530426
169
28.852072
24.127043
118
false
false
0
0
0
0
0
0
0.473373
false
false
4
7ab39a64309492e78826e7627c78d021666d3ab2
35,158,602,297,031
e44ef18836519918f763e5715b293bf89349929f
/algs4-II/1/test/SAPTest.java
209fa61786ac471ec87046d2cc094db6d4f5989e
[]
no_license
Asalle/coursera
https://github.com/Asalle/coursera
10938c4d859576ad560b604b15404b78e0933f74
bd6c85684d111776223e93b125a36d6c907405d6
refs/heads/master
2021-08-17T15:50:13.555000
2017-11-21T10:33:06
2017-11-21T10:33:06
107,301,073
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import org.testng.annotations.Test; import static org.testng.Assert.*; /** * Created by mirzaiev on 21.11.2017. */ public class SAPTest { @Test public void testLength() throws Exception { } @Test public void testAncestor() throws Exception { } @Test public void testLength1() throws Exception { } @Test public void testAncestor1() throws Exception { } }
UTF-8
Java
409
java
SAPTest.java
Java
[ { "context": "ort static org.testng.Assert.*;\n\n/**\n * Created by mirzaiev on 21.11.2017.\n */\npublic class SAPTest {\n @Te", "end": 99, "score": 0.999476969242096, "start": 91, "tag": "USERNAME", "value": "mirzaiev" } ]
null
[]
import org.testng.annotations.Test; import static org.testng.Assert.*; /** * Created by mirzaiev on 21.11.2017. */ public class SAPTest { @Test public void testLength() throws Exception { } @Test public void testAncestor() throws Exception { } @Test public void testLength1() throws Exception { } @Test public void testAncestor1() throws Exception { } }
409
0.645477
0.621027
25
15.4
18.068758
50
false
false
0
0
0
0
0
0
0.08
false
false
4
f1cd66f1cc9156eeb6863a584db97a4bc03fdd8f
20,555,713,518,393
08bd28dab9a12044c901356d6bed1da8145653b9
/app/src/main/java/com/idhub/wallet/didhub/util/BIP44Util.java
a3147c397a3ba27f3b8e9fc9553b4593a1cefadc
[ "MIT" ]
permissive
idhub-did-plus/did-wallet-android
https://github.com/idhub-did-plus/did-wallet-android
45f1943c8f4d8fd0aebe15720c73ac1833e08113
34f2b5ea712ed46da176167a646cbddf580e63f6
refs/heads/master
2020-07-01T12:59:33.768000
2020-01-02T06:21:22
2020-01-02T06:21:22
201,180,587
3
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.idhub.wallet.didhub.util; import com.google.common.collect.ImmutableList; import org.bitcoinj.crypto.ChildNumber; import java.util.ArrayList; import java.util.List; public class BIP44Util { public final static String BITCOIN_MAINNET_PATH = "m/44'/0'/0'"; public final static String BITCOIN_TESTNET_PATH = "m/44'/1'/0'"; public final static String BITCOIN_SEGWIT_MAIN_PATH = "m/49'/0'/0'"; public final static String BITCOIN_SEGWIT_TESTNET_PATH = "m/49'/1'/0'"; public final static String ETHEREUM_PATH = "m/44'/60'/0'/0/0"; public final static String EOS_PATH = "m/44'/194'"; public final static String EOS_SLIP48 = "m/48'/4'/0'/0'/0',m/48'/4'/1'/0'/0'"; public final static String EOS_LEDGER = "m/44'/194'/0'/0/0"; public static ImmutableList<ChildNumber> generatePath(String path) { List<ChildNumber> list = new ArrayList<>(); for (String p : path.split("/")) { if ("m".equalsIgnoreCase(p) || "".equals(p.trim())) { continue; } else if (p.charAt(p.length() - 1) == '\'') { list.add(new ChildNumber(Integer.parseInt(p.substring(0, p.length() - 1)), true)); } else { list.add(new ChildNumber(Integer.parseInt(p), false)); } } ImmutableList.Builder<ChildNumber> builder = ImmutableList.builder(); return builder.addAll(list).build(); } // public static String getBTCMnemonicPath(String segWit, boolean isMainnet) { // if (Metadata.P2WPKH.equalsIgnoreCase(segWit)) { // return isMainnet ? BITCOIN_SEGWIT_MAIN_PATH : BITCOIN_SEGWIT_TESTNET_PATH; // } else { // return isMainnet ? BITCOIN_MAINNET_PATH : BITCOIN_TESTNET_PATH; // } // } }
UTF-8
Java
1,664
java
BIP44Util.java
Java
[]
null
[]
package com.idhub.wallet.didhub.util; import com.google.common.collect.ImmutableList; import org.bitcoinj.crypto.ChildNumber; import java.util.ArrayList; import java.util.List; public class BIP44Util { public final static String BITCOIN_MAINNET_PATH = "m/44'/0'/0'"; public final static String BITCOIN_TESTNET_PATH = "m/44'/1'/0'"; public final static String BITCOIN_SEGWIT_MAIN_PATH = "m/49'/0'/0'"; public final static String BITCOIN_SEGWIT_TESTNET_PATH = "m/49'/1'/0'"; public final static String ETHEREUM_PATH = "m/44'/60'/0'/0/0"; public final static String EOS_PATH = "m/44'/194'"; public final static String EOS_SLIP48 = "m/48'/4'/0'/0'/0',m/48'/4'/1'/0'/0'"; public final static String EOS_LEDGER = "m/44'/194'/0'/0/0"; public static ImmutableList<ChildNumber> generatePath(String path) { List<ChildNumber> list = new ArrayList<>(); for (String p : path.split("/")) { if ("m".equalsIgnoreCase(p) || "".equals(p.trim())) { continue; } else if (p.charAt(p.length() - 1) == '\'') { list.add(new ChildNumber(Integer.parseInt(p.substring(0, p.length() - 1)), true)); } else { list.add(new ChildNumber(Integer.parseInt(p), false)); } } ImmutableList.Builder<ChildNumber> builder = ImmutableList.builder(); return builder.addAll(list).build(); } // public static String getBTCMnemonicPath(String segWit, boolean isMainnet) { // if (Metadata.P2WPKH.equalsIgnoreCase(segWit)) { // return isMainnet ? BITCOIN_SEGWIT_MAIN_PATH : BITCOIN_SEGWIT_TESTNET_PATH; // } else { // return isMainnet ? BITCOIN_MAINNET_PATH : BITCOIN_TESTNET_PATH; // } // } }
1,664
0.66226
0.628606
45
35.977779
29.812368
90
false
false
0
0
0
0
0
0
0.622222
false
false
4
fbb485c76f3f2e77b16faa1826af52727aab47fb
29,703,993,860,828
6297b6da268278fc98444e45cd65991a7dffbaf6
/publicsdk/src/main/java/zj/neverland/publicsdk/widget/easypicker/PickerViewManager.java
361feaab49ac784b4dbc2444439180bb3f64dded
[ "Apache-2.0" ]
permissive
hopjojo/PublicWidget
https://github.com/hopjojo/PublicWidget
4a20f238ec301c3eb38a3db9b12ad1ef5e6656d2
e8f70dbd8cc36d7e367a5b24ba6b6bb089ccf2f3
refs/heads/master
2020-12-02T19:47:57.224000
2017-07-12T07:58:00
2017-07-12T07:58:00
96,376,588
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package zj.neverland.publicsdk.widget.easypicker; import android.app.Activity; import android.content.Context; import android.content.res.AssetManager; import android.graphics.Color; import android.view.View; import com.bigkoo.pickerview.OptionsPickerView; import com.bigkoo.pickerview.TimePickerView; import com.google.gson.Gson; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import zj.neverland.publicsdk.utils.DateUtil; import zj.neverland.publicsdk.utils.KeyBoardUtils; import zj.neverland.publicsdk.widget.easypicker.bean.JsonBean; /** * Created by cefoc on 2017/5/3. * Class Note: */ public class PickerViewManager { private ArrayList<JsonBean> options1Items = new ArrayList<>(); private ArrayList<ArrayList<String>> options2Items = new ArrayList<>(); private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>(); private Context context; public PickerViewManager(Context context) { this.context = context; } //时间选择 public TimePickerView CustomTimePicker(TimePickerView.Type type, String selectdTime, final PickerCallBack.TimePickerCallBack timePickerCallBack) { Calendar selectedDate = Calendar.getInstance(); if (selectdTime != null && !selectdTime.isEmpty()) { String formatType; switch (type) { case ALL: formatType = "yyyy-MM-dd HH:mm:ss"; break; case YEAR_MONTH_DAY: formatType = "yyyy-MM-dd"; break; case HOURS_MINS: formatType = "HH:mm"; break; case MONTH_DAY_HOUR_MIN: formatType = "MM-dd HH:mm"; break; case YEAR_MONTH: formatType = "yyyy-MM"; break; case YEAR_MONTH_DAY_HOUR_MIN: formatType = "yyyy-MM-dd HH:mm"; break; default: formatType = "yyyy-MM-dd HH:mm:ss"; break; } selectedDate.setTime(DateUtil.stringToDate(selectdTime, formatType)); } Calendar startDate = Calendar.getInstance(); startDate.set(2000, 0, 1); // Calendar endDate = Calendar.getInstance(); // endDate.set(2021, 12, 30); //关闭软键盘 KeyBoardUtils keyBoard = new KeyBoardUtils((Activity)context); keyBoard.closeKeybord(); //时间选择器 TimePickerView pvTime = new TimePickerView.Builder(context, new TimePickerView.OnTimeSelectListener() { @Override public void onTimeSelect(Date date, View v) {//选中事件回调 timePickerCallBack.callback(date, v); } }) .setType(type) .setLabel("年", "月", "日", "时", "分", "秒") //设置空字符串以隐藏单位提示 hide label .setTitleText("请选择日期") .setDividerColor(Color.DKGRAY) .setContentSize(20) .setDate(selectedDate) .setRangDate(startDate, null) .isCenterLabel(false) .build(); return pvTime; } //城市地点选择 public void CityOptionsPicker(final PickerCallBack.CityOptionsPickerCallBack cityoptions) { initJsonData(); OptionsPickerView pvOptions = new OptionsPickerView.Builder(context, new OptionsPickerView.OnOptionsSelectListener() { @Override public void onOptionsSelect(int options1, int options2, int options3, View v) { cityoptions.callback(options1Items.get(options1).getPickerViewText(),options2Items.get(options1).get(options2),options3Items.get(options1).get(options2).get(options3),v); } }) .setTitleText("请选择") .setDividerColor(Color.BLACK) .setTextColorCenter(Color.BLACK) //设置选中项文字颜色 .setContentTextSize(20) .setOutSideCancelable(false)// default is true .build(); /*pvOptions.setPicker(options1Items);//一级选择器 pvOptions.setPicker(options1Items, options2Items);//二级选择器*/ pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器 pvOptions.show(); } private void initJsonData() {//解析数据 /** * 注意:assets 目录下的Json文件仅供参考,实际使用可自行替换文件 * 关键逻辑在于循环体 * * */ StringBuilder stringBuilder = new StringBuilder(); try { AssetManager assetManager = context.getAssets(); BufferedReader bf = new BufferedReader(new InputStreamReader( assetManager.open("province.json"))); String line; while ((line = bf.readLine()) != null) { stringBuilder.append(line); } } catch (IOException e) { e.printStackTrace(); } String JsonData = stringBuilder.toString();//获取assets目录下的json文件数据 ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体 /** * 添加省份数据 * * 注意:如果是添加的JavaBean实体,则实体类需要实现 IPickerViewData 接口, * PickerView会通过getPickerViewText方法获取字符串显示出来。 */ options1Items = jsonBean; for (int i=0;i<jsonBean.size();i++){//遍历省份 ArrayList<String> CityList = new ArrayList<>();//该省的城市列表(第二级) ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表(第三极) for (int c=0; c<jsonBean.get(i).getCityList().size(); c++){//遍历该省份的所有城市 String CityName = jsonBean.get(i).getCityList().get(c).getName(); CityList.add(CityName);//添加城市 ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表 //如果无地区数据,建议添加空字符串,防止数据为null 导致三个选项长度不匹配造成崩溃 if (jsonBean.get(i).getCityList().get(c).getArea() == null ||jsonBean.get(i).getCityList().get(c).getArea().size()==0) { City_AreaList.add(""); }else { for (int d=0; d < jsonBean.get(i).getCityList().get(c).getArea().size(); d++) {//该城市对应地区所有数据 String AreaName = jsonBean.get(i).getCityList().get(c).getArea().get(d); City_AreaList.add(AreaName);//添加该城市所有地区数据 } } Province_AreaList.add(City_AreaList);//添加该省所有地区数据 } /** * 添加城市数据 */ options2Items.add(CityList); /** * 添加地区数据 */ options3Items.add(Province_AreaList); } } public ArrayList<JsonBean> parseData(String result) { ArrayList<JsonBean> detail = new ArrayList<>(); try { org.json.JSONArray data = new org.json.JSONArray(result); Gson gson = new Gson(); for (int i = 0; i < data.length(); i++) { JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class); detail.add(entity); } } catch (Exception e) { e.printStackTrace(); } return detail; } }
UTF-8
Java
7,980
java
PickerViewManager.java
Java
[ { "context": "dget.easypicker.bean.JsonBean;\n\n\n/**\n * Created by cefoc on 2017/5/3.\n * Class Note:\n */\n\npublic class Pic", "end": 691, "score": 0.9997003078460693, "start": 686, "tag": "USERNAME", "value": "cefoc" } ]
null
[]
package zj.neverland.publicsdk.widget.easypicker; import android.app.Activity; import android.content.Context; import android.content.res.AssetManager; import android.graphics.Color; import android.view.View; import com.bigkoo.pickerview.OptionsPickerView; import com.bigkoo.pickerview.TimePickerView; import com.google.gson.Gson; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import zj.neverland.publicsdk.utils.DateUtil; import zj.neverland.publicsdk.utils.KeyBoardUtils; import zj.neverland.publicsdk.widget.easypicker.bean.JsonBean; /** * Created by cefoc on 2017/5/3. * Class Note: */ public class PickerViewManager { private ArrayList<JsonBean> options1Items = new ArrayList<>(); private ArrayList<ArrayList<String>> options2Items = new ArrayList<>(); private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>(); private Context context; public PickerViewManager(Context context) { this.context = context; } //时间选择 public TimePickerView CustomTimePicker(TimePickerView.Type type, String selectdTime, final PickerCallBack.TimePickerCallBack timePickerCallBack) { Calendar selectedDate = Calendar.getInstance(); if (selectdTime != null && !selectdTime.isEmpty()) { String formatType; switch (type) { case ALL: formatType = "yyyy-MM-dd HH:mm:ss"; break; case YEAR_MONTH_DAY: formatType = "yyyy-MM-dd"; break; case HOURS_MINS: formatType = "HH:mm"; break; case MONTH_DAY_HOUR_MIN: formatType = "MM-dd HH:mm"; break; case YEAR_MONTH: formatType = "yyyy-MM"; break; case YEAR_MONTH_DAY_HOUR_MIN: formatType = "yyyy-MM-dd HH:mm"; break; default: formatType = "yyyy-MM-dd HH:mm:ss"; break; } selectedDate.setTime(DateUtil.stringToDate(selectdTime, formatType)); } Calendar startDate = Calendar.getInstance(); startDate.set(2000, 0, 1); // Calendar endDate = Calendar.getInstance(); // endDate.set(2021, 12, 30); //关闭软键盘 KeyBoardUtils keyBoard = new KeyBoardUtils((Activity)context); keyBoard.closeKeybord(); //时间选择器 TimePickerView pvTime = new TimePickerView.Builder(context, new TimePickerView.OnTimeSelectListener() { @Override public void onTimeSelect(Date date, View v) {//选中事件回调 timePickerCallBack.callback(date, v); } }) .setType(type) .setLabel("年", "月", "日", "时", "分", "秒") //设置空字符串以隐藏单位提示 hide label .setTitleText("请选择日期") .setDividerColor(Color.DKGRAY) .setContentSize(20) .setDate(selectedDate) .setRangDate(startDate, null) .isCenterLabel(false) .build(); return pvTime; } //城市地点选择 public void CityOptionsPicker(final PickerCallBack.CityOptionsPickerCallBack cityoptions) { initJsonData(); OptionsPickerView pvOptions = new OptionsPickerView.Builder(context, new OptionsPickerView.OnOptionsSelectListener() { @Override public void onOptionsSelect(int options1, int options2, int options3, View v) { cityoptions.callback(options1Items.get(options1).getPickerViewText(),options2Items.get(options1).get(options2),options3Items.get(options1).get(options2).get(options3),v); } }) .setTitleText("请选择") .setDividerColor(Color.BLACK) .setTextColorCenter(Color.BLACK) //设置选中项文字颜色 .setContentTextSize(20) .setOutSideCancelable(false)// default is true .build(); /*pvOptions.setPicker(options1Items);//一级选择器 pvOptions.setPicker(options1Items, options2Items);//二级选择器*/ pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器 pvOptions.show(); } private void initJsonData() {//解析数据 /** * 注意:assets 目录下的Json文件仅供参考,实际使用可自行替换文件 * 关键逻辑在于循环体 * * */ StringBuilder stringBuilder = new StringBuilder(); try { AssetManager assetManager = context.getAssets(); BufferedReader bf = new BufferedReader(new InputStreamReader( assetManager.open("province.json"))); String line; while ((line = bf.readLine()) != null) { stringBuilder.append(line); } } catch (IOException e) { e.printStackTrace(); } String JsonData = stringBuilder.toString();//获取assets目录下的json文件数据 ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体 /** * 添加省份数据 * * 注意:如果是添加的JavaBean实体,则实体类需要实现 IPickerViewData 接口, * PickerView会通过getPickerViewText方法获取字符串显示出来。 */ options1Items = jsonBean; for (int i=0;i<jsonBean.size();i++){//遍历省份 ArrayList<String> CityList = new ArrayList<>();//该省的城市列表(第二级) ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表(第三极) for (int c=0; c<jsonBean.get(i).getCityList().size(); c++){//遍历该省份的所有城市 String CityName = jsonBean.get(i).getCityList().get(c).getName(); CityList.add(CityName);//添加城市 ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表 //如果无地区数据,建议添加空字符串,防止数据为null 导致三个选项长度不匹配造成崩溃 if (jsonBean.get(i).getCityList().get(c).getArea() == null ||jsonBean.get(i).getCityList().get(c).getArea().size()==0) { City_AreaList.add(""); }else { for (int d=0; d < jsonBean.get(i).getCityList().get(c).getArea().size(); d++) {//该城市对应地区所有数据 String AreaName = jsonBean.get(i).getCityList().get(c).getArea().get(d); City_AreaList.add(AreaName);//添加该城市所有地区数据 } } Province_AreaList.add(City_AreaList);//添加该省所有地区数据 } /** * 添加城市数据 */ options2Items.add(CityList); /** * 添加地区数据 */ options3Items.add(Province_AreaList); } } public ArrayList<JsonBean> parseData(String result) { ArrayList<JsonBean> detail = new ArrayList<>(); try { org.json.JSONArray data = new org.json.JSONArray(result); Gson gson = new Gson(); for (int i = 0; i < data.length(); i++) { JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class); detail.add(entity); } } catch (Exception e) { e.printStackTrace(); } return detail; } }
7,980
0.570633
0.563434
199
35.994976
29.786257
186
false
false
0
0
0
0
0
0
0.603015
false
false
4
c43a6b54205841015467f25f8b693fef7aa3c21d
3,813,931,027,339
ec380b5848d9709159b5341feba9ddac8f31a16a
/MobileSafe/src/com/example/mobilesafe/activity/AddressActivity.java
6ddf9b0f9655b67086e096982471fedd338fe6aa
[]
no_license
shenliang-me/MobileSafe
https://github.com/shenliang-me/MobileSafe
7623d3587859659e630b8fe39b2de16d9aab1385
07a60bf007cdae805b6adb41f5766bedf55c6cce
refs/heads/master
2021-01-10T03:46:56.567000
2016-03-06T13:16:25
2016-03-06T13:16:25
53,254,285
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.mobilesafe.activity; import com.example.mobilesafe.R; import com.example.mobilesafe.Utils.ToastUtils; import com.example.mobilesafe.db.dao.AddressDao; import android.app.Activity; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class AddressActivity extends Activity { private EditText etNumber; private Button btnStart; private TextView tvResult; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_address); etNumber = (EditText) findViewById(R.id.et_number); btnStart = (Button) findViewById(R.id.btn_start); tvResult = (TextView) findViewById(R.id.tv_result); btnStart.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String number = etNumber.getText().toString().trim(); if (!TextUtils.isEmpty(number)) { String address = (String) AddressDao.getAddress(number); tvResult.setText(address); }else { ToastUtils.showToast(getApplicationContext(), "输入内容不能为空"); } } }); } }
UTF-8
Java
1,337
java
AddressActivity.java
Java
[]
null
[]
package com.example.mobilesafe.activity; import com.example.mobilesafe.R; import com.example.mobilesafe.Utils.ToastUtils; import com.example.mobilesafe.db.dao.AddressDao; import android.app.Activity; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class AddressActivity extends Activity { private EditText etNumber; private Button btnStart; private TextView tvResult; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_address); etNumber = (EditText) findViewById(R.id.et_number); btnStart = (Button) findViewById(R.id.btn_start); tvResult = (TextView) findViewById(R.id.tv_result); btnStart.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String number = etNumber.getText().toString().trim(); if (!TextUtils.isEmpty(number)) { String address = (String) AddressDao.getAddress(number); tvResult.setText(address); }else { ToastUtils.showToast(getApplicationContext(), "输入内容不能为空"); } } }); } }
1,337
0.757759
0.757759
49
25.959183
20.070244
63
false
false
0
0
0
0
0
0
1.816326
false
false
4
8e76a0563c25cc73353a5044265184429e244e9e
36,000,415,884,806
8813b71328a3d647f56feb4210341b22ae59d5f8
/src/ch/unibnf/scg/jseuss/testing/JSeuss.java
35031e796220d7fb894ab2d76243c45155926acc
[]
no_license
nes1983/JSeuss
https://github.com/nes1983/JSeuss
723ee49480872a61868d18971eb5b861764cf17f
f1a3400da9f0ebfc5f25a6397133158d4ef08342
refs/heads/master
2021-01-15T21:44:15.669000
2011-05-30T16:19:38
2011-05-30T16:19:38
3,016,154
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ch.unibnf.scg.jseuss.testing; import javassist.CannotCompileException; import javassist.ClassPool; import javassist.Loader; import javassist.NotFoundException; import org.junit.runners.BlockJUnit4ClassRunner; import org.junit.runners.model.InitializationError; import ch.unibnf.scg.jseuss.core.javaassist.generic.JSeussTranslator; import ch.unibnf.scg.jseuss.utils.JSeussConfig; import ch.unibnf.scg.jseuss.utils.JSeussUtils; public class JSeuss extends BlockJUnit4ClassRunner { final String mainClass = "usecase.activerecord.ActiveRecordApp"; final String mocks = "usecase.activerecord.mocks."; public static JSeuss currentJseuss; static Loader cl = makeClassLoader(); { JSeussUtils.addToIgnoreList(mocks); } public JSeuss(Class<?> klass) throws InitializationError, ClassNotFoundException { super(cl.loadClass(addToIgnoreList(klass.getName()))); } private static String addToIgnoreList(String name) { JSeussUtils.addToIgnoreList(name); return name; } static Loader makeClassLoader() { JSeussTranslator t = new JSeussTranslator(); ClassPool pool = ClassPool.getDefault(); Loader cl = new Loader(ClassLoader.getSystemClassLoader(),pool); setIgnoreList(cl); try { cl.addTranslator(pool, t); } catch (NotFoundException e) { throw new RuntimeException(e); } catch (CannotCompileException e) { throw new RuntimeException(e); } return cl; } static void setIgnoreList(Loader cl) { for(String s : JSeussConfig.PACKAGE_IGNORE_LIST) cl.delegateLoadingOf(s); } }
UTF-8
Java
1,582
java
JSeuss.java
Java
[]
null
[]
package ch.unibnf.scg.jseuss.testing; import javassist.CannotCompileException; import javassist.ClassPool; import javassist.Loader; import javassist.NotFoundException; import org.junit.runners.BlockJUnit4ClassRunner; import org.junit.runners.model.InitializationError; import ch.unibnf.scg.jseuss.core.javaassist.generic.JSeussTranslator; import ch.unibnf.scg.jseuss.utils.JSeussConfig; import ch.unibnf.scg.jseuss.utils.JSeussUtils; public class JSeuss extends BlockJUnit4ClassRunner { final String mainClass = "usecase.activerecord.ActiveRecordApp"; final String mocks = "usecase.activerecord.mocks."; public static JSeuss currentJseuss; static Loader cl = makeClassLoader(); { JSeussUtils.addToIgnoreList(mocks); } public JSeuss(Class<?> klass) throws InitializationError, ClassNotFoundException { super(cl.loadClass(addToIgnoreList(klass.getName()))); } private static String addToIgnoreList(String name) { JSeussUtils.addToIgnoreList(name); return name; } static Loader makeClassLoader() { JSeussTranslator t = new JSeussTranslator(); ClassPool pool = ClassPool.getDefault(); Loader cl = new Loader(ClassLoader.getSystemClassLoader(),pool); setIgnoreList(cl); try { cl.addTranslator(pool, t); } catch (NotFoundException e) { throw new RuntimeException(e); } catch (CannotCompileException e) { throw new RuntimeException(e); } return cl; } static void setIgnoreList(Loader cl) { for(String s : JSeussConfig.PACKAGE_IGNORE_LIST) cl.delegateLoadingOf(s); } }
1,582
0.747788
0.746523
54
27.333334
22.633144
83
false
false
0
0
0
0
0
0
1.648148
false
false
4
6b60d791df058a68bde2718d07f49fdd4fe9f232
29,841,432,829,114
e94a822eef130dcfc7855aa05b3ce234cacbfa4b
/Car98-mvc/src/main/java/com/web/car98/forum/model/CommentAllBean.java
1ee888d5b8ef8dc516f534e743709d8f5f3d4a82
[]
no_license
ron7686/Car98-Mvc
https://github.com/ron7686/Car98-Mvc
52e32848d9e69fe2cf8a7f25c8b5d4e008c58d62
8343b06f523f941e74349d5efcf092f8de31ab9d
refs/heads/master
2023-01-02T00:53:33.365000
2020-10-19T01:55:27
2020-10-19T01:55:27
295,685,640
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.web.car98.forum.model; import java.io.Serializable; public class CommentAllBean implements Serializable { private String comText; private Integer comId; private Integer postID; public CommentAllBean() { super(); } public CommentAllBean(String comText, Integer comId, Integer postID) { super(); this.comText = comText; this.comId = comId; this.postID = postID; } public String getComText() { return comText; } public void setComText(String comText) { this.comText = comText; } public Integer getComId() { return comId; } public void setComId(Integer comId) { this.comId = comId; } public Integer getPostID() { return postID; } public void setPostID(Integer postID) { this.postID = postID; } }
UTF-8
Java
756
java
CommentAllBean.java
Java
[]
null
[]
package com.web.car98.forum.model; import java.io.Serializable; public class CommentAllBean implements Serializable { private String comText; private Integer comId; private Integer postID; public CommentAllBean() { super(); } public CommentAllBean(String comText, Integer comId, Integer postID) { super(); this.comText = comText; this.comId = comId; this.postID = postID; } public String getComText() { return comText; } public void setComText(String comText) { this.comText = comText; } public Integer getComId() { return comId; } public void setComId(Integer comId) { this.comId = comId; } public Integer getPostID() { return postID; } public void setPostID(Integer postID) { this.postID = postID; } }
756
0.71164
0.708995
41
17.439024
16.42878
71
false
false
0
0
0
0
0
0
1.536585
false
false
4
55bed7cabdae9fe6c5002bb1afb1c5f89290e851
12,781,822,709,575
1441daaef5377cdc8ab1a4a22d9b02586f7947a0
/Android/代码库/Keys_Android/app/src/main/java/com/ejoykeys/one/android/network/model/OrderServerVo.java
173f8088cc2c45fc1f8ad25c67835c6dfa2ab4fb
[]
no_license
chenzhenyu/Development_Rooster
https://github.com/chenzhenyu/Development_Rooster
ec4dc43ac16a9059c58665a93ed49fc88866aeba
09e249b5a869f05c1d3c9ae0d6ff108826ba379c
refs/heads/master
2018-11-02T14:26:53.377000
2018-09-28T06:26:08
2018-09-28T06:26:08
128,865,523
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ejoykeys.one.android.network.model; /** * 订单服务 * author:Rooster.Yu * date:2016/10/31. */ public class OrderServerVo { private int pic; private String category; private String explain; public OrderServerVo(int pic, String category, String explain) { this.pic = pic; this.category = category; this.explain = explain; } public int getPic() { return pic; } public void setPic(int pic) { this.pic = pic; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getExplain() { return explain; } public void setExplain(String explain) { this.explain = explain; } }
UTF-8
Java
851
java
OrderServerVo.java
Java
[ { "context": "android.network.model;\r\n\r\n/**\r\n * 订单服务\r\n * author:Rooster.Yu\r\n * date:2016/10/31.\r\n */\r\npublic class OrderServ", "end": 85, "score": 0.9994943737983704, "start": 75, "tag": "NAME", "value": "Rooster.Yu" } ]
null
[]
package com.ejoykeys.one.android.network.model; /** * 订单服务 * author:Rooster.Yu * date:2016/10/31. */ public class OrderServerVo { private int pic; private String category; private String explain; public OrderServerVo(int pic, String category, String explain) { this.pic = pic; this.category = category; this.explain = explain; } public int getPic() { return pic; } public void setPic(int pic) { this.pic = pic; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getExplain() { return explain; } public void setExplain(String explain) { this.explain = explain; } }
851
0.572954
0.563464
42
18.071428
16.417749
68
false
false
0
0
0
0
0
0
0.357143
false
false
4
86905a0c371d3d367cf2bc2354e6c269d12648c7
14,551,349,266,808
8b723c084e0c53d4acad31141c72d2fcce91a943
/Database/JDBC/Labs/JDBC/src/kr/or/bit/utils/ConnectionHelper.java
925a1bf633d6b8f28adf9c4fc89403a9bd491768
[]
no_license
green-in77/bit
https://github.com/green-in77/bit
56a5f4760993a2487d74b969e04b606afb908eff
0f8bda2901d1303bbd1778b5e8c56dc8ee16818d
refs/heads/master
2023-01-27T18:49:48.717000
2020-05-13T06:39:25
2020-05-13T06:39:25
210,523,587
0
1
null
false
2023-01-12T01:50:48
2019-09-24T06:01:38
2022-12-08T05:21:10
2023-01-12T01:50:48
239,926
1
0
187
CSS
false
false
package kr.or.bit.utils; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; /* Class.forName("oracle.jdbc.OracleDriver"); //메모리에 로드. >> new Driver //1. DB연결 conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","bituser","1004"); 1. 모든 CRUD 선행 작업 시 위 코드 필수 -> 반복적인 작업을 줄이자(드라이버 로딩, 연결객체, 명령...자원해제) 많이 쓰이는 작업 2. 다른 계정이나 다른 DB 연결 고민.. //5. DB 연결해제 try { stmt.close(); conn.close(); } catch (SQLException e) { e.printStackTrace(); } */ public class ConnectionHelper { //기능(연결....) >> 함수 >> 자주사용 static >> overloading >> interface //oracle, mysql 등 모두 연결할때 사용하기위해 public static Connection getConnection(String dsn) { Connection conn = null; try { if(dsn.equals("oracle")) { Class.forName("oracle.jdbc.OracleDriver"); conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","bituser","1004"); } else if (dsn.equals("mysql")) { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bitsqldb?useSSL=true","bituser","1004"); } }catch(Exception e) { System.out.println(e.getMessage()); } return conn; } public static Connection getConnection(String dsn, String id, String pwd) { Connection conn = null; try { if(dsn.equals("oracle")) { Class.forName("oracle.jdbc.OracleDriver"); conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe",id,pwd); } else if (dsn.equals("mysql")) { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bitsqldb?useSSL=true",id,pwd); } }catch(Exception e) { System.out.println(e.getMessage()); } return conn; } public static void close(Connection conn) { //객체의 주소값을 받아서... if(conn != null ) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static void close(ResultSet rs) { //객체의 주소값을 받아서... if(rs != null ) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static void close(Statement stmt) { //객체의 주소값을 받아서... if(stmt != null ) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static void close(PreparedStatement pstmt) { //객체의 주소값을 받아서... if(pstmt != null ) { try { pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
UHC
Java
2,826
java
ConnectionHelper.java
Java
[]
null
[]
package kr.or.bit.utils; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; /* Class.forName("oracle.jdbc.OracleDriver"); //메모리에 로드. >> new Driver //1. DB연결 conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","bituser","1004"); 1. 모든 CRUD 선행 작업 시 위 코드 필수 -> 반복적인 작업을 줄이자(드라이버 로딩, 연결객체, 명령...자원해제) 많이 쓰이는 작업 2. 다른 계정이나 다른 DB 연결 고민.. //5. DB 연결해제 try { stmt.close(); conn.close(); } catch (SQLException e) { e.printStackTrace(); } */ public class ConnectionHelper { //기능(연결....) >> 함수 >> 자주사용 static >> overloading >> interface //oracle, mysql 등 모두 연결할때 사용하기위해 public static Connection getConnection(String dsn) { Connection conn = null; try { if(dsn.equals("oracle")) { Class.forName("oracle.jdbc.OracleDriver"); conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","bituser","1004"); } else if (dsn.equals("mysql")) { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bitsqldb?useSSL=true","bituser","1004"); } }catch(Exception e) { System.out.println(e.getMessage()); } return conn; } public static Connection getConnection(String dsn, String id, String pwd) { Connection conn = null; try { if(dsn.equals("oracle")) { Class.forName("oracle.jdbc.OracleDriver"); conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe",id,pwd); } else if (dsn.equals("mysql")) { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bitsqldb?useSSL=true",id,pwd); } }catch(Exception e) { System.out.println(e.getMessage()); } return conn; } public static void close(Connection conn) { //객체의 주소값을 받아서... if(conn != null ) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static void close(ResultSet rs) { //객체의 주소값을 받아서... if(rs != null ) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static void close(Statement stmt) { //객체의 주소값을 받아서... if(stmt != null ) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static void close(PreparedStatement pstmt) { //객체의 주소값을 받아서... if(pstmt != null ) { try { pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
2,826
0.645589
0.631538
112
21.883928
24.736376
108
false
false
0
0
0
0
0
0
2.232143
false
false
4
2cb8d307af13ee9843957cfe74ae3b41990f8896
27,315,992,065,295
205b2bdaaab30bffa75968de5786f2e47f452e6f
/SerieSenoTaylorRecursivo.java
560ed0a8b8dcec082136b6e3544802984d66fb39
[]
no_license
victorhtorres/ED2
https://github.com/victorhtorres/ED2
52ef021710eceb6c6eeaf2fa15d1c951cbb1af92
5699415e9f6ce946bb66ba602e64fa68bc52aa60
refs/heads/master
2021-01-18T01:41:55.154000
2016-09-05T16:02:13
2016-09-05T16:02:13
51,026,118
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class SerieSenoTaylor { public static double serieSeno(double x, int n) { if (n == 0) { return x; } else { return serieSeno(x, n - 1) + (Math.pow(-1, n) / fact(2 * n + 1) ) * Math.pow (x, 2 * n + 1); } } public static int fact(int n) { return factExtend(n, 1); } private static int factExtend(int n, int r) { if (n == 0) { return r; } else { return factExtend(n - 1, n * r); } } } // Version mejorada como cola recursiva: public static double serieSenoCola(double x, int n) { return serieSenoColaExtend(x, n, 0); } private static double serieSenoColaExtend(double x, int n, double r) { if ( n == 0) { return r + (Math.pow(-1, n) / fact(2 * n + 1)) * Math.pow(x, 2 * n + 1); } else { return serieSenoColaExtend (x, n - 1, r + (Math.pow(-1, n) / fact(2 * n + 1)) * Math.pow(x, 2 * n + 1)); } } }
UTF-8
Java
956
java
SerieSenoTaylorRecursivo.java
Java
[ { "context": "\npublic class SerieSenoTaylor {\n\n public static double serieSeno(dou", "end": 19, "score": 0.6782890558242798, "start": 14, "tag": "NAME", "value": "Serie" } ]
null
[]
public class SerieSenoTaylor { public static double serieSeno(double x, int n) { if (n == 0) { return x; } else { return serieSeno(x, n - 1) + (Math.pow(-1, n) / fact(2 * n + 1) ) * Math.pow (x, 2 * n + 1); } } public static int fact(int n) { return factExtend(n, 1); } private static int factExtend(int n, int r) { if (n == 0) { return r; } else { return factExtend(n - 1, n * r); } } } // Version mejorada como cola recursiva: public static double serieSenoCola(double x, int n) { return serieSenoColaExtend(x, n, 0); } private static double serieSenoColaExtend(double x, int n, double r) { if ( n == 0) { return r + (Math.pow(-1, n) / fact(2 * n + 1)) * Math.pow(x, 2 * n + 1); } else { return serieSenoColaExtend (x, n - 1, r + (Math.pow(-1, n) / fact(2 * n + 1)) * Math.pow(x, 2 * n + 1)); } } }
956
0.512552
0.488494
51
17.745098
25.891813
110
false
false
0
0
0
0
0
0
0.509804
false
false
4
47a831ad45bd80677503f7a55b5d15a6ddb182ad
5,188,320,511,633
7e6ffa8bc055606c67e9583804354b16123c6d37
/src/main/java/core/resources/api/user/RolePermissionResource.java
9ee90ca9727749387203194777f1b952de26d261
[]
no_license
mafais/HIS_API
https://github.com/mafais/HIS_API
123380a2d5ef6f578d196d9424e946c843dc63f4
f5558b035aa8a6a3b85ff75838302ba438ad1d8f
refs/heads/master
2021-05-31T19:59:03.720000
2015-12-05T15:25:43
2015-12-05T15:25:43
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package core.resources.api.user; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import lib.driver.api.driver_class.user.RolePermissionDBDriver; import core.classes.api.user.AdminPermission; import core.classes.api.user.AdminRolePermissions; @Path("UserRolePermissionService") public class RolePermissionResource { RolePermissionDBDriver rolePermissionDBDriver = new RolePermissionDBDriver(); @Path("/InsertRolePermission/{roleId}/{permissionId}") @Produces(MediaType.TEXT_PLAIN) @Consumes(MediaType.APPLICATION_JSON) public String InsertRolePermission(@PathParam("roleId") int roleId, @PathParam("permissionId") int permissionId){ String result="false"; boolean r=false; AdminRolePermissions rpObj=new AdminRolePermissions(); rpObj.setRoleId(roleId); rpObj.setPermissoinId(permissionId); try{ r=rolePermissionDBDriver.insertUserRolePermission(rpObj); result=String.valueOf(r); return result; } catch(Exception ex){ ex.printStackTrace(); return result; } } @Path("/DeleteRolePermission/{roleId}") @Produces(MediaType.TEXT_PLAIN) @Consumes(MediaType.APPLICATION_JSON) public String DeleteRolePermission(@PathParam("roleId") int roleId){ String result="false"; boolean r=false; try{ r=rolePermissionDBDriver.DeleteUserRolePermission(roleId); result=String.valueOf(r); return result; } catch(Exception ex){ ex.printStackTrace(); return result; } } }
UTF-8
Java
1,574
java
RolePermissionResource.java
Java
[]
null
[]
package core.resources.api.user; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import lib.driver.api.driver_class.user.RolePermissionDBDriver; import core.classes.api.user.AdminPermission; import core.classes.api.user.AdminRolePermissions; @Path("UserRolePermissionService") public class RolePermissionResource { RolePermissionDBDriver rolePermissionDBDriver = new RolePermissionDBDriver(); @Path("/InsertRolePermission/{roleId}/{permissionId}") @Produces(MediaType.TEXT_PLAIN) @Consumes(MediaType.APPLICATION_JSON) public String InsertRolePermission(@PathParam("roleId") int roleId, @PathParam("permissionId") int permissionId){ String result="false"; boolean r=false; AdminRolePermissions rpObj=new AdminRolePermissions(); rpObj.setRoleId(roleId); rpObj.setPermissoinId(permissionId); try{ r=rolePermissionDBDriver.insertUserRolePermission(rpObj); result=String.valueOf(r); return result; } catch(Exception ex){ ex.printStackTrace(); return result; } } @Path("/DeleteRolePermission/{roleId}") @Produces(MediaType.TEXT_PLAIN) @Consumes(MediaType.APPLICATION_JSON) public String DeleteRolePermission(@PathParam("roleId") int roleId){ String result="false"; boolean r=false; try{ r=rolePermissionDBDriver.DeleteUserRolePermission(roleId); result=String.valueOf(r); return result; } catch(Exception ex){ ex.printStackTrace(); return result; } } }
1,574
0.759212
0.759212
62
24.387096
23.019175
114
false
false
0
0
0
0
0
0
1.870968
false
false
4
7667a10e4aabb1af2d11bc24d1309ec7aee7792d
36,051,955,485,304
40c2f923642f7462fbf553aade3e10f6c6c4d196
/src/com/buss/gjjsj/controller/AyGjjsjController.java
5f1c31dc6f620472fee6704998f3550d8d03b456
[]
no_license
huyongjing/AYHK
https://github.com/huyongjing/AYHK
a100a6654a3add6108fe1d393072dc0fcff5ae04
4b39b34c28ff2fe7b77b74b3f895082d8bfc8d3c
refs/heads/master
2021-04-12T08:01:18.731000
2017-06-16T03:16:09
2017-06-16T03:16:09
94,513,351
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.buss.gjjsj.controller; import com.buss.gjjsj.entity.AyGjjsjEntity; import com.buss.gjjsj.service.AyGjjsjServiceI; import com.buss.shgjj.entity.AyShgjjEntity; import com.buss.zxpz.entity.AyZxpzEntity; import org.apache.commons.collections.map.HashedMap; import org.apache.log4j.Logger; import org.jeecgframework.core.beanvalidator.BeanValidators; import org.jeecgframework.core.common.controller.BaseController; import org.jeecgframework.core.common.exception.BusinessException; import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery; import org.jeecgframework.core.common.model.json.AjaxJson; import org.jeecgframework.core.common.model.json.DataGrid; import org.jeecgframework.core.constant.Globals; import org.jeecgframework.core.util.ExceptionUtil; import org.jeecgframework.core.util.MyBeanUtils; import org.jeecgframework.core.util.ResourceUtil; import org.jeecgframework.core.util.StringUtil; import org.jeecgframework.poi.excel.ExcelImportUtil; import org.jeecgframework.poi.excel.entity.ExportParams; import org.jeecgframework.poi.excel.entity.ImportParams; import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants; import org.jeecgframework.tag.core.easyui.TagUtil; import org.jeecgframework.web.system.service.SystemService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.util.UriComponentsBuilder; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.ConstraintViolation; import javax.validation.Validator; import java.io.IOException; import java.net.URI; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; /** * @Title: Controller * @Description: 社会公积金时间 * @author caozengling * @date 2017-03-20 16:04:30 * @version V1.0 * */ @Controller @RequestMapping("/ayGjjsjController") public class AyGjjsjController extends BaseController { /** * Logger for this class */ private static final Logger logger = Logger.getLogger(AyGjjsjController.class); @Autowired private AyGjjsjServiceI ayGjjsjService; @Autowired private SystemService systemService; @Autowired private Validator validator; /** * 社会公积金时间列表 页面跳转 * * @return */ @RequestMapping(params = "list") public ModelAndView list(HttpServletRequest request) { return new ModelAndView("com/buss/gjjsj/ayGjjsjList"); } /** * easyui AJAX请求数据 * * @param request * @param response * @param dataGrid * @param user */ @RequestMapping(params = "datagrid") public void datagrid(AyGjjsjEntity ayGjjsj,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) { CriteriaQuery cq = new CriteriaQuery(AyGjjsjEntity.class, dataGrid); //查询条件组装器 org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, ayGjjsj, request.getParameterMap()); try{ //自定义追加查询条件 }catch (Exception e) { throw new BusinessException(e.getMessage()); } cq.add(); this.ayGjjsjService.getDataGridReturn(cq, true); /*List<AyGjjsjEntity> sjpzs =dataGrid.getResults(); List<Map<String,Object>> newdata = new ArrayList<Map<String,Object>>(); for(AyGjjsjEntity sjpz:sjpzs){ Map<String,Object> map= new HashedMap(); map.put("id",sjpz.getId()); map.put("year",sjpz.getYear()); map.put("month",sjpz.getMonth()); map.put("tjzt",sjpz.getTjzt()); List<AyZxpzEntity> xm= systemService.findHql("from AyZxpzEntity where zxbm=?",sjpz.getZxbm()); if(xm.size()>0){ map.put("zxbm",xm.get(0).getZx()); } newdata.add(map); } dataGrid.setResults(newdata);*/ TagUtil.datagrid(response, dataGrid); } /** * 删除社会公积金时间 * * @return */ @RequestMapping(params = "doDel") @ResponseBody public AjaxJson doDel(AyGjjsjEntity ayGjjsj, HttpServletRequest request) { String message = null; AjaxJson j = new AjaxJson(); ayGjjsj = systemService.getEntity(AyGjjsjEntity.class, ayGjjsj.getId()); message = "社会公积金时间删除成功"; try{ List<AyShgjjEntity> ayShgjjEntitylist = systemService.findHql("from AyShgjjEntity where sjpzid=?",ayGjjsj.getId()); if(ayShgjjEntitylist!=null){ for (AyShgjjEntity ayShgjjEntity : ayShgjjEntitylist) { systemService.delete(ayShgjjEntity); } } ayGjjsjService.delete(ayGjjsj); systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO); }catch(Exception e){ e.printStackTrace(); message = "社会公积金时间删除失败"; throw new BusinessException(e.getMessage()); } j.setMsg(message); return j; } /** * 批量删除社会公积金时间 * * @return */ @RequestMapping(params = "doBatchDel") @ResponseBody public AjaxJson doBatchDel(String ids,HttpServletRequest request){ String message = null; AjaxJson j = new AjaxJson(); message = "社会公积金时间删除成功"; try{ for(String id:ids.split(",")){ AyGjjsjEntity ayGjjsj = systemService.getEntity(AyGjjsjEntity.class, id ); ayGjjsjService.delete(ayGjjsj); systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO); } }catch(Exception e){ e.printStackTrace(); message = "社会公积金时间删除失败"; throw new BusinessException(e.getMessage()); } j.setMsg(message); return j; } /** * 添加社会公积金时间 * * @param ids * @return */ @RequestMapping(params = "doAdd") @ResponseBody public AjaxJson doAdd(AyGjjsjEntity ayGjjsj, HttpServletRequest request) { String message = null; AjaxJson j = new AjaxJson(); message = "社会公积金时间添加成功"; try{ List<AyGjjsjEntity> aySjpzlist = systemService.findHql("from AyGjjsjEntity where month =? and year =? and zxbm = ?",ayGjjsj.getMonth(),ayGjjsj.getYear(),ayGjjsj.getZxbm()); if(aySjpzlist!=null){ if(aySjpzlist.size()>0){ message = "本月已存在"; }else{ ayGjjsj.setTjzt("0"); ayGjjsjService.save(ayGjjsj); systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO); } }else{ ayGjjsj.setTjzt("0"); ayGjjsjService.save(ayGjjsj); systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO); } }catch(Exception e){ e.printStackTrace(); message = "社会公积金时间添加失败"; throw new BusinessException(e.getMessage()); } j.setMsg(message); return j; } /** * 添加提交 * * @param ids * @return */ @RequestMapping(params = "doTijiao") @ResponseBody public AjaxJson doTijiao(AyGjjsjEntity aySjpz, HttpServletRequest request) { String message = null; AjaxJson j = new AjaxJson(); message = "提交成功"; try{ systemService.updateBySqlString("update AY_GJJSJ set tjzt = 2 where id=" + "'"+aySjpz.getId()+"'");//更新当月的提交状态 systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO); }catch(Exception e){ e.printStackTrace(); message = "时间配置表添加失败"; throw new BusinessException(e.getMessage()); } j.setMsg(message); return j; } /** * 添加提交 * * @param ids * @return */ @RequestMapping(params = "doBohui") @ResponseBody public AjaxJson doBohui(AyGjjsjEntity aySjpz, HttpServletRequest request) { String message = null; AjaxJson j = new AjaxJson(); message = "提交成功"; try{ systemService.updateBySqlString("update AY_GJJSJ set tjzt = 0 where id=" + "'"+aySjpz.getId()+"'");//更新当月的提交状态 systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO); }catch(Exception e){ e.printStackTrace(); message = "时间配置表添加失败"; throw new BusinessException(e.getMessage()); } j.setMsg(message); return j; } /** * 更新社会公积金时间 * * @param ids * @return */ @RequestMapping(params = "doUpdate") @ResponseBody public AjaxJson doUpdate(AyGjjsjEntity ayGjjsj, HttpServletRequest request) { String message = null; AjaxJson j = new AjaxJson(); message = "社会公积金时间更新成功"; AyGjjsjEntity t = ayGjjsjService.get(AyGjjsjEntity.class, ayGjjsj.getId()); try { MyBeanUtils.copyBeanNotNull2Bean(ayGjjsj, t); ayGjjsjService.saveOrUpdate(t); systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO); } catch (Exception e) { e.printStackTrace(); message = "社会公积金时间更新失败"; throw new BusinessException(e.getMessage()); } j.setMsg(message); return j; } /** * 社会公积金时间新增页面跳转 * * @return */ @RequestMapping(params = "goAdd") public ModelAndView goAdd(AyGjjsjEntity ayGjjsj, HttpServletRequest req) { if (StringUtil.isNotEmpty(ayGjjsj.getId())) { ayGjjsj = ayGjjsjService.getEntity(AyGjjsjEntity.class, ayGjjsj.getId()); req.setAttribute("ayGjjsjPage", ayGjjsj); } return new ModelAndView("com/buss/gjjsj/ayGjjsj-add"); } /** * 社会公积金时间编辑页面跳转 * * @return */ @RequestMapping(params = "goUpdate") public ModelAndView goUpdate(AyGjjsjEntity ayGjjsj, HttpServletRequest req) { if (StringUtil.isNotEmpty(ayGjjsj.getId())) { ayGjjsj = ayGjjsjService.getEntity(AyGjjsjEntity.class, ayGjjsj.getId()); Date date = ayGjjsj.getUpdateDate(); Date date1 = ayGjjsj.getCreateDate(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String time = sdf.format(date); String time1 = sdf.format(date1); try { Date newDate = sdf.parse(time); Date newDate1 = sdf.parse(time1); ayGjjsj.setCreateDate(newDate1); ayGjjsj.setUpdateDate(newDate); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } req.setAttribute("ayGjjsjPage", ayGjjsj); } return new ModelAndView("com/buss/gjjsj/ayGjjsj-update"); } /** * 导入功能跳转 * * @return */ @RequestMapping(params = "upload") public ModelAndView upload(HttpServletRequest req) { req.setAttribute("controller_name","ayGjjsjController"); return new ModelAndView("common/upload/pub_excel_upload"); } /** * 导出excel * * @param request * @param response */ @RequestMapping(params = "exportXls") public String exportXls(AyGjjsjEntity ayGjjsj,HttpServletRequest request,HttpServletResponse response , DataGrid dataGrid,ModelMap modelMap) { CriteriaQuery cq = new CriteriaQuery(AyGjjsjEntity.class, dataGrid); org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, ayGjjsj, request.getParameterMap()); List<AyGjjsjEntity> ayGjjsjs = this.ayGjjsjService.getListByCriteriaQuery(cq,false); modelMap.put(NormalExcelConstants.FILE_NAME,"社会公积金时间"); modelMap.put(NormalExcelConstants.CLASS,AyGjjsjEntity.class); modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("社会公积金时间列表", "导出人:"+ResourceUtil.getSessionUserName().getRealName(), "导出信息")); modelMap.put(NormalExcelConstants.DATA_LIST,ayGjjsjs); return NormalExcelConstants.JEECG_EXCEL_VIEW; } /** * 导出excel 使模板 * * @param request * @param response */ @RequestMapping(params = "exportXlsByT") public String exportXlsByT(AyGjjsjEntity ayGjjsj,HttpServletRequest request,HttpServletResponse response , DataGrid dataGrid,ModelMap modelMap) { modelMap.put(NormalExcelConstants.FILE_NAME,"社会公积金时间"); modelMap.put(NormalExcelConstants.CLASS,AyGjjsjEntity.class); modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("社会公积金时间列表", "导出人:"+ResourceUtil.getSessionUserName().getRealName(), "导出信息")); modelMap.put(NormalExcelConstants.DATA_LIST,new ArrayList()); return NormalExcelConstants.JEECG_EXCEL_VIEW; } @SuppressWarnings("unchecked") @RequestMapping(params = "importExcel", method = RequestMethod.POST) @ResponseBody public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) { AjaxJson j = new AjaxJson(); MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; Map<String, MultipartFile> fileMap = multipartRequest.getFileMap(); for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) { MultipartFile file = entity.getValue();// 获取上传文件对象 ImportParams params = new ImportParams(); params.setTitleRows(2); params.setHeadRows(1); params.setNeedSave(true); try { List<AyGjjsjEntity> listAyGjjsjEntitys = ExcelImportUtil.importExcel(file.getInputStream(),AyGjjsjEntity.class,params); for (AyGjjsjEntity ayGjjsj : listAyGjjsjEntitys) { ayGjjsjService.save(ayGjjsj); } j.setMsg("文件导入成功!"); } catch (Exception e) { j.setMsg("文件导入失败!"); logger.error(ExceptionUtil.getExceptionMessage(e)); }finally{ try { file.getInputStream().close(); } catch (IOException e) { e.printStackTrace(); } } } return j; } @RequestMapping(method = RequestMethod.GET) @ResponseBody public List<AyGjjsjEntity> list() { List<AyGjjsjEntity> listAyGjjsjs=ayGjjsjService.getList(AyGjjsjEntity.class); return listAyGjjsjs; } @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ResponseBody public ResponseEntity<?> get(@PathVariable("id") String id) { AyGjjsjEntity task = ayGjjsjService.get(AyGjjsjEntity.class, id); if (task == null) { return new ResponseEntity(HttpStatus.NOT_FOUND); } return new ResponseEntity(task, HttpStatus.OK); } @RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public ResponseEntity<?> create(@RequestBody AyGjjsjEntity ayGjjsj, UriComponentsBuilder uriBuilder) { //调用JSR303 Bean Validator进行校验,如果出错返回含400错误码及json格式的错误信息. Set<ConstraintViolation<AyGjjsjEntity>> failures = validator.validate(ayGjjsj); if (!failures.isEmpty()) { return new ResponseEntity(BeanValidators.extractPropertyAndMessage(failures), HttpStatus.BAD_REQUEST); } //保存 try{ ayGjjsjService.save(ayGjjsj); } catch (Exception e) { e.printStackTrace(); return new ResponseEntity(HttpStatus.NO_CONTENT); } //按照Restful风格约定,创建指向新任务的url, 也可以直接返回id或对象. String id = ayGjjsj.getId(); URI uri = uriBuilder.path("/rest/ayGjjsjController/" + id).build().toUri(); HttpHeaders headers = new HttpHeaders(); headers.setLocation(uri); return new ResponseEntity(headers, HttpStatus.CREATED); } @RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<?> update(@RequestBody AyGjjsjEntity ayGjjsj) { //调用JSR303 Bean Validator进行校验,如果出错返回含400错误码及json格式的错误信息. Set<ConstraintViolation<AyGjjsjEntity>> failures = validator.validate(ayGjjsj); if (!failures.isEmpty()) { return new ResponseEntity(BeanValidators.extractPropertyAndMessage(failures), HttpStatus.BAD_REQUEST); } //保存 try{ ayGjjsjService.saveOrUpdate(ayGjjsj); } catch (Exception e) { e.printStackTrace(); return new ResponseEntity(HttpStatus.NO_CONTENT); } //按Restful约定,返回204状态码, 无内容. 也可以返回200状态码. return new ResponseEntity(HttpStatus.NO_CONTENT); } @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) @ResponseStatus(HttpStatus.NO_CONTENT) public void delete(@PathVariable("id") String id) { ayGjjsjService.deleteEntityById(AyGjjsjEntity.class, id); } }
UTF-8
Java
16,261
java
AyGjjsjController.java
Java
[ { "context": ": Controller \n * @Description: 社会公积金时间\n * @author caozengling\n * @date 2017-03-20 16:04:30\n * @version V1.0 \n", "end": 2377, "score": 0.9992226362228394, "start": 2366, "tag": "USERNAME", "value": "caozengling" } ]
null
[]
package com.buss.gjjsj.controller; import com.buss.gjjsj.entity.AyGjjsjEntity; import com.buss.gjjsj.service.AyGjjsjServiceI; import com.buss.shgjj.entity.AyShgjjEntity; import com.buss.zxpz.entity.AyZxpzEntity; import org.apache.commons.collections.map.HashedMap; import org.apache.log4j.Logger; import org.jeecgframework.core.beanvalidator.BeanValidators; import org.jeecgframework.core.common.controller.BaseController; import org.jeecgframework.core.common.exception.BusinessException; import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery; import org.jeecgframework.core.common.model.json.AjaxJson; import org.jeecgframework.core.common.model.json.DataGrid; import org.jeecgframework.core.constant.Globals; import org.jeecgframework.core.util.ExceptionUtil; import org.jeecgframework.core.util.MyBeanUtils; import org.jeecgframework.core.util.ResourceUtil; import org.jeecgframework.core.util.StringUtil; import org.jeecgframework.poi.excel.ExcelImportUtil; import org.jeecgframework.poi.excel.entity.ExportParams; import org.jeecgframework.poi.excel.entity.ImportParams; import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants; import org.jeecgframework.tag.core.easyui.TagUtil; import org.jeecgframework.web.system.service.SystemService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.util.UriComponentsBuilder; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.ConstraintViolation; import javax.validation.Validator; import java.io.IOException; import java.net.URI; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; /** * @Title: Controller * @Description: 社会公积金时间 * @author caozengling * @date 2017-03-20 16:04:30 * @version V1.0 * */ @Controller @RequestMapping("/ayGjjsjController") public class AyGjjsjController extends BaseController { /** * Logger for this class */ private static final Logger logger = Logger.getLogger(AyGjjsjController.class); @Autowired private AyGjjsjServiceI ayGjjsjService; @Autowired private SystemService systemService; @Autowired private Validator validator; /** * 社会公积金时间列表 页面跳转 * * @return */ @RequestMapping(params = "list") public ModelAndView list(HttpServletRequest request) { return new ModelAndView("com/buss/gjjsj/ayGjjsjList"); } /** * easyui AJAX请求数据 * * @param request * @param response * @param dataGrid * @param user */ @RequestMapping(params = "datagrid") public void datagrid(AyGjjsjEntity ayGjjsj,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) { CriteriaQuery cq = new CriteriaQuery(AyGjjsjEntity.class, dataGrid); //查询条件组装器 org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, ayGjjsj, request.getParameterMap()); try{ //自定义追加查询条件 }catch (Exception e) { throw new BusinessException(e.getMessage()); } cq.add(); this.ayGjjsjService.getDataGridReturn(cq, true); /*List<AyGjjsjEntity> sjpzs =dataGrid.getResults(); List<Map<String,Object>> newdata = new ArrayList<Map<String,Object>>(); for(AyGjjsjEntity sjpz:sjpzs){ Map<String,Object> map= new HashedMap(); map.put("id",sjpz.getId()); map.put("year",sjpz.getYear()); map.put("month",sjpz.getMonth()); map.put("tjzt",sjpz.getTjzt()); List<AyZxpzEntity> xm= systemService.findHql("from AyZxpzEntity where zxbm=?",sjpz.getZxbm()); if(xm.size()>0){ map.put("zxbm",xm.get(0).getZx()); } newdata.add(map); } dataGrid.setResults(newdata);*/ TagUtil.datagrid(response, dataGrid); } /** * 删除社会公积金时间 * * @return */ @RequestMapping(params = "doDel") @ResponseBody public AjaxJson doDel(AyGjjsjEntity ayGjjsj, HttpServletRequest request) { String message = null; AjaxJson j = new AjaxJson(); ayGjjsj = systemService.getEntity(AyGjjsjEntity.class, ayGjjsj.getId()); message = "社会公积金时间删除成功"; try{ List<AyShgjjEntity> ayShgjjEntitylist = systemService.findHql("from AyShgjjEntity where sjpzid=?",ayGjjsj.getId()); if(ayShgjjEntitylist!=null){ for (AyShgjjEntity ayShgjjEntity : ayShgjjEntitylist) { systemService.delete(ayShgjjEntity); } } ayGjjsjService.delete(ayGjjsj); systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO); }catch(Exception e){ e.printStackTrace(); message = "社会公积金时间删除失败"; throw new BusinessException(e.getMessage()); } j.setMsg(message); return j; } /** * 批量删除社会公积金时间 * * @return */ @RequestMapping(params = "doBatchDel") @ResponseBody public AjaxJson doBatchDel(String ids,HttpServletRequest request){ String message = null; AjaxJson j = new AjaxJson(); message = "社会公积金时间删除成功"; try{ for(String id:ids.split(",")){ AyGjjsjEntity ayGjjsj = systemService.getEntity(AyGjjsjEntity.class, id ); ayGjjsjService.delete(ayGjjsj); systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO); } }catch(Exception e){ e.printStackTrace(); message = "社会公积金时间删除失败"; throw new BusinessException(e.getMessage()); } j.setMsg(message); return j; } /** * 添加社会公积金时间 * * @param ids * @return */ @RequestMapping(params = "doAdd") @ResponseBody public AjaxJson doAdd(AyGjjsjEntity ayGjjsj, HttpServletRequest request) { String message = null; AjaxJson j = new AjaxJson(); message = "社会公积金时间添加成功"; try{ List<AyGjjsjEntity> aySjpzlist = systemService.findHql("from AyGjjsjEntity where month =? and year =? and zxbm = ?",ayGjjsj.getMonth(),ayGjjsj.getYear(),ayGjjsj.getZxbm()); if(aySjpzlist!=null){ if(aySjpzlist.size()>0){ message = "本月已存在"; }else{ ayGjjsj.setTjzt("0"); ayGjjsjService.save(ayGjjsj); systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO); } }else{ ayGjjsj.setTjzt("0"); ayGjjsjService.save(ayGjjsj); systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO); } }catch(Exception e){ e.printStackTrace(); message = "社会公积金时间添加失败"; throw new BusinessException(e.getMessage()); } j.setMsg(message); return j; } /** * 添加提交 * * @param ids * @return */ @RequestMapping(params = "doTijiao") @ResponseBody public AjaxJson doTijiao(AyGjjsjEntity aySjpz, HttpServletRequest request) { String message = null; AjaxJson j = new AjaxJson(); message = "提交成功"; try{ systemService.updateBySqlString("update AY_GJJSJ set tjzt = 2 where id=" + "'"+aySjpz.getId()+"'");//更新当月的提交状态 systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO); }catch(Exception e){ e.printStackTrace(); message = "时间配置表添加失败"; throw new BusinessException(e.getMessage()); } j.setMsg(message); return j; } /** * 添加提交 * * @param ids * @return */ @RequestMapping(params = "doBohui") @ResponseBody public AjaxJson doBohui(AyGjjsjEntity aySjpz, HttpServletRequest request) { String message = null; AjaxJson j = new AjaxJson(); message = "提交成功"; try{ systemService.updateBySqlString("update AY_GJJSJ set tjzt = 0 where id=" + "'"+aySjpz.getId()+"'");//更新当月的提交状态 systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO); }catch(Exception e){ e.printStackTrace(); message = "时间配置表添加失败"; throw new BusinessException(e.getMessage()); } j.setMsg(message); return j; } /** * 更新社会公积金时间 * * @param ids * @return */ @RequestMapping(params = "doUpdate") @ResponseBody public AjaxJson doUpdate(AyGjjsjEntity ayGjjsj, HttpServletRequest request) { String message = null; AjaxJson j = new AjaxJson(); message = "社会公积金时间更新成功"; AyGjjsjEntity t = ayGjjsjService.get(AyGjjsjEntity.class, ayGjjsj.getId()); try { MyBeanUtils.copyBeanNotNull2Bean(ayGjjsj, t); ayGjjsjService.saveOrUpdate(t); systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO); } catch (Exception e) { e.printStackTrace(); message = "社会公积金时间更新失败"; throw new BusinessException(e.getMessage()); } j.setMsg(message); return j; } /** * 社会公积金时间新增页面跳转 * * @return */ @RequestMapping(params = "goAdd") public ModelAndView goAdd(AyGjjsjEntity ayGjjsj, HttpServletRequest req) { if (StringUtil.isNotEmpty(ayGjjsj.getId())) { ayGjjsj = ayGjjsjService.getEntity(AyGjjsjEntity.class, ayGjjsj.getId()); req.setAttribute("ayGjjsjPage", ayGjjsj); } return new ModelAndView("com/buss/gjjsj/ayGjjsj-add"); } /** * 社会公积金时间编辑页面跳转 * * @return */ @RequestMapping(params = "goUpdate") public ModelAndView goUpdate(AyGjjsjEntity ayGjjsj, HttpServletRequest req) { if (StringUtil.isNotEmpty(ayGjjsj.getId())) { ayGjjsj = ayGjjsjService.getEntity(AyGjjsjEntity.class, ayGjjsj.getId()); Date date = ayGjjsj.getUpdateDate(); Date date1 = ayGjjsj.getCreateDate(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String time = sdf.format(date); String time1 = sdf.format(date1); try { Date newDate = sdf.parse(time); Date newDate1 = sdf.parse(time1); ayGjjsj.setCreateDate(newDate1); ayGjjsj.setUpdateDate(newDate); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } req.setAttribute("ayGjjsjPage", ayGjjsj); } return new ModelAndView("com/buss/gjjsj/ayGjjsj-update"); } /** * 导入功能跳转 * * @return */ @RequestMapping(params = "upload") public ModelAndView upload(HttpServletRequest req) { req.setAttribute("controller_name","ayGjjsjController"); return new ModelAndView("common/upload/pub_excel_upload"); } /** * 导出excel * * @param request * @param response */ @RequestMapping(params = "exportXls") public String exportXls(AyGjjsjEntity ayGjjsj,HttpServletRequest request,HttpServletResponse response , DataGrid dataGrid,ModelMap modelMap) { CriteriaQuery cq = new CriteriaQuery(AyGjjsjEntity.class, dataGrid); org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, ayGjjsj, request.getParameterMap()); List<AyGjjsjEntity> ayGjjsjs = this.ayGjjsjService.getListByCriteriaQuery(cq,false); modelMap.put(NormalExcelConstants.FILE_NAME,"社会公积金时间"); modelMap.put(NormalExcelConstants.CLASS,AyGjjsjEntity.class); modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("社会公积金时间列表", "导出人:"+ResourceUtil.getSessionUserName().getRealName(), "导出信息")); modelMap.put(NormalExcelConstants.DATA_LIST,ayGjjsjs); return NormalExcelConstants.JEECG_EXCEL_VIEW; } /** * 导出excel 使模板 * * @param request * @param response */ @RequestMapping(params = "exportXlsByT") public String exportXlsByT(AyGjjsjEntity ayGjjsj,HttpServletRequest request,HttpServletResponse response , DataGrid dataGrid,ModelMap modelMap) { modelMap.put(NormalExcelConstants.FILE_NAME,"社会公积金时间"); modelMap.put(NormalExcelConstants.CLASS,AyGjjsjEntity.class); modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("社会公积金时间列表", "导出人:"+ResourceUtil.getSessionUserName().getRealName(), "导出信息")); modelMap.put(NormalExcelConstants.DATA_LIST,new ArrayList()); return NormalExcelConstants.JEECG_EXCEL_VIEW; } @SuppressWarnings("unchecked") @RequestMapping(params = "importExcel", method = RequestMethod.POST) @ResponseBody public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) { AjaxJson j = new AjaxJson(); MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; Map<String, MultipartFile> fileMap = multipartRequest.getFileMap(); for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) { MultipartFile file = entity.getValue();// 获取上传文件对象 ImportParams params = new ImportParams(); params.setTitleRows(2); params.setHeadRows(1); params.setNeedSave(true); try { List<AyGjjsjEntity> listAyGjjsjEntitys = ExcelImportUtil.importExcel(file.getInputStream(),AyGjjsjEntity.class,params); for (AyGjjsjEntity ayGjjsj : listAyGjjsjEntitys) { ayGjjsjService.save(ayGjjsj); } j.setMsg("文件导入成功!"); } catch (Exception e) { j.setMsg("文件导入失败!"); logger.error(ExceptionUtil.getExceptionMessage(e)); }finally{ try { file.getInputStream().close(); } catch (IOException e) { e.printStackTrace(); } } } return j; } @RequestMapping(method = RequestMethod.GET) @ResponseBody public List<AyGjjsjEntity> list() { List<AyGjjsjEntity> listAyGjjsjs=ayGjjsjService.getList(AyGjjsjEntity.class); return listAyGjjsjs; } @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ResponseBody public ResponseEntity<?> get(@PathVariable("id") String id) { AyGjjsjEntity task = ayGjjsjService.get(AyGjjsjEntity.class, id); if (task == null) { return new ResponseEntity(HttpStatus.NOT_FOUND); } return new ResponseEntity(task, HttpStatus.OK); } @RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public ResponseEntity<?> create(@RequestBody AyGjjsjEntity ayGjjsj, UriComponentsBuilder uriBuilder) { //调用JSR303 Bean Validator进行校验,如果出错返回含400错误码及json格式的错误信息. Set<ConstraintViolation<AyGjjsjEntity>> failures = validator.validate(ayGjjsj); if (!failures.isEmpty()) { return new ResponseEntity(BeanValidators.extractPropertyAndMessage(failures), HttpStatus.BAD_REQUEST); } //保存 try{ ayGjjsjService.save(ayGjjsj); } catch (Exception e) { e.printStackTrace(); return new ResponseEntity(HttpStatus.NO_CONTENT); } //按照Restful风格约定,创建指向新任务的url, 也可以直接返回id或对象. String id = ayGjjsj.getId(); URI uri = uriBuilder.path("/rest/ayGjjsjController/" + id).build().toUri(); HttpHeaders headers = new HttpHeaders(); headers.setLocation(uri); return new ResponseEntity(headers, HttpStatus.CREATED); } @RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<?> update(@RequestBody AyGjjsjEntity ayGjjsj) { //调用JSR303 Bean Validator进行校验,如果出错返回含400错误码及json格式的错误信息. Set<ConstraintViolation<AyGjjsjEntity>> failures = validator.validate(ayGjjsj); if (!failures.isEmpty()) { return new ResponseEntity(BeanValidators.extractPropertyAndMessage(failures), HttpStatus.BAD_REQUEST); } //保存 try{ ayGjjsjService.saveOrUpdate(ayGjjsj); } catch (Exception e) { e.printStackTrace(); return new ResponseEntity(HttpStatus.NO_CONTENT); } //按Restful约定,返回204状态码, 无内容. 也可以返回200状态码. return new ResponseEntity(HttpStatus.NO_CONTENT); } @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) @ResponseStatus(HttpStatus.NO_CONTENT) public void delete(@PathVariable("id") String id) { ayGjjsjService.deleteEntityById(AyGjjsjEntity.class, id); } }
16,261
0.736999
0.733688
489
30.498978
28.320986
175
false
false
0
0
0
0
0
0
2.274029
false
false
4
e9371e44a45ecc6ae59933f132bed0cb275ea60f
20,392,504,774,526
5bf9ccaa529b0b5067d8b866629db70799997b34
/src/com/code/servlet/DiseaseInfoServlet.java
34882b01b7dc5447a919bf2d78f5244f5dc996ed
[]
no_license
Promise-Leo/forest_system
https://github.com/Promise-Leo/forest_system
9d13f9f193ed3d4b4a5388b8f28103b4525920e9
c4488bd8c3a73aca46967a1631874328d685dfed
refs/heads/master
2023-04-16T11:14:35.627000
2015-10-21T16:53:33
2015-10-21T16:53:33
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.code.servlet; import com.code.bean.DiseaseBean; import com.code.service.imp.DiseaseServiceimp_old; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class DiseaseInfoServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub this.doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub DiseaseServiceimp_old dls = new DiseaseServiceimp_old(); DiseaseBean a = dls.getDiseaseById(Integer.parseInt(req.getParameter("id"))); a.getName(); a.getSource(); a.getSymptoms(); //a.getROD(); a.getPicture(); //a.getLMA(); a.getMainharm(); System.out.println(a.getName()); req.setAttribute("empManage2",a ); req.getRequestDispatcher("jsp/datamanagement/diseaseInfo.jsp").forward(req, resp); } }
UTF-8
Java
1,145
java
DiseaseInfoServlet.java
Java
[]
null
[]
package com.code.servlet; import com.code.bean.DiseaseBean; import com.code.service.imp.DiseaseServiceimp_old; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class DiseaseInfoServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub this.doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub DiseaseServiceimp_old dls = new DiseaseServiceimp_old(); DiseaseBean a = dls.getDiseaseById(Integer.parseInt(req.getParameter("id"))); a.getName(); a.getSource(); a.getSymptoms(); //a.getROD(); a.getPicture(); //a.getLMA(); a.getMainharm(); System.out.println(a.getName()); req.setAttribute("empManage2",a ); req.getRequestDispatcher("jsp/datamanagement/diseaseInfo.jsp").forward(req, resp); } }
1,145
0.768559
0.767686
39
28.358974
23.414314
84
false
false
0
0
0
0
0
0
1.794872
false
false
4
0f51f1f55c9b0c5dbb127f1c32ae98509863a53f
1,082,331,771,823
3f216893e2d5ee0cfe0130de8cea2f2885d2be0b
/app/src/main/java/com/example/solene/galidog/MapsActivity.java
8dba4ade6eb4d4068fce657ae65c2336c32de8f6
[]
no_license
soleneG02/ProjetGalidog
https://github.com/soleneG02/ProjetGalidog
d4f68c9040c061f995ec0052e186059d4a6c6ff5
c5c71c3ae8ba971d944041deebb85e93322c7a59
refs/heads/master
2020-04-21T03:12:13.500000
2019-02-05T17:12:24
2019-02-05T17:12:24
169,277,432
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.solene.galidog; import android.Manifest; import android.annotation.SuppressLint; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Color; import android.location.GpsSatellite; import android.location.GpsStatus; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.media.MediaPlayer; import android.media.MediaRecorder; import android.os.Environment; import android.support.v4.app.ActivityCompat; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import android.support.v4.content.ContextCompat; import android.util.Log; import android.view.Gravity; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptor; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.Polyline; import com.google.android.gms.maps.model.PolylineOptions; import java.io.IOException; import java.util.ArrayList; import java.util.Random; import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; import static android.Manifest.permission.RECORD_AUDIO; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { /* La classe MapsActivity gère l'enregistrement d'un trajet. */ /* Attributs nécessaires à l'utilisation d'une carte Google Maps, et à la géolocalisation. */ private GoogleMap mMap; private Button btnStartRecord; private LocationManager androidLocationManager; private LocationListener androidLocationListener; private final static int REQUEST_CODE_UPDATE_LOCATION = 42; /* Attributs correspondants aux différents boutons de l'activité : commandes pré enregistrées et enregistrement d'une nouvelle commande. */ private Button btnDroite, btnGauche, btnHalte, btnAutre; private Button btnEnreg, btnStop, btnJouer, btnValide; /* Attributs pour design de l'application. */ private PolylineOptions dessin = new PolylineOptions().width(9).color(Color.BLUE); private Polyline dessinTrajet; private ArrayList<LatLng> listeCoord = new ArrayList<>(); /* Attributs utiles au fonctionnement de l'algorithme. */ private Point pointSuivant; private ArrayList<Point> listePoints = new ArrayList<>(); private ArrayList<CommandeVocale> listeCommandes = new ArrayList<>(); /* Attributs nécessaire à la lecture et l'enregistrement de commandes vocales. */ String AudioSavePathInDevice = null; MediaRecorder mediaRecorder; private int idNewCommande = 0; public static final int RequestPermissionCode = 1; MediaPlayer mediaPlayer; private int ENREG_NB = 0; @Override protected void onCreate(Bundle savedInstanceState) { /* Fonction qui se lance à l'ouverture de l'activité d'enregistrement. */ super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps2); SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); mapFragment.getMapAsync(this); /* Association des boutons du layout à l'activité. Certains boutons (enregistrement d'une commande) sont pour l'instant invisibles à l'écran. */ btnStartRecord = (Button) findViewById(R.id.activity_main_btn_start_record); btnDroite = (Button) findViewById(R.id.activity_main_btn_droite); btnGauche = (Button) findViewById(R.id.activity_main_btn_gauche); btnHalte = (Button) findViewById(R.id.activity_main_btn_halte); btnAutre = (Button) findViewById(R.id.activity_main_btn_autre); btnEnreg = (Button) findViewById(R.id.activity_main_btn_enreg); btnStop = (Button) findViewById(R.id.activity_main_btn_stop); btnJouer = (Button) findViewById(R.id.activity_main_btn_jouer); btnValide = (Button) findViewById(R.id.activity_main_btn_valide); btnEnreg.setVisibility(View.INVISIBLE); btnStop.setVisibility(View.INVISIBLE); btnJouer.setVisibility(View.INVISIBLE); btnValide.setVisibility(View.INVISIBLE); } @Override public void onMapReady(GoogleMap googleMap) { /* Fonction qui se lance lorsque la carte Google Maps est prête. */ mMap = googleMap; /* Initialisation du trajet dessiné */ dessinTrajet = mMap.addPolyline(dessin); /* La fonction androidFirstLocation() affiche la localisation de l'utilisateur à son entrée dans l'activité MapsActivity. */ androidFirstLocation(); /* Démarrage de l'enregistrement */ btnStartRecord.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast toast = Toast.makeText(MapsActivity.this, "L'enregistrement démarre", Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); /*La fonction androidUpdateLocation() enregistre les points du trajet et les commandes vocales associées. */ androidUpdateLocation(); btnStartRecord.setText("Arrêter l'enregistrement"); /* Arrêt de l'enregistrement */ btnStartRecord.setOnClickListener((new View.OnClickListener() { @Override public void onClick(View v) { onPause(); Toast.makeText(MapsActivity.this, "Fin de l'enregistrement", Toast.LENGTH_SHORT).show(); btnStartRecord.setText("Retour à l'accueil"); /* Retour à la page d'accueil, avec envoi des données enregistrées. */ btnStartRecord.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent retourAccueil = new Intent(MapsActivity.this, MainActivity.class); retourAccueil.putParcelableArrayListExtra("commandes", listeCommandes); retourAccueil.putParcelableArrayListExtra("points", listePoints); startActivity(retourAccueil); } }); } })); } }); } public void androidFirstLocation() { /* Fonction qui affiche la géolocalisation de l'utilisateur lorsqu'il arrive pour la première fois sur la page. */ /* Vérification des permissions du téléphone en terme de géolocalisation. */ if (ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions( MapsActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE_UPDATE_LOCATION); } /* Si les permissions sont accordées, mise en place de l'enregistrement. */ else { androidLocationManager = (LocationManager) this.getSystemService(MapsActivity.this.LOCATION_SERVICE); androidLocationListener = new LocationListener() { public void onLocationChanged(Location loc) { /* Récupération des coordonnées actuelles */ double latNow = loc.getLatitude(); double lonNow = loc.getLongitude(); Toast.makeText(MapsActivity.this, "Coordonnées : " + latNow + " / " + lonNow, Toast.LENGTH_SHORT).show(); /* Ajout du point à la liste des points visités. */ LatLng youAreHere = new LatLng(latNow, lonNow); Point newPoint = new Point(latNow, lonNow); listePoints.add(newPoint); /* Démarrage du tracé du trajet. */ listeCoord.add(new LatLng(latNow,lonNow)); dessinTrajet.setPoints(listeCoord); /* Affichage d'un marqueur à l'emplacement de l'utilisateur. */ BitmapDescriptor point1 = BitmapDescriptorFactory.fromResource(R.drawable.point2_init); mMap.addMarker(new MarkerOptions().position(youAreHere).title("Vous êtes ici").icon(point1)); int padding = 17; mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(youAreHere, padding)); } public void onStatusChanged(String provider, int status, Bundle extras) { } public void onProviderEnabled(String provider) { } public void onProviderDisabled(String provider) { } }; /* Requête unique (première géolocalisation) */ androidLocationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, androidLocationListener, null); } } public void androidUpdateLocation() { /* Fonction qui enregistre les différentes positions d'un utilisateur en mouvement, les affiche et les associe aux commandes vocales. */ /* Vérification des permissions du téléphone en terme de géolocalisation. */ if (ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions( MapsActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE_UPDATE_LOCATION); } /* Si les permissions sont accordées, mise en place de l'enregistrement. */ else { androidLocationManager = (LocationManager) this.getSystemService(MapsActivity.this.LOCATION_SERVICE); androidLocationListener = new LocationListener() { public void onLocationChanged(Location loc) { /* Récupération des coordonnées actuelles */ double latNow = loc.getLatitude(); double lonNow = loc.getLongitude(); LatLng youAreHere = new LatLng(latNow, lonNow); /* Création d'une potentielle commande vocale, associé à la localisation actuelle */ BoutonDroite(latNow, lonNow); BoutonGauche(latNow, lonNow); BoutonHalte(latNow, lonNow); BoutonAutre(latNow, lonNow); /* Ajout du point à la liste des points visités. */ pointSuivant = new Point(latNow, lonNow); listePoints.add(pointSuivant); /* Actualisation du tracé du trajet. */ listeCoord.add(new LatLng(latNow,lonNow)); dessinTrajet.setPoints(listeCoord); /* Affichage d'un message lors du premier point enregistré. */ if (pointSuivant.getIdPoint() == 1) { Toast.makeText(MapsActivity.this, "Trace en cours ", Toast.LENGTH_SHORT).show(); } /* Affichage d'un marqueur à l'emplacement de l'utilisateur. */ BitmapDescriptor point2 = BitmapDescriptorFactory.fromResource(R.drawable.point2_trajet); mMap.addMarker(new MarkerOptions().position(youAreHere).title("Point n°" + pointSuivant.getIdPoint()).icon(point2)); int padding = 17; mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(youAreHere, padding)); } public void onStatusChanged(String provider, int status, Bundle extras) { } public void onProviderEnabled(String provider) { } public void onProviderDisabled(String provider) { } }; /* Requête multiple, suivi de la géolocalisation */ androidLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 1, androidLocationListener); } } public void BoutonDroite(final double lat, final double lon) { /* Fonction qui crée une commande vocale "Droite" lors de l'appui sur le bouton. */ btnDroite.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CommandeVocale newCommande = null; try { /* Création d'une nouvelle commande vocale "Droite". */ newCommande = new CommandeVocale("D", lat, lon, MapsActivity.this); } catch (IOException e) { e.printStackTrace(); } /* Ajout à la liste des commandes du trajet.*/ listeCommandes.add(newCommande); /* Affichage d'un marqueur pour signifier l'emplacement associé à la commande. */ BitmapDescriptor pointX = BitmapDescriptorFactory.fromResource(R.drawable.diamond_green); mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lon)).title("Point n°" + pointSuivant.getIdPoint()).icon(pointX)); Toast.makeText(MapsActivity.this, "Bouton droite activé", Toast.LENGTH_SHORT).show(); } }); } public void BoutonGauche(final double lat, final double lon) { /* Fonction qui crée une commande vocale "Gauche" lors de l'appui sur le bouton. */ btnGauche.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CommandeVocale newCommande = null; try { /* Création d'une nouvelle commande vocale "Gauche". */ newCommande = new CommandeVocale("G", lat, lon, MapsActivity.this); } catch (IOException e) { e.printStackTrace(); } /* Ajout à la liste des commandes du trajet.*/ listeCommandes.add(newCommande); /* Affichage d'un marqueur pour signifier l'emplacement associé à la commande. */ BitmapDescriptor pointX = BitmapDescriptorFactory.fromResource(R.drawable.diamond_green); mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lon)).title("Point n°" + pointSuivant.getIdPoint()).icon(pointX)); Toast.makeText(MapsActivity.this, "Bouton gauche activé", Toast.LENGTH_SHORT).show(); } }); } public void BoutonHalte(final double lat, final double lon) { /* Fonction qui crée une commande vocale "Halte" lors de l'appui sur le bouton. */ btnHalte.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CommandeVocale newCommande = null; try { /* Création d'une nouvelle commande vocale "Gauche". */ newCommande = new CommandeVocale("H", lat, lon, MapsActivity.this); } catch (IOException e) { e.printStackTrace(); } /* Ajout à la liste des commandes du trajet.*/ listeCommandes.add(newCommande); /* Affichage d'un marqueur pour signifier l'emplacement associé à la commande. */ BitmapDescriptor pointX = BitmapDescriptorFactory.fromResource(R.drawable.diamond_green); mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lon)).title("Point n°" + pointSuivant.getIdPoint()).icon(pointX)); Toast.makeText(MapsActivity.this, "Bouton halte activé", Toast.LENGTH_SHORT).show(); } }); } public void BoutonAutre(final double lat, final double lon) { /* Fonction qui crée une commande vocale "Autre" lors de l'appui sur le bouton. */ btnAutre.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { /* Affichage des boutons associés à l'enregistrement d'une commande. */ btnGauche.setVisibility(View.INVISIBLE); btnDroite.setVisibility(View.INVISIBLE); btnHalte.setVisibility(View.INVISIBLE); btnAutre.setVisibility(View.INVISIBLE); btnEnreg.setVisibility(View.VISIBLE); btnStop.setVisibility(View.VISIBLE); btnJouer.setVisibility(View.VISIBLE); btnValide.setVisibility(View.VISIBLE); btnStop.setEnabled(false); btnJouer.setEnabled(false); btnValide.setEnabled(false); btnEnreg.setEnabled(true); btnStartRecord.setEnabled(false); /* La fonction Enregistrement() gère les étapes de l'enregistrement d'une nouvelle commande. */ Enregistrement(lat, lon); } }); } public void Enregistrement(final double lat, final double lon){ /* Fonction permettant d'enregistrer une nouvelle commande vocale et de l'associer à une géolocalisation. */ /* Démarrage de l'enregistrement de la commande. */ btnEnreg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { /* Vérification des permissions du téléphone en terme de microphone. */ if (checkPermission()) { /* Compteur du nombre d'enregistrement effectué. Autorisation de 3 enregistrements. */ ENREG_NB++; /* Désactivation de l'accessibilité à certains boutons. */ btnJouer.setEnabled(false); btnValide.setEnabled(false); /* Création du chemin où la commande sera enregistrée. */ Random random = new Random(); AudioSavePathInDevice = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + random + "Enregistrement" + idNewCommande + "AudioRecording.3gp"; Log.i("Chemin", "Le CHEMIN EST / " + AudioSavePathInDevice); idNewCommande++; /* La fonction MediaRecorderReady() prépare le téléphone à l'enregistrement. */ MediaRecorderReady(); try { /* Lancement de l'enregistrement. */ mediaRecorder.prepare(); mediaRecorder.start(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } /* Modification de l'accessibilité à certains boutons. */ btnEnreg.setEnabled(false); btnStop.setEnabled(true); Toast.makeText(MapsActivity.this, "Enregistrement démarré", Toast.LENGTH_LONG).show(); } /* Demande de permission d'accès au microphone si celle ci n'est pas accordée. */ else { requestPermission(); } } }); /* Arrêt de l'enregistrement de la commande. */ btnStop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { /* Arrêt de l'enregistreur. */ mediaRecorder.stop(); /* Modification de l'accessibilité à certains boutons. */ btnStop.setEnabled(false); btnJouer.setEnabled(true); btnEnreg.setEnabled(false); btnValide.setEnabled(false); Toast.makeText(MapsActivity.this, "Enregistrement terminé", Toast.LENGTH_LONG).show(); } }); /* Lecture de l'enregistrement pour vérification par l'utilisateur. */ btnJouer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) throws IllegalArgumentException, SecurityException, IllegalStateException { /* Si l'utilisateur a dépasser le nombre autorisé d'enregistrement, seul le bouton "Valider" sera disponible. */ if (ENREG_NB < 3) { /* Modification de l'accessibilité à certains boutons. */ btnStop.setEnabled(false); btnEnreg.setEnabled(true); btnValide.setEnabled(true); } /* Sinon, l'utilisateur pourra valider ou enregistrer à nouveau. */ else { /* Modification de l'accessibilité à certains boutons. */ btnStop.setEnabled(false); btnEnreg.setEnabled(false); btnValide.setEnabled(true); } /* Lecture de l'enregistrement. */ mediaPlayer = new MediaPlayer(); try { mediaPlayer.setDataSource(AudioSavePathInDevice); mediaPlayer.prepare(); } catch (IOException e) { e.printStackTrace(); } mediaPlayer.start(); Toast.makeText(MapsActivity.this, "Ecoute de l'enregistrement", Toast.LENGTH_LONG).show(); } }); /* Validation de l'enregistrement. */ btnValide.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { /* Confirmation à l'utilisateur que l'enregistrement a été pris en compte. */ MediaPlayer jouer = MediaPlayer.create(MapsActivity.this, R.raw.enreg_valid); jouer.start(); /* Création d'une commande vocale associée au nouvel enregistrement. */ CommandeVocale newCommande = null; try { newCommande = new CommandeVocale(AudioSavePathInDevice, lat, lon, MapsActivity.this); } catch (IOException e) { e.printStackTrace(); } /* Ajout à la liste des commandes du trajet.*/ listeCommandes.add(newCommande); /* Affichage d'un marqueur pour signifier l'emplacement associé à la commande. */ BitmapDescriptor pointX = BitmapDescriptorFactory.fromResource(R.drawable.diamond_green); mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lon)).title("Point n°" + pointSuivant.getIdPoint()).icon(pointX)); /* Affichage des boutons associés aux commandes pré-enregistrées. */ btnEnreg.setVisibility(View.INVISIBLE); btnStop.setVisibility(View.INVISIBLE); btnJouer.setVisibility(View.INVISIBLE); btnValide.setVisibility(View.INVISIBLE); btnGauche.setVisibility(View.VISIBLE); btnDroite.setVisibility(View.VISIBLE); btnHalte.setVisibility(View.VISIBLE); btnAutre.setVisibility(View.VISIBLE); btnGauche.setEnabled(true); btnDroite.setEnabled(true); btnAutre.setEnabled(true); btnHalte.setEnabled(true); btnStartRecord.setEnabled(true); } }); } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { /* Fonction qui vérifie que le téléphone possède bien les permissions en terme de localisation. */ switch (requestCode) { case REQUEST_CODE_UPDATE_LOCATION: if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { androidFirstLocation(); androidUpdateLocation(); } else { Toast.makeText(MapsActivity.this, "Permission refusée.", Toast.LENGTH_LONG).show(); } return; } switch (requestCode) { case RequestPermissionCode: if (grantResults.length> 0) { boolean StoragePermission = grantResults[0] == PackageManager.PERMISSION_GRANTED; boolean RecordPermission = grantResults[1] == PackageManager.PERMISSION_GRANTED; if (StoragePermission && RecordPermission) { Toast.makeText(MapsActivity.this, "Permission Granted", Toast.LENGTH_LONG).show(); } else { Toast.makeText(MapsActivity.this,"Permission Denied", Toast.LENGTH_LONG).show(); } } break; } } @Override protected void onPause() { /* Fonction qui stoppe les fonctions en cours en cas de changement d'orientation ou de fermeture de l'application. */ super.onPause(); if(androidLocationListener!=null) { if (androidLocationManager == null) { androidLocationManager = (LocationManager) this.getSystemService(MapsActivity.this.LOCATION_SERVICE); } androidLocationManager.removeUpdates(androidLocationListener); androidLocationManager=null; androidLocationListener=null; } } public void MediaRecorderReady(){ /* Fonction de préparation du téléphone à l'enregistrement d'une nouvelle commande. */ mediaRecorder=new MediaRecorder(); mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB); /* Choix du chemin de l'enregistrement. */ mediaRecorder.setOutputFile(AudioSavePathInDevice); } private void requestPermission() { /* Fonction qui demande à l'utilisateur la permission. */ ActivityCompat.requestPermissions(MapsActivity.this, new String[]{WRITE_EXTERNAL_STORAGE, RECORD_AUDIO}, RequestPermissionCode); } public boolean checkPermission() { /* Fonction qui vérifie les permissions. */ int result = ContextCompat.checkSelfPermission(getApplicationContext(), WRITE_EXTERNAL_STORAGE); int result1 = ContextCompat.checkSelfPermission(getApplicationContext(), RECORD_AUDIO); return result == PackageManager.PERMISSION_GRANTED && result1 == PackageManager.PERMISSION_GRANTED; } }
UTF-8
Java
27,943
java
MapsActivity.java
Java
[ { "context": "package com.example.solene.galidog;\n\nimport android.Manifest;\nimport android", "end": 26, "score": 0.9454995393753052, "start": 20, "tag": "USERNAME", "value": "solene" } ]
null
[]
package com.example.solene.galidog; import android.Manifest; import android.annotation.SuppressLint; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Color; import android.location.GpsSatellite; import android.location.GpsStatus; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.media.MediaPlayer; import android.media.MediaRecorder; import android.os.Environment; import android.support.v4.app.ActivityCompat; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import android.support.v4.content.ContextCompat; import android.util.Log; import android.view.Gravity; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptor; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.Polyline; import com.google.android.gms.maps.model.PolylineOptions; import java.io.IOException; import java.util.ArrayList; import java.util.Random; import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; import static android.Manifest.permission.RECORD_AUDIO; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { /* La classe MapsActivity gère l'enregistrement d'un trajet. */ /* Attributs nécessaires à l'utilisation d'une carte Google Maps, et à la géolocalisation. */ private GoogleMap mMap; private Button btnStartRecord; private LocationManager androidLocationManager; private LocationListener androidLocationListener; private final static int REQUEST_CODE_UPDATE_LOCATION = 42; /* Attributs correspondants aux différents boutons de l'activité : commandes pré enregistrées et enregistrement d'une nouvelle commande. */ private Button btnDroite, btnGauche, btnHalte, btnAutre; private Button btnEnreg, btnStop, btnJouer, btnValide; /* Attributs pour design de l'application. */ private PolylineOptions dessin = new PolylineOptions().width(9).color(Color.BLUE); private Polyline dessinTrajet; private ArrayList<LatLng> listeCoord = new ArrayList<>(); /* Attributs utiles au fonctionnement de l'algorithme. */ private Point pointSuivant; private ArrayList<Point> listePoints = new ArrayList<>(); private ArrayList<CommandeVocale> listeCommandes = new ArrayList<>(); /* Attributs nécessaire à la lecture et l'enregistrement de commandes vocales. */ String AudioSavePathInDevice = null; MediaRecorder mediaRecorder; private int idNewCommande = 0; public static final int RequestPermissionCode = 1; MediaPlayer mediaPlayer; private int ENREG_NB = 0; @Override protected void onCreate(Bundle savedInstanceState) { /* Fonction qui se lance à l'ouverture de l'activité d'enregistrement. */ super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps2); SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); mapFragment.getMapAsync(this); /* Association des boutons du layout à l'activité. Certains boutons (enregistrement d'une commande) sont pour l'instant invisibles à l'écran. */ btnStartRecord = (Button) findViewById(R.id.activity_main_btn_start_record); btnDroite = (Button) findViewById(R.id.activity_main_btn_droite); btnGauche = (Button) findViewById(R.id.activity_main_btn_gauche); btnHalte = (Button) findViewById(R.id.activity_main_btn_halte); btnAutre = (Button) findViewById(R.id.activity_main_btn_autre); btnEnreg = (Button) findViewById(R.id.activity_main_btn_enreg); btnStop = (Button) findViewById(R.id.activity_main_btn_stop); btnJouer = (Button) findViewById(R.id.activity_main_btn_jouer); btnValide = (Button) findViewById(R.id.activity_main_btn_valide); btnEnreg.setVisibility(View.INVISIBLE); btnStop.setVisibility(View.INVISIBLE); btnJouer.setVisibility(View.INVISIBLE); btnValide.setVisibility(View.INVISIBLE); } @Override public void onMapReady(GoogleMap googleMap) { /* Fonction qui se lance lorsque la carte Google Maps est prête. */ mMap = googleMap; /* Initialisation du trajet dessiné */ dessinTrajet = mMap.addPolyline(dessin); /* La fonction androidFirstLocation() affiche la localisation de l'utilisateur à son entrée dans l'activité MapsActivity. */ androidFirstLocation(); /* Démarrage de l'enregistrement */ btnStartRecord.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast toast = Toast.makeText(MapsActivity.this, "L'enregistrement démarre", Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); /*La fonction androidUpdateLocation() enregistre les points du trajet et les commandes vocales associées. */ androidUpdateLocation(); btnStartRecord.setText("Arrêter l'enregistrement"); /* Arrêt de l'enregistrement */ btnStartRecord.setOnClickListener((new View.OnClickListener() { @Override public void onClick(View v) { onPause(); Toast.makeText(MapsActivity.this, "Fin de l'enregistrement", Toast.LENGTH_SHORT).show(); btnStartRecord.setText("Retour à l'accueil"); /* Retour à la page d'accueil, avec envoi des données enregistrées. */ btnStartRecord.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent retourAccueil = new Intent(MapsActivity.this, MainActivity.class); retourAccueil.putParcelableArrayListExtra("commandes", listeCommandes); retourAccueil.putParcelableArrayListExtra("points", listePoints); startActivity(retourAccueil); } }); } })); } }); } public void androidFirstLocation() { /* Fonction qui affiche la géolocalisation de l'utilisateur lorsqu'il arrive pour la première fois sur la page. */ /* Vérification des permissions du téléphone en terme de géolocalisation. */ if (ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions( MapsActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE_UPDATE_LOCATION); } /* Si les permissions sont accordées, mise en place de l'enregistrement. */ else { androidLocationManager = (LocationManager) this.getSystemService(MapsActivity.this.LOCATION_SERVICE); androidLocationListener = new LocationListener() { public void onLocationChanged(Location loc) { /* Récupération des coordonnées actuelles */ double latNow = loc.getLatitude(); double lonNow = loc.getLongitude(); Toast.makeText(MapsActivity.this, "Coordonnées : " + latNow + " / " + lonNow, Toast.LENGTH_SHORT).show(); /* Ajout du point à la liste des points visités. */ LatLng youAreHere = new LatLng(latNow, lonNow); Point newPoint = new Point(latNow, lonNow); listePoints.add(newPoint); /* Démarrage du tracé du trajet. */ listeCoord.add(new LatLng(latNow,lonNow)); dessinTrajet.setPoints(listeCoord); /* Affichage d'un marqueur à l'emplacement de l'utilisateur. */ BitmapDescriptor point1 = BitmapDescriptorFactory.fromResource(R.drawable.point2_init); mMap.addMarker(new MarkerOptions().position(youAreHere).title("Vous êtes ici").icon(point1)); int padding = 17; mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(youAreHere, padding)); } public void onStatusChanged(String provider, int status, Bundle extras) { } public void onProviderEnabled(String provider) { } public void onProviderDisabled(String provider) { } }; /* Requête unique (première géolocalisation) */ androidLocationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, androidLocationListener, null); } } public void androidUpdateLocation() { /* Fonction qui enregistre les différentes positions d'un utilisateur en mouvement, les affiche et les associe aux commandes vocales. */ /* Vérification des permissions du téléphone en terme de géolocalisation. */ if (ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions( MapsActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE_UPDATE_LOCATION); } /* Si les permissions sont accordées, mise en place de l'enregistrement. */ else { androidLocationManager = (LocationManager) this.getSystemService(MapsActivity.this.LOCATION_SERVICE); androidLocationListener = new LocationListener() { public void onLocationChanged(Location loc) { /* Récupération des coordonnées actuelles */ double latNow = loc.getLatitude(); double lonNow = loc.getLongitude(); LatLng youAreHere = new LatLng(latNow, lonNow); /* Création d'une potentielle commande vocale, associé à la localisation actuelle */ BoutonDroite(latNow, lonNow); BoutonGauche(latNow, lonNow); BoutonHalte(latNow, lonNow); BoutonAutre(latNow, lonNow); /* Ajout du point à la liste des points visités. */ pointSuivant = new Point(latNow, lonNow); listePoints.add(pointSuivant); /* Actualisation du tracé du trajet. */ listeCoord.add(new LatLng(latNow,lonNow)); dessinTrajet.setPoints(listeCoord); /* Affichage d'un message lors du premier point enregistré. */ if (pointSuivant.getIdPoint() == 1) { Toast.makeText(MapsActivity.this, "Trace en cours ", Toast.LENGTH_SHORT).show(); } /* Affichage d'un marqueur à l'emplacement de l'utilisateur. */ BitmapDescriptor point2 = BitmapDescriptorFactory.fromResource(R.drawable.point2_trajet); mMap.addMarker(new MarkerOptions().position(youAreHere).title("Point n°" + pointSuivant.getIdPoint()).icon(point2)); int padding = 17; mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(youAreHere, padding)); } public void onStatusChanged(String provider, int status, Bundle extras) { } public void onProviderEnabled(String provider) { } public void onProviderDisabled(String provider) { } }; /* Requête multiple, suivi de la géolocalisation */ androidLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 1, androidLocationListener); } } public void BoutonDroite(final double lat, final double lon) { /* Fonction qui crée une commande vocale "Droite" lors de l'appui sur le bouton. */ btnDroite.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CommandeVocale newCommande = null; try { /* Création d'une nouvelle commande vocale "Droite". */ newCommande = new CommandeVocale("D", lat, lon, MapsActivity.this); } catch (IOException e) { e.printStackTrace(); } /* Ajout à la liste des commandes du trajet.*/ listeCommandes.add(newCommande); /* Affichage d'un marqueur pour signifier l'emplacement associé à la commande. */ BitmapDescriptor pointX = BitmapDescriptorFactory.fromResource(R.drawable.diamond_green); mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lon)).title("Point n°" + pointSuivant.getIdPoint()).icon(pointX)); Toast.makeText(MapsActivity.this, "Bouton droite activé", Toast.LENGTH_SHORT).show(); } }); } public void BoutonGauche(final double lat, final double lon) { /* Fonction qui crée une commande vocale "Gauche" lors de l'appui sur le bouton. */ btnGauche.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CommandeVocale newCommande = null; try { /* Création d'une nouvelle commande vocale "Gauche". */ newCommande = new CommandeVocale("G", lat, lon, MapsActivity.this); } catch (IOException e) { e.printStackTrace(); } /* Ajout à la liste des commandes du trajet.*/ listeCommandes.add(newCommande); /* Affichage d'un marqueur pour signifier l'emplacement associé à la commande. */ BitmapDescriptor pointX = BitmapDescriptorFactory.fromResource(R.drawable.diamond_green); mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lon)).title("Point n°" + pointSuivant.getIdPoint()).icon(pointX)); Toast.makeText(MapsActivity.this, "Bouton gauche activé", Toast.LENGTH_SHORT).show(); } }); } public void BoutonHalte(final double lat, final double lon) { /* Fonction qui crée une commande vocale "Halte" lors de l'appui sur le bouton. */ btnHalte.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CommandeVocale newCommande = null; try { /* Création d'une nouvelle commande vocale "Gauche". */ newCommande = new CommandeVocale("H", lat, lon, MapsActivity.this); } catch (IOException e) { e.printStackTrace(); } /* Ajout à la liste des commandes du trajet.*/ listeCommandes.add(newCommande); /* Affichage d'un marqueur pour signifier l'emplacement associé à la commande. */ BitmapDescriptor pointX = BitmapDescriptorFactory.fromResource(R.drawable.diamond_green); mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lon)).title("Point n°" + pointSuivant.getIdPoint()).icon(pointX)); Toast.makeText(MapsActivity.this, "Bouton halte activé", Toast.LENGTH_SHORT).show(); } }); } public void BoutonAutre(final double lat, final double lon) { /* Fonction qui crée une commande vocale "Autre" lors de l'appui sur le bouton. */ btnAutre.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { /* Affichage des boutons associés à l'enregistrement d'une commande. */ btnGauche.setVisibility(View.INVISIBLE); btnDroite.setVisibility(View.INVISIBLE); btnHalte.setVisibility(View.INVISIBLE); btnAutre.setVisibility(View.INVISIBLE); btnEnreg.setVisibility(View.VISIBLE); btnStop.setVisibility(View.VISIBLE); btnJouer.setVisibility(View.VISIBLE); btnValide.setVisibility(View.VISIBLE); btnStop.setEnabled(false); btnJouer.setEnabled(false); btnValide.setEnabled(false); btnEnreg.setEnabled(true); btnStartRecord.setEnabled(false); /* La fonction Enregistrement() gère les étapes de l'enregistrement d'une nouvelle commande. */ Enregistrement(lat, lon); } }); } public void Enregistrement(final double lat, final double lon){ /* Fonction permettant d'enregistrer une nouvelle commande vocale et de l'associer à une géolocalisation. */ /* Démarrage de l'enregistrement de la commande. */ btnEnreg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { /* Vérification des permissions du téléphone en terme de microphone. */ if (checkPermission()) { /* Compteur du nombre d'enregistrement effectué. Autorisation de 3 enregistrements. */ ENREG_NB++; /* Désactivation de l'accessibilité à certains boutons. */ btnJouer.setEnabled(false); btnValide.setEnabled(false); /* Création du chemin où la commande sera enregistrée. */ Random random = new Random(); AudioSavePathInDevice = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + random + "Enregistrement" + idNewCommande + "AudioRecording.3gp"; Log.i("Chemin", "Le CHEMIN EST / " + AudioSavePathInDevice); idNewCommande++; /* La fonction MediaRecorderReady() prépare le téléphone à l'enregistrement. */ MediaRecorderReady(); try { /* Lancement de l'enregistrement. */ mediaRecorder.prepare(); mediaRecorder.start(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } /* Modification de l'accessibilité à certains boutons. */ btnEnreg.setEnabled(false); btnStop.setEnabled(true); Toast.makeText(MapsActivity.this, "Enregistrement démarré", Toast.LENGTH_LONG).show(); } /* Demande de permission d'accès au microphone si celle ci n'est pas accordée. */ else { requestPermission(); } } }); /* Arrêt de l'enregistrement de la commande. */ btnStop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { /* Arrêt de l'enregistreur. */ mediaRecorder.stop(); /* Modification de l'accessibilité à certains boutons. */ btnStop.setEnabled(false); btnJouer.setEnabled(true); btnEnreg.setEnabled(false); btnValide.setEnabled(false); Toast.makeText(MapsActivity.this, "Enregistrement terminé", Toast.LENGTH_LONG).show(); } }); /* Lecture de l'enregistrement pour vérification par l'utilisateur. */ btnJouer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) throws IllegalArgumentException, SecurityException, IllegalStateException { /* Si l'utilisateur a dépasser le nombre autorisé d'enregistrement, seul le bouton "Valider" sera disponible. */ if (ENREG_NB < 3) { /* Modification de l'accessibilité à certains boutons. */ btnStop.setEnabled(false); btnEnreg.setEnabled(true); btnValide.setEnabled(true); } /* Sinon, l'utilisateur pourra valider ou enregistrer à nouveau. */ else { /* Modification de l'accessibilité à certains boutons. */ btnStop.setEnabled(false); btnEnreg.setEnabled(false); btnValide.setEnabled(true); } /* Lecture de l'enregistrement. */ mediaPlayer = new MediaPlayer(); try { mediaPlayer.setDataSource(AudioSavePathInDevice); mediaPlayer.prepare(); } catch (IOException e) { e.printStackTrace(); } mediaPlayer.start(); Toast.makeText(MapsActivity.this, "Ecoute de l'enregistrement", Toast.LENGTH_LONG).show(); } }); /* Validation de l'enregistrement. */ btnValide.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { /* Confirmation à l'utilisateur que l'enregistrement a été pris en compte. */ MediaPlayer jouer = MediaPlayer.create(MapsActivity.this, R.raw.enreg_valid); jouer.start(); /* Création d'une commande vocale associée au nouvel enregistrement. */ CommandeVocale newCommande = null; try { newCommande = new CommandeVocale(AudioSavePathInDevice, lat, lon, MapsActivity.this); } catch (IOException e) { e.printStackTrace(); } /* Ajout à la liste des commandes du trajet.*/ listeCommandes.add(newCommande); /* Affichage d'un marqueur pour signifier l'emplacement associé à la commande. */ BitmapDescriptor pointX = BitmapDescriptorFactory.fromResource(R.drawable.diamond_green); mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lon)).title("Point n°" + pointSuivant.getIdPoint()).icon(pointX)); /* Affichage des boutons associés aux commandes pré-enregistrées. */ btnEnreg.setVisibility(View.INVISIBLE); btnStop.setVisibility(View.INVISIBLE); btnJouer.setVisibility(View.INVISIBLE); btnValide.setVisibility(View.INVISIBLE); btnGauche.setVisibility(View.VISIBLE); btnDroite.setVisibility(View.VISIBLE); btnHalte.setVisibility(View.VISIBLE); btnAutre.setVisibility(View.VISIBLE); btnGauche.setEnabled(true); btnDroite.setEnabled(true); btnAutre.setEnabled(true); btnHalte.setEnabled(true); btnStartRecord.setEnabled(true); } }); } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { /* Fonction qui vérifie que le téléphone possède bien les permissions en terme de localisation. */ switch (requestCode) { case REQUEST_CODE_UPDATE_LOCATION: if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { androidFirstLocation(); androidUpdateLocation(); } else { Toast.makeText(MapsActivity.this, "Permission refusée.", Toast.LENGTH_LONG).show(); } return; } switch (requestCode) { case RequestPermissionCode: if (grantResults.length> 0) { boolean StoragePermission = grantResults[0] == PackageManager.PERMISSION_GRANTED; boolean RecordPermission = grantResults[1] == PackageManager.PERMISSION_GRANTED; if (StoragePermission && RecordPermission) { Toast.makeText(MapsActivity.this, "Permission Granted", Toast.LENGTH_LONG).show(); } else { Toast.makeText(MapsActivity.this,"Permission Denied", Toast.LENGTH_LONG).show(); } } break; } } @Override protected void onPause() { /* Fonction qui stoppe les fonctions en cours en cas de changement d'orientation ou de fermeture de l'application. */ super.onPause(); if(androidLocationListener!=null) { if (androidLocationManager == null) { androidLocationManager = (LocationManager) this.getSystemService(MapsActivity.this.LOCATION_SERVICE); } androidLocationManager.removeUpdates(androidLocationListener); androidLocationManager=null; androidLocationListener=null; } } public void MediaRecorderReady(){ /* Fonction de préparation du téléphone à l'enregistrement d'une nouvelle commande. */ mediaRecorder=new MediaRecorder(); mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB); /* Choix du chemin de l'enregistrement. */ mediaRecorder.setOutputFile(AudioSavePathInDevice); } private void requestPermission() { /* Fonction qui demande à l'utilisateur la permission. */ ActivityCompat.requestPermissions(MapsActivity.this, new String[]{WRITE_EXTERNAL_STORAGE, RECORD_AUDIO}, RequestPermissionCode); } public boolean checkPermission() { /* Fonction qui vérifie les permissions. */ int result = ContextCompat.checkSelfPermission(getApplicationContext(), WRITE_EXTERNAL_STORAGE); int result1 = ContextCompat.checkSelfPermission(getApplicationContext(), RECORD_AUDIO); return result == PackageManager.PERMISSION_GRANTED && result1 == PackageManager.PERMISSION_GRANTED; } }
27,943
0.595998
0.594667
642
42.281933
34.063026
143
false
false
0
0
0
0
0
0
0.55296
false
false
4
2b19277d6c6d61d8759ff6743c6dd605663b973a
33,517,924,836,758
47f007d6366dac53b49116d7e0440834a2dee203
/src/CompositePattern/StrongJunior.java
5dc14e1fb932223813bf5c4fa5904d7544a7f9d1
[]
no_license
Aiqwf/Desing-Patterns
https://github.com/Aiqwf/Desing-Patterns
71aaebd95dad29bf3eca942732e332adf7027af3
a07ce3913cf06a9c605982e22d71804869c0bea2
refs/heads/master
2023-09-03T06:57:20.409000
2021-10-28T14:43:37
2021-10-28T14:43:37
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package CompositePattern; public class StrongJunior extends Junior{ private String id; public void setId(String id) { this.id = id; } public String getId() { return id; } public StrongJunior(double salary){ setTitle("sj"); setSalary(salary); } @Override public double getSalary() { return 0; } @Override public String getTitle() { return super.getTitle(); } @Override public String toString() { return "StrongJunior{" + "title='" + title + '\'' + ", salary=" + salary + ", child=" + child + '}' +" id are : "+getId(); } }
UTF-8
Java
713
java
StrongJunior.java
Java
[]
null
[]
package CompositePattern; public class StrongJunior extends Junior{ private String id; public void setId(String id) { this.id = id; } public String getId() { return id; } public StrongJunior(double salary){ setTitle("sj"); setSalary(salary); } @Override public double getSalary() { return 0; } @Override public String getTitle() { return super.getTitle(); } @Override public String toString() { return "StrongJunior{" + "title='" + title + '\'' + ", salary=" + salary + ", child=" + child + '}' +" id are : "+getId(); } }
713
0.499299
0.497896
37
18.270269
14.663153
43
false
false
0
0
0
0
0
0
0.297297
false
false
4
7f865c96e63721bb5bc5469290b0c057398a7483
13,331,578,537,187
5e014279f7c08fc6a108808c09d1f3f11a4bd859
/aoj/2253/Main.java
70a743afb2200c61d7b95c6e4402ef3ec2015e97
[]
no_license
Goryudyuma/java-work
https://github.com/Goryudyuma/java-work
d0ed58714ccdb8ceb3cfcd238513d2742f2ae03a
3b6afe8a083899e7794b4c8143338df69cb51de4
refs/heads/master
2021-03-08T20:37:37.812000
2019-05-29T13:25:59
2019-05-29T13:25:59
50,090,060
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.*; class Main { public static int map[][]; public static int t, n; public static int dx[] = {0,1,1,0,-1,-1}; public static int dy[] = {1,1,0,-1,-1,0}; public static void main(String args[]) { Scanner sc = new Scanner(System.in); while (true) { t = sc.nextInt(); n = sc.nextInt(); if (t == 0 && n ==0) { break; } map = new int[1000][1000]; for (int i = 0; i < 1000; i++) { for (int j = 0; j < 1000; j++) { map[i][j] = 1 << 30; } } for (int i = 0; i < n; i++) { map[sc.nextInt() + 500][sc.nextInt() + 500] = -1; } Queue<Integer[]> que = new ArrayDeque<Integer[]>(); int nx = sc.nextInt() + 500; int ny = sc.nextInt() + 500; que.add(new Integer[]{nx, ny}); map[nx][ny] = 0; while (que.size()!=0) { Integer[] now = que.poll(); int x = now[0]; int y = now[1]; if (map[x][y] >= t) { continue; } for (int i = 0; i < 6; i++) { if (map[x + dx[i]][y + dy[i]] > map[x][y] + 1) { map[x + dx[i]][y + dy[i]] = map[x][y] + 1; que.add(new Integer[]{x + dx[i],y + dy[i]}); } } } int ans = 0; for (int i = 0; i < 1000; i++) { for (int j = 0; j < 1000; j++) { if (map[i][j] >= 0 && map[i][j] != 1 << 30) { ans++; } } } System.out.println(ans); } } }
UTF-8
Java
1,325
java
Main.java
Java
[]
null
[]
import java.util.*; class Main { public static int map[][]; public static int t, n; public static int dx[] = {0,1,1,0,-1,-1}; public static int dy[] = {1,1,0,-1,-1,0}; public static void main(String args[]) { Scanner sc = new Scanner(System.in); while (true) { t = sc.nextInt(); n = sc.nextInt(); if (t == 0 && n ==0) { break; } map = new int[1000][1000]; for (int i = 0; i < 1000; i++) { for (int j = 0; j < 1000; j++) { map[i][j] = 1 << 30; } } for (int i = 0; i < n; i++) { map[sc.nextInt() + 500][sc.nextInt() + 500] = -1; } Queue<Integer[]> que = new ArrayDeque<Integer[]>(); int nx = sc.nextInt() + 500; int ny = sc.nextInt() + 500; que.add(new Integer[]{nx, ny}); map[nx][ny] = 0; while (que.size()!=0) { Integer[] now = que.poll(); int x = now[0]; int y = now[1]; if (map[x][y] >= t) { continue; } for (int i = 0; i < 6; i++) { if (map[x + dx[i]][y + dy[i]] > map[x][y] + 1) { map[x + dx[i]][y + dy[i]] = map[x][y] + 1; que.add(new Integer[]{x + dx[i],y + dy[i]}); } } } int ans = 0; for (int i = 0; i < 1000; i++) { for (int j = 0; j < 1000; j++) { if (map[i][j] >= 0 && map[i][j] != 1 << 30) { ans++; } } } System.out.println(ans); } } }
1,325
0.449811
0.395472
57
22.245613
15.94869
54
false
false
0
0
0
0
0
0
3.947368
false
false
4
577eb38d18db2f1f5b9ce56efb22e1cec963c765
25,383,256,744,407
8820d16dcadee237c689006fb42c2b50e68316f7
/study-core/src/main/java/org/solovyev/study/model/db/SQLBuilder.java
bb62028063223d20976cb0119fa56df2c4adeb5e
[ "Apache-2.0" ]
permissive
serso/study
https://github.com/serso/study
fe64c8fd4164c1ad8501e610fa3378d0d14cb5c7
d2aae1a29aa427ffb23753a5bbc10c9229f046a5
refs/heads/master
2021-01-13T14:20:45.247000
2014-02-28T09:02:29
2014-02-28T09:02:29
1,341,216
2
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright (c) 2009-2010. Created by serso. * * For more information, please, contact serso1988@gmail.com. */ package org.solovyev.study.model.db; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.solovyev.common.collections.LoopData; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import java.util.Collection; /** * User: serso * Date: Apr 5, 2010 * Time: 2:55:50 AM */ public class SQLBuilder { private StringBuilder sql = new StringBuilder(); private int count = 0; public SQLBuilder() { } public SQLBuilder in(@NotNull String tableAlias, @NotNull String columnName, @NotNull Collection c, @NotNull MapSqlParameterSource sqlParameterSource, @NotNull String emptyValue) { sql.append("and").append(" ").append(tableAlias).append(".").append(columnName).append(" "); sql.append("in ('").append(emptyValue).append("'"); String el; LoopData ld = new LoopData(c); for (Object o : c) { sql.append(", "); el = columnName + "_" + ld.getIndex(); sql.append(":").append(el); sqlParameterSource.addValue(el, String.valueOf(o)); ld.next(); } sql.append(") "); return this; } public final static String escape = "\\"; public SQLBuilder like(@NotNull String field, @NotNull String valueName, boolean ignoreCase) { sql.append(" "); if (ignoreCase) { sql.append("upper(").append(field).append(") "); } else { sql.append(field).append(" "); } sql.append("like "); if (ignoreCase) { sql.append("upper(:").append(valueName).append(") "); } else { sql.append(":").append(valueName).append(" "); } sql.append("escape \'" + escape + escape + "\' "); return this; } @NotNull public static String prepareLikeValue(@NotNull String source) { final StringBuilder sb = new StringBuilder(); //if source string doesn't start with wildcard - let's add it to result string if (!source.startsWith("*") && !source.startsWith("?")) { sb.append("%"); } //process screen and replacing human-oriented wildcard with sql wildcard sb.append(screen(source).replace('?', '_').replace('*', '%')); //if source string doesn't end with wildcard - let's add it to result string if (!source.endsWith("*") && !source.endsWith("?")) { sb.append("%"); } return sb.toString(); } @NotNull public static String screen(@NotNull String source) { return screen(screen(source, "_", escape), "%", escape); } @NotNull private static String screen(@NotNull String source, @NotNull String ch, @NotNull String shield) { String[] parts = source.split(ch, -1); StringBuilder sb = new StringBuilder(); if (parts != null) { LoopData loopData = new LoopData(parts); for (String part : parts) { if (!loopData.isFirstAndNext()) { sb.append(shield).append(ch).append(part); } else { sb.append(part); } } } return sb.toString(); } @NotNull public SQLBuilder columns(@Nullable String tableAlias, @NotNull Enum[] enumeration) { LoopData ld = new LoopData(enumeration); for (Enum anEnum : enumeration) { if (tableAlias != null) { sql.append(tableAlias).append("."); } sql.append(anEnum); if (!ld.isLastAndNext()) { sql.append(", "); } else { sql.append(" "); } } return this; } @NotNull public SQLBuilder tables(@NotNull String databaseName, @NotNull String tableName) { return tables(databaseName, tableName, null); } @NotNull public SQLBuilder tables(@NotNull String databaseName, @NotNull String tableName, @Nullable String tableAlias) { sql.append(databaseName).append(".").append(tableName).append(" "); if (tableAlias != null) { sql.append(tableAlias).append(" "); } return this; } @NotNull public SQLBuilder delete() { sql.append("delete "); return this; } @NotNull public SQLBuilder select() { sql.append("select "); return this; } @NotNull public SQLBuilder where() { sql.append("where 1=1 "); return this; } @NotNull public SQLBuilder from() { sql.append("from "); return this; } @NotNull public SQLBuilder exists() { sql.append("and exists "); return this; } @NotNull public SQLBuilder equalsCondition(@Nullable String tableAlias, @NotNull String column, @Nullable Object parameter, @NotNull MapSqlParameterSource sqlParameterSource) { return equalsCondition(true, tableAlias, column, parameter, sqlParameterSource); } @NotNull public SQLBuilder equalsCondition(boolean strict, @Nullable String tableAlias, @NotNull String column, @Nullable Object parameter, @NotNull MapSqlParameterSource sqlParameterSource) { sql.append("and "); return commonEqualsCondition(strict, tableAlias, column, parameter, sqlParameterSource); } @NotNull public SQLBuilder equalsConditionForUpdate(@Nullable String tableAlias, @NotNull String column, @Nullable Object parameter, @NotNull MapSqlParameterSource sqlParameterSource) { return commonEqualsCondition(true, tableAlias, column, parameter, sqlParameterSource); } private SQLBuilder commonEqualsCondition(boolean strict, @Nullable String tableAlias, @NotNull String column, @Nullable Object parameter, @NotNull MapSqlParameterSource sqlParameterSource) { if (strict) { if (tableAlias != null) { sql.append(tableAlias).append("."); } sql.append(column).append(" = :").append(column).append(" "); sqlParameterSource.addValue(column, parameter); } else { if (tableAlias != null) { sql.append(tableAlias).append("."); } sql.append(column).append(" like :").append(column).append(" "); if (parameter != null) { sqlParameterSource.addValue(column, SQLBuilder.prepareLikeValue(String.valueOf(parameter))); } else { sqlParameterSource.addValue(column, parameter); } } return this; } public SQLBuilder addUpdatedValue(@Nullable String tableAlias, @NotNull String column, @Nullable Object parameter, @NotNull MapSqlParameterSource sqlParameterSource) { if (tableAlias != null) { sql.append(tableAlias).append("."); } sql.append(column).append(" = :").append(column); sqlParameterSource.addValue(column, parameter); return this; } public SQLBuilder append(@Nullable String s) { if (s != null) { sql.append(s); } return this; } public SQLBuilder append(@Nullable SQLBuilder sqlBuilder) { if (sqlBuilder != null) { sql.append(sqlBuilder.toString()); } return this; } @NotNull public SQLBuilder allColumns() { sql.append("* "); return this; } @NotNull public SQLBuilder equalsCondition(@NotNull String leftTableAlias, @NotNull String leftColumn, @NotNull String rightTableAlias, @NotNull String rightColumn) { sql.append("and ").append(leftTableAlias).append(".").append(leftColumn).append("=").append(rightTableAlias).append(".").append(rightColumn).append(" "); return this; } @NotNull public StringBuilder getSql() { return sql; } @NotNull @Override public String toString() { return sql.toString(); } public SQLBuilder update() { sql.append("update "); return this; } public SQLBuilder set() { sql.append("set "); return this; } public SQLBuilder comma() { sql.append(", "); return this; } public SQLBuilder insertInto() { sql.append("insert into "); return this; } public SQLBuilder values() { sql.append("values "); return this; } public SQLBuilder addValue(@Nullable Object parameter, @NotNull MapSqlParameterSource sqlParameterSource) { String paramName = "parameter_" + getCount(); sql.append(":").append(paramName).append(" "); sqlParameterSource.addValue(paramName, parameter); return this; } public int getCount() { return count++; } }
UTF-8
Java
7,655
java
SQLBuilder.java
Java
[ { "context": "/*\n * Copyright (c) 2009-2010. Created by serso.\n *\n * For more information, please, contact sers", "end": 47, "score": 0.8533463478088379, "start": 42, "tag": "NAME", "value": "serso" }, { "context": "serso.\n *\n * For more information, please, contact serso1988@gmail.com.\n */\n\npackage org.solovyev.study.model.db;\n\nimpor", "end": 112, "score": 0.9999191164970398, "start": 93, "tag": "EMAIL", "value": "serso1988@gmail.com" }, { "context": "ource;\n\nimport java.util.Collection;\n\n/**\n * User: serso\n * Date: Apr 5, 2010\n * Time: 2:55:50 AM\n */\npubl", "end": 411, "score": 0.9991466403007507, "start": 406, "tag": "USERNAME", "value": "serso" } ]
null
[]
/* * Copyright (c) 2009-2010. Created by serso. * * For more information, please, contact <EMAIL>. */ package org.solovyev.study.model.db; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.solovyev.common.collections.LoopData; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import java.util.Collection; /** * User: serso * Date: Apr 5, 2010 * Time: 2:55:50 AM */ public class SQLBuilder { private StringBuilder sql = new StringBuilder(); private int count = 0; public SQLBuilder() { } public SQLBuilder in(@NotNull String tableAlias, @NotNull String columnName, @NotNull Collection c, @NotNull MapSqlParameterSource sqlParameterSource, @NotNull String emptyValue) { sql.append("and").append(" ").append(tableAlias).append(".").append(columnName).append(" "); sql.append("in ('").append(emptyValue).append("'"); String el; LoopData ld = new LoopData(c); for (Object o : c) { sql.append(", "); el = columnName + "_" + ld.getIndex(); sql.append(":").append(el); sqlParameterSource.addValue(el, String.valueOf(o)); ld.next(); } sql.append(") "); return this; } public final static String escape = "\\"; public SQLBuilder like(@NotNull String field, @NotNull String valueName, boolean ignoreCase) { sql.append(" "); if (ignoreCase) { sql.append("upper(").append(field).append(") "); } else { sql.append(field).append(" "); } sql.append("like "); if (ignoreCase) { sql.append("upper(:").append(valueName).append(") "); } else { sql.append(":").append(valueName).append(" "); } sql.append("escape \'" + escape + escape + "\' "); return this; } @NotNull public static String prepareLikeValue(@NotNull String source) { final StringBuilder sb = new StringBuilder(); //if source string doesn't start with wildcard - let's add it to result string if (!source.startsWith("*") && !source.startsWith("?")) { sb.append("%"); } //process screen and replacing human-oriented wildcard with sql wildcard sb.append(screen(source).replace('?', '_').replace('*', '%')); //if source string doesn't end with wildcard - let's add it to result string if (!source.endsWith("*") && !source.endsWith("?")) { sb.append("%"); } return sb.toString(); } @NotNull public static String screen(@NotNull String source) { return screen(screen(source, "_", escape), "%", escape); } @NotNull private static String screen(@NotNull String source, @NotNull String ch, @NotNull String shield) { String[] parts = source.split(ch, -1); StringBuilder sb = new StringBuilder(); if (parts != null) { LoopData loopData = new LoopData(parts); for (String part : parts) { if (!loopData.isFirstAndNext()) { sb.append(shield).append(ch).append(part); } else { sb.append(part); } } } return sb.toString(); } @NotNull public SQLBuilder columns(@Nullable String tableAlias, @NotNull Enum[] enumeration) { LoopData ld = new LoopData(enumeration); for (Enum anEnum : enumeration) { if (tableAlias != null) { sql.append(tableAlias).append("."); } sql.append(anEnum); if (!ld.isLastAndNext()) { sql.append(", "); } else { sql.append(" "); } } return this; } @NotNull public SQLBuilder tables(@NotNull String databaseName, @NotNull String tableName) { return tables(databaseName, tableName, null); } @NotNull public SQLBuilder tables(@NotNull String databaseName, @NotNull String tableName, @Nullable String tableAlias) { sql.append(databaseName).append(".").append(tableName).append(" "); if (tableAlias != null) { sql.append(tableAlias).append(" "); } return this; } @NotNull public SQLBuilder delete() { sql.append("delete "); return this; } @NotNull public SQLBuilder select() { sql.append("select "); return this; } @NotNull public SQLBuilder where() { sql.append("where 1=1 "); return this; } @NotNull public SQLBuilder from() { sql.append("from "); return this; } @NotNull public SQLBuilder exists() { sql.append("and exists "); return this; } @NotNull public SQLBuilder equalsCondition(@Nullable String tableAlias, @NotNull String column, @Nullable Object parameter, @NotNull MapSqlParameterSource sqlParameterSource) { return equalsCondition(true, tableAlias, column, parameter, sqlParameterSource); } @NotNull public SQLBuilder equalsCondition(boolean strict, @Nullable String tableAlias, @NotNull String column, @Nullable Object parameter, @NotNull MapSqlParameterSource sqlParameterSource) { sql.append("and "); return commonEqualsCondition(strict, tableAlias, column, parameter, sqlParameterSource); } @NotNull public SQLBuilder equalsConditionForUpdate(@Nullable String tableAlias, @NotNull String column, @Nullable Object parameter, @NotNull MapSqlParameterSource sqlParameterSource) { return commonEqualsCondition(true, tableAlias, column, parameter, sqlParameterSource); } private SQLBuilder commonEqualsCondition(boolean strict, @Nullable String tableAlias, @NotNull String column, @Nullable Object parameter, @NotNull MapSqlParameterSource sqlParameterSource) { if (strict) { if (tableAlias != null) { sql.append(tableAlias).append("."); } sql.append(column).append(" = :").append(column).append(" "); sqlParameterSource.addValue(column, parameter); } else { if (tableAlias != null) { sql.append(tableAlias).append("."); } sql.append(column).append(" like :").append(column).append(" "); if (parameter != null) { sqlParameterSource.addValue(column, SQLBuilder.prepareLikeValue(String.valueOf(parameter))); } else { sqlParameterSource.addValue(column, parameter); } } return this; } public SQLBuilder addUpdatedValue(@Nullable String tableAlias, @NotNull String column, @Nullable Object parameter, @NotNull MapSqlParameterSource sqlParameterSource) { if (tableAlias != null) { sql.append(tableAlias).append("."); } sql.append(column).append(" = :").append(column); sqlParameterSource.addValue(column, parameter); return this; } public SQLBuilder append(@Nullable String s) { if (s != null) { sql.append(s); } return this; } public SQLBuilder append(@Nullable SQLBuilder sqlBuilder) { if (sqlBuilder != null) { sql.append(sqlBuilder.toString()); } return this; } @NotNull public SQLBuilder allColumns() { sql.append("* "); return this; } @NotNull public SQLBuilder equalsCondition(@NotNull String leftTableAlias, @NotNull String leftColumn, @NotNull String rightTableAlias, @NotNull String rightColumn) { sql.append("and ").append(leftTableAlias).append(".").append(leftColumn).append("=").append(rightTableAlias).append(".").append(rightColumn).append(" "); return this; } @NotNull public StringBuilder getSql() { return sql; } @NotNull @Override public String toString() { return sql.toString(); } public SQLBuilder update() { sql.append("update "); return this; } public SQLBuilder set() { sql.append("set "); return this; } public SQLBuilder comma() { sql.append(", "); return this; } public SQLBuilder insertInto() { sql.append("insert into "); return this; } public SQLBuilder values() { sql.append("values "); return this; } public SQLBuilder addValue(@Nullable Object parameter, @NotNull MapSqlParameterSource sqlParameterSource) { String paramName = "parameter_" + getCount(); sql.append(":").append(paramName).append(" "); sqlParameterSource.addValue(paramName, parameter); return this; } public int getCount() { return count++; } }
7,643
0.690921
0.687524
287
25.672474
34.266491
191
false
false
0
0
0
0
0
0
2.059233
false
false
4
63d6a27bc64d468d877cbcd67b7418632886230a
644,245,115,458
3c1afec1128a23f4775c741099d00773836829ad
/src/main/java/org/richardinnocent/polysight/auth/server/http/mapper/HttpObjectMapper.java
7f6161846137d562e680b5c23a918edde144c80e
[]
no_license
RichardInnocent/polysight-auth
https://github.com/RichardInnocent/polysight-auth
cc35c908e0eceea5e6d509d18e7efe3296bc864c
a91c636a096a2163becca8b12a61add2b07a89ee
refs/heads/master
2022-07-11T15:57:37.796000
2021-11-08T15:36:15
2021-11-08T15:36:15
214,806,459
1
0
null
false
2021-11-08T15:36:16
2019-10-13T11:16:04
2021-11-07T21:15:57
2021-11-08T15:36:15
208
1
0
0
Java
false
false
package org.richardinnocent.polysight.auth.server.http.mapper; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Component; /** * An {@link ObjectMapper} used to serialize/deserialize HTTP requests/responses. */ @Component @Primary public class HttpObjectMapper extends ObjectMapper { /** * Creates a new object mapper, used in the serialization and deserialization of entities in HTTP * requests/responses, registering the appropriate modules. */ public HttpObjectMapper() { registerModule(new JavaTimeModule()); } }
UTF-8
Java
699
java
HttpObjectMapper.java
Java
[]
null
[]
package org.richardinnocent.polysight.auth.server.http.mapper; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Component; /** * An {@link ObjectMapper} used to serialize/deserialize HTTP requests/responses. */ @Component @Primary public class HttpObjectMapper extends ObjectMapper { /** * Creates a new object mapper, used in the serialization and deserialization of entities in HTTP * requests/responses, registering the appropriate modules. */ public HttpObjectMapper() { registerModule(new JavaTimeModule()); } }
699
0.788269
0.783977
23
29.391304
30.178799
99
false
false
0
0
0
0
0
0
0.347826
false
false
4
4c7ab19c1ac4203104391968fe623c0207669d52
21,835,613,748,814
1fc9d3b4ad52d2c7690e4ec1b4b33e955d2892dd
/src/main/java/com/designPtn/decorator/HouseBlend.java
fcbf03fe1728e3785a83a8eb600b9cdaeda0277d
[]
no_license
yangmengjun/test
https://github.com/yangmengjun/test
750243ff07251902509c820fa1632018378fda1d
934d1e63566d36e65c77b3782f7fc6386bc532a5
refs/heads/master
2022-07-15T17:24:22.297000
2020-06-06T13:25:00
2020-06-06T13:25:00
108,247,967
0
0
null
false
2022-06-17T01:44:39
2017-10-25T09:23:05
2020-06-06T13:24:00
2022-06-17T01:44:38
3,326
0
0
3
Java
false
false
package com.designPtn.decorator; /** * 综合咖啡 */ public class HouseBlend extends Beverage { public HouseBlend(){ desc = "House Blend Coffee"; } @Override public float cost() { return 0.89f; } }
UTF-8
Java
239
java
HouseBlend.java
Java
[]
null
[]
package com.designPtn.decorator; /** * 综合咖啡 */ public class HouseBlend extends Beverage { public HouseBlend(){ desc = "House Blend Coffee"; } @Override public float cost() { return 0.89f; } }
239
0.593074
0.580087
14
15.5
13.756817
42
false
false
0
0
0
0
0
0
0.214286
false
false
4
1d81842e2ed4f621142a610cb1576f0bef29c0f4
9,259,949,557,070
572bab4f7ee48a1594366181378d920616e70e24
/src/mainpackage/AjoutDeplacement.java
bc4545aefe35e1c60a42bc30bf9ab0d3424275cb
[]
no_license
Houda-20/RADEM_Projet_Gestion-de-deplacement
https://github.com/Houda-20/RADEM_Projet_Gestion-de-deplacement
84dc9f04964217360b65f5540372fd6db3a20b59
0dd90319d78b0f9a518a8b7503585b2894a92d21
refs/heads/master
2023-07-26T19:43:36.325000
2021-08-31T02:03:47
2021-08-31T02:03:47
401,536,019
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 mainpackage; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFrame; import javax.swing.JOptionPane; /** * * @author ammani */ public class AjoutDeplacement extends javax.swing.JFrame { /** * Creates new form AjoutDeplacement */ public AjoutDeplacement() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); jLabel0 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jTextField2 = new javax.swing.JTextField(); jTextField4 = new javax.swing.JTextField(); jTextField5 = new javax.swing.JTextField(); jTextField6 = new javax.swing.JTextField(); jTextField7 = new javax.swing.JTextField(); jTextField8 = new javax.swing.JTextField(); jTextField10 = new javax.swing.JTextField(); jTextField12 = new javax.swing.JTextField(); jTextField17 = new javax.swing.JTextField(); jTextField18 = new javax.swing.JTextField(); jTextField19 = new javax.swing.JTextField(); jTextField20 = new javax.swing.JTextField(); jTextField21 = new javax.swing.JTextField(); jTextField22 = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); jLabel12 = new javax.swing.JLabel(); jLabel13 = new javax.swing.JLabel(); jLabel14 = new javax.swing.JLabel(); jLabel15 = new javax.swing.JLabel(); jLabel16 = new javax.swing.JLabel(); jLabel17 = new javax.swing.JLabel(); jLabel18 = new javax.swing.JLabel(); jLabel19 = new javax.swing.JLabel(); jLabel20 = new javax.swing.JLabel(); jLabel21 = new javax.swing.JLabel(); jLabel22 = new javax.swing.JLabel(); jToggleButton1 = new javax.swing.JToggleButton(); jRadioButton1 = new javax.swing.JRadioButton(); jRadioButton2 = new javax.swing.JRadioButton(); jTimeChooser1 = new lu.tudor.santec.jtimechooser.JTimeChooser(); jTimeChooser2 = new lu.tudor.santec.jtimechooser.JTimeChooser(); jDateChooser1 = new com.toedter.calendar.JDateChooser(); jDateChooser2 = new com.toedter.calendar.JDateChooser(); jTextField11 = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); jPanel2.setBackground(new java.awt.Color(204, 204, 255)); jPanel2.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jLabel0.setFont(new java.awt.Font("Tahoma", 1, 48)); // NOI18N jLabel0.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel0.setText("GESTION DES VIHECULES RADEM"); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel0, javax.swing.GroupLayout.DEFAULT_SIZE, 960, Short.MAX_VALUE) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap(26, Short.MAX_VALUE) .addComponent(jLabel0) .addGap(25, 25, 25)) ); jTextField1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jTextField2.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jTextField4.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jTextField5.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jTextField5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField5ActionPerformed(evt); } }); jTextField6.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jTextField7.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jTextField7.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField7ActionPerformed(evt); } }); jTextField8.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jTextField8.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField8ActionPerformed(evt); } }); jTextField10.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jTextField12.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jTextField12.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField12ActionPerformed(evt); } }); jTextField17.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jTextField17.setToolTipText(""); jTextField17.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jTextField17MouseClicked(evt); } }); jTextField17.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField17ActionPerformed(evt); } }); jTextField18.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jTextField18.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField18ActionPerformed(evt); } }); jTextField19.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jTextField20.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jTextField21.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jTextField22.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpackage/images/Deplacement/full_name.png"))); // NOI18N jLabel1.setText("NOM EMPLOYEUR :"); jLabel2.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpackage/images/Deplacement/full_name.png"))); // NOI18N jLabel2.setText("PRENOM EMPLOYEUR :"); jLabel3.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpackage/images/Deplacement/vehicule.png"))); // NOI18N jLabel3.setText("VEHICULE PERSONNEL :"); jLabel4.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpackage/images/Deplacement/matricul_vehicule.png"))); // NOI18N jLabel4.setText("MATRICULE VEHICULE :"); jLabel5.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpackage/images/Deplacement/marque.png"))); // NOI18N jLabel5.setText("MARQUE :"); jLabel6.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpackage/images/Deplacement/Nbr_cheveaux.png"))); // NOI18N jLabel6.setText("NOMBRE DE CHEVAUX :"); jLabel7.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpackage/images/Deplacement/puissance.png"))); // NOI18N jLabel7.setText("PUISSANCE FISCALE :"); jLabel8.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpackage/images/Deplacement/ordre.png"))); // NOI18N jLabel8.setText("ORDRE :"); jLabel9.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel9.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpackage/images/Deplacement/autoroute.png"))); // NOI18N jLabel9.setText("DROIT AUTOROUTE :"); jLabel10.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpackage/images/Deplacement/indemniteKm.png"))); // NOI18N jLabel10.setText("INDEMNITE KM :"); jLabel11.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel11.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpackage/images/Deplacement/destination.png"))); // NOI18N jLabel11.setText("DESTINATION :"); jLabel12.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel12.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpackage/images/Deplacement/distance.png"))); // NOI18N jLabel12.setText("DISTANCE :"); jLabel13.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel13.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpackage/images/Deplacement/date.png"))); // NOI18N jLabel13.setText("DATE DE DEPART :"); jLabel14.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel14.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpackage/images/Deplacement/dateRetour.png"))); // NOI18N jLabel14.setText("DATE DE RETOUR :"); jLabel15.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel15.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpackage/images/Deplacement/heure.png"))); // NOI18N jLabel15.setText("HEURE DE DEPART :"); jLabel16.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel16.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpackage/images/Deplacement/heureRetour.png"))); // NOI18N jLabel16.setText("HEURE DE RETOUR :"); jLabel17.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel17.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpackage/images/Deplacement/nuitPasses.png"))); // NOI18N jLabel17.setText("NUIT PASSES"); jLabel18.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel18.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpackage/images/Deplacement/petitDejeuner.png"))); // NOI18N jLabel18.setText("NOMBRE DE PETIT DEJEUNER :"); jLabel19.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel19.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpackage/images/Deplacement/dejeuner.png"))); // NOI18N jLabel19.setText("NOMBRE DE DEJEUNER :"); jLabel20.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel20.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpackage/images/Deplacement/denir.png"))); // NOI18N jLabel20.setText("NOMBRE DE DINER :"); jLabel21.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel21.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpackage/images/Deplacement/total.png"))); // NOI18N jLabel21.setText("TOTAL"); jLabel22.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel22.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpackage/images/Deplacement/matricul_agence.png"))); // NOI18N jLabel22.setText("MATRICULE AGENCE :"); jToggleButton1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jToggleButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpackage/images/Deplacement/upload.png"))); // NOI18N jToggleButton1.setText("UPLOAD"); jToggleButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jToggleButton1ActionPerformed(evt); } }); jRadioButton1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jRadioButton1.setText("OUI"); jRadioButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButton1ActionPerformed(evt); } }); jRadioButton2.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jRadioButton2.setText("OUI"); jTimeChooser1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jTimeChooser1.setOpaque(true); jTimeChooser1.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseMoved(java.awt.event.MouseEvent evt) { jTimeChooser1MouseMoved(evt); } }); jTimeChooser1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jTimeChooser1MouseClicked(evt); } }); jDateChooser1.setDateFormatString("dd-MM-yyyy"); try { Date date = new SimpleDateFormat("dd-MM-yyyy").parse("10-12-1999"); jDateChooser1.setDate(date); } catch (Exception e) { System.out.println(e); } jDateChooser1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jDateChooser1.addContainerListener(new java.awt.event.ContainerAdapter() { public void componentAdded(java.awt.event.ContainerEvent evt) { jDateChooser1ComponentAdded(evt); } }); jDateChooser2.setToolTipText(""); jDateChooser2.setDateFormatString("dd-MM-yyyy"); try { Date date = new SimpleDateFormat("dd-MM-yyyy").parse("10-12-1999"); jDateChooser2.setDate(date); } catch (Exception e) { System.out.println(e); } jDateChooser2.getDateEditor().addPropertyChangeListener( new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent e) { if ("date".equals(e.getPropertyName())) { long delta =(jDateChooser2.getDate().getTime()-jDateChooser1.getDate().getTime())/(1000*60*60*24); jTextField17.setText(""+delta); jTextField18.setText(""+(delta+1)); jTextField19.setText(""+(delta+1)); jTextField20.setText(""+delta); } } }); jDateChooser2.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jDateChooser2.addContainerListener(new java.awt.event.ContainerAdapter() { public void componentAdded(java.awt.event.ContainerEvent evt) { jDateChooser2ComponentAdded(evt); } }); jDateChooser2.addAncestorListener(new javax.swing.event.AncestorListener() { public void ancestorAdded(javax.swing.event.AncestorEvent evt) { jDateChooser2AncestorAdded(evt); } public void ancestorMoved(javax.swing.event.AncestorEvent evt) { } public void ancestorRemoved(javax.swing.event.AncestorEvent evt) { } }); jDateChooser2.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseDragged(java.awt.event.MouseEvent evt) { jDateChooser2MouseDragged(evt); } }); jDateChooser2.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jDateChooser2MouseClicked(evt); } public void mouseEntered(java.awt.event.MouseEvent evt) { jDateChooser2MouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { jDateChooser2MouseExited(evt); } public void mousePressed(java.awt.event.MouseEvent evt) { jDateChooser2MousePressed(evt); } public void mouseReleased(java.awt.event.MouseEvent evt) { jDateChooser2MouseReleased(evt); } }); jDateChooser2.addInputMethodListener(new java.awt.event.InputMethodListener() { public void caretPositionChanged(java.awt.event.InputMethodEvent evt) { } public void inputMethodTextChanged(java.awt.event.InputMethodEvent evt) { jDateChooser2InputMethodTextChanged(evt); } }); jDateChooser2.addPropertyChangeListener(new java.beans.PropertyChangeListener() { public void propertyChange(java.beans.PropertyChangeEvent evt) { jDateChooser2PropertyChange(evt); } }); jDateChooser2.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { jDateChooser2KeyReleased(evt); } }); jDateChooser2.addVetoableChangeListener(new java.beans.VetoableChangeListener() { public void vetoableChange(java.beans.PropertyChangeEvent evt)throws java.beans.PropertyVetoException { jDateChooser2VetoableChange(evt); } }); jTextField11.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jTextField11.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { jTextField11KeyReleased(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel6) .addComponent(jLabel8) .addComponent(jLabel7) .addComponent(jLabel9) .addComponent(jLabel11) .addComponent(jLabel12) .addComponent(jLabel5) .addComponent(jLabel1) .addComponent(jLabel2) .addComponent(jLabel4) .addComponent(jLabel3) .addComponent(jLabel10)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jTextField5) .addComponent(jTextField4) .addComponent(jTextField2) .addComponent(jTextField1) .addComponent(jTextField7) .addComponent(jTextField8) .addComponent(jTextField10) .addComponent(jTextField12) .addComponent(jRadioButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jRadioButton2, javax.swing.GroupLayout.DEFAULT_SIZE, 175, Short.MAX_VALUE) .addComponent(jTextField6, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jTextField11, javax.swing.GroupLayout.Alignment.TRAILING)) .addGap(26, 26, 26) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel14) .addComponent(jLabel13) .addComponent(jLabel15) .addComponent(jLabel16) .addComponent(jLabel17) .addComponent(jLabel18) .addComponent(jLabel19) .addComponent(jLabel20) .addComponent(jLabel21) .addComponent(jLabel22)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 14, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jTextField20, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jTextField18, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jTextField17, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jTextField22, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jTextField19, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jToggleButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 174, Short.MAX_VALUE) .addComponent(jTimeChooser1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jTimeChooser2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jDateChooser2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jDateChooser1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jTextField21)))) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(21, 21, 21) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 38, Short.MAX_VALUE) .addComponent(jLabel13) .addComponent(jLabel1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel14) .addComponent(jLabel2))) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(3, 3, 3) .addComponent(jDateChooser1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jDateChooser2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(5, 5, 5))) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel15) .addComponent(jLabel3) .addComponent(jRadioButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel16) .addComponent(jLabel4)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel17) .addComponent(jLabel5)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel18) .addComponent(jLabel6) .addComponent(jTextField18, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField7, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel19) .addComponent(jLabel7) .addComponent(jTextField19, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField8, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel20) .addComponent(jLabel8) .addComponent(jTextField20, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel21) .addComponent(jLabel9) .addComponent(jRadioButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField21, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jTimeChooser1, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(2, 2, 2) .addComponent(jTimeChooser2, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextField17, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE))) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField10, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel22, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel10) .addComponent(jTextField22, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel11) .addComponent(jTextField11, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField12, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel12))) .addComponent(jToggleButton1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); jDateChooser2.getAccessibleContext().setAccessibleName(""); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jTextField8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField8ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField8ActionPerformed private void jTextField7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField7ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField7ActionPerformed private void jTextField5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField5ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField5ActionPerformed private boolean valide_int(String test){ char[] text = test.toCharArray(); for (char element:text){ if(element!='0'&&element!='1'&&element!='2'&&element!='3'&&element!='4'&&element!='5'&&element!='6'&&element!='7'&&element!='8'&&element!='9'){ return false; } } return true; } private boolean valide_real(String test){ char[] text = test.toCharArray(); for (char element:text){ if(element!='.'&&element!='0'&&element!='1'&&element!='2'&&element!='3'&&element!='4'&&element!='5'&&element!='6'&&element!='7'&&element!='8'&&element!='9'){ return false; } } return true; } private boolean valide_date(String test){ char[] text = test.toCharArray(); if(text.length!=10||text[2]!='-'||text[5]!='-')return false; int day = Character.getNumericValue(text[0])*10+Character.getNumericValue(text[0]); int month = Character.getNumericValue(text[3])*10+Character.getNumericValue(text[4]); int year = Character.getNumericValue(text[6])*1000+Character.getNumericValue(text[7])*100+Character.getNumericValue(text[8])*10+Character.getNumericValue(text[9]); if(day==0||day>31||month==0||month>12||year==0||year>9999)return false; return true; } private String ouiNon(boolean test){ if(test==true)return "oui"; return "non"; } private void jToggleButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jToggleButton1ActionPerformed // TODO add your handling code here: DateFormat date= new SimpleDateFormat("dd-MM-yyyy"); String NomEmployeur = jTextField1.getText(); String PrenomEmployeur = jTextField2.getText(); String VehiculePersonnel = ouiNon(jRadioButton1.isSelected()); String MatriculeVehicule = jTextField4.getText(); String Marque = jTextField5.getText(); String NombreDeChevaux = jTextField6.getText(); String PuissanceFiscale = jTextField7.getText(); String Ordre =jTextField8.getText(); String DroitAutoroute = ouiNon(jRadioButton2.isSelected()); String IndemniteKm=jTextField10.getText(); String Destination=jTextField11.getText(); String Distance=jTextField12.getText(); String DateDeDepart=date.format(jDateChooser1.getDate()); String DateDeRetour=date.format(jDateChooser2.getDate()); String HeureDeDepart=jTimeChooser1.getTimeField().getText(); String HeureDeRetour=jTimeChooser2.getTimeField().getText(); String NuitPasses=jTextField17.getText(); String NombreDePetitDejeuner=jTextField18.getText(); String NombreDeDejeuner=jTextField19.getText(); String NombreDeDiner=jTextField20.getText();; String Total=jTextField21.getText();; String MatriculeAgence=jTextField22.getText(); if(NomEmployeur.isEmpty()||PrenomEmployeur.isEmpty()||MatriculeVehicule.isEmpty()||Marque.isEmpty()||NombreDeChevaux.isEmpty()||PuissanceFiscale.isEmpty()||Ordre.isEmpty()|| IndemniteKm.isEmpty()||Destination.isEmpty()||Distance.isEmpty()||DateDeDepart.isEmpty()||DateDeRetour.isEmpty()||HeureDeDepart.isEmpty()||HeureDeRetour.isEmpty()|| NuitPasses.isEmpty()||NombreDePetitDejeuner.isEmpty()||NombreDeDejeuner.isEmpty()||NombreDeDiner.isEmpty()||Total.isEmpty()||MatriculeAgence.isEmpty()){ JFrame frame = new JFrame(); JOptionPane.showMessageDialog(frame, "un ou plusieurs champs sont vide veuillez remplir tous les champs svp","GESTION DES VEHICULES RADEM",2); } else{ if(valide_int(NombreDeChevaux)==false){ jTextField6.setText(""); JFrame frame = new JFrame(); JOptionPane.showMessageDialog(frame, "le champ NOMBRE DE CHEVEAUX ne doit pas contenir des lettres ou des caractères spéciales, vous devez tapper que des chiffres","GESTION DES VEHICULES RADEM",2); } else if(valide_int(Ordre)==false){ jTextField8.setText(""); JFrame frame = new JFrame(); JOptionPane.showMessageDialog(frame, "le champ ORDRE ne doit pas contenir des lettres ou des caractères spéciales, vous devez tapper que des chiffres","GESTION DES VEHICULES RADEM",2); } else if(valide_real(IndemniteKm)==false){ jTextField10.setText(""); JFrame frame = new JFrame(); JOptionPane.showMessageDialog(frame, "le champ INDOMNITE KM ne doit pas contenir des lettres ou des caractères spéciales, vous devez tapper que des nombres réels, exemple : 15.79 ou 17","GESTION DES VEHICULES RADEM",2); } else if(valide_int(Distance)==false){ jTextField12.setText(""); JFrame frame = new JFrame(); JOptionPane.showMessageDialog(frame, "le champ DISTANCE ne doit pas contenir des lettres ou des caractères spéciales, vous devez tapper que des chiffres","GESTION DES VEHICULES RADEM",2); } else if(valide_date(DateDeDepart)==false){ try { Date dt = new SimpleDateFormat("dd-MM-yyyy").parse("10-12-1999"); jDateChooser1.setDate(dt); } catch (Exception e) { System.out.println(e); } JFrame frame = new JFrame(); JOptionPane.showMessageDialog(frame, "le champ DATE DE DEPART doit contenir une forme de date valide, exemple : 10-12-1999","GESTION DES VEHICULES RADEM",2); } else if(valide_date(DateDeRetour)==false){ try { Date dt = new SimpleDateFormat("dd-MM-yyyy").parse("10-12-1999"); jDateChooser2.setDate(dt); } catch (Exception e) { System.out.println(e); } JFrame frame = new JFrame(); JOptionPane.showMessageDialog(frame, "le champ DATE DE RETOUR doit contenir une forme de date valide, exemple : 10-12-1999","GESTION DES VEHICULES RADEM",2); } else if(valide_int(NuitPasses)==false){ jTextField17.setText(""); JFrame frame = new JFrame(); JOptionPane.showMessageDialog(frame, "le champ NUIT PASSES ne doit pas contenir des lettres ou des caractères spéciales, vous devez tapper que des chiffres","GESTION DES VEHICULES RADEM",2); } else if(valide_int(NombreDePetitDejeuner)==false){ jTextField18.setText(""); JFrame frame = new JFrame(); JOptionPane.showMessageDialog(frame, "le champ NOMBRE DE PETIT DEJEUNER ne doit pas contenir des lettres ou des caractères spéciales, vous devez tapper que des chiffres","GESTION DES VEHICULES RADEM",2); } else if(valide_int(NombreDeDejeuner)==false){ jTextField19.setText(""); JFrame frame = new JFrame(); JOptionPane.showMessageDialog(frame, "le champ NOMBRE DE DEJEUNER ne doit pas contenir des lettres ou des caractères spéciales, vous devez tapper que des chiffres","GESTION DES VEHICULES RADEM",2); } else if(valide_int(NombreDeDiner)==false){ jTextField20.setText(""); JFrame frame = new JFrame(); JOptionPane.showMessageDialog(frame, "le champ NOMBRE DE DINER ne doit pas contenir des lettres ou des caractères spéciales, vous devez tapper que des chiffres","GESTION DES VEHICULES RADEM",2); } else if(valide_real(Total)==false){ jTextField21.setText(""); JFrame frame = new JFrame(); JOptionPane.showMessageDialog(frame, "le champ TOTAL ne doit pas contenir des lettres ou des caractères spéciales, vous devez tapper que des nombres réels, exemple : 15.79 ou 17","GESTION DES VEHICULES RADEM",2); } else{ Connection con = null; try { con = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:orcl", "c##admin", "admin"); } catch (SQLException ex) { Logger.getLogger(login.class.getName()).log(Level.SEVERE, null, ex); } // Create a statement for SQL query Statement stmt = null; try { stmt = con.createStatement(); } catch (SQLException ex) { Logger.getLogger(login.class.getName()).log(Level.SEVERE, null, ex); } // Execute the query ResultSet rsl = null; try { String sql = "insert into deplacement values('"+NomEmployeur+"','"+PrenomEmployeur+"','"+VehiculePersonnel+"','"+MatriculeVehicule+"','"+Marque+ "',"+NombreDeChevaux+",'"+PuissanceFiscale+"',"+Ordre+",'"+DroitAutoroute+"',"+IndemniteKm+",'"+Destination+"',"+Distance+ ",to_date('"+DateDeDepart+" "+HeureDeDepart+"','dd-MM-yyyy hh24:mi:ss'),to_date('"+DateDeRetour+" "+HeureDeRetour+"','dd-MM-yyyy hh24:mi:ss'),'"+ HeureDeDepart+"','"+HeureDeRetour+"',"+NuitPasses+","+NombreDePetitDejeuner+","+NombreDeDejeuner+","+NombreDeDiner+","+Total+",'"+MatriculeAgence+"')"; stmt.executeQuery(sql); } catch (SQLException ex) { Logger.getLogger(Admin.class.getName()).log(Level.SEVERE, null, ex); } this.setVisible(false); JFrame frame = new JFrame(); JOptionPane.showMessageDialog(frame, "ce deplacement est ajouté avec succès","GESTION DES VEHICULES RADEM",1); } } }//GEN-LAST:event_jToggleButton1ActionPerformed private void jTextField12ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField12ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField12ActionPerformed private void jTextField18ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField18ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField18ActionPerformed private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton1ActionPerformed // TODO add your handling code here: if(jRadioButton1.isSelected()){ Connection con = null; try { con = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:orcl", "c##admin", "admin"); } catch (SQLException ex) { Logger.getLogger(login.class.getName()).log(Level.SEVERE, null, ex); } // Create a statement for SQL query Statement stmt = null; try { stmt = con.createStatement(); } catch (SQLException ex) { Logger.getLogger(login.class.getName()).log(Level.SEVERE, null, ex); } ResultSet rsl = null; try { String sql = "select * from voiturepersonel where (nomemployeur = '"+jTextField1.getText()+"' AND prenomemployeur = '"+jTextField2.getText()+"' )"; rsl=stmt.executeQuery(sql); } catch (SQLException ex) { Logger.getLogger(Admin.class.getName()).log(Level.SEVERE, null, ex); } String matricule=null; String marque=null; String nbrchevaux=null; String puissance=null; int i=0; try { while(rsl.next()){ matricule= rsl.getString("matricul"); marque=rsl.getString("marque"); nbrchevaux=rsl.getString("nbrchevaux"); puissance=rsl.getString("puissancefiscal"); i++; } } catch (SQLException ex) { Logger.getLogger(AjoutDeplacement.class.getName()).log(Level.SEVERE, null, ex); } if(i!=0){ jTextField4.setText(matricule); jTextField5.setText(marque); jTextField6.setText(nbrchevaux); jTextField7.setText(puissance); } } else{ } }//GEN-LAST:event_jRadioButton1ActionPerformed private void jDateChooser2InputMethodTextChanged(java.awt.event.InputMethodEvent evt) {//GEN-FIRST:event_jDateChooser2InputMethodTextChanged // TODO add your handling code here: }//GEN-LAST:event_jDateChooser2InputMethodTextChanged private void jDateChooser2ComponentAdded(java.awt.event.ContainerEvent evt) {//GEN-FIRST:event_jDateChooser2ComponentAdded // TODO add your handling code here: }//GEN-LAST:event_jDateChooser2ComponentAdded private void jDateChooser1ComponentAdded(java.awt.event.ContainerEvent evt) {//GEN-FIRST:event_jDateChooser1ComponentAdded // TODO add your handling code here: }//GEN-LAST:event_jDateChooser1ComponentAdded private void jTimeChooser1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTimeChooser1MouseClicked // TODO add your handling code here: System.out.println("the time is : "+jDateChooser1.getDate()); }//GEN-LAST:event_jTimeChooser1MouseClicked private void jTextField17ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField17ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField17ActionPerformed private void jTextField17MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextField17MouseClicked // TODO add your handling code here: }//GEN-LAST:event_jTextField17MouseClicked private void jTimeChooser1MouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTimeChooser1MouseMoved // TODO add your handling code here: }//GEN-LAST:event_jTimeChooser1MouseMoved private void jDateChooser2MousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jDateChooser2MousePressed // TODO add your handling code here: }//GEN-LAST:event_jDateChooser2MousePressed private void jDateChooser2MouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jDateChooser2MouseExited // TODO add your handling code here: }//GEN-LAST:event_jDateChooser2MouseExited private void jDateChooser2MouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jDateChooser2MouseReleased // TODO add your handling code here: }//GEN-LAST:event_jDateChooser2MouseReleased private void jDateChooser2MouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jDateChooser2MouseEntered // TODO add your handling code here: }//GEN-LAST:event_jDateChooser2MouseEntered private void jDateChooser2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jDateChooser2MouseClicked // TODO add your handling code here: }//GEN-LAST:event_jDateChooser2MouseClicked private void jDateChooser2MouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jDateChooser2MouseDragged // TODO add your handling code here: }//GEN-LAST:event_jDateChooser2MouseDragged private void jDateChooser2VetoableChange(java.beans.PropertyChangeEvent evt)throws java.beans.PropertyVetoException {//GEN-FIRST:event_jDateChooser2VetoableChange // TODO add your handling code here: }//GEN-LAST:event_jDateChooser2VetoableChange private void jDateChooser2PropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_jDateChooser2PropertyChange // TODO add your handling code here: }//GEN-LAST:event_jDateChooser2PropertyChange private void jDateChooser2AncestorAdded(javax.swing.event.AncestorEvent evt) {//GEN-FIRST:event_jDateChooser2AncestorAdded // TODO add your handling code here: }//GEN-LAST:event_jDateChooser2AncestorAdded private void jDateChooser2KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jDateChooser2KeyReleased // TODO add your handling code here: System.out.println("the time is : "+jDateChooser1.getDate()); }//GEN-LAST:event_jDateChooser2KeyReleased private void jTextField11KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField11KeyReleased // TODO add your handling code here: String destination = jTextField11.getText(); try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(login.class.getName()).log(Level.SEVERE, null, ex); } // Create a connection Connection con = null; try { con = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:orcl", "c##admin", "admin"); } catch (SQLException ex) { Logger.getLogger(login.class.getName()).log(Level.SEVERE, null, ex); } // Create a statement for SQL query Statement stmt = null; try { stmt = con.createStatement(); } catch (SQLException ex) { Logger.getLogger(login.class.getName()).log(Level.SEVERE, null, ex); } // Execute the query ResultSet rsl = null; try { rsl = stmt.executeQuery("select * from ville"); } catch (SQLException ex) { Logger.getLogger(login.class.getName()).log(Level.SEVERE, null, ex); } try { while(rsl.next()){ String dest=rsl.getString("ville"); if(destination.equals(dest)){ jTextField12.setText(rsl.getString("distance")); //break; } } } catch (SQLException ex) { Logger.getLogger(login.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_jTextField11KeyReleased /** * @param args the command line arguments */ // Variables declaration - do not modify//GEN-BEGIN:variables private com.toedter.calendar.JDateChooser jDateChooser1; private com.toedter.calendar.JDateChooser jDateChooser2; private javax.swing.JLabel jLabel0; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel15; private javax.swing.JLabel jLabel16; private javax.swing.JLabel jLabel17; private javax.swing.JLabel jLabel18; private javax.swing.JLabel jLabel19; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel20; private javax.swing.JLabel jLabel21; private javax.swing.JLabel jLabel22; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JRadioButton jRadioButton1; private javax.swing.JRadioButton jRadioButton2; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField10; private javax.swing.JTextField jTextField11; private javax.swing.JTextField jTextField12; private javax.swing.JTextField jTextField17; private javax.swing.JTextField jTextField18; private javax.swing.JTextField jTextField19; private javax.swing.JTextField jTextField2; private javax.swing.JTextField jTextField20; private javax.swing.JTextField jTextField21; private javax.swing.JTextField jTextField22; private javax.swing.JTextField jTextField4; private javax.swing.JTextField jTextField5; private javax.swing.JTextField jTextField6; private javax.swing.JTextField jTextField7; private javax.swing.JTextField jTextField8; private lu.tudor.santec.jtimechooser.JTimeChooser jTimeChooser1; private lu.tudor.santec.jtimechooser.JTimeChooser jTimeChooser2; private javax.swing.JToggleButton jToggleButton1; // End of variables declaration//GEN-END:variables }
UTF-8
Java
56,113
java
AjoutDeplacement.java
Java
[ { "context": "import javax.swing.JOptionPane;\n\n/**\n *\n * @author ammani\n */\npublic class AjoutDeplacement extends javax.s", "end": 700, "score": 0.994431734085083, "start": 694, "tag": "USERNAME", "value": "ammani" }, { "context": "ng\"))); // NOI18N\n jLabel20.setText(\"NOMBRE DE DINER :\");\n\n jLabel21.setFont(new java.awt.Font(", "end": 12873, "score": 0.81502366065979, "start": 12865, "tag": "NAME", "value": "DE DINER" } ]
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 mainpackage; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFrame; import javax.swing.JOptionPane; /** * * @author ammani */ public class AjoutDeplacement extends javax.swing.JFrame { /** * Creates new form AjoutDeplacement */ public AjoutDeplacement() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); jLabel0 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jTextField2 = new javax.swing.JTextField(); jTextField4 = new javax.swing.JTextField(); jTextField5 = new javax.swing.JTextField(); jTextField6 = new javax.swing.JTextField(); jTextField7 = new javax.swing.JTextField(); jTextField8 = new javax.swing.JTextField(); jTextField10 = new javax.swing.JTextField(); jTextField12 = new javax.swing.JTextField(); jTextField17 = new javax.swing.JTextField(); jTextField18 = new javax.swing.JTextField(); jTextField19 = new javax.swing.JTextField(); jTextField20 = new javax.swing.JTextField(); jTextField21 = new javax.swing.JTextField(); jTextField22 = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); jLabel12 = new javax.swing.JLabel(); jLabel13 = new javax.swing.JLabel(); jLabel14 = new javax.swing.JLabel(); jLabel15 = new javax.swing.JLabel(); jLabel16 = new javax.swing.JLabel(); jLabel17 = new javax.swing.JLabel(); jLabel18 = new javax.swing.JLabel(); jLabel19 = new javax.swing.JLabel(); jLabel20 = new javax.swing.JLabel(); jLabel21 = new javax.swing.JLabel(); jLabel22 = new javax.swing.JLabel(); jToggleButton1 = new javax.swing.JToggleButton(); jRadioButton1 = new javax.swing.JRadioButton(); jRadioButton2 = new javax.swing.JRadioButton(); jTimeChooser1 = new lu.tudor.santec.jtimechooser.JTimeChooser(); jTimeChooser2 = new lu.tudor.santec.jtimechooser.JTimeChooser(); jDateChooser1 = new com.toedter.calendar.JDateChooser(); jDateChooser2 = new com.toedter.calendar.JDateChooser(); jTextField11 = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); jPanel2.setBackground(new java.awt.Color(204, 204, 255)); jPanel2.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jLabel0.setFont(new java.awt.Font("Tahoma", 1, 48)); // NOI18N jLabel0.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel0.setText("GESTION DES VIHECULES RADEM"); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel0, javax.swing.GroupLayout.DEFAULT_SIZE, 960, Short.MAX_VALUE) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap(26, Short.MAX_VALUE) .addComponent(jLabel0) .addGap(25, 25, 25)) ); jTextField1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jTextField2.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jTextField4.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jTextField5.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jTextField5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField5ActionPerformed(evt); } }); jTextField6.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jTextField7.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jTextField7.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField7ActionPerformed(evt); } }); jTextField8.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jTextField8.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField8ActionPerformed(evt); } }); jTextField10.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jTextField12.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jTextField12.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField12ActionPerformed(evt); } }); jTextField17.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jTextField17.setToolTipText(""); jTextField17.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jTextField17MouseClicked(evt); } }); jTextField17.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField17ActionPerformed(evt); } }); jTextField18.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jTextField18.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField18ActionPerformed(evt); } }); jTextField19.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jTextField20.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jTextField21.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jTextField22.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpackage/images/Deplacement/full_name.png"))); // NOI18N jLabel1.setText("NOM EMPLOYEUR :"); jLabel2.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpackage/images/Deplacement/full_name.png"))); // NOI18N jLabel2.setText("PRENOM EMPLOYEUR :"); jLabel3.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpackage/images/Deplacement/vehicule.png"))); // NOI18N jLabel3.setText("VEHICULE PERSONNEL :"); jLabel4.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpackage/images/Deplacement/matricul_vehicule.png"))); // NOI18N jLabel4.setText("MATRICULE VEHICULE :"); jLabel5.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpackage/images/Deplacement/marque.png"))); // NOI18N jLabel5.setText("MARQUE :"); jLabel6.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpackage/images/Deplacement/Nbr_cheveaux.png"))); // NOI18N jLabel6.setText("NOMBRE DE CHEVAUX :"); jLabel7.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpackage/images/Deplacement/puissance.png"))); // NOI18N jLabel7.setText("PUISSANCE FISCALE :"); jLabel8.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpackage/images/Deplacement/ordre.png"))); // NOI18N jLabel8.setText("ORDRE :"); jLabel9.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel9.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpackage/images/Deplacement/autoroute.png"))); // NOI18N jLabel9.setText("DROIT AUTOROUTE :"); jLabel10.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpackage/images/Deplacement/indemniteKm.png"))); // NOI18N jLabel10.setText("INDEMNITE KM :"); jLabel11.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel11.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpackage/images/Deplacement/destination.png"))); // NOI18N jLabel11.setText("DESTINATION :"); jLabel12.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel12.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpackage/images/Deplacement/distance.png"))); // NOI18N jLabel12.setText("DISTANCE :"); jLabel13.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel13.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpackage/images/Deplacement/date.png"))); // NOI18N jLabel13.setText("DATE DE DEPART :"); jLabel14.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel14.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpackage/images/Deplacement/dateRetour.png"))); // NOI18N jLabel14.setText("DATE DE RETOUR :"); jLabel15.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel15.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpackage/images/Deplacement/heure.png"))); // NOI18N jLabel15.setText("HEURE DE DEPART :"); jLabel16.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel16.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpackage/images/Deplacement/heureRetour.png"))); // NOI18N jLabel16.setText("HEURE DE RETOUR :"); jLabel17.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel17.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpackage/images/Deplacement/nuitPasses.png"))); // NOI18N jLabel17.setText("NUIT PASSES"); jLabel18.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel18.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpackage/images/Deplacement/petitDejeuner.png"))); // NOI18N jLabel18.setText("NOMBRE DE PETIT DEJEUNER :"); jLabel19.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel19.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpackage/images/Deplacement/dejeuner.png"))); // NOI18N jLabel19.setText("NOMBRE DE DEJEUNER :"); jLabel20.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel20.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpackage/images/Deplacement/denir.png"))); // NOI18N jLabel20.setText("NOMBRE <NAME> :"); jLabel21.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel21.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpackage/images/Deplacement/total.png"))); // NOI18N jLabel21.setText("TOTAL"); jLabel22.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel22.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpackage/images/Deplacement/matricul_agence.png"))); // NOI18N jLabel22.setText("MATRICULE AGENCE :"); jToggleButton1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jToggleButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpackage/images/Deplacement/upload.png"))); // NOI18N jToggleButton1.setText("UPLOAD"); jToggleButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jToggleButton1ActionPerformed(evt); } }); jRadioButton1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jRadioButton1.setText("OUI"); jRadioButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButton1ActionPerformed(evt); } }); jRadioButton2.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jRadioButton2.setText("OUI"); jTimeChooser1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jTimeChooser1.setOpaque(true); jTimeChooser1.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseMoved(java.awt.event.MouseEvent evt) { jTimeChooser1MouseMoved(evt); } }); jTimeChooser1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jTimeChooser1MouseClicked(evt); } }); jDateChooser1.setDateFormatString("dd-MM-yyyy"); try { Date date = new SimpleDateFormat("dd-MM-yyyy").parse("10-12-1999"); jDateChooser1.setDate(date); } catch (Exception e) { System.out.println(e); } jDateChooser1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jDateChooser1.addContainerListener(new java.awt.event.ContainerAdapter() { public void componentAdded(java.awt.event.ContainerEvent evt) { jDateChooser1ComponentAdded(evt); } }); jDateChooser2.setToolTipText(""); jDateChooser2.setDateFormatString("dd-MM-yyyy"); try { Date date = new SimpleDateFormat("dd-MM-yyyy").parse("10-12-1999"); jDateChooser2.setDate(date); } catch (Exception e) { System.out.println(e); } jDateChooser2.getDateEditor().addPropertyChangeListener( new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent e) { if ("date".equals(e.getPropertyName())) { long delta =(jDateChooser2.getDate().getTime()-jDateChooser1.getDate().getTime())/(1000*60*60*24); jTextField17.setText(""+delta); jTextField18.setText(""+(delta+1)); jTextField19.setText(""+(delta+1)); jTextField20.setText(""+delta); } } }); jDateChooser2.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jDateChooser2.addContainerListener(new java.awt.event.ContainerAdapter() { public void componentAdded(java.awt.event.ContainerEvent evt) { jDateChooser2ComponentAdded(evt); } }); jDateChooser2.addAncestorListener(new javax.swing.event.AncestorListener() { public void ancestorAdded(javax.swing.event.AncestorEvent evt) { jDateChooser2AncestorAdded(evt); } public void ancestorMoved(javax.swing.event.AncestorEvent evt) { } public void ancestorRemoved(javax.swing.event.AncestorEvent evt) { } }); jDateChooser2.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseDragged(java.awt.event.MouseEvent evt) { jDateChooser2MouseDragged(evt); } }); jDateChooser2.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jDateChooser2MouseClicked(evt); } public void mouseEntered(java.awt.event.MouseEvent evt) { jDateChooser2MouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { jDateChooser2MouseExited(evt); } public void mousePressed(java.awt.event.MouseEvent evt) { jDateChooser2MousePressed(evt); } public void mouseReleased(java.awt.event.MouseEvent evt) { jDateChooser2MouseReleased(evt); } }); jDateChooser2.addInputMethodListener(new java.awt.event.InputMethodListener() { public void caretPositionChanged(java.awt.event.InputMethodEvent evt) { } public void inputMethodTextChanged(java.awt.event.InputMethodEvent evt) { jDateChooser2InputMethodTextChanged(evt); } }); jDateChooser2.addPropertyChangeListener(new java.beans.PropertyChangeListener() { public void propertyChange(java.beans.PropertyChangeEvent evt) { jDateChooser2PropertyChange(evt); } }); jDateChooser2.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { jDateChooser2KeyReleased(evt); } }); jDateChooser2.addVetoableChangeListener(new java.beans.VetoableChangeListener() { public void vetoableChange(java.beans.PropertyChangeEvent evt)throws java.beans.PropertyVetoException { jDateChooser2VetoableChange(evt); } }); jTextField11.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jTextField11.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { jTextField11KeyReleased(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel6) .addComponent(jLabel8) .addComponent(jLabel7) .addComponent(jLabel9) .addComponent(jLabel11) .addComponent(jLabel12) .addComponent(jLabel5) .addComponent(jLabel1) .addComponent(jLabel2) .addComponent(jLabel4) .addComponent(jLabel3) .addComponent(jLabel10)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jTextField5) .addComponent(jTextField4) .addComponent(jTextField2) .addComponent(jTextField1) .addComponent(jTextField7) .addComponent(jTextField8) .addComponent(jTextField10) .addComponent(jTextField12) .addComponent(jRadioButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jRadioButton2, javax.swing.GroupLayout.DEFAULT_SIZE, 175, Short.MAX_VALUE) .addComponent(jTextField6, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jTextField11, javax.swing.GroupLayout.Alignment.TRAILING)) .addGap(26, 26, 26) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel14) .addComponent(jLabel13) .addComponent(jLabel15) .addComponent(jLabel16) .addComponent(jLabel17) .addComponent(jLabel18) .addComponent(jLabel19) .addComponent(jLabel20) .addComponent(jLabel21) .addComponent(jLabel22)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 14, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jTextField20, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jTextField18, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jTextField17, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jTextField22, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jTextField19, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jToggleButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 174, Short.MAX_VALUE) .addComponent(jTimeChooser1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jTimeChooser2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jDateChooser2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jDateChooser1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jTextField21)))) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(21, 21, 21) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 38, Short.MAX_VALUE) .addComponent(jLabel13) .addComponent(jLabel1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel14) .addComponent(jLabel2))) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(3, 3, 3) .addComponent(jDateChooser1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jDateChooser2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(5, 5, 5))) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel15) .addComponent(jLabel3) .addComponent(jRadioButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel16) .addComponent(jLabel4)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel17) .addComponent(jLabel5)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel18) .addComponent(jLabel6) .addComponent(jTextField18, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField7, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel19) .addComponent(jLabel7) .addComponent(jTextField19, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField8, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel20) .addComponent(jLabel8) .addComponent(jTextField20, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel21) .addComponent(jLabel9) .addComponent(jRadioButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField21, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jTimeChooser1, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(2, 2, 2) .addComponent(jTimeChooser2, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextField17, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE))) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField10, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel22, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel10) .addComponent(jTextField22, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel11) .addComponent(jTextField11, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField12, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel12))) .addComponent(jToggleButton1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); jDateChooser2.getAccessibleContext().setAccessibleName(""); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jTextField8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField8ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField8ActionPerformed private void jTextField7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField7ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField7ActionPerformed private void jTextField5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField5ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField5ActionPerformed private boolean valide_int(String test){ char[] text = test.toCharArray(); for (char element:text){ if(element!='0'&&element!='1'&&element!='2'&&element!='3'&&element!='4'&&element!='5'&&element!='6'&&element!='7'&&element!='8'&&element!='9'){ return false; } } return true; } private boolean valide_real(String test){ char[] text = test.toCharArray(); for (char element:text){ if(element!='.'&&element!='0'&&element!='1'&&element!='2'&&element!='3'&&element!='4'&&element!='5'&&element!='6'&&element!='7'&&element!='8'&&element!='9'){ return false; } } return true; } private boolean valide_date(String test){ char[] text = test.toCharArray(); if(text.length!=10||text[2]!='-'||text[5]!='-')return false; int day = Character.getNumericValue(text[0])*10+Character.getNumericValue(text[0]); int month = Character.getNumericValue(text[3])*10+Character.getNumericValue(text[4]); int year = Character.getNumericValue(text[6])*1000+Character.getNumericValue(text[7])*100+Character.getNumericValue(text[8])*10+Character.getNumericValue(text[9]); if(day==0||day>31||month==0||month>12||year==0||year>9999)return false; return true; } private String ouiNon(boolean test){ if(test==true)return "oui"; return "non"; } private void jToggleButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jToggleButton1ActionPerformed // TODO add your handling code here: DateFormat date= new SimpleDateFormat("dd-MM-yyyy"); String NomEmployeur = jTextField1.getText(); String PrenomEmployeur = jTextField2.getText(); String VehiculePersonnel = ouiNon(jRadioButton1.isSelected()); String MatriculeVehicule = jTextField4.getText(); String Marque = jTextField5.getText(); String NombreDeChevaux = jTextField6.getText(); String PuissanceFiscale = jTextField7.getText(); String Ordre =jTextField8.getText(); String DroitAutoroute = ouiNon(jRadioButton2.isSelected()); String IndemniteKm=jTextField10.getText(); String Destination=jTextField11.getText(); String Distance=jTextField12.getText(); String DateDeDepart=date.format(jDateChooser1.getDate()); String DateDeRetour=date.format(jDateChooser2.getDate()); String HeureDeDepart=jTimeChooser1.getTimeField().getText(); String HeureDeRetour=jTimeChooser2.getTimeField().getText(); String NuitPasses=jTextField17.getText(); String NombreDePetitDejeuner=jTextField18.getText(); String NombreDeDejeuner=jTextField19.getText(); String NombreDeDiner=jTextField20.getText();; String Total=jTextField21.getText();; String MatriculeAgence=jTextField22.getText(); if(NomEmployeur.isEmpty()||PrenomEmployeur.isEmpty()||MatriculeVehicule.isEmpty()||Marque.isEmpty()||NombreDeChevaux.isEmpty()||PuissanceFiscale.isEmpty()||Ordre.isEmpty()|| IndemniteKm.isEmpty()||Destination.isEmpty()||Distance.isEmpty()||DateDeDepart.isEmpty()||DateDeRetour.isEmpty()||HeureDeDepart.isEmpty()||HeureDeRetour.isEmpty()|| NuitPasses.isEmpty()||NombreDePetitDejeuner.isEmpty()||NombreDeDejeuner.isEmpty()||NombreDeDiner.isEmpty()||Total.isEmpty()||MatriculeAgence.isEmpty()){ JFrame frame = new JFrame(); JOptionPane.showMessageDialog(frame, "un ou plusieurs champs sont vide veuillez remplir tous les champs svp","GESTION DES VEHICULES RADEM",2); } else{ if(valide_int(NombreDeChevaux)==false){ jTextField6.setText(""); JFrame frame = new JFrame(); JOptionPane.showMessageDialog(frame, "le champ NOMBRE DE CHEVEAUX ne doit pas contenir des lettres ou des caractères spéciales, vous devez tapper que des chiffres","GESTION DES VEHICULES RADEM",2); } else if(valide_int(Ordre)==false){ jTextField8.setText(""); JFrame frame = new JFrame(); JOptionPane.showMessageDialog(frame, "le champ ORDRE ne doit pas contenir des lettres ou des caractères spéciales, vous devez tapper que des chiffres","GESTION DES VEHICULES RADEM",2); } else if(valide_real(IndemniteKm)==false){ jTextField10.setText(""); JFrame frame = new JFrame(); JOptionPane.showMessageDialog(frame, "le champ INDOMNITE KM ne doit pas contenir des lettres ou des caractères spéciales, vous devez tapper que des nombres réels, exemple : 15.79 ou 17","GESTION DES VEHICULES RADEM",2); } else if(valide_int(Distance)==false){ jTextField12.setText(""); JFrame frame = new JFrame(); JOptionPane.showMessageDialog(frame, "le champ DISTANCE ne doit pas contenir des lettres ou des caractères spéciales, vous devez tapper que des chiffres","GESTION DES VEHICULES RADEM",2); } else if(valide_date(DateDeDepart)==false){ try { Date dt = new SimpleDateFormat("dd-MM-yyyy").parse("10-12-1999"); jDateChooser1.setDate(dt); } catch (Exception e) { System.out.println(e); } JFrame frame = new JFrame(); JOptionPane.showMessageDialog(frame, "le champ DATE DE DEPART doit contenir une forme de date valide, exemple : 10-12-1999","GESTION DES VEHICULES RADEM",2); } else if(valide_date(DateDeRetour)==false){ try { Date dt = new SimpleDateFormat("dd-MM-yyyy").parse("10-12-1999"); jDateChooser2.setDate(dt); } catch (Exception e) { System.out.println(e); } JFrame frame = new JFrame(); JOptionPane.showMessageDialog(frame, "le champ DATE DE RETOUR doit contenir une forme de date valide, exemple : 10-12-1999","GESTION DES VEHICULES RADEM",2); } else if(valide_int(NuitPasses)==false){ jTextField17.setText(""); JFrame frame = new JFrame(); JOptionPane.showMessageDialog(frame, "le champ NUIT PASSES ne doit pas contenir des lettres ou des caractères spéciales, vous devez tapper que des chiffres","GESTION DES VEHICULES RADEM",2); } else if(valide_int(NombreDePetitDejeuner)==false){ jTextField18.setText(""); JFrame frame = new JFrame(); JOptionPane.showMessageDialog(frame, "le champ NOMBRE DE PETIT DEJEUNER ne doit pas contenir des lettres ou des caractères spéciales, vous devez tapper que des chiffres","GESTION DES VEHICULES RADEM",2); } else if(valide_int(NombreDeDejeuner)==false){ jTextField19.setText(""); JFrame frame = new JFrame(); JOptionPane.showMessageDialog(frame, "le champ NOMBRE DE DEJEUNER ne doit pas contenir des lettres ou des caractères spéciales, vous devez tapper que des chiffres","GESTION DES VEHICULES RADEM",2); } else if(valide_int(NombreDeDiner)==false){ jTextField20.setText(""); JFrame frame = new JFrame(); JOptionPane.showMessageDialog(frame, "le champ NOMBRE DE DINER ne doit pas contenir des lettres ou des caractères spéciales, vous devez tapper que des chiffres","GESTION DES VEHICULES RADEM",2); } else if(valide_real(Total)==false){ jTextField21.setText(""); JFrame frame = new JFrame(); JOptionPane.showMessageDialog(frame, "le champ TOTAL ne doit pas contenir des lettres ou des caractères spéciales, vous devez tapper que des nombres réels, exemple : 15.79 ou 17","GESTION DES VEHICULES RADEM",2); } else{ Connection con = null; try { con = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:orcl", "c##admin", "admin"); } catch (SQLException ex) { Logger.getLogger(login.class.getName()).log(Level.SEVERE, null, ex); } // Create a statement for SQL query Statement stmt = null; try { stmt = con.createStatement(); } catch (SQLException ex) { Logger.getLogger(login.class.getName()).log(Level.SEVERE, null, ex); } // Execute the query ResultSet rsl = null; try { String sql = "insert into deplacement values('"+NomEmployeur+"','"+PrenomEmployeur+"','"+VehiculePersonnel+"','"+MatriculeVehicule+"','"+Marque+ "',"+NombreDeChevaux+",'"+PuissanceFiscale+"',"+Ordre+",'"+DroitAutoroute+"',"+IndemniteKm+",'"+Destination+"',"+Distance+ ",to_date('"+DateDeDepart+" "+HeureDeDepart+"','dd-MM-yyyy hh24:mi:ss'),to_date('"+DateDeRetour+" "+HeureDeRetour+"','dd-MM-yyyy hh24:mi:ss'),'"+ HeureDeDepart+"','"+HeureDeRetour+"',"+NuitPasses+","+NombreDePetitDejeuner+","+NombreDeDejeuner+","+NombreDeDiner+","+Total+",'"+MatriculeAgence+"')"; stmt.executeQuery(sql); } catch (SQLException ex) { Logger.getLogger(Admin.class.getName()).log(Level.SEVERE, null, ex); } this.setVisible(false); JFrame frame = new JFrame(); JOptionPane.showMessageDialog(frame, "ce deplacement est ajouté avec succès","GESTION DES VEHICULES RADEM",1); } } }//GEN-LAST:event_jToggleButton1ActionPerformed private void jTextField12ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField12ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField12ActionPerformed private void jTextField18ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField18ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField18ActionPerformed private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton1ActionPerformed // TODO add your handling code here: if(jRadioButton1.isSelected()){ Connection con = null; try { con = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:orcl", "c##admin", "admin"); } catch (SQLException ex) { Logger.getLogger(login.class.getName()).log(Level.SEVERE, null, ex); } // Create a statement for SQL query Statement stmt = null; try { stmt = con.createStatement(); } catch (SQLException ex) { Logger.getLogger(login.class.getName()).log(Level.SEVERE, null, ex); } ResultSet rsl = null; try { String sql = "select * from voiturepersonel where (nomemployeur = '"+jTextField1.getText()+"' AND prenomemployeur = '"+jTextField2.getText()+"' )"; rsl=stmt.executeQuery(sql); } catch (SQLException ex) { Logger.getLogger(Admin.class.getName()).log(Level.SEVERE, null, ex); } String matricule=null; String marque=null; String nbrchevaux=null; String puissance=null; int i=0; try { while(rsl.next()){ matricule= rsl.getString("matricul"); marque=rsl.getString("marque"); nbrchevaux=rsl.getString("nbrchevaux"); puissance=rsl.getString("puissancefiscal"); i++; } } catch (SQLException ex) { Logger.getLogger(AjoutDeplacement.class.getName()).log(Level.SEVERE, null, ex); } if(i!=0){ jTextField4.setText(matricule); jTextField5.setText(marque); jTextField6.setText(nbrchevaux); jTextField7.setText(puissance); } } else{ } }//GEN-LAST:event_jRadioButton1ActionPerformed private void jDateChooser2InputMethodTextChanged(java.awt.event.InputMethodEvent evt) {//GEN-FIRST:event_jDateChooser2InputMethodTextChanged // TODO add your handling code here: }//GEN-LAST:event_jDateChooser2InputMethodTextChanged private void jDateChooser2ComponentAdded(java.awt.event.ContainerEvent evt) {//GEN-FIRST:event_jDateChooser2ComponentAdded // TODO add your handling code here: }//GEN-LAST:event_jDateChooser2ComponentAdded private void jDateChooser1ComponentAdded(java.awt.event.ContainerEvent evt) {//GEN-FIRST:event_jDateChooser1ComponentAdded // TODO add your handling code here: }//GEN-LAST:event_jDateChooser1ComponentAdded private void jTimeChooser1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTimeChooser1MouseClicked // TODO add your handling code here: System.out.println("the time is : "+jDateChooser1.getDate()); }//GEN-LAST:event_jTimeChooser1MouseClicked private void jTextField17ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField17ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField17ActionPerformed private void jTextField17MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextField17MouseClicked // TODO add your handling code here: }//GEN-LAST:event_jTextField17MouseClicked private void jTimeChooser1MouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTimeChooser1MouseMoved // TODO add your handling code here: }//GEN-LAST:event_jTimeChooser1MouseMoved private void jDateChooser2MousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jDateChooser2MousePressed // TODO add your handling code here: }//GEN-LAST:event_jDateChooser2MousePressed private void jDateChooser2MouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jDateChooser2MouseExited // TODO add your handling code here: }//GEN-LAST:event_jDateChooser2MouseExited private void jDateChooser2MouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jDateChooser2MouseReleased // TODO add your handling code here: }//GEN-LAST:event_jDateChooser2MouseReleased private void jDateChooser2MouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jDateChooser2MouseEntered // TODO add your handling code here: }//GEN-LAST:event_jDateChooser2MouseEntered private void jDateChooser2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jDateChooser2MouseClicked // TODO add your handling code here: }//GEN-LAST:event_jDateChooser2MouseClicked private void jDateChooser2MouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jDateChooser2MouseDragged // TODO add your handling code here: }//GEN-LAST:event_jDateChooser2MouseDragged private void jDateChooser2VetoableChange(java.beans.PropertyChangeEvent evt)throws java.beans.PropertyVetoException {//GEN-FIRST:event_jDateChooser2VetoableChange // TODO add your handling code here: }//GEN-LAST:event_jDateChooser2VetoableChange private void jDateChooser2PropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_jDateChooser2PropertyChange // TODO add your handling code here: }//GEN-LAST:event_jDateChooser2PropertyChange private void jDateChooser2AncestorAdded(javax.swing.event.AncestorEvent evt) {//GEN-FIRST:event_jDateChooser2AncestorAdded // TODO add your handling code here: }//GEN-LAST:event_jDateChooser2AncestorAdded private void jDateChooser2KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jDateChooser2KeyReleased // TODO add your handling code here: System.out.println("the time is : "+jDateChooser1.getDate()); }//GEN-LAST:event_jDateChooser2KeyReleased private void jTextField11KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField11KeyReleased // TODO add your handling code here: String destination = jTextField11.getText(); try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(login.class.getName()).log(Level.SEVERE, null, ex); } // Create a connection Connection con = null; try { con = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:orcl", "c##admin", "admin"); } catch (SQLException ex) { Logger.getLogger(login.class.getName()).log(Level.SEVERE, null, ex); } // Create a statement for SQL query Statement stmt = null; try { stmt = con.createStatement(); } catch (SQLException ex) { Logger.getLogger(login.class.getName()).log(Level.SEVERE, null, ex); } // Execute the query ResultSet rsl = null; try { rsl = stmt.executeQuery("select * from ville"); } catch (SQLException ex) { Logger.getLogger(login.class.getName()).log(Level.SEVERE, null, ex); } try { while(rsl.next()){ String dest=rsl.getString("ville"); if(destination.equals(dest)){ jTextField12.setText(rsl.getString("distance")); //break; } } } catch (SQLException ex) { Logger.getLogger(login.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_jTextField11KeyReleased /** * @param args the command line arguments */ // Variables declaration - do not modify//GEN-BEGIN:variables private com.toedter.calendar.JDateChooser jDateChooser1; private com.toedter.calendar.JDateChooser jDateChooser2; private javax.swing.JLabel jLabel0; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel15; private javax.swing.JLabel jLabel16; private javax.swing.JLabel jLabel17; private javax.swing.JLabel jLabel18; private javax.swing.JLabel jLabel19; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel20; private javax.swing.JLabel jLabel21; private javax.swing.JLabel jLabel22; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JRadioButton jRadioButton1; private javax.swing.JRadioButton jRadioButton2; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField10; private javax.swing.JTextField jTextField11; private javax.swing.JTextField jTextField12; private javax.swing.JTextField jTextField17; private javax.swing.JTextField jTextField18; private javax.swing.JTextField jTextField19; private javax.swing.JTextField jTextField2; private javax.swing.JTextField jTextField20; private javax.swing.JTextField jTextField21; private javax.swing.JTextField jTextField22; private javax.swing.JTextField jTextField4; private javax.swing.JTextField jTextField5; private javax.swing.JTextField jTextField6; private javax.swing.JTextField jTextField7; private javax.swing.JTextField jTextField8; private lu.tudor.santec.jtimechooser.JTimeChooser jTimeChooser1; private lu.tudor.santec.jtimechooser.JTimeChooser jTimeChooser2; private javax.swing.JToggleButton jToggleButton1; // End of variables declaration//GEN-END:variables }
56,111
0.623148
0.601219
991
55.600403
42.769367
235
false
false
0
0
0
0
0
0
0.827447
false
false
4
ed03e97fd452e156128086b69999edf327b34228
15,874,199,177,775
525a53383e2383c26c6c7bec1a3c307365954545
/src/main/java/com/biddingplatform/db/entities/Fee.java
49a2f670b06923816e04523bfa38ecd0caec27b3
[]
no_license
mareksagan/BiddingPlatform
https://github.com/mareksagan/BiddingPlatform
1c503d13b36c942627b06c6f16c40b79260125d6
666a131904fddc15f4b2f0188271c8706a63df85
refs/heads/master
2022-11-11T21:30:05.186000
2020-06-30T20:56:59
2020-06-30T20:56:59
261,062,036
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.biddingplatform.db.entities; import javax.persistence.*; import java.util.UUID; @Entity @Table(name = "fee") public class Fee { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id", nullable = false) private UUID id; @OneToOne @JoinColumn(name= "id", insertable = false, updatable = false) private Category category; @Column(name = "percentage", nullable = false, precision = 0) private double percentage; public UUID getId() { return id; } public Fee setId(UUID id) { this.id = id; return this; } public Category getCategory() { return category; } public Fee setCategory(Category category) { this.category = category; return this; } public double getPercentage() { return percentage; } public Fee setPercentage(double percentage) { this.percentage = percentage; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Fee feeEntity = (Fee) o; if (Double.compare(feeEntity.percentage, percentage) != 0) return false; if (id != null ? !id.equals(feeEntity.id) : feeEntity.id != null) return false; if (category != null ? !category.equals(feeEntity.category) : feeEntity.category != null) return false; return true; } @Override public int hashCode() { int result; long temp; result = id != null ? id.hashCode() : 0; result = 31 * result + (category != null ? category.hashCode() : 0); temp = Double.doubleToLongBits(percentage); result = 31 * result + (int) (temp ^ (temp >>> 32)); return result; } }
UTF-8
Java
1,828
java
Fee.java
Java
[]
null
[]
package com.biddingplatform.db.entities; import javax.persistence.*; import java.util.UUID; @Entity @Table(name = "fee") public class Fee { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id", nullable = false) private UUID id; @OneToOne @JoinColumn(name= "id", insertable = false, updatable = false) private Category category; @Column(name = "percentage", nullable = false, precision = 0) private double percentage; public UUID getId() { return id; } public Fee setId(UUID id) { this.id = id; return this; } public Category getCategory() { return category; } public Fee setCategory(Category category) { this.category = category; return this; } public double getPercentage() { return percentage; } public Fee setPercentage(double percentage) { this.percentage = percentage; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Fee feeEntity = (Fee) o; if (Double.compare(feeEntity.percentage, percentage) != 0) return false; if (id != null ? !id.equals(feeEntity.id) : feeEntity.id != null) return false; if (category != null ? !category.equals(feeEntity.category) : feeEntity.category != null) return false; return true; } @Override public int hashCode() { int result; long temp; result = id != null ? id.hashCode() : 0; result = 31 * result + (category != null ? category.hashCode() : 0); temp = Double.doubleToLongBits(percentage); result = 31 * result + (int) (temp ^ (temp >>> 32)); return result; } }
1,828
0.595733
0.590263
73
24.041096
24.117542
111
false
false
0
0
0
0
0
0
0.506849
false
false
4
afb2659984354e540d338f32cb971f5d422a9da6
20,194,936,281,739
a3faf05d1aee36e96a2b77384892ef2df580f4cc
/CanonDataStructures/src/main/java/codefellows/datastructures/LinkedQueue.java
e58115179fcd32692872da25b1635ea099229dc1
[]
no_license
Plastiche/amazon-java-502d1
https://github.com/Plastiche/amazon-java-502d1
9268e7ff63205bf042e0b5e2111203fafee0aa05
592b903b93cd38af0eedced7215243220b529073
refs/heads/master
2021-02-25T14:16:31.555000
2020-02-05T23:46:52
2020-02-05T23:46:52
245,456,625
2
0
null
true
2020-03-06T15:39:04
2020-03-06T15:39:03
2020-02-05T23:46:56
2020-02-05T23:46:52
9,122
0
0
0
null
false
false
package codefellows.datastructures; public class LinkedQueue<E> implements Queue<E> { private LinkedList<E> list; public LinkedQueue() { list = new LinkedList<>(); } @Override public int size() { return list.size(); } @Override public boolean isEmpty() { return list.isEmpty(); } @Override public void enqueue(E value) { list.append(value); } @Override public E dequeue() { if (!this.isEmpty()) { return list.removeAtIndex(0); } return null; } @Override public E peek() { if (!this.isEmpty()) { return list.get(0); } return null; } }
UTF-8
Java
717
java
LinkedQueue.java
Java
[]
null
[]
package codefellows.datastructures; public class LinkedQueue<E> implements Queue<E> { private LinkedList<E> list; public LinkedQueue() { list = new LinkedList<>(); } @Override public int size() { return list.size(); } @Override public boolean isEmpty() { return list.isEmpty(); } @Override public void enqueue(E value) { list.append(value); } @Override public E dequeue() { if (!this.isEmpty()) { return list.removeAtIndex(0); } return null; } @Override public E peek() { if (!this.isEmpty()) { return list.get(0); } return null; } }
717
0.527197
0.524407
40
16.924999
13.528465
49
false
false
0
0
0
0
0
0
0.25
false
false
4
b0ef4a61944e8b1505739e507139d36ae7588ef8
25,262,997,674,433
448a7f3a1ec5d76ee47b97f343a5437c1d670eb9
/src/test/java/de/tuberlin/av/openteagle/api/TestCLI.java
cba21a64e5d4d260ae9b1b0292cbd2a81253a0a7
[]
no_license
tubav/OpenTeagle_API
https://github.com/tubav/OpenTeagle_API
80d5656c95bdfc7f987bb1b6ab8729d99131047a
a0da7e295b02f1a5cc7e1a42436b6d58fd7a0800
refs/heads/master
2021-01-13T02:31:59.370000
2012-07-02T07:13:27
2012-07-02T07:13:27
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package de.tuberlin.av.openteagle.api; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class TestCLI { private transient CLI cli; @Before public void setUp() { this.cli = new CLI(); } @Test public void testWrongParameter() { final String[] args = { "sdf" }; final String expected = "ERROR"; final String cliResult = this.cli.parse(args); Assert.assertTrue(cliResult.startsWith(expected)); } @Test public void testListVCTsCommand() { final String[] args = { "listVCTs" }; final String unexpected = "Usage"; final String cliResult = this.cli.parse(args); Assert.assertFalse(cliResult.isEmpty()); Assert.assertFalse(cliResult.contains(unexpected)); } @Test public void testShowVCTCommand() { final String[] args = { "showVCT", "-id=1" }; final String unexpected = "Usage"; final String cliResult = this.cli.parse(args); Assert.assertFalse(cliResult.isEmpty()); Assert.assertFalse(cliResult.contains(unexpected)); } @Test public void testShowUnknownVCTCommand() { final String[] args = { "showVCT", "-id=afsdsadf" }; final String expected = "not found"; final String cliResult = this.cli.parse(args); Assert.assertTrue(cliResult.contains(expected)); } }
UTF-8
Java
1,256
java
TestCLI.java
Java
[]
null
[]
package de.tuberlin.av.openteagle.api; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class TestCLI { private transient CLI cli; @Before public void setUp() { this.cli = new CLI(); } @Test public void testWrongParameter() { final String[] args = { "sdf" }; final String expected = "ERROR"; final String cliResult = this.cli.parse(args); Assert.assertTrue(cliResult.startsWith(expected)); } @Test public void testListVCTsCommand() { final String[] args = { "listVCTs" }; final String unexpected = "Usage"; final String cliResult = this.cli.parse(args); Assert.assertFalse(cliResult.isEmpty()); Assert.assertFalse(cliResult.contains(unexpected)); } @Test public void testShowVCTCommand() { final String[] args = { "showVCT", "-id=1" }; final String unexpected = "Usage"; final String cliResult = this.cli.parse(args); Assert.assertFalse(cliResult.isEmpty()); Assert.assertFalse(cliResult.contains(unexpected)); } @Test public void testShowUnknownVCTCommand() { final String[] args = { "showVCT", "-id=afsdsadf" }; final String expected = "not found"; final String cliResult = this.cli.parse(args); Assert.assertTrue(cliResult.contains(expected)); } }
1,256
0.703025
0.702229
58
20.655172
19.857729
54
false
false
0
0
0
0
0
0
1.431034
false
false
4
7bb929cb74321b318ac3188e3ea535558c837982
22,522,808,523,781
ded2330f5d1589d50fb531a3466a277163a9c5f2
/meal/jxd-whotel/src/main/java/com/whotel/front/entity/PayOrder.java
521c07e6f4cacc705ce12efdc10ce158f0981c88
[]
no_license
hasone/whotel
https://github.com/hasone/whotel
d106cb85ca0fecfa7a0f631b096c8c396e806b76
92ab351d056021f02539262e74c019a6363e9be7
refs/heads/master
2021-06-18T01:22:50.462000
2017-06-14T12:10:47
2017-06-14T12:10:47
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.whotel.front.entity; import java.util.Date; import java.util.List; import org.mongodb.morphia.annotations.Entity; import org.mongodb.morphia.annotations.Indexed; import com.whotel.common.entity.UnDeletedEntity; import com.whotel.common.enums.PayMent; import com.whotel.common.enums.PayMode; import com.whotel.common.enums.TradeStatus; import com.whotel.common.util.RepoUtil; import com.whotel.company.entity.Company; /** * 支付订单 * * @author fy * */ @Entity(noClassnameStored=true) public class PayOrder extends UnDeletedEntity { private static final long serialVersionUID = 4583963349534789697L; private String name; private Long totalFee; private Long refundFee; @Indexed(unique = true) private String orderSn; private String tradeSn; private PayMent payMent; private PayMode payMode = PayMode.CHARGE; private Integer nums; private String businessId; private TradeStatus status; private String openId; private String companyId; private String remark; private Date createTime; private Date updateTime; private Boolean wxnotifyState;//通知状态,true为通知e运通成功,false为通知e运通失败 private String mbrCardTypeCode; private String hotelNmae; private String hotelCode; private String mbrCardNo; public String getName() { return name; } public void setName(String name) { this.name = name; } public Long getTotalFee() { return totalFee; } public void setTotalFee(Long totalFee) { this.totalFee = totalFee; } public String getOrderSn() { return orderSn; } public void setOrderSn(String orderSn) { this.orderSn = orderSn; } public String getTradeSn() { return tradeSn; } public void setTradeSn(String tradeSn) { this.tradeSn = tradeSn; } public TradeStatus getStatus() { return status; } public void setStatus(TradeStatus status) { this.status = status; } public String getOpenId() { return openId; } public void setOpenId(String openId) { this.openId = openId; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public PayMent getPayMent() { return payMent; } public void setPayMent(PayMent payMent) { this.payMent = payMent; } public PayMode getPayMode() { return payMode; } public void setPayMode(PayMode payMode) { this.payMode = payMode; } public Integer getNums() { return nums; } public void setNums(Integer nums) { this.nums = nums; } public String getBusinessId() { return businessId; } public void setBusinessId(String businessId) { this.businessId = businessId; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public String getCompanyId() { return companyId; } public void setCompanyId(String companyId) { this.companyId = companyId; } public Company getCompany() { return RepoUtil.getCompany(companyId); } public Boolean getWxnotifyState() { return wxnotifyState; } public void setWxnotifyState(Boolean wxnotifyState) { this.wxnotifyState = wxnotifyState; } public String getMbrCardTypeCode() { return mbrCardTypeCode; } public void setMbrCardTypeCode(String mbrCardTypeCode) { this.mbrCardTypeCode = mbrCardTypeCode; } public String getHotelNmae() { return hotelNmae; } public void setHotelNmae(String hotelNmae) { this.hotelNmae = hotelNmae; } public String getHotelCode() { return hotelCode; } public void setHotelCode(String hotelCode) { this.hotelCode = hotelCode; } public String getMbrCardNo() { return mbrCardNo; } public void setMbrCardNo(String mbrCardNo) { this.mbrCardNo = mbrCardNo; } @Override public String toString() { return "PayOrder [name=" + name + ", totalFee=" + totalFee + ", orderSn=" + orderSn + ", tradeSn=" + tradeSn + ", payMent=" + payMent + ", payMode=" + payMode + ", nums=" + nums + ", businessId=" + businessId + ", status=" + status + ", openId=" + openId + ", companyId=" + companyId + ", remark=" + remark + ", createTime=" + createTime + ", updateTime=" + updateTime + ", wxnotifyState=" + wxnotifyState + ", mbrCardTypeCode=" + mbrCardTypeCode + ", hotelNmae=" + hotelNmae + ", hotelCode=" + hotelCode + ", mbrCardNo=" + mbrCardNo + "]"; } public Long getRefundFee() { return refundFee; } public void setRefundFee(Long refundFee) { this.refundFee = refundFee; } }
UTF-8
Java
4,858
java
PayOrder.java
Java
[ { "context": "y.entity.Company;\r\n\r\n/**\r\n * 支付订单\r\n * \r\n * @author fy\r\n * \r\n */\r\n@Entity(noClassnameStored=true)\r\npubli", "end": 480, "score": 0.9548356533050537, "start": 478, "tag": "USERNAME", "value": "fy" } ]
null
[]
package com.whotel.front.entity; import java.util.Date; import java.util.List; import org.mongodb.morphia.annotations.Entity; import org.mongodb.morphia.annotations.Indexed; import com.whotel.common.entity.UnDeletedEntity; import com.whotel.common.enums.PayMent; import com.whotel.common.enums.PayMode; import com.whotel.common.enums.TradeStatus; import com.whotel.common.util.RepoUtil; import com.whotel.company.entity.Company; /** * 支付订单 * * @author fy * */ @Entity(noClassnameStored=true) public class PayOrder extends UnDeletedEntity { private static final long serialVersionUID = 4583963349534789697L; private String name; private Long totalFee; private Long refundFee; @Indexed(unique = true) private String orderSn; private String tradeSn; private PayMent payMent; private PayMode payMode = PayMode.CHARGE; private Integer nums; private String businessId; private TradeStatus status; private String openId; private String companyId; private String remark; private Date createTime; private Date updateTime; private Boolean wxnotifyState;//通知状态,true为通知e运通成功,false为通知e运通失败 private String mbrCardTypeCode; private String hotelNmae; private String hotelCode; private String mbrCardNo; public String getName() { return name; } public void setName(String name) { this.name = name; } public Long getTotalFee() { return totalFee; } public void setTotalFee(Long totalFee) { this.totalFee = totalFee; } public String getOrderSn() { return orderSn; } public void setOrderSn(String orderSn) { this.orderSn = orderSn; } public String getTradeSn() { return tradeSn; } public void setTradeSn(String tradeSn) { this.tradeSn = tradeSn; } public TradeStatus getStatus() { return status; } public void setStatus(TradeStatus status) { this.status = status; } public String getOpenId() { return openId; } public void setOpenId(String openId) { this.openId = openId; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public PayMent getPayMent() { return payMent; } public void setPayMent(PayMent payMent) { this.payMent = payMent; } public PayMode getPayMode() { return payMode; } public void setPayMode(PayMode payMode) { this.payMode = payMode; } public Integer getNums() { return nums; } public void setNums(Integer nums) { this.nums = nums; } public String getBusinessId() { return businessId; } public void setBusinessId(String businessId) { this.businessId = businessId; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public String getCompanyId() { return companyId; } public void setCompanyId(String companyId) { this.companyId = companyId; } public Company getCompany() { return RepoUtil.getCompany(companyId); } public Boolean getWxnotifyState() { return wxnotifyState; } public void setWxnotifyState(Boolean wxnotifyState) { this.wxnotifyState = wxnotifyState; } public String getMbrCardTypeCode() { return mbrCardTypeCode; } public void setMbrCardTypeCode(String mbrCardTypeCode) { this.mbrCardTypeCode = mbrCardTypeCode; } public String getHotelNmae() { return hotelNmae; } public void setHotelNmae(String hotelNmae) { this.hotelNmae = hotelNmae; } public String getHotelCode() { return hotelCode; } public void setHotelCode(String hotelCode) { this.hotelCode = hotelCode; } public String getMbrCardNo() { return mbrCardNo; } public void setMbrCardNo(String mbrCardNo) { this.mbrCardNo = mbrCardNo; } @Override public String toString() { return "PayOrder [name=" + name + ", totalFee=" + totalFee + ", orderSn=" + orderSn + ", tradeSn=" + tradeSn + ", payMent=" + payMent + ", payMode=" + payMode + ", nums=" + nums + ", businessId=" + businessId + ", status=" + status + ", openId=" + openId + ", companyId=" + companyId + ", remark=" + remark + ", createTime=" + createTime + ", updateTime=" + updateTime + ", wxnotifyState=" + wxnotifyState + ", mbrCardTypeCode=" + mbrCardTypeCode + ", hotelNmae=" + hotelNmae + ", hotelCode=" + hotelCode + ", mbrCardNo=" + mbrCardNo + "]"; } public Long getRefundFee() { return refundFee; } public void setRefundFee(Long refundFee) { this.refundFee = refundFee; } }
4,858
0.678171
0.67422
240
18.049999
21.64538
163
false
false
0
0
0
0
0
0
1.325
false
false
4
ec14553785e4bb0c5b0a44355ba8181c4d055b2c
8,504,035,252,395
6f7f1e133cdf8f0e6b8b93bedee1b3908d13588f
/src/StringTest/StringMethod.java
06def3b7a6a634a69c82e8944b6a8187c8627eb5
[]
no_license
zhoulaiyin/javaprojects
https://github.com/zhoulaiyin/javaprojects
68553cb11846ddd0bccac3ff09150226d126032c
accdae505e0ce70ebad8c9773653e3e8fcf18b85
refs/heads/master
2021-04-19T12:46:01.331000
2020-09-22T11:48:07
2020-09-22T11:48:07
249,605,218
0
0
null
false
2020-03-24T03:56:28
2020-03-24T03:37:41
2020-03-24T03:37:45
2020-03-24T03:56:27
0
0
0
0
null
false
false
package StringTest; public class StringMethod { public void replace() { String str = "Hello World"; System.out.println( str.replace( 'H','W' ) ); System.out.println( str.replaceFirst("He", "Wa") ); System.out.println( str.replaceAll("He", "Ha") ); } public void split() { String str = "www-runoob-com"; String[] temp; String delimeter = "-"; temp = str.split(delimeter); for(int i =0; i < temp.length ; i++){ System.out.println(temp[i]); System.out.println(""); } System.out.println("------java for each-----"); String str1 = "www.runoob.com"; String[] temp1; String delimeter1 = "\\."; temp1 = str1.split(delimeter1); for(String x : temp1){ System.out.println(x); System.out.println(""); } } public void Concate() { long startTime = System.currentTimeMillis(); for(int i=0;i<5000;i++){ String result = "This is" + "testing the" + "difference"+ "between" + "String"+ "and"+ "StringBuffer"; } long endTime = System.currentTimeMillis(); System.out.println("+拼接耗时: " + (endTime - startTime)+ " ms"); long startTime1 = System.currentTimeMillis(); for(int i=0;i<5000;i++){ StringBuffer result = new StringBuffer(); result.append("This is"); result.append("testing the"); result.append("difference"); result.append("between"); result.append("String"); result.append("and"); result.append("StringBuffer"); } long endTime1 = System.currentTimeMillis(); System.out.println("StringBuffer耗时: " + (endTime1 - startTime1)+ " ms"); } public void find() { String strOrig = "Hello world ,Hello Runoob"; int lastIndex = strOrig.lastIndexOf("Runoob"); if(lastIndex == - 1){ System.out.println("没有发现 Runoob"); }else{ System.out.println("Runoob 找到的位置索引: "+ lastIndex); } } }
GB18030
Java
2,227
java
StringMethod.java
Java
[]
null
[]
package StringTest; public class StringMethod { public void replace() { String str = "Hello World"; System.out.println( str.replace( 'H','W' ) ); System.out.println( str.replaceFirst("He", "Wa") ); System.out.println( str.replaceAll("He", "Ha") ); } public void split() { String str = "www-runoob-com"; String[] temp; String delimeter = "-"; temp = str.split(delimeter); for(int i =0; i < temp.length ; i++){ System.out.println(temp[i]); System.out.println(""); } System.out.println("------java for each-----"); String str1 = "www.runoob.com"; String[] temp1; String delimeter1 = "\\."; temp1 = str1.split(delimeter1); for(String x : temp1){ System.out.println(x); System.out.println(""); } } public void Concate() { long startTime = System.currentTimeMillis(); for(int i=0;i<5000;i++){ String result = "This is" + "testing the" + "difference"+ "between" + "String"+ "and"+ "StringBuffer"; } long endTime = System.currentTimeMillis(); System.out.println("+拼接耗时: " + (endTime - startTime)+ " ms"); long startTime1 = System.currentTimeMillis(); for(int i=0;i<5000;i++){ StringBuffer result = new StringBuffer(); result.append("This is"); result.append("testing the"); result.append("difference"); result.append("between"); result.append("String"); result.append("and"); result.append("StringBuffer"); } long endTime1 = System.currentTimeMillis(); System.out.println("StringBuffer耗时: " + (endTime1 - startTime1)+ " ms"); } public void find() { String strOrig = "Hello world ,Hello Runoob"; int lastIndex = strOrig.lastIndexOf("Runoob"); if(lastIndex == - 1){ System.out.println("没有发现 Runoob"); }else{ System.out.println("Runoob 找到的位置索引: "+ lastIndex); } } }
2,227
0.518028
0.507531
68
31.220589
19.525131
80
false
false
0
0
0
0
0
0
0.691176
false
false
4
3bc4bf8c34b3daba9976f0e500225b44b5b300b5
13,305,808,750,232
7d49a65558edbd185b6b8f3c3cc78d09b39f5492
/src/main/java/Model/builder/MilkTea.java
267e3d9112f3e0588f88beeb35350c13f242c151
[]
no_license
yujun-8848/Flink
https://github.com/yujun-8848/Flink
5ddb22815bd134cbe0393d2d9e403ece5d94e5cb
2af47cf4ae6bbe2cdcbb7227788c6fe40bd93ba1
refs/heads/master
2023-01-22T05:44:05.260000
2020-11-27T09:21:52
2020-11-27T09:21:52
266,236,413
0
0
null
false
2020-11-27T09:23:56
2020-05-23T00:52:36
2020-11-27T09:23:34
2020-11-27T09:23:55
717
0
0
4
Java
false
false
package Model.builder; /** * 建造者模式用于创建过程中稳定,但配置多变的对象。 * 将一个复杂的构建与其表示相分离,使得同样的构建过程可以创建不同的表示。 * 现在建造者模式主要用来通过链式调用生成不同的配置。 * 比如制作一杯珍珠奶茶,它的制作过程是稳定的,除了必须要知道奶茶的种类和规格外, * 是否加珍珠和是否加冰是可选的 */ public class MilkTea { private final String type; private final String size; private final boolean pearl; private final boolean ice; private MilkTea(Builder builder) { this.ice = builder.ice; this.pearl = builder.pearl; this.type = builder.type; this.size = builder.size; } public String show() { StringBuilder sb = new StringBuilder(); if(ice){ sb.append("加冰").append("的"); }else { sb.append("不加冰").append("的"); } if(pearl){ sb.append("加珍珠").append("的"); }else { sb.append("不加珍珠").append("的"); } sb.append(size).append("的").append(type).append("奶茶"); return sb.toString(); } static class Builder { private String type; private String size = "小杯"; private boolean pearl; private boolean ice; public Builder(String type) { this.type = type; } public Builder size(String size) { this.size = size; return this; } public Builder pearl(boolean pearl) { this.pearl = pearl; return this; } public Builder ice(boolean ice) { this.ice = ice; return this; } public MilkTea build() { return new MilkTea(this); } } }
UTF-8
Java
1,919
java
MilkTea.java
Java
[]
null
[]
package Model.builder; /** * 建造者模式用于创建过程中稳定,但配置多变的对象。 * 将一个复杂的构建与其表示相分离,使得同样的构建过程可以创建不同的表示。 * 现在建造者模式主要用来通过链式调用生成不同的配置。 * 比如制作一杯珍珠奶茶,它的制作过程是稳定的,除了必须要知道奶茶的种类和规格外, * 是否加珍珠和是否加冰是可选的 */ public class MilkTea { private final String type; private final String size; private final boolean pearl; private final boolean ice; private MilkTea(Builder builder) { this.ice = builder.ice; this.pearl = builder.pearl; this.type = builder.type; this.size = builder.size; } public String show() { StringBuilder sb = new StringBuilder(); if(ice){ sb.append("加冰").append("的"); }else { sb.append("不加冰").append("的"); } if(pearl){ sb.append("加珍珠").append("的"); }else { sb.append("不加珍珠").append("的"); } sb.append(size).append("的").append(type).append("奶茶"); return sb.toString(); } static class Builder { private String type; private String size = "小杯"; private boolean pearl; private boolean ice; public Builder(String type) { this.type = type; } public Builder size(String size) { this.size = size; return this; } public Builder pearl(boolean pearl) { this.pearl = pearl; return this; } public Builder ice(boolean ice) { this.ice = ice; return this; } public MilkTea build() { return new MilkTea(this); } } }
1,919
0.538989
0.538989
69
22.231884
15.272543
62
false
false
0
0
0
0
0
0
0.405797
false
false
4
2148c4e809e714de030d1c900fb1cc47bd969da7
18,322,330,510,533
06be23b77422e02bb0f5c67e2850a29050b8b8cf
/Shop/src/conn/VizualizareClienti.java
4af67924c0ba57bcf5aca2b7ddd116ee7263b31f
[]
no_license
Stroescu-Andrei/Project-Shop
https://github.com/Stroescu-Andrei/Project-Shop
809927b88e75b48e40d3f8f4af52f925d0fe87ec
576a5042fd8593e7cc63e21a5a8aa432831ed819
refs/heads/master
2020-12-22T23:29:49.725000
2020-01-29T11:16:58
2020-01-29T11:16:58
236,963,317
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 conn; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; import oracle.jdbc.OraclePreparedStatement; import oracle.jdbc.OracleResultSet; /** * * @author stroe */ public class VizualizareClienti extends javax.swing.JFrame { Connection conn=null; OraclePreparedStatement pst=null,pst1=null,pst2=null; OracleResultSet rs=null; /** * Creates new form VizualizareClienti */ public VizualizareClienti() { super("Vizualizare Produse Și Gestiune"); initComponents(); conn=JavaConnectDB.ConnecrDB(); Show_Products_In_JTable(); } int pos =0; //resetare campuri public void clearFields(){ cod.setText(null); nume.setText(null); telefon.setText(null); strada.setText(null); numar.setText(null); tip.setText(null); } //Verificati campurile de intrare public boolean checkInputs(){ if( cod.getText()==null || nume.getText()==null || telefon.getText()==null || strada.getText()==null || numar.getText()==null ){ return false; }else{ try{ Float.parseFloat(numar.getText()); return true; }catch(Exception ex){ return false; } } } //Afisarea datelor in Tabla // 1 -- Umplerea listei cu datele public ArrayList<Clienti> getClientiList(){ ArrayList<Clienti> clientiList = new ArrayList<Clienti>(); String query = "select * from client"; try { Statement state=conn.createStatement(); ResultSet rs=state.executeQuery(query); Clienti product; while(rs.next()){ product=new Clienti(rs.getInt("CODCLIENT"),rs.getString("NUME"),rs.getString("TELEFON"),rs.getString("STRADA"),rs.getString("NUMARUL"),rs.getString("TIPCLIENT")); clientiList.add(product); } } catch (SQLException ex) { Logger.getLogger(VizualizareProduse.class.getName()).log(Level.SEVERE, null, ex); } return clientiList; } // 2 -- Popularea Tablei public void Show_Products_In_JTable(){ ArrayList<Clienti> list = getClientiList(); DefaultTableModel model = (DefaultTableModel)clienti.getModel(); model.setRowCount(0); Object[] row = new Object[6]; for(int i=0;i<list.size();i++){ row[0] = list.get(i).getcod(); row[1] = list.get(i).getnume(); row[2] = list.get(i).gettelefon(); row[3] = list.get(i).getstrada(); row[4] = list.get(i).getnumar(); row[5] = list.get(i).gettip(); model.addRow(row); } } public void ShowItem(int index){ cod.setText(Integer.toString(getClientiList().get(index).getcod())); nume.setText(getClientiList().get(index).getnume()); telefon.setText(getClientiList().get(index).gettelefon()); strada.setText(getClientiList().get(index).getstrada()); numar.setText(getClientiList().get(index).getnumar()); tip.setText(getClientiList().get(index).gettip()); } /** * * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); numar = new javax.swing.JTextField(); strada = new javax.swing.JTextField(); telefon = new javax.swing.JTextField(); nume = new javax.swing.JTextField(); cod = new javax.swing.JTextField(); jScrollPane2 = new javax.swing.JScrollPane(); clienti = new javax.swing.JTable(); urmatorul = new javax.swing.JButton(); anterior = new javax.swing.JButton(); inapoi = new javax.swing.JButton(); jLabel2 = new javax.swing.JLabel(); jLabel12 = new javax.swing.JLabel(); actualizati = new javax.swing.JButton(); sterge = new javax.swing.JButton(); tip = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanel1.setBackground(new java.awt.Color(153, 153, 0)); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel1.setText("Cod Client"); jLabel3.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel3.setText("Nume"); jLabel4.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel4.setText("Telefon"); jLabel5.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel5.setText("Strada"); jLabel6.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel6.setText("Numarul"); jLabel8.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel8.setText("Tip Client"); numar.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N numar.setPreferredSize(new java.awt.Dimension(6, 25)); strada.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N strada.setPreferredSize(new java.awt.Dimension(6, 25)); telefon.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N telefon.setPreferredSize(new java.awt.Dimension(6, 25)); nume.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N nume.setPreferredSize(new java.awt.Dimension(6, 25)); cod.setEditable(false); cod.setBackground(new java.awt.Color(204, 204, 204)); cod.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N cod.setEnabled(false); cod.setPreferredSize(new java.awt.Dimension(6, 25)); clienti.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Cod Client", "Nume", "Telefon", "Strada", "Numarul", "Tip Client" } )); clienti.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { clientiMouseClicked(evt); } }); jScrollPane2.setViewportView(clienti); urmatorul.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N urmatorul.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagini/Forward_20px.png"))); // NOI18N urmatorul.setText("Urmatorul"); urmatorul.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { urmatorulActionPerformed(evt); } }); anterior.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N anterior.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagini/Back_20px.png"))); // NOI18N anterior.setText("Anterior"); anterior.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { anteriorActionPerformed(evt); } }); inapoi.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N inapoi.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagini/Back_20px.png"))); // NOI18N inapoi.setText("Inapoi"); inapoi.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { inapoiActionPerformed(evt); } }); jLabel2.setBackground(new java.awt.Color(0, 204, 204)); jLabel2.setOpaque(true); jLabel12.setBackground(new java.awt.Color(255, 255, 255)); jLabel12.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N jLabel12.setForeground(new java.awt.Color(0, 204, 204)); jLabel12.setText("Vizualizare Clienti Și Gestiune"); actualizati.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N actualizati.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagini/Update_20px.png"))); // NOI18N actualizati.setText("Actualizare"); actualizati.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { actualizatiActionPerformed(evt); } }); sterge.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N sterge.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagini/Delete_20px.png"))); // NOI18N sterge.setText("Ștergere"); sterge.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { stergeActionPerformed(evt); } }); tip.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { tipActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(71, 71, 71) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel6, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel8, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING)) .addGap(12, 12, 12)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(inapoi))) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(17, 17, 17) .addComponent(actualizati) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(sterge)) .addGroup(jPanel1Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(cod, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(telefon, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(numar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(nume, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(strada, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(tip, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel1Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel12) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 817, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(58, 58, 58)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(143, 143, 143) .addComponent(anterior) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(urmatorul) .addGap(146, 146, 146)))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 1218, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(58, 58, 58)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(33, 33, 33) .addComponent(jLabel12) .addGap(65, 65, 65) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(cod, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(22, 22, 22) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(nume, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(22, 22, 22) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(telefon, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(21, 21, 21) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(strada, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(22, 22, 22) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(numar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(22, 22, 22) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel8) .addComponent(tip, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 355, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(92, 92, 92) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 3, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(26, 26, 26) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(inapoi) .addComponent(actualizati) .addComponent(sterge) .addComponent(urmatorul) .addComponent(anterior)) .addContainerGap(66, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 1284, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); setSize(new java.awt.Dimension(1302, 745)); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void clientiMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_clientiMouseClicked // TODO add your handling code here: int index=clienti.getSelectedRow(); ShowItem(index); }//GEN-LAST:event_clientiMouseClicked private void urmatorulActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_urmatorulActionPerformed // TODO add your handling code here: pos++; if(pos>=getClientiList().size()){ pos=getClientiList().size()-1; } ShowItem(pos); }//GEN-LAST:event_urmatorulActionPerformed private void anteriorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_anteriorActionPerformed // TODO add your handling code here: pos--; if(pos<0){ pos=0; } ShowItem(pos); }//GEN-LAST:event_anteriorActionPerformed private void inapoiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_inapoiActionPerformed // TODO add your handling code here: this.hide(); Meniu frm=new Meniu(); frm.setVisible(true); }//GEN-LAST:event_inapoiActionPerformed private void actualizatiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_actualizatiActionPerformed // TODO add your handling code here: if(checkInputs()){ String UptadeQuery=null; pst=null; pst1=null; try { //UptadeQuery="UPDATE localizare SET CODPOSTAL=? where CODCLIENT=?"; //pst1=(OraclePreparedStatement) conn.prepareStatement(UptadeQuery); //pst1.setString(1, postal.getText()); //pst1.executeUpdate(); UptadeQuery="UPDATE client SET NUME=?, TELEFON=?, STRADA=?, NUMARUL=?, TIPCLIENT=? WHERE CODCLIENT=?"; pst=(OraclePreparedStatement) conn.prepareStatement(UptadeQuery); pst.setString(1, nume.getText()); pst.setString(2, telefon.getText()); pst.setString(3, strada.getText()); pst.setString(4, numar.getText()); pst.setString(5, tip.getText()); pst.setString(6, cod.getText()); pst.executeUpdate(); Show_Products_In_JTable(); JOptionPane.showMessageDialog(null, "Clientul A Fost Actualizata!"); clearFields(); } catch (Exception ex) { Logger.getLogger(AdaugatiClienti.class.getName()).log(Level.SEVERE, null, ex); } } }//GEN-LAST:event_actualizatiActionPerformed private void stergeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_stergeActionPerformed // TODO add your handling code here: if(!cod.getText().equals("")) { try { pst1=(OraclePreparedStatement) conn.prepareStatement("DELETE FROM factura WHERE CODCLIENT=?"); int id1=Integer.parseInt(cod.getText()); pst1.setInt(1, id1); pst1.executeUpdate(); pst=(OraclePreparedStatement) conn.prepareStatement("DELETE FROM client WHERE CODCLIENT=?"); int id=Integer.parseInt(cod.getText()); pst.setInt(1, id); pst.executeUpdate(); Show_Products_In_JTable(); JOptionPane.showMessageDialog(null,"Clientul a fost sters!"); clearFields(); } catch (SQLException ex) { Logger.getLogger(AdaugatiClienti.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(null,"Clientul nu a fost sters!"); } }else{ JOptionPane.showMessageDialog(null,"Clientul nu a fost sters : Nu se șterge id-ul!"); } }//GEN-LAST:event_stergeActionPerformed private void tipActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tipActionPerformed // TODO add your handling code here: }//GEN-LAST:event_tipActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(VizualizareClienti.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(VizualizareClienti.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(VizualizareClienti.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(VizualizareClienti.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new VizualizareClienti().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton actualizati; private javax.swing.JButton anterior; private javax.swing.JTable clienti; private javax.swing.JTextField cod; private javax.swing.JButton inapoi; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel8; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JTextField numar; private javax.swing.JTextField nume; private javax.swing.JButton sterge; private javax.swing.JTextField strada; private javax.swing.JTextField telefon; private javax.swing.JTextField tip; private javax.swing.JButton urmatorul; // End of variables declaration//GEN-END:variables }
UTF-8
Java
25,864
java
VizualizareClienti.java
Java
[ { "context": "rt oracle.jdbc.OracleResultSet;\n\n/**\n *\n * @author stroe\n */\npublic class VizualizareClienti extends javax", "end": 585, "score": 0.9993368983268738, "start": 580, "tag": "USERNAME", "value": "stroe" } ]
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 conn; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; import oracle.jdbc.OraclePreparedStatement; import oracle.jdbc.OracleResultSet; /** * * @author stroe */ public class VizualizareClienti extends javax.swing.JFrame { Connection conn=null; OraclePreparedStatement pst=null,pst1=null,pst2=null; OracleResultSet rs=null; /** * Creates new form VizualizareClienti */ public VizualizareClienti() { super("Vizualizare Produse Și Gestiune"); initComponents(); conn=JavaConnectDB.ConnecrDB(); Show_Products_In_JTable(); } int pos =0; //resetare campuri public void clearFields(){ cod.setText(null); nume.setText(null); telefon.setText(null); strada.setText(null); numar.setText(null); tip.setText(null); } //Verificati campurile de intrare public boolean checkInputs(){ if( cod.getText()==null || nume.getText()==null || telefon.getText()==null || strada.getText()==null || numar.getText()==null ){ return false; }else{ try{ Float.parseFloat(numar.getText()); return true; }catch(Exception ex){ return false; } } } //Afisarea datelor in Tabla // 1 -- Umplerea listei cu datele public ArrayList<Clienti> getClientiList(){ ArrayList<Clienti> clientiList = new ArrayList<Clienti>(); String query = "select * from client"; try { Statement state=conn.createStatement(); ResultSet rs=state.executeQuery(query); Clienti product; while(rs.next()){ product=new Clienti(rs.getInt("CODCLIENT"),rs.getString("NUME"),rs.getString("TELEFON"),rs.getString("STRADA"),rs.getString("NUMARUL"),rs.getString("TIPCLIENT")); clientiList.add(product); } } catch (SQLException ex) { Logger.getLogger(VizualizareProduse.class.getName()).log(Level.SEVERE, null, ex); } return clientiList; } // 2 -- Popularea Tablei public void Show_Products_In_JTable(){ ArrayList<Clienti> list = getClientiList(); DefaultTableModel model = (DefaultTableModel)clienti.getModel(); model.setRowCount(0); Object[] row = new Object[6]; for(int i=0;i<list.size();i++){ row[0] = list.get(i).getcod(); row[1] = list.get(i).getnume(); row[2] = list.get(i).gettelefon(); row[3] = list.get(i).getstrada(); row[4] = list.get(i).getnumar(); row[5] = list.get(i).gettip(); model.addRow(row); } } public void ShowItem(int index){ cod.setText(Integer.toString(getClientiList().get(index).getcod())); nume.setText(getClientiList().get(index).getnume()); telefon.setText(getClientiList().get(index).gettelefon()); strada.setText(getClientiList().get(index).getstrada()); numar.setText(getClientiList().get(index).getnumar()); tip.setText(getClientiList().get(index).gettip()); } /** * * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); numar = new javax.swing.JTextField(); strada = new javax.swing.JTextField(); telefon = new javax.swing.JTextField(); nume = new javax.swing.JTextField(); cod = new javax.swing.JTextField(); jScrollPane2 = new javax.swing.JScrollPane(); clienti = new javax.swing.JTable(); urmatorul = new javax.swing.JButton(); anterior = new javax.swing.JButton(); inapoi = new javax.swing.JButton(); jLabel2 = new javax.swing.JLabel(); jLabel12 = new javax.swing.JLabel(); actualizati = new javax.swing.JButton(); sterge = new javax.swing.JButton(); tip = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanel1.setBackground(new java.awt.Color(153, 153, 0)); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel1.setText("Cod Client"); jLabel3.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel3.setText("Nume"); jLabel4.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel4.setText("Telefon"); jLabel5.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel5.setText("Strada"); jLabel6.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel6.setText("Numarul"); jLabel8.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel8.setText("Tip Client"); numar.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N numar.setPreferredSize(new java.awt.Dimension(6, 25)); strada.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N strada.setPreferredSize(new java.awt.Dimension(6, 25)); telefon.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N telefon.setPreferredSize(new java.awt.Dimension(6, 25)); nume.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N nume.setPreferredSize(new java.awt.Dimension(6, 25)); cod.setEditable(false); cod.setBackground(new java.awt.Color(204, 204, 204)); cod.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N cod.setEnabled(false); cod.setPreferredSize(new java.awt.Dimension(6, 25)); clienti.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Cod Client", "Nume", "Telefon", "Strada", "Numarul", "Tip Client" } )); clienti.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { clientiMouseClicked(evt); } }); jScrollPane2.setViewportView(clienti); urmatorul.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N urmatorul.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagini/Forward_20px.png"))); // NOI18N urmatorul.setText("Urmatorul"); urmatorul.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { urmatorulActionPerformed(evt); } }); anterior.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N anterior.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagini/Back_20px.png"))); // NOI18N anterior.setText("Anterior"); anterior.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { anteriorActionPerformed(evt); } }); inapoi.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N inapoi.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagini/Back_20px.png"))); // NOI18N inapoi.setText("Inapoi"); inapoi.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { inapoiActionPerformed(evt); } }); jLabel2.setBackground(new java.awt.Color(0, 204, 204)); jLabel2.setOpaque(true); jLabel12.setBackground(new java.awt.Color(255, 255, 255)); jLabel12.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N jLabel12.setForeground(new java.awt.Color(0, 204, 204)); jLabel12.setText("Vizualizare Clienti Și Gestiune"); actualizati.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N actualizati.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagini/Update_20px.png"))); // NOI18N actualizati.setText("Actualizare"); actualizati.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { actualizatiActionPerformed(evt); } }); sterge.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N sterge.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagini/Delete_20px.png"))); // NOI18N sterge.setText("Ștergere"); sterge.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { stergeActionPerformed(evt); } }); tip.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { tipActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(71, 71, 71) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel6, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel8, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING)) .addGap(12, 12, 12)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(inapoi))) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(17, 17, 17) .addComponent(actualizati) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(sterge)) .addGroup(jPanel1Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(cod, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(telefon, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(numar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(nume, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(strada, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(tip, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel1Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel12) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 817, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(58, 58, 58)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(143, 143, 143) .addComponent(anterior) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(urmatorul) .addGap(146, 146, 146)))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 1218, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(58, 58, 58)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(33, 33, 33) .addComponent(jLabel12) .addGap(65, 65, 65) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(cod, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(22, 22, 22) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(nume, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(22, 22, 22) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(telefon, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(21, 21, 21) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(strada, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(22, 22, 22) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(numar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(22, 22, 22) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel8) .addComponent(tip, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 355, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(92, 92, 92) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 3, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(26, 26, 26) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(inapoi) .addComponent(actualizati) .addComponent(sterge) .addComponent(urmatorul) .addComponent(anterior)) .addContainerGap(66, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 1284, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); setSize(new java.awt.Dimension(1302, 745)); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void clientiMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_clientiMouseClicked // TODO add your handling code here: int index=clienti.getSelectedRow(); ShowItem(index); }//GEN-LAST:event_clientiMouseClicked private void urmatorulActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_urmatorulActionPerformed // TODO add your handling code here: pos++; if(pos>=getClientiList().size()){ pos=getClientiList().size()-1; } ShowItem(pos); }//GEN-LAST:event_urmatorulActionPerformed private void anteriorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_anteriorActionPerformed // TODO add your handling code here: pos--; if(pos<0){ pos=0; } ShowItem(pos); }//GEN-LAST:event_anteriorActionPerformed private void inapoiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_inapoiActionPerformed // TODO add your handling code here: this.hide(); Meniu frm=new Meniu(); frm.setVisible(true); }//GEN-LAST:event_inapoiActionPerformed private void actualizatiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_actualizatiActionPerformed // TODO add your handling code here: if(checkInputs()){ String UptadeQuery=null; pst=null; pst1=null; try { //UptadeQuery="UPDATE localizare SET CODPOSTAL=? where CODCLIENT=?"; //pst1=(OraclePreparedStatement) conn.prepareStatement(UptadeQuery); //pst1.setString(1, postal.getText()); //pst1.executeUpdate(); UptadeQuery="UPDATE client SET NUME=?, TELEFON=?, STRADA=?, NUMARUL=?, TIPCLIENT=? WHERE CODCLIENT=?"; pst=(OraclePreparedStatement) conn.prepareStatement(UptadeQuery); pst.setString(1, nume.getText()); pst.setString(2, telefon.getText()); pst.setString(3, strada.getText()); pst.setString(4, numar.getText()); pst.setString(5, tip.getText()); pst.setString(6, cod.getText()); pst.executeUpdate(); Show_Products_In_JTable(); JOptionPane.showMessageDialog(null, "Clientul A Fost Actualizata!"); clearFields(); } catch (Exception ex) { Logger.getLogger(AdaugatiClienti.class.getName()).log(Level.SEVERE, null, ex); } } }//GEN-LAST:event_actualizatiActionPerformed private void stergeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_stergeActionPerformed // TODO add your handling code here: if(!cod.getText().equals("")) { try { pst1=(OraclePreparedStatement) conn.prepareStatement("DELETE FROM factura WHERE CODCLIENT=?"); int id1=Integer.parseInt(cod.getText()); pst1.setInt(1, id1); pst1.executeUpdate(); pst=(OraclePreparedStatement) conn.prepareStatement("DELETE FROM client WHERE CODCLIENT=?"); int id=Integer.parseInt(cod.getText()); pst.setInt(1, id); pst.executeUpdate(); Show_Products_In_JTable(); JOptionPane.showMessageDialog(null,"Clientul a fost sters!"); clearFields(); } catch (SQLException ex) { Logger.getLogger(AdaugatiClienti.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(null,"Clientul nu a fost sters!"); } }else{ JOptionPane.showMessageDialog(null,"Clientul nu a fost sters : Nu se șterge id-ul!"); } }//GEN-LAST:event_stergeActionPerformed private void tipActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tipActionPerformed // TODO add your handling code here: }//GEN-LAST:event_tipActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(VizualizareClienti.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(VizualizareClienti.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(VizualizareClienti.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(VizualizareClienti.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new VizualizareClienti().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton actualizati; private javax.swing.JButton anterior; private javax.swing.JTable clienti; private javax.swing.JTextField cod; private javax.swing.JButton inapoi; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel8; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JTextField numar; private javax.swing.JTextField nume; private javax.swing.JButton sterge; private javax.swing.JTextField strada; private javax.swing.JTextField telefon; private javax.swing.JTextField tip; private javax.swing.JButton urmatorul; // End of variables declaration//GEN-END:variables }
25,864
0.610325
0.593774
542
46.712177
36.465145
178
false
false
0
0
0
0
0
0
0.808118
false
false
4