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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8ee08635a186d48187b74b06ca1952e5e3e767ca | 32,358,283,610,552 | 0da74559986cc4359fa3b491ead35dbf2ec99615 | /src/com/ds/metrocabs/repository/paymentmodelrepository/PaymentDao.java | 6767460dcb14f49135dcd3a97575e922f703b777 | []
| no_license | ankit261192/MetroCabs | https://github.com/ankit261192/MetroCabs | a77b687adcff540f78d94248fc37830efad515e5 | 5405384fa0567c9f4909e20bad94726dbc857048 | refs/heads/master | 2020-03-08T13:54:42.482000 | 2018-04-05T07:13:24 | 2018-04-05T07:13:24 | 128,170,587 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ds.metrocabs.repository.paymentmodelrepository;
import java.util.List;
import com.ds.metrocabs.model.payment.Payment;
public interface PaymentDao {
public int save(final Payment payment) throws Exception;
public boolean update(final Payment payment ) throws Exception;
public boolean delete(final Payment payment ) throws Exception;
public Payment find(final int id) throws Exception;
public List<Payment> findAll() throws Exception;
}
| UTF-8 | Java | 456 | java | PaymentDao.java | Java | []
| null | []
| package com.ds.metrocabs.repository.paymentmodelrepository;
import java.util.List;
import com.ds.metrocabs.model.payment.Payment;
public interface PaymentDao {
public int save(final Payment payment) throws Exception;
public boolean update(final Payment payment ) throws Exception;
public boolean delete(final Payment payment ) throws Exception;
public Payment find(final int id) throws Exception;
public List<Payment> findAll() throws Exception;
}
| 456 | 0.809211 | 0.809211 | 13 | 34.076923 | 25.378553 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 13 |
dc34d2f0a6fac342b28186875f20ab3084603e85 | 38,225,208,938,501 | 48fed5e3d628425a3fdbbde9aaa2f04a9eed33ef | /java1pc8e1/src/controller/manager/HashPasswordManager.java | f0cae3db1d91deb8c1076b11e0bc3748e2462daf | []
| no_license | laurentiuspilca/java1p_martie_2018 | https://github.com/laurentiuspilca/java1p_martie_2018 | ace17d65843411d639b83162f7f288b36f60bd85 | 0bfae44b7dcc47ebf0363ae69f9379b6165a5a45 | refs/heads/master | 2021-03-30T20:30:51.453000 | 2018-05-04T18:25:52 | 2018-05-04T18:25:52 | 124,581,745 | 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 controller.manager;
import java.security.MessageDigest;
/**
*
* @author student
*/
public class HashPasswordManager {
private HashPasswordManager() {}
private static final class SingletonHolder {
private static final HashPasswordManager INSTANCE = new HashPasswordManager();
}
public static HashPasswordManager getInstance() {
return SingletonHolder.INSTANCE;
}
public String hashPassword(String password) {
try {
StringBuilder sb = new StringBuilder();
MessageDigest md = MessageDigest.getInstance("SHA-512");
byte [] digested = md.digest(password.getBytes());
for (int i=0;i<digested.length;i++) {
sb.append(Integer.toHexString(0XFF & digested[i]));
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
| UTF-8 | Java | 1,168 | java | HashPasswordManager.java | Java | [
{
"context": "rt java.security.MessageDigest;\n\n/**\n *\n * @author student\n */\npublic class HashPasswordManager {\n privat",
"end": 276,
"score": 0.9988762736320496,
"start": 269,
"tag": "USERNAME",
"value": "student"
}
]
| 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 controller.manager;
import java.security.MessageDigest;
/**
*
* @author student
*/
public class HashPasswordManager {
private HashPasswordManager() {}
private static final class SingletonHolder {
private static final HashPasswordManager INSTANCE = new HashPasswordManager();
}
public static HashPasswordManager getInstance() {
return SingletonHolder.INSTANCE;
}
public String hashPassword(String password) {
try {
StringBuilder sb = new StringBuilder();
MessageDigest md = MessageDigest.getInstance("SHA-512");
byte [] digested = md.digest(password.getBytes());
for (int i=0;i<digested.length;i++) {
sb.append(Integer.toHexString(0XFF & digested[i]));
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
| 1,168 | 0.607877 | 0.603596 | 42 | 26.809525 | 24.155487 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.380952 | false | false | 13 |
cc1e783c61fe0bdca0d13d10cd9f8f4b6a584f50 | 11,888,469,537,199 | c4465a51a16b1373b1e4ea1fdb5e4ea125ad21a8 | /bd-build/src/main/java/com/g2forge/bulldozer/build/maven/distribution/DistributionRepository.java | 85d3029a561d6d5164461663f560d2b3920e499f | [
"Apache-2.0"
]
| permissive | g2forge/bulldozer | https://github.com/g2forge/bulldozer | 761fda20e048685ea1a2782e29331b7202de8137 | 800512b1bee8b7807fa621639fe72e5be547841d | refs/heads/master | 2022-12-23T22:58:29.224000 | 2022-12-13T04:37:42 | 2022-12-13T04:37:42 | 120,644,440 | 0 | 1 | Apache-2.0 | false | 2022-12-13T04:35:44 | 2018-02-07T16:58:57 | 2021-12-27T23:42:26 | 2022-12-13T04:35:44 | 276 | 0 | 1 | 1 | Java | false | false | package com.g2forge.bulldozer.build.maven.distribution;
import javax.xml.bind.annotation.XmlRootElement;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
@Data
@Builder
@AllArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
@XmlRootElement(name = "repository")
public class DistributionRepository implements IDistributionRepository {
protected final String id;
protected final String name;
protected final String url;
} | UTF-8 | Java | 527 | java | DistributionRepository.java | Java | []
| null | []
| package com.g2forge.bulldozer.build.maven.distribution;
import javax.xml.bind.annotation.XmlRootElement;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
@Data
@Builder
@AllArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
@XmlRootElement(name = "repository")
public class DistributionRepository implements IDistributionRepository {
protected final String id;
protected final String name;
protected final String url;
} | 527 | 0.833017 | 0.83112 | 22 | 23 | 21.825756 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.545455 | false | false | 13 |
a0ae07fa8d0038f0ed7f1197931890ebf054d5e9 | 29,386,166,309,568 | 5025c1bcc5f5662d072f3f4f546e3e1479e85f14 | /th_dubbo/dubbo_huanxin/src/test/java/com/th/dubbo/server/TestHuanXinApi.java | de2bfde2ba46baf13f5ffd7e9e134ea2a8b6b551 | []
| no_license | 63966367/tanhua | https://github.com/63966367/tanhua | b169ea1f03b00c7a2ac0b4d35383c3591a0f2ec8 | 788e36a833891aebf16c2c0db9c167801d3f0fe0 | refs/heads/master | 2023-05-14T20:17:37.562000 | 2021-06-01T01:55:24 | 2021-06-01T01:55:24 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.th.dubbo.server;
/*
* @author Lise
* @date 2021年05月31日 18:05
* @program: tanhua
*/
import com.th.dubbo.serverIsImpl.api.HuanXinApi;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
@SpringBootTest
@RunWith(SpringRunner.class)
public class TestHuanXinApi {
@Resource
private HuanXinApi huanXinApi;
@Test
public void testGetToken(){
String token = this.huanXinApi.getToken();
System.out.println("token: " +token);
}
@Test
public void testRegister(){
//注册用户id为1的用户到环信
System.out.println(this.huanXinApi.register(1L));
}
@Test
public void testQueryHuanXinUser(){
//根据用户id查询环信用户信息
System.out.println(this.huanXinApi.queryHuanXinUser(1L));
}
}
| UTF-8 | Java | 971 | java | TestHuanXinApi.java | Java | [
{
"context": "package com.th.dubbo.server;\n\n/*\n * @author Lise\n * @date 2021年05月31日 18:05\n * @program: tanhua\n *",
"end": 48,
"score": 0.9731280207633972,
"start": 44,
"tag": "USERNAME",
"value": "Lise"
}
]
| null | []
| package com.th.dubbo.server;
/*
* @author Lise
* @date 2021年05月31日 18:05
* @program: tanhua
*/
import com.th.dubbo.serverIsImpl.api.HuanXinApi;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
@SpringBootTest
@RunWith(SpringRunner.class)
public class TestHuanXinApi {
@Resource
private HuanXinApi huanXinApi;
@Test
public void testGetToken(){
String token = this.huanXinApi.getToken();
System.out.println("token: " +token);
}
@Test
public void testRegister(){
//注册用户id为1的用户到环信
System.out.println(this.huanXinApi.register(1L));
}
@Test
public void testQueryHuanXinUser(){
//根据用户id查询环信用户信息
System.out.println(this.huanXinApi.queryHuanXinUser(1L));
}
}
| 971 | 0.70185 | 0.68444 | 42 | 20.880953 | 19.5341 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 13 |
cf23495d3690d2df756e782c50f20769784e89d2 | 37,125,697,322,030 | e2d07a8a5034647b29388e804d4c456bac6b4441 | /AdidasTest/src/test/java/com/adidastest/steps/PayLoad.java | 4831fd49671775a131acd5b27504d2a2aee1e80a | []
| no_license | aashu555/ad-das_test | https://github.com/aashu555/ad-das_test | e0f6d39de065d292c1ce51d953544d41bf491711 | a541a15274fd8bf0110cd570c8f98e961a536bd3 | refs/heads/master | 2023-02-12T02:15:36.789000 | 2021-01-12T18:31:04 | 2021-01-12T18:31:04 | 329,072,704 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.adidastest.steps;
public class PayLoad {
public static int id=0;
public String getPayLoad(String status) {
String payLoad="{\r\n" +
" \"id\": "+id+",\r\n" +
" \"category\": {\r\n" +
" \"id\": 0,\r\n" +
" \"name\": \"domestic\"\r\n" +
" },\r\n" +
" \"name\": \"cow\",\r\n" +
" \"photoUrls\": [\r\n" +
" \"string\"\r\n" +
" ],\r\n" +
" \"tags\": [\r\n" +
" {\r\n" +
" \"id\": 0,\r\n" +
" \"name\": \"terrestrial animal\"\r\n" +
" }\r\n" +
" ],\r\n" +
" \"status\": \""+status+"\"\r\n" +
"}";
return payLoad;
}
}
| UTF-8 | Java | 630 | java | PayLoad.java | Java | []
| null | []
| package com.adidastest.steps;
public class PayLoad {
public static int id=0;
public String getPayLoad(String status) {
String payLoad="{\r\n" +
" \"id\": "+id+",\r\n" +
" \"category\": {\r\n" +
" \"id\": 0,\r\n" +
" \"name\": \"domestic\"\r\n" +
" },\r\n" +
" \"name\": \"cow\",\r\n" +
" \"photoUrls\": [\r\n" +
" \"string\"\r\n" +
" ],\r\n" +
" \"tags\": [\r\n" +
" {\r\n" +
" \"id\": 0,\r\n" +
" \"name\": \"terrestrial animal\"\r\n" +
" }\r\n" +
" ],\r\n" +
" \"status\": \""+status+"\"\r\n" +
"}";
return payLoad;
}
}
| 630 | 0.387302 | 0.38254 | 27 | 22.333334 | 12.701706 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.444444 | false | false | 13 |
17368d4ed90306a4dee5b2b6b40a39a4d472a91b | 21,904,333,257,732 | 2de2f34bbcab5c7f2a4179cc205ff69656d63b2c | /202co3043_alias-master/Lab/Lab4/GRATO_SV/app/src/main/java/com/example/grato_sv/Activity/tungtookattendance.java | 24fefafe56005944a2ea0e02394178c3c672152b | []
| no_license | tuclen-3/GRATO | https://github.com/tuclen-3/GRATO | 477f9011c4bf1dd60d0762cf059caaa9a349ac47 | 8c36f321f425e37cacc7bb61ca5c7d7d5015d453 | refs/heads/main | 2023-04-08T14:16:21.695000 | 2021-04-25T13:34:03 | 2021-04-25T13:34:03 | 361,428,582 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.grato_sv.Activity;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.example.grato_sv.R;
public class tungtookattendance extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tungtookattendance);
}
} | UTF-8 | Java | 394 | java | tungtookattendance.java | Java | []
| null | []
| package com.example.grato_sv.Activity;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.example.grato_sv.R;
public class tungtookattendance extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tungtookattendance);
}
} | 394 | 0.771574 | 0.771574 | 16 | 23.6875 | 23.288191 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false | 13 |
9182164bc2640e9e3d2ec13700243a634eeb771a | 1,958,505,153,336 | 8542e160d766fb01be19a52f7968608edde8c936 | /otts/WebApplicationFramework/src/otts/test/com/collabscm/otts/access/persistence/MessageRepositoryTest.java | ed5a2d4fa581bf87cd07338fd6c2ac28075397e7 | []
| no_license | dalinhuang/otts | https://github.com/dalinhuang/otts | 1aa9d3dd130d9002930acc5c8b21a7e8c21031e4 | 44b6bb0e90a49b62900c5ed65c3186e44651e361 | refs/heads/master | 2018-01-08T22:08:34.201000 | 2010-12-24T10:46:34 | 2010-12-24T10:46:34 | 53,299,596 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.collabscm.otts.access.persistence;
import static com.hp.gdcc.waf.crypt.Cryptography.encrypt;
import java.util.List;
import org.junit.After;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import com.collabscm.otts.model.Driver;
import com.collabscm.otts.phone.model.Message;
import com.collabscm.otts.phone.model.MessageRepository;
import com.hp.gdcc.waf.test.AbstractTestCase;
import com.hp.gdcc.waf.utils.JsonUtils;
@ContextConfiguration(locations = { "classpath:infrastructure-core-config.xml" })
public class MessageRepositoryTest extends AbstractTestCase {
@Autowired
private MessageRepository messageRepository;
@Test
@Rollback(false)
public void readed() {
System.out.println(encrypt("kfksd&&123"));
System.out.println(encrypt("kfsedbc123"));
System.out.println(encrypt("kfksd&&123111222"));
//messageRepository.readed(2);
}
// @Test
@Rollback(true)
public void save() {
Message message = new Message();
message.setId(4);
// messageRepository.save(message);
}
@After
public void destroy() {
}
}
| UTF-8 | Java | 1,254 | java | MessageRepositoryTest.java | Java | []
| null | []
| package com.collabscm.otts.access.persistence;
import static com.hp.gdcc.waf.crypt.Cryptography.encrypt;
import java.util.List;
import org.junit.After;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import com.collabscm.otts.model.Driver;
import com.collabscm.otts.phone.model.Message;
import com.collabscm.otts.phone.model.MessageRepository;
import com.hp.gdcc.waf.test.AbstractTestCase;
import com.hp.gdcc.waf.utils.JsonUtils;
@ContextConfiguration(locations = { "classpath:infrastructure-core-config.xml" })
public class MessageRepositoryTest extends AbstractTestCase {
@Autowired
private MessageRepository messageRepository;
@Test
@Rollback(false)
public void readed() {
System.out.println(encrypt("kfksd&&123"));
System.out.println(encrypt("kfsedbc123"));
System.out.println(encrypt("kfksd&&123111222"));
//messageRepository.readed(2);
}
// @Test
@Rollback(true)
public void save() {
Message message = new Message();
message.setId(4);
// messageRepository.save(message);
}
@After
public void destroy() {
}
}
| 1,254 | 0.745614 | 0.732057 | 47 | 24.680851 | 22.504946 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.06383 | false | false | 13 |
ce467e3620121f95aec570c031191803d3326b30 | 5,033,701,717,958 | d811700fb4262f10a42bb9617e4a8cd6cbed2350 | /src/main/java/com/mashibing/config/SystemConfig.java | 417d1b3735edbe12e9ba1ebcc4dfe0736b1e6a85 | []
| no_license | wulafrom/01_oa | https://github.com/wulafrom/01_oa | 1cdbf80b6b5555a060f3e1509d593ae23b9b4f91 | 0e5b2a4ae77b6c7d60c658952058235d7efe3b60 | refs/heads/master | 2023-04-16T02:28:16.242000 | 2021-03-30T17:11:27 | 2021-03-30T17:11:27 | 345,108,010 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mashibing.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* 系统配置相关
* @author: h'mm
* @date: 2021/3/9 18:31:55
*/
@Component
public class SystemConfig {
@Value("${system.name}")
private String systemName;
@Value("${system.domain}")
private String domain;
public SystemConfig() {
}
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
public String getSystemName() {
return systemName;
}
public void setSystemName(String systemName) {
this.systemName = systemName;
}
}
| UTF-8 | Java | 719 | java | SystemConfig.java | Java | [
{
"context": "k.stereotype.Component;\n\n/**\n * 系统配置相关\n * @author: h'mm\n * @date: 2021/3/9 18:31:55\n */\n@Component\npublic",
"end": 170,
"score": 0.9997022747993469,
"start": 166,
"tag": "USERNAME",
"value": "h'mm"
}
]
| null | []
| package com.mashibing.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* 系统配置相关
* @author: h'mm
* @date: 2021/3/9 18:31:55
*/
@Component
public class SystemConfig {
@Value("${system.name}")
private String systemName;
@Value("${system.domain}")
private String domain;
public SystemConfig() {
}
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
public String getSystemName() {
return systemName;
}
public void setSystemName(String systemName) {
this.systemName = systemName;
}
}
| 719 | 0.647808 | 0.630835 | 38 | 17.605263 | 16.685228 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.236842 | false | false | 13 |
278cefa5dcb2ab2bafd0b3871d53825aa67f3074 | 5,033,701,714,960 | 548feb853e2bde8e682e7979c9a8913fe8a51ee3 | /src/contest1118/P1589.java | e6e3446ee9cc429880be133cc9d01d79d87aa862 | []
| no_license | fanjinhao/AKOJ | https://github.com/fanjinhao/AKOJ | cc0159c249e45e7eccb251ec39fb86d44b07d334 | 1d940d063eb372e6bbfd1362dc3af1b0145afb2f | refs/heads/master | 2021-07-25T13:03:44.239000 | 2017-11-07T13:26:48 | 2017-11-07T13:26:48 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package contest1118;
import com.sun.media.sound.SoftTuning;
import java.util.Scanner;
/**
* Created by fan on 2017/10/9.
*/
public class P1589 {
static int n, m, top = 0;
static boolean flag = false;
static boolean [][]vis;
static int [][]map;
static Node []node;
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
while (cin.hasNext()) {
n = cin.nextInt();
m = cin.nextInt();
map = new int[n][m];
vis = new boolean[n][m];
node = new Node[n*m];
vis = new boolean[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
map[i][j] = cin.nextInt();
}
}
dfs(0, 0, 1);
if(!flag)
System.out.println("impossible\n");
else
System.out.println();
}
cin.close();
}
private static void dfs(int x, int y, int front) {
if (x == n-1 && y ==m) {
flag = true;
for (int i = 0; i < top; i++) {
System.out.print(String.format("(%d,%d) ", node[i].x+1, node[i].y+1));
}
return;
}
if (x >= n || x < 0 || y >= m || y < 0)
return;
if (vis[x][y]) return;
vis[x][y] = true;
node[top++] = new Node(x, y);
if (map[x][y] >= 5 && map[x][y] <= 6) {
if (front == 1)
dfs(x, y+1, 1);
else if (front == 2)
dfs(x+1, y, 2);
else if (front == 3)
dfs(x, y-1, 3);
else if (front == 4)
dfs(x-1, y, 4);
}
if (map[x][y] >= 1 && map[x][y] <= 4) {
if (front == 1) {
dfs(x-1, y, 4);
dfs(x+1, y, 2);
}
else if (front == 2) {
dfs(x, y+1, 1);
dfs(x, y-1, 3);
}
else if (front == 3) {
dfs(x-1, y, 4);
dfs(x+1, y, 2);
}
else if (front == 4) {
dfs(x, y-1, 3);
dfs(x, y+1, 1);
}
}
vis[x][y] = false;
top--;
return;
}
static class Node {
int x, y;
public Node(int x, int y) {
this.x = x;
this.y = y;
}
}
}
| UTF-8 | Java | 2,459 | java | P1589.java | Java | [
{
"context": "ing;\n\nimport java.util.Scanner;\n\n/**\n * Created by fan on 2017/10/9.\n */\npublic class P1589 {\n static",
"end": 110,
"score": 0.9291431903839111,
"start": 107,
"tag": "USERNAME",
"value": "fan"
}
]
| null | []
| package contest1118;
import com.sun.media.sound.SoftTuning;
import java.util.Scanner;
/**
* Created by fan on 2017/10/9.
*/
public class P1589 {
static int n, m, top = 0;
static boolean flag = false;
static boolean [][]vis;
static int [][]map;
static Node []node;
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
while (cin.hasNext()) {
n = cin.nextInt();
m = cin.nextInt();
map = new int[n][m];
vis = new boolean[n][m];
node = new Node[n*m];
vis = new boolean[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
map[i][j] = cin.nextInt();
}
}
dfs(0, 0, 1);
if(!flag)
System.out.println("impossible\n");
else
System.out.println();
}
cin.close();
}
private static void dfs(int x, int y, int front) {
if (x == n-1 && y ==m) {
flag = true;
for (int i = 0; i < top; i++) {
System.out.print(String.format("(%d,%d) ", node[i].x+1, node[i].y+1));
}
return;
}
if (x >= n || x < 0 || y >= m || y < 0)
return;
if (vis[x][y]) return;
vis[x][y] = true;
node[top++] = new Node(x, y);
if (map[x][y] >= 5 && map[x][y] <= 6) {
if (front == 1)
dfs(x, y+1, 1);
else if (front == 2)
dfs(x+1, y, 2);
else if (front == 3)
dfs(x, y-1, 3);
else if (front == 4)
dfs(x-1, y, 4);
}
if (map[x][y] >= 1 && map[x][y] <= 4) {
if (front == 1) {
dfs(x-1, y, 4);
dfs(x+1, y, 2);
}
else if (front == 2) {
dfs(x, y+1, 1);
dfs(x, y-1, 3);
}
else if (front == 3) {
dfs(x-1, y, 4);
dfs(x+1, y, 2);
}
else if (front == 4) {
dfs(x, y-1, 3);
dfs(x, y+1, 1);
}
}
vis[x][y] = false;
top--;
return;
}
static class Node {
int x, y;
public Node(int x, int y) {
this.x = x;
this.y = y;
}
}
}
| 2,459 | 0.355836 | 0.330216 | 98 | 24.091837 | 15.382263 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.94898 | false | false | 13 |
e34028698f8c3ccec1b0b055ea7e5b1866fa9f7f | 18,803,366,822,301 | 0c912fe3b209bc7cffef0782eaf6c8bd9dd092a1 | /modeshape-jcr/src/test/java/org/modeshape/jcr/RepositoryRestoreTest.java | e0baf26bdbc4d761f421a5dae61e4e957f40a969 | [
"Apache-2.0"
]
| permissive | hchiorean/modeshape | https://github.com/hchiorean/modeshape | a9d2ea6f7a545a5bfda92e9ab3217ca53c3c935f | 70c00f7a6521ab96cb8b0698a23c1c15461a5d2b | refs/heads/master | 2020-04-04T18:41:47.836000 | 2014-07-24T15:03:05 | 2014-07-24T15:03:05 | 2,686,838 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* ModeShape (http://www.modeshape.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.modeshape.jcr;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import javax.jcr.ImportUUIDBehavior;
import javax.jcr.NoSuchWorkspaceException;
import javax.jcr.PathNotFoundException;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.query.Query;
import javax.jcr.query.QueryResult;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.modeshape.common.statistic.Stopwatch;
import org.modeshape.common.util.FileUtil;
import org.modeshape.jcr.api.Problems;
/**
* Test performance writing graph subtrees of various sizes with varying number of properties
*/
public class RepositoryRestoreTest extends SingleUseAbstractTest {
private File backupDirectory;
private File backupDirectory2;
@Override
protected RepositoryConfiguration createRepositoryConfiguration( String repositoryName,
Environment environment ) throws Exception {
return RepositoryConfiguration.read("config/backup-repo-config.json").with(environment);
}
@Before
@Override
public void beforeEach() throws Exception {
File backupArea = new File("target/backupArea");
backupDirectory = new File(backupArea, "repoBackups");
backupDirectory2 = new File(backupArea, "repoBackupsAfter");
FileUtil.delete(backupArea);
backupDirectory.mkdirs();
backupDirectory2.mkdirs();
new File(backupArea, "backRepo").mkdirs();
new File(backupArea, "restoreRepo").mkdirs();
super.beforeEach();
}
@Test
@Ignore( "Comment out when generating and writing export files" )
public void testExporting() throws Exception {
print = true;
String path = "/backupAndRestoreTestContent";
populateRepositoryContent(session(), path);
FileOutputStream stream = new FileOutputStream("src/test/resources/io/generated-3-system-view.xml");
session().exportSystemView(path, stream, false, false);
stream.close();
}
@Test
public void shouldBackupRepositoryWithMultipleWorkspaces() throws Exception {
loadContent();
Problems problems = session().getWorkspace().getRepositoryManager().backupRepository(backupDirectory);
assertNoProblems(problems);
// Make some changes that will not be in the backup ...
session().getRootNode().addNode("node-not-in-backup");
session().save();
assertContentInWorkspace(repository(), "default", "/node-not-in-backup");
assertContentInWorkspace(repository(), "ws2");
assertContentInWorkspace(repository(), "ws3");
// Start up a new repository
((LocalEnvironment)environment).setShared(true);
RepositoryConfiguration config = RepositoryConfiguration.read("config/restore-repo-config.json").with(environment);
JcrRepository newRepository = new JcrRepository(config);
try {
newRepository.start();
// And restore it from the contents ...
JcrSession newSession = newRepository.login();
try {
Problems restoreProblems = newSession.getWorkspace().getRepositoryManager().restoreRepository(backupDirectory);
assertNoProblems(restoreProblems);
} finally {
newSession.logout();
}
// Check that the node that was added *after* the backup is not there ...
assertContentNotInWorkspace(newRepository, "default", "/node-not-in-backup");
// Before we assert the content, create a backup of it (for comparison purposes when debugging) ...
newSession = newRepository.login();
try {
Problems backupProblems = newSession.getWorkspace().getRepositoryManager().backupRepository(backupDirectory2);
assertNoProblems(backupProblems);
} finally {
newSession.logout();
}
assertWorkspaces(newRepository, "default", "ws2", "ws3");
assertContentInWorkspace(newRepository, null);
assertContentInWorkspace(newRepository, "ws2");
assertContentInWorkspace(newRepository, "ws3");
queryContentInWorkspace(newRepository, null);
} finally {
newRepository.shutdown().get(10, TimeUnit.SECONDS);
}
}
@Test
public void shouldBackupAndRestoreRepositoryWithMultipleWorkspaces() throws Exception {
// Load the content and verify it's there ...
loadContent();
assertContentInWorkspace(repository(), "default");
assertContentInWorkspace(repository(), "ws2");
assertContentInWorkspace(repository(), "ws3");
// Make the backup, and check that there are no problems ...
Problems problems = session().getWorkspace().getRepositoryManager().backupRepository(backupDirectory);
assertNoProblems(problems);
// Make some changes that will not be in the backup ...
session().getRootNode().addNode("node-not-in-backup");
session().save();
// Check the content again ...
assertContentInWorkspace(repository(), "default", "/node-not-in-backup");
assertContentInWorkspace(repository(), "ws2");
assertContentInWorkspace(repository(), "ws3");
// Restore the content from the backup into our current repository ...
JcrSession newSession = repository().login();
try {
Problems restoreProblems = newSession.getWorkspace().getRepositoryManager().restoreRepository(backupDirectory);
assertNoProblems(restoreProblems);
} finally {
newSession.logout();
}
assertWorkspaces(repository(), "default", "ws2", "ws3");
// Check the content again ...
assertContentInWorkspace(repository(), "default");
assertContentInWorkspace(repository(), "ws2");
assertContentInWorkspace(repository(), "ws3");
assertContentNotInWorkspace(repository(), "default", "/node-not-in-backup");
queryContentInWorkspace(repository(), null);
}
private void assertWorkspaces( JcrRepository newRepository,
String... workspaceNames ) throws RepositoryException {
Set<String> expectedNames = new HashSet<String>();
for (String expectedName : workspaceNames) {
expectedNames.add(expectedName);
}
Set<String> actualNames = new HashSet<String>();
JcrSession session = newRepository.login();
try {
for (String actualName : session.getWorkspace().getAccessibleWorkspaceNames()) {
actualNames.add(actualName);
}
} finally {
session.logout();
}
assertThat(actualNames, is(expectedNames));
}
private void queryContentInWorkspace( JcrRepository newRepository,
String workspaceName ) throws RepositoryException {
JcrSession session = newRepository.login();
try {
String statement = "SELECT [car:model], [car:year], [car:msrp] FROM [car:Car] AS car";
Query query = session.getWorkspace().getQueryManager().createQuery(statement, Query.JCR_SQL2);
QueryResult results = query.execute();
assertThat(results.getRows().getSize(), is(13L));
} finally {
session.logout();
}
}
private void assertContentInWorkspace( JcrRepository newRepository,
String workspaceName,
String... paths ) throws RepositoryException {
JcrSession session = workspaceName != null ? newRepository.login(workspaceName) : newRepository.login();
try {
session.getRootNode();
session.getNode("/Cars");
session.getNode("/Cars/Hybrid");
session.getNode("/Cars/Hybrid/Toyota Prius");
session.getNode("/Cars/Hybrid/Toyota Highlander");
session.getNode("/Cars/Hybrid/Nissan Altima");
session.getNode("/Cars/Sports/Aston Martin DB9");
session.getNode("/Cars/Sports/Infiniti G37");
session.getNode("/Cars/Luxury/Cadillac DTS");
session.getNode("/Cars/Luxury/Bentley Continental");
session.getNode("/Cars/Luxury/Lexus IS350");
session.getNode("/Cars/Utility/Land Rover LR2");
session.getNode("/Cars/Utility/Land Rover LR3");
session.getNode("/Cars/Utility/Hummer H3");
session.getNode("/Cars/Utility/Ford F-150");
session.getNode("/Cars/Utility/Toyota Land Cruiser");
for (String path : paths) {
session.getNode(path);
}
} finally {
session.logout();
}
}
private void assertContentNotInWorkspace( JcrRepository newRepository,
String workspaceName,
String... paths ) throws RepositoryException {
JcrSession session = workspaceName != null ? newRepository.login(workspaceName) : newRepository.login();
try {
session.getRootNode();
for (String path : paths) {
try {
session.getNode(path);
fail("Should not have found '" + path + "'");
} catch (PathNotFoundException e) {
// expected
}
}
} finally {
session.logout();
}
}
protected void assertNoProblems( Problems problems ) {
if (problems.hasProblems()) {
System.out.println(problems);
}
assertThat(problems.hasProblems(), is(false));
}
protected void loadContent() throws Exception {
importIntoWorkspace("default", "io/cars-system-view.xml");
importIntoWorkspace("ws2", "io/cars-system-view.xml");
importIntoWorkspace("ws3", "io/cars-system-view.xml");
}
protected void importIntoWorkspace( String workspaceName,
String resourcePath ) throws IOException, RepositoryException {
Session session = null;
try {
session = repository().login(workspaceName);
} catch (NoSuchWorkspaceException e) {
// Create the workspace ...
session().getWorkspace().createWorkspace(workspaceName);
// Create a new session ...
session = repository().login(workspaceName);
}
try {
importContent(session.getRootNode(), resourcePath, ImportUUIDBehavior.IMPORT_UUID_COLLISION_THROW);
} finally {
session.logout();
}
}
protected void populateRepositoryContent( Session session,
String testName ) throws Exception {
int depth = 6;
int breadth = 3;
int properties = 6;
session.getRootNode().addNode(testName, "nt:unstructured");
createSubgraph(session(), testName, depth, breadth, properties, false, new Stopwatch(), print ? System.out : null, null);
}
}
| UTF-8 | Java | 12,128 | java | RepositoryRestoreTest.java | Java | []
| null | []
| /*
* ModeShape (http://www.modeshape.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.modeshape.jcr;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import javax.jcr.ImportUUIDBehavior;
import javax.jcr.NoSuchWorkspaceException;
import javax.jcr.PathNotFoundException;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.query.Query;
import javax.jcr.query.QueryResult;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.modeshape.common.statistic.Stopwatch;
import org.modeshape.common.util.FileUtil;
import org.modeshape.jcr.api.Problems;
/**
* Test performance writing graph subtrees of various sizes with varying number of properties
*/
public class RepositoryRestoreTest extends SingleUseAbstractTest {
private File backupDirectory;
private File backupDirectory2;
@Override
protected RepositoryConfiguration createRepositoryConfiguration( String repositoryName,
Environment environment ) throws Exception {
return RepositoryConfiguration.read("config/backup-repo-config.json").with(environment);
}
@Before
@Override
public void beforeEach() throws Exception {
File backupArea = new File("target/backupArea");
backupDirectory = new File(backupArea, "repoBackups");
backupDirectory2 = new File(backupArea, "repoBackupsAfter");
FileUtil.delete(backupArea);
backupDirectory.mkdirs();
backupDirectory2.mkdirs();
new File(backupArea, "backRepo").mkdirs();
new File(backupArea, "restoreRepo").mkdirs();
super.beforeEach();
}
@Test
@Ignore( "Comment out when generating and writing export files" )
public void testExporting() throws Exception {
print = true;
String path = "/backupAndRestoreTestContent";
populateRepositoryContent(session(), path);
FileOutputStream stream = new FileOutputStream("src/test/resources/io/generated-3-system-view.xml");
session().exportSystemView(path, stream, false, false);
stream.close();
}
@Test
public void shouldBackupRepositoryWithMultipleWorkspaces() throws Exception {
loadContent();
Problems problems = session().getWorkspace().getRepositoryManager().backupRepository(backupDirectory);
assertNoProblems(problems);
// Make some changes that will not be in the backup ...
session().getRootNode().addNode("node-not-in-backup");
session().save();
assertContentInWorkspace(repository(), "default", "/node-not-in-backup");
assertContentInWorkspace(repository(), "ws2");
assertContentInWorkspace(repository(), "ws3");
// Start up a new repository
((LocalEnvironment)environment).setShared(true);
RepositoryConfiguration config = RepositoryConfiguration.read("config/restore-repo-config.json").with(environment);
JcrRepository newRepository = new JcrRepository(config);
try {
newRepository.start();
// And restore it from the contents ...
JcrSession newSession = newRepository.login();
try {
Problems restoreProblems = newSession.getWorkspace().getRepositoryManager().restoreRepository(backupDirectory);
assertNoProblems(restoreProblems);
} finally {
newSession.logout();
}
// Check that the node that was added *after* the backup is not there ...
assertContentNotInWorkspace(newRepository, "default", "/node-not-in-backup");
// Before we assert the content, create a backup of it (for comparison purposes when debugging) ...
newSession = newRepository.login();
try {
Problems backupProblems = newSession.getWorkspace().getRepositoryManager().backupRepository(backupDirectory2);
assertNoProblems(backupProblems);
} finally {
newSession.logout();
}
assertWorkspaces(newRepository, "default", "ws2", "ws3");
assertContentInWorkspace(newRepository, null);
assertContentInWorkspace(newRepository, "ws2");
assertContentInWorkspace(newRepository, "ws3");
queryContentInWorkspace(newRepository, null);
} finally {
newRepository.shutdown().get(10, TimeUnit.SECONDS);
}
}
@Test
public void shouldBackupAndRestoreRepositoryWithMultipleWorkspaces() throws Exception {
// Load the content and verify it's there ...
loadContent();
assertContentInWorkspace(repository(), "default");
assertContentInWorkspace(repository(), "ws2");
assertContentInWorkspace(repository(), "ws3");
// Make the backup, and check that there are no problems ...
Problems problems = session().getWorkspace().getRepositoryManager().backupRepository(backupDirectory);
assertNoProblems(problems);
// Make some changes that will not be in the backup ...
session().getRootNode().addNode("node-not-in-backup");
session().save();
// Check the content again ...
assertContentInWorkspace(repository(), "default", "/node-not-in-backup");
assertContentInWorkspace(repository(), "ws2");
assertContentInWorkspace(repository(), "ws3");
// Restore the content from the backup into our current repository ...
JcrSession newSession = repository().login();
try {
Problems restoreProblems = newSession.getWorkspace().getRepositoryManager().restoreRepository(backupDirectory);
assertNoProblems(restoreProblems);
} finally {
newSession.logout();
}
assertWorkspaces(repository(), "default", "ws2", "ws3");
// Check the content again ...
assertContentInWorkspace(repository(), "default");
assertContentInWorkspace(repository(), "ws2");
assertContentInWorkspace(repository(), "ws3");
assertContentNotInWorkspace(repository(), "default", "/node-not-in-backup");
queryContentInWorkspace(repository(), null);
}
private void assertWorkspaces( JcrRepository newRepository,
String... workspaceNames ) throws RepositoryException {
Set<String> expectedNames = new HashSet<String>();
for (String expectedName : workspaceNames) {
expectedNames.add(expectedName);
}
Set<String> actualNames = new HashSet<String>();
JcrSession session = newRepository.login();
try {
for (String actualName : session.getWorkspace().getAccessibleWorkspaceNames()) {
actualNames.add(actualName);
}
} finally {
session.logout();
}
assertThat(actualNames, is(expectedNames));
}
private void queryContentInWorkspace( JcrRepository newRepository,
String workspaceName ) throws RepositoryException {
JcrSession session = newRepository.login();
try {
String statement = "SELECT [car:model], [car:year], [car:msrp] FROM [car:Car] AS car";
Query query = session.getWorkspace().getQueryManager().createQuery(statement, Query.JCR_SQL2);
QueryResult results = query.execute();
assertThat(results.getRows().getSize(), is(13L));
} finally {
session.logout();
}
}
private void assertContentInWorkspace( JcrRepository newRepository,
String workspaceName,
String... paths ) throws RepositoryException {
JcrSession session = workspaceName != null ? newRepository.login(workspaceName) : newRepository.login();
try {
session.getRootNode();
session.getNode("/Cars");
session.getNode("/Cars/Hybrid");
session.getNode("/Cars/Hybrid/Toyota Prius");
session.getNode("/Cars/Hybrid/Toyota Highlander");
session.getNode("/Cars/Hybrid/Nissan Altima");
session.getNode("/Cars/Sports/Aston Martin DB9");
session.getNode("/Cars/Sports/Infiniti G37");
session.getNode("/Cars/Luxury/Cadillac DTS");
session.getNode("/Cars/Luxury/Bentley Continental");
session.getNode("/Cars/Luxury/Lexus IS350");
session.getNode("/Cars/Utility/Land Rover LR2");
session.getNode("/Cars/Utility/Land Rover LR3");
session.getNode("/Cars/Utility/Hummer H3");
session.getNode("/Cars/Utility/Ford F-150");
session.getNode("/Cars/Utility/Toyota Land Cruiser");
for (String path : paths) {
session.getNode(path);
}
} finally {
session.logout();
}
}
private void assertContentNotInWorkspace( JcrRepository newRepository,
String workspaceName,
String... paths ) throws RepositoryException {
JcrSession session = workspaceName != null ? newRepository.login(workspaceName) : newRepository.login();
try {
session.getRootNode();
for (String path : paths) {
try {
session.getNode(path);
fail("Should not have found '" + path + "'");
} catch (PathNotFoundException e) {
// expected
}
}
} finally {
session.logout();
}
}
protected void assertNoProblems( Problems problems ) {
if (problems.hasProblems()) {
System.out.println(problems);
}
assertThat(problems.hasProblems(), is(false));
}
protected void loadContent() throws Exception {
importIntoWorkspace("default", "io/cars-system-view.xml");
importIntoWorkspace("ws2", "io/cars-system-view.xml");
importIntoWorkspace("ws3", "io/cars-system-view.xml");
}
protected void importIntoWorkspace( String workspaceName,
String resourcePath ) throws IOException, RepositoryException {
Session session = null;
try {
session = repository().login(workspaceName);
} catch (NoSuchWorkspaceException e) {
// Create the workspace ...
session().getWorkspace().createWorkspace(workspaceName);
// Create a new session ...
session = repository().login(workspaceName);
}
try {
importContent(session.getRootNode(), resourcePath, ImportUUIDBehavior.IMPORT_UUID_COLLISION_THROW);
} finally {
session.logout();
}
}
protected void populateRepositoryContent( Session session,
String testName ) throws Exception {
int depth = 6;
int breadth = 3;
int properties = 6;
session.getRootNode().addNode(testName, "nt:unstructured");
createSubgraph(session(), testName, depth, breadth, properties, false, new Stopwatch(), print ? System.out : null, null);
}
}
| 12,128 | 0.627721 | 0.624011 | 295 | 40.111866 | 30.979671 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.735593 | false | false | 13 |
24ce9bc12c281f3d36ae9d37a5ae84873ef7a43e | 18,794,776,954,426 | c52e35057c9f223982c7d2b516ddcee2e3c2368b | /src/org/dzh/bytesutil/converters/Converter.java | 49e2df68ef30b896b4dc4a751584a69cc78bb667 | []
| no_license | zhtmf/bytes-util | https://github.com/zhtmf/bytes-util | 5b788a5903fc38dc069c8f299b23a51fb5c24711 | ae04bcae1f24a16745482a63d1732cc5798275e9 | refs/heads/master | 2018-11-01T00:55:32.652000 | 2018-09-11T11:07:38 | 2018-09-11T11:07:38 | 142,764,894 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.dzh.bytesutil.converters;
import java.io.IOException;
import java.io.OutputStream;
import org.dzh.bytesutil.converters.auxiliary.FieldInfo;
import org.dzh.bytesutil.converters.auxiliary.MarkableInputStream;
public interface Converter<T> {
void serialize(T value, OutputStream dest
, FieldInfo fi, Object self)
throws IOException,UnsupportedOperationException;
T deserialize(MarkableInputStream is, FieldInfo fi, Object self)
throws IOException,UnsupportedOperationException;
}
| UTF-8 | Java | 504 | java | Converter.java | Java | []
| null | []
| package org.dzh.bytesutil.converters;
import java.io.IOException;
import java.io.OutputStream;
import org.dzh.bytesutil.converters.auxiliary.FieldInfo;
import org.dzh.bytesutil.converters.auxiliary.MarkableInputStream;
public interface Converter<T> {
void serialize(T value, OutputStream dest
, FieldInfo fi, Object self)
throws IOException,UnsupportedOperationException;
T deserialize(MarkableInputStream is, FieldInfo fi, Object self)
throws IOException,UnsupportedOperationException;
}
| 504 | 0.821429 | 0.821429 | 15 | 32.599998 | 22.8263 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.666667 | false | false | 13 |
80f7cf04fbfd7adfe7cfc3de3eb1756b115640ee | 30,958,124,276,870 | cfb2c447fb7946b97d6c63a8447baeaf3675e158 | /AttendanceManagement/app/src/main/java/kr/ac/kopo/ctc/A000/ItemForDaily.java | d07e67cc08da242b8f1a1397c68e027f70f304e5 | []
| no_license | JihyeonNam-0327/AndroidOTPApplicationProject | https://github.com/JihyeonNam-0327/AndroidOTPApplicationProject | 87834ae1eda8c7010244700d656808d7fda0d70b | 00c016034dce69147fabfe05c3aaed6780519630 | refs/heads/master | 2021-04-09T11:54:51.720000 | 2018-04-05T04:14:49 | 2018-04-05T04:15:06 | 125,622,148 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package kr.ac.kopo.ctc.A000;
/**
* Created by jihyeon on 2018-03-30.
*/
public class ItemForDaily {
private String time_in; // 이름
private String time_out; // 비밀번호
private String status; //학과
public void setTimeIn(String time_in){ // 종가
this.time_in = time_in;
}
public void setTimeOut(String time_out){ // 전일비
this.time_out = time_out;
}
public void setStatus(String status) { this.status = status; }
public String getTimeIn() {
return time_in;
}
public String getTimeOut() {
return time_out;
}
public String getStatus() { return status; }
}
| UTF-8 | Java | 659 | java | ItemForDaily.java | Java | [
{
"context": "package kr.ac.kopo.ctc.A000;\n\n/**\n * Created by jihyeon on 2018-03-30.\n */\n\npublic class ItemForDaily {\n\n",
"end": 55,
"score": 0.999638020992279,
"start": 48,
"tag": "USERNAME",
"value": "jihyeon"
}
]
| null | []
| package kr.ac.kopo.ctc.A000;
/**
* Created by jihyeon on 2018-03-30.
*/
public class ItemForDaily {
private String time_in; // 이름
private String time_out; // 비밀번호
private String status; //학과
public void setTimeIn(String time_in){ // 종가
this.time_in = time_in;
}
public void setTimeOut(String time_out){ // 전일비
this.time_out = time_out;
}
public void setStatus(String status) { this.status = status; }
public String getTimeIn() {
return time_in;
}
public String getTimeOut() {
return time_out;
}
public String getStatus() { return status; }
}
| 659 | 0.612954 | 0.595577 | 28 | 21.607143 | 18.809837 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.357143 | false | false | 13 |
1082c8f804d388bbef6408a7c894afa8f0cfef65 | 29,695,403,938,841 | 84007d9ef352ed952a7d8f176e8dc143566197e8 | /src/main/java/com/cms/dao/DepartmentDao.java | 2189631aebf2523d63a8fb62d004aec1588172ff | []
| no_license | raviBhai/cms | https://github.com/raviBhai/cms | 0099664b3b30463fe89abc8e6904e4fc478ea5ba | 17c91043847e7c0f05574134de4d2ced96a9be5e | refs/heads/master | 2021-08-22T13:45:51.933000 | 2017-11-30T10:23:43 | 2017-11-30T10:23:43 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cms.dao;
import com.cms.model.Department;
/**
* Created by raviagrawal on 23/03/17.
*/
public interface DepartmentDao {
Department findByName(String name);
}
| UTF-8 | Java | 179 | java | DepartmentDao.java | Java | [
{
"context": "mport com.cms.model.Department;\n\n/**\n * Created by raviagrawal on 23/03/17.\n */\npublic interface DepartmentDao {",
"end": 85,
"score": 0.9985455274581909,
"start": 74,
"tag": "USERNAME",
"value": "raviagrawal"
}
]
| null | []
| package com.cms.dao;
import com.cms.model.Department;
/**
* Created by raviagrawal on 23/03/17.
*/
public interface DepartmentDao {
Department findByName(String name);
}
| 179 | 0.72067 | 0.687151 | 11 | 15.272727 | 16.141932 | 39 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.272727 | false | false | 13 |
b4a9cee440746b32ba0c72d3e1318913d087b9e0 | 12,463,995,138,286 | ee7d27a6d8eaef1b1543d64d1831f2367d74f480 | /src/com/hjellming/derby/Heat.java | 029323af9cb9c71c8c39b0f3324409af0d6a0237 | []
| no_license | hinsoncl/scouts | https://github.com/hinsoncl/scouts | 1087979f0ac96de6a1ce5595911fcc175b38aa08 | 152dfd423d1bffe4295f82372aab7f56c461a8f3 | refs/heads/master | 2016-09-16T04:49:43.435000 | 2013-01-28T14:35:59 | 2013-01-28T14:35:59 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hjellming.derby;
import java.util.*;
import java.io.IOException;
import java.io.Writer;
import java.io.PrintWriter;
import java.io.PrintStream;
/**
* Created by IntelliJ IDEA.
* User: Tom
* Date: Feb 4, 2008
* Time: 1:05:37 AM
* To change this template use File | Settings | File Templates.
*/
public class Heat
{
private int numLanes;
private int heatNumber;
private ArrayList<Racer> racersInLanes = new ArrayList();
private static int nLaneForAssignmentFactor = 0;
private static Heat heatForAssignmentFactor = null;
private static Random random = new Random(System.currentTimeMillis());
public Heat(int numLanes, int heatNumber)
{
this.numLanes = numLanes;
this.heatNumber = heatNumber;
}
public boolean assignLanes(Division division, PrintStream debug) throws IOException
{
if ((division == null) || (division.getNumRacers() == 0))
return false;
if (debug != null)
{
debug.print("Assigning ");
debug.print(numLanes);
debug.print(" lanes for ");
debug.print(division.getName());
debug.print(", heat ");
debug.println(heatNumber);
}
// First need to get a sortable copy of the list of all racers in this division
List<Racer> racers = new ArrayList(division.getRacers());
// For each lane in this heat
for (int i = 1; i <= numLanes; i++)
{
if (debug != null)
{
debug.print("Find a racer for heat ");
debug.print(heatNumber);
debug.print(", lane ");
debug.println(i);
}
// Sort the racers based on their assignment factor
Collections.sort(racers, new RacerAssignmentFactorComparator(this, i));
/*
if (debug != null)
{
debug.println("Racers sorted by assignment factor: ");
for (Racer racer : racers)
racer.getLaneAssignentFactor(this, i, debug);
}
*/
// How many racers have the lowest score?
int nMinAssignmentFactor = racers.get(0).getLaneAssignentFactor(this, i, null);
int numRacersWithMinimum = 0;
for (Racer racer : racers)
{
if (racer.getLaneAssignentFactor(this, i, debug) > nMinAssignmentFactor)
break;
numRacersWithMinimum++;
}
Racer racerAssigned;
if (numRacersWithMinimum == 1)
racerAssigned = racers.get(0);
else
{
// Need to randomly pick one of the racers for this lane.
int nRacerAssignedToLane = random.nextInt(numRacersWithMinimum);
racerAssigned = racers.get(nRacerAssignedToLane);
}
racerAssigned.assignedToHeat(this, i);
racersInLanes.add(racerAssigned);
if (debug != null)
debug.println(racerAssigned.getName() + " was assigned for his heat #" + racerAssigned.getHeats().size());
}
return true;
}
public Racer getRacerInLane(int nLane)
{
if ((nLane < 1) || (nLane > numLanes) || (nLane > racersInLanes.size()))
return null;
return racersInLanes.get(nLane - 1);
}
public int getNumLanes()
{
return numLanes;
}
public void setNumLanes(int numLanes)
{
this.numLanes = numLanes;
}
public int getHeatNumber()
{
return heatNumber;
}
public void setHeatNumber(int heatNumber)
{
this.heatNumber = heatNumber;
}
}
class RacerAssignmentFactorComparator implements Comparator
{
private Heat heat;
private int nLane;
public RacerAssignmentFactorComparator(Heat heat, int nLane)
{
this.heat = heat;
this.nLane = nLane;
}
public int compare(Object o1, Object o2)
{
Racer racer1 = (Racer)o1;
Racer racer2 = (Racer)o2;
try
{
int racer1AssignmentFactor = racer1.getLaneAssignentFactor(heat, nLane, null);
int racer2AssignmentFactor = racer2.getLaneAssignentFactor(heat, nLane, null);
return racer1AssignmentFactor - racer2AssignmentFactor;
}
catch (IOException e)
{
return 0;
}
}
} | UTF-8 | Java | 4,702 | java | Heat.java | Java | [
{
"context": "am;\r\n\r\n/**\r\n * Created by IntelliJ IDEA.\r\n * User: Tom\r\n * Date: Feb 4, 2008\r\n * Time: 1:05:37 AM\r\n * To",
"end": 213,
"score": 0.9977758526802063,
"start": 210,
"tag": "NAME",
"value": "Tom"
}
]
| null | []
| package com.hjellming.derby;
import java.util.*;
import java.io.IOException;
import java.io.Writer;
import java.io.PrintWriter;
import java.io.PrintStream;
/**
* Created by IntelliJ IDEA.
* User: Tom
* Date: Feb 4, 2008
* Time: 1:05:37 AM
* To change this template use File | Settings | File Templates.
*/
public class Heat
{
private int numLanes;
private int heatNumber;
private ArrayList<Racer> racersInLanes = new ArrayList();
private static int nLaneForAssignmentFactor = 0;
private static Heat heatForAssignmentFactor = null;
private static Random random = new Random(System.currentTimeMillis());
public Heat(int numLanes, int heatNumber)
{
this.numLanes = numLanes;
this.heatNumber = heatNumber;
}
public boolean assignLanes(Division division, PrintStream debug) throws IOException
{
if ((division == null) || (division.getNumRacers() == 0))
return false;
if (debug != null)
{
debug.print("Assigning ");
debug.print(numLanes);
debug.print(" lanes for ");
debug.print(division.getName());
debug.print(", heat ");
debug.println(heatNumber);
}
// First need to get a sortable copy of the list of all racers in this division
List<Racer> racers = new ArrayList(division.getRacers());
// For each lane in this heat
for (int i = 1; i <= numLanes; i++)
{
if (debug != null)
{
debug.print("Find a racer for heat ");
debug.print(heatNumber);
debug.print(", lane ");
debug.println(i);
}
// Sort the racers based on their assignment factor
Collections.sort(racers, new RacerAssignmentFactorComparator(this, i));
/*
if (debug != null)
{
debug.println("Racers sorted by assignment factor: ");
for (Racer racer : racers)
racer.getLaneAssignentFactor(this, i, debug);
}
*/
// How many racers have the lowest score?
int nMinAssignmentFactor = racers.get(0).getLaneAssignentFactor(this, i, null);
int numRacersWithMinimum = 0;
for (Racer racer : racers)
{
if (racer.getLaneAssignentFactor(this, i, debug) > nMinAssignmentFactor)
break;
numRacersWithMinimum++;
}
Racer racerAssigned;
if (numRacersWithMinimum == 1)
racerAssigned = racers.get(0);
else
{
// Need to randomly pick one of the racers for this lane.
int nRacerAssignedToLane = random.nextInt(numRacersWithMinimum);
racerAssigned = racers.get(nRacerAssignedToLane);
}
racerAssigned.assignedToHeat(this, i);
racersInLanes.add(racerAssigned);
if (debug != null)
debug.println(racerAssigned.getName() + " was assigned for his heat #" + racerAssigned.getHeats().size());
}
return true;
}
public Racer getRacerInLane(int nLane)
{
if ((nLane < 1) || (nLane > numLanes) || (nLane > racersInLanes.size()))
return null;
return racersInLanes.get(nLane - 1);
}
public int getNumLanes()
{
return numLanes;
}
public void setNumLanes(int numLanes)
{
this.numLanes = numLanes;
}
public int getHeatNumber()
{
return heatNumber;
}
public void setHeatNumber(int heatNumber)
{
this.heatNumber = heatNumber;
}
}
class RacerAssignmentFactorComparator implements Comparator
{
private Heat heat;
private int nLane;
public RacerAssignmentFactorComparator(Heat heat, int nLane)
{
this.heat = heat;
this.nLane = nLane;
}
public int compare(Object o1, Object o2)
{
Racer racer1 = (Racer)o1;
Racer racer2 = (Racer)o2;
try
{
int racer1AssignmentFactor = racer1.getLaneAssignentFactor(heat, nLane, null);
int racer2AssignmentFactor = racer2.getLaneAssignentFactor(heat, nLane, null);
return racer1AssignmentFactor - racer2AssignmentFactor;
}
catch (IOException e)
{
return 0;
}
}
} | 4,702 | 0.544236 | 0.537431 | 164 | 26.682926 | 25.626719 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.530488 | false | false | 13 |
18885aa4bb490ca7ea92290a78125a8e1a4f1984 | 17,179,869,194,990 | 81910b6335a247dee22360d6ca628c4ee631a401 | /app/src/main/java/com/smsapplication/InboxActivity.java | 72afa227b7b87a59e0997696393e10a078e15340 | []
| no_license | ank27/SMSMessanger | https://github.com/ank27/SMSMessanger | eb36884c41f8b744dac9e6c27357054ccd21157e | b461791a3d85914aa9ad696c842697c2268cd495 | refs/heads/master | 2021-01-20T15:39:16.424000 | 2016-07-05T11:37:25 | 2016-07-05T11:37:25 | 62,566,733 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.smsapplication;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.graphics.Bitmap;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveApi;
import com.google.android.gms.drive.MetadataChangeSet;
import com.smsapplication.Adapter.InboxAdapter;
import com.smsapplication.Adapter.SMSSearchAdapter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
public class InboxActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
public String TAG="Inbox";
CoordinatorLayout coordinator_inbox;
DrawerLayout drawer_layout;
Toolbar toolbar_inbox;
public static NavigationView navigationView;
FrameLayout frame_container;
FragmentManager fragmentManager;
FragmentTransaction transaction;
public int open_fragment=0;
String removeFragment = "";
Activity activity;
GoogleApiClient mGoogleApiClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inbox);
// if(savedInstanceState==null) {
// transaction = fragmentManager.beginTransaction();
// }
coordinator_inbox = (CoordinatorLayout) findViewById(R.id.coordinator_inbox);
drawer_layout = (DrawerLayout) findViewById(R.id.drawer_layout);
toolbar_inbox = (Toolbar) findViewById(R.id.toolbar_inbox);
setSupportActionBar(toolbar_inbox);
navigationView = (NavigationView) findViewById(R.id.navigationView);
toolbar_inbox.setNavigationIcon(R.drawable.ic_menu_white_24dp);
toolbar_inbox.setTitle("Inbox");
toolbar_inbox.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
drawer_layout.openDrawer(GravityCompat.START);
}
});
invalidateOptionsMenu();
navigationView.setNavigationItemSelectedListener(this);
activity=this;
frame_container = (FrameLayout) findViewById(R.id.frame_container);
fragmentManager = getSupportFragmentManager();
}
@Override
public void onResume() {
super.onResume();
navigationView.setCheckedItem(R.id.home);
drawer_layout.closeDrawers();
}
@Override
public void onResumeFragments(){
super.onResumeFragments();
set_fragment(0);
invalidateOptionsMenu();
}
@Override
public void onBackPressed(){
View focus = getCurrentFocus();
if (focus != null) {
hiddenKeyboard(focus);
}
if(open_fragment==0){
super.onBackPressed();
InboxActivity.this.finish();
}else {
InboxActivity.this.finish();
}
}
private void hiddenKeyboard(View v) {
InputMethodManager keyboard = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
keyboard.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
private void set_fragment(int open_fragment) {
String tag = "";
Fragment fragment = null;
if (open_fragment==0) {
tag = "Inbox";
if (fragmentManager.findFragmentByTag(tag) == null) {
transaction=fragmentManager.beginTransaction();
fragment = new FragmentInbox();
fragmentManager.popBackStack(removeFragment,FragmentManager.POP_BACK_STACK_INCLUSIVE);
removeFragment=tag;
transaction.addToBackStack(tag);
transaction.replace(R.id.frame_container, fragment, tag).commit();
}
else {
fragmentManager.popBackStack(tag, 0);
}
}
else if (open_fragment==1) {
tag = "About";
if (fragmentManager.findFragmentByTag(tag) == null) {
fragment = new FragmentAbout();
fragmentManager.popBackStack(removeFragment,FragmentManager.POP_BACK_STACK_INCLUSIVE);
transaction=fragmentManager.beginTransaction();
transaction.addToBackStack(tag);
removeFragment=tag;
transaction.replace(R.id.frame_container, fragment, tag).commit();
} else {
fragmentManager.popBackStack(tag, 0);
}
}
}
@Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.home) {
item.setCheckable(true);
drawer_layout.closeDrawers();
open_fragment=0;
set_fragment(0);
}
if (id == R.id.about_us) {
drawer_layout.closeDrawers();
item.setChecked(true);
open_fragment=1;
set_fragment(1);
}
if(id==R.id.backup_to_drive){
Intent backupIntent=new Intent(InboxActivity.this,BackUpActivity.class);
startActivity(backupIntent);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
| UTF-8 | Java | 6,460 | java | InboxActivity.java | Java | []
| null | []
| package com.smsapplication;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.graphics.Bitmap;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveApi;
import com.google.android.gms.drive.MetadataChangeSet;
import com.smsapplication.Adapter.InboxAdapter;
import com.smsapplication.Adapter.SMSSearchAdapter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
public class InboxActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
public String TAG="Inbox";
CoordinatorLayout coordinator_inbox;
DrawerLayout drawer_layout;
Toolbar toolbar_inbox;
public static NavigationView navigationView;
FrameLayout frame_container;
FragmentManager fragmentManager;
FragmentTransaction transaction;
public int open_fragment=0;
String removeFragment = "";
Activity activity;
GoogleApiClient mGoogleApiClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inbox);
// if(savedInstanceState==null) {
// transaction = fragmentManager.beginTransaction();
// }
coordinator_inbox = (CoordinatorLayout) findViewById(R.id.coordinator_inbox);
drawer_layout = (DrawerLayout) findViewById(R.id.drawer_layout);
toolbar_inbox = (Toolbar) findViewById(R.id.toolbar_inbox);
setSupportActionBar(toolbar_inbox);
navigationView = (NavigationView) findViewById(R.id.navigationView);
toolbar_inbox.setNavigationIcon(R.drawable.ic_menu_white_24dp);
toolbar_inbox.setTitle("Inbox");
toolbar_inbox.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
drawer_layout.openDrawer(GravityCompat.START);
}
});
invalidateOptionsMenu();
navigationView.setNavigationItemSelectedListener(this);
activity=this;
frame_container = (FrameLayout) findViewById(R.id.frame_container);
fragmentManager = getSupportFragmentManager();
}
@Override
public void onResume() {
super.onResume();
navigationView.setCheckedItem(R.id.home);
drawer_layout.closeDrawers();
}
@Override
public void onResumeFragments(){
super.onResumeFragments();
set_fragment(0);
invalidateOptionsMenu();
}
@Override
public void onBackPressed(){
View focus = getCurrentFocus();
if (focus != null) {
hiddenKeyboard(focus);
}
if(open_fragment==0){
super.onBackPressed();
InboxActivity.this.finish();
}else {
InboxActivity.this.finish();
}
}
private void hiddenKeyboard(View v) {
InputMethodManager keyboard = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
keyboard.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
private void set_fragment(int open_fragment) {
String tag = "";
Fragment fragment = null;
if (open_fragment==0) {
tag = "Inbox";
if (fragmentManager.findFragmentByTag(tag) == null) {
transaction=fragmentManager.beginTransaction();
fragment = new FragmentInbox();
fragmentManager.popBackStack(removeFragment,FragmentManager.POP_BACK_STACK_INCLUSIVE);
removeFragment=tag;
transaction.addToBackStack(tag);
transaction.replace(R.id.frame_container, fragment, tag).commit();
}
else {
fragmentManager.popBackStack(tag, 0);
}
}
else if (open_fragment==1) {
tag = "About";
if (fragmentManager.findFragmentByTag(tag) == null) {
fragment = new FragmentAbout();
fragmentManager.popBackStack(removeFragment,FragmentManager.POP_BACK_STACK_INCLUSIVE);
transaction=fragmentManager.beginTransaction();
transaction.addToBackStack(tag);
removeFragment=tag;
transaction.replace(R.id.frame_container, fragment, tag).commit();
} else {
fragmentManager.popBackStack(tag, 0);
}
}
}
@Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.home) {
item.setCheckable(true);
drawer_layout.closeDrawers();
open_fragment=0;
set_fragment(0);
}
if (id == R.id.about_us) {
drawer_layout.closeDrawers();
item.setChecked(true);
open_fragment=1;
set_fragment(1);
}
if(id==R.id.backup_to_drive){
Intent backupIntent=new Intent(InboxActivity.this,BackUpActivity.class);
startActivity(backupIntent);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
| 6,460 | 0.675851 | 0.672136 | 174 | 36.120689 | 22.605877 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.718391 | false | false | 13 |
cac71cd49cfd1387becd650246513bb49bd930ee | 32,555,852,145,555 | af79916025156e3d0cf4986b126fbe7f059753e2 | /web/dx/renshi/src/main/java/com/renshi/biz/employee/EmployeeBiz.java | 009444d464df38465cf13c99608ac5a955e41319 | []
| no_license | Letmebeawinner/yywt | https://github.com/Letmebeawinner/yywt | 5380680fadb7fc0d4c86fb92234f7c69cb216010 | 254fa0f54c09300d4bdcdf8617d97d75003536bd | refs/heads/master | 2022-12-26T06:17:11.755000 | 2020-02-14T10:04:29 | 2020-02-14T10:04:29 | 240,468,510 | 0 | 0 | null | false | 2022-12-16T11:36:21 | 2020-02-14T09:08:31 | 2020-02-14T10:12:37 | 2022-12-16T11:36:19 | 84,424 | 0 | 0 | 65 | Roff | false | false | package com.renshi.biz.employee;
import com.a_268.base.core.BaseBiz;
import com.a_268.base.core.Pagination;
import com.a_268.base.util.ObjectUtils;
import com.a_268.base.util.StringUtils;
import com.renshi.biz.common.BaseHessianBiz;
import com.renshi.dao.employee.EmployeeDao;
import com.renshi.entity.employee.Employee;
import com.renshi.entity.employee.QueryEmployee;
import com.renshi.entity.user.SysUser;
import com.renshi.utils.AgeUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
/**
* 员工Biz
*
* @author 268
*/
@Service
public class EmployeeBiz extends BaseBiz<Employee, EmployeeDao> {
@Autowired
private BaseHessianBiz baseHessianBiz;
private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/**
* 条件查询教职工
*
* @param queryEmployee
*/
public List<Employee> getEmployeeList(Employee queryEmployee, Pagination pagination) {
List<Employee> employeeList = new ArrayList<>();
String whereSql = " 1=1";
whereSql += " and status!=2";
if (!StringUtils.isTrimEmpty(queryEmployee.getName())) {
whereSql += " and name like '%" + queryEmployee.getName() + "%'";
}
whereSql +=" order by sort";
employeeList = this.find(pagination, whereSql);
return employeeList;
}
/**
* 条件查询教职工
*
* @param whereSql
*/
public List<Employee> getEmployeeListBySql(String whereSql, Pagination pagination) {
whereSql += " order by sort";
List<Employee> employeeList = this.find(pagination, whereSql);
return employeeList;
}
/**
* id查询教职工
*
* @param id
*/
public Employee findEmployeeById(Long id) {
Employee employee = this.findById(id);
if (ObjectUtils.isNotNull(employee)) {
BeanUtils.copyProperties(employee, employee);
SysUser sysUser = baseHessianBiz.querySysUser(2, id);
if (ObjectUtils.isNotNull(sysUser)) {
// employee.setMobile(sysUser.getMobile());
employee.setSysUserId(sysUser.getId());
}
}
return employee;
}
/**
* 编号查询教职工
*
* @param employeeNo
*/
public Employee findEmployeeByEmployeeNo(String employeeNo) {
String whereSql = " 1=1";
whereSql += " and employeeNo=" + employeeNo;
List<Employee> employeeList = this.find(null, whereSql);
if (ObjectUtils.isNull(employeeList)) {
return null;
}
return employeeList.get(0);
}
/**
* 添加教职工
*
* @param queryEmployee
*/
public String addEmployee(Employee queryEmployee) {
Employee employee = queryEmployee;
employee.setStatus(1);
this.save(employee);
SysUser sysUser = new SysUser();
sysUser.setMobile(queryEmployee.getMobile());
sysUser.setUserName(queryEmployee.getName());//设置用户的用户名
sysUser.setAnotherName(queryEmployee.getName());//设置用户别名
sysUser.setPassword("111111");//默认初始密码
sysUser.setLinkId(employee.getId());
sysUser.setUserType(2);
sysUser.setStatus(0);
String str = baseHessianBiz.addSysUser(sysUser);
if (!StringUtils.isTrimEmpty(str) && !isNumeric(str) && !str.contains("成功")) {
delete(employee);
}
return str;
}
/**
* 判断字符穿是否为数字
*
* @param str
* @return
*/
public static boolean isNumeric(String str) {
if (str == null || str.equals("")) {
return false;
}
for (int i = str.length(); --i >= 0; ) {
if (!Character.isDigit(str.charAt(i))) {
return false;
}
}
return true;
}
/**
* 修改教职工
*
* @param queryEmployee
*/
public String updateEmployee(QueryEmployee queryEmployee) {
SysUser sysUser = baseHessianBiz.querySysUserById(queryEmployee.getSysUserId());
String str = null;
if (ObjectUtils.isNotNull(sysUser)) {
sysUser.setId(queryEmployee.getSysUserId());
sysUser.setUserName(queryEmployee.getName());
sysUser.setAnotherName(queryEmployee.getName());
sysUser.setMobile(queryEmployee.getMobile());
str = baseHessianBiz.updateSysUser(sysUser);
}
if (StringUtils.isTrimEmpty(str)) {
Employee employee = queryEmployee;
update(employee);
}
return str;
}
/**
* 修改教职工类别
*
* @param queryEmployee
*/
public String updateEmployeeType(QueryEmployee queryEmployee) {
SysUser sysUser = baseHessianBiz.querySysUserById(queryEmployee.getSysUserId());
String str = baseHessianBiz.updateSysUser(sysUser);
if (StringUtils.isTrimEmpty(str)) {
Employee employee = queryEmployee;
employee.setType(updateType(employee.getId(),1L,0));
update(employee);
}
return str;
}
/**
* 修改教职工类别
*
* @param queryEmployee
*/
public String updateEmployeeTypeBySource(QueryEmployee queryEmployee) {
SysUser sysUser = baseHessianBiz.querySysUserById(queryEmployee.getSysUserId());
String str = baseHessianBiz.updateSysUser(sysUser);
if (StringUtils.isTrimEmpty(str)) {
Employee employee = queryEmployee;
employee.setType(updateType(employee.getId(),queryEmployee.getType(),0));
employee.setUnitDepartment(queryEmployee.getUnitDepartment());
update(employee);
}
return str;
}
/**
* 计算真正需要修改的type值
* @param employeeId 教职工表id
* @param type 修改修改的type
* @param cancelType 要取消的类型
* @return
*/
public Long updateType(Long employeeId, Long type, int cancelType){
Employee employee=this.findById(employeeId);
if(employee.getType().longValue()==0){ //原来什么都不是 直接操作
return type;
}else { //原来有角色
if(type.longValue()==0){ //取消某角色
if(employee.getType().longValue()!=3){ //原只有一个当前角色
return 0L;
}else { //原来是全角色 去除一个
return cancelType==2?1L:2L;
}
}else { //添加某角色
if(employee.getType().longValue()==type.longValue()){ //原有角色就是当前角色
return type;
}else { //原有不是当前角色 赋予全角色
return 3L;
}
}
}
}
/**
* 删除教职工
*
* @param queryEmployee
*/
public String deleteEmployee(Employee queryEmployee) {
SysUser sysUser = baseHessianBiz.querySysUserById(queryEmployee.getSysUserId());
if (ObjectUtils.isNotNull(sysUser)) {
baseHessianBiz.deleteSysUserById(sysUser.getId());
}
Employee employee = queryEmployee;
employee.setStatus(2);
update(employee);
return "";
}
/**
* 批量倒入教职工
*
* @param myFile
* @param request
* @return
* @throws Exception
*/
public String batchImportEmployee(MultipartFile myFile, HttpServletRequest request) throws Exception {
StringBuffer msg = new StringBuffer();
// datalist拼装List<String[]> datalist,
HSSFWorkbook wookbook = new HSSFWorkbook(myFile.getInputStream());
HSSFSheet sheet = wookbook.getSheetAt(0);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
int rows = sheet.getLastRowNum();// 指的行数,一共有多少行+
List<String> nameList=new ArrayList<>();
for (int i = 1; i < rows + 1; i++) {
// 读取左上端单元格
HSSFRow row = sheet.getRow(i);
// 行不为空
if (row != null) {
String name = getCellValue(row.getCell((short) 0));//姓名
name = name.trim().replaceAll(" ", "");
if(nameList.contains(name)){
msg.append("第" + i + "行" + name + "姓名重复");
break;
}
nameList.add(name);
String employeeTypeStr = getCellValue(row.getCell((short) 1));//教职工类别(都是教职工,属于党校人员) 1教师(暂时不用) 2县级非领导 3校领导 4中层干部 5一般干部 6技术工人
String category = getCellValue(row.getCell((short) 2));//教职工类别
String sex = getCellValue(row.getCell((short) 3));//性别
String birthday = getCellValue(row.getCell((short) 4));//出生年月
String nationality = getCellValue(row.getCell((short) 5));//民族
String nativePlace = getCellValue(row.getCell((short) 6));//籍贯
String birthdayPlace = getCellValue(row.getCell((short) 7));//出生地
String enterPartyTime = getCellValue(row.getCell((short) 8));//入党时间
String workTime = getCellValue(row.getCell((short) 9));//参加工作时间
String identityCard = getCellValue(row.getCell((short) 10));//身份证号码
String profressTelnel = getCellValue(row.getCell((short) 11));//专业技术职务
String speciality = getCellValue(row.getCell((short) 12));//特长
String education = getCellValue(row.getCell((short) 13));//全日制学历学位
String profession = getCellValue(row.getCell((short) 14));//毕业院校
String jobEducation = getCellValue(row.getCell((short) 15));//在职教育学历学位
String jobProfession = getCellValue(row.getCell((short) 16));//在职教育毕业院校及专业
String presentPost = getCellValue(row.getCell((short) 17));//现任职务
String mobile = getCellValue(row.getCell((short) 18));//手机号
String department = getCellValue(row.getCell((short) 19));//部门
String level = getCellValue(row.getCell((short) 20));//级别
String appointTime = getCellValue(row.getCell((short) 21));//任现职务时间
String officeTime = getCellValue(row.getCell((short) 22));//任同职级时间
String description = getCellValue(row.getCell((short) 23));//备注
Long employeeType = 0L;
if (employeeTypeStr.equals("县级非领导")) {
employeeType = 2L;
} else if (employeeTypeStr.equals("校领导")) {
employeeType = 3L;
} else if (employeeTypeStr.equals("中层干部")) {
employeeType = 4L;
} else if (employeeTypeStr.equals("一般干部")) {
employeeType = 5L;
} else if (employeeTypeStr.equals("技术工人")) {
employeeType = 6L;
}
// if (StringUtils.isTrimEmpty(identityCard) || (identityCard.length() != 18 && identityCard.length() != 15)) {
// msg.append("第" + i + "行身份证号填写错误;");
// break;
// }
// List<Employee> list = find(null, " status!=2 and identityCard='" + identityCard + "'");
// if (ObjectUtils.isNotNull(list)) {
// msg.append("第" + i + "行身份证号重复,已跳过;");
// continue;
// }
if (StringUtils.isTrimEmpty(nationality)) {
msg.append("第" + i + "行民族填写错误;");
break;
}
//是否存在当前职工
Employee employee = new Employee();
List<Employee> employeeList = this.getEmployeeListBySql(" status!=2 and source=1 and name='" + name.trim() + "'", null);
if (ObjectUtils.isNotNull(employeeList) && employeeList.size() > 0) {
employee = employeeList.get(0);
}
// if (!StringUtils.isTrimEmpty(category)) {
employee.setCategory(category);
// }
// if (!StringUtils.isTrimEmpty(department)) {
employee.setDepartment(department);
// }
// if (!StringUtils.isTrimEmpty(presentPost)) {
employee.setPresentPost(presentPost);
// }
// if (!StringUtils.isTrimEmpty(level)) {
employee.setLevel(level);
// }
// if (!StringUtils.isTrimEmpty(name)) {
employee.setName(name.trim());
// }
// if (!StringUtils.isTrimEmpty(birthdayPlace)) {
employee.setBirthdayPlace(birthdayPlace);
// }
// if (!StringUtils.isTrimEmpty(profressTelnel)) {
employee.setProfressTelnel(profressTelnel);
// }
// if (!StringUtils.isTrimEmpty(mobile)) {
employee.setMobile(mobile);
// }
// if (!StringUtils.isTrimEmpty(speciality)) {
employee.setSpeciality(speciality);
// }
employee.setIdentityCard(identityCard);
if (!StringUtils.isTrimEmpty(identityCard)) {
int age = AgeUtils.getAgeByIDcard(identityCard);
employee.setAge(Long.valueOf(age));
}
if (sex.equals("男")) {
employee.setSex(0);
} else if (sex.equals("女")) {
employee.setSex(1);
} else {
msg.append("第" + i + "行性别填写错误;");
break;
}
if (nationality.indexOf("族") > -1) {
employee.setNationality(nationality);
} else {
employee.setNationality(nationality + "族");
}
// if (!StringUtils.isTrimEmpty(nativePlace)) {
employee.setNativePlace(nativePlace);
// }
if (StringUtils.isTrimEmpty(birthday)) {
employee.setBirthDay(null);
} else {
employee.setBirthDay(sdf.parse(birthday.trim()));
}
if (StringUtils.isTrimEmpty(enterPartyTime)) {
employee.setEnterPartyTime(null);
} else {
employee.setEnterPartyTime(sdf.parse(enterPartyTime.trim()));
}
if (StringUtils.isTrimEmpty(workTime)) {
employee.setWorkTime(null);
} else {
employee.setWorkTime(sdf.parse(workTime.trim()));
}
// if (!StringUtils.isTrimEmpty(education)) {
employee.setEducation(education);
// }
// if (!StringUtils.isTrimEmpty(profession)) {
employee.setProfession(profession);
// }
// if (!StringUtils.isTrimEmpty(jobEducation)) {
employee.setJobEducation(jobEducation);
// }
// if (!StringUtils.isTrimEmpty(jobProfession)) {
employee.setJobProfession(jobProfession);
// }
// if (!StringUtils.isTrimEmpty(appointTime)) {
employee.setAppointTime(appointTime);
// }
// if (!StringUtils.isTrimEmpty(officeTime)) {
employee.setOfficeTime(officeTime);
// }
// if (!StringUtils.isTrimEmpty(description)) {
employee.setDescription(description);
// }
if (employeeType != 0) {
employee.setEmployeeType(employeeType);
}
employee.setStatus(1);
employee.setSort(i);
if (ObjectUtils.isNotNull(employeeList) && employeeList.size() > 0) {
this.update(employee);
} else {
this.save(employee);
SysUser sysUser = new SysUser();
sysUser.setMobile(employee.getMobile());
sysUser.setUserName(employee.getName());//设置用户的用户名
sysUser.setAnotherName(employee.getName());//设置用户别名
sysUser.setPassword("111111");//默认初始密码
sysUser.setLinkId(employee.getId());
sysUser.setUserType(2);
sysUser.setStatus(0);
String str = baseHessianBiz.addSysUser(sysUser);
System.out.println("批量倒入教职工_EmployeeBiz.batchImportEmployee_###############" + str);
}
}
}
return msg.toString();
}
/**
* 批量倒入教职工同步信息
*
* @param myFile
* @param request
* @return
* @throws Exception
*/
public String batchImportEmployeeSynchronization(MultipartFile myFile, HttpServletRequest request) throws Exception {
StringBuffer msg = new StringBuffer();
// datalist拼装List<String[]> datalist,
HSSFWorkbook wookbook = new HSSFWorkbook(myFile.getInputStream());
HSSFSheet sheet = wookbook.getSheetAt(0);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
int rows = sheet.getLastRowNum();// 指的行数,一共有多少行+
for (int i = 1; i < rows + 1; i++) {
// 读取左上端单元格
HSSFRow row = sheet.getRow(i);
// 行不为空
if (row != null) {
String category = getCellValue(row.getCell((short) 0));//教职工类别
String cangong = getCellValue(row.getCell((short) 1));//参公 没有用
String department = getCellValue(row.getCell((short) 2));//部门
String presentPost = getCellValue(row.getCell((short) 3));//现任职务
String level = getCellValue(row.getCell((short) 4));//级别
String name = getCellValue(row.getCell((short) 5));//姓名
String sex = getCellValue(row.getCell((short) 6));//性别
String nationality = getCellValue(row.getCell((short) 7));//民族
String nativePlace = getCellValue(row.getCell((short) 8));//籍贯
String birthday = getCellValue(row.getCell((short) 9));//出生年月
String enterPartyTime = getCellValue(row.getCell((short) 10));//入党时间
String workTime = getCellValue(row.getCell((short) 11));//参加工作时间
String education = getCellValue(row.getCell((short) 12));//全日制学历学位---education
String profession = getCellValue(row.getCell((short) 13));//毕业院校---profession
String jobEducation = getCellValue(row.getCell((short) 14));//在职教育学历学位---jobEducation
String jobProfession = getCellValue(row.getCell((short) 15));//在职教育毕业院校及专业----jobProfession
String appointTime = getCellValue(row.getCell((short) 16));//任现职务时间
String officeTime = getCellValue(row.getCell((short) 17));//任同职级时间
String description = getCellValue(row.getCell((short) 18));//备注
String age = getCellValue(row.getCell((short) 19));//备注
if (StringUtils.isTrimEmpty(nationality)) {
msg.append("第" + i + "行民族填写错误;");
break;
}
System.out.println("----------------" + name.replace(" ", "").replace(" ", ""));
List<Employee> employeeList = this.find(null, " name='" + name.replace(" ", "").replace(" ", "") + "'");
if (employeeList.size() == 0) {
msg.append("第" + i + "数据不存在;");
break;
}
if (ObjectUtils.isNull(employeeList)) {
System.out.println("********************************************");
}
Employee employee = new Employee();
employee.setId(employeeList.get(0).getId());
employee.setCategory(category);
employee.setDepartment(department);
employee.setPresentPost(presentPost);
employee.setLevel(level);
employee.setName(name.replace(" ", "").replace(" ", "").trim());
// employee.setBirthdayPlace(birthdayPlace);
// employee.setProfressTelnel(profressTelnel);
// employee.setMobile(mobile);
// employee.setSpeciality(speciality);
// employee.setIdentityCard(identityCard);
// int age = AgeUtils.getAgeByIDcard(identityCard);
employee.setAge(Long.valueOf(age));
if (sex.equals("男")) {
employee.setSex(0);
} else if (sex.equals("女")) {
employee.setSex(1);
} else {
msg.append("第" + i + "行性别填写错误;");
break;
}
if (nationality.indexOf("族") > -1) {
employee.setNationality(nationality);
} else {
employee.setNationality(nationality + "族");
}
employee.setNativePlace(nativePlace);
if (StringUtils.isTrimEmpty(birthday)) {
employee.setBirthDay(null);
} else {
employee.setBirthDay(sdf.parse(birthday.trim()));
}
if (StringUtils.isTrimEmpty(enterPartyTime)) {
employee.setEnterPartyTime(null);
} else {
employee.setEnterPartyTime(sdf.parse(enterPartyTime.trim()));
}
if (StringUtils.isTrimEmpty(workTime)) {
employee.setWorkTime(null);
} else {
employee.setWorkTime(sdf.parse(workTime.trim()));
}
employee.setEducation(education);
employee.setProfession(profession);
employee.setJobEducation(jobEducation);
employee.setJobProfession(jobProfession);
employee.setAppointTime(appointTime);
employee.setOfficeTime(officeTime);
employee.setDescription(description);
// employee.setEmployeeType(2L);
// employee.setStatus(1);
System.out.println("-----------------" + employee);
// save(employee);
update(employee);
}
}
return msg.toString();
}
/**
* @param cell
* @return
* @Description 获得Hsscell内容
*/
public String getCellValue(HSSFCell cell) {
String value = "";
if (cell != null) {
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_FORMULA:
break;
case HSSFCell.CELL_TYPE_NUMERIC:
DecimalFormat df = new DecimalFormat("0");
value = df.format(cell.getNumericCellValue());
break;
case HSSFCell.CELL_TYPE_STRING:
value = cell.getStringCellValue().trim();
break;
default:
value = "";
break;
}
}
return value.trim();
}
}
| UTF-8 | Java | 24,815 | java | EmployeeBiz.java | Java | [
{
"context": "mport java.util.List;\n\n/**\n * 员工Biz\n *\n * @author 268\n */\n@Service\npublic class EmployeeBiz extends Bas",
"end": 1042,
"score": 0.9992766380310059,
"start": 1039,
"tag": "USERNAME",
"value": "268"
},
{
"context": ".getName());//设置用户别名\n sysUser.setPassword(\"111111\");//默认初始密码\n sysUser.setLinkId(employee.get",
"end": 3570,
"score": 0.9994069933891296,
"start": 3564,
"tag": "PASSWORD",
"value": "111111"
},
{
"context": "//设置用户别名\n sysUser.setPassword(\"111111\");//默认初始密码\n sysUser.setLinkId(",
"end": 16599,
"score": 0.9993807673454285,
"start": 16593,
"tag": "PASSWORD",
"value": "111111"
}
]
| null | []
| package com.renshi.biz.employee;
import com.a_268.base.core.BaseBiz;
import com.a_268.base.core.Pagination;
import com.a_268.base.util.ObjectUtils;
import com.a_268.base.util.StringUtils;
import com.renshi.biz.common.BaseHessianBiz;
import com.renshi.dao.employee.EmployeeDao;
import com.renshi.entity.employee.Employee;
import com.renshi.entity.employee.QueryEmployee;
import com.renshi.entity.user.SysUser;
import com.renshi.utils.AgeUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
/**
* 员工Biz
*
* @author 268
*/
@Service
public class EmployeeBiz extends BaseBiz<Employee, EmployeeDao> {
@Autowired
private BaseHessianBiz baseHessianBiz;
private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/**
* 条件查询教职工
*
* @param queryEmployee
*/
public List<Employee> getEmployeeList(Employee queryEmployee, Pagination pagination) {
List<Employee> employeeList = new ArrayList<>();
String whereSql = " 1=1";
whereSql += " and status!=2";
if (!StringUtils.isTrimEmpty(queryEmployee.getName())) {
whereSql += " and name like '%" + queryEmployee.getName() + "%'";
}
whereSql +=" order by sort";
employeeList = this.find(pagination, whereSql);
return employeeList;
}
/**
* 条件查询教职工
*
* @param whereSql
*/
public List<Employee> getEmployeeListBySql(String whereSql, Pagination pagination) {
whereSql += " order by sort";
List<Employee> employeeList = this.find(pagination, whereSql);
return employeeList;
}
/**
* id查询教职工
*
* @param id
*/
public Employee findEmployeeById(Long id) {
Employee employee = this.findById(id);
if (ObjectUtils.isNotNull(employee)) {
BeanUtils.copyProperties(employee, employee);
SysUser sysUser = baseHessianBiz.querySysUser(2, id);
if (ObjectUtils.isNotNull(sysUser)) {
// employee.setMobile(sysUser.getMobile());
employee.setSysUserId(sysUser.getId());
}
}
return employee;
}
/**
* 编号查询教职工
*
* @param employeeNo
*/
public Employee findEmployeeByEmployeeNo(String employeeNo) {
String whereSql = " 1=1";
whereSql += " and employeeNo=" + employeeNo;
List<Employee> employeeList = this.find(null, whereSql);
if (ObjectUtils.isNull(employeeList)) {
return null;
}
return employeeList.get(0);
}
/**
* 添加教职工
*
* @param queryEmployee
*/
public String addEmployee(Employee queryEmployee) {
Employee employee = queryEmployee;
employee.setStatus(1);
this.save(employee);
SysUser sysUser = new SysUser();
sysUser.setMobile(queryEmployee.getMobile());
sysUser.setUserName(queryEmployee.getName());//设置用户的用户名
sysUser.setAnotherName(queryEmployee.getName());//设置用户别名
sysUser.setPassword("<PASSWORD>");//默认初始密码
sysUser.setLinkId(employee.getId());
sysUser.setUserType(2);
sysUser.setStatus(0);
String str = baseHessianBiz.addSysUser(sysUser);
if (!StringUtils.isTrimEmpty(str) && !isNumeric(str) && !str.contains("成功")) {
delete(employee);
}
return str;
}
/**
* 判断字符穿是否为数字
*
* @param str
* @return
*/
public static boolean isNumeric(String str) {
if (str == null || str.equals("")) {
return false;
}
for (int i = str.length(); --i >= 0; ) {
if (!Character.isDigit(str.charAt(i))) {
return false;
}
}
return true;
}
/**
* 修改教职工
*
* @param queryEmployee
*/
public String updateEmployee(QueryEmployee queryEmployee) {
SysUser sysUser = baseHessianBiz.querySysUserById(queryEmployee.getSysUserId());
String str = null;
if (ObjectUtils.isNotNull(sysUser)) {
sysUser.setId(queryEmployee.getSysUserId());
sysUser.setUserName(queryEmployee.getName());
sysUser.setAnotherName(queryEmployee.getName());
sysUser.setMobile(queryEmployee.getMobile());
str = baseHessianBiz.updateSysUser(sysUser);
}
if (StringUtils.isTrimEmpty(str)) {
Employee employee = queryEmployee;
update(employee);
}
return str;
}
/**
* 修改教职工类别
*
* @param queryEmployee
*/
public String updateEmployeeType(QueryEmployee queryEmployee) {
SysUser sysUser = baseHessianBiz.querySysUserById(queryEmployee.getSysUserId());
String str = baseHessianBiz.updateSysUser(sysUser);
if (StringUtils.isTrimEmpty(str)) {
Employee employee = queryEmployee;
employee.setType(updateType(employee.getId(),1L,0));
update(employee);
}
return str;
}
/**
* 修改教职工类别
*
* @param queryEmployee
*/
public String updateEmployeeTypeBySource(QueryEmployee queryEmployee) {
SysUser sysUser = baseHessianBiz.querySysUserById(queryEmployee.getSysUserId());
String str = baseHessianBiz.updateSysUser(sysUser);
if (StringUtils.isTrimEmpty(str)) {
Employee employee = queryEmployee;
employee.setType(updateType(employee.getId(),queryEmployee.getType(),0));
employee.setUnitDepartment(queryEmployee.getUnitDepartment());
update(employee);
}
return str;
}
/**
* 计算真正需要修改的type值
* @param employeeId 教职工表id
* @param type 修改修改的type
* @param cancelType 要取消的类型
* @return
*/
public Long updateType(Long employeeId, Long type, int cancelType){
Employee employee=this.findById(employeeId);
if(employee.getType().longValue()==0){ //原来什么都不是 直接操作
return type;
}else { //原来有角色
if(type.longValue()==0){ //取消某角色
if(employee.getType().longValue()!=3){ //原只有一个当前角色
return 0L;
}else { //原来是全角色 去除一个
return cancelType==2?1L:2L;
}
}else { //添加某角色
if(employee.getType().longValue()==type.longValue()){ //原有角色就是当前角色
return type;
}else { //原有不是当前角色 赋予全角色
return 3L;
}
}
}
}
/**
* 删除教职工
*
* @param queryEmployee
*/
public String deleteEmployee(Employee queryEmployee) {
SysUser sysUser = baseHessianBiz.querySysUserById(queryEmployee.getSysUserId());
if (ObjectUtils.isNotNull(sysUser)) {
baseHessianBiz.deleteSysUserById(sysUser.getId());
}
Employee employee = queryEmployee;
employee.setStatus(2);
update(employee);
return "";
}
/**
* 批量倒入教职工
*
* @param myFile
* @param request
* @return
* @throws Exception
*/
public String batchImportEmployee(MultipartFile myFile, HttpServletRequest request) throws Exception {
StringBuffer msg = new StringBuffer();
// datalist拼装List<String[]> datalist,
HSSFWorkbook wookbook = new HSSFWorkbook(myFile.getInputStream());
HSSFSheet sheet = wookbook.getSheetAt(0);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
int rows = sheet.getLastRowNum();// 指的行数,一共有多少行+
List<String> nameList=new ArrayList<>();
for (int i = 1; i < rows + 1; i++) {
// 读取左上端单元格
HSSFRow row = sheet.getRow(i);
// 行不为空
if (row != null) {
String name = getCellValue(row.getCell((short) 0));//姓名
name = name.trim().replaceAll(" ", "");
if(nameList.contains(name)){
msg.append("第" + i + "行" + name + "姓名重复");
break;
}
nameList.add(name);
String employeeTypeStr = getCellValue(row.getCell((short) 1));//教职工类别(都是教职工,属于党校人员) 1教师(暂时不用) 2县级非领导 3校领导 4中层干部 5一般干部 6技术工人
String category = getCellValue(row.getCell((short) 2));//教职工类别
String sex = getCellValue(row.getCell((short) 3));//性别
String birthday = getCellValue(row.getCell((short) 4));//出生年月
String nationality = getCellValue(row.getCell((short) 5));//民族
String nativePlace = getCellValue(row.getCell((short) 6));//籍贯
String birthdayPlace = getCellValue(row.getCell((short) 7));//出生地
String enterPartyTime = getCellValue(row.getCell((short) 8));//入党时间
String workTime = getCellValue(row.getCell((short) 9));//参加工作时间
String identityCard = getCellValue(row.getCell((short) 10));//身份证号码
String profressTelnel = getCellValue(row.getCell((short) 11));//专业技术职务
String speciality = getCellValue(row.getCell((short) 12));//特长
String education = getCellValue(row.getCell((short) 13));//全日制学历学位
String profession = getCellValue(row.getCell((short) 14));//毕业院校
String jobEducation = getCellValue(row.getCell((short) 15));//在职教育学历学位
String jobProfession = getCellValue(row.getCell((short) 16));//在职教育毕业院校及专业
String presentPost = getCellValue(row.getCell((short) 17));//现任职务
String mobile = getCellValue(row.getCell((short) 18));//手机号
String department = getCellValue(row.getCell((short) 19));//部门
String level = getCellValue(row.getCell((short) 20));//级别
String appointTime = getCellValue(row.getCell((short) 21));//任现职务时间
String officeTime = getCellValue(row.getCell((short) 22));//任同职级时间
String description = getCellValue(row.getCell((short) 23));//备注
Long employeeType = 0L;
if (employeeTypeStr.equals("县级非领导")) {
employeeType = 2L;
} else if (employeeTypeStr.equals("校领导")) {
employeeType = 3L;
} else if (employeeTypeStr.equals("中层干部")) {
employeeType = 4L;
} else if (employeeTypeStr.equals("一般干部")) {
employeeType = 5L;
} else if (employeeTypeStr.equals("技术工人")) {
employeeType = 6L;
}
// if (StringUtils.isTrimEmpty(identityCard) || (identityCard.length() != 18 && identityCard.length() != 15)) {
// msg.append("第" + i + "行身份证号填写错误;");
// break;
// }
// List<Employee> list = find(null, " status!=2 and identityCard='" + identityCard + "'");
// if (ObjectUtils.isNotNull(list)) {
// msg.append("第" + i + "行身份证号重复,已跳过;");
// continue;
// }
if (StringUtils.isTrimEmpty(nationality)) {
msg.append("第" + i + "行民族填写错误;");
break;
}
//是否存在当前职工
Employee employee = new Employee();
List<Employee> employeeList = this.getEmployeeListBySql(" status!=2 and source=1 and name='" + name.trim() + "'", null);
if (ObjectUtils.isNotNull(employeeList) && employeeList.size() > 0) {
employee = employeeList.get(0);
}
// if (!StringUtils.isTrimEmpty(category)) {
employee.setCategory(category);
// }
// if (!StringUtils.isTrimEmpty(department)) {
employee.setDepartment(department);
// }
// if (!StringUtils.isTrimEmpty(presentPost)) {
employee.setPresentPost(presentPost);
// }
// if (!StringUtils.isTrimEmpty(level)) {
employee.setLevel(level);
// }
// if (!StringUtils.isTrimEmpty(name)) {
employee.setName(name.trim());
// }
// if (!StringUtils.isTrimEmpty(birthdayPlace)) {
employee.setBirthdayPlace(birthdayPlace);
// }
// if (!StringUtils.isTrimEmpty(profressTelnel)) {
employee.setProfressTelnel(profressTelnel);
// }
// if (!StringUtils.isTrimEmpty(mobile)) {
employee.setMobile(mobile);
// }
// if (!StringUtils.isTrimEmpty(speciality)) {
employee.setSpeciality(speciality);
// }
employee.setIdentityCard(identityCard);
if (!StringUtils.isTrimEmpty(identityCard)) {
int age = AgeUtils.getAgeByIDcard(identityCard);
employee.setAge(Long.valueOf(age));
}
if (sex.equals("男")) {
employee.setSex(0);
} else if (sex.equals("女")) {
employee.setSex(1);
} else {
msg.append("第" + i + "行性别填写错误;");
break;
}
if (nationality.indexOf("族") > -1) {
employee.setNationality(nationality);
} else {
employee.setNationality(nationality + "族");
}
// if (!StringUtils.isTrimEmpty(nativePlace)) {
employee.setNativePlace(nativePlace);
// }
if (StringUtils.isTrimEmpty(birthday)) {
employee.setBirthDay(null);
} else {
employee.setBirthDay(sdf.parse(birthday.trim()));
}
if (StringUtils.isTrimEmpty(enterPartyTime)) {
employee.setEnterPartyTime(null);
} else {
employee.setEnterPartyTime(sdf.parse(enterPartyTime.trim()));
}
if (StringUtils.isTrimEmpty(workTime)) {
employee.setWorkTime(null);
} else {
employee.setWorkTime(sdf.parse(workTime.trim()));
}
// if (!StringUtils.isTrimEmpty(education)) {
employee.setEducation(education);
// }
// if (!StringUtils.isTrimEmpty(profession)) {
employee.setProfession(profession);
// }
// if (!StringUtils.isTrimEmpty(jobEducation)) {
employee.setJobEducation(jobEducation);
// }
// if (!StringUtils.isTrimEmpty(jobProfession)) {
employee.setJobProfession(jobProfession);
// }
// if (!StringUtils.isTrimEmpty(appointTime)) {
employee.setAppointTime(appointTime);
// }
// if (!StringUtils.isTrimEmpty(officeTime)) {
employee.setOfficeTime(officeTime);
// }
// if (!StringUtils.isTrimEmpty(description)) {
employee.setDescription(description);
// }
if (employeeType != 0) {
employee.setEmployeeType(employeeType);
}
employee.setStatus(1);
employee.setSort(i);
if (ObjectUtils.isNotNull(employeeList) && employeeList.size() > 0) {
this.update(employee);
} else {
this.save(employee);
SysUser sysUser = new SysUser();
sysUser.setMobile(employee.getMobile());
sysUser.setUserName(employee.getName());//设置用户的用户名
sysUser.setAnotherName(employee.getName());//设置用户别名
sysUser.setPassword("<PASSWORD>");//默认初始密码
sysUser.setLinkId(employee.getId());
sysUser.setUserType(2);
sysUser.setStatus(0);
String str = baseHessianBiz.addSysUser(sysUser);
System.out.println("批量倒入教职工_EmployeeBiz.batchImportEmployee_###############" + str);
}
}
}
return msg.toString();
}
/**
* 批量倒入教职工同步信息
*
* @param myFile
* @param request
* @return
* @throws Exception
*/
public String batchImportEmployeeSynchronization(MultipartFile myFile, HttpServletRequest request) throws Exception {
StringBuffer msg = new StringBuffer();
// datalist拼装List<String[]> datalist,
HSSFWorkbook wookbook = new HSSFWorkbook(myFile.getInputStream());
HSSFSheet sheet = wookbook.getSheetAt(0);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
int rows = sheet.getLastRowNum();// 指的行数,一共有多少行+
for (int i = 1; i < rows + 1; i++) {
// 读取左上端单元格
HSSFRow row = sheet.getRow(i);
// 行不为空
if (row != null) {
String category = getCellValue(row.getCell((short) 0));//教职工类别
String cangong = getCellValue(row.getCell((short) 1));//参公 没有用
String department = getCellValue(row.getCell((short) 2));//部门
String presentPost = getCellValue(row.getCell((short) 3));//现任职务
String level = getCellValue(row.getCell((short) 4));//级别
String name = getCellValue(row.getCell((short) 5));//姓名
String sex = getCellValue(row.getCell((short) 6));//性别
String nationality = getCellValue(row.getCell((short) 7));//民族
String nativePlace = getCellValue(row.getCell((short) 8));//籍贯
String birthday = getCellValue(row.getCell((short) 9));//出生年月
String enterPartyTime = getCellValue(row.getCell((short) 10));//入党时间
String workTime = getCellValue(row.getCell((short) 11));//参加工作时间
String education = getCellValue(row.getCell((short) 12));//全日制学历学位---education
String profession = getCellValue(row.getCell((short) 13));//毕业院校---profession
String jobEducation = getCellValue(row.getCell((short) 14));//在职教育学历学位---jobEducation
String jobProfession = getCellValue(row.getCell((short) 15));//在职教育毕业院校及专业----jobProfession
String appointTime = getCellValue(row.getCell((short) 16));//任现职务时间
String officeTime = getCellValue(row.getCell((short) 17));//任同职级时间
String description = getCellValue(row.getCell((short) 18));//备注
String age = getCellValue(row.getCell((short) 19));//备注
if (StringUtils.isTrimEmpty(nationality)) {
msg.append("第" + i + "行民族填写错误;");
break;
}
System.out.println("----------------" + name.replace(" ", "").replace(" ", ""));
List<Employee> employeeList = this.find(null, " name='" + name.replace(" ", "").replace(" ", "") + "'");
if (employeeList.size() == 0) {
msg.append("第" + i + "数据不存在;");
break;
}
if (ObjectUtils.isNull(employeeList)) {
System.out.println("********************************************");
}
Employee employee = new Employee();
employee.setId(employeeList.get(0).getId());
employee.setCategory(category);
employee.setDepartment(department);
employee.setPresentPost(presentPost);
employee.setLevel(level);
employee.setName(name.replace(" ", "").replace(" ", "").trim());
// employee.setBirthdayPlace(birthdayPlace);
// employee.setProfressTelnel(profressTelnel);
// employee.setMobile(mobile);
// employee.setSpeciality(speciality);
// employee.setIdentityCard(identityCard);
// int age = AgeUtils.getAgeByIDcard(identityCard);
employee.setAge(Long.valueOf(age));
if (sex.equals("男")) {
employee.setSex(0);
} else if (sex.equals("女")) {
employee.setSex(1);
} else {
msg.append("第" + i + "行性别填写错误;");
break;
}
if (nationality.indexOf("族") > -1) {
employee.setNationality(nationality);
} else {
employee.setNationality(nationality + "族");
}
employee.setNativePlace(nativePlace);
if (StringUtils.isTrimEmpty(birthday)) {
employee.setBirthDay(null);
} else {
employee.setBirthDay(sdf.parse(birthday.trim()));
}
if (StringUtils.isTrimEmpty(enterPartyTime)) {
employee.setEnterPartyTime(null);
} else {
employee.setEnterPartyTime(sdf.parse(enterPartyTime.trim()));
}
if (StringUtils.isTrimEmpty(workTime)) {
employee.setWorkTime(null);
} else {
employee.setWorkTime(sdf.parse(workTime.trim()));
}
employee.setEducation(education);
employee.setProfession(profession);
employee.setJobEducation(jobEducation);
employee.setJobProfession(jobProfession);
employee.setAppointTime(appointTime);
employee.setOfficeTime(officeTime);
employee.setDescription(description);
// employee.setEmployeeType(2L);
// employee.setStatus(1);
System.out.println("-----------------" + employee);
// save(employee);
update(employee);
}
}
return msg.toString();
}
/**
* @param cell
* @return
* @Description 获得Hsscell内容
*/
public String getCellValue(HSSFCell cell) {
String value = "";
if (cell != null) {
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_FORMULA:
break;
case HSSFCell.CELL_TYPE_NUMERIC:
DecimalFormat df = new DecimalFormat("0");
value = df.format(cell.getNumericCellValue());
break;
case HSSFCell.CELL_TYPE_STRING:
value = cell.getStringCellValue().trim();
break;
default:
value = "";
break;
}
}
return value.trim();
}
}
| 24,823 | 0.535676 | 0.528851 | 584 | 39.388699 | 26.677961 | 139 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.558219 | false | false | 13 |
80253fc9550d48cdd2fca144a1fe5d6c50ffda59 | 9,620,726,756,522 | 4d25f75ba6f30a0a612362d3b732994c31ab6af9 | /src/main/java/com/voting/sessions/service/AssociatedVoteService.java | 160dc0459e08ee3b7f8b2398f2d2cd44e3cfe50c | []
| no_license | Locomontero/STF_backend | https://github.com/Locomontero/STF_backend | 37472b048fa01c00ec6ede252d4b8cd2150d3be1 | c40fded7ae44190878da6543904107fee8cd5502 | refs/heads/master | 2022-12-27T05:58:25.926000 | 2020-10-14T19:10:34 | 2020-10-14T19:10:34 | 304,110,675 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.voting.sessions.service;
import com.voting.sessions.dto.AssociatedVoteResultDto;
import com.voting.sessions.entity.AssociatedVote;
public interface AssociatedVoteService {
AssociatedVote vote (AssociatedVote associatedVote, Long agendaId);
AssociatedVoteResultDto getVoteResult(Long agendaId);
}
| UTF-8 | Java | 317 | java | AssociatedVoteService.java | Java | []
| null | []
| package com.voting.sessions.service;
import com.voting.sessions.dto.AssociatedVoteResultDto;
import com.voting.sessions.entity.AssociatedVote;
public interface AssociatedVoteService {
AssociatedVote vote (AssociatedVote associatedVote, Long agendaId);
AssociatedVoteResultDto getVoteResult(Long agendaId);
}
| 317 | 0.835962 | 0.835962 | 12 | 25.416666 | 26.001469 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.833333 | false | false | 13 |
897833ef9c99ac18c327b31b17b5b121a4e5d101 | 26,225,070,318,752 | c277740d076e608a03ff5717419f1c448af12493 | /src/it/hellokitty/gt/bulletin/repository/AttachmentHistoryRepository.java | 82e8f4d1ba113ffdc9190c742d0f08f6491d11f2 | []
| no_license | HelloKittyJavaTeam/bulletin | https://github.com/HelloKittyJavaTeam/bulletin | 85ef92b898b1c12837ff1022905ca2aa5f83f62e | 42b88dd9031b2aafdd94720141a6456db037008e | refs/heads/master | 2021-01-23T13:29:10.250000 | 2015-07-21T07:39:05 | 2015-07-21T07:39:05 | 38,881,286 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package it.hellokitty.gt.bulletin.repository;
import it.ferrari.gt.repository.Repository;
import it.hellokitty.gt.bulletin.entity.AttachmentHistory;
public interface AttachmentHistoryRepository extends Repository<AttachmentHistory>{}
| UTF-8 | Java | 242 | java | AttachmentHistoryRepository.java | Java | []
| null | []
| package it.hellokitty.gt.bulletin.repository;
import it.ferrari.gt.repository.Repository;
import it.hellokitty.gt.bulletin.entity.AttachmentHistory;
public interface AttachmentHistoryRepository extends Repository<AttachmentHistory>{}
| 242 | 0.838843 | 0.838843 | 6 | 38.333332 | 30.21405 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 13 |
eb0e9996229134560a7a83e199f97e5a5dc1570a | 22,024,592,303,367 | 30955a0d9a80679394d299956d9fa5307547bf12 | /QRCreator/src/main/java/to/kit/barcode/QRCreator.java | cf6f5a3b88ae553235ea46bb50787039918d6eeb | []
| no_license | Buchikichi/QRCreator | https://github.com/Buchikichi/QRCreator | 760e065afd9a12913a74661fc39e290ca21f3973 | 90478cbe10b7ef8cd50bdaafa85e8a309484ba36 | refs/heads/master | 2021-01-21T12:40:12.821000 | 2016-04-14T04:20:04 | 2016-04-14T04:20:04 | 24,749,622 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package to.kit.barcode;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.swing.JOptionPane;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
/**
* QRCreator
* @author H.Sasai
*/
public class QRCreator {
public void create(String contents) throws IOException, WriterException {
int width = 320;
int height = 320;
BarcodeFormat format = BarcodeFormat.QR_CODE;
Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
QRCodeWriter writer = new QRCodeWriter();
String filename = contents.replaceAll("[/]", "_");
hints.put(EncodeHintType.CHARACTER_SET, "Shift_JIS");
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
BitMatrix bitMatrix = writer.encode(contents, format, width, height, hints);
BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix);
ImageIO.write(image, "png", new File(filename + ".png"));
}
public String inputContent() {
return JOptionPane.showInputDialog("入力してください", "にほんご");
}
public static void main(String[] args) throws Exception {
QRCreator app = new QRCreator();
String contents;
if (0 < args.length) {
contents = args[0];
} else {
contents = app.inputContent();
}
if (contents == null || contents.trim().isEmpty()) {
return;
}
app.create(contents);
}
}
| UTF-8 | Java | 1,720 | java | QRCreator.java | Java | [
{
"context": "ErrorCorrectionLevel;\n\n/**\n * QRCreator\n * @author H.Sasai\n */\npublic class QRCreator {\n\tpublic void create(",
"end": 584,
"score": 0.9998706579208374,
"start": 577,
"tag": "NAME",
"value": "H.Sasai"
}
]
| null | []
| package to.kit.barcode;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.swing.JOptionPane;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
/**
* QRCreator
* @author H.Sasai
*/
public class QRCreator {
public void create(String contents) throws IOException, WriterException {
int width = 320;
int height = 320;
BarcodeFormat format = BarcodeFormat.QR_CODE;
Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
QRCodeWriter writer = new QRCodeWriter();
String filename = contents.replaceAll("[/]", "_");
hints.put(EncodeHintType.CHARACTER_SET, "Shift_JIS");
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
BitMatrix bitMatrix = writer.encode(contents, format, width, height, hints);
BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix);
ImageIO.write(image, "png", new File(filename + ".png"));
}
public String inputContent() {
return JOptionPane.showInputDialog("入力してください", "にほんご");
}
public static void main(String[] args) throws Exception {
QRCreator app = new QRCreator();
String contents;
if (0 < args.length) {
contents = args[0];
} else {
contents = app.inputContent();
}
if (contents == null || contents.trim().isEmpty()) {
return;
}
app.create(contents);
}
}
| 1,720 | 0.744104 | 0.738797 | 58 | 28.241379 | 23.309248 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.775862 | false | false | 13 |
f09cf42a87eb94a46b039ae079504495f3f522e7 | 23,725,399,350,562 | c7d345b80c927feafe4d5978eb998a2c29e5410a | /ms_hackathon/app/src/main/java/com/andevcon/hackathon/msft/fragments/PagesListFragment.java | 18617ffdcb0a945f9eba1d98ec386db3255a3e1c | [
"Apache-2.0"
]
| permissive | sundarsiva/andevcon | https://github.com/sundarsiva/andevcon | f27884386cea26d82e0b9f2666318e474f8b33e7 | 7d10adf4067204b833197bdad9b3e71d2b098550 | refs/heads/master | 2021-01-10T03:05:57.875000 | 2015-12-03T06:18:45 | 2015-12-03T06:18:45 | 47,221,016 | 0 | 2 | null | false | 2015-12-02T00:13:06 | 2015-12-01T22:18:48 | 2015-12-01T22:22:23 | 2015-12-02T00:13:06 | 1,342 | 0 | 1 | 0 | Java | null | null | package com.andevcon.hackathon.msft.fragments;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupMenu;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.andevcon.hackathon.msft.R;
import com.andevcon.hackathon.msft.activities.DetailActivity;
import com.andevcon.hackathon.msft.adapters.PagesRecylerViewAdapter;
import com.andevcon.hackathon.msft.api.ApiClient;
import com.andevcon.hackathon.msft.helpers.Constants;
import com.microsoft.onenotevos.Envelope;
import com.microsoft.onenotevos.Page;
import java.util.Arrays;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
public class PagesListFragment extends Fragment {
@Bind(R.id.rvPagesList)
RecyclerView rvPagesList;
@Bind(R.id.pbPagesList)
ProgressBar pbPagesList;
@Bind(R.id.srlPagesList)
SwipeRefreshLayout srlPagesList;
private String mSectionId;
private static final String TAG = PagesListFragment.class.getSimpleName();
public static PagesListFragment newInstance(String secionId) {
PagesListFragment fragment = new PagesListFragment();
Bundle args = new Bundle();
args.putString(Constants.KEY_SECTION_ID, secionId);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mSectionId = getArguments().getString(Constants.KEY_SECTION_ID, "");
Log.d(TAG, "onCreate() called with: " + "mSectionId = [" + mSectionId + "]");
}
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup view = (ViewGroup) inflater.inflate(R.layout.fragment_travelog_pages_list, null);
ButterKnife.bind(this, view);
initUI();
fetchPages();
return view;
}
private void initUI() {
srlPagesList.setColorSchemeResources(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
srlPagesList.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
fetchPages();
}
});
}
private void fetchPages() {
togglePbVisibility(true);
ApiClient.apiService.getPagesFromSections(mSectionId, new Callback<Envelope<Page>>() {
@Override
public void success(Envelope<Page> pageEnvelope, Response response) {
togglePbVisibility(false);
srlPagesList.setRefreshing(false);
if (pageEnvelope != null) {
List<Page> pagesList = Arrays.asList(pageEnvelope.value);
if (pagesList != null && pagesList.size() > 0) {
setupRecyclerView(pagesList);
}
}
}
@Override
public void failure(RetrofitError error) {
togglePbVisibility(false);
srlPagesList.setRefreshing(false);
Log.e(TAG, "Failed to fetchPages - " + Log.getStackTraceString(error));
}
});
}
private void togglePbVisibility(boolean show) {
pbPagesList.setVisibility(show ? View.VISIBLE : View.GONE);
rvPagesList.setVisibility(!show ? View.VISIBLE : View.GONE);
}
private void setupRecyclerView(List<Page> pagesList) {
if (rvPagesList != null) {
rvPagesList.setLayoutManager(new LinearLayoutManager(rvPagesList.getContext()));
rvPagesList.setAdapter(new PagesRecylerViewAdapter(getActivity(), pagesList, new PagesRecylerViewAdapter.ClickListener() {
@Override
public void onClickListener(Page page, int position) {
launchDetailActivity(page);
}
@Override
public void onLongClickListener(Page page, int position, View view) {
showPopUpMenu(page, view);
}
}));
}
}
private void showPopUpMenu(final Page page, final View viewLocal) {
PopupMenu popupMenu = new PopupMenu(getActivity(), viewLocal);
popupMenu.getMenuInflater().inflate(R.menu.page_menu, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(final MenuItem menuItem) {
if (menuItem.getItemId() == R.id.item_share) {
launchShareIntent(page);
} else if (menuItem.getItemId() == R.id.item_delete) {
ApiClient.apiService.deletePage(page.id, new Callback<Response>() {
@Override
public void success(Response response, Response response2) {
Toast.makeText(getActivity(), page.title + " is deleted", Toast.LENGTH_SHORT).show();
fetchPages();
}
@Override
public void failure(RetrofitError error) {
Toast.makeText(getActivity(), page.title + " is not deleted", Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(getActivity(), "Link is copied to clipboard - \n\n" + page.contentUrl, Toast.LENGTH_SHORT).show();
}
return true;
}
});
popupMenu.show();
}
private void launchShareIntent(Page page) {
try {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, page.title);
i.putExtra(Intent.EXTRA_TEXT, page.contentUrl);
startActivity(Intent.createChooser(i, "Share with...."));
} catch(Exception e) {
Log.e(TAG, "exception while sharing - " + e.getLocalizedMessage());
}
}
private void launchDetailActivity(Page page) {
Intent intent = new Intent(getActivity(), DetailActivity.class);
intent.putExtra(DetailActivity.EXTRA_PAGE_ID, page.id);
intent.putExtra(DetailActivity.EXTRA_PAGE_NAME, page.title);
startActivity(intent);
}
}
| UTF-8 | Java | 7,046 | java | PagesListFragment.java | Java | []
| null | []
| package com.andevcon.hackathon.msft.fragments;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupMenu;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.andevcon.hackathon.msft.R;
import com.andevcon.hackathon.msft.activities.DetailActivity;
import com.andevcon.hackathon.msft.adapters.PagesRecylerViewAdapter;
import com.andevcon.hackathon.msft.api.ApiClient;
import com.andevcon.hackathon.msft.helpers.Constants;
import com.microsoft.onenotevos.Envelope;
import com.microsoft.onenotevos.Page;
import java.util.Arrays;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
public class PagesListFragment extends Fragment {
@Bind(R.id.rvPagesList)
RecyclerView rvPagesList;
@Bind(R.id.pbPagesList)
ProgressBar pbPagesList;
@Bind(R.id.srlPagesList)
SwipeRefreshLayout srlPagesList;
private String mSectionId;
private static final String TAG = PagesListFragment.class.getSimpleName();
public static PagesListFragment newInstance(String secionId) {
PagesListFragment fragment = new PagesListFragment();
Bundle args = new Bundle();
args.putString(Constants.KEY_SECTION_ID, secionId);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mSectionId = getArguments().getString(Constants.KEY_SECTION_ID, "");
Log.d(TAG, "onCreate() called with: " + "mSectionId = [" + mSectionId + "]");
}
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup view = (ViewGroup) inflater.inflate(R.layout.fragment_travelog_pages_list, null);
ButterKnife.bind(this, view);
initUI();
fetchPages();
return view;
}
private void initUI() {
srlPagesList.setColorSchemeResources(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
srlPagesList.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
fetchPages();
}
});
}
private void fetchPages() {
togglePbVisibility(true);
ApiClient.apiService.getPagesFromSections(mSectionId, new Callback<Envelope<Page>>() {
@Override
public void success(Envelope<Page> pageEnvelope, Response response) {
togglePbVisibility(false);
srlPagesList.setRefreshing(false);
if (pageEnvelope != null) {
List<Page> pagesList = Arrays.asList(pageEnvelope.value);
if (pagesList != null && pagesList.size() > 0) {
setupRecyclerView(pagesList);
}
}
}
@Override
public void failure(RetrofitError error) {
togglePbVisibility(false);
srlPagesList.setRefreshing(false);
Log.e(TAG, "Failed to fetchPages - " + Log.getStackTraceString(error));
}
});
}
private void togglePbVisibility(boolean show) {
pbPagesList.setVisibility(show ? View.VISIBLE : View.GONE);
rvPagesList.setVisibility(!show ? View.VISIBLE : View.GONE);
}
private void setupRecyclerView(List<Page> pagesList) {
if (rvPagesList != null) {
rvPagesList.setLayoutManager(new LinearLayoutManager(rvPagesList.getContext()));
rvPagesList.setAdapter(new PagesRecylerViewAdapter(getActivity(), pagesList, new PagesRecylerViewAdapter.ClickListener() {
@Override
public void onClickListener(Page page, int position) {
launchDetailActivity(page);
}
@Override
public void onLongClickListener(Page page, int position, View view) {
showPopUpMenu(page, view);
}
}));
}
}
private void showPopUpMenu(final Page page, final View viewLocal) {
PopupMenu popupMenu = new PopupMenu(getActivity(), viewLocal);
popupMenu.getMenuInflater().inflate(R.menu.page_menu, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(final MenuItem menuItem) {
if (menuItem.getItemId() == R.id.item_share) {
launchShareIntent(page);
} else if (menuItem.getItemId() == R.id.item_delete) {
ApiClient.apiService.deletePage(page.id, new Callback<Response>() {
@Override
public void success(Response response, Response response2) {
Toast.makeText(getActivity(), page.title + " is deleted", Toast.LENGTH_SHORT).show();
fetchPages();
}
@Override
public void failure(RetrofitError error) {
Toast.makeText(getActivity(), page.title + " is not deleted", Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(getActivity(), "Link is copied to clipboard - \n\n" + page.contentUrl, Toast.LENGTH_SHORT).show();
}
return true;
}
});
popupMenu.show();
}
private void launchShareIntent(Page page) {
try {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, page.title);
i.putExtra(Intent.EXTRA_TEXT, page.contentUrl);
startActivity(Intent.createChooser(i, "Share with...."));
} catch(Exception e) {
Log.e(TAG, "exception while sharing - " + e.getLocalizedMessage());
}
}
private void launchDetailActivity(Page page) {
Intent intent = new Intent(getActivity(), DetailActivity.class);
intent.putExtra(DetailActivity.EXTRA_PAGE_ID, page.id);
intent.putExtra(DetailActivity.EXTRA_PAGE_NAME, page.title);
startActivity(intent);
}
}
| 7,046 | 0.623049 | 0.622197 | 188 | 36.478722 | 29.291538 | 134 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.659574 | false | false | 13 |
b25265755caedc22f9a9c3f14c828e5ec0581ad6 | 30,751,965,881,405 | d3dc7cce3026141d4d706b7b915e6ab62c9ffdb3 | /src/minecraft/net/minecraft/src/VillageDoorInfo.java | bfb6dfe477b1b18869ae73ee3ad5c0c6f17b5c3a | []
| no_license | Rob4001/UMC-Client | https://github.com/Rob4001/UMC-Client | eec49225f15224cda910fd7850878b3e594913d2 | ab93ea52a7f0e36ec22ea50d096e209000cd3d78 | refs/heads/master | 2016-09-06T01:58:30.770000 | 2012-03-04T16:18:49 | 2012-03-04T16:19:12 | 3,112,848 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.minecraft.src;
public class VillageDoorInfo
{
public final int field_48600_a;
public final int field_48598_b;
public final int field_48599_c;
public final int field_48596_d;
public final int field_48597_e;
public int field_48594_f;
public boolean field_48595_g;
private int field_48601_h;
public VillageDoorInfo(int par1, int par2, int par3, int par4, int par5, int par6)
{
field_48595_g = false;
field_48601_h = 0;
field_48600_a = par1;
field_48598_b = par2;
field_48599_c = par3;
field_48596_d = par4;
field_48597_e = par5;
field_48594_f = par6;
}
public int func_48588_a(int par1, int par2, int par3)
{
int i = par1 - field_48600_a;
int j = par2 - field_48598_b;
int k = par3 - field_48599_c;
return i * i + j * j + k * k;
}
public int func_48593_b(int par1, int par2, int par3)
{
int i = par1 - field_48600_a - field_48596_d;
int j = par2 - field_48598_b;
int k = par3 - field_48599_c - field_48597_e;
return i * i + j * j + k * k;
}
public int func_48590_a()
{
return field_48600_a + field_48596_d;
}
public int func_48592_b()
{
return field_48598_b;
}
public int func_48591_c()
{
return field_48599_c + field_48597_e;
}
public boolean func_48586_a(int par1, int par2)
{
int i = par1 - field_48600_a;
int j = par2 - field_48599_c;
return i * field_48596_d + j * field_48597_e >= 0;
}
public void func_48585_d()
{
field_48601_h = 0;
}
public void func_48589_e()
{
field_48601_h++;
}
public int func_48587_f()
{
return field_48601_h;
}
}
| UTF-8 | Java | 1,816 | java | VillageDoorInfo.java | Java | []
| null | []
| package net.minecraft.src;
public class VillageDoorInfo
{
public final int field_48600_a;
public final int field_48598_b;
public final int field_48599_c;
public final int field_48596_d;
public final int field_48597_e;
public int field_48594_f;
public boolean field_48595_g;
private int field_48601_h;
public VillageDoorInfo(int par1, int par2, int par3, int par4, int par5, int par6)
{
field_48595_g = false;
field_48601_h = 0;
field_48600_a = par1;
field_48598_b = par2;
field_48599_c = par3;
field_48596_d = par4;
field_48597_e = par5;
field_48594_f = par6;
}
public int func_48588_a(int par1, int par2, int par3)
{
int i = par1 - field_48600_a;
int j = par2 - field_48598_b;
int k = par3 - field_48599_c;
return i * i + j * j + k * k;
}
public int func_48593_b(int par1, int par2, int par3)
{
int i = par1 - field_48600_a - field_48596_d;
int j = par2 - field_48598_b;
int k = par3 - field_48599_c - field_48597_e;
return i * i + j * j + k * k;
}
public int func_48590_a()
{
return field_48600_a + field_48596_d;
}
public int func_48592_b()
{
return field_48598_b;
}
public int func_48591_c()
{
return field_48599_c + field_48597_e;
}
public boolean func_48586_a(int par1, int par2)
{
int i = par1 - field_48600_a;
int j = par2 - field_48599_c;
return i * field_48596_d + j * field_48597_e >= 0;
}
public void func_48585_d()
{
field_48601_h = 0;
}
public void func_48589_e()
{
field_48601_h++;
}
public int func_48587_f()
{
return field_48601_h;
}
}
| 1,816 | 0.547357 | 0.406388 | 78 | 22.282051 | 18.739029 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.564103 | false | false | 13 |
812db439286dba547d719c9707130a57c1d754d7 | 4,904,852,682,399 | 9cb229279c36966d87c8dd2162b333752bcc638c | /src/main/java/io/polyglotapps/user/UserService.java | 52003b922a643d3c06da9c278ae68a3c4905722a | []
| no_license | arturmkrtchyan/spring-boot-skeleton | https://github.com/arturmkrtchyan/spring-boot-skeleton | efbc41f5d146f799346fc94ede9f1859cc98404a | 937d38818280785214f9f29bf5d720a75707524d | refs/heads/master | 2020-12-02T22:18:11.435000 | 2017-07-03T12:56:11 | 2017-07-03T12:56:11 | 96,110,765 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package io.polyglotapps.user;
import io.polyglotapps.system.EntityCreatedEvent;
import io.polyglotapps.system.security.AuthorizationFailureException;
import io.polyglotapps.system.security.SecurityContextAccessor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.Optional;
import java.util.UUID;
@Service
@Slf4j
class UserService {
@Autowired
private UserRepository repository;
@Autowired
PasswordEncoder passwordEncoder;
@Autowired
private SecurityContextAccessor securityContextAccessor;
@Autowired
private ApplicationEventPublisher eventPublisher;
User createUser(final User user) {
//encode password before saving.
final String plainPassword = user.getCredentials().getPassword();
final String encodedPassword = passwordEncoder.encode(plainPassword);
user.getCredentials().setPassword(encodedPassword);
// create email verification code
user.setEmailVerificationCode(UUID.randomUUID().toString());
final User createdUser = repository.save(user);
// TODO email needs to be sent via listener
eventPublisher.publishEvent(new EntityCreatedEvent<User>(createdUser));
return createdUser;
}
User updateUser(final Long id, final User user) {
final String email = (String) securityContextAccessor.getContext().getAuthentication().getPrincipal();
final User persistedUser = repository.findByCredentialsEmail(email)
.orElseThrow(AuthorizationFailureException::new);
// TODO move to spring security
if(!persistedUser.getId().equals(id)) {
throw new AuthorizationFailureException();
}
persistedUser.merge(user);
return repository.save(persistedUser);
}
User verifyEmail(final String token) {
final Optional<User> user = repository.findByEmailVerificationCode(token);
if(user.isPresent() && token.equals(user.get().getEmailVerificationCode())) {
user.get().setEmailVerificationCode(null);
user.get().setIsEmailVerified(Boolean.TRUE);
return repository.save(user.get());
}
return null;
}
Optional<User> getUserByEmail(final String email) {
return repository.findByCredentialsEmail(email);
}
boolean tryAuthentication(final Credentials credentials) {
log.info(credentials.toString());
final Optional<User> userResult = getUserByEmail(credentials.getEmail());
return userResult.filter(user -> passwordEncoder.matches(credentials.getPassword(),
user.getCredentials().getPassword())).isPresent();
}
}
| UTF-8 | Java | 2,914 | java | UserService.java | Java | []
| null | []
| package io.polyglotapps.user;
import io.polyglotapps.system.EntityCreatedEvent;
import io.polyglotapps.system.security.AuthorizationFailureException;
import io.polyglotapps.system.security.SecurityContextAccessor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.Optional;
import java.util.UUID;
@Service
@Slf4j
class UserService {
@Autowired
private UserRepository repository;
@Autowired
PasswordEncoder passwordEncoder;
@Autowired
private SecurityContextAccessor securityContextAccessor;
@Autowired
private ApplicationEventPublisher eventPublisher;
User createUser(final User user) {
//encode password before saving.
final String plainPassword = user.getCredentials().getPassword();
final String encodedPassword = passwordEncoder.encode(plainPassword);
user.getCredentials().setPassword(encodedPassword);
// create email verification code
user.setEmailVerificationCode(UUID.randomUUID().toString());
final User createdUser = repository.save(user);
// TODO email needs to be sent via listener
eventPublisher.publishEvent(new EntityCreatedEvent<User>(createdUser));
return createdUser;
}
User updateUser(final Long id, final User user) {
final String email = (String) securityContextAccessor.getContext().getAuthentication().getPrincipal();
final User persistedUser = repository.findByCredentialsEmail(email)
.orElseThrow(AuthorizationFailureException::new);
// TODO move to spring security
if(!persistedUser.getId().equals(id)) {
throw new AuthorizationFailureException();
}
persistedUser.merge(user);
return repository.save(persistedUser);
}
User verifyEmail(final String token) {
final Optional<User> user = repository.findByEmailVerificationCode(token);
if(user.isPresent() && token.equals(user.get().getEmailVerificationCode())) {
user.get().setEmailVerificationCode(null);
user.get().setIsEmailVerified(Boolean.TRUE);
return repository.save(user.get());
}
return null;
}
Optional<User> getUserByEmail(final String email) {
return repository.findByCredentialsEmail(email);
}
boolean tryAuthentication(final Credentials credentials) {
log.info(credentials.toString());
final Optional<User> userResult = getUserByEmail(credentials.getEmail());
return userResult.filter(user -> passwordEncoder.matches(credentials.getPassword(),
user.getCredentials().getPassword())).isPresent();
}
}
| 2,914 | 0.716541 | 0.715511 | 85 | 33.282352 | 29.300718 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.447059 | false | false | 13 |
df7522fb88fdb114f1d3864691cba83ef11d9b14 | 30,313,879,188,987 | da08213a2f9efb64df56e19e2c63c0da3fa1dc33 | /app/src/main/java/it/mad8/expenseshare/ExpenseShareApplication.java | abcffe4953d067401ececfea53fa69764df40454 | []
| no_license | aceandro2812/ExpenseShareApp | https://github.com/aceandro2812/ExpenseShareApp | 24738c894cfafe2db7b9aa09e3d94c1707462318 | 2394a2281491e156169fd6ed6d345769dce30aff | refs/heads/master | 2021-06-20T13:44:32.821000 | 2017-07-25T13:42:30 | 2017-07-25T13:42:30 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package it.mad8.expenseshare;
import android.app.Application;
import it.mad8.expenseshare.model.UserModel;
/**
* Created by giaco on 12/05/2017.
*/
public class ExpenseShareApplication extends Application {
private UserModel user;
public ExpenseShareApplication() {
super();
}
@Override
public void onCreate() {
super.onCreate();
}
public void setUserModel(UserModel user){
this.user = user;
}
public UserModel getUserModel(){
return user;
}
}
| UTF-8 | Java | 527 | java | ExpenseShareApplication.java | Java | [
{
"context": "8.expenseshare.model.UserModel;\n\n/**\n * Created by giaco on 12/05/2017.\n */\n\npublic class ExpenseShareAppl",
"end": 134,
"score": 0.9996607303619385,
"start": 129,
"tag": "USERNAME",
"value": "giaco"
}
]
| null | []
| package it.mad8.expenseshare;
import android.app.Application;
import it.mad8.expenseshare.model.UserModel;
/**
* Created by giaco on 12/05/2017.
*/
public class ExpenseShareApplication extends Application {
private UserModel user;
public ExpenseShareApplication() {
super();
}
@Override
public void onCreate() {
super.onCreate();
}
public void setUserModel(UserModel user){
this.user = user;
}
public UserModel getUserModel(){
return user;
}
}
| 527 | 0.650854 | 0.631879 | 31 | 16 | 16.842726 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.258065 | false | false | 13 |
f7c780fc331359c1262b02c1f03ed73cab988d77 | 5,437,428,644,878 | a335ee604ad472d56101055311733c1a876f6c86 | /pyweather/src/main/java/com/neuroandroid/pyweather/bean/ISelect.java | 0aa1146d01cff3718507cbceb2ebd77bbce01ee6 | []
| no_license | pangyu646182805/PYWeather | https://github.com/pangyu646182805/PYWeather | 6c4bc04cd1b5c7998f9032e73ade2025cacb7ea0 | 99f0514fc5ee6cec205a2db5dec517ca1cc16d5a | refs/heads/master | 2021-01-23T10:08:36.398000 | 2017-07-27T16:19:49 | 2017-07-27T16:19:49 | 93,040,896 | 32 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.neuroandroid.pyweather.bean;
import android.view.View;
/**
* Created by NeuroAndroid on 2017/3/9.
*/
public interface ISelect {
int SINGLE_MODE = 1;
int MULTIPLE_MODE = 2;
String getText();
void setText(String text);
boolean isSelected();
void setSelected(boolean selected);
interface OnItemSelectedListener<T> {
void onItemSelected(View view, int position, boolean isSelected, T t);
}
}
| UTF-8 | Java | 450 | java | ISelect.java | Java | [
{
"context": "ean;\n\nimport android.view.View;\n\n/**\n * Created by NeuroAndroid on 2017/3/9.\n */\n\npublic interface ISelect {\n ",
"end": 99,
"score": 0.9992652535438538,
"start": 87,
"tag": "USERNAME",
"value": "NeuroAndroid"
}
]
| null | []
| package com.neuroandroid.pyweather.bean;
import android.view.View;
/**
* Created by NeuroAndroid on 2017/3/9.
*/
public interface ISelect {
int SINGLE_MODE = 1;
int MULTIPLE_MODE = 2;
String getText();
void setText(String text);
boolean isSelected();
void setSelected(boolean selected);
interface OnItemSelectedListener<T> {
void onItemSelected(View view, int position, boolean isSelected, T t);
}
}
| 450 | 0.68 | 0.662222 | 24 | 17.75 | 19.799517 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 13 |
60e3d67ede975ec90c46f7696eafde5e5867af70 | 4,724,464,041,539 | 9a32b4bf06aaf662deddf230a109882e62cf60d0 | /app/src/main/java/intellibitz/intellidroid/widget/advrecyclerview/swipeable/annotation/SwipeableItemStateFlags.java | a10e64631e489640d50a9e43abf28215c7222c88 | [
"Apache-2.0"
]
| permissive | intellibitz/IntelliDroid | https://github.com/intellibitz/IntelliDroid | 4ed66d78cfaf70ce9f8cb9656089d66ebafcd99e | feb5353dd5f5ce85d1118f2cc2b9aa3b674dc354 | refs/heads/master | 2022-11-29T23:55:11.890000 | 2020-08-19T13:21:26 | 2020-08-19T13:21:26 | 288,398,784 | 0 | 0 | Apache-2.0 | false | 2020-08-19T13:21:28 | 2020-08-18T08:27:37 | 2020-08-19T11:46:34 | 2020-08-19T13:21:27 | 923 | 0 | 0 | 0 | Java | false | false |
package intellibitz.intellidroid.widget.advrecyclerview.swipeable.annotation;
import intellibitz.intellidroid.widget.advrecyclerview.swipeable.SwipeableItemConstants;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import androidx.annotation.IntDef;
import intellibitz.intellidroid.widget.advrecyclerview.swipeable.SwipeableItemConstants;
@IntDef(flag = true, value = {
SwipeableItemConstants.STATE_FLAG_SWIPING,
SwipeableItemConstants.STATE_FLAG_IS_ACTIVE,
SwipeableItemConstants.STATE_FLAG_IS_UPDATED,
})
@Retention(RetentionPolicy.SOURCE)
public @interface SwipeableItemStateFlags {
}
| UTF-8 | Java | 654 | java | SwipeableItemStateFlags.java | Java | []
| null | []
|
package intellibitz.intellidroid.widget.advrecyclerview.swipeable.annotation;
import intellibitz.intellidroid.widget.advrecyclerview.swipeable.SwipeableItemConstants;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import androidx.annotation.IntDef;
import intellibitz.intellidroid.widget.advrecyclerview.swipeable.SwipeableItemConstants;
@IntDef(flag = true, value = {
SwipeableItemConstants.STATE_FLAG_SWIPING,
SwipeableItemConstants.STATE_FLAG_IS_ACTIVE,
SwipeableItemConstants.STATE_FLAG_IS_UPDATED,
})
@Retention(RetentionPolicy.SOURCE)
public @interface SwipeableItemStateFlags {
}
| 654 | 0.82263 | 0.82263 | 18 | 35.222221 | 29.387365 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false | 13 |
c89e3aaa50cf637a7b382fe3769f97137b3c57b9 | 14,817,637,174,864 | 40aea068ee4d38a331d1b26b9d9e13aad38a5639 | /src/main/java/com/vaibhavi/intuit/demo/ordermanagement/service/OrderPlaceService.java | 4a45517f216da10e435bda71ff69d49bac7d5da0 | []
| no_license | akleem2/order-management | https://github.com/akleem2/order-management | ad5719bbaa97314496bb91a831d061823e7c4229 | 3d9e161aa69c57c2b7b82b72cb7809614f6db7ac | refs/heads/main | 2023-04-23T07:17:11.504000 | 2021-05-10T15:56:11 | 2021-05-10T15:56:11 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.vaibhavi.intuit.demo.ordermanagement.service;
import com.vaibhavi.intuit.demo.ordermanagement.entity.Order;
public interface OrderPlaceService {
public Order placeOrder(Order productOrder);
public Object makePaymentService(Order productOrder);
}
| UTF-8 | Java | 277 | java | OrderPlaceService.java | Java | []
| null | []
| package com.vaibhavi.intuit.demo.ordermanagement.service;
import com.vaibhavi.intuit.demo.ordermanagement.entity.Order;
public interface OrderPlaceService {
public Order placeOrder(Order productOrder);
public Object makePaymentService(Order productOrder);
}
| 277 | 0.794224 | 0.794224 | 11 | 23.181818 | 25.756969 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.636364 | false | false | 13 |
03070d5f128cc59eadc1bb3e2ec64b77ba30d4a0 | 7,937,099,631,251 | 774ed22832843367326a5e234b0c1ba8b0756bcf | /api/src/main/java/com/example/api/service/IUserProductService.java | 2c934279223c8c334da6969aac6fb86ccf30b510 | []
| no_license | mayben0t/backend | https://github.com/mayben0t/backend | 8875a3c83cfbf6aa0fbef7dda077f22c4ba876a8 | fefb50cfa57ce2eea34ccaa0958548cde9383d6b | refs/heads/master | 2021-07-10T12:27:09.818000 | 2020-04-21T14:53:10 | 2020-04-21T14:53:10 | 241,405,506 | 0 | 0 | null | false | 2021-03-31T21:56:14 | 2020-02-18T16:06:26 | 2020-04-21T14:54:34 | 2021-03-31T21:56:14 | 103 | 0 | 0 | 2 | Java | false | false | package com.example.api.service;
import com.example.api.model.UserProduct;
import java.util.List;
public interface IUserProductService {
List<UserProduct> getAll();
List<UserProduct> getAllByPage(Integer start,Integer size);
Integer getAllCount();
void insert(UserProduct userProduct);
UserProduct selectByUserIdAndDesc(Integer userId, String desc);
int update(UserProduct userProduct);
int updateByUserId(UserProduct userProduct);
}
| UTF-8 | Java | 472 | java | IUserProductService.java | Java | []
| null | []
| package com.example.api.service;
import com.example.api.model.UserProduct;
import java.util.List;
public interface IUserProductService {
List<UserProduct> getAll();
List<UserProduct> getAllByPage(Integer start,Integer size);
Integer getAllCount();
void insert(UserProduct userProduct);
UserProduct selectByUserIdAndDesc(Integer userId, String desc);
int update(UserProduct userProduct);
int updateByUserId(UserProduct userProduct);
}
| 472 | 0.762712 | 0.762712 | 22 | 20.454546 | 22.471653 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.545455 | false | false | 13 |
af31955bbdb77a76bbdd58d24da461ef5ce1f422 | 36,593,121,374,107 | 733eff02981dde2c16d031ab13f77fe6c9728ea2 | /src/test/java/interfaces/seleniumActionsMethodsI.java | 3b53e3f2b62bad052dd50d52a43b4afbe0b5deb7 | []
| no_license | Chinchi13/test | https://github.com/Chinchi13/test | 82b90026887613bdf7917e04a6b07125e2aea39a | 89c46f7ce2ce78f533ad7444f8688009f0ecfdf2 | refs/heads/main | 2022-12-31T14:48:04.296000 | 2020-10-25T23:16:56 | 2020-10-25T23:16:56 | 307,177,969 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package interfaces;
import org.openqa.selenium.WebElement;
public interface seleniumActionsMethodsI {
public void moveMouse(WebElement element) throws InterruptedException;
public void moveMouseSlider(WebElement element);
public void moveMouseSliderDisminucion(WebElement element);
public void moveMouseSliderAumentoAdicional(WebElement element);
}
| UTF-8 | Java | 356 | java | seleniumActionsMethodsI.java | Java | []
| null | []
| package interfaces;
import org.openqa.selenium.WebElement;
public interface seleniumActionsMethodsI {
public void moveMouse(WebElement element) throws InterruptedException;
public void moveMouseSlider(WebElement element);
public void moveMouseSliderDisminucion(WebElement element);
public void moveMouseSliderAumentoAdicional(WebElement element);
}
| 356 | 0.851124 | 0.851124 | 11 | 31.363636 | 26.995867 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.909091 | false | false | 13 |
6c2ed22e0f5ae96b2389724ee498b4b207f4a8eb | 24,893,630,471,587 | 3fad0d82933d30f457daae03cef65e52b7c91300 | /76/src/Solution.java | bea0107e8684f2498e228ba781be81416d4a60b5 | []
| no_license | 616905919/leetcode | https://github.com/616905919/leetcode | c3b8241099e2de712aef0f2f8cd073897ade0566 | ff50d8b4a13747446f3fae4dbbd5a780af0c556b | refs/heads/master | 2016-09-01T15:45:34.137000 | 2016-03-23T13:38:27 | 2016-03-23T13:38:41 | 54,562,137 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
public class Solution {
public String minWindow(String s, String t) {
HashMap<Character, Integer> h = new HashMap<Character, Integer>();
for(int i = 0 ; i < t.length() ; i++){
if(h.containsKey(t.charAt(i))){
h.put(t.charAt(i), h.get(t.charAt(i))+1);
}
else h.put(t.charAt(i), 1);
}
new Object().equals(new Object());
Collection<Integer> c = new ArrayList<Integer>();
}
}
| UTF-8 | Java | 563 | java | Solution.java | Java | []
| null | []
| import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
public class Solution {
public String minWindow(String s, String t) {
HashMap<Character, Integer> h = new HashMap<Character, Integer>();
for(int i = 0 ; i < t.length() ; i++){
if(h.containsKey(t.charAt(i))){
h.put(t.charAt(i), h.get(t.charAt(i))+1);
}
else h.put(t.charAt(i), 1);
}
new Object().equals(new Object());
Collection<Integer> c = new ArrayList<Integer>();
}
}
| 563 | 0.602131 | 0.596803 | 19 | 27.631578 | 20.003185 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.578947 | false | false | 13 |
5029893bca4bba7ac5fb6a9cf95d1c5cb29fee08 | 13,623,636,287,947 | 724b43e4f9aeacfc4d069b38e6cfc4f718507bbc | /lab/app/src/main/java/mk/ukim/finki/lab/model/Movie.java | 5352c4295fdfe19546a4ef958a8ddffa7188ae46 | []
| no_license | todorht/MPIP_lab | https://github.com/todorht/MPIP_lab | 4938dfbbe32393e55b3c233d0d42470b3d54bece | b58c30d08d882490dc96f375e18613e29c8143e7 | refs/heads/master | 2023-02-13T04:05:07.776000 | 2021-01-05T21:32:45 | 2021-01-05T21:32:45 | 312,571,047 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package mk.ukim.finki.lab.model;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.List;
public class Movie {
@SerializedName("Title")
private String title;
@SerializedName("Year")
private String year;
@SerializedName("Rated")
private String rated;
@SerializedName("Released")
private String released;
@SerializedName("Runtime")
private String runtime;
@SerializedName("Genre")
private String genre;
@SerializedName("Director")
private String director;
@SerializedName("Writer")
private String writer;
@SerializedName("Actors")
private String actors;
@SerializedName("Plot")
private String plot;
@SerializedName("Language")
private String language;
@SerializedName("Country")
private String country;
@SerializedName("Awards")
private String awards;
@SerializedName("Poster")
private String poster;
@SerializedName("Ratings")
private List<Rating> ratings;
@SerializedName("Metascore")
private String metascore;
private String imdbRating;
private String imdbVotes;
@SerializedName("imdbID")
private String imdbId;
@SerializedName("Type")
private String type;
@SerializedName("DVD")
private String dvd;
@SerializedName("BoxOffice")
private String boxOffice;
@SerializedName("Production")
private String production;
@SerializedName("Website")
private String website;
@SerializedName("Response")
private String response;
public Movie(String name, String director ,String description) {
this.id = (long) (Math.random() *1000);
this.name = name;
this.director = director;
this.description = description;
this.actors = new ArrayList<>();
}
public Movie(String name, String director ,String description, List<Actor> actors) {
this.id = (long) (Math.random() *1000);
this.name = name;
this.director = director;
this.description = description;
this.actors = actors;
}
}
| UTF-8 | Java | 2,098 | java | Movie.java | Java | []
| null | []
| package mk.ukim.finki.lab.model;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.List;
public class Movie {
@SerializedName("Title")
private String title;
@SerializedName("Year")
private String year;
@SerializedName("Rated")
private String rated;
@SerializedName("Released")
private String released;
@SerializedName("Runtime")
private String runtime;
@SerializedName("Genre")
private String genre;
@SerializedName("Director")
private String director;
@SerializedName("Writer")
private String writer;
@SerializedName("Actors")
private String actors;
@SerializedName("Plot")
private String plot;
@SerializedName("Language")
private String language;
@SerializedName("Country")
private String country;
@SerializedName("Awards")
private String awards;
@SerializedName("Poster")
private String poster;
@SerializedName("Ratings")
private List<Rating> ratings;
@SerializedName("Metascore")
private String metascore;
private String imdbRating;
private String imdbVotes;
@SerializedName("imdbID")
private String imdbId;
@SerializedName("Type")
private String type;
@SerializedName("DVD")
private String dvd;
@SerializedName("BoxOffice")
private String boxOffice;
@SerializedName("Production")
private String production;
@SerializedName("Website")
private String website;
@SerializedName("Response")
private String response;
public Movie(String name, String director ,String description) {
this.id = (long) (Math.random() *1000);
this.name = name;
this.director = director;
this.description = description;
this.actors = new ArrayList<>();
}
public Movie(String name, String director ,String description, List<Actor> actors) {
this.id = (long) (Math.random() *1000);
this.name = name;
this.director = director;
this.description = description;
this.actors = actors;
}
}
| 2,098 | 0.673975 | 0.670162 | 73 | 27.739725 | 13.324226 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.60274 | false | false | 13 |
5a5e6c142e83091978dd81a73e664304ae181559 | 9,775,345,595,730 | 063b7bc0348788fb8a82efd606a45afbe67ec193 | /src/main/java/com/movies/Gmovies/GMovieService.java | 38e067c2b833b2db75a724bea3528a383aa98803 | []
| no_license | ranjanr2/GMovies | https://github.com/ranjanr2/GMovies | 47a0df6694f956b4cd21fa0d4fe9acbfd8b11e3a | 1d6d60c2d9ab363d208001049143e8281a27ca50 | refs/heads/main | 2023-03-25T15:09:32.045000 | 2021-03-20T21:07:09 | 2021-03-20T21:07:09 | 349,752,347 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.movies.Gmovies;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
//title, director, actors, release year, description and star rating.
@Service
public class GMovieService {
private final GMovieRepository movieRepository;
public GMovieService(GMovieRepository movieRepository) {
this.movieRepository = movieRepository;
}
public void create(GMovieDto movieDto) {
movieRepository.save(
new GMovieEntity(movieDto.getTitle(),
movieDto.getDirector(),
movieDto.getActors(),
movieDto.getRelease(),
movieDto.getDescription(),
new ArrayList<>()
));
}
public List<GMovieDto> getAllMovies() {
return movieRepository.findAll()
.stream()
.map(movieEntity -> {
return new GMovieDto(movieEntity.getTitle(),
movieEntity.getDirector(),
movieEntity.getActors(),
movieEntity.getRelease(),
movieEntity.getDescription(),
movieEntity.getRating(),
movieEntity.getReviews() );
})
.collect(Collectors.toList());
}
public GMovieDto getMovieByTitle(String title) {
return movieRepository.findAll()
.stream()
.filter(movieEntity -> movieEntity.getTitle().equals(title))
.map(movieEntity -> {
return new GMovieDto(movieEntity.getTitle(),
movieEntity.getDirector(),
movieEntity.getActors(),
movieEntity.getRelease(),
movieEntity.getDescription(),
movieEntity.getRating(),
movieEntity.getReviews());
}).collect(Collectors.toList())
.stream().findFirst().orElse(null);
}
public void updateMovie(MovieReviewDto movieReviewDto) {
GMovieEntity movieEntity = movieRepository.findAll()
.stream()
.filter(en ->
en.getTitle().equals(movieReviewDto.getTitle()))
.collect(Collectors.toList()).stream().findFirst().orElse(null);
if (movieEntity != null){
movieEntity.addRating(movieReviewDto.getRating());
movieEntity.addReview(movieReviewDto.getReview());
}
movieRepository.save(movieEntity);
}
}
| UTF-8 | Java | 2,741 | java | GMovieService.java | Java | []
| null | []
| package com.movies.Gmovies;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
//title, director, actors, release year, description and star rating.
@Service
public class GMovieService {
private final GMovieRepository movieRepository;
public GMovieService(GMovieRepository movieRepository) {
this.movieRepository = movieRepository;
}
public void create(GMovieDto movieDto) {
movieRepository.save(
new GMovieEntity(movieDto.getTitle(),
movieDto.getDirector(),
movieDto.getActors(),
movieDto.getRelease(),
movieDto.getDescription(),
new ArrayList<>()
));
}
public List<GMovieDto> getAllMovies() {
return movieRepository.findAll()
.stream()
.map(movieEntity -> {
return new GMovieDto(movieEntity.getTitle(),
movieEntity.getDirector(),
movieEntity.getActors(),
movieEntity.getRelease(),
movieEntity.getDescription(),
movieEntity.getRating(),
movieEntity.getReviews() );
})
.collect(Collectors.toList());
}
public GMovieDto getMovieByTitle(String title) {
return movieRepository.findAll()
.stream()
.filter(movieEntity -> movieEntity.getTitle().equals(title))
.map(movieEntity -> {
return new GMovieDto(movieEntity.getTitle(),
movieEntity.getDirector(),
movieEntity.getActors(),
movieEntity.getRelease(),
movieEntity.getDescription(),
movieEntity.getRating(),
movieEntity.getReviews());
}).collect(Collectors.toList())
.stream().findFirst().orElse(null);
}
public void updateMovie(MovieReviewDto movieReviewDto) {
GMovieEntity movieEntity = movieRepository.findAll()
.stream()
.filter(en ->
en.getTitle().equals(movieReviewDto.getTitle()))
.collect(Collectors.toList()).stream().findFirst().orElse(null);
if (movieEntity != null){
movieEntity.addRating(movieReviewDto.getRating());
movieEntity.addReview(movieReviewDto.getReview());
}
movieRepository.save(movieEntity);
}
}
| 2,741 | 0.533747 | 0.533747 | 77 | 34.597404 | 23.43117 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.480519 | false | false | 13 |
338e67eba75be1047334c2918053c8fb9251a555 | 5,987,184,441,283 | f1c12e6a3922587725961b9686f866b12ba41139 | /soak/src/web/no/unified/soak/webapp/action/CourseFileFormController.java | c5333bc9feaf00a1f8e584951fbaabd6e78322cf | [
"Apache-2.0"
]
| permissive | frikomport/frikomport | https://github.com/frikomport/frikomport | bdd98f7f23dc599991c8b6b240245aa6fd99f1f2 | 30516632a5c9f63d793ff3c18213178e007441bc | refs/heads/master | 2020-04-06T06:38:59.712000 | 2014-09-29T11:43:18 | 2014-09-29T11:43:18 | 24,589,973 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* This file is distributed under the GNU Public Licence (GPL).
* See http://www.gnu.org/copyleft/gpl.html for further details
* of the GPL.
*
* @author Unified Consulting AS
*/
/*
* Created January 19th 2006
*/
package no.unified.soak.webapp.action;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import no.unified.soak.Constants;
import no.unified.soak.model.Attachment;
import no.unified.soak.model.Course;
import no.unified.soak.service.AttachmentManager;
import no.unified.soak.service.CourseManager;
import no.unified.soak.webapp.util.FileUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;
/**
* Handles uploading/deletion of files attached to a course
*
* @author hrj
*/
public class CourseFileFormController extends BaseFormController {
private CourseManager courseManager = null;
private AttachmentManager attachmentManager = null;
public void setCourseManager(CourseManager courseManager) {
this.courseManager = courseManager;
}
public void setAttachmentManager(AttachmentManager attachmentManager) {
this.attachmentManager = attachmentManager;
}
/**
* @see org.springframework.web.servlet.mvc.SimpleFormController#referenceData(javax.servlet.http.HttpServletRequest)
*/
protected Map referenceData(HttpServletRequest request)
throws Exception {
Map<String, Object> model = new HashMap<String, Object>();
Course course = null;
String courseid = request.getParameter("courseId");
course = courseManager.getCourse(courseid);
model.put("course", course);
AttachmentsBackingObject abo = getAttachmentsBackingObjects(new Long(
courseid));
model.put("attachmentsBackingObject", abo);
return model;
}
/**
* Gets the info of the attachments attached to given objects
*
* @param courseid
* the course to get the attachements for
* @return The attachments
*/
private AttachmentsBackingObject getAttachmentsBackingObjects(Long courseid) {
AttachmentsBackingObject abo = new AttachmentsBackingObject();
List attachments = attachmentManager.getCourseAttachments(courseid);
abo.setAttachments(attachments);
return abo;
}
/**
* @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse, java.lang.Object,
* org.springframework.validation.BindException)
*/
public ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors)
throws Exception {
if (log.isDebugEnabled()) {
log.debug("entering 'onSubmit' method...");
}
Map<String, Object> model = new HashMap<String, Object>();
FileUpload fileUpload = (FileUpload) command;
String courseid = request.getParameter("courseId");
Locale locale = request.getLocale();
// Are we to cancel?
if (request.getParameter("docancel") != null) {
if (log.isDebugEnabled()) {
log.debug("recieved 'cancel' from jsp");
}
return new ModelAndView(getCancelView(), "id", courseid);
} // or to download?
else if (request.getParameter("download") != null) {
// Stream file to the client
try {
String attachmentId = request.getParameter("attachmentid");
if ((attachmentId != null) &&
StringUtils.isNumeric(attachmentId) &&
(new Integer(attachmentId).intValue() != 0)) {
Attachment attachment = attachmentManager.getAttachment(new Long(
attachmentId));
FileUtil.downloadFile(request, response, attachment.getContentType(), attachment.getStoredname(), attachment.getFilename());
saveMessage(request, getText("attachment.sent", locale));
}
} catch (FileNotFoundException fnfe) {
log.error(fnfe);
String key = "attachment.sendError";
errors.reject(key);
return showForm(request, response, errors);
} catch (IOException ioe) {
log.error(ioe);
String key = "errors.ioerror";
errors.reject(key);
return showForm(request, response, errors);
}
} else if (request.getParameter("delete") != null) {
// Delete the file and the attachment-object
String attachmentId = request.getParameter("attachmentid");
if ((attachmentId != null) && StringUtils.isNumeric(attachmentId) &&
(new Integer(attachmentId).intValue() != 0)) {
Attachment attachment = attachmentManager.getAttachment(new Long(attachmentId));
try {
boolean deleted = FileUtil.deleteFile(attachment.getStoredname());
if (!deleted) {
String key = "errors.deleteFile";
errors.reject(key);
return showForm(request, response, errors);
} else {
attachmentManager.removeAttachment(new Long(
attachmentId));
}
saveMessage(request, getText("attachment.deleted", locale));
} catch (Exception e) {
log.error(e);
String key = "errors.deleteFile";
errors.reject(key);
return showForm(request, response, errors);
}
}
} else {
// Recieve file from client
if (fileUpload.getFile().length == 0) {
Object[] args = new Object[] {
getText("uploadForm.file", request.getLocale())
};
errors.rejectValue("file", "errors.required", args, "File");
return showForm(request, response, errors);
}
String key = "attachment.maxsize";
String maxSize = getText(key, locale);
// Is the file within the size limit?
if (fileUpload.getFile().length > new Long(maxSize)) {
key = "errors.filetoobig";
String[] args = {
fileUpload.getName(),
String.valueOf(fileUpload.getFile().length), maxSize
};
errors.rejectValue("file", key, args,
"File is bigger than allowed size (" + maxSize + " bytes)");
return showForm(request, response, errors);
}
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile(
"file");
// the directory to upload to
Attachment attachment = saveAttachment(courseid, file);
String storedname = Constants.ATTACHMENT_FILE_PREFIX +
attachment.getId();
try {
FileUtil.recieveFile(file, null, storedname);
saveMessage(request, getText("attachment.recieved", locale));
} catch (FileNotFoundException fnfe) {
log.error(fnfe);
key = "attachment.recieveError";
errors.reject(key);
return showForm(request, response, errors);
} catch (IOException ioe) {
log.error(ioe);
key = "errors.ioerror";
errors.reject(key);
return showForm(request, response, errors);
}
attachment.setStoredname(storedname);
attachmentManager.saveAttachment(attachment);
}
// Fetch info about the course
Course course = courseManager.getCourse(courseid);
model.put("course", course);
// Fetch the new file list
AttachmentsBackingObject abo = getAttachmentsBackingObjects(new Long(courseid));
model.put("attachmentsBackingObject", abo);
// Reset the fileUpload-object
fileUpload = new FileUpload();
model.put("fileUpload", fileUpload);
return new ModelAndView(getSuccessView(), model);
}
/**
* Persists the attachment
*
* @param courseid
* The course the attachment is going to be connected to
* @param file
* The file that contains the needed info to create the
* attachment
* @return The persisted attachment
*/
private Attachment saveAttachment(String courseid, CommonsMultipartFile file) {
Attachment attachment = new Attachment();
attachment.setContentType(file.getContentType());
attachment.setFilename(file.getOriginalFilename());
attachment.setCourseId(new Long(courseid));
attachment.setSize(file.getSize());
attachmentManager.saveAttachment(attachment);
return attachment;
}
}
| UTF-8 | Java | 10,033 | java | CourseFileFormController.java | Java | [
{
"context": "tion of files attached to a course\r\n *\r\n * @author hrj\r\n */\r\npublic class CourseFileFormController exten",
"end": 1207,
"score": 0.999466061592102,
"start": 1204,
"tag": "USERNAME",
"value": "hrj"
},
{
"context": "log.error(fnfe);\r\n\r\n String key = \"attachment.sendError\";\r\n errors.reject(key);\r\n\r\n ",
"end": 4826,
"score": 0.9988674521446228,
"start": 4806,
"tag": "KEY",
"value": "attachment.sendError"
},
{
"context": " log.error(ioe);\r\n\r\n String key = \"errors.ioerror\";\r\n errors.reject(key);\r\n\r\n ",
"end": 5050,
"score": 0.9991152882575989,
"start": 5036,
"tag": "KEY",
"value": "errors.ioerror"
},
{
"context": "deleted) {\r\n String key = \"errors.deleteFile\";\r\n errors.reject(key);\r\n\r",
"end": 5819,
"score": 0.9988084435462952,
"start": 5802,
"tag": "KEY",
"value": "errors.deleteFile"
},
{
"context": "og.error(e);\r\n\r\n String key = \"errors.deleteFile\";\r\n errors.reject(key);\r\n\r\n ",
"end": 6324,
"score": 0.9988052248954773,
"start": 6307,
"tag": "KEY",
"value": "errors.deleteFile"
},
{
"context": "ors);\r\n }\r\n\r\n String key = \"attachment.maxsize\";\r\n String maxSize = getText(key, loca",
"end": 6929,
"score": 0.9992642998695374,
"start": 6911,
"tag": "KEY",
"value": "attachment.maxsize"
},
{
"context": "th > new Long(maxSize)) {\r\n key = \"errors.filetoobig\";\r\n\r\n String[] args = {\r\n ",
"end": 7146,
"score": 0.9994531273841858,
"start": 7129,
"tag": "KEY",
"value": "errors.filetoobig"
},
{
"context": " log.error(fnfe);\r\n key = \"attachment.recieveError\";\r\n errors.reject(key);\r\n\r\n ",
"end": 8290,
"score": 0.9994003176689148,
"start": 8267,
"tag": "KEY",
"value": "attachment.recieveError"
},
{
"context": " log.error(ioe);\r\n key = \"errors.ioerror\";\r\n errors.reject(key);\r\n\r\n ",
"end": 8505,
"score": 0.999420166015625,
"start": 8491,
"tag": "KEY",
"value": "errors.ioerror"
}
]
| null | []
| /*
* This file is distributed under the GNU Public Licence (GPL).
* See http://www.gnu.org/copyleft/gpl.html for further details
* of the GPL.
*
* @author Unified Consulting AS
*/
/*
* Created January 19th 2006
*/
package no.unified.soak.webapp.action;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import no.unified.soak.Constants;
import no.unified.soak.model.Attachment;
import no.unified.soak.model.Course;
import no.unified.soak.service.AttachmentManager;
import no.unified.soak.service.CourseManager;
import no.unified.soak.webapp.util.FileUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;
/**
* Handles uploading/deletion of files attached to a course
*
* @author hrj
*/
public class CourseFileFormController extends BaseFormController {
private CourseManager courseManager = null;
private AttachmentManager attachmentManager = null;
public void setCourseManager(CourseManager courseManager) {
this.courseManager = courseManager;
}
public void setAttachmentManager(AttachmentManager attachmentManager) {
this.attachmentManager = attachmentManager;
}
/**
* @see org.springframework.web.servlet.mvc.SimpleFormController#referenceData(javax.servlet.http.HttpServletRequest)
*/
protected Map referenceData(HttpServletRequest request)
throws Exception {
Map<String, Object> model = new HashMap<String, Object>();
Course course = null;
String courseid = request.getParameter("courseId");
course = courseManager.getCourse(courseid);
model.put("course", course);
AttachmentsBackingObject abo = getAttachmentsBackingObjects(new Long(
courseid));
model.put("attachmentsBackingObject", abo);
return model;
}
/**
* Gets the info of the attachments attached to given objects
*
* @param courseid
* the course to get the attachements for
* @return The attachments
*/
private AttachmentsBackingObject getAttachmentsBackingObjects(Long courseid) {
AttachmentsBackingObject abo = new AttachmentsBackingObject();
List attachments = attachmentManager.getCourseAttachments(courseid);
abo.setAttachments(attachments);
return abo;
}
/**
* @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse, java.lang.Object,
* org.springframework.validation.BindException)
*/
public ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors)
throws Exception {
if (log.isDebugEnabled()) {
log.debug("entering 'onSubmit' method...");
}
Map<String, Object> model = new HashMap<String, Object>();
FileUpload fileUpload = (FileUpload) command;
String courseid = request.getParameter("courseId");
Locale locale = request.getLocale();
// Are we to cancel?
if (request.getParameter("docancel") != null) {
if (log.isDebugEnabled()) {
log.debug("recieved 'cancel' from jsp");
}
return new ModelAndView(getCancelView(), "id", courseid);
} // or to download?
else if (request.getParameter("download") != null) {
// Stream file to the client
try {
String attachmentId = request.getParameter("attachmentid");
if ((attachmentId != null) &&
StringUtils.isNumeric(attachmentId) &&
(new Integer(attachmentId).intValue() != 0)) {
Attachment attachment = attachmentManager.getAttachment(new Long(
attachmentId));
FileUtil.downloadFile(request, response, attachment.getContentType(), attachment.getStoredname(), attachment.getFilename());
saveMessage(request, getText("attachment.sent", locale));
}
} catch (FileNotFoundException fnfe) {
log.error(fnfe);
String key = "attachment.sendError";
errors.reject(key);
return showForm(request, response, errors);
} catch (IOException ioe) {
log.error(ioe);
String key = "errors.ioerror";
errors.reject(key);
return showForm(request, response, errors);
}
} else if (request.getParameter("delete") != null) {
// Delete the file and the attachment-object
String attachmentId = request.getParameter("attachmentid");
if ((attachmentId != null) && StringUtils.isNumeric(attachmentId) &&
(new Integer(attachmentId).intValue() != 0)) {
Attachment attachment = attachmentManager.getAttachment(new Long(attachmentId));
try {
boolean deleted = FileUtil.deleteFile(attachment.getStoredname());
if (!deleted) {
String key = "errors.deleteFile";
errors.reject(key);
return showForm(request, response, errors);
} else {
attachmentManager.removeAttachment(new Long(
attachmentId));
}
saveMessage(request, getText("attachment.deleted", locale));
} catch (Exception e) {
log.error(e);
String key = "errors.deleteFile";
errors.reject(key);
return showForm(request, response, errors);
}
}
} else {
// Recieve file from client
if (fileUpload.getFile().length == 0) {
Object[] args = new Object[] {
getText("uploadForm.file", request.getLocale())
};
errors.rejectValue("file", "errors.required", args, "File");
return showForm(request, response, errors);
}
String key = "attachment.maxsize";
String maxSize = getText(key, locale);
// Is the file within the size limit?
if (fileUpload.getFile().length > new Long(maxSize)) {
key = "errors.filetoobig";
String[] args = {
fileUpload.getName(),
String.valueOf(fileUpload.getFile().length), maxSize
};
errors.rejectValue("file", key, args,
"File is bigger than allowed size (" + maxSize + " bytes)");
return showForm(request, response, errors);
}
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile(
"file");
// the directory to upload to
Attachment attachment = saveAttachment(courseid, file);
String storedname = Constants.ATTACHMENT_FILE_PREFIX +
attachment.getId();
try {
FileUtil.recieveFile(file, null, storedname);
saveMessage(request, getText("attachment.recieved", locale));
} catch (FileNotFoundException fnfe) {
log.error(fnfe);
key = "attachment.recieveError";
errors.reject(key);
return showForm(request, response, errors);
} catch (IOException ioe) {
log.error(ioe);
key = "errors.ioerror";
errors.reject(key);
return showForm(request, response, errors);
}
attachment.setStoredname(storedname);
attachmentManager.saveAttachment(attachment);
}
// Fetch info about the course
Course course = courseManager.getCourse(courseid);
model.put("course", course);
// Fetch the new file list
AttachmentsBackingObject abo = getAttachmentsBackingObjects(new Long(courseid));
model.put("attachmentsBackingObject", abo);
// Reset the fileUpload-object
fileUpload = new FileUpload();
model.put("fileUpload", fileUpload);
return new ModelAndView(getSuccessView(), model);
}
/**
* Persists the attachment
*
* @param courseid
* The course the attachment is going to be connected to
* @param file
* The file that contains the needed info to create the
* attachment
* @return The persisted attachment
*/
private Attachment saveAttachment(String courseid, CommonsMultipartFile file) {
Attachment attachment = new Attachment();
attachment.setContentType(file.getContentType());
attachment.setFilename(file.getOriginalFilename());
attachment.setCourseId(new Long(courseid));
attachment.setSize(file.getSize());
attachmentManager.saveAttachment(attachment);
return attachment;
}
}
| 10,033 | 0.586764 | 0.585867 | 268 | 35.436565 | 28.045267 | 144 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.615672 | false | false | 13 |
88685df6984805de4ff72952e2d300ea7c97bfc6 | 2,637,109,988,640 | e29a5ed0167ededdc4948c55bc54a04fbff933a7 | /src/com/phoenixkahlo/utils/BinUtils.java | f84c2b91c009c6160d8779feca4768e8f33cd260 | []
| no_license | gretchenfrage/Altitude-Extrapolation | https://github.com/gretchenfrage/Altitude-Extrapolation | 8704c3fa5ac260ff9ad7962be44b4de7581aeb84 | 44113a22185ce7bf20cec9c8fd732d8ab15c51bb | refs/heads/master | 2021-01-10T10:56:50.212000 | 2016-04-27T01:02:48 | 2016-04-27T01:02:48 | 53,713,415 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.phoenixkahlo.utils;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
/*
* Static class for binary operations
*/
public class BinUtils {
private BinUtils() {}
public static byte[] intToBytes(int n) {
return ByteBuffer.allocate(4).putInt(n).array();
}
public static int bytesToInt(byte[] bytes) {
return ByteBuffer.wrap(bytes).getInt();
}
public static void writeInt(OutputStream out, int n) throws IOException {
out.write(intToBytes(n));
}
public static int readInt(InputStream in) throws IOException {
byte[] bytes = new byte[4];
in.read(bytes);
return bytesToInt(bytes);
}
public static byte[] doubleToBytes(double n) {
return ByteBuffer.allocate(8).putDouble(n).array();
}
public static double bytesToDouble(byte[] bytes) {
return ByteBuffer.wrap(bytes).getDouble();
}
public static void writeDouble(OutputStream out, double n) throws IOException {
out.write(doubleToBytes(n));
}
public static double readDouble(InputStream in) throws IOException {
byte[] bytes = new byte[8];
in.read(bytes);
return bytesToDouble(bytes);
}
public static byte[] stringToBytes(String string) {
return string.getBytes(StandardCharsets.UTF_8);
}
public static String bytesToString(byte[] bytes) {
return new String(bytes, StandardCharsets.UTF_8);
}
public static void writeString(OutputStream out, String string) throws IOException {
byte[] bytes = stringToBytes(string);
writeInt(out, bytes.length);
out.write(bytes);
}
public static String readString(InputStream in) throws IOException {
byte[] bytes = new byte[readInt(in)];
in.read(bytes);
return bytesToString(bytes);
}
}
| UTF-8 | Java | 1,788 | java | BinUtils.java | Java | []
| null | []
| package com.phoenixkahlo.utils;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
/*
* Static class for binary operations
*/
public class BinUtils {
private BinUtils() {}
public static byte[] intToBytes(int n) {
return ByteBuffer.allocate(4).putInt(n).array();
}
public static int bytesToInt(byte[] bytes) {
return ByteBuffer.wrap(bytes).getInt();
}
public static void writeInt(OutputStream out, int n) throws IOException {
out.write(intToBytes(n));
}
public static int readInt(InputStream in) throws IOException {
byte[] bytes = new byte[4];
in.read(bytes);
return bytesToInt(bytes);
}
public static byte[] doubleToBytes(double n) {
return ByteBuffer.allocate(8).putDouble(n).array();
}
public static double bytesToDouble(byte[] bytes) {
return ByteBuffer.wrap(bytes).getDouble();
}
public static void writeDouble(OutputStream out, double n) throws IOException {
out.write(doubleToBytes(n));
}
public static double readDouble(InputStream in) throws IOException {
byte[] bytes = new byte[8];
in.read(bytes);
return bytesToDouble(bytes);
}
public static byte[] stringToBytes(String string) {
return string.getBytes(StandardCharsets.UTF_8);
}
public static String bytesToString(byte[] bytes) {
return new String(bytes, StandardCharsets.UTF_8);
}
public static void writeString(OutputStream out, String string) throws IOException {
byte[] bytes = stringToBytes(string);
writeInt(out, bytes.length);
out.write(bytes);
}
public static String readString(InputStream in) throws IOException {
byte[] bytes = new byte[readInt(in)];
in.read(bytes);
return bytesToString(bytes);
}
}
| 1,788 | 0.723154 | 0.719799 | 72 | 23.833334 | 23.332739 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.444444 | false | false | 13 |
deccde79aab0ed6f63141a5f13a316a45f41d973 | 32,152,125,203,541 | 3893176e6b16ddddd5d8e6f244fb5a42674ecd8d | /app/src/main/java/com/zo0okadev/newspulse/ui/fragments/NewsSections.java | 7969676f4712a6fe0caab39f2f44d5d46ec543da | []
| no_license | zo0oka/NewsPulse | https://github.com/zo0oka/NewsPulse | 1f65a2db6d9a633ff12ee95d5bd0418cb073f112 | 3cd3dbb180e366f57092d49e476a46c29db7a4bf | refs/heads/master | 2020-04-30T02:51:40.039000 | 2019-10-10T22:03:17 | 2019-10-10T22:03:17 | 176,571,786 | 5 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zo0okadev.newspulse.ui.fragments;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.zo0okadev.newspulse.R;
import com.zo0okadev.newspulse.model.sections.Section;
import com.zo0okadev.newspulse.ui.AppViewModel;
import com.zo0okadev.newspulse.ui.adapters.SectionsAdapter;
import java.util.List;
public class NewsSections extends Fragment {
public NewsSections() {
}
@SuppressWarnings("ConstantConditions")
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_news_sections, container, false);
TextView subTitle = getActivity().findViewById(R.id.toolbar_sub_header);
subTitle.setText(getString(R.string.news_sections_toolbar_header));
RecyclerView recyclerView = rootView.findViewById(R.id.news_sections_recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(rootView.getContext(), RecyclerView.VERTICAL, false));
final SectionsAdapter sectionsAdapter = new SectionsAdapter(getActivity());
recyclerView.setAdapter(sectionsAdapter);
DividerItemDecoration itemDecoration = new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL);
recyclerView.addItemDecoration(itemDecoration);
AppViewModel appViewModel = ViewModelProviders.of(getActivity()).get(AppViewModel.class);
appViewModel.getAllNewsSections().observe(this, new Observer<List<Section>>() {
@Override
public void onChanged(List<Section> sections) {
sectionsAdapter.setSections(sections);
}
});
return rootView;
}
}
| UTF-8 | Java | 2,230 | java | NewsSections.java | Java | []
| null | []
| package com.zo0okadev.newspulse.ui.fragments;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.zo0okadev.newspulse.R;
import com.zo0okadev.newspulse.model.sections.Section;
import com.zo0okadev.newspulse.ui.AppViewModel;
import com.zo0okadev.newspulse.ui.adapters.SectionsAdapter;
import java.util.List;
public class NewsSections extends Fragment {
public NewsSections() {
}
@SuppressWarnings("ConstantConditions")
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_news_sections, container, false);
TextView subTitle = getActivity().findViewById(R.id.toolbar_sub_header);
subTitle.setText(getString(R.string.news_sections_toolbar_header));
RecyclerView recyclerView = rootView.findViewById(R.id.news_sections_recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(rootView.getContext(), RecyclerView.VERTICAL, false));
final SectionsAdapter sectionsAdapter = new SectionsAdapter(getActivity());
recyclerView.setAdapter(sectionsAdapter);
DividerItemDecoration itemDecoration = new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL);
recyclerView.addItemDecoration(itemDecoration);
AppViewModel appViewModel = ViewModelProviders.of(getActivity()).get(AppViewModel.class);
appViewModel.getAllNewsSections().observe(this, new Observer<List<Section>>() {
@Override
public void onChanged(List<Section> sections) {
sectionsAdapter.setSections(sections);
}
});
return rootView;
}
}
| 2,230 | 0.752018 | 0.749776 | 61 | 35.557377 | 32.477242 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.655738 | false | false | 13 |
054e38c9e414c43dc31f4ff33cf31fa5edefd763 | 16,896,401,382,024 | e2c2b2cafdf036f67079e0d7868571568bbbe399 | /OSCJP/src/com/chris/oscjp/chapter7/AnimalDoctor.java | 57fe5c795102a844aa04fd1d7ff81c5f19e08e83 | []
| no_license | christopher-clark/OSCJ_Programming_Code | https://github.com/christopher-clark/OSCJ_Programming_Code | 60e23ea3d950232b5defe4539340ea33cefe6a53 | e9fe7d7bbfa9a4566eabcd553c9ad650d93c3064 | refs/heads/master | 2016-08-11T16:49:06.958000 | 2016-05-05T11:28:45 | 2016-05-05T11:28:45 | 48,510,276 | 0 | 0 | null | false | 2016-05-05T11:28:45 | 2015-12-23T20:44:16 | 2016-01-29T00:02:18 | 2016-05-05T11:28:45 | 100 | 0 | 0 | 0 | Java | null | null | package com.chris.oscjp.chapter7;
import java.util.*;
public class AnimalDoctor {
// method takes an array of any animal subtype
public void checkAnimals(Animal[] animals) {
for(Animal a : animals) {
a.checkup();
}
}
public static void main(String[] args) {
List<Animal> ani = new ArrayList<Animal>();
ani.add(new Cat()); // OK
ani.add(new Dog()); // OK
// test it
Dog[] dogs = {new Dog(), new Dog()};
Cat[] cats = {new Cat(), new Cat(), new Cat()};
Bird[] birds = {new Bird()};
Animal[] animals = {new Cat(), new Dog(),new Bird(),new Bird(),new Bird(), new Cat(), new Dog(),new Bird()};
Animal[] c = birds;
AnimalDoctor doc = new AnimalDoctor();
doc.checkAnimals(dogs); // pass the Dog[]
doc.checkAnimals(cats); // pass the Cat[]
doc.checkAnimals(birds); // pass the Bird[]
System.out.println();
doc.checkAnimals(animals);
System.out.println();
doc.checkAnimals(c);
Dog mutley = new Dog();
mutley.setName("Mutley");
mutley.setType("Cartoon Dog");
System.out.println(mutley.toString());
if(mutley instanceof Dog)
System.out.println("mutley is a Dog");
if(mutley instanceof Animal)
System.out.println("mutley is an Animal");
}
}
| UTF-8 | Java | 1,218 | java | AnimalDoctor.java | Java | [
{
"context": "s(c);\r\n\tDog mutley = new Dog();\r\n\tmutley.setName(\"Mutley\");\r\n\tmutley.setType(\"Cartoon Dog\");\r\n\tSystem.out.",
"end": 979,
"score": 0.9930979609489441,
"start": 973,
"tag": "NAME",
"value": "Mutley"
}
]
| null | []
| package com.chris.oscjp.chapter7;
import java.util.*;
public class AnimalDoctor {
// method takes an array of any animal subtype
public void checkAnimals(Animal[] animals) {
for(Animal a : animals) {
a.checkup();
}
}
public static void main(String[] args) {
List<Animal> ani = new ArrayList<Animal>();
ani.add(new Cat()); // OK
ani.add(new Dog()); // OK
// test it
Dog[] dogs = {new Dog(), new Dog()};
Cat[] cats = {new Cat(), new Cat(), new Cat()};
Bird[] birds = {new Bird()};
Animal[] animals = {new Cat(), new Dog(),new Bird(),new Bird(),new Bird(), new Cat(), new Dog(),new Bird()};
Animal[] c = birds;
AnimalDoctor doc = new AnimalDoctor();
doc.checkAnimals(dogs); // pass the Dog[]
doc.checkAnimals(cats); // pass the Cat[]
doc.checkAnimals(birds); // pass the Bird[]
System.out.println();
doc.checkAnimals(animals);
System.out.println();
doc.checkAnimals(c);
Dog mutley = new Dog();
mutley.setName("Mutley");
mutley.setType("Cartoon Dog");
System.out.println(mutley.toString());
if(mutley instanceof Dog)
System.out.println("mutley is a Dog");
if(mutley instanceof Animal)
System.out.println("mutley is an Animal");
}
}
| 1,218 | 0.635468 | 0.634647 | 42 | 27 | 19.879398 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.857143 | false | false | 13 |
6204b39b895ce92d9280f9d2bfca35b62c56ac99 | 20,521,353,764,369 | 906bc1a47e24cbd16b3925e941ef32fa5e12bc58 | /parent/service/service_order/src/main/java/com/jk/order/service/impl/OrderServiceImpl.java | 2ee501d2d706cb9a21496635fa6c556fde992228 | []
| no_license | zengyijava/Online_Edu | https://github.com/zengyijava/Online_Edu | e46899f0a0bdcf37b8a111caaddac7b606c2de25 | 016436b6b3f2410129bcb772510f223264c39f45 | refs/heads/master | 2023-01-09T16:09:02.598000 | 2020-11-11T01:20:29 | 2020-11-11T01:20:29 | 289,658,307 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jk.order.service.impl;
import com.jk.commonutils.ordervo.CourseWebVoOrder;
import com.jk.commonutils.ordervo.UcenterMemberOrder;
import com.jk.order.client.EduClient;
import com.jk.order.client.UcenterClient;
import com.jk.order.entity.Order;
import com.jk.order.mapper.OrderMapper;
import com.jk.order.service.OrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jk.order.utils.OrderNoUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* <p>
* 订单 服务实现类
* </p>
*
* @author zy
* @since 2020-06-20
*/
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
@Autowired
private EduClient eudClient;
@Autowired
private UcenterClient ucenterClient;
@Override
public String saveOrder(String courseId, String memberId) {
//根据课程id查询课程信息,sql语句多表查询
CourseWebVoOrder courseInfoOrder = eudClient.getCourseInfoOrder(courseId);
//根据用户id获取用户信息
UcenterMemberOrder userInfoOrder = ucenterClient.getUserInfoOrder(memberId);
//创建Order对象,向order对象里面设置需要数据
Order order = new Order();
order.setOrderNo(OrderNoUtil.getOrderNo());//订单号
order.setCourseId(courseId); //课程id
order.setCourseTitle(courseInfoOrder.getTitle());
order.setCourseCover(courseInfoOrder.getCover());
order.setTeacherName(courseInfoOrder.getTeacherName());
order.setTotalFee(courseInfoOrder.getPrice());
order.setMemberId(memberId);
order.setMobile(userInfoOrder.getMobile());
order.setNickname(userInfoOrder.getNickname());
order.setStatus(0); //订单状态(0:未支付 1:已支付)
order.setPayType(1); //支付类型 ,微信1
baseMapper.insert(order);
//返回订单号
return order.getOrderNo();
}
}
| UTF-8 | Java | 2,040 | java | OrderServiceImpl.java | Java | [
{
"context": "ice;\n\n/**\n * <p>\n * 订单 服务实现类\n * </p>\n *\n * @author zy\n * @since 2020-06-20\n */\n@Service\npublic class Or",
"end": 603,
"score": 0.9995557069778442,
"start": 601,
"tag": "USERNAME",
"value": "zy"
}
]
| null | []
| package com.jk.order.service.impl;
import com.jk.commonutils.ordervo.CourseWebVoOrder;
import com.jk.commonutils.ordervo.UcenterMemberOrder;
import com.jk.order.client.EduClient;
import com.jk.order.client.UcenterClient;
import com.jk.order.entity.Order;
import com.jk.order.mapper.OrderMapper;
import com.jk.order.service.OrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jk.order.utils.OrderNoUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* <p>
* 订单 服务实现类
* </p>
*
* @author zy
* @since 2020-06-20
*/
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
@Autowired
private EduClient eudClient;
@Autowired
private UcenterClient ucenterClient;
@Override
public String saveOrder(String courseId, String memberId) {
//根据课程id查询课程信息,sql语句多表查询
CourseWebVoOrder courseInfoOrder = eudClient.getCourseInfoOrder(courseId);
//根据用户id获取用户信息
UcenterMemberOrder userInfoOrder = ucenterClient.getUserInfoOrder(memberId);
//创建Order对象,向order对象里面设置需要数据
Order order = new Order();
order.setOrderNo(OrderNoUtil.getOrderNo());//订单号
order.setCourseId(courseId); //课程id
order.setCourseTitle(courseInfoOrder.getTitle());
order.setCourseCover(courseInfoOrder.getCover());
order.setTeacherName(courseInfoOrder.getTeacherName());
order.setTotalFee(courseInfoOrder.getPrice());
order.setMemberId(memberId);
order.setMobile(userInfoOrder.getMobile());
order.setNickname(userInfoOrder.getNickname());
order.setStatus(0); //订单状态(0:未支付 1:已支付)
order.setPayType(1); //支付类型 ,微信1
baseMapper.insert(order);
//返回订单号
return order.getOrderNo();
}
}
| 2,040 | 0.72737 | 0.720447 | 53 | 34.433964 | 23.596058 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.603774 | false | false | 13 |
4396eb83d3f62ad50d087c98f3cf96c2c13a0606 | 31,164,282,706,119 | 5214d60a2d7f9092c18e46fca082899c0d5e8a9f | /pm/truco/jogador/JogadorFactory.java | b2f2c618a3f82d5fa335e434b8e25936b0d1564f | []
| no_license | arthur-xavier/pm-tp2 | https://github.com/arthur-xavier/pm-tp2 | 332e2824a0ab2b2703294156d1a5ebcbe444890f | 531fc7ecb29cf964ad8e23eec7d22e674dda620e | refs/heads/master | 2021-01-01T03:47:43.509000 | 2016-05-12T02:25:12 | 2016-05-12T02:25:12 | 58,282,841 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pm.truco.jogador;
public class JogadorFactory {
public static Jogador criarJogador(Jogador.TipoJogador tipo, String nome, int equipe) {
Jogador jogador;
switch(tipo) {
case RANDOMICO:
jogador = new JogadorRandomico();
break;
case HUMANO:
default:
jogador = new JogadorHumano();
break;
}
jogador.setNome(nome);
jogador.setEquipe(equipe);
return jogador;
}
}
| UTF-8 | Java | 446 | java | JogadorFactory.java | Java | []
| null | []
| package pm.truco.jogador;
public class JogadorFactory {
public static Jogador criarJogador(Jogador.TipoJogador tipo, String nome, int equipe) {
Jogador jogador;
switch(tipo) {
case RANDOMICO:
jogador = new JogadorRandomico();
break;
case HUMANO:
default:
jogador = new JogadorHumano();
break;
}
jogador.setNome(nome);
jogador.setEquipe(equipe);
return jogador;
}
}
| 446 | 0.636771 | 0.636771 | 23 | 18.391304 | 19.336245 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.565217 | false | false | 13 |
262a30f3628bad16462928346de9fa0195324b0c | 652,835,092,920 | 4be32b14ea7495c379bc03263529af66d592d169 | /JavaBase/ClassWeek/src/res/유닛.java | fea79128fcf59d5b899d840c8f6b890f83dd1dc1 | []
| no_license | LeeYoungki/TeamNOVA | https://github.com/LeeYoungki/TeamNOVA | 3cfded7ffe5a146253e82416d352b32aee9097c7 | 8ab9b3d270dbcd32d24b8b135a989771f8fb208c | refs/heads/master | 2017-05-12T04:14:29.697000 | 2017-05-11T06:08:38 | 2017-05-11T06:08:38 | 82,804,850 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package res;
public class 유닛 {
private int 공격력;
private int 방어력;
private int 체력;
private int 최대체력;
private int 공격력상승치;
private int 방어력상승치;
private int 체력상승치;
private int 이동속도;
private int 위치;
public synchronized void 이동하기(int 목적지){
this.set위치( 목적지 );
}
public synchronized void 강해지기(){
this.set공격력( this.get공격력() + this.get공격력상승치() );
this.set방어력( this.get방어력() + this.get방어력상승치() );
this.set최대체력( this.get최대체력() + this.get체력상승치() );
this.set체력( this.get최대체력() );
}
public int get공격력() {
return 공격력;
}
public void set공격력(int 공격력) {
this.공격력 = 공격력;
}
public int get방어력() {
return 방어력;
}
public void set방어력(int 방어력) {
this.방어력 = 방어력;
}
public int get체력() {
return 체력;
}
public void set체력(int 체력) {
this.체력 = 체력;
}
public int get최대체력() {
return 최대체력;
}
public void set최대체력(int 최대체력) {
this.최대체력 = 최대체력;
}
public int get공격력상승치() {
return 공격력상승치;
}
public void set공격력상승치(int 공격력상승치) {
this.공격력상승치 = 공격력상승치;
}
public int get방어력상승치() {
return 방어력상승치;
}
public void set방어력상승치(int 방어력상승치) {
this.방어력상승치 = 방어력상승치;
}
public int get체력상승치() {
return 체력상승치;
}
public void set체력상승치(int 체력상승치) {
this.체력상승치 = 체력상승치;
}
public int get이동속도() {
return 이동속도;
}
public void set이동속도(int 이동속도) {
this.이동속도 = 이동속도;
}
public int get위치() {
return 위치;
}
public void set위치(int 위치) {
this.위치 = 위치;
}
}
| UTF-8 | Java | 2,285 | java | 유닛.java | Java | []
| null | []
| package res;
public class 유닛 {
private int 공격력;
private int 방어력;
private int 체력;
private int 최대체력;
private int 공격력상승치;
private int 방어력상승치;
private int 체력상승치;
private int 이동속도;
private int 위치;
public synchronized void 이동하기(int 목적지){
this.set위치( 목적지 );
}
public synchronized void 강해지기(){
this.set공격력( this.get공격력() + this.get공격력상승치() );
this.set방어력( this.get방어력() + this.get방어력상승치() );
this.set최대체력( this.get최대체력() + this.get체력상승치() );
this.set체력( this.get최대체력() );
}
public int get공격력() {
return 공격력;
}
public void set공격력(int 공격력) {
this.공격력 = 공격력;
}
public int get방어력() {
return 방어력;
}
public void set방어력(int 방어력) {
this.방어력 = 방어력;
}
public int get체력() {
return 체력;
}
public void set체력(int 체력) {
this.체력 = 체력;
}
public int get최대체력() {
return 최대체력;
}
public void set최대체력(int 최대체력) {
this.최대체력 = 최대체력;
}
public int get공격력상승치() {
return 공격력상승치;
}
public void set공격력상승치(int 공격력상승치) {
this.공격력상승치 = 공격력상승치;
}
public int get방어력상승치() {
return 방어력상승치;
}
public void set방어력상승치(int 방어력상승치) {
this.방어력상승치 = 방어력상승치;
}
public int get체력상승치() {
return 체력상승치;
}
public void set체력상승치(int 체력상승치) {
this.체력상승치 = 체력상승치;
}
public int get이동속도() {
return 이동속도;
}
public void set이동속도(int 이동속도) {
this.이동속도 = 이동속도;
}
public int get위치() {
return 위치;
}
public void set위치(int 위치) {
this.위치 = 위치;
}
}
| 2,285 | 0.531978 | 0.531978 | 96 | 16.427084 | 14.389482 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.34375 | false | false | 13 |
00d90f6cf77827dc5eb64b982547fed9c75c45ae | 34,230,889,349,600 | 5f35476b3f91cdcb35fae2abac9520dd7f2469b2 | /GridSerenityProcess/src/test/java/com/test/serenitygrid/GridSerenityProcess/steps/GridSerenityProcessSteps.java | a2f7f587b1d3360a565549dcf7724c40987fef86 | []
| no_license | selvavaithi/LearnProgram | https://github.com/selvavaithi/LearnProgram | 00fa868ee58917649f336d08f97e130edefa8302 | 360eb24116744fd33f97bf1881ac8323d2b81467 | refs/heads/master | 2020-12-21T00:23:22.593000 | 2017-05-17T09:02:42 | 2017-05-17T09:02:42 | 57,105,631 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.test.serenitygrid.GridSerenityProcess.steps;
import org.jbehave.core.annotations.Given;
import org.jbehave.core.annotations.Named;
import org.jbehave.core.annotations.Then;
import org.jbehave.core.annotations.When;
import com.test.serenitygrid.GridSerenityProcess.model.GridSerenityProcessStepspages;
import net.thucydides.core.annotations.Steps;
public class GridSerenityProcessSteps {
@Steps
GridSerenityProcessStepspages gridserenityprocesspages;
@Given("I go to PCH website")
public void givenIGoToPCHWebsite() {
gridserenityprocesspages.openPCHurl();
}
@When("I click on the registration button")
public void whenIClickOnTheRegistrationButton() {
gridserenityprocesspages.clickOnRegisterButton();
}
@Then("I should present in registration page")
public void thenIShouldPresentInRegistrationPage() {
gridserenityprocesspages.verifyPageIsRegistration();
}
@Then("I click on the registration submit button")
public void thenIClickOnTheRegistrationSubmitButton() {
gridserenityprocesspages.clickRegisterSubmitBtn();
}
@Then("Verify the registration page validation error message")
public void thenVerifyTheRegistrationPageValidationErrorMessage() {
gridserenityprocesspages.VerifyRegisterPageErrorMessgae();
}
@Then("I enter value for first and last name as $myfirstname and $mylastname respectively")
public void thenIEnterValueForFirstAndLastName(String myfirstname, String mylastname) {
gridserenityprocesspages.EnterFNandLN(myfirstname, mylastname);
}
@Then("Verify the registration page validation error message is withour first and last name")
public void thenVerifyTheRegistrationPageValidationErrorMessageIsWithourFirstAndLastName() {
}
@Then("I search $nearbyplace that are near $place")
public void ThenIsearchnearbyplacethatarenearplaces(@Named("nearbyplace") String nearbyplace,
@Named("place") String place) {
gridserenityprocesspages.Isearchnearbyplacethatarenearplaces(nearbyplace, place);
}
}
| UTF-8 | Java | 1,978 | java | GridSerenityProcessSteps.java | Java | []
| null | []
| package com.test.serenitygrid.GridSerenityProcess.steps;
import org.jbehave.core.annotations.Given;
import org.jbehave.core.annotations.Named;
import org.jbehave.core.annotations.Then;
import org.jbehave.core.annotations.When;
import com.test.serenitygrid.GridSerenityProcess.model.GridSerenityProcessStepspages;
import net.thucydides.core.annotations.Steps;
public class GridSerenityProcessSteps {
@Steps
GridSerenityProcessStepspages gridserenityprocesspages;
@Given("I go to PCH website")
public void givenIGoToPCHWebsite() {
gridserenityprocesspages.openPCHurl();
}
@When("I click on the registration button")
public void whenIClickOnTheRegistrationButton() {
gridserenityprocesspages.clickOnRegisterButton();
}
@Then("I should present in registration page")
public void thenIShouldPresentInRegistrationPage() {
gridserenityprocesspages.verifyPageIsRegistration();
}
@Then("I click on the registration submit button")
public void thenIClickOnTheRegistrationSubmitButton() {
gridserenityprocesspages.clickRegisterSubmitBtn();
}
@Then("Verify the registration page validation error message")
public void thenVerifyTheRegistrationPageValidationErrorMessage() {
gridserenityprocesspages.VerifyRegisterPageErrorMessgae();
}
@Then("I enter value for first and last name as $myfirstname and $mylastname respectively")
public void thenIEnterValueForFirstAndLastName(String myfirstname, String mylastname) {
gridserenityprocesspages.EnterFNandLN(myfirstname, mylastname);
}
@Then("Verify the registration page validation error message is withour first and last name")
public void thenVerifyTheRegistrationPageValidationErrorMessageIsWithourFirstAndLastName() {
}
@Then("I search $nearbyplace that are near $place")
public void ThenIsearchnearbyplacethatarenearplaces(@Named("nearbyplace") String nearbyplace,
@Named("place") String place) {
gridserenityprocesspages.Isearchnearbyplacethatarenearplaces(nearbyplace, place);
}
}
| 1,978 | 0.819515 | 0.819515 | 56 | 34.32143 | 31.346626 | 94 | false | false | 0 | 0 | 0 | 0 | 76 | 0.038423 | 1.107143 | false | false | 13 |
9d6a594f154c2adc289710946d6a8c66660786bf | 37,245,956,415,409 | b2131e97ba9a62b4589a96743e1623b689fdf48e | /JavaFiles/WriteFile.java | 1f34da7102c8fb1548c10dae17eb61fed62d80e7 | []
| no_license | cian-shan/Cs4013-Project2020 | https://github.com/cian-shan/Cs4013-Project2020 | 249719a6ef9b547f751a26bab239aaf5cc3b91a4 | 396dad0b06ddd917a8e41bd3fda7ec87d99f98f9 | refs/heads/main | 2023-02-04T14:07:20.286000 | 2020-12-13T17:36:12 | 2020-12-13T17:36:12 | 321,028,854 | 0 | 0 | null | true | 2020-12-13T09:32:53 | 2020-12-13T09:32:52 | 2020-12-13T00:35:00 | 2020-12-13T03:19:21 | 280 | 0 | 0 | 0 | null | false | false | //author:Jack Boland
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.GregorianCalendar;
/**
* The type Write file.
*/
public class WriteFile{
/**
* Write property.
*
* @param owners the owners
* @param estvalue the estvalue
* @param location the location
* @param PPR the ppr
* @param yearsowned the yearsowned
* @param eircode the eircode
* @param address the address
* @throws FileNotFoundException the file not found exception
*/
public void WriteProperty(String owners,int estvalue, String location,char PPR,String yearsowned,String eircode,String address) throws FileNotFoundException {
String filename = "property.csv";
FileOutputStream fos = new FileOutputStream(filename, true);
PrintWriter pw = new PrintWriter(fos);
pw.println(owners + "," + estvalue+ "," + location+ "," + PPR + "," + yearsowned + "," + eircode + "," + address);
pw.flush();
pw.close();
}
/**
* Write payments.
*
* @param owner the owner
* @param address the address
* @param status the status
* @param taxowed the taxowed
* @param yeardue the yeardue
* @param eircode the eircode
* @param Balance the balance
* @throws FileNotFoundException the file not found exception
*/
public void WritePayments(String owner, String address, char status, double taxowed, String yeardue, String eircode,String Balance) throws FileNotFoundException {
GregorianCalendar date = (GregorianCalendar) GregorianCalendar.getInstance();
String filename = "payments.csv";
FileOutputStream fos = new FileOutputStream(filename, true);
PrintWriter pw = new PrintWriter(fos);
pw.println(owner + "," + address + "," + status + "," + taxowed + "," + yeardue + "," + eircode);
pw.flush();
pw.close();
}
} | UTF-8 | Java | 1,920 | java | WriteFile.java | Java | [
{
"context": "//author:Jack Boland\r\nimport java.io.FileNotFoundException;\r\nimport ja",
"end": 20,
"score": 0.9998769164085388,
"start": 9,
"tag": "NAME",
"value": "Jack Boland"
}
]
| null | []
| //author:<NAME>
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.GregorianCalendar;
/**
* The type Write file.
*/
public class WriteFile{
/**
* Write property.
*
* @param owners the owners
* @param estvalue the estvalue
* @param location the location
* @param PPR the ppr
* @param yearsowned the yearsowned
* @param eircode the eircode
* @param address the address
* @throws FileNotFoundException the file not found exception
*/
public void WriteProperty(String owners,int estvalue, String location,char PPR,String yearsowned,String eircode,String address) throws FileNotFoundException {
String filename = "property.csv";
FileOutputStream fos = new FileOutputStream(filename, true);
PrintWriter pw = new PrintWriter(fos);
pw.println(owners + "," + estvalue+ "," + location+ "," + PPR + "," + yearsowned + "," + eircode + "," + address);
pw.flush();
pw.close();
}
/**
* Write payments.
*
* @param owner the owner
* @param address the address
* @param status the status
* @param taxowed the taxowed
* @param yeardue the yeardue
* @param eircode the eircode
* @param Balance the balance
* @throws FileNotFoundException the file not found exception
*/
public void WritePayments(String owner, String address, char status, double taxowed, String yeardue, String eircode,String Balance) throws FileNotFoundException {
GregorianCalendar date = (GregorianCalendar) GregorianCalendar.getInstance();
String filename = "payments.csv";
FileOutputStream fos = new FileOutputStream(filename, true);
PrintWriter pw = new PrintWriter(fos);
pw.println(owner + "," + address + "," + status + "," + taxowed + "," + yeardue + "," + eircode);
pw.flush();
pw.close();
}
} | 1,915 | 0.666146 | 0.666146 | 62 | 29 | 34.188755 | 163 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.403226 | false | false | 13 |
033064e18f382e8f363a611699adf81821d77da8 | 35,502,199,702,075 | ffe1179c5e528ccd86530d0ad693db16911725e7 | /Nagarro_Qps_2/K_Unique_Character_Substrings.java | 8fe5c0164eac4dafee8056e1f611e3ac205ee193 | []
| no_license | monukumar98/Nagaaro_BootCamp | https://github.com/monukumar98/Nagaaro_BootCamp | cfdb547882c7f6dd8efdcf4446927fa0c1a0f893 | 4f68b3c96d97e7023efaec3119fe363a888c320c | refs/heads/master | 2023-07-13T18:22:38.073000 | 2021-08-31T13:06:03 | 2021-08-31T13:06:03 | 351,819,377 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Nagarro_Qps_2;
import java.util.Scanner;
public class K_Unique_Character_Substrings {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t>0) {
int n = sc.nextInt();
int arr[] = new int [n];
for (int i = 0; i < arr.length; i++) {
arr[i]=sc.nextInt();
}
for (int pass = 1; pass <n; pass++) {
for (int i = 0; i <=n-pass-1; i++) {
// sawp
if(isPossible(arr[i],arr[i+1])) {
int temp = arr[i];
arr[i]=arr[i+1];
arr[i+1]=temp;
}
}
}
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]);
}
System.out.println();
t--;
}
}
// 98 9
public static boolean isPossible(int n1, int n2) {
// TODO Auto-generated method stub
String s1= ""+n1;
String s2= ""+n2;
long n1n2=Long.parseLong(s1+s2);// 989
long n2n1=Long.parseLong(s2+s1);// 998
if(n2n1>n1n2) {
return true;
}
return false;
}
}
| UTF-8 | Java | 1,017 | java | K_Unique_Character_Substrings.java | Java | []
| null | []
| package Nagarro_Qps_2;
import java.util.Scanner;
public class K_Unique_Character_Substrings {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t>0) {
int n = sc.nextInt();
int arr[] = new int [n];
for (int i = 0; i < arr.length; i++) {
arr[i]=sc.nextInt();
}
for (int pass = 1; pass <n; pass++) {
for (int i = 0; i <=n-pass-1; i++) {
// sawp
if(isPossible(arr[i],arr[i+1])) {
int temp = arr[i];
arr[i]=arr[i+1];
arr[i+1]=temp;
}
}
}
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]);
}
System.out.println();
t--;
}
}
// 98 9
public static boolean isPossible(int n1, int n2) {
// TODO Auto-generated method stub
String s1= ""+n1;
String s2= ""+n2;
long n1n2=Long.parseLong(s1+s2);// 989
long n2n1=Long.parseLong(s2+s1);// 998
if(n2n1>n1n2) {
return true;
}
return false;
}
}
| 1,017 | 0.548673 | 0.512291 | 52 | 18.557692 | 15.283744 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3 | false | false | 13 |
e71fe7018ae30a067e6b8c2bb10a12713360ff81 | 38,946,763,464,096 | 17bb5a7f82e1284064de6aa3f1e3ab6603f9906f | /dubbo-api/src/main/java/com/wkl/api/OrderService.java | f454d5e9c14999d79f46cfabd204ffa887880ad4 | []
| no_license | wangkljya/A-Simple-Distributed-Demo | https://github.com/wangkljya/A-Simple-Distributed-Demo | 6f2c942ed5961062efb9f07279962e87c93c2fab | 22753f95d0f017287dc03547162f88ba194243e5 | refs/heads/master | 2021-04-15T15:38:26.070000 | 2018-03-23T15:48:50 | 2018-03-23T15:48:50 | 126,499,131 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.wkl.api;
import com.wkl.object.GoodOrder;
public interface OrderService {
public boolean OrderAdd(GoodOrder goodOrder);
}
| UTF-8 | Java | 137 | java | OrderService.java | Java | []
| null | []
| package com.wkl.api;
import com.wkl.object.GoodOrder;
public interface OrderService {
public boolean OrderAdd(GoodOrder goodOrder);
}
| 137 | 0.79562 | 0.79562 | 7 | 18.571428 | 17.269768 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 13 |
d73436b94b1721a3fc72b710541755e6dcd382f5 | 39,530,879,015,095 | dc9493b66d278b542b514bdc299feeb51bccb104 | /src/prop/assignment0/StatementsNode.java | 2507beab407504f464fa94a117656ca18997d4b2 | []
| no_license | jepl4052/prop | https://github.com/jepl4052/prop | 47bd6a124be98da6b3eb9759dde977c570c0a0b3 | d5ce7138de755bc64affaf7dca8a8115be09f963 | refs/heads/master | 2020-04-07T08:27:21.661000 | 2018-11-21T15:58:15 | 2018-11-21T15:58:15 | 158,214,788 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* @authors:
* jens plate, jepl4052
* erik hörnström, erho7892
* marcus posette, mapo8904
*/
package prop.assignment0;
public class StatementsNode implements INode {
//stmts = [ assign , stmts ] ;
private INode child1, child2;
@Override
public Object evaluate(Object[] args) throws Exception {
return (this.child1 != null) ? this.child1.evaluate(args).toString() + this.child2.evaluate(args).toString() : "";
}
@Override
public void buildString(StringBuilder builder, int tabs) {
Tabber.append(builder, tabs);
builder.append("StatementsNode\n");
tabs++;
if(this.child1 != null) {
this.child1.buildString(builder, tabs);
}
if(this.child2 != null) {
this.child2.buildString(builder, tabs);
}
}
public void addStatement(INode stmt) {
if(this.child1 == null) {
this.child1 = stmt;
} else if (child2 == null) {
this.child2 = stmt;
}
}
}
| UTF-8 | Java | 1,029 | java | StatementsNode.java | Java | [
{
"context": "/**\n * @authors:\n * jens plate, jepl4052\n * erik hörnström, erho7892\n * marcus p",
"end": 30,
"score": 0.9998518824577332,
"start": 20,
"tag": "NAME",
"value": "jens plate"
},
{
"context": "/**\n * @authors:\n * jens plate, jepl4052\n * erik hörnström, erho7892\n * marcus posette, ma",
"end": 40,
"score": 0.9996278285980225,
"start": 32,
"tag": "USERNAME",
"value": "jepl4052"
},
{
"context": "/**\n * @authors:\n * jens plate, jepl4052\n * erik hörnström, erho7892\n * marcus posette, mapo8904\n */\n\npackag",
"end": 58,
"score": 0.9998682737350464,
"start": 44,
"tag": "NAME",
"value": "erik hörnström"
},
{
"context": "uthors:\n * jens plate, jepl4052\n * erik hörnström, erho7892\n * marcus posette, mapo8904\n */\n\npackage prop.ass",
"end": 68,
"score": 0.9996338486671448,
"start": 60,
"tag": "USERNAME",
"value": "erho7892"
},
{
"context": "ens plate, jepl4052\n * erik hörnström, erho7892\n * marcus posette, mapo8904\n */\n\npackage prop.assignment0;\n\npublic ",
"end": 86,
"score": 0.9998646974563599,
"start": 72,
"tag": "NAME",
"value": "marcus posette"
},
{
"context": "052\n * erik hörnström, erho7892\n * marcus posette, mapo8904\n */\n\npackage prop.assignment0;\n\npublic class Stat",
"end": 96,
"score": 0.9995031356811523,
"start": 88,
"tag": "USERNAME",
"value": "mapo8904"
}
]
| null | []
| /**
* @authors:
* <NAME>, jepl4052
* <NAME>, erho7892
* <NAME>, mapo8904
*/
package prop.assignment0;
public class StatementsNode implements INode {
//stmts = [ assign , stmts ] ;
private INode child1, child2;
@Override
public Object evaluate(Object[] args) throws Exception {
return (this.child1 != null) ? this.child1.evaluate(args).toString() + this.child2.evaluate(args).toString() : "";
}
@Override
public void buildString(StringBuilder builder, int tabs) {
Tabber.append(builder, tabs);
builder.append("StatementsNode\n");
tabs++;
if(this.child1 != null) {
this.child1.buildString(builder, tabs);
}
if(this.child2 != null) {
this.child2.buildString(builder, tabs);
}
}
public void addStatement(INode stmt) {
if(this.child1 == null) {
this.child1 = stmt;
} else if (child2 == null) {
this.child2 = stmt;
}
}
}
| 1,007 | 0.583252 | 0.557936 | 45 | 21.822222 | 23.844206 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.444444 | false | false | 13 |
af3fdece9252ae6b5895f56c8f4b6e639f298e8a | 37,632,503,466,198 | 977cfd3ef881d6250a65bb13f9f04ff2289dd719 | /src/hom2/gamelogic/CmdNav.java | 1964e0c9f62e7faef121bea51acbd755c573c638 | []
| no_license | HOM2/HOM2 | https://github.com/HOM2/HOM2 | 8d1e682a88bc44d94f687398af5cfb2edebbc4ed | 6c0f433d954cf68cc0d97b74cc8487855a4f0fae | refs/heads/master | 2021-01-23T08:11:19.795000 | 2015-04-13T08:35:32 | 2015-04-13T08:35:32 | 33,463,657 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright Yiqi Liu
*
*/
package hom2.gamelogic;
/**
*
* @author Alex
*/
public abstract class CmdNav implements CmdGame{
protected GameController gameController;
}
| UTF-8 | Java | 194 | java | CmdNav.java | Java | [
{
"context": "/*\r\n * Copyright Yiqi Liu\r\n * \r\n */\r\npackage hom2.gamelogic;\r\n\r\n/**\r\n *\r\n *",
"end": 25,
"score": 0.9997731447219849,
"start": 17,
"tag": "NAME",
"value": "Yiqi Liu"
},
{
"context": "*/\r\npackage hom2.gamelogic;\r\n\r\n/**\r\n *\r\n * @author Alex\r\n */\r\npublic abstract class CmdNav implements Cmd",
"end": 88,
"score": 0.9998058080673218,
"start": 84,
"tag": "NAME",
"value": "Alex"
}
]
| null | []
| /*
* Copyright <NAME>
*
*/
package hom2.gamelogic;
/**
*
* @author Alex
*/
public abstract class CmdNav implements CmdGame{
protected GameController gameController;
}
| 192 | 0.64433 | 0.639175 | 13 | 12.923077 | 15.954076 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.153846 | false | false | 13 |
9388a36075801d7426ef658cb6feb1ba71a66883 | 30,253,749,683,588 | 708d7398b27efa2c2320704742a4f22ec73d031f | /src/main/java/com/community/codeeditor/controller/JavaController.java | 4d760cb3043e2b3515a1a6825fa57334f58e38bd | []
| no_license | lzjlzj10086/Community | https://github.com/lzjlzj10086/Community | 36b27257e855183a943b3ea94d7c814cd6b28d38 | c4328f24c7eb4ecb2313a3510024dfed47ca888c | refs/heads/master | 2023-04-18T12:07:43.600000 | 2021-05-05T09:20:15 | 2021-05-05T09:20:15 | 299,913,876 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.community.codeeditor.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class JavaController {
@RequestMapping("javaExecute")
public String javaExecute(){
return "javaIndex";
}
}
| UTF-8 | Java | 307 | java | JavaController.java | Java | []
| null | []
| package com.community.codeeditor.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class JavaController {
@RequestMapping("javaExecute")
public String javaExecute(){
return "javaIndex";
}
}
| 307 | 0.76873 | 0.76873 | 13 | 22.615385 | 20.435785 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.307692 | false | false | 5 |
42f3e04ca139cdd5d929df9fa931ef78e833508d | 32,049,045,991,936 | 28eba19c519ad0a1ac6c3022cc25022bb2b734a3 | /A2Prj/src/com/mycompany/a2/IGameWorld.java | 6e0b2596f2480698937272b05e12db6c68887a84 | []
| no_license | DanielPCurtis/CSC133Asteroids | https://github.com/DanielPCurtis/CSC133Asteroids | 1a8d1132e06280e00b25d32117cf6cf4b2bfb251 | efed46e5708464bbbd4ecc247da0b4d3c359b3dd | refs/heads/master | 2022-09-18T04:51:27.767000 | 2020-05-28T13:02:41 | 2020-05-28T13:02:41 | 267,054,547 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mycompany.a2;
public interface IGameWorld {
public int getPlayerScore();
public int getMissileCount();
public IIterator getIterator();
public int getElapsedTime();
public boolean getSoundToggle();
public String getSound();
public int getLivesRemaining();
}
| UTF-8 | Java | 288 | java | IGameWorld.java | Java | []
| null | []
| package com.mycompany.a2;
public interface IGameWorld {
public int getPlayerScore();
public int getMissileCount();
public IIterator getIterator();
public int getElapsedTime();
public boolean getSoundToggle();
public String getSound();
public int getLivesRemaining();
}
| 288 | 0.746528 | 0.743056 | 11 | 24.181818 | 11.400305 | 33 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.363636 | false | false | 5 |
64919bef0be3f9afb6ab9269ed9102c0adba0dca | 2,808,908,668,313 | 22a203909379ecc230670fec40a345036c1a2a9f | /Java/java mockito/src/main/java/br/com/alura/leilao/dao/PagamentoDao.java | 31827d5c5a2885455fb10318796488f9d963053d | []
| no_license | fernandosiillva/projetos | https://github.com/fernandosiillva/projetos | faced070945dff7160fe365f583086e320967d95 | 9c3dc142d875e6b3a1f06ee7e5a5dcbd43ab4628 | refs/heads/master | 2021-12-15T08:25:21.662000 | 2021-12-15T00:40:11 | 2021-12-15T00:40:11 | 222,556,237 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.alura.leilao.dao;
import javax.persistence.EntityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import br.com.alura.leilao.model.Pagamento;
@Repository
public class PagamentoDao {
private EntityManager em;
@Autowired
public PagamentoDao(EntityManager em) {
this.em = em;
}
public void salvar(Pagamento pagamento) {
em.persist(pagamento);
}
}
| UTF-8 | Java | 450 | java | PagamentoDao.java | Java | []
| null | []
| package br.com.alura.leilao.dao;
import javax.persistence.EntityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import br.com.alura.leilao.model.Pagamento;
@Repository
public class PagamentoDao {
private EntityManager em;
@Autowired
public PagamentoDao(EntityManager em) {
this.em = em;
}
public void salvar(Pagamento pagamento) {
em.persist(pagamento);
}
}
| 450 | 0.784444 | 0.784444 | 24 | 17.75 | 19.255411 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false | 5 |
232a18ce8add0754531b3a83d69e4818e73b6e66 | 29,188,597,769,409 | c75da55efe2db27c3b5405654f1a77f18b4f21fb | /src/main/java/com/zhb/javaSE/others/toObj/duotai/Eagle.java | e485b4e7ba9689ca9d5409a545be7f031fd746d9 | []
| no_license | Rainboz/StudyJava | https://github.com/Rainboz/StudyJava | 16c525404f6b5b68ed7b67907f6b003e38802748 | 246dd053e0bb39a5ca214c37763f3e909e531a4f | refs/heads/master | 2022-07-10T18:33:43.814000 | 2019-08-28T10:50:20 | 2019-08-28T10:50:20 | 145,509,535 | 0 | 0 | null | false | 2022-07-01T17:42:06 | 2018-08-21T05:09:53 | 2019-08-28T10:50:46 | 2022-07-01T17:42:05 | 1,446 | 0 | 0 | 6 | JavaScript | false | false | package com.zhb.javaSE.toObj.duotai;
public class Eagle extends Animal{
protected void eat(){
System.out.println("Eagle子类");
}
}
| UTF-8 | Java | 154 | java | Eagle.java | Java | []
| null | []
| package com.zhb.javaSE.toObj.duotai;
public class Eagle extends Animal{
protected void eat(){
System.out.println("Eagle子类");
}
}
| 154 | 0.653333 | 0.653333 | 7 | 20.428572 | 16.114388 | 39 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 5 |
7ee9bdbc13d861d7baa0e74f9abd3a78d91634e5 | 25,795,573,619,793 | 06788f48f6961842ec796ef6df8f68a0de877b7a | /src/vista/PanelElegirNivel.java | 54ca759d20537e3b2feb58506fc1ac5ecde27f7b | []
| no_license | juanantoniot10/Tetris-desktop-Java-Multiplayer | https://github.com/juanantoniot10/Tetris-desktop-Java-Multiplayer | ca754449058ccd0b920d21ad911f7197a08686f0 | 5c4837763a3117a94af3dd475651ca3a7fa61459 | refs/heads/master | 2020-03-24T20:50:29.295000 | 2018-08-03T21:56:53 | 2018-08-03T21:56:53 | 142,773,218 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package vista;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.Font;
import javax.swing.SwingConstants;
import java.awt.Insets;
import java.awt.Dimension;
import javax.swing.BoxLayout;
import java.awt.Color;
public class PanelElegirNivel extends JPanel{
/**
*
*/
private static final long serialVersionUID = 1L;
private JButton nivel1;
private JButton nivel2;
private JButton nivel3;
private JButton nivel4;
private JButton nivel5;
private JButton nivel6;
private JButton nivel7;
private JButton nivel8;
private JButton nivel9;
public PanelElegirNivel() {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
nivel1 = new JButton("nivel 1");
nivel1.setForeground(Color.LIGHT_GRAY);
nivel1.setBackground(new Color(0, 51, 0));
nivel1.setName("1");
nivel1.setMinimumSize(new Dimension(43, 23));
nivel1.setMaximumSize(new Dimension(2220, 400));
nivel1.setMargin(new Insets(20, 20, 20, 20));
nivel1.setHorizontalTextPosition(SwingConstants.LEADING);
nivel1.setFont(new Font("Pristina", Font.BOLD, 25));
add(nivel1);
nivel2 = new JButton("nivel 2");
nivel2.setForeground(Color.LIGHT_GRAY);
nivel2.setBackground(new Color(0, 102, 0));
nivel2.setName("2");
nivel2.setMinimumSize(new Dimension(43, 23));
nivel2.setMaximumSize(new Dimension(2220, 400));
nivel2.setMargin(new Insets(20, 20, 20, 20));
nivel2.setHorizontalTextPosition(SwingConstants.LEADING);
nivel2.setFont(new Font("Pristina", Font.BOLD, 25));
add(nivel2);
nivel3 = new JButton("nivel 3");
nivel3.setForeground(Color.LIGHT_GRAY);
nivel3.setBackground(new Color(102, 153, 0));
nivel3.setName("3");
nivel3.setMinimumSize(new Dimension(43, 23));
nivel3.setMaximumSize(new Dimension(2220, 400));
nivel3.setMargin(new Insets(20, 20, 20, 20));
nivel3.setHorizontalTextPosition(SwingConstants.LEADING);
nivel3.setFont(new Font("Pristina", Font.BOLD, 25));
add(nivel3);
nivel4 = new JButton("nivel 4");
nivel4.setForeground(Color.LIGHT_GRAY);
nivel4.setBackground(new Color(102, 102, 0));
nivel4.setName("4");
nivel4.setMinimumSize(new Dimension(43, 23));
nivel4.setMaximumSize(new Dimension(2220, 400));
nivel4.setMargin(new Insets(20, 20, 20, 20));
nivel4.setHorizontalTextPosition(SwingConstants.LEADING);
nivel4.setFont(new Font("Pristina", Font.BOLD, 25));
add(nivel4);
nivel5 = new JButton("nivel 5");
nivel5.setForeground(Color.LIGHT_GRAY);
nivel5.setBackground(new Color(255, 153, 51));
nivel5.setName("5");
nivel5.setMinimumSize(new Dimension(43, 23));
nivel5.setMaximumSize(new Dimension(2220, 400));
nivel5.setMargin(new Insets(20, 20, 20, 20));
nivel5.setHorizontalTextPosition(SwingConstants.LEADING);
nivel5.setFont(new Font("Pristina", Font.BOLD, 25));
add(nivel5);
nivel6 = new JButton("nivel 6");
nivel6.setForeground(Color.LIGHT_GRAY);
nivel6.setBackground(new Color(204, 102, 0));
nivel6.setName("6");
nivel6.setMinimumSize(new Dimension(43, 23));
nivel6.setMaximumSize(new Dimension(2220, 400));
nivel6.setMargin(new Insets(20, 20, 20, 20));
nivel6.setHorizontalTextPosition(SwingConstants.LEADING);
nivel6.setFont(new Font("Pristina", Font.BOLD, 24));
add(nivel6);
nivel7 = new JButton("nivel 7");
nivel7.setForeground(Color.LIGHT_GRAY);
nivel7.setBackground(new Color(255, 102, 51));
nivel7.setName("7");
nivel7.setMinimumSize(new Dimension(43, 23));
nivel7.setMaximumSize(new Dimension(2220, 400));
nivel7.setMargin(new Insets(20, 20, 20, 20));
nivel7.setHorizontalTextPosition(SwingConstants.LEADING);
nivel7.setFont(new Font("Pristina", Font.BOLD, 25));
add(nivel7);
nivel8 = new JButton("nivel 8");
nivel8.setForeground(Color.LIGHT_GRAY);
nivel8.setBackground(new Color(204, 51, 51));
nivel8.setName("8");
nivel8.setMinimumSize(new Dimension(43, 23));
nivel8.setMaximumSize(new Dimension(2220, 400));
nivel8.setMargin(new Insets(20, 20, 20, 20));
nivel8.setHorizontalTextPosition(SwingConstants.LEADING);
nivel8.setFont(new Font("Pristina", Font.BOLD, 25));
add(nivel8);
nivel9 = new JButton("nivel 9");
nivel9.setForeground(Color.LIGHT_GRAY);
nivel9.setBackground(new Color(204, 0, 0));
nivel9.setName("9");
nivel9.setMinimumSize(new Dimension(43, 23));
nivel9.setMaximumSize(new Dimension(2220, 400));
nivel9.setMargin(new Insets(20, 20, 20, 20));
nivel9.setHorizontalTextPosition(SwingConstants.LEADING);
nivel9.setFont(new Font("Pristina", Font.BOLD, 24));
add(nivel9);
}
}
| UTF-8 | Java | 4,503 | java | PanelElegirNivel.java | Java | []
| null | []
| package vista;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.Font;
import javax.swing.SwingConstants;
import java.awt.Insets;
import java.awt.Dimension;
import javax.swing.BoxLayout;
import java.awt.Color;
public class PanelElegirNivel extends JPanel{
/**
*
*/
private static final long serialVersionUID = 1L;
private JButton nivel1;
private JButton nivel2;
private JButton nivel3;
private JButton nivel4;
private JButton nivel5;
private JButton nivel6;
private JButton nivel7;
private JButton nivel8;
private JButton nivel9;
public PanelElegirNivel() {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
nivel1 = new JButton("nivel 1");
nivel1.setForeground(Color.LIGHT_GRAY);
nivel1.setBackground(new Color(0, 51, 0));
nivel1.setName("1");
nivel1.setMinimumSize(new Dimension(43, 23));
nivel1.setMaximumSize(new Dimension(2220, 400));
nivel1.setMargin(new Insets(20, 20, 20, 20));
nivel1.setHorizontalTextPosition(SwingConstants.LEADING);
nivel1.setFont(new Font("Pristina", Font.BOLD, 25));
add(nivel1);
nivel2 = new JButton("nivel 2");
nivel2.setForeground(Color.LIGHT_GRAY);
nivel2.setBackground(new Color(0, 102, 0));
nivel2.setName("2");
nivel2.setMinimumSize(new Dimension(43, 23));
nivel2.setMaximumSize(new Dimension(2220, 400));
nivel2.setMargin(new Insets(20, 20, 20, 20));
nivel2.setHorizontalTextPosition(SwingConstants.LEADING);
nivel2.setFont(new Font("Pristina", Font.BOLD, 25));
add(nivel2);
nivel3 = new JButton("nivel 3");
nivel3.setForeground(Color.LIGHT_GRAY);
nivel3.setBackground(new Color(102, 153, 0));
nivel3.setName("3");
nivel3.setMinimumSize(new Dimension(43, 23));
nivel3.setMaximumSize(new Dimension(2220, 400));
nivel3.setMargin(new Insets(20, 20, 20, 20));
nivel3.setHorizontalTextPosition(SwingConstants.LEADING);
nivel3.setFont(new Font("Pristina", Font.BOLD, 25));
add(nivel3);
nivel4 = new JButton("nivel 4");
nivel4.setForeground(Color.LIGHT_GRAY);
nivel4.setBackground(new Color(102, 102, 0));
nivel4.setName("4");
nivel4.setMinimumSize(new Dimension(43, 23));
nivel4.setMaximumSize(new Dimension(2220, 400));
nivel4.setMargin(new Insets(20, 20, 20, 20));
nivel4.setHorizontalTextPosition(SwingConstants.LEADING);
nivel4.setFont(new Font("Pristina", Font.BOLD, 25));
add(nivel4);
nivel5 = new JButton("nivel 5");
nivel5.setForeground(Color.LIGHT_GRAY);
nivel5.setBackground(new Color(255, 153, 51));
nivel5.setName("5");
nivel5.setMinimumSize(new Dimension(43, 23));
nivel5.setMaximumSize(new Dimension(2220, 400));
nivel5.setMargin(new Insets(20, 20, 20, 20));
nivel5.setHorizontalTextPosition(SwingConstants.LEADING);
nivel5.setFont(new Font("Pristina", Font.BOLD, 25));
add(nivel5);
nivel6 = new JButton("nivel 6");
nivel6.setForeground(Color.LIGHT_GRAY);
nivel6.setBackground(new Color(204, 102, 0));
nivel6.setName("6");
nivel6.setMinimumSize(new Dimension(43, 23));
nivel6.setMaximumSize(new Dimension(2220, 400));
nivel6.setMargin(new Insets(20, 20, 20, 20));
nivel6.setHorizontalTextPosition(SwingConstants.LEADING);
nivel6.setFont(new Font("Pristina", Font.BOLD, 24));
add(nivel6);
nivel7 = new JButton("nivel 7");
nivel7.setForeground(Color.LIGHT_GRAY);
nivel7.setBackground(new Color(255, 102, 51));
nivel7.setName("7");
nivel7.setMinimumSize(new Dimension(43, 23));
nivel7.setMaximumSize(new Dimension(2220, 400));
nivel7.setMargin(new Insets(20, 20, 20, 20));
nivel7.setHorizontalTextPosition(SwingConstants.LEADING);
nivel7.setFont(new Font("Pristina", Font.BOLD, 25));
add(nivel7);
nivel8 = new JButton("nivel 8");
nivel8.setForeground(Color.LIGHT_GRAY);
nivel8.setBackground(new Color(204, 51, 51));
nivel8.setName("8");
nivel8.setMinimumSize(new Dimension(43, 23));
nivel8.setMaximumSize(new Dimension(2220, 400));
nivel8.setMargin(new Insets(20, 20, 20, 20));
nivel8.setHorizontalTextPosition(SwingConstants.LEADING);
nivel8.setFont(new Font("Pristina", Font.BOLD, 25));
add(nivel8);
nivel9 = new JButton("nivel 9");
nivel9.setForeground(Color.LIGHT_GRAY);
nivel9.setBackground(new Color(204, 0, 0));
nivel9.setName("9");
nivel9.setMinimumSize(new Dimension(43, 23));
nivel9.setMaximumSize(new Dimension(2220, 400));
nivel9.setMargin(new Insets(20, 20, 20, 20));
nivel9.setHorizontalTextPosition(SwingConstants.LEADING);
nivel9.setFont(new Font("Pristina", Font.BOLD, 24));
add(nivel9);
}
}
| 4,503 | 0.729514 | 0.648457 | 129 | 33.906979 | 17.918612 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.155039 | false | false | 5 |
670f38fef59a958a3249fce2503bba7e500f024e | 34,385,508,184,502 | ea513bf993aff40cddff7db006680f244cc28b87 | /app/src/main/java/com/users/adapter/UsersAdapter.java | 33fd3ff7d379a57771e470663e2121dac34ecf60 | []
| no_license | jats2k9/Simple-Android-App | https://github.com/jats2k9/Simple-Android-App | 0f9630ae5a3a219f18c34eb3bbfb25305abe6a28 | 331b071caa02c3756277082585a4eb55b65e8316 | refs/heads/master | 2020-07-09T02:05:25.489000 | 2019-08-23T00:56:48 | 2019-08-23T00:56:48 | 203,844,987 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.users.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.users.R;
import com.users.model.User;
import java.util.List;
public class UsersAdapter extends RecyclerView.Adapter<UsersAdapter.UserViewHolder> {
private List<User> usersData;
private Context context;
public UsersAdapter(List<User> usersData, Context context) {
this.usersData = usersData;
this.context = context;
}
@NonNull
@Override
public UserViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.user_cardview, parent, false);
return new UserViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull UserViewHolder holder, int position) {
holder.bindData(usersData.get(position));
}
@Override
public int getItemCount() {
return usersData.size();
}
static class UserViewHolder extends RecyclerView.ViewHolder {
TextView userName;
ImageView user_image;
public UserViewHolder(View viewItem) {
super(viewItem);
userName = viewItem.findViewById(R.id.user_name);
user_image = viewItem.findViewById(R.id.user_image);
}
public void bindData(User user) {
userName.setText(user.getUserName());
user_image.setImageBitmap(user.getUserImg());
}
}
}
| UTF-8 | Java | 1,679 | java | UsersAdapter.java | Java | []
| null | []
| package com.users.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.users.R;
import com.users.model.User;
import java.util.List;
public class UsersAdapter extends RecyclerView.Adapter<UsersAdapter.UserViewHolder> {
private List<User> usersData;
private Context context;
public UsersAdapter(List<User> usersData, Context context) {
this.usersData = usersData;
this.context = context;
}
@NonNull
@Override
public UserViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.user_cardview, parent, false);
return new UserViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull UserViewHolder holder, int position) {
holder.bindData(usersData.get(position));
}
@Override
public int getItemCount() {
return usersData.size();
}
static class UserViewHolder extends RecyclerView.ViewHolder {
TextView userName;
ImageView user_image;
public UserViewHolder(View viewItem) {
super(viewItem);
userName = viewItem.findViewById(R.id.user_name);
user_image = viewItem.findViewById(R.id.user_image);
}
public void bindData(User user) {
userName.setText(user.getUserName());
user_image.setImageBitmap(user.getUserImg());
}
}
}
| 1,679 | 0.693865 | 0.693865 | 64 | 25.234375 | 25.047918 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 5 |
cd5dbdbcb6430ae3e59f371ee44d3675a49a0a3c | 34,385,508,186,410 | 4e7d789ad0475faaa4f2d19d0bf24ffd607f7661 | /src/main/java/chapter9/Task15.java | 0f41d8498ea6a761db15f83fb47ff677870f1501 | []
| no_license | sHiniz0r/java8book | https://github.com/sHiniz0r/java8book | 5d5eedb1b84436fe0a4851c430695e85ec4af992 | 4c7b1631f44888c9017f884ccde61bd435e59d3d | refs/heads/master | 2020-04-26T00:24:38.891000 | 2019-04-03T17:06:23 | 2019-04-03T17:06:23 | 173,176,995 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package chapter9;
import java.io.*;
import java.util.Arrays;
public class Task15 {
private static final String FILE_PATH = "src/main/resources/array_serialize2";
public static void main(String[] args) throws IOException, ClassNotFoundException {
Point[] points = new Point[] {new Point(1,2), new Point(3,4)};
serialize(points);
Point[] points1 = deserialize();
Arrays.stream(points1).forEach(System.out::println);
}
private static void serialize(Point[] array) throws IOException {
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(FILE_PATH));
objectOutputStream.writeObject(array);
objectOutputStream.close();
}
private static Point[] deserialize() throws IOException, ClassNotFoundException {
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(FILE_PATH));
Object deserialized = objectInputStream.readObject();
objectInputStream.close();
return (Point[]) deserialized;
}
private static class Point implements Serializable {
private static final long serialVersionUID = 2;
private int[] arr = new int[2];
Point(int x, int y) {
this.arr[0] = x;
this.arr[1] = y;
}
int getX() {
return arr[0];
}
void setX(int x) {
this.arr[0] = x;
}
int getY() {
return arr[1];
}
void setY(int y) {
this.arr[1] = y;
}
@Override
public String toString() {
return "Point{" +
"x=" + arr[0] +
", y=" + arr[1] +
'}';
}
}
}
| UTF-8 | Java | 1,771 | java | Task15.java | Java | []
| null | []
| package chapter9;
import java.io.*;
import java.util.Arrays;
public class Task15 {
private static final String FILE_PATH = "src/main/resources/array_serialize2";
public static void main(String[] args) throws IOException, ClassNotFoundException {
Point[] points = new Point[] {new Point(1,2), new Point(3,4)};
serialize(points);
Point[] points1 = deserialize();
Arrays.stream(points1).forEach(System.out::println);
}
private static void serialize(Point[] array) throws IOException {
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(FILE_PATH));
objectOutputStream.writeObject(array);
objectOutputStream.close();
}
private static Point[] deserialize() throws IOException, ClassNotFoundException {
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(FILE_PATH));
Object deserialized = objectInputStream.readObject();
objectInputStream.close();
return (Point[]) deserialized;
}
private static class Point implements Serializable {
private static final long serialVersionUID = 2;
private int[] arr = new int[2];
Point(int x, int y) {
this.arr[0] = x;
this.arr[1] = y;
}
int getX() {
return arr[0];
}
void setX(int x) {
this.arr[0] = x;
}
int getY() {
return arr[1];
}
void setY(int y) {
this.arr[1] = y;
}
@Override
public String toString() {
return "Point{" +
"x=" + arr[0] +
", y=" + arr[1] +
'}';
}
}
}
| 1,771 | 0.568605 | 0.557312 | 69 | 24.666666 | 26.471569 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.449275 | false | false | 5 |
a13a3d35d28a66b471bfc2d9a7d24f2944b7655c | 39,462,159,532,161 | 5a132ee9a1c2cc935e7fe280ada4518ea41ff156 | /app/src/main/java/com/github/vasiliz/vkclient/login/LoginPresenter.java | 78af4d6dee32c689dc3c4c4b3b360fb130b91b8b | []
| no_license | VasiliZ/VKClient | https://github.com/VasiliZ/VKClient | 1654fa47a1d6db08dabd27e006c6c1e54d329fc6 | 32a0a56e75156430a448fd4dd1ad0710c0e0229e | refs/heads/master | 2020-04-23T21:14:05.670000 | 2019-06-17T09:41:53 | 2019-06-17T09:41:53 | 171,446,339 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.github.vasiliz.vkclient.login;
import android.arch.lifecycle.Lifecycle;
import android.content.SharedPreferences;
import android.support.annotation.NonNull;
import com.github.vasiliz.vkclient.login.ui.LoginActivity;
import com.github.vasiliz.vkclient.mymvp.VkBaseView;
import com.github.vasiliz.vkclient.mymvp.VkPresenter;
public class LoginPresenter extends VkPresenter<VkBaseView> implements ILoginView {
private final LoginModel mLoginModel;
private final LoginActivity mLoginActivity;
public LoginPresenter(final SharedPreferences pSharedPreferences, final LoginActivity pLoginActivity) {
mLoginModel = new LoginModel(pSharedPreferences, this);
mLoginActivity = pLoginActivity;
}
@Override
public void saveToken(final String pUrl) {
mLoginModel.saveToken(pUrl);
}
@Override
public void checkLogin() {
if (mLoginModel.checkLogin()) {
mLoginActivity.goToMainScreen();
} else {
mLoginActivity.init();
}
}
@Override
public String getToken() {
return mLoginModel.getToken();
}
@Override
public void reAuth() {
mLoginModel.removePreference();
mLoginActivity.init();
}
@NonNull
@Override
public Lifecycle getLifecycle() {
return mLoginActivity.getLifecycle();
}
}
| UTF-8 | Java | 1,367 | java | LoginPresenter.java | Java | [
{
"context": "package com.github.vasiliz.vkclient.login;\n\nimport android.arch.lifecycle.Li",
"end": 26,
"score": 0.9936316609382629,
"start": 19,
"tag": "USERNAME",
"value": "vasiliz"
},
{
"context": "id.support.annotation.NonNull;\n\nimport com.github.vasiliz.vkclient.login.ui.LoginActivity;\nimport com.githu",
"end": 196,
"score": 0.9966805577278137,
"start": 189,
"tag": "USERNAME",
"value": "vasiliz"
},
{
"context": "kclient.login.ui.LoginActivity;\nimport com.github.vasiliz.vkclient.mymvp.VkBaseView;\nimport com.github.vasi",
"end": 255,
"score": 0.9875336289405823,
"start": 248,
"tag": "USERNAME",
"value": "vasiliz"
},
{
"context": "iliz.vkclient.mymvp.VkBaseView;\nimport com.github.vasiliz.vkclient.mymvp.VkPresenter;\n\npublic class LoginPr",
"end": 308,
"score": 0.9776111245155334,
"start": 301,
"tag": "USERNAME",
"value": "vasiliz"
}
]
| null | []
| package com.github.vasiliz.vkclient.login;
import android.arch.lifecycle.Lifecycle;
import android.content.SharedPreferences;
import android.support.annotation.NonNull;
import com.github.vasiliz.vkclient.login.ui.LoginActivity;
import com.github.vasiliz.vkclient.mymvp.VkBaseView;
import com.github.vasiliz.vkclient.mymvp.VkPresenter;
public class LoginPresenter extends VkPresenter<VkBaseView> implements ILoginView {
private final LoginModel mLoginModel;
private final LoginActivity mLoginActivity;
public LoginPresenter(final SharedPreferences pSharedPreferences, final LoginActivity pLoginActivity) {
mLoginModel = new LoginModel(pSharedPreferences, this);
mLoginActivity = pLoginActivity;
}
@Override
public void saveToken(final String pUrl) {
mLoginModel.saveToken(pUrl);
}
@Override
public void checkLogin() {
if (mLoginModel.checkLogin()) {
mLoginActivity.goToMainScreen();
} else {
mLoginActivity.init();
}
}
@Override
public String getToken() {
return mLoginModel.getToken();
}
@Override
public void reAuth() {
mLoginModel.removePreference();
mLoginActivity.init();
}
@NonNull
@Override
public Lifecycle getLifecycle() {
return mLoginActivity.getLifecycle();
}
}
| 1,367 | 0.702268 | 0.702268 | 51 | 25.803921 | 23.747875 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.392157 | false | false | 5 |
1c3e228c98fb95466f39893ed3151e000724f619 | 37,958,920,986,601 | 0ac05e3da06d78292fdfb64141ead86ff6ca038f | /OSWE/oswe/openCRX/rtjar/rt.jar.src/com/sun/corba/se/spi/activation/_InitialNameServiceImplBase.java | b3df620a09c4e8c73d7004794efebea30f8ac8ed | []
| no_license | qoo7972365/timmy | https://github.com/qoo7972365/timmy | 31581cdcbb8858ac19a8bb7b773441a68b6c390a | 2fc8baba4f53d38dfe9c2b3afd89dcf87cbef578 | refs/heads/master | 2023-07-26T12:26:35.266000 | 2023-07-17T12:35:19 | 2023-07-17T12:35:19 | 353,889,195 | 7 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | /* */ package com.sun.corba.se.spi.activation;
/* */
/* */ import com.sun.corba.se.spi.activation.InitialNameServicePackage.NameAlreadyBound;
/* */ import com.sun.corba.se.spi.activation.InitialNameServicePackage.NameAlreadyBoundHelper;
/* */ import java.util.Hashtable;
/* */ import org.omg.CORBA.BAD_OPERATION;
/* */ import org.omg.CORBA.CompletionStatus;
/* */ import org.omg.CORBA.Object;
/* */ import org.omg.CORBA.ObjectHelper;
/* */ import org.omg.CORBA.portable.InputStream;
/* */ import org.omg.CORBA.portable.InvokeHandler;
/* */ import org.omg.CORBA.portable.ObjectImpl;
/* */ import org.omg.CORBA.portable.OutputStream;
/* */ import org.omg.CORBA.portable.ResponseHandler;
/* */
/* */ public abstract class _InitialNameServiceImplBase
/* */ extends ObjectImpl
/* */ implements InitialNameService, InvokeHandler
/* */ {
/* 20 */ private static Hashtable _methods = new Hashtable<>();
/* */
/* */ static {
/* 23 */ _methods.put("bind", new Integer(0));
/* */ }
/* */
/* */
/* */
/* */
/* */ public OutputStream _invoke(String paramString, InputStream paramInputStream, ResponseHandler paramResponseHandler) {
/* 30 */ OutputStream outputStream = null;
/* 31 */ Integer integer = (Integer)_methods.get(paramString);
/* 32 */ if (integer == null) {
/* 33 */ throw new BAD_OPERATION(0, CompletionStatus.COMPLETED_MAYBE);
/* */ }
/* 35 */ switch (integer.intValue()) {
/* */
/* */ case 0:
/* */
/* */ try {
/* */
/* */
/* 42 */ String str = paramInputStream.read_string();
/* 43 */ Object object = ObjectHelper.read(paramInputStream);
/* 44 */ boolean bool = paramInputStream.read_boolean();
/* 45 */ bind(str, object, bool);
/* 46 */ outputStream = paramResponseHandler.createReply();
/* 47 */ } catch (NameAlreadyBound nameAlreadyBound) {
/* 48 */ outputStream = paramResponseHandler.createExceptionReply();
/* 49 */ NameAlreadyBoundHelper.write(outputStream, nameAlreadyBound);
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* 58 */ return outputStream;
/* */ }
/* */ throw new BAD_OPERATION(0, CompletionStatus.COMPLETED_MAYBE);
/* */ }
/* 62 */ private static String[] __ids = new String[] { "IDL:activation/InitialNameService:1.0" };
/* */
/* */
/* */
/* */ public String[] _ids() {
/* 67 */ return (String[])__ids.clone();
/* */ }
/* */ }
/* Location: /Users/timmy/timmy/OSWE/oswe/openCRX/rt.jar!/com/sun/corba/se/spi/activation/_InitialNameServiceImplBase.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/ | UTF-8 | Java | 2,849 | java | _InitialNameServiceImplBase.java | Java | [
{
"context": " }\n/* */ }\n\n\n/* Location: /Users/timmy/timmy/OSWE/oswe/openCRX/rt.jar!/com/sun/corba/se/",
"end": 2680,
"score": 0.7762710452079773,
"start": 2675,
"tag": "USERNAME",
"value": "timmy"
}
]
| null | []
| /* */ package com.sun.corba.se.spi.activation;
/* */
/* */ import com.sun.corba.se.spi.activation.InitialNameServicePackage.NameAlreadyBound;
/* */ import com.sun.corba.se.spi.activation.InitialNameServicePackage.NameAlreadyBoundHelper;
/* */ import java.util.Hashtable;
/* */ import org.omg.CORBA.BAD_OPERATION;
/* */ import org.omg.CORBA.CompletionStatus;
/* */ import org.omg.CORBA.Object;
/* */ import org.omg.CORBA.ObjectHelper;
/* */ import org.omg.CORBA.portable.InputStream;
/* */ import org.omg.CORBA.portable.InvokeHandler;
/* */ import org.omg.CORBA.portable.ObjectImpl;
/* */ import org.omg.CORBA.portable.OutputStream;
/* */ import org.omg.CORBA.portable.ResponseHandler;
/* */
/* */ public abstract class _InitialNameServiceImplBase
/* */ extends ObjectImpl
/* */ implements InitialNameService, InvokeHandler
/* */ {
/* 20 */ private static Hashtable _methods = new Hashtable<>();
/* */
/* */ static {
/* 23 */ _methods.put("bind", new Integer(0));
/* */ }
/* */
/* */
/* */
/* */
/* */ public OutputStream _invoke(String paramString, InputStream paramInputStream, ResponseHandler paramResponseHandler) {
/* 30 */ OutputStream outputStream = null;
/* 31 */ Integer integer = (Integer)_methods.get(paramString);
/* 32 */ if (integer == null) {
/* 33 */ throw new BAD_OPERATION(0, CompletionStatus.COMPLETED_MAYBE);
/* */ }
/* 35 */ switch (integer.intValue()) {
/* */
/* */ case 0:
/* */
/* */ try {
/* */
/* */
/* 42 */ String str = paramInputStream.read_string();
/* 43 */ Object object = ObjectHelper.read(paramInputStream);
/* 44 */ boolean bool = paramInputStream.read_boolean();
/* 45 */ bind(str, object, bool);
/* 46 */ outputStream = paramResponseHandler.createReply();
/* 47 */ } catch (NameAlreadyBound nameAlreadyBound) {
/* 48 */ outputStream = paramResponseHandler.createExceptionReply();
/* 49 */ NameAlreadyBoundHelper.write(outputStream, nameAlreadyBound);
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* 58 */ return outputStream;
/* */ }
/* */ throw new BAD_OPERATION(0, CompletionStatus.COMPLETED_MAYBE);
/* */ }
/* 62 */ private static String[] __ids = new String[] { "IDL:activation/InitialNameService:1.0" };
/* */
/* */
/* */
/* */ public String[] _ids() {
/* 67 */ return (String[])__ids.clone();
/* */ }
/* */ }
/* Location: /Users/timmy/timmy/OSWE/oswe/openCRX/rt.jar!/com/sun/corba/se/spi/activation/_InitialNameServiceImplBase.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/ | 2,849 | 0.566164 | 0.548965 | 75 | 37 | 30.027987 | 136 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.506667 | false | false | 5 |
9fe9f5471ad2c5ffbf30dfb55a6a391266d4af2e | 33,818,572,547,426 | f033174478ae23f26ad9832f58c276b0aae633bf | /jtm-platform/platform-user/src/main/java/com/dqcer/platformuser/web/dao/SysRoleDao.java | 57feebe6bb5a9085ff964723f81bdfe85184311c | []
| no_license | dqcer/jtm-master | https://github.com/dqcer/jtm-master | 5781d97901f92885eccb84d72e191530cfa4ddb4 | c20aaec0590441f26c2a95211681462e7612d3ec | refs/heads/master | 2022-04-04T07:36:41.843000 | 2020-02-28T13:09:04 | 2020-02-28T13:09:04 | 233,071,025 | 0 | 0 | null | false | 2022-03-08T21:18:11 | 2020-01-10T15:04:34 | 2020-02-28T13:09:20 | 2022-03-08T21:18:10 | 59 | 0 | 0 | 1 | Java | false | false | package com.dqcer.platformuser.web.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.dqcer.jtmcommon.entity.sys.SysRoleEntity;
public interface SysRoleDao extends BaseMapper<SysRoleEntity> {
}
| UTF-8 | Java | 217 | java | SysRoleDao.java | Java | []
| null | []
| package com.dqcer.platformuser.web.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.dqcer.jtmcommon.entity.sys.SysRoleEntity;
public interface SysRoleDao extends BaseMapper<SysRoleEntity> {
}
| 217 | 0.834101 | 0.834101 | 7 | 30 | 26.511454 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 5 |
cb3db30b507151189b2bdc72398f850b4c365c50 | 37,692,633,018,375 | 4279b112a9f7742ea5456b5bf7615a7891a72aee | /superjumper/core/src/com/mygdx/game/shuriken.java | 90777a7e4828ca8b5b153c1b4df8b3484f64902c | []
| no_license | Moriarty005/Juegos | https://github.com/Moriarty005/Juegos | edc7dfface9247403622942acaa8e101a0a33691 | f8fa93b749ad88e9e703ebd120052e43d337ae65 | refs/heads/master | 2022-04-09T21:02:35.297000 | 2020-02-06T11:58:42 | 2020-02-06T11:58:42 | 235,196,050 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mygdx.game;
/**
*
* @author lolac
*/
public class shuriken extends DynamicGameObject{
public static final float SQUIRREL_WIDTH = 1;
public static final float SQUIRREL_HEIGHT = 0.6f;
public static final float SQUIRREL_VELOCITY_X = 3f;
public static final float SQUIRREL_VELOCITY_Y = 3f;
float stateTime = 0;
public shuriken (float x, float y) {
super(x, y, SQUIRREL_WIDTH, SQUIRREL_HEIGHT);
velocity.set(SQUIRREL_VELOCITY_X, 0);
}
public void update (float deltaTime) {
position.add(velocity.x * deltaTime, velocity.y * deltaTime);
bounds.x = position.x - SQUIRREL_WIDTH / 2;
bounds.y = position.y - SQUIRREL_HEIGHT / 2;
if (position.x < SQUIRREL_WIDTH / 2) {
position.x = SQUIRREL_WIDTH / 2;
velocity.x = SQUIRREL_VELOCITY_X;
}
if (position.x > World.WORLD_WIDTH - SQUIRREL_WIDTH / 2) {
position.x = World.WORLD_WIDTH - SQUIRREL_WIDTH / 2;
velocity.x = -SQUIRREL_VELOCITY_X;
}
stateTime += deltaTime;
}
}
| UTF-8 | Java | 1,346 | java | shuriken.java | Java | [
{
"context": "or.\n */\npackage com.mygdx.game;\n\n/**\n *\n * @author lolac\n */\npublic class shuriken extends DynamicGameObje",
"end": 233,
"score": 0.9995103478431702,
"start": 228,
"tag": "USERNAME",
"value": "lolac"
}
]
| 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.mygdx.game;
/**
*
* @author lolac
*/
public class shuriken extends DynamicGameObject{
public static final float SQUIRREL_WIDTH = 1;
public static final float SQUIRREL_HEIGHT = 0.6f;
public static final float SQUIRREL_VELOCITY_X = 3f;
public static final float SQUIRREL_VELOCITY_Y = 3f;
float stateTime = 0;
public shuriken (float x, float y) {
super(x, y, SQUIRREL_WIDTH, SQUIRREL_HEIGHT);
velocity.set(SQUIRREL_VELOCITY_X, 0);
}
public void update (float deltaTime) {
position.add(velocity.x * deltaTime, velocity.y * deltaTime);
bounds.x = position.x - SQUIRREL_WIDTH / 2;
bounds.y = position.y - SQUIRREL_HEIGHT / 2;
if (position.x < SQUIRREL_WIDTH / 2) {
position.x = SQUIRREL_WIDTH / 2;
velocity.x = SQUIRREL_VELOCITY_X;
}
if (position.x > World.WORLD_WIDTH - SQUIRREL_WIDTH / 2) {
position.x = World.WORLD_WIDTH - SQUIRREL_WIDTH / 2;
velocity.x = -SQUIRREL_VELOCITY_X;
}
stateTime += deltaTime;
}
}
| 1,346 | 0.598068 | 0.58841 | 40 | 32.650002 | 25.720177 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.625 | false | false | 5 |
7cd7dd871e39bc855a49e6401827ca1026b427fb | 9,028,021,316,793 | 5643be695c01df622c3c34f1485bea9955a74987 | /src/main/java/br/com/sicredi/repository/AssociadoRepository.java | 2d7c960f6465bb574be922e9915891c1a76525e5 | []
| no_license | felipeb2it/sicred-coop-v1 | https://github.com/felipeb2it/sicred-coop-v1 | efdeee605505a9f73933d4493f8d25d22e68f7a1 | 6505554deb4b9d4cb1c3d07b91ab2df2be0c7b86 | refs/heads/master | 2023-05-03T07:08:03.118000 | 2021-05-24T23:21:05 | 2021-05-24T23:21:05 | 364,815,849 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.sicredi.repository;
import br.com.sicredi.model.Associado;
import io.micronaut.context.annotation.Executable;
import io.micronaut.data.annotation.Repository;
import io.micronaut.data.repository.CrudRepository;
@Repository
public interface AssociadoRepository extends CrudRepository<Associado, Long> {
@Executable
Associado find(String cpf);
}
| UTF-8 | Java | 379 | java | AssociadoRepository.java | Java | []
| null | []
| package br.com.sicredi.repository;
import br.com.sicredi.model.Associado;
import io.micronaut.context.annotation.Executable;
import io.micronaut.data.annotation.Repository;
import io.micronaut.data.repository.CrudRepository;
@Repository
public interface AssociadoRepository extends CrudRepository<Associado, Long> {
@Executable
Associado find(String cpf);
}
| 379 | 0.794195 | 0.794195 | 14 | 25.071428 | 24.267746 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.714286 | false | false | 5 |
5544fd9c2c1a011df6f0d51290c11fd55e15a8de | 38,414,187,525,020 | 4c10ff51368fec012dce484527d659b5db0f774d | /src/main/java/ca/weblite/objc/Client.java | b01456e117f74369f190249feb037a20540253c8 | [
"Apache-2.0"
]
| permissive | shannah/Java-Objective-C-Bridge | https://github.com/shannah/Java-Objective-C-Bridge | 6987ea57f11766e6a39db882caa6b9d5289d9544 | dbd12377aee75acf3afd6f99b4ff92e8faf56058 | refs/heads/master | 2022-07-14T06:34:22.946000 | 2022-03-18T13:06:34 | 2022-03-18T13:06:34 | 6,445,289 | 79 | 29 | null | false | 2022-06-14T16:14:13 | 2012-10-29T18:16:18 | 2022-04-07T04:54:34 | 2022-03-18T13:06:40 | 2,117 | 106 | 23 | 17 | Java | false | false | package ca.weblite.objc;
import static ca.weblite.objc.RuntimeUtils.*;
import com.sun.jna.Pointer;
import java.util.ArrayList;
import java.util.List;
/**
* <p>An object-oriented wrapper around the RuntimeUtils static methods for
* interacting with the Objective-C runtime.</p>
*
* <p>A client object stores settings about whether to coerce inputs and/or
* outputs from messages. There are two global instances of this class
* that are used most often:</p>
* <ol>
* <li>{@link #getInstance()}: The default client with settings to coerce
* both inputs and outputs. If you need to make a direct call to the
* Objective-C runtime, this is usually the client that you would use.
* </li>
* <li>{@link #getRawClient()}: Reference to a simple client that is set to
* <em>not</em> coerce input and output. This is handy if you want to
* pass in the raw Pointers as parameters, and receive raw pointers as
* output.
* </li>
* </ol>
*
* @author shannah
* @version $Id: $Id
* @since 1.1
*/
public class Client {
/**
* Reference to the default client instance with type coercion enabled
* for both inputs and outputs.
*/
private static final Client instance = new Client(true, true);
private Client(boolean coerceInputs, boolean coerceOutputs) {
this.coerceInputs = coerceInputs;
this.coerceOutputs = coerceOutputs;
}
/**
* Retrieves the global reference to a client that has both input coercion
* and output coercion enabled.
*
* @return Singleton instance.
*/
public static Client getInstance() {
return instance;
}
/**
* Reference to a simple client that has type coercion disabled for both
* inputs and outputs.
*/
private static final Client rawClient = new Client(false, false);
/**
* Retrieves singleton instance to a simple client that has type coercion
* disabled for both inputs and outputs.
*
* @return a {@link ca.weblite.objc.Client} object.
*/
public static Client getRawClient(){
return rawClient;
}
/**
* Flag to indicate whether inputs to messages should be coerced. If
* this flag is true, than any Java inputs will be converted to their
* corresponding C types using the TypeMapper class and its corresponding
* TypeMapping subclasses.
*
*/
final boolean coerceInputs;
/**
* Flag to indicate whether the output of messages should be coerced. If
* this flag is true, then any C outputs from messages will be converted
* to their corresponding Java types using the TypeMapper class.
*/
final boolean coerceOutputs;
/**
* Set the coerceInputs flag. Setting this to true will cause all subsequent
* requests to coerce the input (i.e. convert Java parameters to corresponding
* C-types).
*
*
* @param coerceInputs Whether to coerce inputs to messages.
* @return Self for chaining.
* @see TypeMapper
* @see TypeMapping
* @deprecated Use {@link #getRawClient() } to get a client with coercion off. Use {@link #getInstance() } to get a client with coercion on.
*/
@Deprecated
public Client setCoerceInputs(boolean coerceInputs){
throw new UnsupportedOperationException("Cannot modify coerce inputs setting on shared global instance of Objective-C client");
}
/**
* Sets the coerceOutputs flag. Setting this to true will cause all subsequent
* requests to coerce the output (i.e.convert C return values to corresponding
* Java types.
*
* @param coerceOutputs Whether to coerce the outputs of messages.
* @return Self for chaining.
* @see TypeMapper
* @see TypeMapping
* @deprecated Use {@link #getRawClient() } to get a client with coercion off. Use {@link #getInstance() } to get a client with coercion on.
*/
@Deprecated
public Client setCoerceOutputs(boolean coerceOutputs){
throw new UnsupportedOperationException("Cannot modify coerce inputs setting on shared global instance of Objective-C client");
}
/**
* Returns the coerceInputs flag. If this returns true, then it means that
* the client is currently set to coerce all inputs to messages.
*
* @return True if input coercion is enabled.
* @see TypeMapper
* @see TypeMapping
*/
public boolean getCoerceInputs(){
return coerceInputs;
}
/**
* Returns the coerceOutputs flag. If this returns true, then it means that
* the client is currently set to coerce all outputs of messages.
*
* @return True if output coercion is enabled.
* @see TypeMapper
* @see TypeMapping
*/
public boolean getCoerceOutputs(){
return coerceOutputs;
}
/**
* Sends a message to an Objective-C object.
* <pre>
* {@code
* String hello = (String)Client.getInstance()
* .send(cls("NSString"), sel("stringWithUTF8String:"), "Hello");
* }
* </pre>
*
* @param receiver A pointer to the object to which the message is being sent.
* @param selector A pointer to the selector to call on the target.
* @param args Variable arguments of the message.
* @return The return value of the message call.
*/
public Object send(Pointer receiver, Pointer selector, Object... args){
return msg(coerceOutputs, coerceInputs,receiver, selector, args);
}
/**
* Sends a message to an Objective-C object. String selector version.
*
* <pre>
* {@code
* String hello = (String)Client.getInstance()
* .send(cls("NSString"), "stringWithUTF8String:", "Hello");
* }
* </pre>
*
* @param receiver A pointer to the object to which the message is being sent.
* @param selector The string selector. (E.g. "addObject:atIndex:")
* @param args Variable arguments of the message.
* @return The return value of the message call.
*/
public Object send(Pointer receiver, String selector, Object... args){
return send(receiver, sel(selector), args);
}
/**
* Sends a message to an Objective-C object. String target and Pointer
* selector version. Typically this variant is used when you need to
* call a class method (e.g. to instantiate a new object). In this case
* the receiver is interpreted as a class name.
* <pre>
* {@code
* String hello = (String)Client.getInstance()
* .send("NSString", sel("stringWithUTF8String:"), "Hello");
* }
* </pre>
*
* @param receiver The name of a class to send the message to.
* @param selector Pointer to the selector.
* @param args Variable arguments of the message.
* @return The return value of the message call.
*/
public Object send(String receiver, Pointer selector, Object... args){
return send(cls(receiver), selector, args);
}
/**
* Sends a message to an Objective-C object. String target and String
* selector version. Typically this variant is used when you need to
* call a class method (e.g. to instantiate a new object). In this case
* the receiver is interpreted as a class name.
* <pre>
* {@code
* String hello = (String)Client.getInstance()
* .send("NSString", "stringWithUTF8String:", "Hello");
* }
* </pre>
*
* @param receiver The name of a class to send the message to.
* @param selector Pointer to the selector.
* @param args Variable arguments of the message.
* @return The return value of the message call.
*/
public Object send(String receiver, String selector, Object... args){
try {
return send(cls(receiver), sel(selector), args);
} catch (Exception ex) {
if (ex.getCause() instanceof NoSuchMethodException) {
throw new RuntimeException("Cannot find selector "+selector+" for receiver "+receiver, ex);
}
throw ex;
}
}
/**
* Sends a message to an Objective-C object. Peerable target/Pointer selector
* variant. This variant is used if you have a Peerable object that is
* wrapping the Object pointer. E.g. Both the Proxy class and NSObject
* class implement this interface.
* <pre>
* {@code
* Proxy array = Client.getInstance().sendProxy("NSMutableArray", sel("array"));
* String hello = (String)Client
* .getInstance().send(array, sel("addObject:atIndex"), "Hello", 2);
* }
* </pre>
*
* @param selector Pointer to the selector.
* @param args Variable arguments of the message.
* @return The return value of the message call.
* @param proxy a {@link ca.weblite.objc.Peerable} object.
*/
public Object send(Peerable proxy, Pointer selector, Object... args){
return send(proxy.getPeer(), selector, args);
}
/**
* Sends a message to an Objective-C object. Peerable target/String selector
* variant. This variant is used if you have a Peerable object that is
* wrapping the Object pointer. E.g. Both the Proxy class and NSObject
* class implement this interface.
* <pre>
* {@code
* Proxy array = Client.getInstance().sendProxy("NSMutableArray", "array");
* String hello = (String)Client
* .getInstance().send(array, "addObject:atIndex", "Hello", 2);
* }
* </pre>
*
* @param selector Pointer to the selector.
* @param args Variable arguments of the message.
* @return The return value of the message call.
* @param proxy a {@link ca.weblite.objc.Peerable} object.
*/
public Object send(Peerable proxy, String selector, Object... args){
return send(proxy.getPeer(), sel(selector), args);
}
/**
* A wrapper around send() to ensure that a pointer is returned from the
* message.
*
* @param receiver The object to which the message is being sent.
* @param selector The selector to call on the receiver.
* @param args Variable arguments to the message.
* @return A pointer result from the message invocation.
*/
public Pointer sendPointer(Pointer receiver, Pointer selector, Object... args){
//System.out.println("In sendPointer for "+selName(selector));
Object res = send(receiver, selector, args);
if (res instanceof Pointer) {
return (Pointer)res;
} else if (res instanceof Proxy) {
return ((Proxy)res).getPeer();
} else if (res instanceof Long) {
return new Pointer((Long) res);
} else {
return (Pointer)res;
}
}
/**
* A wrapper around send() to ensure that a pointer is returned from the
* message.
*
* @param receiver The object to which the message is being sent.
* @param selector The selector to call on the receiver.
* @param args Variable arguments to the message.
* @return A pointer result from the message invocation.
*/
public Pointer sendPointer(Pointer receiver, String selector, Object... args){
return sendPointer(receiver, sel(selector), args);
}
/**
* A wrapper around send() to ensure that a pointer is returned from the
* message.
*
* @param receiver The object to which the message is being sent.
* @param selector The selector to call on the receiver.
* @param args Variable arguments to the message.
* @return A pointer result from the message invocation.
*/
public Pointer sendPointer(String receiver, Pointer selector, Object... args){
return sendPointer(cls(receiver), selector, args);
}
/**
* A wrapper around send() to ensure that a pointer is returned from the
* message.
*
* @param receiver The object to which the message is being sent.
* @param selector The selector to call on the receiver.
* @param args Variable arguments to the message.
* @return A pointer result from the message invocation.
*/
public Pointer sendPointer(String receiver, String selector, Object... args){
return sendPointer(cls(receiver), sel(selector), args);
}
/**
* A wrapper around send() to ensure that a Proxy object is returned from the
* message.
*
* @param receiver The object to which the message is being sent.
* @param selector The selector to call on the receiver.
* @param args Variable arguments to the message.
* @return A Proxy object wrapper of the result from the message invocation.
*/
public Proxy sendProxy(Pointer receiver, Pointer selector, Object... args){
return (Proxy)send(receiver, selector, args);
}
/**
* A wrapper around send() to ensure that a Proxy object is returned from the
* message.
*
* @param receiver The object to which the message is being sent.
* @param selector The selector to call on the receiver.
* @param args Variable arguments to the message.
* @return A Proxy object wrapper of the result from the message invocation.
*/
public Proxy sendProxy(String receiver, Pointer selector, Object... args){
return sendProxy(cls(receiver), selector, args);
}
/**
* A wrapper around send() to ensure that a Proxy object is returned from the
* message.
*
* @param receiver The object to which the message is being sent.
* @param selector The selector to call on the receiver.
* @param args Variable arguments to the message.
* @return A Proxy object wrapper of the result from the message invocation.
*/
public Proxy sendProxy(String receiver, String selector, Object... args){
return sendProxy(cls(receiver), sel(selector), args);
}
/**
* A wrapper around send() to ensure that a Proxy object is returned from the
* message.
*
* @param receiver The object to which the message is being sent.
* @param selector The selector to call on the receiver.
* @param args Variable arguments to the message.
* @return A Proxy object wrapper of the result from the message invocation.
*/
public Proxy sendProxy(Pointer receiver, String selector, Object... args){
return sendProxy(receiver, sel(selector), args);
}
/**
* <p>chain.</p>
*
* @param cls a {@link java.lang.String} object.
* @param selector a {@link com.sun.jna.Pointer} object.
* @param args a {@link java.lang.Object} object.
* @return a {@link ca.weblite.objc.Proxy} object.
*/
public Proxy chain(String cls, Pointer selector, Object... args){
Pointer res = Client.getRawClient().sendPointer(cls, selector, args);
return new Proxy(res);
}
/**
* <p>chain.</p>
*
* @param cls a {@link java.lang.String} object.
* @param selector a {@link java.lang.String} object.
* @param args a {@link java.lang.Object} object.
* @return a {@link ca.weblite.objc.Proxy} object.
*/
public Proxy chain(String cls, String selector, Object... args){
return chain(cls, sel(selector), args);
}
/**
* Creates a new peerable and receivable object of the specified class.
* This will create the Objective-C peer and link it to this new class.
*
* @param cls The class of the instance that should be created.
* @return A PeerableRecipient object that is connected to an objective-c
* peer object.
*/
public PeerableRecipient newObject(Class<? extends PeerableRecipient> cls){
try {
PeerableRecipient instance = cls.newInstance();
if ( instance.getPeer() == Pointer.NULL){
Pointer peer = new Pointer(createProxy(instance));
instance.setPeer(peer);
}
return instance;
} catch (Exception ex){
throw new RuntimeException(ex);
}
}
/**
* Sends an array of messages in a chain.
*
* @param messages a {@link ca.weblite.objc.Message} object.
* @return a {@link java.lang.Object} object.
*/
public Object send(Message... messages){
return RuntimeUtils.msg(messages);
}
/**
* Builds a chain of messages that can be executed together at a later time.
*
* @param parameters a {@link java.lang.Object} object.
* @return an array of {@link ca.weblite.objc.Message} objects.
*/
public Message[] buildMessageChain(Object... parameters){
List<Message> messages = new ArrayList<Message>();
for (int i=0; i<parameters.length; i++){
Object parameter = parameters[i];
Message buffer = new Message();
buffer.coerceInput = this.coerceInputs;
buffer.coerceOutput = this.coerceOutputs;
if (parameter instanceof String) {
if ("_".equals(parameter)) {
buffer.receiver = Pointer.NULL;
} else {
buffer.receiver = cls((String)parameter);
}
} else if (parameter instanceof Peerable) {
buffer.receiver = ((Peerable)parameter).getPeer();
} else {
buffer.receiver = (Pointer)parameter;
}
i++;
if (parameter instanceof String) {
buffer.selector = sel((String)parameter);
} else if (parameter instanceof Peerable) {
buffer.selector = ((Peerable)parameter).getPeer();
} else {
buffer.selector = (Pointer)parameter;
}
i++;
while ( i<parameters.length && parameter != null ){
buffer.args.add(parameters[i++]);
}
messages.add(buffer);
}
return messages.toArray(Message[]::new);
}
}
| UTF-8 | Java | 18,255 | java | Client.java | Java | [
{
"context": "s\n * output.\n * </li>\n * </ol>\n *\n * @author shannah\n * @version $Id: $Id\n * @since 1.1\n */\npubli",
"end": 988,
"score": 0.8070316910743713,
"start": 986,
"tag": "NAME",
"value": "sh"
},
{
"context": "* output.\n * </li>\n * </ol>\n *\n * @author shannah\n * @version $Id: $Id\n * @since 1.1\n */\npublic cla",
"end": 993,
"score": 0.5786202549934387,
"start": 988,
"tag": "USERNAME",
"value": "annah"
}
]
| null | []
| package ca.weblite.objc;
import static ca.weblite.objc.RuntimeUtils.*;
import com.sun.jna.Pointer;
import java.util.ArrayList;
import java.util.List;
/**
* <p>An object-oriented wrapper around the RuntimeUtils static methods for
* interacting with the Objective-C runtime.</p>
*
* <p>A client object stores settings about whether to coerce inputs and/or
* outputs from messages. There are two global instances of this class
* that are used most often:</p>
* <ol>
* <li>{@link #getInstance()}: The default client with settings to coerce
* both inputs and outputs. If you need to make a direct call to the
* Objective-C runtime, this is usually the client that you would use.
* </li>
* <li>{@link #getRawClient()}: Reference to a simple client that is set to
* <em>not</em> coerce input and output. This is handy if you want to
* pass in the raw Pointers as parameters, and receive raw pointers as
* output.
* </li>
* </ol>
*
* @author shannah
* @version $Id: $Id
* @since 1.1
*/
public class Client {
/**
* Reference to the default client instance with type coercion enabled
* for both inputs and outputs.
*/
private static final Client instance = new Client(true, true);
private Client(boolean coerceInputs, boolean coerceOutputs) {
this.coerceInputs = coerceInputs;
this.coerceOutputs = coerceOutputs;
}
/**
* Retrieves the global reference to a client that has both input coercion
* and output coercion enabled.
*
* @return Singleton instance.
*/
public static Client getInstance() {
return instance;
}
/**
* Reference to a simple client that has type coercion disabled for both
* inputs and outputs.
*/
private static final Client rawClient = new Client(false, false);
/**
* Retrieves singleton instance to a simple client that has type coercion
* disabled for both inputs and outputs.
*
* @return a {@link ca.weblite.objc.Client} object.
*/
public static Client getRawClient(){
return rawClient;
}
/**
* Flag to indicate whether inputs to messages should be coerced. If
* this flag is true, than any Java inputs will be converted to their
* corresponding C types using the TypeMapper class and its corresponding
* TypeMapping subclasses.
*
*/
final boolean coerceInputs;
/**
* Flag to indicate whether the output of messages should be coerced. If
* this flag is true, then any C outputs from messages will be converted
* to their corresponding Java types using the TypeMapper class.
*/
final boolean coerceOutputs;
/**
* Set the coerceInputs flag. Setting this to true will cause all subsequent
* requests to coerce the input (i.e. convert Java parameters to corresponding
* C-types).
*
*
* @param coerceInputs Whether to coerce inputs to messages.
* @return Self for chaining.
* @see TypeMapper
* @see TypeMapping
* @deprecated Use {@link #getRawClient() } to get a client with coercion off. Use {@link #getInstance() } to get a client with coercion on.
*/
@Deprecated
public Client setCoerceInputs(boolean coerceInputs){
throw new UnsupportedOperationException("Cannot modify coerce inputs setting on shared global instance of Objective-C client");
}
/**
* Sets the coerceOutputs flag. Setting this to true will cause all subsequent
* requests to coerce the output (i.e.convert C return values to corresponding
* Java types.
*
* @param coerceOutputs Whether to coerce the outputs of messages.
* @return Self for chaining.
* @see TypeMapper
* @see TypeMapping
* @deprecated Use {@link #getRawClient() } to get a client with coercion off. Use {@link #getInstance() } to get a client with coercion on.
*/
@Deprecated
public Client setCoerceOutputs(boolean coerceOutputs){
throw new UnsupportedOperationException("Cannot modify coerce inputs setting on shared global instance of Objective-C client");
}
/**
* Returns the coerceInputs flag. If this returns true, then it means that
* the client is currently set to coerce all inputs to messages.
*
* @return True if input coercion is enabled.
* @see TypeMapper
* @see TypeMapping
*/
public boolean getCoerceInputs(){
return coerceInputs;
}
/**
* Returns the coerceOutputs flag. If this returns true, then it means that
* the client is currently set to coerce all outputs of messages.
*
* @return True if output coercion is enabled.
* @see TypeMapper
* @see TypeMapping
*/
public boolean getCoerceOutputs(){
return coerceOutputs;
}
/**
* Sends a message to an Objective-C object.
* <pre>
* {@code
* String hello = (String)Client.getInstance()
* .send(cls("NSString"), sel("stringWithUTF8String:"), "Hello");
* }
* </pre>
*
* @param receiver A pointer to the object to which the message is being sent.
* @param selector A pointer to the selector to call on the target.
* @param args Variable arguments of the message.
* @return The return value of the message call.
*/
public Object send(Pointer receiver, Pointer selector, Object... args){
return msg(coerceOutputs, coerceInputs,receiver, selector, args);
}
/**
* Sends a message to an Objective-C object. String selector version.
*
* <pre>
* {@code
* String hello = (String)Client.getInstance()
* .send(cls("NSString"), "stringWithUTF8String:", "Hello");
* }
* </pre>
*
* @param receiver A pointer to the object to which the message is being sent.
* @param selector The string selector. (E.g. "addObject:atIndex:")
* @param args Variable arguments of the message.
* @return The return value of the message call.
*/
public Object send(Pointer receiver, String selector, Object... args){
return send(receiver, sel(selector), args);
}
/**
* Sends a message to an Objective-C object. String target and Pointer
* selector version. Typically this variant is used when you need to
* call a class method (e.g. to instantiate a new object). In this case
* the receiver is interpreted as a class name.
* <pre>
* {@code
* String hello = (String)Client.getInstance()
* .send("NSString", sel("stringWithUTF8String:"), "Hello");
* }
* </pre>
*
* @param receiver The name of a class to send the message to.
* @param selector Pointer to the selector.
* @param args Variable arguments of the message.
* @return The return value of the message call.
*/
public Object send(String receiver, Pointer selector, Object... args){
return send(cls(receiver), selector, args);
}
/**
* Sends a message to an Objective-C object. String target and String
* selector version. Typically this variant is used when you need to
* call a class method (e.g. to instantiate a new object). In this case
* the receiver is interpreted as a class name.
* <pre>
* {@code
* String hello = (String)Client.getInstance()
* .send("NSString", "stringWithUTF8String:", "Hello");
* }
* </pre>
*
* @param receiver The name of a class to send the message to.
* @param selector Pointer to the selector.
* @param args Variable arguments of the message.
* @return The return value of the message call.
*/
public Object send(String receiver, String selector, Object... args){
try {
return send(cls(receiver), sel(selector), args);
} catch (Exception ex) {
if (ex.getCause() instanceof NoSuchMethodException) {
throw new RuntimeException("Cannot find selector "+selector+" for receiver "+receiver, ex);
}
throw ex;
}
}
/**
* Sends a message to an Objective-C object. Peerable target/Pointer selector
* variant. This variant is used if you have a Peerable object that is
* wrapping the Object pointer. E.g. Both the Proxy class and NSObject
* class implement this interface.
* <pre>
* {@code
* Proxy array = Client.getInstance().sendProxy("NSMutableArray", sel("array"));
* String hello = (String)Client
* .getInstance().send(array, sel("addObject:atIndex"), "Hello", 2);
* }
* </pre>
*
* @param selector Pointer to the selector.
* @param args Variable arguments of the message.
* @return The return value of the message call.
* @param proxy a {@link ca.weblite.objc.Peerable} object.
*/
public Object send(Peerable proxy, Pointer selector, Object... args){
return send(proxy.getPeer(), selector, args);
}
/**
* Sends a message to an Objective-C object. Peerable target/String selector
* variant. This variant is used if you have a Peerable object that is
* wrapping the Object pointer. E.g. Both the Proxy class and NSObject
* class implement this interface.
* <pre>
* {@code
* Proxy array = Client.getInstance().sendProxy("NSMutableArray", "array");
* String hello = (String)Client
* .getInstance().send(array, "addObject:atIndex", "Hello", 2);
* }
* </pre>
*
* @param selector Pointer to the selector.
* @param args Variable arguments of the message.
* @return The return value of the message call.
* @param proxy a {@link ca.weblite.objc.Peerable} object.
*/
public Object send(Peerable proxy, String selector, Object... args){
return send(proxy.getPeer(), sel(selector), args);
}
/**
* A wrapper around send() to ensure that a pointer is returned from the
* message.
*
* @param receiver The object to which the message is being sent.
* @param selector The selector to call on the receiver.
* @param args Variable arguments to the message.
* @return A pointer result from the message invocation.
*/
public Pointer sendPointer(Pointer receiver, Pointer selector, Object... args){
//System.out.println("In sendPointer for "+selName(selector));
Object res = send(receiver, selector, args);
if (res instanceof Pointer) {
return (Pointer)res;
} else if (res instanceof Proxy) {
return ((Proxy)res).getPeer();
} else if (res instanceof Long) {
return new Pointer((Long) res);
} else {
return (Pointer)res;
}
}
/**
* A wrapper around send() to ensure that a pointer is returned from the
* message.
*
* @param receiver The object to which the message is being sent.
* @param selector The selector to call on the receiver.
* @param args Variable arguments to the message.
* @return A pointer result from the message invocation.
*/
public Pointer sendPointer(Pointer receiver, String selector, Object... args){
return sendPointer(receiver, sel(selector), args);
}
/**
* A wrapper around send() to ensure that a pointer is returned from the
* message.
*
* @param receiver The object to which the message is being sent.
* @param selector The selector to call on the receiver.
* @param args Variable arguments to the message.
* @return A pointer result from the message invocation.
*/
public Pointer sendPointer(String receiver, Pointer selector, Object... args){
return sendPointer(cls(receiver), selector, args);
}
/**
* A wrapper around send() to ensure that a pointer is returned from the
* message.
*
* @param receiver The object to which the message is being sent.
* @param selector The selector to call on the receiver.
* @param args Variable arguments to the message.
* @return A pointer result from the message invocation.
*/
public Pointer sendPointer(String receiver, String selector, Object... args){
return sendPointer(cls(receiver), sel(selector), args);
}
/**
* A wrapper around send() to ensure that a Proxy object is returned from the
* message.
*
* @param receiver The object to which the message is being sent.
* @param selector The selector to call on the receiver.
* @param args Variable arguments to the message.
* @return A Proxy object wrapper of the result from the message invocation.
*/
public Proxy sendProxy(Pointer receiver, Pointer selector, Object... args){
return (Proxy)send(receiver, selector, args);
}
/**
* A wrapper around send() to ensure that a Proxy object is returned from the
* message.
*
* @param receiver The object to which the message is being sent.
* @param selector The selector to call on the receiver.
* @param args Variable arguments to the message.
* @return A Proxy object wrapper of the result from the message invocation.
*/
public Proxy sendProxy(String receiver, Pointer selector, Object... args){
return sendProxy(cls(receiver), selector, args);
}
/**
* A wrapper around send() to ensure that a Proxy object is returned from the
* message.
*
* @param receiver The object to which the message is being sent.
* @param selector The selector to call on the receiver.
* @param args Variable arguments to the message.
* @return A Proxy object wrapper of the result from the message invocation.
*/
public Proxy sendProxy(String receiver, String selector, Object... args){
return sendProxy(cls(receiver), sel(selector), args);
}
/**
* A wrapper around send() to ensure that a Proxy object is returned from the
* message.
*
* @param receiver The object to which the message is being sent.
* @param selector The selector to call on the receiver.
* @param args Variable arguments to the message.
* @return A Proxy object wrapper of the result from the message invocation.
*/
public Proxy sendProxy(Pointer receiver, String selector, Object... args){
return sendProxy(receiver, sel(selector), args);
}
/**
* <p>chain.</p>
*
* @param cls a {@link java.lang.String} object.
* @param selector a {@link com.sun.jna.Pointer} object.
* @param args a {@link java.lang.Object} object.
* @return a {@link ca.weblite.objc.Proxy} object.
*/
public Proxy chain(String cls, Pointer selector, Object... args){
Pointer res = Client.getRawClient().sendPointer(cls, selector, args);
return new Proxy(res);
}
/**
* <p>chain.</p>
*
* @param cls a {@link java.lang.String} object.
* @param selector a {@link java.lang.String} object.
* @param args a {@link java.lang.Object} object.
* @return a {@link ca.weblite.objc.Proxy} object.
*/
public Proxy chain(String cls, String selector, Object... args){
return chain(cls, sel(selector), args);
}
/**
* Creates a new peerable and receivable object of the specified class.
* This will create the Objective-C peer and link it to this new class.
*
* @param cls The class of the instance that should be created.
* @return A PeerableRecipient object that is connected to an objective-c
* peer object.
*/
public PeerableRecipient newObject(Class<? extends PeerableRecipient> cls){
try {
PeerableRecipient instance = cls.newInstance();
if ( instance.getPeer() == Pointer.NULL){
Pointer peer = new Pointer(createProxy(instance));
instance.setPeer(peer);
}
return instance;
} catch (Exception ex){
throw new RuntimeException(ex);
}
}
/**
* Sends an array of messages in a chain.
*
* @param messages a {@link ca.weblite.objc.Message} object.
* @return a {@link java.lang.Object} object.
*/
public Object send(Message... messages){
return RuntimeUtils.msg(messages);
}
/**
* Builds a chain of messages that can be executed together at a later time.
*
* @param parameters a {@link java.lang.Object} object.
* @return an array of {@link ca.weblite.objc.Message} objects.
*/
public Message[] buildMessageChain(Object... parameters){
List<Message> messages = new ArrayList<Message>();
for (int i=0; i<parameters.length; i++){
Object parameter = parameters[i];
Message buffer = new Message();
buffer.coerceInput = this.coerceInputs;
buffer.coerceOutput = this.coerceOutputs;
if (parameter instanceof String) {
if ("_".equals(parameter)) {
buffer.receiver = Pointer.NULL;
} else {
buffer.receiver = cls((String)parameter);
}
} else if (parameter instanceof Peerable) {
buffer.receiver = ((Peerable)parameter).getPeer();
} else {
buffer.receiver = (Pointer)parameter;
}
i++;
if (parameter instanceof String) {
buffer.selector = sel((String)parameter);
} else if (parameter instanceof Peerable) {
buffer.selector = ((Peerable)parameter).getPeer();
} else {
buffer.selector = (Pointer)parameter;
}
i++;
while ( i<parameters.length && parameter != null ){
buffer.args.add(parameters[i++]);
}
messages.add(buffer);
}
return messages.toArray(Message[]::new);
}
}
| 18,255 | 0.621419 | 0.620926 | 506 | 35.077076 | 29.596363 | 145 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.328063 | false | false | 5 |
30bcd3abb781316bec370ae48f89783ad07f6eaf | 23,390,391,937,829 | 6baf1fe00541560788e78de5244ae17a7a2b375a | /hollywood/com.oculus.browser-base/sources/defpackage/C5051uD1.java | 8b31c4a8e45f1683d20d3783ae8971120c899fbf | []
| no_license | phwd/quest-tracker | https://github.com/phwd/quest-tracker | 286e605644fc05f00f4904e51f73d77444a78003 | 3d46fbb467ba11bee5827f7cae7dfeabeb1fd2ba | refs/heads/main | 2023-03-29T20:33:10.959000 | 2021-04-10T22:14:11 | 2021-04-10T22:14:11 | 357,185,040 | 4 | 2 | null | true | 2021-04-12T12:28:09 | 2021-04-12T12:28:08 | 2021-04-10T22:15:44 | 2021-04-10T22:15:39 | 116,441 | 0 | 0 | 0 | null | false | false | package defpackage;
import java.util.Objects;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/* renamed from: uD1 reason: default package and case insensitive filesystem */
/* compiled from: chromium-OculusBrowser.apk-stable-281887347 */
public final class C5051uD1 extends KL0 {
public final /* synthetic */ int[] t;
public final /* synthetic */ ML0 u;
/* JADX INFO: super call moved to the top of the method (can break code semantics) */
public C5051uD1(ML0 ml0, YV yv, int[] iArr) {
super(ml0, yv, true);
this.u = ml0;
this.t = iArr;
}
@Override // defpackage.KL0
public final void n(C3350kF1 kf1) {
MF1 mf1 = this.u.c;
RF1 rf1 = this.q;
int[] iArr = this.t;
Objects.requireNonNull(mf1);
JSONObject jSONObject = new JSONObject();
long b = mf1.b();
try {
jSONObject.put("requestId", b);
jSONObject.put("type", "QUEUE_GET_ITEMS");
jSONObject.put("mediaSessionId", mf1.o());
JSONArray jSONArray = new JSONArray();
for (int i : iArr) {
jSONArray.put(i);
}
jSONObject.put("itemIds", jSONArray);
} catch (JSONException unused) {
}
mf1.a(jSONObject.toString(), b, null);
mf1.y.c(b, rf1);
}
}
| UTF-8 | Java | 1,376 | java | C5051uD1.java | Java | []
| null | []
| package defpackage;
import java.util.Objects;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/* renamed from: uD1 reason: default package and case insensitive filesystem */
/* compiled from: chromium-OculusBrowser.apk-stable-281887347 */
public final class C5051uD1 extends KL0 {
public final /* synthetic */ int[] t;
public final /* synthetic */ ML0 u;
/* JADX INFO: super call moved to the top of the method (can break code semantics) */
public C5051uD1(ML0 ml0, YV yv, int[] iArr) {
super(ml0, yv, true);
this.u = ml0;
this.t = iArr;
}
@Override // defpackage.KL0
public final void n(C3350kF1 kf1) {
MF1 mf1 = this.u.c;
RF1 rf1 = this.q;
int[] iArr = this.t;
Objects.requireNonNull(mf1);
JSONObject jSONObject = new JSONObject();
long b = mf1.b();
try {
jSONObject.put("requestId", b);
jSONObject.put("type", "QUEUE_GET_ITEMS");
jSONObject.put("mediaSessionId", mf1.o());
JSONArray jSONArray = new JSONArray();
for (int i : iArr) {
jSONArray.put(i);
}
jSONObject.put("itemIds", jSONArray);
} catch (JSONException unused) {
}
mf1.a(jSONObject.toString(), b, null);
mf1.y.c(b, rf1);
}
}
| 1,376 | 0.586483 | 0.555233 | 43 | 31 | 20.365269 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.813953 | false | false | 5 |
3876f8095a8bfdfa9281dd3b11bae80e9b96bfc3 | 8,950,711,851,736 | 39304aee576621424ac4f6f09b4371da75a4d63b | /src/main/java/com/chapter4/bloodAlcoholCalculator/ParametersReceiver.java | 3c5350b041c8ac6921a0d8e9ed50d7fb9d091a9b | []
| no_license | MonsieurVictor/57_Challenges | https://github.com/MonsieurVictor/57_Challenges | 9aeeabe92c34739eb3c4c70c104b878a6b120229 | e267469b9e38f2fe49994026dd670224624abe20 | refs/heads/master | 2023-05-11T17:35:15.726000 | 2019-06-27T07:53:18 | 2019-06-27T07:53:18 | 122,217,736 | 0 | 0 | null | false | 2023-05-09T17:56:11 | 2018-02-20T15:37:30 | 2019-06-27T07:53:29 | 2023-05-09T17:56:08 | 1,037 | 0 | 0 | 1 | Java | false | false | package com.chapter4.bloodAlcoholCalculator;
/**
* is responsible for receiving values from console
**/
import com.utils.ConsoleInputsReceiver;
public class ParametersReceiver {
ConsoleInputsReceiver console = new ConsoleInputsReceiver();
private String promptSexMsg = "What is your sex? \n1. Male \n2. Female";
private String promptWeightMsg = "How many kg do you weigh?";
private String promptHoursPassedMsg = "How many hours have passed since the last drink?";
HumanParameters promptHumanParameters(HumanParameters human) {
while (true) {
System.out.println(promptSexMsg);
int sex = console.insistOnIntegerPositiveInput();
if (sex == 1) {
human.alcoDigesting.alcoholDistributionRatio = 0.73;
break;
}
if (sex == 2) {
human.alcoDigesting.alcoholDistributionRatio = 0.66;
break;
}
}
System.out.println(promptWeightMsg);
human.weight = console.insistOnIntegerPositiveInput();
System.out.println(promptHoursPassedMsg);
human.alcoDigesting.hoursPassed = console.insistOnDoublePositiveInput();
return human;
}
}
| UTF-8 | Java | 1,241 | java | ParametersReceiver.java | Java | []
| null | []
| package com.chapter4.bloodAlcoholCalculator;
/**
* is responsible for receiving values from console
**/
import com.utils.ConsoleInputsReceiver;
public class ParametersReceiver {
ConsoleInputsReceiver console = new ConsoleInputsReceiver();
private String promptSexMsg = "What is your sex? \n1. Male \n2. Female";
private String promptWeightMsg = "How many kg do you weigh?";
private String promptHoursPassedMsg = "How many hours have passed since the last drink?";
HumanParameters promptHumanParameters(HumanParameters human) {
while (true) {
System.out.println(promptSexMsg);
int sex = console.insistOnIntegerPositiveInput();
if (sex == 1) {
human.alcoDigesting.alcoholDistributionRatio = 0.73;
break;
}
if (sex == 2) {
human.alcoDigesting.alcoholDistributionRatio = 0.66;
break;
}
}
System.out.println(promptWeightMsg);
human.weight = console.insistOnIntegerPositiveInput();
System.out.println(promptHoursPassedMsg);
human.alcoDigesting.hoursPassed = console.insistOnDoublePositiveInput();
return human;
}
}
| 1,241 | 0.646253 | 0.637389 | 43 | 27.860466 | 28.272413 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.395349 | false | false | 5 |
74d4885b949ceab15ef96e304c8a91e9ea5b99c2 | 28,080,496,239,903 | 383d7ab2cc5906c56574be9eec67978cb29c8e9c | /src/main/java/com/yhw/common/model/YhwUser.java | 2e0b538890d326cc1f64c32b969cb905f8192a44 | []
| no_license | wang6688/YhwUserCentral | https://github.com/wang6688/YhwUserCentral | dbf8dad9519b2d0e67426a812c61f6728ff9b991 | 95327d2fa01ddc9ef15693f9d755a549430fccca | refs/heads/master | 2020-03-15T21:07:52.822000 | 2018-05-06T15:09:58 | 2018-05-06T15:09:58 | 132,348,379 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.yhw.common.model;
import com.yhw.common.model.base.BaseYhwUser;
/**
* Generated by JFinal.
*/
@SuppressWarnings("serial")
public class YhwUser extends BaseYhwUser<YhwUser> {
}
| UTF-8 | Java | 194 | java | YhwUser.java | Java | []
| null | []
| package com.yhw.common.model;
import com.yhw.common.model.base.BaseYhwUser;
/**
* Generated by JFinal.
*/
@SuppressWarnings("serial")
public class YhwUser extends BaseYhwUser<YhwUser> {
}
| 194 | 0.742268 | 0.742268 | 11 | 16.636364 | 18.341572 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.272727 | false | false | 5 |
65e304c39740d304d921f7c98fbe5d7eb46759a5 | 19,602,230,746,066 | f3135ac60a8d85183f9422e8d9d91a6ef699c032 | /vraptor-core/src/test/java/br/com/caelum/vraptor/ioc/cdi/CDIBasedContainerTest.java | 4fe5263ab9fc35ef1d1f178cf2768dbdeab8e28e | [
"Apache-2.0"
]
| permissive | pvrsouza/vraptor4 | https://github.com/pvrsouza/vraptor4 | e3c7bcb6eb43396825496b54517f3bdaf3e36143 | ba2e03a496a85e76ae8e3d4d09f5197ff629d2ed | refs/heads/master | 2021-01-22T14:46:23.520000 | 2013-12-18T11:17:46 | 2013-12-18T11:17:46 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.caelum.vraptor.ioc.cdi;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertEquals;
import java.lang.reflect.Field;
import java.util.concurrent.Callable;
import javax.inject.Inject;
import org.hamcrest.MatcherAssert;
import org.junit.Test;
import org.junit.runner.RunWith;
import br.com.caelum.cdi.component.UsingCacheComponent;
import br.com.caelum.vraptor.WeldJunitRunner;
import br.com.caelum.vraptor.core.RequestInfo;
import br.com.caelum.vraptor.http.MutableRequest;
import br.com.caelum.vraptor.http.MutableResponse;
import br.com.caelum.vraptor.interceptor.PackagesAcceptor;
import br.com.caelum.vraptor.ioc.Container;
import br.com.caelum.vraptor.ioc.ContainerProvider;
import br.com.caelum.vraptor.ioc.GenericContainerTest;
import br.com.caelum.vraptor.ioc.WhatToDo;
@RunWith(WeldJunitRunner.class)
public class CDIBasedContainerTest extends GenericContainerTest {
@Inject private CDIBasedContainer cdiBasedContainer;
@Inject private CDIProvider cdiProvider;
@Inject private Contexts contexts;
private int counter;
@Override
protected ContainerProvider getProvider() {
return cdiProvider;
}
@Override
public void tearDown() {
super.tearDown();
contexts.stopRequestScope();
contexts.stopConversationScope();
contexts.stopSessionScope();
contexts.stopApplicationScope();
}
@Override
protected <T> T executeInsideRequest(final WhatToDo<T> execution) {
Callable<T> task = new Callable<T>() {
@Override
public T call() throws Exception {
contexts.startRequestScope();
contexts.startSessionScope();
RequestInfo request = new RequestInfo(null, null,
cdiBasedContainer.instanceFor(MutableRequest.class),
cdiBasedContainer.instanceFor(MutableResponse.class));
T result = execution.execute(request, counter);
contexts.stopRequestScope();
contexts.stopSessionScope();
return result;
}
};
try {
T call = task.call();
return call;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@SuppressWarnings("rawtypes")
private Object actualInstance(Object instance) {
try {
//sorry, but i have to initialize the weld proxy
initializeProxy(instance);
Field field = instance.getClass().getDeclaredField("BEAN_INSTANCE_CACHE");
field.setAccessible(true);
ThreadLocal mapa = (ThreadLocal) field.get(instance);
return mapa.get();
} catch (Exception exception) {
return instance;
}
}
@Override
protected <T> T instanceFor(final Class<T> component, Container container) {
T maybeAWeldProxy = container.instanceFor(component);
return component.cast(actualInstance(maybeAWeldProxy));
}
@Override
protected void checkSimilarity(Class<?> component, boolean shouldBeTheSame,
Object firstInstance, Object secondInstance) {
if (shouldBeTheSame) {
MatcherAssert.assertThat("Should be the same instance for "
+ component.getName(), actualInstance(firstInstance),
is(equalTo(actualInstance(secondInstance))));
} else {
MatcherAssert.assertThat("Should not be the same instance for "
+ component.getName(), actualInstance(firstInstance),
is(not(equalTo(actualInstance(secondInstance)))));
}
}
@Test
public void instantiateCustomAcceptor(){
actualInstance(cdiBasedContainer.instanceFor(PackagesAcceptor.class));
}
private void initializeProxy(Object component) {
component.toString();
}
@Test
public void shouldCreateComponentsWithCache(){
UsingCacheComponent component = cdiBasedContainer.instanceFor(UsingCacheComponent.class);
component.putWithLRU("test","test");
component.putWithDefault("test2","test2");
assertEquals(component.putWithLRU("test","test"),"test");
assertEquals(component.putWithDefault("test2","test2"),"test2");
}
} | UTF-8 | Java | 3,852 | java | CDIBasedContainerTest.java | Java | []
| null | []
| package br.com.caelum.vraptor.ioc.cdi;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertEquals;
import java.lang.reflect.Field;
import java.util.concurrent.Callable;
import javax.inject.Inject;
import org.hamcrest.MatcherAssert;
import org.junit.Test;
import org.junit.runner.RunWith;
import br.com.caelum.cdi.component.UsingCacheComponent;
import br.com.caelum.vraptor.WeldJunitRunner;
import br.com.caelum.vraptor.core.RequestInfo;
import br.com.caelum.vraptor.http.MutableRequest;
import br.com.caelum.vraptor.http.MutableResponse;
import br.com.caelum.vraptor.interceptor.PackagesAcceptor;
import br.com.caelum.vraptor.ioc.Container;
import br.com.caelum.vraptor.ioc.ContainerProvider;
import br.com.caelum.vraptor.ioc.GenericContainerTest;
import br.com.caelum.vraptor.ioc.WhatToDo;
@RunWith(WeldJunitRunner.class)
public class CDIBasedContainerTest extends GenericContainerTest {
@Inject private CDIBasedContainer cdiBasedContainer;
@Inject private CDIProvider cdiProvider;
@Inject private Contexts contexts;
private int counter;
@Override
protected ContainerProvider getProvider() {
return cdiProvider;
}
@Override
public void tearDown() {
super.tearDown();
contexts.stopRequestScope();
contexts.stopConversationScope();
contexts.stopSessionScope();
contexts.stopApplicationScope();
}
@Override
protected <T> T executeInsideRequest(final WhatToDo<T> execution) {
Callable<T> task = new Callable<T>() {
@Override
public T call() throws Exception {
contexts.startRequestScope();
contexts.startSessionScope();
RequestInfo request = new RequestInfo(null, null,
cdiBasedContainer.instanceFor(MutableRequest.class),
cdiBasedContainer.instanceFor(MutableResponse.class));
T result = execution.execute(request, counter);
contexts.stopRequestScope();
contexts.stopSessionScope();
return result;
}
};
try {
T call = task.call();
return call;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@SuppressWarnings("rawtypes")
private Object actualInstance(Object instance) {
try {
//sorry, but i have to initialize the weld proxy
initializeProxy(instance);
Field field = instance.getClass().getDeclaredField("BEAN_INSTANCE_CACHE");
field.setAccessible(true);
ThreadLocal mapa = (ThreadLocal) field.get(instance);
return mapa.get();
} catch (Exception exception) {
return instance;
}
}
@Override
protected <T> T instanceFor(final Class<T> component, Container container) {
T maybeAWeldProxy = container.instanceFor(component);
return component.cast(actualInstance(maybeAWeldProxy));
}
@Override
protected void checkSimilarity(Class<?> component, boolean shouldBeTheSame,
Object firstInstance, Object secondInstance) {
if (shouldBeTheSame) {
MatcherAssert.assertThat("Should be the same instance for "
+ component.getName(), actualInstance(firstInstance),
is(equalTo(actualInstance(secondInstance))));
} else {
MatcherAssert.assertThat("Should not be the same instance for "
+ component.getName(), actualInstance(firstInstance),
is(not(equalTo(actualInstance(secondInstance)))));
}
}
@Test
public void instantiateCustomAcceptor(){
actualInstance(cdiBasedContainer.instanceFor(PackagesAcceptor.class));
}
private void initializeProxy(Object component) {
component.toString();
}
@Test
public void shouldCreateComponentsWithCache(){
UsingCacheComponent component = cdiBasedContainer.instanceFor(UsingCacheComponent.class);
component.putWithLRU("test","test");
component.putWithDefault("test2","test2");
assertEquals(component.putWithLRU("test","test"),"test");
assertEquals(component.putWithDefault("test2","test2"),"test2");
}
} | 3,852 | 0.76298 | 0.761682 | 131 | 28.412214 | 23.337833 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.045802 | false | false | 5 |
1e79657aee587a23713867d120f61d9ea7642070 | 26,525,718,082,238 | 24397b7a79ed4f21fe374520f89f747577d42c7b | /app/src/main/java/com/lenovo/bount/newsquarter/bean/ResponsBodyBean.java | f880160aad061a7d34e98a51aa1d453cbe885f14 | []
| no_license | Bount0000/Newsquarter2 | https://github.com/Bount0000/Newsquarter2 | b6e06d730a4004b0edb7733b94b64feadc794bc3 | 5f4bbc5a758e8beae4f48ee2c630465521c6b7da | refs/heads/master | 2021-05-06T21:44:10.449000 | 2017-12-20T00:46:22 | 2017-12-20T00:46:22 | 112,676,555 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lenovo.bount.newsquarter.bean;
/**
* Created by lenovo on 2017/11/27.
*/
public class ResponsBodyBean<Data> {
public String msg;
public String code;
public Data data;
}
| UTF-8 | Java | 198 | java | ResponsBodyBean.java | Java | [
{
"context": ".lenovo.bount.newsquarter.bean;\n\n/**\n * Created by lenovo on 2017/11/27.\n */\n\npublic class ResponsBodyBean<",
"end": 68,
"score": 0.9995119571685791,
"start": 62,
"tag": "USERNAME",
"value": "lenovo"
}
]
| null | []
| package com.lenovo.bount.newsquarter.bean;
/**
* Created by lenovo on 2017/11/27.
*/
public class ResponsBodyBean<Data> {
public String msg;
public String code;
public Data data;
}
| 198 | 0.686869 | 0.646465 | 12 | 15.5 | 15.478479 | 42 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 5 |
f80cd31ec843bcfc1c6a493836d770bdcb243749 | 21,500,606,285,454 | fb629046d1bc92899e485982c91a0dc2ff025603 | /openTCS-Example-CommAdapter-Vehicle/src/main/java/de/fraunhofer/iml/opentcs/example/commadapter/vehicle/exchange/myControlPanel.java | e7723b25fb3ac1d07f8674683b2ee62d73d661a5 | []
| no_license | touchmii/OpenTCS-5-Modbus | https://github.com/touchmii/OpenTCS-5-Modbus | b17c7d74bae743a919964ad87b0243ec7c7a3e29 | 1ef521c2b30c6c20f90f382e00ec76e57e7ac55a | refs/heads/master | 2022-12-01T09:23:58.407000 | 2020-08-17T13:13:19 | 2020-08-17T13:13:19 | 275,038,176 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Created by JFormDesigner on Fri Jun 26 08:07:09 CST 2020
*/
package de.fraunhofer.iml.opentcs.example.commadapter.vehicle.exchange;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
//import java.util.Comparator;
//import java.util.Call
import static java.util.Objects.requireNonNull;
import javax.inject.Inject;
import javax.swing.*;
import javax.swing.GroupLayout;
import javax.swing.LayoutStyle;
import javax.swing.border.*;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
import com.google.inject.assistedinject.Assisted;
import de.fraunhofer.iml.opentcs.example.commadapter.vehicle.ExampleProcessModel;
import de.fraunhofer.iml.opentcs.example.commadapter.vehicle.telegrams.OrderRequest;
import org.opentcs.components.kernel.services.VehicleService;
import org.opentcs.customizations.ServiceCallWrapper;
import org.opentcs.drivers.vehicle.VehicleProcessModel;
import org.opentcs.drivers.vehicle.management.*;
import org.opentcs.util.CallWrapper;
import org.opentcs.util.Comparators;
import org.opentcs.data.model.Point;
import org.opentcs.util.gui.StringListCellRenderer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Benoni Jiang
*/
public class myControlPanel extends VehicleCommAdapterPanel {
private static final Logger LOG = LoggerFactory.getLogger((ControlPanel.class));
private static final int MAX_LAST_ORDERS = 20;
private final DefaultListModel<OrderRequest> lastOrderListModel = new DefaultListModel<>();
private final VehicleService vehicleService;
private final CallWrapper callWrapper;
private ExampleProcessModelTO processModel;
@Inject
public myControlPanel(@Assisted ExampleProcessModelTO processModel,
@Assisted VehicleService vehicleService,
@ServiceCallWrapper CallWrapper callWrapper) {
this.processModel = requireNonNull(processModel, "processModel");
this.vehicleService = requireNonNull(vehicleService, "vehicleService");
this.callWrapper = requireNonNull(callWrapper, "callWrepper");
initComponents();
// initComboBoxes();
// initGuiContent();
}
private void initComBoBoxes() {
try {
destinationComboBox.removeAllItems();
callWrapper.call(() -> vehicleService.fetchObjects(Point.class)).stream()
.sorted(Comparators.objectsByName())
.forEach(point -> destinationComboBox.addItem(point));
actionComboBox.removeAllItems();
for (OrderRequest.OrderAction curAction : OrderRequest.OrderAction.values()) {
actionComboBox.addItem(curAction);
}
} catch (Exception ex) {
LOG.warn("Error fetching points", ex);
}
}
private void initGuiContent() {
for (VehicleProcessModel.Attribute attribute : VehicleProcessModel.Attribute.values()) {
processModelChange(attribute.name(), processModel);
}
for (ExampleProcessModel.Attribute attribute : ExampleProcessModel.Attribute.values()) {
processModelChange(attribute.name(), processModel);
}
}
@Override
public void processModelChange(String attributeChanged, VehicleProcessModelTO newProcessModle) {
if (!(newProcessModle instanceof ExampleProcessModelTO)) {
return;
}
processModel = (ExampleProcessModelTO) newProcessModle;
if (Objects.equals(attributeChanged,
VehicleProcessModel.Attribute.COMM_ADAPTER_ENABLED.name())) {
updateCommAdapterEnabled(processModel.isCommAdapterEnabled());
}
}
private void updateCommAdapterEnabled(boolean enabled) {
SwingUtilities.invokeLater(() -> {
enableAdapterCheckBox.setSelected(enabled);
hostTextField.setEditable(!enabled);
portTextField.setEditable(!enabled);
aliveTimeoutTextField.setEditable(!enabled);
disconnectOnTimeoutChkBox.setEnabled(!enabled);
reconnectOnConnectionLossChkBox.setEnabled(!enabled);
enableLoggingChkBox.setEnabled(!enabled);
});
}
private void enableAdapterCheckBoxActionPerformed(ActionEvent e) {
// TODO add your code here
}
private void disconnectOnTimeoutChkBoxActionPerformed(ActionEvent e) {
// TODO add your code here
}
private void reconnectOnConnectionLossChkBoxActionPerformed(ActionEvent e) {
// TODO add your code here
}
private void enableLoggingChkBoxActionPerformed(ActionEvent e) {
// TODO add your code here
}
private void sendOrderButtonActionPerformed(ActionEvent e) {
// TODO add your code here
}
private void repeatLastOrderButtonActionPerformed(ActionEvent e) {
// TODO add your code here
}
private void initComponents() {
// JFormDesigner - Component initialization - DO NOT MODIFY //GEN-BEGIN:initComponents
// Generated using JFormDesigner Evaluation license - Benoni Jiang
ResourceBundle bundle = ResourceBundle.getBundle("de.fraunhofer.iml.opentcs.example.commadapter.vehicle.Bundle");
connectionSettingsPanel = new JPanel();
enableAdapterCheckBox = new JCheckBox();
hostLabel = new JLabel();
hostTextField = new JTextField();
connectedButton = new JButton();
portLabel = new JLabel();
portTextField = new JTextField();
activeButton = new JButton();
aliveTimeoutLable = new JLabel();
aliveTimeoutTextField = new JTextField();
disconnectOnTimeoutChkBox = new JCheckBox();
reconnectOnConnectionLossChkBox = new JCheckBox();
enableLoggingChkBox = new JCheckBox();
setOrderPanel = new JPanel();
destinationLabel = new JLabel();
destinationComboBox = new JComboBox<>();
actionLabel = new JLabel();
actionComboBox = new JComboBox<>();
orderIdLabel = new JLabel();
orderIdTextField = new JTextField();
sendOrderButton = new JButton();
repeatOrderPanel = new JPanel();
lastOrdersScrollPane = new JScrollPane();
lastOrdersList = new JList<>();
lastOrderDetailsPanel = new JPanel();
destinationLabel1 = new JLabel();
lastDestinationTextField = new JTextField();
actionLabel1 = new JLabel();
lastActionTextField = new JTextField();
lastOrderIdLabel = new JLabel();
lastOrderIdTextField = new JTextField();
repeatLastOrderButton = new JButton();
//======== this ========
setBorder ( new javax . swing. border .CompoundBorder ( new javax . swing. border .TitledBorder ( new javax . swing. border .
EmptyBorder ( 0, 0 ,0 , 0) , "JF\u006frmDes\u0069gner \u0045valua\u0074ion" , javax. swing .border . TitledBorder. CENTER ,javax . swing
. border .TitledBorder . BOTTOM, new java. awt .Font ( "D\u0069alog", java .awt . Font. BOLD ,12 ) ,
java . awt. Color .red ) , getBorder () ) ); addPropertyChangeListener( new java. beans .PropertyChangeListener ( )
{ @Override public void propertyChange (java . beans. PropertyChangeEvent e) { if( "\u0062order" .equals ( e. getPropertyName () ) )
throw new RuntimeException( ) ;} } );
//======== connectionSettingsPanel ========
{
connectionSettingsPanel.setBorder(new TitledBorder(null, "Connection to vehicle", TitledBorder.LEADING, TitledBorder.DEFAULT_POSITION,
new Font("Tahoma", Font.BOLD, 11)));
connectionSettingsPanel.setLayout(new GridBagLayout());
((GridBagLayout)connectionSettingsPanel.getLayout()).columnWidths = new int[] {0, 0, 0, 0, 0, 0, 0};
((GridBagLayout)connectionSettingsPanel.getLayout()).columnWeights = new double[] {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0E-4};
//---- enableAdapterCheckBox ----
enableAdapterCheckBox.setText(bundle.getString("EnableAdapter"));
enableAdapterCheckBox.addActionListener(e -> enableAdapterCheckBoxActionPerformed(e));
connectionSettingsPanel.add(enableAdapterCheckBox, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.NONE,
new Insets(0, 0, 0, 0), 0, 0));
//---- hostLabel ----
hostLabel.setText(bundle.getString("VehicleIpAddress"));
connectionSettingsPanel.add(hostLabel, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0,
GridBagConstraints.EAST, GridBagConstraints.NONE,
new Insets(0, 3, 0, 3), 0, 0));
//---- hostTextField ----
hostTextField.setColumns(12);
hostTextField.setText("XXX.XXX.XXX.XXX");
connectionSettingsPanel.add(hostTextField, new GridBagConstraints(2, 0, 4, 1, 10.0, 10.0,
GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL,
new Insets(0, 0, 3, 3), 0, 0));
//---- connectedButton ----
connectedButton.setIcon(new ImageIcon(getClass().getResource("/de/fraunhofer/iml/opentcs/example/commadapter/vehicle/res/symbols/LEDGray.gif")));
connectedButton.setText(bundle.getString("AdapterConnected"));
connectedButton.setBorderPainted(false);
connectedButton.setDisabledIcon(new ImageIcon(getClass().getResource("/de/fraunhofer/iml/opentcs/example/commadapter/vehicle/res/symbols/LEDRed.gif")));
connectedButton.setDisabledSelectedIcon(new ImageIcon(getClass().getResource("/de/fraunhofer/iml/opentcs/example/commadapter/vehicle/res/symbols/LEDGreen.gif")));
connectedButton.setEnabled(false);
connectionSettingsPanel.add(connectedButton, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0,
GridBagConstraints.WEST, GridBagConstraints.NONE,
new Insets(0, 0, 0, 0), 0, 0));
//---- portLabel ----
portLabel.setText(bundle.getString("VehicleTcpPort"));
connectionSettingsPanel.add(portLabel, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0,
GridBagConstraints.EAST, GridBagConstraints.NONE,
new Insets(0, 3, 0, 3), 0, 0));
//---- portTextField ----
portTextField.setDocument(new PlainDocument(){
@Override
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException {
try {
String oldString = getText(0, getLength());
StringBuilder newString = new StringBuilder(oldString);
newString.insert(offs, str);
int newValue = Integer.parseInt(newString.toString());
if (newValue >= 1 && newValue <= 65535) {
super.insertString(offs, str, a);
}
}
catch(NumberFormatException e) { }
}
}
);
portTextField.setColumns(6);
portTextField.setText("XXXXX");
connectionSettingsPanel.add(portTextField, new GridBagConstraints(2, 1, 2, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL,
new Insets(0, 0, 3, 3), 0, 0));
//---- activeButton ----
activeButton.setIcon(new ImageIcon(getClass().getResource("/de/fraunhofer/iml/opentcs/example/commadapter/vehicle/res/symbols/LEDGray.gif")));
activeButton.setText(bundle.getString("ControlPanel.AdapterActive"));
activeButton.setBorderPainted(false);
activeButton.setDisabledIcon(new ImageIcon(getClass().getResource("/de/fraunhofer/iml/opentcs/example/commadapter/vehicle/res/symbols/LEDRed.gif")));
activeButton.setDisabledSelectedIcon(new ImageIcon(getClass().getResource("/de/fraunhofer/iml/opentcs/example/commadapter/vehicle/res/symbols/LEDGreen.gif")));
activeButton.setEnabled(false);
connectionSettingsPanel.add(activeButton, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0,
GridBagConstraints.WEST, GridBagConstraints.NONE,
new Insets(0, 0, 0, 0), 0, 0));
//---- aliveTimeoutLable ----
aliveTimeoutLable.setText(bundle.getString("ControlPanel.IdleAfter"));
connectionSettingsPanel.add(aliveTimeoutLable, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0,
GridBagConstraints.EAST, GridBagConstraints.NONE,
new Insets(0, 3, 0, 3), 0, 0));
//---- aliveTimeoutTextField ----
aliveTimeoutTextField.setDocument(new PlainDocument(){
@Override
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException {
try {
Integer.parseInt(str);
super.insertString(offs, str, a);
}
catch(NumberFormatException e) { }
}
});
aliveTimeoutTextField.setColumns(6);
aliveTimeoutTextField.setText("XXXXX");
connectionSettingsPanel.add(aliveTimeoutTextField, new GridBagConstraints(2, 2, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL,
new Insets(0, 0, 3, 3), 0, 0));
//---- disconnectOnTimeoutChkBox ----
disconnectOnTimeoutChkBox.setText(bundle.getString("ControlPanel.DisconnectOnTimeout"));
disconnectOnTimeoutChkBox.addActionListener(e -> disconnectOnTimeoutChkBoxActionPerformed(e));
connectionSettingsPanel.add(disconnectOnTimeoutChkBox, new GridBagConstraints(0, 3, 2, 1, 0.0, 0.0,
GridBagConstraints.WEST, GridBagConstraints.NONE,
new Insets(0, 0, 0, 0), 0, 0));
//---- reconnectOnConnectionLossChkBox ----
reconnectOnConnectionLossChkBox.setText(bundle.getString("ControlPanel.DisconnectOnConnectionLoss"));
reconnectOnConnectionLossChkBox.addActionListener(e -> reconnectOnConnectionLossChkBoxActionPerformed(e));
connectionSettingsPanel.add(reconnectOnConnectionLossChkBox, new GridBagConstraints(0, 4, 2, 1, 0.0, 0.0,
GridBagConstraints.WEST, GridBagConstraints.NONE,
new Insets(0, 0, 0, 0), 0, 0));
//---- enableLoggingChkBox ----
enableLoggingChkBox.setText(bundle.getString("ControlPanel.EnableLogging"));
enableLoggingChkBox.addActionListener(e -> enableLoggingChkBoxActionPerformed(e));
connectionSettingsPanel.add(enableLoggingChkBox, new GridBagConstraints(0, 5, 2, 1, 0.0, 0.0,
GridBagConstraints.WEST, GridBagConstraints.NONE,
new Insets(0, 0, 0, 0), 0, 0));
}
//======== setOrderPanel ========
{
setOrderPanel.setBorder(new TitledBorder(null, "New order telegram", TitledBorder.LEADING, TitledBorder.DEFAULT_POSITION,
new Font("Tahoma", Font.BOLD, 11)));
setOrderPanel.setLayout(new GridBagLayout());
//---- destinationLabel ----
destinationLabel.setText(bundle.getString("OrderDestination"));
setOrderPanel.add(destinationLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0,
GridBagConstraints.EAST, GridBagConstraints.NONE,
new Insets(0, 3, 0, 3), 0, 0));
//---- destinationComboBox ----
destinationComboBox.setEditor(new TCSObjectComboBoxEditor());
destinationComboBox.setRenderer(new StringListCellRenderer<Point>(point -> point.getName()));
destinationComboBox.setEditable(true);
setOrderPanel.add(destinationComboBox, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0,
GridBagConstraints.WEST, GridBagConstraints.NONE,
new Insets(0, 0, 3, 3), 0, 0));
//---- actionLabel ----
actionLabel.setText(bundle.getString("OrderAction"));
setOrderPanel.add(actionLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0,
GridBagConstraints.EAST, GridBagConstraints.NONE,
new Insets(0, 3, 0, 3), 0, 0));
setOrderPanel.add(actionComboBox, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0,
GridBagConstraints.WEST, GridBagConstraints.NONE,
new Insets(0, 0, 3, 3), 0, 0));
//---- orderIdLabel ----
orderIdLabel.setText(bundle.getString("OrderID"));
setOrderPanel.add(orderIdLabel, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0,
GridBagConstraints.EAST, GridBagConstraints.NONE,
new Insets(0, 3, 0, 3), 0, 0));
//---- orderIdTextField ----
orderIdTextField.setColumns(6);
orderIdTextField.setText("1");
setOrderPanel.add(orderIdTextField, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0,
GridBagConstraints.WEST, GridBagConstraints.NONE,
new Insets(0, 0, 3, 3), 0, 0));
//---- sendOrderButton ----
sendOrderButton.setText(bundle.getString("SendNewOrder"));
sendOrderButton.addActionListener(e -> sendOrderButtonActionPerformed(e));
setOrderPanel.add(sendOrderButton, new GridBagConstraints(0, 3, 2, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL,
new Insets(0, 3, 3, 3), 0, 0));
}
//======== repeatOrderPanel ========
{
repeatOrderPanel.setBorder(new TitledBorder(null, "Last orders sent to vehicle", TitledBorder.LEADING, TitledBorder.DEFAULT_POSITION,
new Font("Tahoma", Font.BOLD, 11)));
repeatOrderPanel.setMinimumSize(new Dimension(199, 170));
//======== lastOrdersScrollPane ========
{
//---- lastOrdersList ----
lastOrdersList.setModel(lastOrderListModel);
lastOrdersList.setCellRenderer(new OrderListCellRenderer());
lastOrdersList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
lastOrdersScrollPane.setViewportView(lastOrdersList);
}
//======== lastOrderDetailsPanel ========
{
lastOrderDetailsPanel.setLayout(new GridBagLayout());
//---- destinationLabel1 ----
destinationLabel1.setText(bundle.getString("OrderDestination"));
lastOrderDetailsPanel.add(destinationLabel1, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0,
GridBagConstraints.EAST, GridBagConstraints.NONE,
new Insets(0, 3, 0, 3), 0, 0));
//---- lastDestinationTextField ----
lastDestinationTextField.setEditable(false);
lastDestinationTextField.setColumns(12);
lastDestinationTextField.setHorizontalAlignment(SwingConstants.RIGHT);
lastOrderDetailsPanel.add(lastDestinationTextField, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0,
GridBagConstraints.WEST, GridBagConstraints.NONE,
new Insets(0, 0, 3, 3), 0, 0));
//---- actionLabel1 ----
actionLabel1.setText(bundle.getString("OrderAction"));
lastOrderDetailsPanel.add(actionLabel1, new GridBagConstraints(0, 9, 1, 1, 0.0, 0.0,
GridBagConstraints.EAST, GridBagConstraints.NONE,
new Insets(0, 3, 0, 3), 0, 0));
//---- lastActionTextField ----
lastActionTextField.setEditable(false);
lastActionTextField.setColumns(12);
lastActionTextField.setHorizontalAlignment(SwingConstants.RIGHT);
lastOrderDetailsPanel.add(lastActionTextField, new GridBagConstraints(1, 9, 1, 1, 0.0, 0.0,
GridBagConstraints.WEST, GridBagConstraints.NONE,
new Insets(0, 0, 3, 3), 0, 0));
//---- lastOrderIdLabel ----
lastOrderIdLabel.setText(bundle.getString("OrderID"));
lastOrderDetailsPanel.add(lastOrderIdLabel, new GridBagConstraints(0, 11, 1, 1, 0.0, 0.0,
GridBagConstraints.EAST, GridBagConstraints.NONE,
new Insets(0, 3, 0, 3), 0, 0));
//---- lastOrderIdTextField ----
lastOrderIdTextField.setEditable(false);
lastOrderIdTextField.setColumns(6);
lastOrderDetailsPanel.add(lastOrderIdTextField, new GridBagConstraints(1, 11, 1, 1, 0.0, 0.0,
GridBagConstraints.WEST, GridBagConstraints.NONE,
new Insets(0, 0, 3, 3), 0, 0));
//---- repeatLastOrderButton ----
repeatLastOrderButton.setText(bundle.getString("SendLastOrderAgain"));
repeatLastOrderButton.setEnabled(false);
repeatLastOrderButton.addActionListener(e -> repeatLastOrderButtonActionPerformed(e));
lastOrderDetailsPanel.add(repeatLastOrderButton, new GridBagConstraints(0, 12, 2, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL,
new Insets(0, 3, 3, 3), 0, 0));
}
GroupLayout repeatOrderPanelLayout = new GroupLayout(repeatOrderPanel);
repeatOrderPanel.setLayout(repeatOrderPanelLayout);
repeatOrderPanelLayout.setHorizontalGroup(
repeatOrderPanelLayout.createParallelGroup()
.addGroup(repeatOrderPanelLayout.createSequentialGroup()
.addComponent(lastOrdersScrollPane, GroupLayout.PREFERRED_SIZE, 166, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lastOrderDetailsPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0))
);
repeatOrderPanelLayout.setVerticalGroup(
repeatOrderPanelLayout.createParallelGroup()
.addGroup(repeatOrderPanelLayout.createSequentialGroup()
.addGroup(repeatOrderPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING, false)
.addComponent(lastOrdersScrollPane)
.addComponent(lastOrderDetailsPanel, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, 0))
);
}
GroupLayout layout = new GroupLayout(this);
setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup()
.addGroup(layout.createSequentialGroup()
.addGap(0, 0, 0)
.addGroup(layout.createParallelGroup()
.addGroup(layout.createSequentialGroup()
.addComponent(connectionSettingsPanel, GroupLayout.PREFERRED_SIZE, 400, GroupLayout.PREFERRED_SIZE)
.addGap(6, 6, 6)
.addComponent(setOrderPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addComponent(repeatOrderPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, 0))
);
layout.setVerticalGroup(
layout.createParallelGroup()
.addGroup(layout.createSequentialGroup()
.addGap(0, 0, 0)
.addGroup(layout.createParallelGroup()
.addComponent(connectionSettingsPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(setOrderPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGap(6, 6, 6)
.addComponent(repeatOrderPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
// JFormDesigner - End of component initialization //GEN-END:initComponents
}
// JFormDesigner - Variables declaration - DO NOT MODIFY //GEN-BEGIN:variables
// Generated using JFormDesigner Evaluation license - Benoni Jiang
private JPanel connectionSettingsPanel;
private JCheckBox enableAdapterCheckBox;
private JLabel hostLabel;
private JTextField hostTextField;
private JButton connectedButton;
private JLabel portLabel;
private JTextField portTextField;
private JButton activeButton;
private JLabel aliveTimeoutLable;
private JTextField aliveTimeoutTextField;
private JCheckBox disconnectOnTimeoutChkBox;
private JCheckBox reconnectOnConnectionLossChkBox;
private JCheckBox enableLoggingChkBox;
private JPanel setOrderPanel;
private JLabel destinationLabel;
private JComboBox<Point> destinationComboBox;
private JLabel actionLabel;
private JComboBox<OrderRequest.OrderAction> actionComboBox;
private JLabel orderIdLabel;
private JTextField orderIdTextField;
private JButton sendOrderButton;
private JPanel repeatOrderPanel;
private JScrollPane lastOrdersScrollPane;
private JList<OrderRequest> lastOrdersList;
private JPanel lastOrderDetailsPanel;
private JLabel destinationLabel1;
private JTextField lastDestinationTextField;
private JLabel actionLabel1;
private JTextField lastActionTextField;
private JLabel lastOrderIdLabel;
private JTextField lastOrderIdTextField;
private JButton repeatLastOrderButton;
// JFormDesigner - End of variables declaration //GEN-END:variables
}
| UTF-8 | Java | 26,185 | java | myControlPanel.java | Java | [
{
"context": "r;\nimport org.slf4j.LoggerFactory;\n\n/**\n * @author Benoni Jiang\n */\npublic class myControlPanel extends VehicleCo",
"end": 1261,
"score": 0.9998505115509033,
"start": 1249,
"tag": "NAME",
"value": "Benoni Jiang"
},
{
"context": "Generated using JFormDesigner Evaluation license - Benoni Jiang\n ResourceBundle bundle = ResourceBundle.ge",
"end": 5148,
"score": 0.9998878240585327,
"start": 5136,
"tag": "NAME",
"value": "Benoni Jiang"
},
{
"context": "Generated using JFormDesigner Evaluation license - Benoni Jiang\n private JPanel connectionSettingsPanel;\n p",
"end": 24792,
"score": 0.9999019503593445,
"start": 24780,
"tag": "NAME",
"value": "Benoni Jiang"
}
]
| null | []
| /*
* Created by JFormDesigner on Fri Jun 26 08:07:09 CST 2020
*/
package de.fraunhofer.iml.opentcs.example.commadapter.vehicle.exchange;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
//import java.util.Comparator;
//import java.util.Call
import static java.util.Objects.requireNonNull;
import javax.inject.Inject;
import javax.swing.*;
import javax.swing.GroupLayout;
import javax.swing.LayoutStyle;
import javax.swing.border.*;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
import com.google.inject.assistedinject.Assisted;
import de.fraunhofer.iml.opentcs.example.commadapter.vehicle.ExampleProcessModel;
import de.fraunhofer.iml.opentcs.example.commadapter.vehicle.telegrams.OrderRequest;
import org.opentcs.components.kernel.services.VehicleService;
import org.opentcs.customizations.ServiceCallWrapper;
import org.opentcs.drivers.vehicle.VehicleProcessModel;
import org.opentcs.drivers.vehicle.management.*;
import org.opentcs.util.CallWrapper;
import org.opentcs.util.Comparators;
import org.opentcs.data.model.Point;
import org.opentcs.util.gui.StringListCellRenderer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author <NAME>
*/
public class myControlPanel extends VehicleCommAdapterPanel {
private static final Logger LOG = LoggerFactory.getLogger((ControlPanel.class));
private static final int MAX_LAST_ORDERS = 20;
private final DefaultListModel<OrderRequest> lastOrderListModel = new DefaultListModel<>();
private final VehicleService vehicleService;
private final CallWrapper callWrapper;
private ExampleProcessModelTO processModel;
@Inject
public myControlPanel(@Assisted ExampleProcessModelTO processModel,
@Assisted VehicleService vehicleService,
@ServiceCallWrapper CallWrapper callWrapper) {
this.processModel = requireNonNull(processModel, "processModel");
this.vehicleService = requireNonNull(vehicleService, "vehicleService");
this.callWrapper = requireNonNull(callWrapper, "callWrepper");
initComponents();
// initComboBoxes();
// initGuiContent();
}
private void initComBoBoxes() {
try {
destinationComboBox.removeAllItems();
callWrapper.call(() -> vehicleService.fetchObjects(Point.class)).stream()
.sorted(Comparators.objectsByName())
.forEach(point -> destinationComboBox.addItem(point));
actionComboBox.removeAllItems();
for (OrderRequest.OrderAction curAction : OrderRequest.OrderAction.values()) {
actionComboBox.addItem(curAction);
}
} catch (Exception ex) {
LOG.warn("Error fetching points", ex);
}
}
private void initGuiContent() {
for (VehicleProcessModel.Attribute attribute : VehicleProcessModel.Attribute.values()) {
processModelChange(attribute.name(), processModel);
}
for (ExampleProcessModel.Attribute attribute : ExampleProcessModel.Attribute.values()) {
processModelChange(attribute.name(), processModel);
}
}
@Override
public void processModelChange(String attributeChanged, VehicleProcessModelTO newProcessModle) {
if (!(newProcessModle instanceof ExampleProcessModelTO)) {
return;
}
processModel = (ExampleProcessModelTO) newProcessModle;
if (Objects.equals(attributeChanged,
VehicleProcessModel.Attribute.COMM_ADAPTER_ENABLED.name())) {
updateCommAdapterEnabled(processModel.isCommAdapterEnabled());
}
}
private void updateCommAdapterEnabled(boolean enabled) {
SwingUtilities.invokeLater(() -> {
enableAdapterCheckBox.setSelected(enabled);
hostTextField.setEditable(!enabled);
portTextField.setEditable(!enabled);
aliveTimeoutTextField.setEditable(!enabled);
disconnectOnTimeoutChkBox.setEnabled(!enabled);
reconnectOnConnectionLossChkBox.setEnabled(!enabled);
enableLoggingChkBox.setEnabled(!enabled);
});
}
private void enableAdapterCheckBoxActionPerformed(ActionEvent e) {
// TODO add your code here
}
private void disconnectOnTimeoutChkBoxActionPerformed(ActionEvent e) {
// TODO add your code here
}
private void reconnectOnConnectionLossChkBoxActionPerformed(ActionEvent e) {
// TODO add your code here
}
private void enableLoggingChkBoxActionPerformed(ActionEvent e) {
// TODO add your code here
}
private void sendOrderButtonActionPerformed(ActionEvent e) {
// TODO add your code here
}
private void repeatLastOrderButtonActionPerformed(ActionEvent e) {
// TODO add your code here
}
private void initComponents() {
// JFormDesigner - Component initialization - DO NOT MODIFY //GEN-BEGIN:initComponents
// Generated using JFormDesigner Evaluation license - <NAME>
ResourceBundle bundle = ResourceBundle.getBundle("de.fraunhofer.iml.opentcs.example.commadapter.vehicle.Bundle");
connectionSettingsPanel = new JPanel();
enableAdapterCheckBox = new JCheckBox();
hostLabel = new JLabel();
hostTextField = new JTextField();
connectedButton = new JButton();
portLabel = new JLabel();
portTextField = new JTextField();
activeButton = new JButton();
aliveTimeoutLable = new JLabel();
aliveTimeoutTextField = new JTextField();
disconnectOnTimeoutChkBox = new JCheckBox();
reconnectOnConnectionLossChkBox = new JCheckBox();
enableLoggingChkBox = new JCheckBox();
setOrderPanel = new JPanel();
destinationLabel = new JLabel();
destinationComboBox = new JComboBox<>();
actionLabel = new JLabel();
actionComboBox = new JComboBox<>();
orderIdLabel = new JLabel();
orderIdTextField = new JTextField();
sendOrderButton = new JButton();
repeatOrderPanel = new JPanel();
lastOrdersScrollPane = new JScrollPane();
lastOrdersList = new JList<>();
lastOrderDetailsPanel = new JPanel();
destinationLabel1 = new JLabel();
lastDestinationTextField = new JTextField();
actionLabel1 = new JLabel();
lastActionTextField = new JTextField();
lastOrderIdLabel = new JLabel();
lastOrderIdTextField = new JTextField();
repeatLastOrderButton = new JButton();
//======== this ========
setBorder ( new javax . swing. border .CompoundBorder ( new javax . swing. border .TitledBorder ( new javax . swing. border .
EmptyBorder ( 0, 0 ,0 , 0) , "JF\u006frmDes\u0069gner \u0045valua\u0074ion" , javax. swing .border . TitledBorder. CENTER ,javax . swing
. border .TitledBorder . BOTTOM, new java. awt .Font ( "D\u0069alog", java .awt . Font. BOLD ,12 ) ,
java . awt. Color .red ) , getBorder () ) ); addPropertyChangeListener( new java. beans .PropertyChangeListener ( )
{ @Override public void propertyChange (java . beans. PropertyChangeEvent e) { if( "\u0062order" .equals ( e. getPropertyName () ) )
throw new RuntimeException( ) ;} } );
//======== connectionSettingsPanel ========
{
connectionSettingsPanel.setBorder(new TitledBorder(null, "Connection to vehicle", TitledBorder.LEADING, TitledBorder.DEFAULT_POSITION,
new Font("Tahoma", Font.BOLD, 11)));
connectionSettingsPanel.setLayout(new GridBagLayout());
((GridBagLayout)connectionSettingsPanel.getLayout()).columnWidths = new int[] {0, 0, 0, 0, 0, 0, 0};
((GridBagLayout)connectionSettingsPanel.getLayout()).columnWeights = new double[] {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0E-4};
//---- enableAdapterCheckBox ----
enableAdapterCheckBox.setText(bundle.getString("EnableAdapter"));
enableAdapterCheckBox.addActionListener(e -> enableAdapterCheckBoxActionPerformed(e));
connectionSettingsPanel.add(enableAdapterCheckBox, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.NONE,
new Insets(0, 0, 0, 0), 0, 0));
//---- hostLabel ----
hostLabel.setText(bundle.getString("VehicleIpAddress"));
connectionSettingsPanel.add(hostLabel, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0,
GridBagConstraints.EAST, GridBagConstraints.NONE,
new Insets(0, 3, 0, 3), 0, 0));
//---- hostTextField ----
hostTextField.setColumns(12);
hostTextField.setText("XXX.XXX.XXX.XXX");
connectionSettingsPanel.add(hostTextField, new GridBagConstraints(2, 0, 4, 1, 10.0, 10.0,
GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL,
new Insets(0, 0, 3, 3), 0, 0));
//---- connectedButton ----
connectedButton.setIcon(new ImageIcon(getClass().getResource("/de/fraunhofer/iml/opentcs/example/commadapter/vehicle/res/symbols/LEDGray.gif")));
connectedButton.setText(bundle.getString("AdapterConnected"));
connectedButton.setBorderPainted(false);
connectedButton.setDisabledIcon(new ImageIcon(getClass().getResource("/de/fraunhofer/iml/opentcs/example/commadapter/vehicle/res/symbols/LEDRed.gif")));
connectedButton.setDisabledSelectedIcon(new ImageIcon(getClass().getResource("/de/fraunhofer/iml/opentcs/example/commadapter/vehicle/res/symbols/LEDGreen.gif")));
connectedButton.setEnabled(false);
connectionSettingsPanel.add(connectedButton, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0,
GridBagConstraints.WEST, GridBagConstraints.NONE,
new Insets(0, 0, 0, 0), 0, 0));
//---- portLabel ----
portLabel.setText(bundle.getString("VehicleTcpPort"));
connectionSettingsPanel.add(portLabel, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0,
GridBagConstraints.EAST, GridBagConstraints.NONE,
new Insets(0, 3, 0, 3), 0, 0));
//---- portTextField ----
portTextField.setDocument(new PlainDocument(){
@Override
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException {
try {
String oldString = getText(0, getLength());
StringBuilder newString = new StringBuilder(oldString);
newString.insert(offs, str);
int newValue = Integer.parseInt(newString.toString());
if (newValue >= 1 && newValue <= 65535) {
super.insertString(offs, str, a);
}
}
catch(NumberFormatException e) { }
}
}
);
portTextField.setColumns(6);
portTextField.setText("XXXXX");
connectionSettingsPanel.add(portTextField, new GridBagConstraints(2, 1, 2, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL,
new Insets(0, 0, 3, 3), 0, 0));
//---- activeButton ----
activeButton.setIcon(new ImageIcon(getClass().getResource("/de/fraunhofer/iml/opentcs/example/commadapter/vehicle/res/symbols/LEDGray.gif")));
activeButton.setText(bundle.getString("ControlPanel.AdapterActive"));
activeButton.setBorderPainted(false);
activeButton.setDisabledIcon(new ImageIcon(getClass().getResource("/de/fraunhofer/iml/opentcs/example/commadapter/vehicle/res/symbols/LEDRed.gif")));
activeButton.setDisabledSelectedIcon(new ImageIcon(getClass().getResource("/de/fraunhofer/iml/opentcs/example/commadapter/vehicle/res/symbols/LEDGreen.gif")));
activeButton.setEnabled(false);
connectionSettingsPanel.add(activeButton, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0,
GridBagConstraints.WEST, GridBagConstraints.NONE,
new Insets(0, 0, 0, 0), 0, 0));
//---- aliveTimeoutLable ----
aliveTimeoutLable.setText(bundle.getString("ControlPanel.IdleAfter"));
connectionSettingsPanel.add(aliveTimeoutLable, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0,
GridBagConstraints.EAST, GridBagConstraints.NONE,
new Insets(0, 3, 0, 3), 0, 0));
//---- aliveTimeoutTextField ----
aliveTimeoutTextField.setDocument(new PlainDocument(){
@Override
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException {
try {
Integer.parseInt(str);
super.insertString(offs, str, a);
}
catch(NumberFormatException e) { }
}
});
aliveTimeoutTextField.setColumns(6);
aliveTimeoutTextField.setText("XXXXX");
connectionSettingsPanel.add(aliveTimeoutTextField, new GridBagConstraints(2, 2, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL,
new Insets(0, 0, 3, 3), 0, 0));
//---- disconnectOnTimeoutChkBox ----
disconnectOnTimeoutChkBox.setText(bundle.getString("ControlPanel.DisconnectOnTimeout"));
disconnectOnTimeoutChkBox.addActionListener(e -> disconnectOnTimeoutChkBoxActionPerformed(e));
connectionSettingsPanel.add(disconnectOnTimeoutChkBox, new GridBagConstraints(0, 3, 2, 1, 0.0, 0.0,
GridBagConstraints.WEST, GridBagConstraints.NONE,
new Insets(0, 0, 0, 0), 0, 0));
//---- reconnectOnConnectionLossChkBox ----
reconnectOnConnectionLossChkBox.setText(bundle.getString("ControlPanel.DisconnectOnConnectionLoss"));
reconnectOnConnectionLossChkBox.addActionListener(e -> reconnectOnConnectionLossChkBoxActionPerformed(e));
connectionSettingsPanel.add(reconnectOnConnectionLossChkBox, new GridBagConstraints(0, 4, 2, 1, 0.0, 0.0,
GridBagConstraints.WEST, GridBagConstraints.NONE,
new Insets(0, 0, 0, 0), 0, 0));
//---- enableLoggingChkBox ----
enableLoggingChkBox.setText(bundle.getString("ControlPanel.EnableLogging"));
enableLoggingChkBox.addActionListener(e -> enableLoggingChkBoxActionPerformed(e));
connectionSettingsPanel.add(enableLoggingChkBox, new GridBagConstraints(0, 5, 2, 1, 0.0, 0.0,
GridBagConstraints.WEST, GridBagConstraints.NONE,
new Insets(0, 0, 0, 0), 0, 0));
}
//======== setOrderPanel ========
{
setOrderPanel.setBorder(new TitledBorder(null, "New order telegram", TitledBorder.LEADING, TitledBorder.DEFAULT_POSITION,
new Font("Tahoma", Font.BOLD, 11)));
setOrderPanel.setLayout(new GridBagLayout());
//---- destinationLabel ----
destinationLabel.setText(bundle.getString("OrderDestination"));
setOrderPanel.add(destinationLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0,
GridBagConstraints.EAST, GridBagConstraints.NONE,
new Insets(0, 3, 0, 3), 0, 0));
//---- destinationComboBox ----
destinationComboBox.setEditor(new TCSObjectComboBoxEditor());
destinationComboBox.setRenderer(new StringListCellRenderer<Point>(point -> point.getName()));
destinationComboBox.setEditable(true);
setOrderPanel.add(destinationComboBox, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0,
GridBagConstraints.WEST, GridBagConstraints.NONE,
new Insets(0, 0, 3, 3), 0, 0));
//---- actionLabel ----
actionLabel.setText(bundle.getString("OrderAction"));
setOrderPanel.add(actionLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0,
GridBagConstraints.EAST, GridBagConstraints.NONE,
new Insets(0, 3, 0, 3), 0, 0));
setOrderPanel.add(actionComboBox, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0,
GridBagConstraints.WEST, GridBagConstraints.NONE,
new Insets(0, 0, 3, 3), 0, 0));
//---- orderIdLabel ----
orderIdLabel.setText(bundle.getString("OrderID"));
setOrderPanel.add(orderIdLabel, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0,
GridBagConstraints.EAST, GridBagConstraints.NONE,
new Insets(0, 3, 0, 3), 0, 0));
//---- orderIdTextField ----
orderIdTextField.setColumns(6);
orderIdTextField.setText("1");
setOrderPanel.add(orderIdTextField, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0,
GridBagConstraints.WEST, GridBagConstraints.NONE,
new Insets(0, 0, 3, 3), 0, 0));
//---- sendOrderButton ----
sendOrderButton.setText(bundle.getString("SendNewOrder"));
sendOrderButton.addActionListener(e -> sendOrderButtonActionPerformed(e));
setOrderPanel.add(sendOrderButton, new GridBagConstraints(0, 3, 2, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL,
new Insets(0, 3, 3, 3), 0, 0));
}
//======== repeatOrderPanel ========
{
repeatOrderPanel.setBorder(new TitledBorder(null, "Last orders sent to vehicle", TitledBorder.LEADING, TitledBorder.DEFAULT_POSITION,
new Font("Tahoma", Font.BOLD, 11)));
repeatOrderPanel.setMinimumSize(new Dimension(199, 170));
//======== lastOrdersScrollPane ========
{
//---- lastOrdersList ----
lastOrdersList.setModel(lastOrderListModel);
lastOrdersList.setCellRenderer(new OrderListCellRenderer());
lastOrdersList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
lastOrdersScrollPane.setViewportView(lastOrdersList);
}
//======== lastOrderDetailsPanel ========
{
lastOrderDetailsPanel.setLayout(new GridBagLayout());
//---- destinationLabel1 ----
destinationLabel1.setText(bundle.getString("OrderDestination"));
lastOrderDetailsPanel.add(destinationLabel1, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0,
GridBagConstraints.EAST, GridBagConstraints.NONE,
new Insets(0, 3, 0, 3), 0, 0));
//---- lastDestinationTextField ----
lastDestinationTextField.setEditable(false);
lastDestinationTextField.setColumns(12);
lastDestinationTextField.setHorizontalAlignment(SwingConstants.RIGHT);
lastOrderDetailsPanel.add(lastDestinationTextField, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0,
GridBagConstraints.WEST, GridBagConstraints.NONE,
new Insets(0, 0, 3, 3), 0, 0));
//---- actionLabel1 ----
actionLabel1.setText(bundle.getString("OrderAction"));
lastOrderDetailsPanel.add(actionLabel1, new GridBagConstraints(0, 9, 1, 1, 0.0, 0.0,
GridBagConstraints.EAST, GridBagConstraints.NONE,
new Insets(0, 3, 0, 3), 0, 0));
//---- lastActionTextField ----
lastActionTextField.setEditable(false);
lastActionTextField.setColumns(12);
lastActionTextField.setHorizontalAlignment(SwingConstants.RIGHT);
lastOrderDetailsPanel.add(lastActionTextField, new GridBagConstraints(1, 9, 1, 1, 0.0, 0.0,
GridBagConstraints.WEST, GridBagConstraints.NONE,
new Insets(0, 0, 3, 3), 0, 0));
//---- lastOrderIdLabel ----
lastOrderIdLabel.setText(bundle.getString("OrderID"));
lastOrderDetailsPanel.add(lastOrderIdLabel, new GridBagConstraints(0, 11, 1, 1, 0.0, 0.0,
GridBagConstraints.EAST, GridBagConstraints.NONE,
new Insets(0, 3, 0, 3), 0, 0));
//---- lastOrderIdTextField ----
lastOrderIdTextField.setEditable(false);
lastOrderIdTextField.setColumns(6);
lastOrderDetailsPanel.add(lastOrderIdTextField, new GridBagConstraints(1, 11, 1, 1, 0.0, 0.0,
GridBagConstraints.WEST, GridBagConstraints.NONE,
new Insets(0, 0, 3, 3), 0, 0));
//---- repeatLastOrderButton ----
repeatLastOrderButton.setText(bundle.getString("SendLastOrderAgain"));
repeatLastOrderButton.setEnabled(false);
repeatLastOrderButton.addActionListener(e -> repeatLastOrderButtonActionPerformed(e));
lastOrderDetailsPanel.add(repeatLastOrderButton, new GridBagConstraints(0, 12, 2, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL,
new Insets(0, 3, 3, 3), 0, 0));
}
GroupLayout repeatOrderPanelLayout = new GroupLayout(repeatOrderPanel);
repeatOrderPanel.setLayout(repeatOrderPanelLayout);
repeatOrderPanelLayout.setHorizontalGroup(
repeatOrderPanelLayout.createParallelGroup()
.addGroup(repeatOrderPanelLayout.createSequentialGroup()
.addComponent(lastOrdersScrollPane, GroupLayout.PREFERRED_SIZE, 166, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lastOrderDetailsPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0))
);
repeatOrderPanelLayout.setVerticalGroup(
repeatOrderPanelLayout.createParallelGroup()
.addGroup(repeatOrderPanelLayout.createSequentialGroup()
.addGroup(repeatOrderPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING, false)
.addComponent(lastOrdersScrollPane)
.addComponent(lastOrderDetailsPanel, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, 0))
);
}
GroupLayout layout = new GroupLayout(this);
setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup()
.addGroup(layout.createSequentialGroup()
.addGap(0, 0, 0)
.addGroup(layout.createParallelGroup()
.addGroup(layout.createSequentialGroup()
.addComponent(connectionSettingsPanel, GroupLayout.PREFERRED_SIZE, 400, GroupLayout.PREFERRED_SIZE)
.addGap(6, 6, 6)
.addComponent(setOrderPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addComponent(repeatOrderPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, 0))
);
layout.setVerticalGroup(
layout.createParallelGroup()
.addGroup(layout.createSequentialGroup()
.addGap(0, 0, 0)
.addGroup(layout.createParallelGroup()
.addComponent(connectionSettingsPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(setOrderPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGap(6, 6, 6)
.addComponent(repeatOrderPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
// JFormDesigner - End of component initialization //GEN-END:initComponents
}
// JFormDesigner - Variables declaration - DO NOT MODIFY //GEN-BEGIN:variables
// Generated using JFormDesigner Evaluation license - <NAME>
private JPanel connectionSettingsPanel;
private JCheckBox enableAdapterCheckBox;
private JLabel hostLabel;
private JTextField hostTextField;
private JButton connectedButton;
private JLabel portLabel;
private JTextField portTextField;
private JButton activeButton;
private JLabel aliveTimeoutLable;
private JTextField aliveTimeoutTextField;
private JCheckBox disconnectOnTimeoutChkBox;
private JCheckBox reconnectOnConnectionLossChkBox;
private JCheckBox enableLoggingChkBox;
private JPanel setOrderPanel;
private JLabel destinationLabel;
private JComboBox<Point> destinationComboBox;
private JLabel actionLabel;
private JComboBox<OrderRequest.OrderAction> actionComboBox;
private JLabel orderIdLabel;
private JTextField orderIdTextField;
private JButton sendOrderButton;
private JPanel repeatOrderPanel;
private JScrollPane lastOrdersScrollPane;
private JList<OrderRequest> lastOrdersList;
private JPanel lastOrderDetailsPanel;
private JLabel destinationLabel1;
private JTextField lastDestinationTextField;
private JLabel actionLabel1;
private JTextField lastActionTextField;
private JLabel lastOrderIdLabel;
private JTextField lastOrderIdTextField;
private JButton repeatLastOrderButton;
// JFormDesigner - End of variables declaration //GEN-END:variables
}
| 26,167 | 0.635822 | 0.616613 | 514 | 49.943581 | 35.353397 | 174 | false | false | 0 | 0 | 0 | 0 | 75 | 0.016956 | 1.367704 | false | false | 5 |
4f880a769913279fabe7148fa373be2a2841006d | 180,388,655,881 | 39f14d34e5c5e97c95cb569ac477336be74292c1 | /src/main/java/com/company/project/service/ReceivedDetailService.java | 8c0c88da94eb16c287dc081e04dbf05203c9bdd2 | []
| no_license | hz31831368/spring-boot-api-project-seed | https://github.com/hz31831368/spring-boot-api-project-seed | 2c59ef176900ca619273ebec50c614bc49ea3c51 | 5005c2f87cd16ddf8114d1526e315c894db51df4 | refs/heads/master | 2021-01-02T08:25:04.413000 | 2017-08-01T13:52:11 | 2017-08-01T13:52:11 | 99,006,424 | 0 | 0 | null | true | 2017-08-01T13:50:00 | 2017-08-01T13:50:00 | 2017-08-01T13:00:01 | 2017-07-24T10:12:38 | 60 | 0 | 0 | 0 | null | null | null | package com.company.project.service;
import com.company.project.model.ReceivedDetail;
import com.company.project.core.Service;
/**
* Created by CodeGenerator on 2017/08/01.
*/
public interface ReceivedDetailService extends Service<ReceivedDetail> {
}
| UTF-8 | Java | 256 | java | ReceivedDetailService.java | Java | [
{
"context": ".company.project.core.Service;\n\n\n/**\n * Created by CodeGenerator on 2017/08/01.\n */\npublic interface ReceivedDetai",
"end": 160,
"score": 0.9933990240097046,
"start": 147,
"tag": "USERNAME",
"value": "CodeGenerator"
}
]
| null | []
| package com.company.project.service;
import com.company.project.model.ReceivedDetail;
import com.company.project.core.Service;
/**
* Created by CodeGenerator on 2017/08/01.
*/
public interface ReceivedDetailService extends Service<ReceivedDetail> {
}
| 256 | 0.792969 | 0.761719 | 11 | 22.272728 | 24.698513 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.272727 | false | false | 5 |
7e5ad43e05735a2507f6d23b82107e80fe19d310 | 27,410,481,284,887 | 822e8268fb17256dd3b2aa71eb81323a8a66b27f | /gemfirexd/core/src/main/java/com/pivotal/gemfirexd/internal/impl/store/access/heap/Heap_v10_2.java | b49a8834f83263c0fee393d9bd62d21ea45f4003 | [
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"Apache-1.1",
"GPL-2.0-only",
"Plexus",
"JSON",
"MIT",
"Apache-2.0",
"BSD-2-Clause",
"LicenseRef-scancode-generic-export-compliance",
"LicenseRef-scancode-generic-cla"
]
| permissive | gemxd/gemfirexd-oss | https://github.com/gemxd/gemfirexd-oss | 3d096b2de5cd49f787e65d4ee65bb51cd35cab4b | d89cad2b075df92fc3acce09b9f8dc7b30be2445 | refs/heads/master | 2020-12-28T04:41:41.641000 | 2020-11-18T03:39:41 | 2020-11-18T03:39:41 | 48,769,190 | 13 | 9 | Apache-2.0 | false | 2018-10-12T07:42:55 | 2015-12-29T22:07:26 | 2018-06-17T22:03:24 | 2018-10-11T16:53:51 | 112,345 | 11 | 19 | 0 | Java | false | null | /*
Derby - Class com.pivotal.gemfirexd.internal.impl.store.access.btree.index.B2I
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to you under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.pivotal.gemfirexd.internal.impl.store.access.heap;
import com.pivotal.gemfirexd.internal.shared.common.StoredFormatIds;
import java.io.IOException;
import java.io.ObjectOutput;
import java.io.ObjectInput;
import java.lang.ClassNotFoundException;
/**
* @format_id ACCESS_HEAP_V2_ID
*
* @purpose The tag that describes the on disk representation of the Heap
* conglomerate object. Access contains no "directory" of
* conglomerate information. In order to bootstrap opening a file
* it encodes the factory that can open the conglomerate in the
* conglomerate id itself. There exists a single HeapFactory which
* must be able to read all heap format id's.
*
* This format was used for all Derby database Heap's in version
* 10.2 and previous versions.
*
* @upgrade The format id of this object is currently always read from disk
* as the first field of the conglomerate itself. A bootstrap
* problem exists as we don't know the format id of the heap
* until we are in the "middle" of reading the Heap. Thus the
* base Heap implementation must be able to read and write
* all formats based on the reading the
* "format_of_this_conglomerate".
*
* soft upgrade to ACCESS_HEAP_V3_ID:
* read:
* old format is readable by current Heap implementation,
* with automatic in memory creation of default collation
* id needed by new format. No code other than
* readExternal and writeExternal need know about old format.
* write:
* will never write out new format id in soft upgrade mode.
* Code in readExternal and writeExternal handles writing
* correct version. Code in the factory handles making
* sure new conglomerates use the Heap_v10_2 class
* that will write out old format info.
*
* hard upgrade to ACCESS_HEAP_V3_ID:
* read:
* old format is readable by current Heap implementation,
* with automatic in memory creation of default collation
* id needed by new format.
* write:
* Only "lazy" upgrade will happen. New format will only
* get written for new conglomerate created after the
* upgrade. Old conglomerates continue to be handled the
* same as soft upgrade.
*
* @disk_layout
* format_of_this_conlgomerate(byte[])
* containerid(long)
* segmentid(int)
* number_of_columns(int)
* array_of_format_ids(byte[][])
**/
public class Heap_v10_2 extends Heap
{
/**
* No arg constructor, required by Formatable.
**/
public Heap_v10_2()
{
super();
}
/**************************************************************************
* Public Methods required by Storable interface, implies
* Externalizable, TypedFormat:
**************************************************************************
*/
/**
* Return my format identifier.
* <p>
* This identifier was used for Heap in all Derby versions prior to 10.3.
* Databases hard upgraded to a version 10.3 and later will write the new
* format, see Heap. Databases created in 10.3 and later will also write
* the new format, see Heap.
*
* @see com.pivotal.gemfirexd.internal.iapi.services.io.TypedFormat#getTypeFormatId
**/
public int getTypeFormatId()
{
// return identifier used for Heap in all derby versions prior to 10.3
return StoredFormatIds.ACCESS_HEAP_V2_ID;
}
/**
* Store the stored representation of the column value in the
* stream.
* <p>
* For more detailed description of the format see documentation
* at top of file.
*
* @see java.io.Externalizable#writeExternal
**/
public void writeExternal(ObjectOutput out) throws IOException
{
super.writeExternal_v10_2(out);
}
}
| UTF-8 | Java | 5,133 | java | Heap_v10_2.java | Java | []
| null | []
| /*
Derby - Class com.pivotal.gemfirexd.internal.impl.store.access.btree.index.B2I
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to you under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.pivotal.gemfirexd.internal.impl.store.access.heap;
import com.pivotal.gemfirexd.internal.shared.common.StoredFormatIds;
import java.io.IOException;
import java.io.ObjectOutput;
import java.io.ObjectInput;
import java.lang.ClassNotFoundException;
/**
* @format_id ACCESS_HEAP_V2_ID
*
* @purpose The tag that describes the on disk representation of the Heap
* conglomerate object. Access contains no "directory" of
* conglomerate information. In order to bootstrap opening a file
* it encodes the factory that can open the conglomerate in the
* conglomerate id itself. There exists a single HeapFactory which
* must be able to read all heap format id's.
*
* This format was used for all Derby database Heap's in version
* 10.2 and previous versions.
*
* @upgrade The format id of this object is currently always read from disk
* as the first field of the conglomerate itself. A bootstrap
* problem exists as we don't know the format id of the heap
* until we are in the "middle" of reading the Heap. Thus the
* base Heap implementation must be able to read and write
* all formats based on the reading the
* "format_of_this_conglomerate".
*
* soft upgrade to ACCESS_HEAP_V3_ID:
* read:
* old format is readable by current Heap implementation,
* with automatic in memory creation of default collation
* id needed by new format. No code other than
* readExternal and writeExternal need know about old format.
* write:
* will never write out new format id in soft upgrade mode.
* Code in readExternal and writeExternal handles writing
* correct version. Code in the factory handles making
* sure new conglomerates use the Heap_v10_2 class
* that will write out old format info.
*
* hard upgrade to ACCESS_HEAP_V3_ID:
* read:
* old format is readable by current Heap implementation,
* with automatic in memory creation of default collation
* id needed by new format.
* write:
* Only "lazy" upgrade will happen. New format will only
* get written for new conglomerate created after the
* upgrade. Old conglomerates continue to be handled the
* same as soft upgrade.
*
* @disk_layout
* format_of_this_conlgomerate(byte[])
* containerid(long)
* segmentid(int)
* number_of_columns(int)
* array_of_format_ids(byte[][])
**/
public class Heap_v10_2 extends Heap
{
/**
* No arg constructor, required by Formatable.
**/
public Heap_v10_2()
{
super();
}
/**************************************************************************
* Public Methods required by Storable interface, implies
* Externalizable, TypedFormat:
**************************************************************************
*/
/**
* Return my format identifier.
* <p>
* This identifier was used for Heap in all Derby versions prior to 10.3.
* Databases hard upgraded to a version 10.3 and later will write the new
* format, see Heap. Databases created in 10.3 and later will also write
* the new format, see Heap.
*
* @see com.pivotal.gemfirexd.internal.iapi.services.io.TypedFormat#getTypeFormatId
**/
public int getTypeFormatId()
{
// return identifier used for Heap in all derby versions prior to 10.3
return StoredFormatIds.ACCESS_HEAP_V2_ID;
}
/**
* Store the stored representation of the column value in the
* stream.
* <p>
* For more detailed description of the format see documentation
* at top of file.
*
* @see java.io.Externalizable#writeExternal
**/
public void writeExternal(ObjectOutput out) throws IOException
{
super.writeExternal_v10_2(out);
}
}
| 5,133 | 0.618936 | 0.611923 | 136 | 36.742645 | 30.619581 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.213235 | false | false | 5 |
8ed1871baf58ab5575a993d5fae95a12e213fb6c | 32,590,211,855,861 | 9dea961c5d203219a683599b1faa94e134a7dac6 | /src/main/java/jp/winschool/spring/test10/Test10Controller.java | 671d0c773182e647f994acb704ff8933745a0728 | []
| no_license | y-akuzawa/SampleTest10 | https://github.com/y-akuzawa/SampleTest10 | f2bb6d59bcd61a18e82712da0140cbdab589c793 | 0a69f54ac5d96a3fb7b822767df4c6585302cb40 | refs/heads/master | 2022-11-07T22:11:07.842000 | 2020-06-24T02:23:15 | 2020-06-24T02:23:15 | 274,549,170 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package jp.winschool.spring.test10;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class Test10Controller {
@Autowired
private JdbcTemplate jdbcTemplate;
@GetMapping("/")
public String index(Model model) {
String sql = "SELECT id, name, mail, age, gender, contents FROM inquiry";
RowMapper<Inquiry> rowMapper = new RowMapper<Inquiry>() {
@Override
public Inquiry mapRow(ResultSet rs, int rowNum) throws SQLException {
Inquiry inquiry = new Inquiry();
inquiry.setId(rs.getInt("id"));
inquiry.setName(rs.getString("name"));
inquiry.setMail(rs.getString("mail"));
inquiry.setAge(rs.getInt("age"));
inquiry.setGender(rs.getString("gender"));
inquiry.setContents(rs.getString("contents"));
return inquiry;
}
};
List<Inquiry> inquiries = jdbcTemplate.query(sql, rowMapper);
model.addAttribute("inquiries", inquiries);
return "index";
}
}
| UTF-8 | Java | 1,328 | java | Test10Controller.java | Java | []
| null | []
| package jp.winschool.spring.test10;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class Test10Controller {
@Autowired
private JdbcTemplate jdbcTemplate;
@GetMapping("/")
public String index(Model model) {
String sql = "SELECT id, name, mail, age, gender, contents FROM inquiry";
RowMapper<Inquiry> rowMapper = new RowMapper<Inquiry>() {
@Override
public Inquiry mapRow(ResultSet rs, int rowNum) throws SQLException {
Inquiry inquiry = new Inquiry();
inquiry.setId(rs.getInt("id"));
inquiry.setName(rs.getString("name"));
inquiry.setMail(rs.getString("mail"));
inquiry.setAge(rs.getInt("age"));
inquiry.setGender(rs.getString("gender"));
inquiry.setContents(rs.getString("contents"));
return inquiry;
}
};
List<Inquiry> inquiries = jdbcTemplate.query(sql, rowMapper);
model.addAttribute("inquiries", inquiries);
return "index";
}
}
| 1,328 | 0.71009 | 0.707078 | 47 | 26.25532 | 22.417192 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.148936 | false | false | 5 |
200e17669d56cea2b4819bdfc60ca2c8564d092d | 2,877,628,144,749 | f29c606def1f089a33e3321b05e31a7964d722e2 | /xfbManage_ym/src/com/emagsoftware/xfb/service/impl/OrderInfoServiceImpl.java | 9a8163262348502d748b8a1f186022b2052fce0c | []
| no_license | luckminghua/gitskill | https://github.com/luckminghua/gitskill | b942691f2ac49cb271155d4347593bf15bac9e05 | 0571fb514227eb6cbb4a51468d5972e3b3efcbcf | refs/heads/master | 2016-09-22T08:02:07.307000 | 2016-07-14T02:51:06 | 2016-07-14T02:51:06 | 63,292,370 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.emagsoftware.xfb.service.impl;
import com.emagsoftware.frame.utils.SystemConstant;
import com.emagsoftware.xfb.dao.LogDao;
import com.emagsoftware.xfb.dao.OrderInfoDao;
import com.emagsoftware.xfb.pojo.OrderInfo;
import com.emagsoftware.xfb.pojo.TSysLog;
import com.emagsoftware.xfb.service.OrderInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
* Created with IntelliJ IDEA.
* User: Administrator
* Date: 15-4-1
* Time: 上午10:39
* To change this template use File | Settings | File Templates.
*/
@Service
public class OrderInfoServiceImpl implements OrderInfoService {
@Autowired
private OrderInfoDao orderInfoDao;
@Autowired
private LogDao logDao;
public OrderInfo getOrderById(String id) throws Exception {
return orderInfoDao.getOrderById(id);
}
public void updateOrderInfo(OrderInfo orderInfo) throws Exception {
logDao.sysLog(new TSysLog(SystemConstant.LOG_TYPE_UPDATE, "修改订单【order:" + orderInfo.toString() + "】"));
orderInfoDao.updateOrderInfo(orderInfo);
}
@Override
public int getOrderListCount(Map<String, Object> params) throws Exception {
return orderInfoDao.getOrderListCount(params);
}
@Override
public List<OrderInfo> getOrderList(Map<String, Object> params) throws Exception {
return orderInfoDao.getOrderList(params);
}
@Override
public void updateOrderPayStatus(OrderInfo orderInfo) throws Exception {
// TODO Auto-generated method stub
orderInfoDao.updateOrderPayStatus(orderInfo);
}
@Override
public float getServiceCharge(String orderId) throws Exception {
OrderInfo order=orderInfoDao.getServiceCharge(orderId);
float service=(float) ((order.getUseLimit())*(order.getAllStageAmount())*(order.getStagePlan()*0.01));
return service;
}
}
| UTF-8 | Java | 1,962 | java | OrderInfoServiceImpl.java | Java | [
{
"context": ".Map;\n\n/**\n * Created with IntelliJ IDEA.\n * User: Administrator\n * Date: 15-4-1\n * Time: 上午10:39\n * To change thi",
"end": 536,
"score": 0.5621221661567688,
"start": 523,
"tag": "NAME",
"value": "Administrator"
}
]
| null | []
| package com.emagsoftware.xfb.service.impl;
import com.emagsoftware.frame.utils.SystemConstant;
import com.emagsoftware.xfb.dao.LogDao;
import com.emagsoftware.xfb.dao.OrderInfoDao;
import com.emagsoftware.xfb.pojo.OrderInfo;
import com.emagsoftware.xfb.pojo.TSysLog;
import com.emagsoftware.xfb.service.OrderInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
* Created with IntelliJ IDEA.
* User: Administrator
* Date: 15-4-1
* Time: 上午10:39
* To change this template use File | Settings | File Templates.
*/
@Service
public class OrderInfoServiceImpl implements OrderInfoService {
@Autowired
private OrderInfoDao orderInfoDao;
@Autowired
private LogDao logDao;
public OrderInfo getOrderById(String id) throws Exception {
return orderInfoDao.getOrderById(id);
}
public void updateOrderInfo(OrderInfo orderInfo) throws Exception {
logDao.sysLog(new TSysLog(SystemConstant.LOG_TYPE_UPDATE, "修改订单【order:" + orderInfo.toString() + "】"));
orderInfoDao.updateOrderInfo(orderInfo);
}
@Override
public int getOrderListCount(Map<String, Object> params) throws Exception {
return orderInfoDao.getOrderListCount(params);
}
@Override
public List<OrderInfo> getOrderList(Map<String, Object> params) throws Exception {
return orderInfoDao.getOrderList(params);
}
@Override
public void updateOrderPayStatus(OrderInfo orderInfo) throws Exception {
// TODO Auto-generated method stub
orderInfoDao.updateOrderPayStatus(orderInfo);
}
@Override
public float getServiceCharge(String orderId) throws Exception {
OrderInfo order=orderInfoDao.getServiceCharge(orderId);
float service=(float) ((order.getUseLimit())*(order.getAllStageAmount())*(order.getStagePlan()*0.01));
return service;
}
}
| 1,962 | 0.747428 | 0.74177 | 66 | 28.454546 | 28.361937 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.712121 | false | false | 5 |
794ac7afbe9559906373e3ec5db10cd9288095de | 28,965,259,448,966 | 7106882efb61ccdf5141ddec39b2b340a14e6300 | /src/main/java/com/wxx/user_role/service/RoleService.java | fc866136fa18333486cedc0bed908928502238b9 | []
| no_license | web-wu/user_role-configuration | https://github.com/web-wu/user_role-configuration | a1f78576b574c38a80b3c948198d90f6d4c25b95 | d79d61f7ad7806ae0926475c8fb0c704803431f1 | refs/heads/master | 2023-03-29T05:02:02.807000 | 2021-03-30T09:18:35 | 2021-03-30T09:18:35 | 352,939,455 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.wxx.user_role.service;
import com.wxx.user_role.entity.Role;
import java.util.List;
public interface RoleService {
List<Role> getRoleList();
void addRole(Role role);
}
| UTF-8 | Java | 192 | java | RoleService.java | Java | []
| null | []
| package com.wxx.user_role.service;
import com.wxx.user_role.entity.Role;
import java.util.List;
public interface RoleService {
List<Role> getRoleList();
void addRole(Role role);
}
| 192 | 0.729167 | 0.729167 | 11 | 16.454546 | 15.245647 | 37 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false | 5 |
48a5ca6090fef583d1a215fe93277122b7769256 | 29,764,123,406,261 | add07ece4c9580bbf0e60cae14ae2ca976277805 | /blogPessoal/src/main/java/com/generation/blogPessoal/Security/BasicSecurityConfig.java | ddaeb9a05a61b38b7f12e8e715aea31353c15d24 | [
"MIT"
]
| permissive | diegoalonso231/Blog-Pessoal | https://github.com/diegoalonso231/Blog-Pessoal | 149b3683202d14c4a983f719ab0ab3e7de9012cc | 89cb4b4167842c0a162ce7d56db0f400a6aadc91 | refs/heads/main | 2023-04-20T20:49:59.810000 | 2021-05-11T13:10:47 | 2021-05-11T13:10:47 | 364,374,748 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.generation.blogPessoal.Security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@EnableWebSecurity
public class BasicSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService; //injeção de WebSecurityConfigurerAdapter
/* METODO PARA SOBRESCREVER O PADRAO DA CLASSE 'UserDetailsService' */
@Override //throws tratativa de erros.
protected void configure(AuthenticationManagerBuilder auth)throws Exception{
auth.userDetailsService(userDetailsService);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception{
http.authorizeRequests()
.antMatchers("/usuarios/logar").permitAll() // <--- libera esses end points para o client ter um acesso sem ter um token.
.antMatchers("/usuarios/cadastrar").permitAll() // <--- libera esses end points para o client ter um acesso sem ter um token.
.anyRequest().authenticated() /* nao deixar acessar os demais endpoints sem estarem com um token */
.and().httpBasic() /* trabalha com uma seguranca basica */
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) /* STATELESS -> nao salva a secao */
.and().cors()
.and().csrf().disable(); /* desabilita as configuracoes padroes */
}
}
| UTF-8 | Java | 2,110 | java | BasicSecurityConfig.java | Java | []
| null | []
| package com.generation.blogPessoal.Security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@EnableWebSecurity
public class BasicSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService; //injeção de WebSecurityConfigurerAdapter
/* METODO PARA SOBRESCREVER O PADRAO DA CLASSE 'UserDetailsService' */
@Override //throws tratativa de erros.
protected void configure(AuthenticationManagerBuilder auth)throws Exception{
auth.userDetailsService(userDetailsService);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception{
http.authorizeRequests()
.antMatchers("/usuarios/logar").permitAll() // <--- libera esses end points para o client ter um acesso sem ter um token.
.antMatchers("/usuarios/cadastrar").permitAll() // <--- libera esses end points para o client ter um acesso sem ter um token.
.anyRequest().authenticated() /* nao deixar acessar os demais endpoints sem estarem com um token */
.and().httpBasic() /* trabalha com uma seguranca basica */
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) /* STATELESS -> nao salva a secao */
.and().cors()
.and().csrf().disable(); /* desabilita as configuracoes padroes */
}
}
| 2,110 | 0.804554 | 0.804554 | 44 | 46.909092 | 39.772545 | 128 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.5 | false | false | 5 |
c3c6d1aa55ed4ba8e7ba3af85a48b25beeb58d57 | 28,089,086,123,106 | b20ea3883b7e26d023d2c6d9f7a73fdc400e2062 | /src/edu/uic/cs494/AsynchronousVersion/solution/SolutionItem.java | 1251f9463efe03b2a1c9aa1726d219872ce9261c | []
| no_license | RoshanSharma1/Warehouse-Management-system | https://github.com/RoshanSharma1/Warehouse-Management-system | 8d0783219b8b834b65cf2b593f4653c1e45231bd | 5fafa2f91a61aae3bc724f2b0e828a0f7332f81c | refs/heads/master | 2023-05-27T15:39:53.517000 | 2021-06-07T06:58:25 | 2021-06-07T06:58:25 | 370,513,027 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.uic.cs494.AsynchronousVersion.solution;
import edu.uic.cs494.AsynchronousVersion.Item;
public class SolutionItem implements Item {
public String description;
public SolutionItem(String description) {
this.description = description;
}
}
| UTF-8 | Java | 272 | java | SolutionItem.java | Java | []
| null | []
| package edu.uic.cs494.AsynchronousVersion.solution;
import edu.uic.cs494.AsynchronousVersion.Item;
public class SolutionItem implements Item {
public String description;
public SolutionItem(String description) {
this.description = description;
}
}
| 272 | 0.757353 | 0.735294 | 11 | 23.727272 | 21.119102 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.363636 | false | false | 5 |
ca135ac1a01718741dfb9f851e4c663be9393baa | 7,052,336,342,624 | 30c94454387d41dc68a5c96ad70158b0cea2a218 | /comparator.java | 6854e59d9d9dbd0bc8f671d48a9a76fe2aa4f329 | []
| no_license | soplinger/lesson44_comparables | https://github.com/soplinger/lesson44_comparables | 3f9e646982993ef4552fc727253a335b0f8c2a28 | 6f865071c301ba674545a3c9dd358ecefe0e242a | refs/heads/master | 2020-05-05T01:39:16.502000 | 2019-04-05T02:53:10 | 2019-04-05T02:53:10 | 179,610,355 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.company;
import java.util.Comparator;
public class comparator implements Comparator {
public int compare(Object first, Object second) {
int number;
BankAccount first1 = (BankAccount) first;
BankAccount second1 = (BankAccount) second;
if (first1.balance < second1.balance)
number = -1;
else
if (first1.balance > second1.balance)
number = 1;
else
number = 0;
return number;
}
}
| UTF-8 | Java | 511 | java | comparator.java | Java | []
| null | []
| package com.company;
import java.util.Comparator;
public class comparator implements Comparator {
public int compare(Object first, Object second) {
int number;
BankAccount first1 = (BankAccount) first;
BankAccount second1 = (BankAccount) second;
if (first1.balance < second1.balance)
number = -1;
else
if (first1.balance > second1.balance)
number = 1;
else
number = 0;
return number;
}
}
| 511 | 0.581213 | 0.563601 | 23 | 21.217392 | 19.074127 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.434783 | false | false | 5 |
b961821d34aac028cccbf592ac300cbf5ed89027 | 6,116,033,465,890 | 664e232422c758e4f9ad08d2ab5438b0e22a6f8e | /master_data_service-ejb/src/main/java/com/dsv/road/masterdata/model/CustomerOrderProfileKey.java | 05271d0a66e67119ff1882cba3136fe2e114fd9f | []
| no_license | Verholt/Java-code | https://github.com/Verholt/Java-code | fbc6ab022ca709a34ddeb20f74a00a904b092421 | 0d7d8de9e911109c127bf5bfb0b02d3b9e42e336 | refs/heads/master | 2021-05-10T09:08:32.463000 | 2018-01-25T13:38:51 | 2018-01-25T13:38:51 | 118,915,852 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.dsv.road.masterdata.model;
import java.sql.Timestamp;
import javax.interceptor.Interceptors;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import com.dsv.shared.logger.LoggerInterceptor;
@Entity
@NamedQueries({
@NamedQuery(name = CustomerOrderProfileKey.FIND_ALL_PROFILE_KEYS_NAMED_QUERY, query = "SELECT b FROM CustomerOrderProfileKey b"),
@NamedQuery(name = CustomerOrderProfileKey.SEARCH_PROFILE_KEYS_NAMED_QUERY, query = "SELECT b FROM CustomerOrderProfileKey b WHERE UPPER(b.key) LIKE :" + CustomerOrderProfileKey.FILTER_QUERY_PARAM)
})
@Table(name = "CO_PROFILE_KEY")
@Interceptors(LoggerInterceptor.class)
public class CustomerOrderProfileKey {
public static final String FIND_ALL_PROFILE_KEYS_NAMED_QUERY = "findAllProfileKeys";
public static final String FILTER_QUERY_PARAM = "filter";
public static final String SEARCH_PROFILE_KEYS_NAMED_QUERY = "searchProfileKeys";
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
Long id;
@Column(name = "KEY", nullable = false, length = 50, unique = true)
String key;
@Column(name = "DESCRIPTION", nullable = false, length = 1000)
String description;
@Column(name = "CREATED_AT", nullable = false)
Timestamp createdAt;
@Column(name = "CREATED_BY", length = 50, nullable = false)
String createdBy;
@Column(name = "UPDATED_AT")
Timestamp updatedAt;
@Column(name = "UPDATED_BY", length = 50)
String updatedBy;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Timestamp getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Timestamp createdAt) {
this.createdAt = createdAt;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Timestamp getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Timestamp updatedAt) {
this.updatedAt = updatedAt;
}
public String getUpdatedBy() {
return updatedBy;
}
public void setUpdatedBy(String updatedBy) {
this.updatedBy = updatedBy;
}
}
| UTF-8 | Java | 2,568 | java | CustomerOrderProfileKey.java | Java | []
| null | []
| package com.dsv.road.masterdata.model;
import java.sql.Timestamp;
import javax.interceptor.Interceptors;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import com.dsv.shared.logger.LoggerInterceptor;
@Entity
@NamedQueries({
@NamedQuery(name = CustomerOrderProfileKey.FIND_ALL_PROFILE_KEYS_NAMED_QUERY, query = "SELECT b FROM CustomerOrderProfileKey b"),
@NamedQuery(name = CustomerOrderProfileKey.SEARCH_PROFILE_KEYS_NAMED_QUERY, query = "SELECT b FROM CustomerOrderProfileKey b WHERE UPPER(b.key) LIKE :" + CustomerOrderProfileKey.FILTER_QUERY_PARAM)
})
@Table(name = "CO_PROFILE_KEY")
@Interceptors(LoggerInterceptor.class)
public class CustomerOrderProfileKey {
public static final String FIND_ALL_PROFILE_KEYS_NAMED_QUERY = "findAllProfileKeys";
public static final String FILTER_QUERY_PARAM = "filter";
public static final String SEARCH_PROFILE_KEYS_NAMED_QUERY = "searchProfileKeys";
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
Long id;
@Column(name = "KEY", nullable = false, length = 50, unique = true)
String key;
@Column(name = "DESCRIPTION", nullable = false, length = 1000)
String description;
@Column(name = "CREATED_AT", nullable = false)
Timestamp createdAt;
@Column(name = "CREATED_BY", length = 50, nullable = false)
String createdBy;
@Column(name = "UPDATED_AT")
Timestamp updatedAt;
@Column(name = "UPDATED_BY", length = 50)
String updatedBy;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Timestamp getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Timestamp createdAt) {
this.createdAt = createdAt;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Timestamp getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Timestamp updatedAt) {
this.updatedAt = updatedAt;
}
public String getUpdatedBy() {
return updatedBy;
}
public void setUpdatedBy(String updatedBy) {
this.updatedBy = updatedBy;
}
}
| 2,568 | 0.746885 | 0.742991 | 110 | 22.345455 | 28.138435 | 198 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.172727 | false | false | 5 |
517601386596cfb29fb9875286e9aade48f318af | 23,837,068,513,148 | d6cf27ac29f76ff8ad468b334f5169c28ed56b31 | /Backend/ETourFinalproject/src/main/java/com/iacsd/Etour/controller/datepackagedetailController.java | dadfa9c450bf24e0c14b4d9b7d3cf6df97fbf0f5 | []
| no_license | Raniket25/CDACProject | https://github.com/Raniket25/CDACProject | b50d3107822079bf0f3000003e5d8c74aae067fa | ccdfd35c858367315a612843a0653b35d8333228 | refs/heads/main | 2023-02-27T13:00:18.267000 | 2021-02-02T12:41:38 | 2021-02-02T12:41:38 | 335,224,967 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.iacsd.Etour.controller;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import com.iacsd.Etour.entities.Datepackagedetail;
import com.iacsd.Etour.entities.Packagecompletedetail;
import com.iacsd.Etour.services.datepackagedetailService;
@CrossOrigin("http://localhost:4200")
@RestController
public class datepackagedetailController {
@Autowired
private datepackagedetailService service;
@GetMapping("/datepackdetails")
public List<Datepackagedetail> getpackagedetail()
{
return this.service.getdatepackagedetails();
}
@GetMapping("/datepackdetail/{datepackageid}")
public Datepackagedetail getPackDetail(@PathVariable int datepackageid)
{
return this.service.getDatePackDetail(datepackageid);
}
}
| UTF-8 | Java | 1,041 | java | datepackagedetailController.java | Java | []
| null | []
| package com.iacsd.Etour.controller;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import com.iacsd.Etour.entities.Datepackagedetail;
import com.iacsd.Etour.entities.Packagecompletedetail;
import com.iacsd.Etour.services.datepackagedetailService;
@CrossOrigin("http://localhost:4200")
@RestController
public class datepackagedetailController {
@Autowired
private datepackagedetailService service;
@GetMapping("/datepackdetails")
public List<Datepackagedetail> getpackagedetail()
{
return this.service.getdatepackagedetails();
}
@GetMapping("/datepackdetail/{datepackageid}")
public Datepackagedetail getPackDetail(@PathVariable int datepackageid)
{
return this.service.getDatePackDetail(datepackageid);
}
}
| 1,041 | 0.826129 | 0.822286 | 35 | 28.742857 | 24.835854 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.885714 | false | false | 5 |
8a7a05e3d26a9e130eefe97136fc9999525208b2 | 9,483,287,820,363 | 544aa0ac66bb89615d8f5f4d9f01a4fd84e99b29 | /Cloneable.java | 0e2074cc712188d72ee92b3ab4aeb931e5e44ca0 | []
| no_license | Tanishq777/OOPS-Based-Combat-Strategy-Game | https://github.com/Tanishq777/OOPS-Based-Combat-Strategy-Game | 8403c162fbbd359b3bffad00bfca11a72c1bb6b9 | b19d619c7e61a6f39a80fc89531e53b909655ae3 | refs/heads/main | 2023-07-10T23:16:15.019000 | 2021-08-14T13:49:36 | 2021-08-14T13:49:36 | 396,021,842 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.company;
public interface Cloneable {
}
| UTF-8 | Java | 57 | java | Cloneable.java | Java | []
| null | []
| package com.company;
public interface Cloneable {
}
| 57 | 0.719298 | 0.719298 | 4 | 12.25 | 12.090802 | 28 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 5 |
de7ded614987c7e9048497c9e5055ab652ce786f | 26,998,164,445,523 | 102dfa93471425080cee5fcf179fb67591a3e6e1 | /submissions/project3/battaglinijason_74793_2117566_Engine.java | d7880c2022e786f4ac655bc0b5e980e5df8b9aff | []
| no_license | Walter-Shaffer/1061-TA-F17 | https://github.com/Walter-Shaffer/1061-TA-F17 | 53646db8836b8051d876de2ca0a268f242c0905a | dc1ff702af73f4feba004de539a36b145560913b | refs/heads/master | 2021-08-28T20:32:14.175000 | 2017-12-13T04:17:36 | 2017-12-13T04:17:36 | 103,681,473 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* [Engine].java
* Author: [Jason Battaglini]
* Submission Date: [11/03/17]
*
* Purpose: Provides necessary methods and objects for the bagels class to run.
*
* Statement of Academic Honesty:
*
* The following code represents my own work. I have neither
* received nor given inappropriate assistance. I have not copied
* or modified code from any source other than the course webpage
* or the course textbook. I recognize that any unauthorized
* assistance or plagiarism will be handled in accordance
* with the policies at Clemson University and the
* policies of this course. I recognize that my work is based
* on an assignment created by the School of Computing
* at Clemson University. Any publishing or posting
* of source code for this project is strictly prohibited
* unless you have written consent from the instructor.
*/
import java.util.Random;
public class Engine {
private int numDigits;
private int[] secretNumber=new int[numDigits];
private Random randomNumberGenerator=new Random();
//converts the secret number to an array of single digits
public int[] convertNumToDigitArray(String x){
/*int numDigits=x.length();
int[] convertNumToDigitArray= new int[numDigits];
for(int i=0;i<numDigits;i++){
convertNumToDigitArray[i]=x.charAt(i);
//Character.getNumericValue(x.charAt(i));
}
return convertNumToDigitArray;*/
int[] array = new int[x.length()];
String[] ar = new String[x.length()];
for(int j = 0; j < x.length(); j++){
ar[j] = x.substring(j,j+1);
}
for(int i = 0; i < x.length(); i++){
array[i] = Integer.parseInt(ar[i],10);
}
return array;
}
//generates a secret number of length numDigits
public void generateNewSecret(){
for(int i=0; i<numDigits; i++){
secretNumber[i]=randomNumberGenerator.nextInt(10);
}
}
//sets the secretNumber
public void setSecretNumber(int[] secretNumber){
this.secretNumber=secretNumber;
}
public void setNumDigits(int numDigits){
this.numDigits=numDigits;
this.secretNumber=new int[numDigits];
}
//returns the secretNumber
public int[] getSecretNumber(){
for (int j=0; j<secretNumber.length; j++) //NULL
{
System.out.print("" + secretNumber[j]);
}
return secretNumber;
}
//returns the number of digits entered by the user in Bagels
public int getNumDigits(){
return numDigits;
}
}
| UTF-8 | Java | 2,441 | java | battaglinijason_74793_2117566_Engine.java | Java | [
{
"context": "\r\n/*\r\n* [Engine].java\r\n* Author: [Jason Battaglini]\r\n* Submission Date: [11/03/17]\r\n*\r\n* Purpose: Pr",
"end": 50,
"score": 0.9998787641525269,
"start": 34,
"tag": "NAME",
"value": "Jason Battaglini"
}
]
| null | []
|
/*
* [Engine].java
* Author: [<NAME>]
* Submission Date: [11/03/17]
*
* Purpose: Provides necessary methods and objects for the bagels class to run.
*
* Statement of Academic Honesty:
*
* The following code represents my own work. I have neither
* received nor given inappropriate assistance. I have not copied
* or modified code from any source other than the course webpage
* or the course textbook. I recognize that any unauthorized
* assistance or plagiarism will be handled in accordance
* with the policies at Clemson University and the
* policies of this course. I recognize that my work is based
* on an assignment created by the School of Computing
* at Clemson University. Any publishing or posting
* of source code for this project is strictly prohibited
* unless you have written consent from the instructor.
*/
import java.util.Random;
public class Engine {
private int numDigits;
private int[] secretNumber=new int[numDigits];
private Random randomNumberGenerator=new Random();
//converts the secret number to an array of single digits
public int[] convertNumToDigitArray(String x){
/*int numDigits=x.length();
int[] convertNumToDigitArray= new int[numDigits];
for(int i=0;i<numDigits;i++){
convertNumToDigitArray[i]=x.charAt(i);
//Character.getNumericValue(x.charAt(i));
}
return convertNumToDigitArray;*/
int[] array = new int[x.length()];
String[] ar = new String[x.length()];
for(int j = 0; j < x.length(); j++){
ar[j] = x.substring(j,j+1);
}
for(int i = 0; i < x.length(); i++){
array[i] = Integer.parseInt(ar[i],10);
}
return array;
}
//generates a secret number of length numDigits
public void generateNewSecret(){
for(int i=0; i<numDigits; i++){
secretNumber[i]=randomNumberGenerator.nextInt(10);
}
}
//sets the secretNumber
public void setSecretNumber(int[] secretNumber){
this.secretNumber=secretNumber;
}
public void setNumDigits(int numDigits){
this.numDigits=numDigits;
this.secretNumber=new int[numDigits];
}
//returns the secretNumber
public int[] getSecretNumber(){
for (int j=0; j<secretNumber.length; j++) //NULL
{
System.out.print("" + secretNumber[j]);
}
return secretNumber;
}
//returns the number of digits entered by the user in Bagels
public int getNumDigits(){
return numDigits;
}
}
| 2,431 | 0.687423 | 0.680869 | 82 | 27.695122 | 21.757359 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.47561 | false | false | 5 |
41f97308be10cabb63efb02720119f535ea864f9 | 24,627,342,500,236 | 7766fd9f7011b15e033212056e4af9fe3943b853 | /app/src/main/java/com/jueda/ndian/activity/me/view/RegisterActivity.java | e8ae7a3c721dd28f8cf10f05fd70c3958da2bbd8 | []
| no_license | torkuds/ChuYou | https://github.com/torkuds/ChuYou | cd7cacfaf79d13031b4e3b42ffdb01f8c16dd7e5 | 470fc5da25f190bac033803af61e34881f47654a | refs/heads/master | 2021-06-12T23:36:21.165000 | 2017-03-24T19:45:41 | 2017-03-24T19:45:41 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jueda.ndian.activity.me.view;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.jueda.ndian.NdianApplication;
import com.jueda.ndian.R;
import com.jueda.ndian.activity.me.biz.CheckPhoneBiz;
import com.jueda.ndian.nohttp.WaitDialog;
import com.jueda.ndian.utils.ChangeTitle;
import com.jueda.ndian.utils.Constants;
import com.jueda.ndian.utils.CountdownUtil;
import com.jueda.ndian.utils.KeyboardManage;
import com.jueda.ndian.utils.LogUtil;
import com.jueda.ndian.utils.ToastShow;
import org.json.JSONException;
import org.json.JSONObject;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
/**
* 注册手机号检测
*/
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {
public static final String TAG="RegisterActivity";
public static RegisterActivity instance=null;
private Button register;//注册\
private EditText userName;//手机号
private EditText passWord;//密码
private Button get_code;//获取验证码
private EditText code;//验证码输入
private CountdownUtil tu=null;//计时器
private final int RESULT_OK=1;
private final int RESULT_ERROR=2;
private WaitDialog waitDialog;
private int number=0;//次数,暂时先避免跳转多出
Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
//短信验证成功跳转
case RESULT_OK:
if(waitDialog!=null&&waitDialog.isShowing()){
waitDialog.dismiss();
}
if(tu!=null){
tu.cancel();
tu.onFinish();
}
if(number==0){
number=1;
Intent intent=new Intent(RegisterActivity.this,RegisterUserActivity.class);
intent.putExtra("who","RegisterActivity");
intent.putExtra("phone",userName.getText().toString().trim());
intent.putExtra("password",passWord.getText().toString().trim());
startActivity(intent);
}
break;
//短信出错
case RESULT_ERROR:
if(waitDialog!=null&&waitDialog.isShowing()){
waitDialog.dismiss();
}
String error= (String) msg.obj;
new LogUtil("短信",error+"");
if(error.equals("468")){
new ToastShow(getApplicationContext(),"验证码错误",1000);
}else {
if (error.equals("466")) {
new ToastShow(getApplicationContext(), "验证码为空", 1000);
} else if (error.equals("456")) {
new ToastShow(getApplicationContext(), "手机号为空", 1000);
} else if (error.equals("457")) {
new ToastShow(getApplicationContext(), "手机号码格式错误", 1000);
if(tu!=null){
tu.cancel();
tu.onFinish();
}
} else if (error.equals("603")) {
new ToastShow(getApplicationContext(), "手机号码格式错误", 1000);
if(tu!=null){
tu.cancel();
tu.onFinish();
}
} else if (error.equals("478")||error.equals("465")||error.equals("464")||error.equals("463")||error.equals("477")||error.equals("476")) {
new ToastShow(getApplicationContext(), "短信发送超过限额", 1000);
if(tu!=null){
tu.cancel();
tu.onFinish();
}
}else if(error.equals("472")||error.equals("467")||error.equals("462")){
new ToastShow(getApplicationContext(), "操作过于频繁,稍后再试", 1000);
if(tu!=null){
tu.cancel();
tu.onFinish();
}
}else{
new ToastShow(getApplicationContext(), "短信错误", 1000);
if(tu!=null){
tu.cancel();
tu.onFinish();
}
}
}
break;
//短信倒计时
case Constants.TIMING_OF:
long s=(Long) msg.obj/1000;
get_code.setText(s+"");
break;
//倒计时结束
case Constants.CMT_TIME_MARKSTOP:
tu.cancel();
tu=null;
get_code.setEnabled(true);
get_code.setClickable(true);
get_code.setText(getResources().getString(R.string.To_resend));
break;
//手机号检测成功
case Constants.ON_SUCCEED:
String status= (String) msg.obj;
if(status.equals("1")){
SMSSDK.submitVerificationCode("86", userName.getText().toString().trim(), code
.getText().toString());
}else{
if(waitDialog!=null&&waitDialog.isShowing()){
waitDialog.dismiss();
}
new ToastShow(RegisterActivity.this,R.string.The_phone_number_has_been_registered,1000);
}
break;
//手机号检查失败
case Constants.FAILURE:
if(waitDialog!=null&&waitDialog.isShowing()){
waitDialog.dismiss();
}
new ToastShow(RegisterActivity.this,R.string.Network_is_bad_please_try_again,1000);
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
instance=this;
new ChangeTitle(this);
InitSDK();
setContentView(R.layout.activity_register);
InitView();
setOnClick();
}
private void InitSDK() {
//mob短信初始化
SMSSDK.initSDK(this, Constants.APPKEY, Constants.APPSECRET);
EventHandler eh=new EventHandler(){
@Override
public void afterEvent(int event, int result, Object data) {
if (result == SMSSDK.RESULT_COMPLETE) {
//回调完成
if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
//提交验证码成功
handler.sendEmptyMessage(RESULT_OK);
}else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE){
//短信已发送
}
}else{
((Throwable)data).printStackTrace();
try {
Throwable throwable = (Throwable) data;
throwable.printStackTrace();
JSONObject object = new JSONObject(throwable.getMessage());
Message message=new Message();
message.obj=object.getString("status");
message.what=RESULT_ERROR;
handler.sendMessage(message);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
};
SMSSDK.registerEventHandler(eh); //注册短信回调
}
//计时开始
private void Timing() {
get_code.setClickable(false);
get_code.setEnabled(false);
tu=new CountdownUtil(120000, 1000, handler);
tu.start();
}
private void setOnClick() {
register.setOnClickListener(this);
get_code.setOnClickListener(this);
}
private void InitView() {
NdianApplication.instance.setTitle(this, getResources().getString(R.string.registered), true);
register=(Button)findViewById(R.id.register);
get_code=(Button)findViewById(R.id.get_code);
code=(EditText)findViewById(R.id.code);
userName=(EditText)findViewById(R.id.userName);
passWord=(EditText)findViewById(R.id.passWord);
}
@Override
protected void onDestroy() {
instance=null;
if(tu!=null){
tu.cancel();
}
super.onDestroy();
}
@Override
public void onClick(View v) {
new KeyboardManage().CloseKeyboard(v,RegisterActivity.this);
switch (v.getId()){
//注册
case R.id.register:
/**判断是否输入完整*/
if(userName.getText().toString().equals("")||passWord.getText().toString().equals("")||code.getText().toString().equals("")){
new ToastShow(RegisterActivity.this,getResources().getString(R.string.Incomplete_information),1000);
}else {
if(passWord.getText().toString().length()>=6&&passWord.getText().toString().length()<=20){
if (userName.getText().toString().equals("")) {
new ToastShow(RegisterActivity.this, getResources().getString(R.string.Mobile_phone_number_is_empty), 1000);
}else {
//检查手机号是否注册
number=0;
waitDialog=new WaitDialog(RegisterActivity.this);
new CheckPhoneBiz(RegisterActivity.this, handler, userName.getText().toString().trim(),false);
}
}else{
new ToastShow(RegisterActivity.this,getResources().getString(R.string.Password_length_is_wrong),1000);
}
}
break;
//获取验证码
case R.id.get_code:
//判断是否有网
if(Constants.currentNetworkType==Constants.TYPE_NONE){
new ToastShow(RegisterActivity.this,getResources().getString(R.string.No_network_please_check_the_network1),1000);
}else {
if (userName.getText().toString().equals("")) {
new ToastShow(RegisterActivity.this, getResources().getString(R.string.Mobile_phone_number_is_empty), 1000);
} else {
Timing();
SMSSDK.getVerificationCode("86", userName.getText().toString().trim());
}
}
break;
}
}
}
| UTF-8 | Java | 11,466 | java | RegisterActivity.java | Java | [
{
"context": "xt userName;//手机号\n private EditText passWord;//密码\n private Button get_code;//获取验证码\n private E",
"end": 1136,
"score": 0.9689247012138367,
"start": 1134,
"tag": "PASSWORD",
"value": "密码"
},
{
"context": " intent.putExtra(\"password\",passWord.getText().toString().trim());\n ",
"end": 2233,
"score": 0.9596234560012817,
"start": 2229,
"tag": "PASSWORD",
"value": "pass"
}
]
| null | []
| package com.jueda.ndian.activity.me.view;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.jueda.ndian.NdianApplication;
import com.jueda.ndian.R;
import com.jueda.ndian.activity.me.biz.CheckPhoneBiz;
import com.jueda.ndian.nohttp.WaitDialog;
import com.jueda.ndian.utils.ChangeTitle;
import com.jueda.ndian.utils.Constants;
import com.jueda.ndian.utils.CountdownUtil;
import com.jueda.ndian.utils.KeyboardManage;
import com.jueda.ndian.utils.LogUtil;
import com.jueda.ndian.utils.ToastShow;
import org.json.JSONException;
import org.json.JSONObject;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
/**
* 注册手机号检测
*/
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {
public static final String TAG="RegisterActivity";
public static RegisterActivity instance=null;
private Button register;//注册\
private EditText userName;//手机号
private EditText passWord;//密码
private Button get_code;//获取验证码
private EditText code;//验证码输入
private CountdownUtil tu=null;//计时器
private final int RESULT_OK=1;
private final int RESULT_ERROR=2;
private WaitDialog waitDialog;
private int number=0;//次数,暂时先避免跳转多出
Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
//短信验证成功跳转
case RESULT_OK:
if(waitDialog!=null&&waitDialog.isShowing()){
waitDialog.dismiss();
}
if(tu!=null){
tu.cancel();
tu.onFinish();
}
if(number==0){
number=1;
Intent intent=new Intent(RegisterActivity.this,RegisterUserActivity.class);
intent.putExtra("who","RegisterActivity");
intent.putExtra("phone",userName.getText().toString().trim());
intent.putExtra("password",<PASSWORD>Word.getText().toString().trim());
startActivity(intent);
}
break;
//短信出错
case RESULT_ERROR:
if(waitDialog!=null&&waitDialog.isShowing()){
waitDialog.dismiss();
}
String error= (String) msg.obj;
new LogUtil("短信",error+"");
if(error.equals("468")){
new ToastShow(getApplicationContext(),"验证码错误",1000);
}else {
if (error.equals("466")) {
new ToastShow(getApplicationContext(), "验证码为空", 1000);
} else if (error.equals("456")) {
new ToastShow(getApplicationContext(), "手机号为空", 1000);
} else if (error.equals("457")) {
new ToastShow(getApplicationContext(), "手机号码格式错误", 1000);
if(tu!=null){
tu.cancel();
tu.onFinish();
}
} else if (error.equals("603")) {
new ToastShow(getApplicationContext(), "手机号码格式错误", 1000);
if(tu!=null){
tu.cancel();
tu.onFinish();
}
} else if (error.equals("478")||error.equals("465")||error.equals("464")||error.equals("463")||error.equals("477")||error.equals("476")) {
new ToastShow(getApplicationContext(), "短信发送超过限额", 1000);
if(tu!=null){
tu.cancel();
tu.onFinish();
}
}else if(error.equals("472")||error.equals("467")||error.equals("462")){
new ToastShow(getApplicationContext(), "操作过于频繁,稍后再试", 1000);
if(tu!=null){
tu.cancel();
tu.onFinish();
}
}else{
new ToastShow(getApplicationContext(), "短信错误", 1000);
if(tu!=null){
tu.cancel();
tu.onFinish();
}
}
}
break;
//短信倒计时
case Constants.TIMING_OF:
long s=(Long) msg.obj/1000;
get_code.setText(s+"");
break;
//倒计时结束
case Constants.CMT_TIME_MARKSTOP:
tu.cancel();
tu=null;
get_code.setEnabled(true);
get_code.setClickable(true);
get_code.setText(getResources().getString(R.string.To_resend));
break;
//手机号检测成功
case Constants.ON_SUCCEED:
String status= (String) msg.obj;
if(status.equals("1")){
SMSSDK.submitVerificationCode("86", userName.getText().toString().trim(), code
.getText().toString());
}else{
if(waitDialog!=null&&waitDialog.isShowing()){
waitDialog.dismiss();
}
new ToastShow(RegisterActivity.this,R.string.The_phone_number_has_been_registered,1000);
}
break;
//手机号检查失败
case Constants.FAILURE:
if(waitDialog!=null&&waitDialog.isShowing()){
waitDialog.dismiss();
}
new ToastShow(RegisterActivity.this,R.string.Network_is_bad_please_try_again,1000);
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
instance=this;
new ChangeTitle(this);
InitSDK();
setContentView(R.layout.activity_register);
InitView();
setOnClick();
}
private void InitSDK() {
//mob短信初始化
SMSSDK.initSDK(this, Constants.APPKEY, Constants.APPSECRET);
EventHandler eh=new EventHandler(){
@Override
public void afterEvent(int event, int result, Object data) {
if (result == SMSSDK.RESULT_COMPLETE) {
//回调完成
if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
//提交验证码成功
handler.sendEmptyMessage(RESULT_OK);
}else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE){
//短信已发送
}
}else{
((Throwable)data).printStackTrace();
try {
Throwable throwable = (Throwable) data;
throwable.printStackTrace();
JSONObject object = new JSONObject(throwable.getMessage());
Message message=new Message();
message.obj=object.getString("status");
message.what=RESULT_ERROR;
handler.sendMessage(message);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
};
SMSSDK.registerEventHandler(eh); //注册短信回调
}
//计时开始
private void Timing() {
get_code.setClickable(false);
get_code.setEnabled(false);
tu=new CountdownUtil(120000, 1000, handler);
tu.start();
}
private void setOnClick() {
register.setOnClickListener(this);
get_code.setOnClickListener(this);
}
private void InitView() {
NdianApplication.instance.setTitle(this, getResources().getString(R.string.registered), true);
register=(Button)findViewById(R.id.register);
get_code=(Button)findViewById(R.id.get_code);
code=(EditText)findViewById(R.id.code);
userName=(EditText)findViewById(R.id.userName);
passWord=(EditText)findViewById(R.id.passWord);
}
@Override
protected void onDestroy() {
instance=null;
if(tu!=null){
tu.cancel();
}
super.onDestroy();
}
@Override
public void onClick(View v) {
new KeyboardManage().CloseKeyboard(v,RegisterActivity.this);
switch (v.getId()){
//注册
case R.id.register:
/**判断是否输入完整*/
if(userName.getText().toString().equals("")||passWord.getText().toString().equals("")||code.getText().toString().equals("")){
new ToastShow(RegisterActivity.this,getResources().getString(R.string.Incomplete_information),1000);
}else {
if(passWord.getText().toString().length()>=6&&passWord.getText().toString().length()<=20){
if (userName.getText().toString().equals("")) {
new ToastShow(RegisterActivity.this, getResources().getString(R.string.Mobile_phone_number_is_empty), 1000);
}else {
//检查手机号是否注册
number=0;
waitDialog=new WaitDialog(RegisterActivity.this);
new CheckPhoneBiz(RegisterActivity.this, handler, userName.getText().toString().trim(),false);
}
}else{
new ToastShow(RegisterActivity.this,getResources().getString(R.string.Password_length_is_wrong),1000);
}
}
break;
//获取验证码
case R.id.get_code:
//判断是否有网
if(Constants.currentNetworkType==Constants.TYPE_NONE){
new ToastShow(RegisterActivity.this,getResources().getString(R.string.No_network_please_check_the_network1),1000);
}else {
if (userName.getText().toString().equals("")) {
new ToastShow(RegisterActivity.this, getResources().getString(R.string.Mobile_phone_number_is_empty), 1000);
} else {
Timing();
SMSSDK.getVerificationCode("86", userName.getText().toString().trim());
}
}
break;
}
}
}
| 11,472 | 0.486735 | 0.474824 | 269 | 40.197025 | 28.540361 | 162 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.747212 | false | false | 5 |
ebb00271ad498918c9d87441420a0a41d43190af | 28,698,971,495,158 | eed798c186f44146bfc1e8691f093b168b9bee85 | /src/day06/ReverseString.java | d6ac05c369960c803ea799931a6e5b10dd033043 | []
| no_license | yahto1307/niuke | https://github.com/yahto1307/niuke | f1a0008101a6b879317e9d91ead1ab08347c442f | 8fdbdc2f36f5499277d2a6e243ca106df3dce4be | refs/heads/master | 2021-07-05T15:35:29.972000 | 2017-09-28T06:51:45 | 2017-09-28T06:51:45 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package day06;
import org.junit.Test;
import java.util.Scanner;
/**
* Created by yahto on 12/07/2017.
*/
public class ReverseString {
public String reverseString(String str) {
if (str == null || str.length() == 0){
return str;
}
char[] arr = str.toCharArray();
int j = arr.length - 1;
for (int i = 0; i <= (arr.length - 1) / 2; i++, j--) {
if (i >= j) {
break;
}
char temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
return String.valueOf(arr);
}
@Test
public void test() {
System.out.println(reverseString("abcdef"));
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()){
System.out.println(reverseString(scanner.nextLine()));
}
scanner.close();
}
}
| UTF-8 | Java | 888 | java | ReverseString.java | Java | [
{
"context": "est;\n\nimport java.util.Scanner;\n\n/**\n * Created by yahto on 12/07/2017.\n */\npublic class ReverseString {\n ",
"end": 90,
"score": 0.9987914562225342,
"start": 85,
"tag": "USERNAME",
"value": "yahto"
}
]
| null | []
| package day06;
import org.junit.Test;
import java.util.Scanner;
/**
* Created by yahto on 12/07/2017.
*/
public class ReverseString {
public String reverseString(String str) {
if (str == null || str.length() == 0){
return str;
}
char[] arr = str.toCharArray();
int j = arr.length - 1;
for (int i = 0; i <= (arr.length - 1) / 2; i++, j--) {
if (i >= j) {
break;
}
char temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
return String.valueOf(arr);
}
@Test
public void test() {
System.out.println(reverseString("abcdef"));
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()){
System.out.println(reverseString(scanner.nextLine()));
}
scanner.close();
}
}
| 888 | 0.492117 | 0.475225 | 37 | 23 | 17.823458 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.540541 | false | false | 5 |
fd7033edac5e56a84120f7f2818c3c0421c6f2b4 | 28,458,453,327,184 | edfcda448135a2d459b3ddc9201ff628f1b61125 | /kiki-client/src/main/java/cn/edu/nju/pasalab/kiki/client/ClientContext.java | 4c1f0e59d3fa75576db37918e755b4d59c0f74e0 | []
| no_license | saltylin/KiKi | https://github.com/saltylin/KiKi | a6fc13e598a1527d17bacce4a7a42b8300a531b6 | 8a536340dd26aa53bce8a251a0013996ca034b7a | refs/heads/master | 2021-05-03T21:40:35.242000 | 2016-11-04T14:05:58 | 2016-11-04T14:05:58 | 71,518,650 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.edu.nju.pasalab.kiki.client;
import cn.edu.nju.pasalab.kiki.common.Configuration;
public final class ClientContext {
private ClientContext() {} // Prevents initialization
public static Configuration getConf() {
return Configuration.getInstance();
}
}
| UTF-8 | Java | 275 | java | ClientContext.java | Java | []
| null | []
| package cn.edu.nju.pasalab.kiki.client;
import cn.edu.nju.pasalab.kiki.common.Configuration;
public final class ClientContext {
private ClientContext() {} // Prevents initialization
public static Configuration getConf() {
return Configuration.getInstance();
}
}
| 275 | 0.76 | 0.76 | 11 | 24 | 21.913052 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.272727 | false | false | 5 |
d1d464789284716debc713bf83cf0ad2caecaabd | 7,945,689,525,021 | d22ea121f8874feeedfc7947d76d53449a77f639 | /app/src/main/java/com/motorola/mobiledp/ccc/xcmp/CommandCreate.java | 0ec40fe7fc3536ca25bfc9be9a286d1decf98246 | []
| no_license | JiaLei123/MobileDP | https://github.com/JiaLei123/MobileDP | f167f172237766ebe05389fd2874a61c677b6e55 | ec9df52c03ffc78075b5d2f7ad657b148f2353a4 | refs/heads/master | 2021-01-11T03:35:48.936000 | 2016-04-29T04:45:41 | 2016-04-29T04:45:41 | 57,355,215 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
*
*/
package com.motorola.mobiledp.ccc.xcmp;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author WDGK73
*
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CommandCreate {
public int opcode();
}
| UTF-8 | Java | 366 | java | CommandCreate.java | Java | [
{
"context": "mport java.lang.annotation.Target;\n\n/**\n * @author WDGK73\n *\n */\n@Target(ElementType.METHOD)\n@Retention(Ret",
"end": 236,
"score": 0.9996307492256165,
"start": 230,
"tag": "USERNAME",
"value": "WDGK73"
}
]
| null | []
| /**
*
*/
package com.motorola.mobiledp.ccc.xcmp;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author WDGK73
*
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CommandCreate {
public int opcode();
}
| 366 | 0.762295 | 0.756831 | 19 | 18.263159 | 16.561979 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.368421 | false | false | 5 |
e0c5dd9abaadfcde0bf46982227e0f52cab9c118 | 26,456,998,611,202 | 8e2c83abb2c70f48021f483d9cc7b4a9b7a9d6b1 | /Restaurant-Finder 2/app/src/main/java/com/example/jxq48/restaurant_finder/presentation/RestaurantHost/CommentsFragment.java | 0ac26b82af4002a942aacdac4aeb639c9afb6717 | []
| no_license | sidhappy/Android-Application-Restaurant-Finder | https://github.com/sidhappy/Android-Application-Restaurant-Finder | fa341e2f7412832d33a6d88b75f31412c0c0c5a4 | 2f5dac4c837d92507613bfab0c07b61c2df702b0 | refs/heads/master | 2021-01-16T23:07:48.734000 | 2016-01-21T06:36:19 | 2016-01-21T06:36:19 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* This fragment is used to display the comment list about a restaurant
*/
package com.example.jxq48.restaurant_finder.presentation.RestaurantHost;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.example.jxq48.restaurant_finder.R;
import com.example.jxq48.restaurant_finder.entities.Comment;
import com.example.jxq48.restaurant_finder.entities.Restaurant;
import com.example.jxq48.restaurant_finder.presentation.adapter.CommentsViewAdapter;
import com.example.jxq48.restaurant_finder.ws.remote.RemoteServerProxy;
import java.util.ArrayList;
/**
* Created by jxq48 on 7/17/15.
*/
public class CommentsFragment extends Fragment {
private Restaurant restaurant;
// send request to server and get comment list about a restaurant
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(
R.layout.fragment_comments, container, false);
Intent i = getActivity().getIntent();
restaurant = (Restaurant) i.getSerializableExtra("RESTAURANT");
int restID = restaurant.getRestID();
RemoteServerProxy proxy = new RemoteServerProxy();
if (proxy.getComments(restID) != null) {
ArrayList<Comment> comms = proxy.getComments(restID);
ListView lv = (ListView) v.findViewById(R.id.comments_list);
lv.setAdapter(new CommentsViewAdapter(getActivity(), comms));
}
return v;
}
}
| UTF-8 | Java | 1,674 | java | CommentsFragment.java | Java | [
{
"context": "y;\n\nimport java.util.ArrayList;\n\n/**\n * Created by jxq48 on 7/17/15.\n */\npublic class CommentsFragment ext",
"end": 747,
"score": 0.9995995759963989,
"start": 742,
"tag": "USERNAME",
"value": "jxq48"
}
]
| null | []
| /**
* This fragment is used to display the comment list about a restaurant
*/
package com.example.jxq48.restaurant_finder.presentation.RestaurantHost;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.example.jxq48.restaurant_finder.R;
import com.example.jxq48.restaurant_finder.entities.Comment;
import com.example.jxq48.restaurant_finder.entities.Restaurant;
import com.example.jxq48.restaurant_finder.presentation.adapter.CommentsViewAdapter;
import com.example.jxq48.restaurant_finder.ws.remote.RemoteServerProxy;
import java.util.ArrayList;
/**
* Created by jxq48 on 7/17/15.
*/
public class CommentsFragment extends Fragment {
private Restaurant restaurant;
// send request to server and get comment list about a restaurant
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(
R.layout.fragment_comments, container, false);
Intent i = getActivity().getIntent();
restaurant = (Restaurant) i.getSerializableExtra("RESTAURANT");
int restID = restaurant.getRestID();
RemoteServerProxy proxy = new RemoteServerProxy();
if (proxy.getComments(restID) != null) {
ArrayList<Comment> comms = proxy.getComments(restID);
ListView lv = (ListView) v.findViewById(R.id.comments_list);
lv.setAdapter(new CommentsViewAdapter(getActivity(), comms));
}
return v;
}
}
| 1,674 | 0.722222 | 0.710872 | 48 | 33.875 | 27.575371 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.604167 | false | false | 5 |
1d8c08d76732a64cbc3e8c8782234eb949d9c96d | 21,019,569,974,789 | ec7244321445c1f2b526a85baa07bb6d77885270 | /src/com/rman/youfood/rest/InstructionResource.java | 2bd114d73cda7e8557308d01de53239bf6615606 | []
| no_license | yannick85/YouFood | https://github.com/yannick85/YouFood | 8175079ffa3f23a75410397b9866b6bc3539eddd | 2c0b5420d7d68608031946056d5643b1f6b88d4a | refs/heads/master | 2021-05-26T20:47:55.256000 | 2013-04-14T09:33:52 | 2013-04-14T09:33:52 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.rman.youfood.rest;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import com.rman.youfood.converter.JsonInstructionConverter;
import com.rman.youfood.dao.DaoFactory;
import com.rman.youfood.dao.InstructionDao;
import com.rman.youfood.dao.InstructionMenuDao;
import com.rman.youfood.entity.Instruction;
@Path("/instruction")
public class InstructionResource {
@GET @Path("/one/{id}")
public Instruction getInstruction(@PathParam("id") String id){
InstructionDao instructionDao = DaoFactory.getInstance().getInstructionDao();
return instructionDao.getInstructionById(Long.valueOf(id));
}
@GET @Path("/{id}")
public List<Instruction> getInstructionForZone(@PathParam("id") String id){
InstructionDao instructionDao = DaoFactory.getInstance().getInstructionDao();
return instructionDao.getInstructionsForZone(Long.valueOf(id));
}
@POST
public Response addInstruction(String jsonInstruction){
try {
JSONObject json = new JSONObject(jsonInstruction);
Instruction instruction = JsonInstructionConverter.JsonToInstruction(json);
InstructionDao instructionDao = DaoFactory.getInstance().getInstructionDao();
InstructionMenuDao instructionMenuDao = DaoFactory.getInstance().getInstructionMenuDao();
instructionDao.addInstruction(instruction);
for (int i = 0; i < instruction.getMenus().size(); i++){
instruction.getMenus().get(i).setInstruction(instruction);
instructionMenuDao.addInstructionMenu(instruction.getMenus().get(i));
}
} catch (JSONException e) {
return Response.serverError().build();
}
return Response.ok().build();
//return Response.created(URI.create("/instruction/one/"+instruction.getId())).build();
}
@PUT @Path("/finish/{id}")
public Response finishInstruction(@PathParam("id") String id){
Long instructionId = Long.valueOf(id);
InstructionDao instructionDao = DaoFactory.getInstance().getInstructionDao();
Instruction i = instructionDao.getInstructionById(instructionId);
if(i != null){
i.setServed(true);
if(!instructionDao.finishInstruction(i)){
return Response.serverError().build();
}
} else {
return Response.serverError().build();
}
return Response.ok().build();
}
}
| UTF-8 | Java | 2,440 | java | InstructionResource.java | Java | []
| null | []
| package com.rman.youfood.rest;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import com.rman.youfood.converter.JsonInstructionConverter;
import com.rman.youfood.dao.DaoFactory;
import com.rman.youfood.dao.InstructionDao;
import com.rman.youfood.dao.InstructionMenuDao;
import com.rman.youfood.entity.Instruction;
@Path("/instruction")
public class InstructionResource {
@GET @Path("/one/{id}")
public Instruction getInstruction(@PathParam("id") String id){
InstructionDao instructionDao = DaoFactory.getInstance().getInstructionDao();
return instructionDao.getInstructionById(Long.valueOf(id));
}
@GET @Path("/{id}")
public List<Instruction> getInstructionForZone(@PathParam("id") String id){
InstructionDao instructionDao = DaoFactory.getInstance().getInstructionDao();
return instructionDao.getInstructionsForZone(Long.valueOf(id));
}
@POST
public Response addInstruction(String jsonInstruction){
try {
JSONObject json = new JSONObject(jsonInstruction);
Instruction instruction = JsonInstructionConverter.JsonToInstruction(json);
InstructionDao instructionDao = DaoFactory.getInstance().getInstructionDao();
InstructionMenuDao instructionMenuDao = DaoFactory.getInstance().getInstructionMenuDao();
instructionDao.addInstruction(instruction);
for (int i = 0; i < instruction.getMenus().size(); i++){
instruction.getMenus().get(i).setInstruction(instruction);
instructionMenuDao.addInstructionMenu(instruction.getMenus().get(i));
}
} catch (JSONException e) {
return Response.serverError().build();
}
return Response.ok().build();
//return Response.created(URI.create("/instruction/one/"+instruction.getId())).build();
}
@PUT @Path("/finish/{id}")
public Response finishInstruction(@PathParam("id") String id){
Long instructionId = Long.valueOf(id);
InstructionDao instructionDao = DaoFactory.getInstance().getInstructionDao();
Instruction i = instructionDao.getInstructionById(instructionId);
if(i != null){
i.setServed(true);
if(!instructionDao.finishInstruction(i)){
return Response.serverError().build();
}
} else {
return Response.serverError().build();
}
return Response.ok().build();
}
}
| 2,440 | 0.756557 | 0.756148 | 72 | 32.888889 | 27.138819 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.916667 | false | false | 5 |
764d999bb873712f47a53bb4eae7ed0503702c6b | 28,862,180,256,690 | 43b71c160b5891d27a1f917fb60f778fd656e228 | /rt/wsdl/src/test/java/org/apache/cxf/wsdl/interceptors/DocLiteralInInterceptorTest.java | d0236a917a64bfb091bd2275d174430553f90e71 | [
"LicenseRef-scancode-unknown",
"Apache-2.0"
]
| permissive | apache/cxf | https://github.com/apache/cxf | b512f24f94d3cce2c90774698240568d609c040d | 66368976c7260eefd734dd0416b00f077176459e | refs/heads/main | 2023-09-03T13:02:40.099000 | 2023-09-01T11:54:27 | 2023-09-01T11:54:27 | 16,977,479 | 923 | 1,708 | Apache-2.0 | false | 2023-09-14T13:16:19 | 2014-02-19T08:00:08 | 2023-09-13T02:39:55 | 2023-09-14T13:16:18 | 130,862 | 829 | 1,395 | 40 | Java | false | false | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.cxf.wsdl.interceptors;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.dom.DOMSource;
import org.apache.cxf.databinding.source.SourceDataBinding;
import org.apache.cxf.endpoint.Endpoint;
import org.apache.cxf.helpers.XPathUtils;
import org.apache.cxf.message.Exchange;
import org.apache.cxf.message.ExchangeImpl;
import org.apache.cxf.message.Message;
import org.apache.cxf.message.MessageContentsList;
import org.apache.cxf.message.MessageImpl;
import org.apache.cxf.service.Service;
import org.apache.cxf.service.model.BindingInfo;
import org.apache.cxf.service.model.BindingOperationInfo;
import org.apache.cxf.service.model.EndpointInfo;
import org.apache.cxf.service.model.InterfaceInfo;
import org.apache.cxf.service.model.MessageInfo;
import org.apache.cxf.service.model.MessageInfo.Type;
import org.apache.cxf.service.model.MessagePartInfo;
import org.apache.cxf.service.model.OperationInfo;
import org.apache.cxf.service.model.ServiceInfo;
import org.apache.cxf.staxutils.PartialXMLStreamReader;
import org.apache.cxf.staxutils.StaxUtils;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Unit test for testing DocLiteralInInterceptor to use Source Data Binding
*
*/
public class DocLiteralInInterceptorTest {
private static final String NS = "http://cxf.apache.org/wsdl-first/types";
@Test
public void testUnmarshalSourceData() throws Exception {
XMLStreamReader reader = StaxUtils.createXMLStreamReader(getClass()
.getResourceAsStream("resources/multiPartDocLitBareReq.xml"));
assertEquals(XMLStreamConstants.START_ELEMENT, reader.nextTag());
XMLStreamReader filteredReader = new PartialXMLStreamReader(reader,
new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"));
// advance the xml reader to the message parts
StaxUtils.read(filteredReader);
assertEquals(XMLStreamConstants.START_ELEMENT, reader.nextTag());
Message m = new MessageImpl();
Exchange exchange = new ExchangeImpl();
Service service = mock(Service.class);
exchange.put(Service.class, service);
when(service.getDataBinding()).thenReturn(new SourceDataBinding());
when(service.size()).thenReturn(0);
when(service.isEmpty()).thenReturn(true);
Endpoint endpoint = mock(Endpoint.class);
exchange.put(Endpoint.class, endpoint);
OperationInfo operationInfo = new OperationInfo();
operationInfo.setProperty("operation.is.synthetic", Boolean.TRUE);
MessageInfo messageInfo = new MessageInfo(operationInfo, Type.INPUT,
new QName("http://foo.com", "bar"));
messageInfo.addMessagePart(new MessagePartInfo(new QName("http://foo.com", "partInfo1"), null));
messageInfo.addMessagePart(new MessagePartInfo(new QName("http://foo.com", "partInfo2"), null));
messageInfo.addMessagePart(new MessagePartInfo(new QName("http://foo.com", "partInfo3"), null));
messageInfo.addMessagePart(new MessagePartInfo(new QName("http://foo.com", "partInfo4"), null));
for (MessagePartInfo mpi : messageInfo.getMessageParts()) {
mpi.setMessageContainer(messageInfo);
}
operationInfo.setInput("inputName", messageInfo);
BindingOperationInfo boi = new BindingOperationInfo(null, operationInfo);
exchange.put(BindingOperationInfo.class, boi);
EndpointInfo endpointInfo = mock(EndpointInfo.class);
BindingInfo binding = mock(BindingInfo.class);
when(endpoint.getEndpointInfo()).thenReturn(endpointInfo);
when(endpointInfo.getBinding()).thenReturn(binding);
when(binding.getProperties()).thenReturn(new HashMap<String, Object>());
when(endpointInfo.getProperties()).thenReturn(new HashMap<String, Object>());
when(endpoint.size()).thenReturn(0);
when(endpoint.isEmpty()).thenReturn(true);
ServiceInfo serviceInfo = mock(ServiceInfo.class);
when(endpointInfo.getService()).thenReturn(serviceInfo);
when(serviceInfo.getName()).thenReturn(new QName("http://foo.com", "service"));
InterfaceInfo interfaceInfo = mock(InterfaceInfo.class);
when(serviceInfo.getInterface()).thenReturn(interfaceInfo);
when(interfaceInfo.getName()).thenReturn(new QName("http://foo.com", "interface"));
when(endpointInfo.getName()).thenReturn(new QName("http://foo.com", "endpoint"));
when(endpointInfo.getProperty("URI", URI.class)).thenReturn(new URI("dummy"));
List<OperationInfo> operations = new ArrayList<>();
when(interfaceInfo.getOperations()).thenReturn(operations);
m.setExchange(exchange);
m.put(Message.SCHEMA_VALIDATION_ENABLED, false);
m.setContent(XMLStreamReader.class, reader);
new DocLiteralInInterceptor().handleMessage(m);
MessageContentsList params = (MessageContentsList)m.getContent(List.class);
assertEquals(4, params.size());
assertEquals("StringDefaultInputElem",
((DOMSource)params.get(0)).getNode().getFirstChild().getNodeName());
assertEquals("IntParamInElem",
((DOMSource)params.get(1)).getNode().getFirstChild().getNodeName());
}
@Test
public void testUnmarshalSourceDataWrapped() throws Exception {
XMLStreamReader reader = StaxUtils.createXMLStreamReader(getClass()
.getResourceAsStream("resources/docLitWrappedReq.xml"));
assertEquals(XMLStreamConstants.START_ELEMENT, reader.nextTag());
XMLStreamReader filteredReader = new PartialXMLStreamReader(reader,
new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"));
// advance the xml reader to the message parts
StaxUtils.read(filteredReader);
assertEquals(XMLStreamConstants.START_ELEMENT, reader.nextTag());
Message m = new MessageImpl();
// request to keep the document as wrapped
m.put(DocLiteralInInterceptor.KEEP_PARAMETERS_WRAPPER, true);
Exchange exchange = new ExchangeImpl();
Service service = mock(Service.class);
exchange.put(Service.class, service);
when(service.getDataBinding()).thenReturn(new SourceDataBinding());
when(service.size()).thenReturn(0);
when(service.isEmpty()).thenReturn(true);
Endpoint endpoint = mock(Endpoint.class);
exchange.put(Endpoint.class, endpoint);
// wrapped
OperationInfo operationInfo = new OperationInfo();
MessageInfo messageInfo = new MessageInfo(operationInfo, Type.INPUT, new QName(NS, "foo"));
messageInfo.addMessagePart(new MessagePartInfo(new QName(NS, "personId"), null));
messageInfo.addMessagePart(new MessagePartInfo(new QName(NS, "ssn"), null));
messageInfo.getMessagePart(0).setConcreteName(new QName(NS, "personId"));
messageInfo.getMessagePart(1).setConcreteName(new QName(NS, "ssn"));
operationInfo.setInput("inputName", messageInfo);
// wrapper
OperationInfo operationInfoWrapper = new OperationInfo();
MessageInfo messageInfoWrapper = new MessageInfo(operationInfo, Type.INPUT, new QName(NS, "foo"));
messageInfoWrapper.addMessagePart(new MessagePartInfo(new QName(NS, "GetPerson"), null));
messageInfoWrapper.getMessagePart(0).setConcreteName(new QName(NS, "GetPerson"));
operationInfoWrapper.setInput("inputName", messageInfoWrapper);
operationInfoWrapper.setUnwrappedOperation(operationInfo);
ServiceInfo serviceInfo = mock(ServiceInfo.class);
when(serviceInfo.getName()).thenReturn(new QName("http://foo.com", "service"));
InterfaceInfo interfaceInfo = mock(InterfaceInfo.class);
when(serviceInfo.getInterface()).thenReturn(interfaceInfo);
when(interfaceInfo.getName()).thenReturn(new QName("http://foo.com", "interface"));
BindingInfo bindingInfo = new BindingInfo(serviceInfo, "");
BindingOperationInfo boi = new BindingOperationInfo(bindingInfo, operationInfoWrapper);
exchange.put(BindingOperationInfo.class, boi);
EndpointInfo endpointInfo = mock(EndpointInfo.class);
BindingInfo binding = mock(BindingInfo.class);
when(endpoint.getEndpointInfo()).thenReturn(endpointInfo);
when(endpointInfo.getBinding()).thenReturn(binding);
when(binding.getProperties()).thenReturn(new HashMap<String, Object>());
when(endpointInfo.getProperties()).thenReturn(new HashMap<String, Object>());
when(endpoint.size()).thenReturn(0);
when(endpoint.isEmpty()).thenReturn(true);
when(endpointInfo.getService()).thenReturn(serviceInfo);
when(endpointInfo.getName()).thenReturn(new QName("http://foo.com", "endpoint"));
when(endpointInfo.getProperty("URI", URI.class)).thenReturn(new URI("dummy"));
List<OperationInfo> operations = new ArrayList<>();
when(interfaceInfo.getOperations()).thenReturn(operations);
m.setExchange(exchange);
m.put(Message.SCHEMA_VALIDATION_ENABLED, false);
m.setContent(XMLStreamReader.class, reader);
new DocLiteralInInterceptor().handleMessage(m);
MessageContentsList params = (MessageContentsList)m.getContent(List.class);
// we expect a wrapped document
assertEquals(1, params.size());
Map<String, String> ns = new HashMap<>();
ns.put("ns", NS);
XPathUtils xu = new XPathUtils(ns);
assertEquals("hello", xu.getValueString("//ns:GetPerson/ns:personId",
((DOMSource)params.get(0)).getNode().getFirstChild()));
assertEquals("1234", xu.getValueString("//ns:GetPerson/ns:ssn",
((DOMSource)params.get(0)).getNode().getFirstChild()));
}
} | UTF-8 | Java | 11,043 | java | DocLiteralInInterceptorTest.java | Java | []
| null | []
| /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.cxf.wsdl.interceptors;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.dom.DOMSource;
import org.apache.cxf.databinding.source.SourceDataBinding;
import org.apache.cxf.endpoint.Endpoint;
import org.apache.cxf.helpers.XPathUtils;
import org.apache.cxf.message.Exchange;
import org.apache.cxf.message.ExchangeImpl;
import org.apache.cxf.message.Message;
import org.apache.cxf.message.MessageContentsList;
import org.apache.cxf.message.MessageImpl;
import org.apache.cxf.service.Service;
import org.apache.cxf.service.model.BindingInfo;
import org.apache.cxf.service.model.BindingOperationInfo;
import org.apache.cxf.service.model.EndpointInfo;
import org.apache.cxf.service.model.InterfaceInfo;
import org.apache.cxf.service.model.MessageInfo;
import org.apache.cxf.service.model.MessageInfo.Type;
import org.apache.cxf.service.model.MessagePartInfo;
import org.apache.cxf.service.model.OperationInfo;
import org.apache.cxf.service.model.ServiceInfo;
import org.apache.cxf.staxutils.PartialXMLStreamReader;
import org.apache.cxf.staxutils.StaxUtils;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Unit test for testing DocLiteralInInterceptor to use Source Data Binding
*
*/
public class DocLiteralInInterceptorTest {
private static final String NS = "http://cxf.apache.org/wsdl-first/types";
@Test
public void testUnmarshalSourceData() throws Exception {
XMLStreamReader reader = StaxUtils.createXMLStreamReader(getClass()
.getResourceAsStream("resources/multiPartDocLitBareReq.xml"));
assertEquals(XMLStreamConstants.START_ELEMENT, reader.nextTag());
XMLStreamReader filteredReader = new PartialXMLStreamReader(reader,
new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"));
// advance the xml reader to the message parts
StaxUtils.read(filteredReader);
assertEquals(XMLStreamConstants.START_ELEMENT, reader.nextTag());
Message m = new MessageImpl();
Exchange exchange = new ExchangeImpl();
Service service = mock(Service.class);
exchange.put(Service.class, service);
when(service.getDataBinding()).thenReturn(new SourceDataBinding());
when(service.size()).thenReturn(0);
when(service.isEmpty()).thenReturn(true);
Endpoint endpoint = mock(Endpoint.class);
exchange.put(Endpoint.class, endpoint);
OperationInfo operationInfo = new OperationInfo();
operationInfo.setProperty("operation.is.synthetic", Boolean.TRUE);
MessageInfo messageInfo = new MessageInfo(operationInfo, Type.INPUT,
new QName("http://foo.com", "bar"));
messageInfo.addMessagePart(new MessagePartInfo(new QName("http://foo.com", "partInfo1"), null));
messageInfo.addMessagePart(new MessagePartInfo(new QName("http://foo.com", "partInfo2"), null));
messageInfo.addMessagePart(new MessagePartInfo(new QName("http://foo.com", "partInfo3"), null));
messageInfo.addMessagePart(new MessagePartInfo(new QName("http://foo.com", "partInfo4"), null));
for (MessagePartInfo mpi : messageInfo.getMessageParts()) {
mpi.setMessageContainer(messageInfo);
}
operationInfo.setInput("inputName", messageInfo);
BindingOperationInfo boi = new BindingOperationInfo(null, operationInfo);
exchange.put(BindingOperationInfo.class, boi);
EndpointInfo endpointInfo = mock(EndpointInfo.class);
BindingInfo binding = mock(BindingInfo.class);
when(endpoint.getEndpointInfo()).thenReturn(endpointInfo);
when(endpointInfo.getBinding()).thenReturn(binding);
when(binding.getProperties()).thenReturn(new HashMap<String, Object>());
when(endpointInfo.getProperties()).thenReturn(new HashMap<String, Object>());
when(endpoint.size()).thenReturn(0);
when(endpoint.isEmpty()).thenReturn(true);
ServiceInfo serviceInfo = mock(ServiceInfo.class);
when(endpointInfo.getService()).thenReturn(serviceInfo);
when(serviceInfo.getName()).thenReturn(new QName("http://foo.com", "service"));
InterfaceInfo interfaceInfo = mock(InterfaceInfo.class);
when(serviceInfo.getInterface()).thenReturn(interfaceInfo);
when(interfaceInfo.getName()).thenReturn(new QName("http://foo.com", "interface"));
when(endpointInfo.getName()).thenReturn(new QName("http://foo.com", "endpoint"));
when(endpointInfo.getProperty("URI", URI.class)).thenReturn(new URI("dummy"));
List<OperationInfo> operations = new ArrayList<>();
when(interfaceInfo.getOperations()).thenReturn(operations);
m.setExchange(exchange);
m.put(Message.SCHEMA_VALIDATION_ENABLED, false);
m.setContent(XMLStreamReader.class, reader);
new DocLiteralInInterceptor().handleMessage(m);
MessageContentsList params = (MessageContentsList)m.getContent(List.class);
assertEquals(4, params.size());
assertEquals("StringDefaultInputElem",
((DOMSource)params.get(0)).getNode().getFirstChild().getNodeName());
assertEquals("IntParamInElem",
((DOMSource)params.get(1)).getNode().getFirstChild().getNodeName());
}
@Test
public void testUnmarshalSourceDataWrapped() throws Exception {
XMLStreamReader reader = StaxUtils.createXMLStreamReader(getClass()
.getResourceAsStream("resources/docLitWrappedReq.xml"));
assertEquals(XMLStreamConstants.START_ELEMENT, reader.nextTag());
XMLStreamReader filteredReader = new PartialXMLStreamReader(reader,
new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"));
// advance the xml reader to the message parts
StaxUtils.read(filteredReader);
assertEquals(XMLStreamConstants.START_ELEMENT, reader.nextTag());
Message m = new MessageImpl();
// request to keep the document as wrapped
m.put(DocLiteralInInterceptor.KEEP_PARAMETERS_WRAPPER, true);
Exchange exchange = new ExchangeImpl();
Service service = mock(Service.class);
exchange.put(Service.class, service);
when(service.getDataBinding()).thenReturn(new SourceDataBinding());
when(service.size()).thenReturn(0);
when(service.isEmpty()).thenReturn(true);
Endpoint endpoint = mock(Endpoint.class);
exchange.put(Endpoint.class, endpoint);
// wrapped
OperationInfo operationInfo = new OperationInfo();
MessageInfo messageInfo = new MessageInfo(operationInfo, Type.INPUT, new QName(NS, "foo"));
messageInfo.addMessagePart(new MessagePartInfo(new QName(NS, "personId"), null));
messageInfo.addMessagePart(new MessagePartInfo(new QName(NS, "ssn"), null));
messageInfo.getMessagePart(0).setConcreteName(new QName(NS, "personId"));
messageInfo.getMessagePart(1).setConcreteName(new QName(NS, "ssn"));
operationInfo.setInput("inputName", messageInfo);
// wrapper
OperationInfo operationInfoWrapper = new OperationInfo();
MessageInfo messageInfoWrapper = new MessageInfo(operationInfo, Type.INPUT, new QName(NS, "foo"));
messageInfoWrapper.addMessagePart(new MessagePartInfo(new QName(NS, "GetPerson"), null));
messageInfoWrapper.getMessagePart(0).setConcreteName(new QName(NS, "GetPerson"));
operationInfoWrapper.setInput("inputName", messageInfoWrapper);
operationInfoWrapper.setUnwrappedOperation(operationInfo);
ServiceInfo serviceInfo = mock(ServiceInfo.class);
when(serviceInfo.getName()).thenReturn(new QName("http://foo.com", "service"));
InterfaceInfo interfaceInfo = mock(InterfaceInfo.class);
when(serviceInfo.getInterface()).thenReturn(interfaceInfo);
when(interfaceInfo.getName()).thenReturn(new QName("http://foo.com", "interface"));
BindingInfo bindingInfo = new BindingInfo(serviceInfo, "");
BindingOperationInfo boi = new BindingOperationInfo(bindingInfo, operationInfoWrapper);
exchange.put(BindingOperationInfo.class, boi);
EndpointInfo endpointInfo = mock(EndpointInfo.class);
BindingInfo binding = mock(BindingInfo.class);
when(endpoint.getEndpointInfo()).thenReturn(endpointInfo);
when(endpointInfo.getBinding()).thenReturn(binding);
when(binding.getProperties()).thenReturn(new HashMap<String, Object>());
when(endpointInfo.getProperties()).thenReturn(new HashMap<String, Object>());
when(endpoint.size()).thenReturn(0);
when(endpoint.isEmpty()).thenReturn(true);
when(endpointInfo.getService()).thenReturn(serviceInfo);
when(endpointInfo.getName()).thenReturn(new QName("http://foo.com", "endpoint"));
when(endpointInfo.getProperty("URI", URI.class)).thenReturn(new URI("dummy"));
List<OperationInfo> operations = new ArrayList<>();
when(interfaceInfo.getOperations()).thenReturn(operations);
m.setExchange(exchange);
m.put(Message.SCHEMA_VALIDATION_ENABLED, false);
m.setContent(XMLStreamReader.class, reader);
new DocLiteralInInterceptor().handleMessage(m);
MessageContentsList params = (MessageContentsList)m.getContent(List.class);
// we expect a wrapped document
assertEquals(1, params.size());
Map<String, String> ns = new HashMap<>();
ns.put("ns", NS);
XPathUtils xu = new XPathUtils(ns);
assertEquals("hello", xu.getValueString("//ns:GetPerson/ns:personId",
((DOMSource)params.get(0)).getNode().getFirstChild()));
assertEquals("1234", xu.getValueString("//ns:GetPerson/ns:ssn",
((DOMSource)params.get(0)).getNode().getFirstChild()));
}
} | 11,043 | 0.702345 | 0.700082 | 245 | 44.077553 | 31.023462 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.918367 | false | false | 5 |
7f50ff69469a811888ae61edc1ca6992adbcd990 | 8,461,085,641,282 | da776a3defea5157b52c9a4a8db362e8c76fdd3b | /parent/parent-common/common-module-crawler/src/main/java/com/crawler/pbccrc/json/LoginData.java | 2bb9d8a8082b974e4522a4510baf4404ae3cc948 | []
| no_license | moutainhigh/crawler | https://github.com/moutainhigh/crawler | d4f306d74a9f16bce3490d4dbdcedad953120f97 | 4c201cdf24a025d0b1056188e0f0f4beee0b80aa | refs/heads/master | 2020-09-21T12:22:54.075000 | 2018-11-06T04:33:15 | 2018-11-06T04:33:15 | 224,787,613 | 1 | 0 | null | true | 2019-11-29T06:06:28 | 2019-11-29T06:06:28 | 2018-12-04T07:12:15 | 2018-11-06T05:12:35 | 64,796 | 0 | 0 | 0 | null | false | false | package com.crawler.pbccrc.json;
import com.gargoylesoftware.htmlunit.util.Cookie;
import java.io.Serializable;
import java.util.Set;
public class LoginData implements Serializable {
/**
*
*/
private static final long serialVersionUID = -3350030291792254007L;
private String statusCode;
private String message;
private Set<Cookie> cookies;
private String codeImageUrl;
private String codeValue;
public LoginData() {
super();
}
public LoginData(String statusCode, String message, Set<Cookie> cookies) {
this.statusCode = statusCode;
this.message = message;
this.cookies = cookies;
}
public String getStatusCode() {
return statusCode;
}
public void setStatusCode(String statusCode) {
this.statusCode = statusCode;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Set<Cookie> getCookies() {
return cookies;
}
public void setCookies(Set<Cookie> cookies) {
this.cookies = cookies;
}
public String getCodeImageUrl() {
return codeImageUrl;
}
public void setCodeImageUrl(String codeImageUrl) {
this.codeImageUrl = codeImageUrl;
}
public String getCodeValue() {
return codeValue;
}
public void setCodeValue(String codeValue) {
this.codeValue = codeValue;
}
@Override
public String toString() {
return "LoginData [statusCode=" + statusCode + ", message=" + message
+ ", cookies=" + cookies + ", codeImageUrl=" + codeImageUrl
+ ", codeValue=" + codeValue + "]";
}
}
| UTF-8 | Java | 1,521 | java | LoginData.java | Java | []
| null | []
| package com.crawler.pbccrc.json;
import com.gargoylesoftware.htmlunit.util.Cookie;
import java.io.Serializable;
import java.util.Set;
public class LoginData implements Serializable {
/**
*
*/
private static final long serialVersionUID = -3350030291792254007L;
private String statusCode;
private String message;
private Set<Cookie> cookies;
private String codeImageUrl;
private String codeValue;
public LoginData() {
super();
}
public LoginData(String statusCode, String message, Set<Cookie> cookies) {
this.statusCode = statusCode;
this.message = message;
this.cookies = cookies;
}
public String getStatusCode() {
return statusCode;
}
public void setStatusCode(String statusCode) {
this.statusCode = statusCode;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Set<Cookie> getCookies() {
return cookies;
}
public void setCookies(Set<Cookie> cookies) {
this.cookies = cookies;
}
public String getCodeImageUrl() {
return codeImageUrl;
}
public void setCodeImageUrl(String codeImageUrl) {
this.codeImageUrl = codeImageUrl;
}
public String getCodeValue() {
return codeValue;
}
public void setCodeValue(String codeValue) {
this.codeValue = codeValue;
}
@Override
public String toString() {
return "LoginData [statusCode=" + statusCode + ", message=" + message
+ ", cookies=" + cookies + ", codeImageUrl=" + codeImageUrl
+ ", codeValue=" + codeValue + "]";
}
}
| 1,521 | 0.718606 | 0.706114 | 73 | 19.835617 | 19.664316 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.452055 | false | false | 5 |
ee8259f50af74fc67b41f1c2f22d60d51dacde30 | 15,092,515,080,945 | 480507f0b2667ce7e3abf08d9c517f6adc4e4a9c | /src/main/java/cz/pedry/examplespringapp/controller/ExampleController.java | 9bd89faf93d201676b88c050de9e1b917471abf2 | [
"Apache-2.0"
]
| permissive | ppedrycz/nohibernate-spring-example | https://github.com/ppedrycz/nohibernate-spring-example | fa445fcc25e75f0d7215a845e1ce49dd009fa0d8 | e8950b8409ec1712777a6d3693bc8c402fe1b761 | refs/heads/master | 2021-01-20T01:25:31.308000 | 2017-05-04T14:23:49 | 2017-05-04T14:23:49 | 89,277,422 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cz.pedry.examplespringapp.controller;
import cz.pedry.examplespringapp.entity.Sprite;
import cz.pedry.examplespringapp.model.Circle;
import cz.pedry.examplespringapp.model.Rectangle;
import cz.pedry.examplespringapp.repository.SpriteRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ExampleController {
@Autowired
private SpriteRepository spriteRepository;
@RequestMapping("/")
public String mainPage() {
spriteRepository.save(new Sprite(new Circle(Math.random(), Math.random(), Math.random())));
spriteRepository.save(new Sprite(new Rectangle(Math.random(), Math.random(), Math.random() + 1, Math.random() + 1)));
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Two Sprites are added on page refresh. <br/>\n");
stringBuilder.append("Every Sprite has one Geometry, every geometry = one cell in database <br/>\n");
stringBuilder.append("Geometry can be Circle or Rectangle <br/>\n");
stringBuilder.append("Actual list of Sprites: <br/>\n");
stringBuilder.append("<br/>\n");
Iterable<Sprite> allSprites = spriteRepository.findAll();
for (Sprite s : allSprites) {
stringBuilder.append(s + "<br/>\n");
}
return stringBuilder.toString();
}
}
| UTF-8 | Java | 1,488 | java | ExampleController.java | Java | []
| null | []
| package cz.pedry.examplespringapp.controller;
import cz.pedry.examplespringapp.entity.Sprite;
import cz.pedry.examplespringapp.model.Circle;
import cz.pedry.examplespringapp.model.Rectangle;
import cz.pedry.examplespringapp.repository.SpriteRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ExampleController {
@Autowired
private SpriteRepository spriteRepository;
@RequestMapping("/")
public String mainPage() {
spriteRepository.save(new Sprite(new Circle(Math.random(), Math.random(), Math.random())));
spriteRepository.save(new Sprite(new Rectangle(Math.random(), Math.random(), Math.random() + 1, Math.random() + 1)));
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Two Sprites are added on page refresh. <br/>\n");
stringBuilder.append("Every Sprite has one Geometry, every geometry = one cell in database <br/>\n");
stringBuilder.append("Geometry can be Circle or Rectangle <br/>\n");
stringBuilder.append("Actual list of Sprites: <br/>\n");
stringBuilder.append("<br/>\n");
Iterable<Sprite> allSprites = spriteRepository.findAll();
for (Sprite s : allSprites) {
stringBuilder.append(s + "<br/>\n");
}
return stringBuilder.toString();
}
}
| 1,488 | 0.714382 | 0.713038 | 38 | 38.157894 | 33.126968 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.684211 | false | false | 5 |
2a615297498498fb21f47a93d86a46cbca9b015f | 29,661,044,146,698 | 22795f9dbaad1de84f747f9791a28c6173ed3bca | /test.core/koopa/core/data/test/TokensTest.java | 40e6152ab2e74bb343bf1a9cd3c456a2bdd46622 | []
| no_license | benravago/koopa | https://github.com/benravago/koopa | f9d1a36f61b86e3b417a574d1a5902db12c01bb3 | e03690fd834574572d95bf60ca8b9eb0effce869 | refs/heads/master | 2020-07-02T22:34:47.412000 | 2019-12-29T19:35:01 | 2019-12-29T19:35:01 | 201,689,942 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package koopa.core.data.test;
import static koopa.core.util.test.Util.asListOfRanges;
import java.util.ArrayList;
import java.util.Arrays;
import koopa.core.data.Position;
import koopa.core.data.Token;
import koopa.core.data.Tokens;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/**
* Tests the different operations in {@linkplain Tokens}.
*/
class TokensTest {
static String TEXT = "One accurate measurement is worth a thousand expert opinions.";
static int LENGTH = TEXT.length();
static Position START = new Position(0, 0, 0);
static Position STOP = START.offsetBy(LENGTH - 1);
static Token TOKEN = new Token(TEXT, START, STOP);
@Test
void testFullSubtokenIsSameAsOriginal() {
var t = new Token(TEXT, START, STOP);
var sub = Tokens.subtoken(t, 0, LENGTH);
assertSame(t, sub);
}
@Test
void testAnyLengthSubtokens() {
var t = new Token(TEXT, START, STOP);
for (var l = 0; l < LENGTH; l++) {
for (var i = 0; i < LENGTH - l; i++) {
var sub = Tokens.subtoken(t, i, i + l);
assertEquals(TEXT.substring(i, i + l), sub.getText());
assertEquals(l, sub.getLength());
}
}
}
@Test
void testFullSubtokenToEndIsSameAsOriginal() {
var t = new Token(TEXT, START, STOP);
var sub = Tokens.subtoken(t, 0);
assertSame(t, sub);
}
@Test
void testCanHasSubtokenToEnd() {
var t = new Token(TEXT, START, STOP);
var from = LENGTH / 4;
var sub = Tokens.subtoken(t, from);
assertEquals(TEXT.substring(from), sub.getText());
assertEquals(LENGTH - from, sub.getLength());
assertEquals(asListOfRanges(from, LENGTH - 1), sub.getRanges());
}
@Test
void testCanHasSubtoken() {
var t = new Token(TEXT, START, STOP);
var from = LENGTH / 4;
var to = from + LENGTH / 2;
var sub = Tokens.subtoken(t, from, to);
assertEquals(TEXT.substring(from, to), sub.getText());
assertEquals(to - from, sub.getLength());
assertEquals(asListOfRanges(from, to - 1), sub.getRanges());
}
@Test
void testSubtokensInheritTags() {
var t = new Token(TEXT, START, STOP, "Quote", "Grace Hopper");
var sub = Tokens.subtoken(t, LENGTH / 2);
assertEquals(t.getTags(), sub.getTags());
}
Token tokenFromRanges(int... positions) {
var parts = new ArrayList<Token>(positions.length / 2);
for (var i = 0; i < positions.length; i += 2) {
parts.add(Tokens.subtoken(TOKEN, positions[i], positions[i + 1]));
}
return Tokens.join(parts);
}
@Test
void testSubtokenToEndSplitsRanges1() {
var mid = LENGTH / 2;
var t = tokenFromRanges(0, mid, mid, LENGTH);
var from = mid / 2;
var sub = Tokens.subtoken(t, from);
var substring = TEXT.substring(from);
assertEquals(substring, sub.getText());
assertEquals(substring.length(), sub.getLength());
assertEquals(asListOfRanges(from, mid - 1, mid, LENGTH - 1), sub.getRanges());
}
@Test
void testSubtokenToEndSplitsRanges2() {
var mid = LENGTH / 2;
var t = tokenFromRanges(0, mid, mid, LENGTH);
var from = mid + mid / 2;
var sub = Tokens.subtoken(t, from);
var substring = TEXT.substring(from);
assertEquals(substring, sub.getText());
assertEquals(substring.length(), sub.getLength());
assertEquals(asListOfRanges(from, LENGTH - 1), sub.getRanges());
}
@Test
void testSubtokenSplitsRanges() {
var mid = LENGTH / 2;
var t = tokenFromRanges(0, mid, mid, LENGTH);
var from = mid / 2;
var to = mid + mid / 2;
var sub = Tokens.subtoken(t, from, to);
var substring = TEXT.substring(from, to);
assertEquals(substring, sub.getText());
assertEquals(substring.length(), sub.getLength());
assertEquals(asListOfRanges(from, mid - 1, mid, to - 1), sub.getRanges());
}
@Test
void testCanSplitToken() {
var t = tokenFromRanges(0, LENGTH);
var mid = LENGTH / 2;
var tokens = Tokens.split(t, mid);
assertEquals(2, tokens.length);
var first = tokens[0];
var second = tokens[1];
assertEquals(TEXT.substring(0, mid), first.getText());
assertEquals(TEXT.substring(mid, LENGTH), second.getText());
assertEquals(asListOfRanges(0, mid - 1), first.getRanges());
assertEquals(asListOfRanges(mid, LENGTH - 1), second.getRanges());
}
@Test
void testCanJoinTokens() {
var t1 = new Token(TEXT, START, STOP, "Quote", "Grace Hopper");
var text = "From then on, when anything went wrong with a computer, we said it had bugs in it.";
var length = text.length();
var start = STOP.offsetBy(1);
var end = start.offsetBy(length - 1);
var t2 = new Token(text, start, end, "Cobol");
var t = Tokens.join(Arrays.asList(new Token[]{t1, t2}));
var expected = TEXT + text;
assertEquals(expected, t.getText());
assertEquals(expected.length(), t.getLength());
// The combined token does not inherit the tags from its parts.
assertEquals(0, t.getTags().size());
assertEquals( asListOfRanges(0, LENGTH - 1, LENGTH, LENGTH + length - 1), t.getRanges() );
}
}
| UTF-8 | Java | 5,498 | java | TokensTest.java | Java | [
{
"context": " var t = new Token(TEXT, START, STOP, \"Quote\", \"Grace Hopper\");\n var sub = Tokens.subtoken(t, LENGTH / ",
"end": 2333,
"score": 0.9891152381896973,
"start": 2321,
"tag": "NAME",
"value": "Grace Hopper"
},
{
"context": " var t1 = new Token(TEXT, START, STOP, \"Quote\", \"Grace Hopper\");\n var text = \"From then on, when anythin",
"end": 4787,
"score": 0.9997339248657227,
"start": 4775,
"tag": "NAME",
"value": "Grace Hopper"
}
]
| null | []
| package koopa.core.data.test;
import static koopa.core.util.test.Util.asListOfRanges;
import java.util.ArrayList;
import java.util.Arrays;
import koopa.core.data.Position;
import koopa.core.data.Token;
import koopa.core.data.Tokens;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/**
* Tests the different operations in {@linkplain Tokens}.
*/
class TokensTest {
static String TEXT = "One accurate measurement is worth a thousand expert opinions.";
static int LENGTH = TEXT.length();
static Position START = new Position(0, 0, 0);
static Position STOP = START.offsetBy(LENGTH - 1);
static Token TOKEN = new Token(TEXT, START, STOP);
@Test
void testFullSubtokenIsSameAsOriginal() {
var t = new Token(TEXT, START, STOP);
var sub = Tokens.subtoken(t, 0, LENGTH);
assertSame(t, sub);
}
@Test
void testAnyLengthSubtokens() {
var t = new Token(TEXT, START, STOP);
for (var l = 0; l < LENGTH; l++) {
for (var i = 0; i < LENGTH - l; i++) {
var sub = Tokens.subtoken(t, i, i + l);
assertEquals(TEXT.substring(i, i + l), sub.getText());
assertEquals(l, sub.getLength());
}
}
}
@Test
void testFullSubtokenToEndIsSameAsOriginal() {
var t = new Token(TEXT, START, STOP);
var sub = Tokens.subtoken(t, 0);
assertSame(t, sub);
}
@Test
void testCanHasSubtokenToEnd() {
var t = new Token(TEXT, START, STOP);
var from = LENGTH / 4;
var sub = Tokens.subtoken(t, from);
assertEquals(TEXT.substring(from), sub.getText());
assertEquals(LENGTH - from, sub.getLength());
assertEquals(asListOfRanges(from, LENGTH - 1), sub.getRanges());
}
@Test
void testCanHasSubtoken() {
var t = new Token(TEXT, START, STOP);
var from = LENGTH / 4;
var to = from + LENGTH / 2;
var sub = Tokens.subtoken(t, from, to);
assertEquals(TEXT.substring(from, to), sub.getText());
assertEquals(to - from, sub.getLength());
assertEquals(asListOfRanges(from, to - 1), sub.getRanges());
}
@Test
void testSubtokensInheritTags() {
var t = new Token(TEXT, START, STOP, "Quote", "<NAME>");
var sub = Tokens.subtoken(t, LENGTH / 2);
assertEquals(t.getTags(), sub.getTags());
}
Token tokenFromRanges(int... positions) {
var parts = new ArrayList<Token>(positions.length / 2);
for (var i = 0; i < positions.length; i += 2) {
parts.add(Tokens.subtoken(TOKEN, positions[i], positions[i + 1]));
}
return Tokens.join(parts);
}
@Test
void testSubtokenToEndSplitsRanges1() {
var mid = LENGTH / 2;
var t = tokenFromRanges(0, mid, mid, LENGTH);
var from = mid / 2;
var sub = Tokens.subtoken(t, from);
var substring = TEXT.substring(from);
assertEquals(substring, sub.getText());
assertEquals(substring.length(), sub.getLength());
assertEquals(asListOfRanges(from, mid - 1, mid, LENGTH - 1), sub.getRanges());
}
@Test
void testSubtokenToEndSplitsRanges2() {
var mid = LENGTH / 2;
var t = tokenFromRanges(0, mid, mid, LENGTH);
var from = mid + mid / 2;
var sub = Tokens.subtoken(t, from);
var substring = TEXT.substring(from);
assertEquals(substring, sub.getText());
assertEquals(substring.length(), sub.getLength());
assertEquals(asListOfRanges(from, LENGTH - 1), sub.getRanges());
}
@Test
void testSubtokenSplitsRanges() {
var mid = LENGTH / 2;
var t = tokenFromRanges(0, mid, mid, LENGTH);
var from = mid / 2;
var to = mid + mid / 2;
var sub = Tokens.subtoken(t, from, to);
var substring = TEXT.substring(from, to);
assertEquals(substring, sub.getText());
assertEquals(substring.length(), sub.getLength());
assertEquals(asListOfRanges(from, mid - 1, mid, to - 1), sub.getRanges());
}
@Test
void testCanSplitToken() {
var t = tokenFromRanges(0, LENGTH);
var mid = LENGTH / 2;
var tokens = Tokens.split(t, mid);
assertEquals(2, tokens.length);
var first = tokens[0];
var second = tokens[1];
assertEquals(TEXT.substring(0, mid), first.getText());
assertEquals(TEXT.substring(mid, LENGTH), second.getText());
assertEquals(asListOfRanges(0, mid - 1), first.getRanges());
assertEquals(asListOfRanges(mid, LENGTH - 1), second.getRanges());
}
@Test
void testCanJoinTokens() {
var t1 = new Token(TEXT, START, STOP, "Quote", "<NAME>");
var text = "From then on, when anything went wrong with a computer, we said it had bugs in it.";
var length = text.length();
var start = STOP.offsetBy(1);
var end = start.offsetBy(length - 1);
var t2 = new Token(text, start, end, "Cobol");
var t = Tokens.join(Arrays.asList(new Token[]{t1, t2}));
var expected = TEXT + text;
assertEquals(expected, t.getText());
assertEquals(expected.length(), t.getLength());
// The combined token does not inherit the tags from its parts.
assertEquals(0, t.getTags().size());
assertEquals( asListOfRanges(0, LENGTH - 1, LENGTH, LENGTH + length - 1), t.getRanges() );
}
}
| 5,486 | 0.598218 | 0.588396 | 158 | 33.79747 | 24.50956 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.253165 | false | false | 5 |
b4791db0bc9b060c73f555ba5cc9f3c8816175e5 | 6,657,199,346,008 | 163047bd2995cb2d12a72a9cd532e448578f91f7 | /src/main/java/com/echeng/resumeparser/domain/resume/Employment.java | 109b3b44e530edd60b93b9ef6defaeef38f98eae | []
| no_license | doudou0o/resumeParser | https://github.com/doudou0o/resumeParser | 33fb0dee745a0203af7aade01e1a5c999d40a607 | 2f6338da85fd4395cae13dd9c457c8833a241999 | refs/heads/master | 2021-01-18T07:28:38.742000 | 2017-03-13T09:19:43 | 2017-03-13T09:19:43 | 84,289,420 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.echeng.resumeparser.domain.resume;
public class Employment {
}
| UTF-8 | Java | 77 | java | Employment.java | Java | []
| null | []
| package com.echeng.resumeparser.domain.resume;
public class Employment {
}
| 77 | 0.792208 | 0.792208 | 5 | 14.4 | 18.467268 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false | 5 |
4c7f12f6ac2803a92f270d4d270ec4a64f4ffeab | 13,451,837,583,378 | 52d12ffd0667ea14747a8d0edb049dffce298e5b | /code-processor/src/test/java/br/com/objectos/code/processor/ServicesProcessorTest.java | 06ecadd6954ee68ceed74d792c648998e20a5546 | [
"Apache-2.0"
]
| permissive | objectos/code | https://github.com/objectos/code | 4270d29d4ac089b009f4348d482b81110e291655 | f5e9dfc532268d7aeb59e7d223b478bade4ff14b | refs/heads/master | 2022-03-18T01:33:32.793000 | 2022-03-01T14:30:34 | 2022-03-01T14:30:34 | 35,187,154 | 0 | 0 | null | false | 2015-11-02T13:21:29 | 2015-05-06T23:00:05 | 2015-10-12T18:34:48 | 2015-11-02T13:21:29 | 3,964 | 0 | 0 | 1 | Java | null | null | /*
* Copyright (C) 2014-2022 Objectos Software LTDA.
*
* 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 br.com.objectos.code.processor;
import static br.com.objectos.tools.Tools.compilationUnit;
import static br.com.objectos.tools.Tools.javac;
import static br.com.objectos.tools.Tools.processor;
import static org.testng.Assert.assertEquals;
import br.com.objectos.tools.Compilation;
import org.testng.annotations.Test;
public class ServicesProcessorTest {
static final String PROCESSOR = "META-INF/services/javax.annotation.processing.Processor";
@Test
public void test() {
Compilation compilation = javac(
processor(new ServicesProcessor()),
compilationUnit(
"package pkg01;",
"import javax.annotation.processing.Processor;",
"@br.com.objectos.code.annotations.Services(Processor.class)",
"public class Processor01 {}"
),
compilationUnit(
"package pkg02;",
"import javax.annotation.processing.Processor;",
"@br.com.objectos.code.annotations.Services(Processor.class)",
"public class Processor02 {}"
)
);
compilation.assertWasSuccessful();
assertHasLines(
compilation.getResource(PROCESSOR).contents(),
"pkg01.Processor01",
"pkg02.Processor02"
);
}
private void assertHasLines(String contents, String... expected) {
String[] parts;
parts = contents.split("\n");
assertEquals(parts, expected);
}
}
| UTF-8 | Java | 2,029 | java | ServicesProcessorTest.java | Java | []
| null | []
| /*
* Copyright (C) 2014-2022 Objectos Software LTDA.
*
* 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 br.com.objectos.code.processor;
import static br.com.objectos.tools.Tools.compilationUnit;
import static br.com.objectos.tools.Tools.javac;
import static br.com.objectos.tools.Tools.processor;
import static org.testng.Assert.assertEquals;
import br.com.objectos.tools.Compilation;
import org.testng.annotations.Test;
public class ServicesProcessorTest {
static final String PROCESSOR = "META-INF/services/javax.annotation.processing.Processor";
@Test
public void test() {
Compilation compilation = javac(
processor(new ServicesProcessor()),
compilationUnit(
"package pkg01;",
"import javax.annotation.processing.Processor;",
"@br.com.objectos.code.annotations.Services(Processor.class)",
"public class Processor01 {}"
),
compilationUnit(
"package pkg02;",
"import javax.annotation.processing.Processor;",
"@br.com.objectos.code.annotations.Services(Processor.class)",
"public class Processor02 {}"
)
);
compilation.assertWasSuccessful();
assertHasLines(
compilation.getResource(PROCESSOR).contents(),
"pkg01.Processor01",
"pkg02.Processor02"
);
}
private void assertHasLines(String contents, String... expected) {
String[] parts;
parts = contents.split("\n");
assertEquals(parts, expected);
}
}
| 2,029 | 0.693445 | 0.679645 | 64 | 30.703125 | 25.712156 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.546875 | false | false | 5 |
f53350c1ed669f02bd74095adfd49510c2af8989 | 29,996,051,658,093 | daadde5bcbf205a943e84553f5267535e259f53b | /src/test/java/com/worktajm/gw/web/rest/TimeEntryResourceIntTest.java | af3d5c0bfc6a5ca364842b1c84b5a850bb806ab0 | []
| no_license | hirro/worktajm-jh-gw | https://github.com/hirro/worktajm-jh-gw | 4b2c3cf9eecafcf0034cd4f0c8692d6045f74c45 | f7d586f98fc30c638e892902d522cbd6adfd2bc4 | refs/heads/master | 2021-01-01T04:21:15.663000 | 2017-07-03T08:47:46 | 2017-07-03T08:47:46 | 59,433,626 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.worktajm.gw.web.rest;
import com.worktajm.gw.WorktajmApp;
import com.worktajm.gw.domain.TimeEntry;
import com.worktajm.gw.repository.TimeEntryRepository;
import com.worktajm.gw.repository.search.TimeEntrySearchRepository;
import com.worktajm.gw.service.dto.TimeEntryDTO;
import com.worktajm.gw.service.mapper.TimeEntryMapper;
import com.worktajm.gw.web.rest.errors.ExceptionTranslator;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import java.time.Instant;
import java.time.ZonedDateTime;
import java.time.ZoneOffset;
import java.time.ZoneId;
import java.util.List;
import static com.worktajm.gw.web.rest.TestUtil.sameInstant;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Test class for the TimeEntryResource REST controller.
*
* @see TimeEntryResource
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = WorktajmApp.class)
public class TimeEntryResourceIntTest {
private static final ZonedDateTime DEFAULT_START = ZonedDateTime.ofInstant(Instant.ofEpochMilli(0L), ZoneOffset.UTC);
private static final ZonedDateTime UPDATED_START = ZonedDateTime.now(ZoneId.systemDefault()).withNano(0);
private static final ZonedDateTime DEFAULT_END = ZonedDateTime.ofInstant(Instant.ofEpochMilli(0L), ZoneOffset.UTC);
private static final ZonedDateTime UPDATED_END = ZonedDateTime.now(ZoneId.systemDefault()).withNano(0);
private static final String DEFAULT_COMMENT = "AAAAAAAAAA";
private static final String UPDATED_COMMENT = "BBBBBBBBBB";
@Autowired
private TimeEntryRepository timeEntryRepository;
@Autowired
private TimeEntryMapper timeEntryMapper;
@Autowired
private TimeEntrySearchRepository timeEntrySearchRepository;
@Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
@Autowired
private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
@Autowired
private ExceptionTranslator exceptionTranslator;
@Autowired
private EntityManager em;
private MockMvc restTimeEntryMockMvc;
private TimeEntry timeEntry;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
TimeEntryResource timeEntryResource = new TimeEntryResource(timeEntryRepository, timeEntryMapper, timeEntrySearchRepository);
this.restTimeEntryMockMvc = MockMvcBuilders.standaloneSetup(timeEntryResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setMessageConverters(jacksonMessageConverter).build();
}
/**
* Create an entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static TimeEntry createEntity(EntityManager em) {
TimeEntry timeEntry = new TimeEntry()
.start(DEFAULT_START)
.end(DEFAULT_END)
.comment(DEFAULT_COMMENT);
return timeEntry;
}
@Before
public void initTest() {
timeEntrySearchRepository.deleteAll();
timeEntry = createEntity(em);
}
@Test
@Transactional
public void createTimeEntry() throws Exception {
int databaseSizeBeforeCreate = timeEntryRepository.findAll().size();
// Create the TimeEntry
TimeEntryDTO timeEntryDTO = timeEntryMapper.toDto(timeEntry);
restTimeEntryMockMvc.perform(post("/api/time-entries")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(timeEntryDTO)))
.andExpect(status().isCreated());
// Validate the TimeEntry in the database
List<TimeEntry> timeEntryList = timeEntryRepository.findAll();
assertThat(timeEntryList).hasSize(databaseSizeBeforeCreate + 1);
TimeEntry testTimeEntry = timeEntryList.get(timeEntryList.size() - 1);
assertThat(testTimeEntry.getStart()).isEqualTo(DEFAULT_START);
assertThat(testTimeEntry.getEnd()).isEqualTo(DEFAULT_END);
assertThat(testTimeEntry.getComment()).isEqualTo(DEFAULT_COMMENT);
// Validate the TimeEntry in Elasticsearch
TimeEntry timeEntryEs = timeEntrySearchRepository.findOne(testTimeEntry.getId());
assertThat(timeEntryEs).isEqualToComparingFieldByField(testTimeEntry);
}
@Test
@Transactional
public void createTimeEntryWithExistingId() throws Exception {
int databaseSizeBeforeCreate = timeEntryRepository.findAll().size();
// Create the TimeEntry with an existing ID
timeEntry.setId(1L);
TimeEntryDTO timeEntryDTO = timeEntryMapper.toDto(timeEntry);
// An entity with an existing ID cannot be created, so this API call must fail
restTimeEntryMockMvc.perform(post("/api/time-entries")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(timeEntryDTO)))
.andExpect(status().isBadRequest());
// Validate the Alice in the database
List<TimeEntry> timeEntryList = timeEntryRepository.findAll();
assertThat(timeEntryList).hasSize(databaseSizeBeforeCreate);
}
@Test
@Transactional
public void checkStartIsRequired() throws Exception {
int databaseSizeBeforeTest = timeEntryRepository.findAll().size();
// set the field null
timeEntry.setStart(null);
// Create the TimeEntry, which fails.
TimeEntryDTO timeEntryDTO = timeEntryMapper.toDto(timeEntry);
restTimeEntryMockMvc.perform(post("/api/time-entries")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(timeEntryDTO)))
.andExpect(status().isBadRequest());
List<TimeEntry> timeEntryList = timeEntryRepository.findAll();
assertThat(timeEntryList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
public void getAllTimeEntries() throws Exception {
// Initialize the database
timeEntryRepository.saveAndFlush(timeEntry);
// Get all the timeEntryList
restTimeEntryMockMvc.perform(get("/api/time-entries?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(timeEntry.getId().intValue())))
.andExpect(jsonPath("$.[*].start").value(hasItem(sameInstant(DEFAULT_START))))
.andExpect(jsonPath("$.[*].end").value(hasItem(sameInstant(DEFAULT_END))))
.andExpect(jsonPath("$.[*].comment").value(hasItem(DEFAULT_COMMENT.toString())));
}
@Test
@Transactional
public void getTimeEntry() throws Exception {
// Initialize the database
timeEntryRepository.saveAndFlush(timeEntry);
// Get the timeEntry
restTimeEntryMockMvc.perform(get("/api/time-entries/{id}", timeEntry.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.id").value(timeEntry.getId().intValue()))
.andExpect(jsonPath("$.start").value(sameInstant(DEFAULT_START)))
.andExpect(jsonPath("$.end").value(sameInstant(DEFAULT_END)))
.andExpect(jsonPath("$.comment").value(DEFAULT_COMMENT.toString()));
}
@Test
@Transactional
public void getNonExistingTimeEntry() throws Exception {
// Get the timeEntry
restTimeEntryMockMvc.perform(get("/api/time-entries/{id}", Long.MAX_VALUE))
.andExpect(status().isNotFound());
}
@Test
@Transactional
public void updateTimeEntry() throws Exception {
// Initialize the database
timeEntryRepository.saveAndFlush(timeEntry);
timeEntrySearchRepository.save(timeEntry);
int databaseSizeBeforeUpdate = timeEntryRepository.findAll().size();
// Update the timeEntry
TimeEntry updatedTimeEntry = timeEntryRepository.findOne(timeEntry.getId());
updatedTimeEntry
.start(UPDATED_START)
.end(UPDATED_END)
.comment(UPDATED_COMMENT);
TimeEntryDTO timeEntryDTO = timeEntryMapper.toDto(updatedTimeEntry);
restTimeEntryMockMvc.perform(put("/api/time-entries")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(timeEntryDTO)))
.andExpect(status().isOk());
// Validate the TimeEntry in the database
List<TimeEntry> timeEntryList = timeEntryRepository.findAll();
assertThat(timeEntryList).hasSize(databaseSizeBeforeUpdate);
TimeEntry testTimeEntry = timeEntryList.get(timeEntryList.size() - 1);
assertThat(testTimeEntry.getStart()).isEqualTo(UPDATED_START);
assertThat(testTimeEntry.getEnd()).isEqualTo(UPDATED_END);
assertThat(testTimeEntry.getComment()).isEqualTo(UPDATED_COMMENT);
// Validate the TimeEntry in Elasticsearch
TimeEntry timeEntryEs = timeEntrySearchRepository.findOne(testTimeEntry.getId());
assertThat(timeEntryEs).isEqualToComparingFieldByField(testTimeEntry);
}
@Test
@Transactional
public void updateNonExistingTimeEntry() throws Exception {
int databaseSizeBeforeUpdate = timeEntryRepository.findAll().size();
// Create the TimeEntry
TimeEntryDTO timeEntryDTO = timeEntryMapper.toDto(timeEntry);
// If the entity doesn't have an ID, it will be created instead of just being updated
restTimeEntryMockMvc.perform(put("/api/time-entries")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(timeEntryDTO)))
.andExpect(status().isCreated());
// Validate the TimeEntry in the database
List<TimeEntry> timeEntryList = timeEntryRepository.findAll();
assertThat(timeEntryList).hasSize(databaseSizeBeforeUpdate + 1);
}
@Test
@Transactional
public void deleteTimeEntry() throws Exception {
// Initialize the database
timeEntryRepository.saveAndFlush(timeEntry);
timeEntrySearchRepository.save(timeEntry);
int databaseSizeBeforeDelete = timeEntryRepository.findAll().size();
// Get the timeEntry
restTimeEntryMockMvc.perform(delete("/api/time-entries/{id}", timeEntry.getId())
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isOk());
// Validate Elasticsearch is empty
boolean timeEntryExistsInEs = timeEntrySearchRepository.exists(timeEntry.getId());
assertThat(timeEntryExistsInEs).isFalse();
// Validate the database is empty
List<TimeEntry> timeEntryList = timeEntryRepository.findAll();
assertThat(timeEntryList).hasSize(databaseSizeBeforeDelete - 1);
}
@Test
@Transactional
public void searchTimeEntry() throws Exception {
// Initialize the database
timeEntryRepository.saveAndFlush(timeEntry);
timeEntrySearchRepository.save(timeEntry);
// Search the timeEntry
restTimeEntryMockMvc.perform(get("/api/_search/time-entries?query=id:" + timeEntry.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(timeEntry.getId().intValue())))
.andExpect(jsonPath("$.[*].start").value(hasItem(sameInstant(DEFAULT_START))))
.andExpect(jsonPath("$.[*].end").value(hasItem(sameInstant(DEFAULT_END))))
.andExpect(jsonPath("$.[*].comment").value(hasItem(DEFAULT_COMMENT.toString())));
}
@Test
@Transactional
public void equalsVerifier() throws Exception {
TestUtil.equalsVerifier(TimeEntry.class);
TimeEntry timeEntry1 = new TimeEntry();
timeEntry1.setId(1L);
TimeEntry timeEntry2 = new TimeEntry();
timeEntry2.setId(timeEntry1.getId());
assertThat(timeEntry1).isEqualTo(timeEntry2);
timeEntry2.setId(2L);
assertThat(timeEntry1).isNotEqualTo(timeEntry2);
timeEntry1.setId(null);
assertThat(timeEntry1).isNotEqualTo(timeEntry2);
}
@Test
@Transactional
public void dtoEqualsVerifier() throws Exception {
TestUtil.equalsVerifier(TimeEntryDTO.class);
TimeEntryDTO timeEntryDTO1 = new TimeEntryDTO();
timeEntryDTO1.setId(1L);
TimeEntryDTO timeEntryDTO2 = new TimeEntryDTO();
assertThat(timeEntryDTO1).isNotEqualTo(timeEntryDTO2);
timeEntryDTO2.setId(timeEntryDTO1.getId());
assertThat(timeEntryDTO1).isEqualTo(timeEntryDTO2);
timeEntryDTO2.setId(2L);
assertThat(timeEntryDTO1).isNotEqualTo(timeEntryDTO2);
timeEntryDTO1.setId(null);
assertThat(timeEntryDTO1).isNotEqualTo(timeEntryDTO2);
}
@Test
@Transactional
public void testEntityFromId() {
assertThat(timeEntryMapper.fromId(42L).getId()).isEqualTo(42);
assertThat(timeEntryMapper.fromId(null)).isNull();
}
}
| UTF-8 | Java | 14,136 | java | TimeEntryResourceIntTest.java | Java | []
| null | []
| package com.worktajm.gw.web.rest;
import com.worktajm.gw.WorktajmApp;
import com.worktajm.gw.domain.TimeEntry;
import com.worktajm.gw.repository.TimeEntryRepository;
import com.worktajm.gw.repository.search.TimeEntrySearchRepository;
import com.worktajm.gw.service.dto.TimeEntryDTO;
import com.worktajm.gw.service.mapper.TimeEntryMapper;
import com.worktajm.gw.web.rest.errors.ExceptionTranslator;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import java.time.Instant;
import java.time.ZonedDateTime;
import java.time.ZoneOffset;
import java.time.ZoneId;
import java.util.List;
import static com.worktajm.gw.web.rest.TestUtil.sameInstant;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Test class for the TimeEntryResource REST controller.
*
* @see TimeEntryResource
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = WorktajmApp.class)
public class TimeEntryResourceIntTest {
private static final ZonedDateTime DEFAULT_START = ZonedDateTime.ofInstant(Instant.ofEpochMilli(0L), ZoneOffset.UTC);
private static final ZonedDateTime UPDATED_START = ZonedDateTime.now(ZoneId.systemDefault()).withNano(0);
private static final ZonedDateTime DEFAULT_END = ZonedDateTime.ofInstant(Instant.ofEpochMilli(0L), ZoneOffset.UTC);
private static final ZonedDateTime UPDATED_END = ZonedDateTime.now(ZoneId.systemDefault()).withNano(0);
private static final String DEFAULT_COMMENT = "AAAAAAAAAA";
private static final String UPDATED_COMMENT = "BBBBBBBBBB";
@Autowired
private TimeEntryRepository timeEntryRepository;
@Autowired
private TimeEntryMapper timeEntryMapper;
@Autowired
private TimeEntrySearchRepository timeEntrySearchRepository;
@Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
@Autowired
private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
@Autowired
private ExceptionTranslator exceptionTranslator;
@Autowired
private EntityManager em;
private MockMvc restTimeEntryMockMvc;
private TimeEntry timeEntry;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
TimeEntryResource timeEntryResource = new TimeEntryResource(timeEntryRepository, timeEntryMapper, timeEntrySearchRepository);
this.restTimeEntryMockMvc = MockMvcBuilders.standaloneSetup(timeEntryResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setMessageConverters(jacksonMessageConverter).build();
}
/**
* Create an entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static TimeEntry createEntity(EntityManager em) {
TimeEntry timeEntry = new TimeEntry()
.start(DEFAULT_START)
.end(DEFAULT_END)
.comment(DEFAULT_COMMENT);
return timeEntry;
}
@Before
public void initTest() {
timeEntrySearchRepository.deleteAll();
timeEntry = createEntity(em);
}
@Test
@Transactional
public void createTimeEntry() throws Exception {
int databaseSizeBeforeCreate = timeEntryRepository.findAll().size();
// Create the TimeEntry
TimeEntryDTO timeEntryDTO = timeEntryMapper.toDto(timeEntry);
restTimeEntryMockMvc.perform(post("/api/time-entries")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(timeEntryDTO)))
.andExpect(status().isCreated());
// Validate the TimeEntry in the database
List<TimeEntry> timeEntryList = timeEntryRepository.findAll();
assertThat(timeEntryList).hasSize(databaseSizeBeforeCreate + 1);
TimeEntry testTimeEntry = timeEntryList.get(timeEntryList.size() - 1);
assertThat(testTimeEntry.getStart()).isEqualTo(DEFAULT_START);
assertThat(testTimeEntry.getEnd()).isEqualTo(DEFAULT_END);
assertThat(testTimeEntry.getComment()).isEqualTo(DEFAULT_COMMENT);
// Validate the TimeEntry in Elasticsearch
TimeEntry timeEntryEs = timeEntrySearchRepository.findOne(testTimeEntry.getId());
assertThat(timeEntryEs).isEqualToComparingFieldByField(testTimeEntry);
}
@Test
@Transactional
public void createTimeEntryWithExistingId() throws Exception {
int databaseSizeBeforeCreate = timeEntryRepository.findAll().size();
// Create the TimeEntry with an existing ID
timeEntry.setId(1L);
TimeEntryDTO timeEntryDTO = timeEntryMapper.toDto(timeEntry);
// An entity with an existing ID cannot be created, so this API call must fail
restTimeEntryMockMvc.perform(post("/api/time-entries")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(timeEntryDTO)))
.andExpect(status().isBadRequest());
// Validate the Alice in the database
List<TimeEntry> timeEntryList = timeEntryRepository.findAll();
assertThat(timeEntryList).hasSize(databaseSizeBeforeCreate);
}
@Test
@Transactional
public void checkStartIsRequired() throws Exception {
int databaseSizeBeforeTest = timeEntryRepository.findAll().size();
// set the field null
timeEntry.setStart(null);
// Create the TimeEntry, which fails.
TimeEntryDTO timeEntryDTO = timeEntryMapper.toDto(timeEntry);
restTimeEntryMockMvc.perform(post("/api/time-entries")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(timeEntryDTO)))
.andExpect(status().isBadRequest());
List<TimeEntry> timeEntryList = timeEntryRepository.findAll();
assertThat(timeEntryList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
public void getAllTimeEntries() throws Exception {
// Initialize the database
timeEntryRepository.saveAndFlush(timeEntry);
// Get all the timeEntryList
restTimeEntryMockMvc.perform(get("/api/time-entries?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(timeEntry.getId().intValue())))
.andExpect(jsonPath("$.[*].start").value(hasItem(sameInstant(DEFAULT_START))))
.andExpect(jsonPath("$.[*].end").value(hasItem(sameInstant(DEFAULT_END))))
.andExpect(jsonPath("$.[*].comment").value(hasItem(DEFAULT_COMMENT.toString())));
}
@Test
@Transactional
public void getTimeEntry() throws Exception {
// Initialize the database
timeEntryRepository.saveAndFlush(timeEntry);
// Get the timeEntry
restTimeEntryMockMvc.perform(get("/api/time-entries/{id}", timeEntry.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.id").value(timeEntry.getId().intValue()))
.andExpect(jsonPath("$.start").value(sameInstant(DEFAULT_START)))
.andExpect(jsonPath("$.end").value(sameInstant(DEFAULT_END)))
.andExpect(jsonPath("$.comment").value(DEFAULT_COMMENT.toString()));
}
@Test
@Transactional
public void getNonExistingTimeEntry() throws Exception {
// Get the timeEntry
restTimeEntryMockMvc.perform(get("/api/time-entries/{id}", Long.MAX_VALUE))
.andExpect(status().isNotFound());
}
@Test
@Transactional
public void updateTimeEntry() throws Exception {
// Initialize the database
timeEntryRepository.saveAndFlush(timeEntry);
timeEntrySearchRepository.save(timeEntry);
int databaseSizeBeforeUpdate = timeEntryRepository.findAll().size();
// Update the timeEntry
TimeEntry updatedTimeEntry = timeEntryRepository.findOne(timeEntry.getId());
updatedTimeEntry
.start(UPDATED_START)
.end(UPDATED_END)
.comment(UPDATED_COMMENT);
TimeEntryDTO timeEntryDTO = timeEntryMapper.toDto(updatedTimeEntry);
restTimeEntryMockMvc.perform(put("/api/time-entries")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(timeEntryDTO)))
.andExpect(status().isOk());
// Validate the TimeEntry in the database
List<TimeEntry> timeEntryList = timeEntryRepository.findAll();
assertThat(timeEntryList).hasSize(databaseSizeBeforeUpdate);
TimeEntry testTimeEntry = timeEntryList.get(timeEntryList.size() - 1);
assertThat(testTimeEntry.getStart()).isEqualTo(UPDATED_START);
assertThat(testTimeEntry.getEnd()).isEqualTo(UPDATED_END);
assertThat(testTimeEntry.getComment()).isEqualTo(UPDATED_COMMENT);
// Validate the TimeEntry in Elasticsearch
TimeEntry timeEntryEs = timeEntrySearchRepository.findOne(testTimeEntry.getId());
assertThat(timeEntryEs).isEqualToComparingFieldByField(testTimeEntry);
}
@Test
@Transactional
public void updateNonExistingTimeEntry() throws Exception {
int databaseSizeBeforeUpdate = timeEntryRepository.findAll().size();
// Create the TimeEntry
TimeEntryDTO timeEntryDTO = timeEntryMapper.toDto(timeEntry);
// If the entity doesn't have an ID, it will be created instead of just being updated
restTimeEntryMockMvc.perform(put("/api/time-entries")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(timeEntryDTO)))
.andExpect(status().isCreated());
// Validate the TimeEntry in the database
List<TimeEntry> timeEntryList = timeEntryRepository.findAll();
assertThat(timeEntryList).hasSize(databaseSizeBeforeUpdate + 1);
}
@Test
@Transactional
public void deleteTimeEntry() throws Exception {
// Initialize the database
timeEntryRepository.saveAndFlush(timeEntry);
timeEntrySearchRepository.save(timeEntry);
int databaseSizeBeforeDelete = timeEntryRepository.findAll().size();
// Get the timeEntry
restTimeEntryMockMvc.perform(delete("/api/time-entries/{id}", timeEntry.getId())
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isOk());
// Validate Elasticsearch is empty
boolean timeEntryExistsInEs = timeEntrySearchRepository.exists(timeEntry.getId());
assertThat(timeEntryExistsInEs).isFalse();
// Validate the database is empty
List<TimeEntry> timeEntryList = timeEntryRepository.findAll();
assertThat(timeEntryList).hasSize(databaseSizeBeforeDelete - 1);
}
@Test
@Transactional
public void searchTimeEntry() throws Exception {
// Initialize the database
timeEntryRepository.saveAndFlush(timeEntry);
timeEntrySearchRepository.save(timeEntry);
// Search the timeEntry
restTimeEntryMockMvc.perform(get("/api/_search/time-entries?query=id:" + timeEntry.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(timeEntry.getId().intValue())))
.andExpect(jsonPath("$.[*].start").value(hasItem(sameInstant(DEFAULT_START))))
.andExpect(jsonPath("$.[*].end").value(hasItem(sameInstant(DEFAULT_END))))
.andExpect(jsonPath("$.[*].comment").value(hasItem(DEFAULT_COMMENT.toString())));
}
@Test
@Transactional
public void equalsVerifier() throws Exception {
TestUtil.equalsVerifier(TimeEntry.class);
TimeEntry timeEntry1 = new TimeEntry();
timeEntry1.setId(1L);
TimeEntry timeEntry2 = new TimeEntry();
timeEntry2.setId(timeEntry1.getId());
assertThat(timeEntry1).isEqualTo(timeEntry2);
timeEntry2.setId(2L);
assertThat(timeEntry1).isNotEqualTo(timeEntry2);
timeEntry1.setId(null);
assertThat(timeEntry1).isNotEqualTo(timeEntry2);
}
@Test
@Transactional
public void dtoEqualsVerifier() throws Exception {
TestUtil.equalsVerifier(TimeEntryDTO.class);
TimeEntryDTO timeEntryDTO1 = new TimeEntryDTO();
timeEntryDTO1.setId(1L);
TimeEntryDTO timeEntryDTO2 = new TimeEntryDTO();
assertThat(timeEntryDTO1).isNotEqualTo(timeEntryDTO2);
timeEntryDTO2.setId(timeEntryDTO1.getId());
assertThat(timeEntryDTO1).isEqualTo(timeEntryDTO2);
timeEntryDTO2.setId(2L);
assertThat(timeEntryDTO1).isNotEqualTo(timeEntryDTO2);
timeEntryDTO1.setId(null);
assertThat(timeEntryDTO1).isNotEqualTo(timeEntryDTO2);
}
@Test
@Transactional
public void testEntityFromId() {
assertThat(timeEntryMapper.fromId(42L).getId()).isEqualTo(42);
assertThat(timeEntryMapper.fromId(null)).isNull();
}
}
| 14,136 | 0.708758 | 0.704655 | 345 | 39.973911 | 29.977324 | 133 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.431884 | false | false | 5 |
8c2d5c2c54e0c123c55d6b9ceff5092497a20085 | 13,013,750,950,893 | 21a975ab932fae956e3c8c86361dc5131bb782a4 | /app/src/main/java/com/huntdreams/weibo/model/UserModel.java | 53f50e75e586c6bb58aef10d6614a14da52a6a55 | []
| no_license | noprom/HuntWeibo | https://github.com/noprom/HuntWeibo | f76358045d0d19e4d728eb7331b536d653eb36ae | 04e0d726c0bb12ccb41dcd96e29e9f9a72df8b68 | refs/heads/master | 2021-01-10T05:45:12.322000 | 2015-07-18T13:53:26 | 2015-07-18T13:53:26 | 36,376,635 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.huntdreams.weibo.model;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
public class UserModel implements Parcelable
{
public transient long timestamp = System.currentTimeMillis(); // Time when wrote to database
private String nameWithRemark;
// Json mapping fields
public String id;
public String screen_name;
public String name;
public String remark;
public String province;
public String city;
public String location;
public String description;
public String url;
public String profile_image_url;
public String domain;
public String gender;
public int followers_count = 0;
public int friends_count = 0;
public int statuses_count = 0;
public int favourites_count = 0;
public int verified_type = 0;
public String created_at;
public boolean following = false;
public boolean allow_all_act_msg = false;
public boolean geo_enabled = false;
public boolean verified = false;
public boolean allow_all_comment = false;
public String avatar_large;
public String verified_reason;
public boolean follow_me = false;
public int online_status = 0;
public int bi_followers_count = 0;
public String cover_image = "";
public String cover_image_phone = "";
public String getName() {
if (TextUtils.isEmpty(remark)){
return screen_name == null ? name : screen_name;
} else if (nameWithRemark == null){
nameWithRemark = String.format("%s(%s)", (screen_name == null ? name : screen_name), remark);
}
return nameWithRemark;
}
public String getNameNoRemark() {
return screen_name == null ? name : screen_name;
}
public String getCover() {
return cover_image.trim().equals("") ? cover_image_phone : cover_image;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(id);
dest.writeString(screen_name);
dest.writeString(name);
dest.writeString(remark);
dest.writeString(province);
dest.writeString(city);
dest.writeString(location);
dest.writeString(description);
dest.writeString(url);
dest.writeString(profile_image_url);
dest.writeString(domain);
dest.writeString(gender);
dest.writeString(created_at);
dest.writeString(avatar_large);
dest.writeString(verified_reason);
dest.writeInt(followers_count);
dest.writeInt(friends_count);
dest.writeInt(statuses_count);
dest.writeInt(favourites_count);
dest.writeInt(verified_type);
dest.writeInt(online_status);
dest.writeInt(bi_followers_count);
dest.writeString(cover_image_phone);
dest.writeString(cover_image);
dest.writeBooleanArray(new boolean[]{following, allow_all_act_msg, geo_enabled, verified, allow_all_comment});
}
public static final Creator<UserModel> CREATOR = new Creator<UserModel>() {
@Override
public UserModel createFromParcel(Parcel input) {
UserModel ret = new UserModel();
ret.id = input.readString();
ret.screen_name = input.readString();
ret.name = input.readString();
ret.remark = input.readString();
ret.province = input.readString();
ret.city = input.readString();
ret.location = input.readString();
ret.description = input.readString();
ret.url = input.readString();
ret.profile_image_url = input.readString();
ret.domain = input.readString();
ret.gender = input.readString();
ret.created_at = input.readString();
ret.avatar_large = input.readString();
ret.verified_reason = input.readString();
ret.followers_count = input.readInt();
ret.friends_count = input.readInt();
ret.statuses_count = input.readInt();
ret.favourites_count = input.readInt();
ret.verified_type = input.readInt();
ret.online_status = input.readInt();
ret.bi_followers_count = input.readInt();
ret.cover_image_phone = input.readString();
ret.cover_image = input.readString();
boolean[] array = new boolean[5];
input.readBooleanArray(array);
ret.following = array[0];
ret.allow_all_act_msg = array[1];
ret.geo_enabled = array[2];
ret.verified = array[3];
ret.allow_all_comment = array[4];
return ret;
}
@Override
public UserModel[] newArray(int size) {
return new UserModel[size];
}
};
}
| UTF-8 | Java | 4,202 | java | UserModel.java | Java | []
| null | []
| package com.huntdreams.weibo.model;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
public class UserModel implements Parcelable
{
public transient long timestamp = System.currentTimeMillis(); // Time when wrote to database
private String nameWithRemark;
// Json mapping fields
public String id;
public String screen_name;
public String name;
public String remark;
public String province;
public String city;
public String location;
public String description;
public String url;
public String profile_image_url;
public String domain;
public String gender;
public int followers_count = 0;
public int friends_count = 0;
public int statuses_count = 0;
public int favourites_count = 0;
public int verified_type = 0;
public String created_at;
public boolean following = false;
public boolean allow_all_act_msg = false;
public boolean geo_enabled = false;
public boolean verified = false;
public boolean allow_all_comment = false;
public String avatar_large;
public String verified_reason;
public boolean follow_me = false;
public int online_status = 0;
public int bi_followers_count = 0;
public String cover_image = "";
public String cover_image_phone = "";
public String getName() {
if (TextUtils.isEmpty(remark)){
return screen_name == null ? name : screen_name;
} else if (nameWithRemark == null){
nameWithRemark = String.format("%s(%s)", (screen_name == null ? name : screen_name), remark);
}
return nameWithRemark;
}
public String getNameNoRemark() {
return screen_name == null ? name : screen_name;
}
public String getCover() {
return cover_image.trim().equals("") ? cover_image_phone : cover_image;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(id);
dest.writeString(screen_name);
dest.writeString(name);
dest.writeString(remark);
dest.writeString(province);
dest.writeString(city);
dest.writeString(location);
dest.writeString(description);
dest.writeString(url);
dest.writeString(profile_image_url);
dest.writeString(domain);
dest.writeString(gender);
dest.writeString(created_at);
dest.writeString(avatar_large);
dest.writeString(verified_reason);
dest.writeInt(followers_count);
dest.writeInt(friends_count);
dest.writeInt(statuses_count);
dest.writeInt(favourites_count);
dest.writeInt(verified_type);
dest.writeInt(online_status);
dest.writeInt(bi_followers_count);
dest.writeString(cover_image_phone);
dest.writeString(cover_image);
dest.writeBooleanArray(new boolean[]{following, allow_all_act_msg, geo_enabled, verified, allow_all_comment});
}
public static final Creator<UserModel> CREATOR = new Creator<UserModel>() {
@Override
public UserModel createFromParcel(Parcel input) {
UserModel ret = new UserModel();
ret.id = input.readString();
ret.screen_name = input.readString();
ret.name = input.readString();
ret.remark = input.readString();
ret.province = input.readString();
ret.city = input.readString();
ret.location = input.readString();
ret.description = input.readString();
ret.url = input.readString();
ret.profile_image_url = input.readString();
ret.domain = input.readString();
ret.gender = input.readString();
ret.created_at = input.readString();
ret.avatar_large = input.readString();
ret.verified_reason = input.readString();
ret.followers_count = input.readInt();
ret.friends_count = input.readInt();
ret.statuses_count = input.readInt();
ret.favourites_count = input.readInt();
ret.verified_type = input.readInt();
ret.online_status = input.readInt();
ret.bi_followers_count = input.readInt();
ret.cover_image_phone = input.readString();
ret.cover_image = input.readString();
boolean[] array = new boolean[5];
input.readBooleanArray(array);
ret.following = array[0];
ret.allow_all_act_msg = array[1];
ret.geo_enabled = array[2];
ret.verified = array[3];
ret.allow_all_comment = array[4];
return ret;
}
@Override
public UserModel[] newArray(int size) {
return new UserModel[size];
}
};
}
| 4,202 | 0.715612 | 0.71228 | 143 | 28.384615 | 18.398056 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.468531 | false | false | 5 |
1870ca575b8aa24a740fc9f4dcb789b6d2f4110d | 137,439,021,099 | 199edb073adc07cee2b4a52944e5f3ca23fcfe23 | /src/codelovers/togetherdemo/utils/Constants.java | 17eaa73094b642f369dc1a8dbcf51e7ae1495371 | []
| no_license | vubinhne/abc | https://github.com/vubinhne/abc | e69b8d16fa11863d68ddb460f5cb49ff9f20abdd | 38c1fd1e959c493b09447ee5b738665863a3bba5 | refs/heads/master | 2016-09-06T11:38:25.683000 | 2015-07-21T08:32:59 | 2015-07-21T08:32:59 | 39,420,007 | 0 | 1 | null | false | 2015-07-21T08:33:03 | 2015-07-21T02:39:48 | 2015-07-21T02:42:06 | 2015-07-21T08:33:00 | 0 | 0 | 1 | 0 | Java | null | null | package codelovers.togetherdemo.utils;
public class Constants {
public static final String OPENFIRE_SERVICE_REST_URL = "http://192.168.32.106:9090";
public static final String OPENFIRE_SERVER = "192.168.32.106";
public static final String SECRET_KEY = "rSuLjzgXk3r22u0X";
public static final int OPENFIRE_PORT = 5222;
}
| UTF-8 | Java | 334 | java | Constants.java | Java | [
{
"context": " final String OPENFIRE_SERVICE_REST_URL = \"http://192.168.32.106:9090\";\n\tpublic static final String OPENFIRE_SERVE",
"end": 145,
"score": 0.9997286796569824,
"start": 131,
"tag": "IP_ADDRESS",
"value": "192.168.32.106"
},
{
"context": "\";\n\tpublic static final String OPENFIRE_SERVER = \"192.168.32.106\";\n\t\n\tpublic static final String SECRET_KEY = \"rSu",
"end": 214,
"score": 0.9997376203536987,
"start": 200,
"tag": "IP_ADDRESS",
"value": "192.168.32.106"
},
{
"context": "106\";\n\t\n\tpublic static final String SECRET_KEY = \"rSuLjzgXk3r22u0X\"; \n\t\n\tpublic static final int OPENFIRE_PORT = 522",
"end": 277,
"score": 0.9980695843696594,
"start": 261,
"tag": "KEY",
"value": "rSuLjzgXk3r22u0X"
}
]
| null | []
| package codelovers.togetherdemo.utils;
public class Constants {
public static final String OPENFIRE_SERVICE_REST_URL = "http://192.168.32.106:9090";
public static final String OPENFIRE_SERVER = "192.168.32.106";
public static final String SECRET_KEY = "<KEY>";
public static final int OPENFIRE_PORT = 5222;
}
| 323 | 0.748503 | 0.646707 | 13 | 24.692308 | 29.25849 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.923077 | false | false | 5 |
a6e11da5708bf23115c1e34b6074b1992654e4d3 | 21,414,707,006,451 | 486b2f3b8a3f876e7f58fd2099c3a88c30427998 | /XeytanJServerAsync/src/main/java/com/melardev/xeytanj/gui/filesystem/FileSystemUiListener.java | ee544eed95fea2a8ebf6ec8d941ec9f61edd1ad4 | []
| no_license | githubassets/XeytanJ-Async-RAT | https://github.com/githubassets/XeytanJ-Async-RAT | 5e3740fe828bf963e5169f9472a2ee4e1f7d0de3 | 17b7b120a7d52a4a1d859a5ef8b62e42b79a12ff | refs/heads/master | 2022-02-19T19:07:47.062000 | 2019-09-11T15:30:51 | 2019-09-11T15:30:51 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.melardev.xeytanj.gui.filesystem;
import com.melardev.xeytanj.models.Client;
public interface FileSystemUiListener {
void onFileSystemPathRequested(Client client, String fileSystemPath);
}
| UTF-8 | Java | 207 | java | FileSystemUiListener.java | Java | []
| null | []
| package com.melardev.xeytanj.gui.filesystem;
import com.melardev.xeytanj.models.Client;
public interface FileSystemUiListener {
void onFileSystemPathRequested(Client client, String fileSystemPath);
}
| 207 | 0.821256 | 0.821256 | 8 | 24.875 | 26.459579 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 5 |
35bfd6dcfd046ba650e77f8f288dc688ae7de591 | 4,587,025,139,615 | eeee719c94f720072698f13a457c50837f580d8a | /bms-price-center-api/src/main/java/com/bms/prce/rest/PRCE0213IRestController.java | a6616d34dd6c60b9ed6c8cbb5674e1f3e2044693 | []
| no_license | moutainhigh/xcdv2 | https://github.com/moutainhigh/xcdv2 | c4f21ce874b2c415eb8bc20997e9f0bf31e9b14d | 23b6c33d45ff86d6bc8dcf014798f70c70b46f24 | refs/heads/master | 2021-06-28T05:06:58.529000 | 2017-08-15T11:28:33 | 2017-08-15T11:29:05 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bms.prce.rest;
import com.bms.prce.bean.param.PRCE0213IParam;
import com.bms.prce.bean.result.PRCE0213IResult;
import com.bms.prce.service.PrcePricePlateService;
import com.framework.boot.base.BaseRestController;
import com.framework.core.db.DbUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@Api(description = "价盘信息查询",
tags = "PRCE0213IRestController", value = "PRCE0213I", position = 0)
public class PRCE0213IRestController extends BaseRestController {
@Autowired
private PrcePricePlateService prcePricePlateService;
/**
* 价盘信息查询
* @Param prce0207IParam
* @return 修改结果
*
*/
@ApiOperation(value = "价盘信息查询", notes = "价盘信息查询")
@RequestMapping(value = "/prce/pricePlateInfoList/_search", method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_VALUE})
public List<PRCE0213IResult> searchPriceList(@RequestBody PRCE0213IParam param) {
param.setLgcsAreaName(DbUtils.buildLikeCondition(param.getLgcsAreaName()));
param.setClassesName(DbUtils.buildLikeCondition(param.getClassesName()));
param.setMachiningName(DbUtils.buildLikeCondition(param.getMachiningName()));
param.setBrandName(DbUtils.buildLikeCondition(param.getBrandName()));
param.setBreedSalesName(DbUtils.buildLikeCondition(param.getBreedSalesName()));
param.setPackageSpecification(DbUtils.buildLikeCondition(param.getPackageSpecification()));
param.setSaleStatusName(DbUtils.buildLikeCondition(param.getSaleStatusName()));
List<PRCE0213IResult> results = prcePricePlateService.findPrcePricePlateList(param);
return results;
}
}
| UTF-8 | Java | 2,138 | java | PRCE0213IRestController.java | Java | []
| null | []
| package com.bms.prce.rest;
import com.bms.prce.bean.param.PRCE0213IParam;
import com.bms.prce.bean.result.PRCE0213IResult;
import com.bms.prce.service.PrcePricePlateService;
import com.framework.boot.base.BaseRestController;
import com.framework.core.db.DbUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@Api(description = "价盘信息查询",
tags = "PRCE0213IRestController", value = "PRCE0213I", position = 0)
public class PRCE0213IRestController extends BaseRestController {
@Autowired
private PrcePricePlateService prcePricePlateService;
/**
* 价盘信息查询
* @Param prce0207IParam
* @return 修改结果
*
*/
@ApiOperation(value = "价盘信息查询", notes = "价盘信息查询")
@RequestMapping(value = "/prce/pricePlateInfoList/_search", method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_VALUE})
public List<PRCE0213IResult> searchPriceList(@RequestBody PRCE0213IParam param) {
param.setLgcsAreaName(DbUtils.buildLikeCondition(param.getLgcsAreaName()));
param.setClassesName(DbUtils.buildLikeCondition(param.getClassesName()));
param.setMachiningName(DbUtils.buildLikeCondition(param.getMachiningName()));
param.setBrandName(DbUtils.buildLikeCondition(param.getBrandName()));
param.setBreedSalesName(DbUtils.buildLikeCondition(param.getBreedSalesName()));
param.setPackageSpecification(DbUtils.buildLikeCondition(param.getPackageSpecification()));
param.setSaleStatusName(DbUtils.buildLikeCondition(param.getSaleStatusName()));
List<PRCE0213IResult> results = prcePricePlateService.findPrcePricePlateList(param);
return results;
}
}
| 2,138 | 0.778098 | 0.760327 | 46 | 44.260868 | 33.324123 | 139 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.673913 | false | false | 5 |
6f4ed24216df1f08cf9475fe33bfdbd71d6ace60 | 5,248,450,046,160 | 965c3daa3e4e252c40021c9d97972918ec2730f7 | /nombre_ok/src/com/sinensia/poo_avanzado/Mascota.java | 1dff1c88bd6f931b76cac7086f5cff7080f8f703 | []
| no_license | ebeltranro/curso_java_spring | https://github.com/ebeltranro/curso_java_spring | b73c71e1678c742f731025faa661f01e8f4db917 | ffc1b68b0cfc3a4b352d8fe040d495dc2c992cd3 | refs/heads/master | 2021-07-03T01:55:26.965000 | 2019-06-07T15:29:45 | 2019-06-07T15:29:45 | 185,391,313 | 0 | 0 | null | false | 2020-10-13T13:23:02 | 2019-05-07T11:52:18 | 2019-06-07T15:30:05 | 2020-10-13T13:23:00 | 2,326 | 0 | 0 | 1 | Java | false | false | package com.sinensia.poo_avanzado;
import com.sinensia.Cliente;
public abstract class Mascota extends Animal { //las mascotas tambien son clase abstracta; son un tipo de animal pero general
protected Cliente propietario; //las mascotas también se caracterizan por tener propietarios
public Mascota(int patas, boolean aerobico, boolean acuatico, String nombre, float tamanho) {
super(patas, aerobico, acuatico, nombre, tamanho);
}
public void pedirComida(){ //metodo concreto porque es lo mismo en todas las mascotas
System.out.println("ALIMENTAME !!");
}
public abstract void saludarPropietario(); //abstracta porque cada mascota saluda al propietario de una forma
public Cliente getPropietario() {
return propietario;
}
public void setPropietario(Cliente propietario) {
this.propietario = propietario;
}
}
| UTF-8 | Java | 928 | java | Mascota.java | Java | []
| null | []
| package com.sinensia.poo_avanzado;
import com.sinensia.Cliente;
public abstract class Mascota extends Animal { //las mascotas tambien son clase abstracta; son un tipo de animal pero general
protected Cliente propietario; //las mascotas también se caracterizan por tener propietarios
public Mascota(int patas, boolean aerobico, boolean acuatico, String nombre, float tamanho) {
super(patas, aerobico, acuatico, nombre, tamanho);
}
public void pedirComida(){ //metodo concreto porque es lo mismo en todas las mascotas
System.out.println("ALIMENTAME !!");
}
public abstract void saludarPropietario(); //abstracta porque cada mascota saluda al propietario de una forma
public Cliente getPropietario() {
return propietario;
}
public void setPropietario(Cliente propietario) {
this.propietario = propietario;
}
}
| 928 | 0.695793 | 0.695793 | 31 | 28.903225 | 37.221531 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.548387 | false | false | 5 |
6e05fe7a0bf034083376206a423a48f33f6f5334 | 17,239,998,793,958 | d8664a070d0b3b00879963b7a8153cc0f1fa5355 | /chapter_004/src/main/java/ru/job4j/stream/StreamUsage.java | dd631fc066f631c14633a3209605501e8d0fd257 | [
"Apache-2.0"
]
| permissive | johnivo/job4j | https://github.com/johnivo/job4j | 107696eac9b2c522d3c4e32216e64b5d9bd58f98 | ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe | refs/heads/master | 2022-11-26T20:11:10.630000 | 2021-02-03T21:03:42 | 2021-02-03T21:03:42 | 159,810,107 | 51 | 64 | Apache-2.0 | false | 2022-11-15T23:33:53 | 2018-11-30T10:52:05 | 2022-10-26T20:03:32 | 2022-11-15T23:33:51 | 2,381 | 32 | 32 | 10 | Java | false | false | package ru.job4j.stream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class StreamUsage {
private String bug;
public StreamUsage(String bug) {
this.bug = bug;
}
public static class Task {
private final String name;
private final long spent;
public Task(String name, long spent) {
this.name = name;
this.spent = spent;
}
@Override
public String toString() {
return "Task{"
+
"name='" + name + '\''
+
", spent=" + spent
+
'}';
}
}
public List<Task> usageFilter(ArrayList<Task> tasks, String bug) {
List<Task> bugs = tasks.stream().filter(
task -> task.name.contains(bug)
).collect(Collectors.toList());
bugs.forEach(System.out::println);
return bugs;
}
public List<String> namesTasks(ArrayList<Task> tasks) {
List<String> names = tasks.stream().map(
task -> task.name
).collect(Collectors.toList());
return names;
}
public long totalSum(ArrayList<Task> tasks) {
long total = tasks.stream().map(
task -> task.spent
).reduce(0L, Long::sum);
return total;
}
}
| UTF-8 | Java | 1,406 | java | StreamUsage.java | Java | []
| null | []
| package ru.job4j.stream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class StreamUsage {
private String bug;
public StreamUsage(String bug) {
this.bug = bug;
}
public static class Task {
private final String name;
private final long spent;
public Task(String name, long spent) {
this.name = name;
this.spent = spent;
}
@Override
public String toString() {
return "Task{"
+
"name='" + name + '\''
+
", spent=" + spent
+
'}';
}
}
public List<Task> usageFilter(ArrayList<Task> tasks, String bug) {
List<Task> bugs = tasks.stream().filter(
task -> task.name.contains(bug)
).collect(Collectors.toList());
bugs.forEach(System.out::println);
return bugs;
}
public List<String> namesTasks(ArrayList<Task> tasks) {
List<String> names = tasks.stream().map(
task -> task.name
).collect(Collectors.toList());
return names;
}
public long totalSum(ArrayList<Task> tasks) {
long total = tasks.stream().map(
task -> task.spent
).reduce(0L, Long::sum);
return total;
}
}
| 1,406 | 0.512802 | 0.51138 | 57 | 23.666666 | 17.397654 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.385965 | false | false | 5 |
c1d6a3632b6a609736eade7879123a08a6153657 | 10,359,461,183,917 | 19613033ecf65b0780b99f1039843f746e375eaa | /src/main/java/br/com/artemis/service/dto/package-info.java | 1b044eda454c3e24eb6907519057f279ff8d90f8 | []
| no_license | BulkSecurityGeneratorProject/artemis | https://github.com/BulkSecurityGeneratorProject/artemis | 162db3684d485b610ff05a899adbc0d16e448b1a | 86b24c59229b1d4b5f1dc42173f068bc384ee8a9 | refs/heads/master | 2022-12-17T01:43:36.408000 | 2018-10-08T17:01:57 | 2018-10-08T17:01:57 | 296,606,656 | 0 | 0 | null | true | 2020-09-18T11:51:57 | 2020-09-18T11:51:56 | 2018-10-08T17:01:59 | 2018-10-08T17:01:58 | 4,345 | 0 | 0 | 0 | null | false | false | /**
* Data Transfer Objects.
*/
package br.com.artemis.service.dto;
| UTF-8 | Java | 70 | java | package-info.java | Java | []
| null | []
| /**
* Data Transfer Objects.
*/
package br.com.artemis.service.dto;
| 70 | 0.685714 | 0.685714 | 4 | 16.5 | 13.955286 | 35 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 5 |
7a4b4b4bdff445b304d881bf0225babfc9681472 | 1,159,641,229,639 | 2863d802d9710edaec35b0973d7e5fc2ca82c780 | /java/com/google/copybara/StarlarkDateTimeModule.java | 171dfca834ef883ac180d2fba9dd38734ec44195 | [
"Apache-2.0"
]
| permissive | google/copybara | https://github.com/google/copybara | d72ea02d217146c789ce239640b8dbf72b448ee2 | 4662b526325a7676f4e4a0f89c23b0a27d37ac35 | refs/heads/master | 2023-08-17T05:34:26.009000 | 2023-08-16T12:50:35 | 2023-08-16T18:41:53 | 67,722,017 | 1,866 | 306 | Apache-2.0 | false | 2023-09-14T14:23:07 | 2016-09-08T16:44:40 | 2023-09-13T20:33:40 | 2023-09-14T14:23:02 | 13,972 | 1,829 | 255 | 66 | Java | false | false | package com.google.copybara;
/*
* Copyright (C) 2022 Google Inc.
*
* 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.
*/
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.copybara.exception.ValidationException;
import java.time.DateTimeException;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.zone.ZoneRulesException;
import java.util.Objects;
import net.starlark.java.annot.Param;
import net.starlark.java.annot.ParamType;
import net.starlark.java.annot.StarlarkBuiltin;
import net.starlark.java.annot.StarlarkMethod;
import net.starlark.java.eval.EvalException;
import net.starlark.java.eval.HasBinary;
import net.starlark.java.eval.StarlarkInt;
import net.starlark.java.eval.StarlarkValue;
import net.starlark.java.syntax.TokenKind;
/** Starlark wrapper for java's Zoned Datetime */
@StarlarkBuiltin(name = "datetime", doc = "Module for datetime manipulation.", documented = false)
public class StarlarkDateTimeModule implements StarlarkValue {
@StarlarkMethod(
name = "now",
doc = "Returns a starlark_datetime object. The object is timezone aware.",
parameters = {
@Param(
name = "tz",
defaultValue = "'America/Los_Angeles'",
doc = "The timezone. E.g. America/New_York, Asia/Tokyo, Europe/Rome",
allowedTypes = {@ParamType(type = String.class)},
named = true)
})
public StarlarkDateTime createFromNow(String zoneIdString) throws ValidationException {
return new StarlarkDateTime(zoneIdString);
}
@StarlarkMethod(
name = "fromtimestamp",
doc =
"Returns a starlark_datetime object representation of the epoch time. The object is"
+ " timezone aware.",
parameters = {
@Param(
name = "timestamp",
defaultValue = "0",
doc = "Epoch time in seconds.",
allowedTypes = {@ParamType(type = StarlarkInt.class)},
named = true),
@Param(
name = "tz",
defaultValue = "'America/Los_Angeles'",
doc = "The timezone. E.g. America/New_York, Asia/Tokyo, Europe/Rome, etc.",
allowedTypes = {@ParamType(type = String.class)},
named = true)
})
public StarlarkDateTime createFromEpochSeconds(StarlarkInt timeInEpochSeconds, String zoneId)
throws ValidationException, EvalException {
return new StarlarkDateTime(timeInEpochSeconds.toLong(null), zoneId);
}
/** The StarLark facing wrapper for ZonedDateTime */
@SuppressWarnings("ZonedDateTimeNowWithZone")
public static class StarlarkDateTime implements StarlarkValue, HasBinary {
private final ZonedDateTime zonedDateTime;
public StarlarkDateTime(String zoneIdString) throws ValidationException {
ZoneId zoneId = convertStringToZoneId(zoneIdString);
this.zonedDateTime = ZonedDateTime.now(zoneId);
}
@SuppressWarnings("GoodTime")
public StarlarkDateTime(long timeInEpochSeconds, String zoneIdString)
throws ValidationException {
ZoneId zoneId = convertStringToZoneId(zoneIdString);
this.zonedDateTime = Instant.ofEpochSecond(timeInEpochSeconds).atZone(zoneId);
}
@Override
public final Object binaryOp(TokenKind operator, Object rightSideOperand, boolean thisLeft)
throws EvalException {
Preconditions.checkArgument(
rightSideOperand instanceof StarlarkDateTime,
"Binary operators are supported between StarkDateTime objects only.");
StarlarkDateTime otherDateTime = (StarlarkDateTime) rightSideOperand;
switch (operator) {
case MINUS:
return new StarlarkTimeDelta(
ChronoUnit.SECONDS.between(otherDateTime.zonedDateTime, zonedDateTime));
// TODO(linjordan) - PLUS between StarklarkDatetime and StarlarkTimeDelta in the future
default:
throw new EvalException(String.format("Glob does not support %s operator", operator));
}
}
private ZoneId convertStringToZoneId(String zoneIdString) throws ValidationException {
try {
return (Strings.isNullOrEmpty(zoneIdString)
? ZoneId.systemDefault()
: ZoneId.of(zoneIdString));
} catch (ZoneRulesException e) {
throw new ValidationException(
String.format(
"An error was thrown creating StarlarkDateTime from zone id. Make sure your"
+ " timezone is available in %s",
ZoneId.getAvailableZoneIds()),
e);
}
}
@SuppressWarnings("GoodTime")
@StarlarkMethod(
name = "in_epoch_seconds",
doc = "Returns the time in epoch seconds for the starlark_datetime instance")
public long getTimeInEpochSeconds() {
return this.zonedDateTime.toEpochSecond();
}
@SuppressWarnings("GoodTime")
@StarlarkMethod(
name = "strftime",
doc =
"Returns a string representation of the StarlarkDateTime object with your chosen"
+ " formatting",
parameters = {
@Param(
name = "format",
doc =
"Format string used to present StarlarkDateTime object. See"
+ " https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html"
+ " for patterns.",
allowedTypes = {@ParamType(type = String.class)},
named = true),
})
public String formatToString(String format) throws ValidationException {
try {
return zonedDateTime.format(DateTimeFormatter.ofPattern(format));
} catch (DateTimeException | IllegalArgumentException e) {
throw new ValidationException(
String.format(
"The StarlarkDateTime object '%s' could not be formatted using format string '%s':",
this, format),
e);
}
}
@Override
public String toString() {
return this.zonedDateTime.toString();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof StarlarkDateTime)) {
return false;
}
return obj == this || this.zonedDateTime.equals(((StarlarkDateTime) obj).zonedDateTime);
}
@Override
public int hashCode() {
return Objects.hashCode(this.zonedDateTime);
}
}
/** Time delta, used to do binary operations with Starlark Datetime */
public static class StarlarkTimeDelta implements StarlarkValue {
private final Duration duration;
/** Breaks StarlarkTimeDelta into days, hours, minutes, and seconds */
@SuppressWarnings("GoodTime")
public StarlarkTimeDelta(long seconds) {
duration = Duration.ofSeconds(seconds);
}
@SuppressWarnings("GoodTime")
@StarlarkMethod(name = "total_seconds", doc = "Total number of seconds in a timedelta object.")
public long totalSeconds() {
return duration.getSeconds();
}
// TODO(linjordan) - implement timedelta + StarlarkDatetime
}
}
| UTF-8 | Java | 7,711 | java | StarlarkDateTimeModule.java | Java | [
{
"context": "zonedDateTime, zonedDateTime));\n // TODO(linjordan) - PLUS between StarklarkDatetime and StarlarkTim",
"end": 4470,
"score": 0.9992689490318298,
"start": 4461,
"tag": "USERNAME",
"value": "linjordan"
},
{
"context": " return duration.getSeconds();\n }\n\n // TODO(linjordan) - implement timedelta + StarlarkDatetime\n }\n}\n",
"end": 7662,
"score": 0.8891492486000061,
"start": 7653,
"tag": "USERNAME",
"value": "linjordan"
}
]
| null | []
| package com.google.copybara;
/*
* Copyright (C) 2022 Google Inc.
*
* 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.
*/
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.copybara.exception.ValidationException;
import java.time.DateTimeException;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.zone.ZoneRulesException;
import java.util.Objects;
import net.starlark.java.annot.Param;
import net.starlark.java.annot.ParamType;
import net.starlark.java.annot.StarlarkBuiltin;
import net.starlark.java.annot.StarlarkMethod;
import net.starlark.java.eval.EvalException;
import net.starlark.java.eval.HasBinary;
import net.starlark.java.eval.StarlarkInt;
import net.starlark.java.eval.StarlarkValue;
import net.starlark.java.syntax.TokenKind;
/** Starlark wrapper for java's Zoned Datetime */
@StarlarkBuiltin(name = "datetime", doc = "Module for datetime manipulation.", documented = false)
public class StarlarkDateTimeModule implements StarlarkValue {
@StarlarkMethod(
name = "now",
doc = "Returns a starlark_datetime object. The object is timezone aware.",
parameters = {
@Param(
name = "tz",
defaultValue = "'America/Los_Angeles'",
doc = "The timezone. E.g. America/New_York, Asia/Tokyo, Europe/Rome",
allowedTypes = {@ParamType(type = String.class)},
named = true)
})
public StarlarkDateTime createFromNow(String zoneIdString) throws ValidationException {
return new StarlarkDateTime(zoneIdString);
}
@StarlarkMethod(
name = "fromtimestamp",
doc =
"Returns a starlark_datetime object representation of the epoch time. The object is"
+ " timezone aware.",
parameters = {
@Param(
name = "timestamp",
defaultValue = "0",
doc = "Epoch time in seconds.",
allowedTypes = {@ParamType(type = StarlarkInt.class)},
named = true),
@Param(
name = "tz",
defaultValue = "'America/Los_Angeles'",
doc = "The timezone. E.g. America/New_York, Asia/Tokyo, Europe/Rome, etc.",
allowedTypes = {@ParamType(type = String.class)},
named = true)
})
public StarlarkDateTime createFromEpochSeconds(StarlarkInt timeInEpochSeconds, String zoneId)
throws ValidationException, EvalException {
return new StarlarkDateTime(timeInEpochSeconds.toLong(null), zoneId);
}
/** The StarLark facing wrapper for ZonedDateTime */
@SuppressWarnings("ZonedDateTimeNowWithZone")
public static class StarlarkDateTime implements StarlarkValue, HasBinary {
private final ZonedDateTime zonedDateTime;
public StarlarkDateTime(String zoneIdString) throws ValidationException {
ZoneId zoneId = convertStringToZoneId(zoneIdString);
this.zonedDateTime = ZonedDateTime.now(zoneId);
}
@SuppressWarnings("GoodTime")
public StarlarkDateTime(long timeInEpochSeconds, String zoneIdString)
throws ValidationException {
ZoneId zoneId = convertStringToZoneId(zoneIdString);
this.zonedDateTime = Instant.ofEpochSecond(timeInEpochSeconds).atZone(zoneId);
}
@Override
public final Object binaryOp(TokenKind operator, Object rightSideOperand, boolean thisLeft)
throws EvalException {
Preconditions.checkArgument(
rightSideOperand instanceof StarlarkDateTime,
"Binary operators are supported between StarkDateTime objects only.");
StarlarkDateTime otherDateTime = (StarlarkDateTime) rightSideOperand;
switch (operator) {
case MINUS:
return new StarlarkTimeDelta(
ChronoUnit.SECONDS.between(otherDateTime.zonedDateTime, zonedDateTime));
// TODO(linjordan) - PLUS between StarklarkDatetime and StarlarkTimeDelta in the future
default:
throw new EvalException(String.format("Glob does not support %s operator", operator));
}
}
private ZoneId convertStringToZoneId(String zoneIdString) throws ValidationException {
try {
return (Strings.isNullOrEmpty(zoneIdString)
? ZoneId.systemDefault()
: ZoneId.of(zoneIdString));
} catch (ZoneRulesException e) {
throw new ValidationException(
String.format(
"An error was thrown creating StarlarkDateTime from zone id. Make sure your"
+ " timezone is available in %s",
ZoneId.getAvailableZoneIds()),
e);
}
}
@SuppressWarnings("GoodTime")
@StarlarkMethod(
name = "in_epoch_seconds",
doc = "Returns the time in epoch seconds for the starlark_datetime instance")
public long getTimeInEpochSeconds() {
return this.zonedDateTime.toEpochSecond();
}
@SuppressWarnings("GoodTime")
@StarlarkMethod(
name = "strftime",
doc =
"Returns a string representation of the StarlarkDateTime object with your chosen"
+ " formatting",
parameters = {
@Param(
name = "format",
doc =
"Format string used to present StarlarkDateTime object. See"
+ " https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html"
+ " for patterns.",
allowedTypes = {@ParamType(type = String.class)},
named = true),
})
public String formatToString(String format) throws ValidationException {
try {
return zonedDateTime.format(DateTimeFormatter.ofPattern(format));
} catch (DateTimeException | IllegalArgumentException e) {
throw new ValidationException(
String.format(
"The StarlarkDateTime object '%s' could not be formatted using format string '%s':",
this, format),
e);
}
}
@Override
public String toString() {
return this.zonedDateTime.toString();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof StarlarkDateTime)) {
return false;
}
return obj == this || this.zonedDateTime.equals(((StarlarkDateTime) obj).zonedDateTime);
}
@Override
public int hashCode() {
return Objects.hashCode(this.zonedDateTime);
}
}
/** Time delta, used to do binary operations with Starlark Datetime */
public static class StarlarkTimeDelta implements StarlarkValue {
private final Duration duration;
/** Breaks StarlarkTimeDelta into days, hours, minutes, and seconds */
@SuppressWarnings("GoodTime")
public StarlarkTimeDelta(long seconds) {
duration = Duration.ofSeconds(seconds);
}
@SuppressWarnings("GoodTime")
@StarlarkMethod(name = "total_seconds", doc = "Total number of seconds in a timedelta object.")
public long totalSeconds() {
return duration.getSeconds();
}
// TODO(linjordan) - implement timedelta + StarlarkDatetime
}
}
| 7,711 | 0.672286 | 0.67099 | 207 | 36.251209 | 28.247606 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.502415 | false | false | 5 |
b6eaf44e21e0fc5ef1d047910ee4b98df59fead7 | 27,590,869,913,720 | b162ed6a18b5b6daeceb716a9166f27f5a4dade7 | /src/main/java/com/space/rabbitmq/sender/FirstSender.java | a99b78beb6b9d89c95af92ef9b81dafc505d0356 | []
| no_license | honcyLi/rabbitmq | https://github.com/honcyLi/rabbitmq | 978ef98eb88412a16628f638e4ec88367567db28 | 1507d0eefcd648f2a9ce73bdc43a3e344b9987fd | refs/heads/master | 2020-06-15T14:10:49.701000 | 2019-07-05T01:35:57 | 2019-07-05T01:35:57 | 195,319,820 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.space.rabbitmq.sender;
import com.space.rabbitmq.config.RabbitMqConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.UUID;
/**
* 消息发送 生产者1
* @author zhuzhe
* @date 2018/5/25 14:28
* @email 1529949535@qq.com
*/
@Slf4j
@Component
public class FirstSender {
@Autowired
private RabbitTemplate rabbitTemplate;
/**
* 发送消息
* @param uuid
* @param message 消息
*/
public void send(String uuid,Object message) {
CorrelationData correlationId = new CorrelationData(uuid);
/**
* RabbitMqConfig.EXCHANGE 指定消息交换机
* RabbitMqConfig.ROUTINGKEY2 指定队列key2
*/
rabbitTemplate.convertAndSend(RabbitMqConfig.EXCHANGE,RabbitMqConfig.QUEUE_NAME1,
message,correlationId);
}
@Autowired
private AmqpTemplate amqpTemplate;
public void sendamqp(String msg) {
// 向消息队列中发送消息
this.rabbitTemplate.convertAndSend(RabbitMqConfig.QUEUE_NAME1, msg);
}
}
| UTF-8 | Java | 1,341 | java | FirstSender.java | Java | [
{
"context": "port java.util.UUID;\n\n/**\n * 消息发送 生产者1\n * @author zhuzhe\n * @date 2018/5/25 14:28\n * @email 1529949535@qq.",
"end": 466,
"score": 0.9996272325515747,
"start": 460,
"tag": "USERNAME",
"value": "zhuzhe"
},
{
"context": "@author zhuzhe\n * @date 2018/5/25 14:28\n * @email 1529949535@qq.com\n */\n@Slf4j\n@Component\npublic class FirstSender {\n",
"end": 519,
"score": 0.9997251629829407,
"start": 502,
"tag": "EMAIL",
"value": "1529949535@qq.com"
}
]
| null | []
| package com.space.rabbitmq.sender;
import com.space.rabbitmq.config.RabbitMqConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.UUID;
/**
* 消息发送 生产者1
* @author zhuzhe
* @date 2018/5/25 14:28
* @email <EMAIL>
*/
@Slf4j
@Component
public class FirstSender {
@Autowired
private RabbitTemplate rabbitTemplate;
/**
* 发送消息
* @param uuid
* @param message 消息
*/
public void send(String uuid,Object message) {
CorrelationData correlationId = new CorrelationData(uuid);
/**
* RabbitMqConfig.EXCHANGE 指定消息交换机
* RabbitMqConfig.ROUTINGKEY2 指定队列key2
*/
rabbitTemplate.convertAndSend(RabbitMqConfig.EXCHANGE,RabbitMqConfig.QUEUE_NAME1,
message,correlationId);
}
@Autowired
private AmqpTemplate amqpTemplate;
public void sendamqp(String msg) {
// 向消息队列中发送消息
this.rabbitTemplate.convertAndSend(RabbitMqConfig.QUEUE_NAME1, msg);
}
}
| 1,331 | 0.713276 | 0.690495 | 47 | 26.085106 | 22.980871 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.404255 | false | false | 5 |
fcd76688a80067095f873f0e2e0073401f5dd1f8 | 22,179,211,130,998 | a609ad305dad8d072c38f689c29391478c3ef2a9 | /src/main/java/edu/jsu/mcis/TicTacToe.java | 7940d29231f987f6032d2b22472e19f07081de1b | []
| no_license | B-Weaver/TicTacToe | https://github.com/B-Weaver/TicTacToe | 2d87f1ec19c5b067a2639e4726d58052700db037 | 3b9f10d41d14fc2ffaf74306fefee4cd4b64ccac | refs/heads/master | 2021-01-13T00:56:19.953000 | 2016-02-01T03:32:14 | 2016-02-01T03:32:14 | 49,662,911 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.jsu.mcis;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TicTacToe extends JPanel implements ActionListener{
protected TicTacToeModel game;
private JButton[][] gridButtons;
private JLabel messageLabel;
private JPanel board;
private int turn;
private int row;
private int col;
private String[] player;
private boolean noWin = true;
public TicTacToe(){
game = new TicTacToeModel();
board = new JPanel();
messageLabel = new JLabel("X make your move");
gridButtons = new JButton[3][3];
board.setLayout(new GridLayout(3, 3));
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
gridButtons[i][j] = new JButton(" ");
gridButtons[i][j].setName("Location"+i+j);
gridButtons[i][j].setFont(new Font("",Font.BOLD, 30));
gridButtons[i][j].setPreferredSize(new Dimension(75, 75));
gridButtons[i][j].addActionListener(this);
gridButtons[i][j].setActionCommand(i + "" + j);
board.add(gridButtons[i][j]);
}
}
board.setSize(600, 600);
add(board);
messageLabel.setPreferredSize(new Dimension(300, 100));
messageLabel.setFont(new Font("",Font.BOLD, 22));
messageLabel.setVerticalAlignment(SwingConstants.CENTER);
messageLabel.setHorizontalAlignment(SwingConstants.CENTER);
add(messageLabel);
player = new String[2];
player[0] = "Player X";
player[1] = "Player O";
}
private void checkForWin(){
String r = game.resultString();
if(r.length() > 0){
noWin = false;
new Thread(new Runnable(){
public void run(){
JOptionPane.showMessageDialog(null, "The winner is " + r, "Game Over", JOptionPane.INFORMATION_MESSAGE);
}}).start();
}
}
public void actionPerformed(ActionEvent e){
JButton b = (JButton)e.getSource();
int r = Integer.parseInt(b.getActionCommand().substring(0, 1));
int c = Integer.parseInt(b.getActionCommand().substring(1, 2));
game.setMark(r, c);
b.setText(game.getMark(r, c));
if(game.xTurn){
messageLabel.setText("Player X make your move");
checkForWin();
if(!noWin){
toggleButtons();
messageLabel.setText("Game Over!");
}
}
else{
messageLabel.setText("Player O make your move");
checkForWin();
if(!noWin){
toggleButtons();
messageLabel.setText("Game Over!");
}
}
}
public void toggleButtons(){
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
gridButtons[i][j].setEnabled(false);
}
}
}
public static void main(String[] args) {
JFrame win = new JFrame();
win.setTitle("Tic Tac Toe");
win.setSize(400, 400);
win.add(new TicTacToe());
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
win.setVisible(true);
}
}
| UTF-8 | Java | 2,827 | java | TicTacToe.java | Java | []
| null | []
| package edu.jsu.mcis;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TicTacToe extends JPanel implements ActionListener{
protected TicTacToeModel game;
private JButton[][] gridButtons;
private JLabel messageLabel;
private JPanel board;
private int turn;
private int row;
private int col;
private String[] player;
private boolean noWin = true;
public TicTacToe(){
game = new TicTacToeModel();
board = new JPanel();
messageLabel = new JLabel("X make your move");
gridButtons = new JButton[3][3];
board.setLayout(new GridLayout(3, 3));
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
gridButtons[i][j] = new JButton(" ");
gridButtons[i][j].setName("Location"+i+j);
gridButtons[i][j].setFont(new Font("",Font.BOLD, 30));
gridButtons[i][j].setPreferredSize(new Dimension(75, 75));
gridButtons[i][j].addActionListener(this);
gridButtons[i][j].setActionCommand(i + "" + j);
board.add(gridButtons[i][j]);
}
}
board.setSize(600, 600);
add(board);
messageLabel.setPreferredSize(new Dimension(300, 100));
messageLabel.setFont(new Font("",Font.BOLD, 22));
messageLabel.setVerticalAlignment(SwingConstants.CENTER);
messageLabel.setHorizontalAlignment(SwingConstants.CENTER);
add(messageLabel);
player = new String[2];
player[0] = "Player X";
player[1] = "Player O";
}
private void checkForWin(){
String r = game.resultString();
if(r.length() > 0){
noWin = false;
new Thread(new Runnable(){
public void run(){
JOptionPane.showMessageDialog(null, "The winner is " + r, "Game Over", JOptionPane.INFORMATION_MESSAGE);
}}).start();
}
}
public void actionPerformed(ActionEvent e){
JButton b = (JButton)e.getSource();
int r = Integer.parseInt(b.getActionCommand().substring(0, 1));
int c = Integer.parseInt(b.getActionCommand().substring(1, 2));
game.setMark(r, c);
b.setText(game.getMark(r, c));
if(game.xTurn){
messageLabel.setText("Player X make your move");
checkForWin();
if(!noWin){
toggleButtons();
messageLabel.setText("Game Over!");
}
}
else{
messageLabel.setText("Player O make your move");
checkForWin();
if(!noWin){
toggleButtons();
messageLabel.setText("Game Over!");
}
}
}
public void toggleButtons(){
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
gridButtons[i][j].setEnabled(false);
}
}
}
public static void main(String[] args) {
JFrame win = new JFrame();
win.setTitle("Tic Tac Toe");
win.setSize(400, 400);
win.add(new TicTacToe());
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
win.setVisible(true);
}
}
| 2,827 | 0.629996 | 0.613725 | 116 | 23.362068 | 20.112356 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.482759 | false | false | 5 |
4f8ff21e6e7c2cc51b308b32134b4348ef63a42f | 32,650,341,399,991 | 128a50f2d3218c91d57618c955fea248b138acf3 | /mavenwebproject-master/src/main/java/eticket/BookAction1.java | 95a7abbe6c3f30c5017d6bde1376b6fae8bb384d | []
| no_license | jitendra-singh01/automate-aws-deploy-jenkins-pipeline | https://github.com/jitendra-singh01/automate-aws-deploy-jenkins-pipeline | ca89192fc1fcb0a5e3ba5eaa8daff1204f5a2677 | 25dac53e3795537982c7d703b22b221ba3cf4d94 | refs/heads/master | 2023-05-13T12:03:28.633000 | 2019-07-10T16:31:11 | 2019-07-10T16:31:11 | 195,995,479 | 0 | 1 | null | false | 2023-05-09T18:11:01 | 2019-07-09T11:30:18 | 2019-07-10T16:31:14 | 2023-05-09T18:10:57 | 2,382 | 0 | 1 | 2 | Java | false | false | //Created by MyEclipse Struts
// XSL source (default): platform:/plugin/com.genuitec.eclipse.cross.easystruts.eclipse_3.8.4/xslt/JavaClass.xsl
package eticket;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
/**
* MyEclipse Struts
* Creation date: 04-09-2007
*
* XDoclet definition:
* @struts:action path="/bookAg1" name="bform" scope="request" validate="true"
* @struts:action-forward name="suc" path="bookticketconf.jsp"
* @struts:action-forward name="fail" path="bookticketfail.jsp"
*/
public class BookAction1 extends Action {
// --------------------------------------------------------- Instance Variables
// --------------------------------------------------------- Methods
/**
* Method execute
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
*/
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)throws Exception {
BookForm bform = (BookForm) form;
/** /BookForm bform=new BookForm();
System.out.println(bform.getBdday());
System.out.println(bform.getBdmonth());
System.out.println(bform.getBdyear());
System.out.println("in Action1111111111111111111111111111111111111");
System.out.println("yera"+bform.getBdday());
System.out.println("yera"+bform.getUsername1());
System.out.println("yera"+bform.getBdyear());
System.out.println("tid="+bform.getTickid());
System.out.println(request.getParameter("bdyear"));**/
bform.setBusno(request.getParameter("busno"));
bform.setTickid(new Integer(request.getParameter("tickid")).intValue());
bform.setUsername1(request.getParameter("username1"));
bform.setBdday(request.getParameter("bdday"));
bform.setBdmonth(request.getParameter("bdmonth"));
bform.setBdyear(request.getParameter("bdyear"));
bform.setNot(request.getParameter("not"));
boolean flag=Validation.bookTemp1(bform,getDataSource(request));
System.out.println("tid="+bform.getTickid());
System.out.println("flag"+flag);
if(flag)
return mapping.findForward("suc");
return mapping.findForward("fail");
}
} | UTF-8 | Java | 2,341 | java | BookAction1.java | Java | [
{
"context": "lue());\n\tbform.setUsername1(request.getParameter(\"username1\"));\n\tbform.setBdday(request.getParameter(\"bdday\")",
"end": 1892,
"score": 0.9994235634803772,
"start": 1883,
"tag": "USERNAME",
"value": "username1"
}
]
| null | []
| //Created by MyEclipse Struts
// XSL source (default): platform:/plugin/com.genuitec.eclipse.cross.easystruts.eclipse_3.8.4/xslt/JavaClass.xsl
package eticket;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
/**
* MyEclipse Struts
* Creation date: 04-09-2007
*
* XDoclet definition:
* @struts:action path="/bookAg1" name="bform" scope="request" validate="true"
* @struts:action-forward name="suc" path="bookticketconf.jsp"
* @struts:action-forward name="fail" path="bookticketfail.jsp"
*/
public class BookAction1 extends Action {
// --------------------------------------------------------- Instance Variables
// --------------------------------------------------------- Methods
/**
* Method execute
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
*/
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)throws Exception {
BookForm bform = (BookForm) form;
/** /BookForm bform=new BookForm();
System.out.println(bform.getBdday());
System.out.println(bform.getBdmonth());
System.out.println(bform.getBdyear());
System.out.println("in Action1111111111111111111111111111111111111");
System.out.println("yera"+bform.getBdday());
System.out.println("yera"+bform.getUsername1());
System.out.println("yera"+bform.getBdyear());
System.out.println("tid="+bform.getTickid());
System.out.println(request.getParameter("bdyear"));**/
bform.setBusno(request.getParameter("busno"));
bform.setTickid(new Integer(request.getParameter("tickid")).intValue());
bform.setUsername1(request.getParameter("username1"));
bform.setBdday(request.getParameter("bdday"));
bform.setBdmonth(request.getParameter("bdmonth"));
bform.setBdyear(request.getParameter("bdyear"));
bform.setNot(request.getParameter("not"));
boolean flag=Validation.bookTemp1(bform,getDataSource(request));
System.out.println("tid="+bform.getTickid());
System.out.println("flag"+flag);
if(flag)
return mapping.findForward("suc");
return mapping.findForward("fail");
}
} | 2,341 | 0.711235 | 0.688167 | 73 | 31.082191 | 24.610807 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.260274 | false | false | 5 |
c50d2daa8d7d81c67cd28e59de1459263dfdb522 | 12,206,297,114,488 | fe8b8b7e162903ea72aed88710e1da899b57d836 | /src/com/codebag/code/mycode/utils/Log.java | d65a107a9c7429cf772116db774ee3da97c5d54a | []
| no_license | redesh/CodeBag | https://github.com/redesh/CodeBag | c46a31a475ce9a242a03f0bacac2cf36d05496d0 | 6b7db01927ea44de7e2c142a72b58ee652f7f035 | refs/heads/master | 2021-01-22T07:18:35.490000 | 2014-10-17T11:00:34 | 2014-10-17T11:00:34 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.codebag.code.mycode.utils;
public class Log {
private static StringBuffer mLog = new StringBuffer();
private static long startTime = 0;
public static void addLog(Object invoker, String msg) {
mLog.append(invoker.getClass().getSimpleName() + ":" + msg + "\n");
android.util.Log.i("log="+ invoker.getClass().getSimpleName(), msg);
}
public static String getLog() {
return mLog.toString();
}
public static void showSystemLog(Object invoker, String msg) {
android.util.Log.i("log="+ invoker.getClass().getSimpleName(), msg);
}
public static void clearLog() {
mLog.setLength(0);
}
public static void startCountTime(Object invoker, String msg) {
startTime = System.currentTimeMillis();
Log.addLog(invoker, msg + " startTime=" + startTime + ">>>>>>>>>>>>>>>>>>>>>>>");
}
public static long endCountTime(Object invoker, String msg) {
long endTime = System.currentTimeMillis();
long detaTime = endTime - startTime;
Log.addLog(invoker, msg + " cost =" + detaTime + ">>>>>>>>>>>>>>>>>>>>>>>");
return detaTime;
}
}
| UTF-8 | Java | 1,069 | java | Log.java | Java | []
| null | []
| package com.codebag.code.mycode.utils;
public class Log {
private static StringBuffer mLog = new StringBuffer();
private static long startTime = 0;
public static void addLog(Object invoker, String msg) {
mLog.append(invoker.getClass().getSimpleName() + ":" + msg + "\n");
android.util.Log.i("log="+ invoker.getClass().getSimpleName(), msg);
}
public static String getLog() {
return mLog.toString();
}
public static void showSystemLog(Object invoker, String msg) {
android.util.Log.i("log="+ invoker.getClass().getSimpleName(), msg);
}
public static void clearLog() {
mLog.setLength(0);
}
public static void startCountTime(Object invoker, String msg) {
startTime = System.currentTimeMillis();
Log.addLog(invoker, msg + " startTime=" + startTime + ">>>>>>>>>>>>>>>>>>>>>>>");
}
public static long endCountTime(Object invoker, String msg) {
long endTime = System.currentTimeMillis();
long detaTime = endTime - startTime;
Log.addLog(invoker, msg + " cost =" + detaTime + ">>>>>>>>>>>>>>>>>>>>>>>");
return detaTime;
}
}
| 1,069 | 0.664172 | 0.662301 | 37 | 27.891891 | 27.657934 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.783784 | false | false | 5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.