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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
04407729fae432b09673599f376806ac10c0322a
| 6,090,263,660,302 |
2c2a102dc5d72b600ebef167f4974a894329596a
|
/app/src/main/java/de/lukaspanni/opensourcestats/ui/details/RepositoryDetailsViewModel.java
|
546051a9cab7ff6b7219fa1cd0de02578feb07a7
|
[
"MIT"
] |
permissive
|
lukaspanni/OpenSourceStats
|
https://github.com/lukaspanni/OpenSourceStats
|
a6567f609cd7b938b79f7f77dbf4396a5b8e3048
|
5756d6a79cc81ee8e8538a9827977fa7ff78df38
|
refs/heads/main
| 2023-08-14T09:40:18.503000 | 2021-09-30T09:57:59 | 2021-09-30T09:57:59 | 299,055,769 | 0 | 0 |
MIT
| false | 2021-05-21T13:34:38 | 2020-09-27T14:59:49 | 2021-04-20T09:53:54 | 2021-05-21T13:34:37 | 9,274 | 0 | 0 | 7 |
Java
| false | false |
package de.lukaspanni.opensourcestats.ui.details;
import android.app.Application;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;
import java.util.Date;
import java.util.Set;
import de.lukaspanni.opensourcestats.OpenSourceStatsApplication;
import de.lukaspanni.opensourcestats.data.RepositoryDataResponse;
import de.lukaspanni.opensourcestats.repository.RepositoryDataRepository;
import de.lukaspanni.opensourcestats.data.RepositoryName;
public class RepositoryDetailsViewModel extends AndroidViewModel {
private MutableLiveData<Date> repositoryCreatedAt;
private MutableLiveData<String> repositoryName;
private MutableLiveData<String> repositoryDescription;
private MutableLiveData<String> repositoryPrimaryLanguage;
private MutableLiveData<Set<String>> repositoryLanguages;
private MutableLiveData<Boolean> repositoryIsPrivate;
public RepositoryDetailsViewModel(Application app) {
super(app);
repositoryCreatedAt = new MutableLiveData<>();
repositoryName = new MutableLiveData<>();
repositoryDescription = new MutableLiveData<>();
repositoryPrimaryLanguage = new MutableLiveData<>();
repositoryLanguages = new MutableLiveData<>();
repositoryIsPrivate = new MutableLiveData<>();
}
public MutableLiveData<Date> getRepositoryCreatedAt() {
return repositoryCreatedAt;
}
public MutableLiveData<String> getRepositoryName() {
return repositoryName;
}
public MutableLiveData<String> getRepositoryDescription() {
return repositoryDescription;
}
public MutableLiveData<String> getRepositoryPrimaryLanguage() {
return repositoryPrimaryLanguage;
}
public MutableLiveData<Set<String>> getRepositoryLanguages() {
return repositoryLanguages;
}
public MutableLiveData<Boolean> getRepositoryIsPrivate() {
return repositoryIsPrivate;
}
public void loadData(String repositoryWithOwner, boolean forceReload) {
this.repositoryName.postValue(repositoryWithOwner);
OpenSourceStatsApplication app = (OpenSourceStatsApplication) getApplication();
RepositoryDataRepository repository = app.getRepositoryDataRepository();
repository.loadRepositoryData(new RepositoryName(repositoryWithOwner), response -> {
RepositoryDataResponse repositoryData = (RepositoryDataResponse) response;
this.repositoryCreatedAt.postValue(repositoryData.getCreatedAt());
this.repositoryDescription.postValue(repositoryData.getDescription());
this.repositoryPrimaryLanguage.postValue(repositoryData.getPrimaryLanguage());
this.repositoryLanguages.postValue(repositoryData.getLanguages());
this.repositoryIsPrivate.postValue(repositoryData.isPrivate());
}, forceReload);
}
}
|
UTF-8
|
Java
| 2,890 |
java
|
RepositoryDetailsViewModel.java
|
Java
|
[] | null |
[] |
package de.lukaspanni.opensourcestats.ui.details;
import android.app.Application;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;
import java.util.Date;
import java.util.Set;
import de.lukaspanni.opensourcestats.OpenSourceStatsApplication;
import de.lukaspanni.opensourcestats.data.RepositoryDataResponse;
import de.lukaspanni.opensourcestats.repository.RepositoryDataRepository;
import de.lukaspanni.opensourcestats.data.RepositoryName;
public class RepositoryDetailsViewModel extends AndroidViewModel {
private MutableLiveData<Date> repositoryCreatedAt;
private MutableLiveData<String> repositoryName;
private MutableLiveData<String> repositoryDescription;
private MutableLiveData<String> repositoryPrimaryLanguage;
private MutableLiveData<Set<String>> repositoryLanguages;
private MutableLiveData<Boolean> repositoryIsPrivate;
public RepositoryDetailsViewModel(Application app) {
super(app);
repositoryCreatedAt = new MutableLiveData<>();
repositoryName = new MutableLiveData<>();
repositoryDescription = new MutableLiveData<>();
repositoryPrimaryLanguage = new MutableLiveData<>();
repositoryLanguages = new MutableLiveData<>();
repositoryIsPrivate = new MutableLiveData<>();
}
public MutableLiveData<Date> getRepositoryCreatedAt() {
return repositoryCreatedAt;
}
public MutableLiveData<String> getRepositoryName() {
return repositoryName;
}
public MutableLiveData<String> getRepositoryDescription() {
return repositoryDescription;
}
public MutableLiveData<String> getRepositoryPrimaryLanguage() {
return repositoryPrimaryLanguage;
}
public MutableLiveData<Set<String>> getRepositoryLanguages() {
return repositoryLanguages;
}
public MutableLiveData<Boolean> getRepositoryIsPrivate() {
return repositoryIsPrivate;
}
public void loadData(String repositoryWithOwner, boolean forceReload) {
this.repositoryName.postValue(repositoryWithOwner);
OpenSourceStatsApplication app = (OpenSourceStatsApplication) getApplication();
RepositoryDataRepository repository = app.getRepositoryDataRepository();
repository.loadRepositoryData(new RepositoryName(repositoryWithOwner), response -> {
RepositoryDataResponse repositoryData = (RepositoryDataResponse) response;
this.repositoryCreatedAt.postValue(repositoryData.getCreatedAt());
this.repositoryDescription.postValue(repositoryData.getDescription());
this.repositoryPrimaryLanguage.postValue(repositoryData.getPrimaryLanguage());
this.repositoryLanguages.postValue(repositoryData.getLanguages());
this.repositoryIsPrivate.postValue(repositoryData.isPrivate());
}, forceReload);
}
}
| 2,890 | 0.757093 | 0.757093 | 79 | 35.582279 | 30.489511 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.531646 | false | false |
3
|
6b042d9c9cba7f17f039b57d177f0cd92e2489f5
| 28,295,244,615,515 |
ef46c1871c1121c02e9cde497fc63456bab8b1b0
|
/orderservice/orderservice/src/main/java/com/readingisgood/orderservice/config/security/JwtUtil.java
|
f31ab10db8b56b32729c8d59961ac78dd33ea5bf
|
[] |
no_license
|
brkyc3/Reading-Is-Good
|
https://github.com/brkyc3/Reading-Is-Good
|
6e4912c4b4af8d9da18d5d604d266aff82be535f
|
d264c1fbb78118603b9f7acd34b1fe55996ab74a
|
refs/heads/master
| 2023-06-04T12:08:10.810000 | 2021-06-27T08:15:57 | 2021-06-27T08:15:57 | 365,583,738 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.readingisgood.orderservice.config.security;
import io.jsonwebtoken.*;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.time.LocalDateTime;
import java.util.Date;
@Component
@Data
@RequiredArgsConstructor
@Slf4j
public class JwtUtil {
@Value("${jwt.secretKey}")
private String key;
@Value("${jwt.expireTimeMs}")
private long ttlMillis;
public String createJWT(String subject) {
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
Date now = new Date();
Date expiration = new Date(now.getTime()+ttlMillis);
return Jwts.builder()
.setIssuedAt(now)
.setExpiration(expiration)
.setSubject(subject)
.signWith(signatureAlgorithm, key)
.compact();
}
public String parseJWT(String jwt) {
return Jwts.parser()
.setSigningKey(key)
.parseClaimsJws(jwt)
.getBody()
.getSubject();
}
public boolean validateJwtToken(String authToken) {
try {
Jwts.parser().setSigningKey(key).parseClaimsJws(authToken);
return true;
} catch (SignatureException e) {
log.error("Invalid JWT signature: {}", e.getMessage());
} catch (MalformedJwtException e) {
log.error("Invalid JWT token: {}", e.getMessage());
} catch (ExpiredJwtException e) {
log.error("JWT token is expired: {}", e.getMessage());
} catch (UnsupportedJwtException e) {
log.error("JWT token is unsupported: {}", e.getMessage());
} catch (IllegalArgumentException e) {
log.error("JWT claims string is empty: {}", e.getMessage());
}
return false;
}
}
|
UTF-8
|
Java
| 2,023 |
java
|
JwtUtil.java
|
Java
|
[] | null |
[] |
package com.readingisgood.orderservice.config.security;
import io.jsonwebtoken.*;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.time.LocalDateTime;
import java.util.Date;
@Component
@Data
@RequiredArgsConstructor
@Slf4j
public class JwtUtil {
@Value("${jwt.secretKey}")
private String key;
@Value("${jwt.expireTimeMs}")
private long ttlMillis;
public String createJWT(String subject) {
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
Date now = new Date();
Date expiration = new Date(now.getTime()+ttlMillis);
return Jwts.builder()
.setIssuedAt(now)
.setExpiration(expiration)
.setSubject(subject)
.signWith(signatureAlgorithm, key)
.compact();
}
public String parseJWT(String jwt) {
return Jwts.parser()
.setSigningKey(key)
.parseClaimsJws(jwt)
.getBody()
.getSubject();
}
public boolean validateJwtToken(String authToken) {
try {
Jwts.parser().setSigningKey(key).parseClaimsJws(authToken);
return true;
} catch (SignatureException e) {
log.error("Invalid JWT signature: {}", e.getMessage());
} catch (MalformedJwtException e) {
log.error("Invalid JWT token: {}", e.getMessage());
} catch (ExpiredJwtException e) {
log.error("JWT token is expired: {}", e.getMessage());
} catch (UnsupportedJwtException e) {
log.error("JWT token is unsupported: {}", e.getMessage());
} catch (IllegalArgumentException e) {
log.error("JWT claims string is empty: {}", e.getMessage());
}
return false;
}
}
| 2,023 | 0.624815 | 0.621849 | 68 | 28.75 | 21.759632 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.470588 | false | false |
3
|
bdc93435320e03a365373d19a6900790222d7d95
| 17,952,963,340,345 |
fdf4b16446a62752c1c13c116a15d896c3696b09
|
/StockMessage/src/com/bigroi/stock/messager/generator/impl/FreeMakerGeneratorImpl.java
|
e0ac97286c3f3072dace24c8f1295a5cae57c9e2
|
[] |
no_license
|
Bigroi/stock
|
https://github.com/Bigroi/stock
|
6720c419249918ae228024b63f017bc87459d5ba
|
b73860bf106dad717f36ae419cc4145603c41d9e
|
refs/heads/master
| 2023-07-19T17:10:11.769000 | 2021-01-06T18:05:14 | 2021-01-06T18:05:14 | 94,612,341 | 8 | 0 | null | false | 2023-07-16T00:14:44 | 2017-06-17T09:01:19 | 2021-01-06T18:06:01 | 2023-07-16T00:14:43 | 86,751 | 2 | 0 | 13 |
Java
| false | false |
package com.bigroi.stock.messager.generator.impl;
import com.bigroi.stock.messager.generator.Generator;
import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.util.Locale;
import java.util.Map;
public class FreeMakerGeneratorImpl implements Generator {
@Override
public String generateBasedOnTemplateString(String template, Map<String, ?> params) {
return generate(cfg -> new Template("string generation", new StringReader(template), cfg), params);
}
@Override
public String generateBasedOnTemplateFile(String templateName, Map<String, ?> params) {
return generate(cfg -> cfg.getTemplate(templateName), params);
}
private String generate(ThrowableFunction<Configuration, Template> templateCreator, Map<String, ?> params) {
try {
Configuration cfg = new Configuration(Configuration.VERSION_2_3_29);
cfg.setDefaultEncoding("UTF-8");
cfg.setLocale(Locale.US);
cfg.setTemplateLoader(new ClassTemplateLoader(this.getClass(), "/"));
Template template = templateCreator.apply(cfg);
var outputStream = new ByteArrayOutputStream();
var writer = new OutputStreamWriter(outputStream);
template.process(params, writer);
return new String(outputStream.toByteArray());
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
private interface ThrowableFunction<T, R> {
R apply(T argument) throws Throwable;
}
}
|
UTF-8
|
Java
| 1,700 |
java
|
FreeMakerGeneratorImpl.java
|
Java
|
[] | null |
[] |
package com.bigroi.stock.messager.generator.impl;
import com.bigroi.stock.messager.generator.Generator;
import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.util.Locale;
import java.util.Map;
public class FreeMakerGeneratorImpl implements Generator {
@Override
public String generateBasedOnTemplateString(String template, Map<String, ?> params) {
return generate(cfg -> new Template("string generation", new StringReader(template), cfg), params);
}
@Override
public String generateBasedOnTemplateFile(String templateName, Map<String, ?> params) {
return generate(cfg -> cfg.getTemplate(templateName), params);
}
private String generate(ThrowableFunction<Configuration, Template> templateCreator, Map<String, ?> params) {
try {
Configuration cfg = new Configuration(Configuration.VERSION_2_3_29);
cfg.setDefaultEncoding("UTF-8");
cfg.setLocale(Locale.US);
cfg.setTemplateLoader(new ClassTemplateLoader(this.getClass(), "/"));
Template template = templateCreator.apply(cfg);
var outputStream = new ByteArrayOutputStream();
var writer = new OutputStreamWriter(outputStream);
template.process(params, writer);
return new String(outputStream.toByteArray());
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
private interface ThrowableFunction<T, R> {
R apply(T argument) throws Throwable;
}
}
| 1,700 | 0.701765 | 0.698824 | 47 | 35.170212 | 30.901573 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.787234 | false | false |
3
|
2104f4262a311d2a98564141836571315deb3eaa
| 10,007,273,857,952 |
9bb02ab9e5e4f211ccbf1245cae08deb64b0e7f5
|
/src/controller/SimulationManager.java
|
b2cb3e4aec4717639310fd5703e00f336a1d7454
|
[] |
no_license
|
vlitan/Multithreading-HW2
|
https://github.com/vlitan/Multithreading-HW2
|
55667c908653f09da1c9fe8f22783dadcd68076a
|
061210cee54e805540fbc7a3ecea3c1f9c558263
|
refs/heads/master
| 2021-01-20T21:34:51.941000 | 2017-04-07T10:33:11 | 2017-04-07T10:33:11 | 101,770,751 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package controller;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JTextField;
import GUI.CoraGUI;
import model.Dispatcher;
import model.SelectionPolicy;
import model.Task;
import model.TaskGenerator;
public class SimulationManager implements Runnable {
private int updateInterval = 1000; //milliseconds
private long lastNow = 0;
private long timeLimit = 100000;
private int maxProcessingTime = 10000;
private int minProcessingTime = 1000;
private int maxNumberOfServers = 2;
private int numberOfClients = 10;
private int minUpdateInterval = 1000;
private int maxUpdateInterval = 2000;
private int threshold = 3;
private SelectionPolicy policy = SelectionPolicy.SHORTEST_QUEUE;
private Dispatcher dispatcher;
private Queue<Task> tasks;
private CoraGUI gui;
public void init(){
dispatcher = new Dispatcher(maxNumberOfServers, numberOfClients);
dispatcher.setStrategy(policy, threshold);
tasks = new ArrayDeque<Task>(numberOfClients + 1);
for (int i = 0; i < numberOfClients; i++){
tasks.add(TaskGenerator.instance().getNext(minProcessingTime, maxProcessingTime));
}
System.out.println("[SimulationManager] created");
gui = new CoraGUI(dispatcher.getServers());
}
public int getThreshold() {
return threshold;
}
public void setThreshold(int threshold) {
this.threshold = threshold;
}
@Override
public void run() {
gui.init();
timeLimit += now();
System.out.println("[SimulationManager] started");
Timer t = new Timer();
t.schedule(new TimerTask(){
@Override
public void run() {
dispatcher.removeClosed();
gui.update(dispatcher.getServers());
}}, 0, 30);
while (now() < timeLimit){
updateInterval = minUpdateInterval + (new Random()).nextInt(maxUpdateInterval - minUpdateInterval);
if(delay(now(), updateInterval)){
dispatcher.dispatchTask(tasks.poll());
System.out.println("[SimulationManager] tick");
}
if (dispatcher.isDone() && tasks.isEmpty()){
gui.displayStats(dispatcher.getStats());
}
}
System.out.println("[SimulationManager] ended");
}
public long now(){
return (System.currentTimeMillis() % Long.MAX_VALUE);
}
private boolean delay(long now, int deltaT){
if (now < lastNow){
lastNow = Long.MAX_VALUE - lastNow + now;
}
if (now - lastNow > deltaT){
lastNow = now;
return true;
}
else
return false;
}
public int getMinProcessingTime() {
return minProcessingTime;
}
public void setMinProcessingTime(int minProcessingTime) {
this.minProcessingTime = minProcessingTime;
}
public long getTimeLimit() {
return timeLimit;
}
public void setTimeLimit(long timeLimit) {
this.timeLimit = timeLimit;
}
public int getMaxProcessingTime() {
return maxProcessingTime;
}
public void setMaxProcessingTime(int maxProcessingTime) {
this.maxProcessingTime = maxProcessingTime;
}
public int getMaxNumberOfServers() {
return maxNumberOfServers;
}
public void setMaxNumberOfServers(int maxNumberOfServers) {
this.maxNumberOfServers = maxNumberOfServers;
}
public int getNumberOfClients() {
return numberOfClients;
}
public void setNumberOfClients(int numberOfClients) {
this.numberOfClients = numberOfClients;
}
public int getMinUpdateInterval() {
return minUpdateInterval;
}
public void setMinUpdateInterval(int minUpdateInterval) {
this.minUpdateInterval = minUpdateInterval;
}
public int getMaxUpdateInterval() {
return maxUpdateInterval;
}
public void setMaxUpdateInterval(int maxUpdateInterval) {
this.maxUpdateInterval = maxUpdateInterval;
}
public SelectionPolicy getPolicy() {
return policy;
}
public void setPolicy(SelectionPolicy policy) {
this.policy = policy;
}
}
|
UTF-8
|
Java
| 3,837 |
java
|
SimulationManager.java
|
Java
|
[] | null |
[] |
package controller;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JTextField;
import GUI.CoraGUI;
import model.Dispatcher;
import model.SelectionPolicy;
import model.Task;
import model.TaskGenerator;
public class SimulationManager implements Runnable {
private int updateInterval = 1000; //milliseconds
private long lastNow = 0;
private long timeLimit = 100000;
private int maxProcessingTime = 10000;
private int minProcessingTime = 1000;
private int maxNumberOfServers = 2;
private int numberOfClients = 10;
private int minUpdateInterval = 1000;
private int maxUpdateInterval = 2000;
private int threshold = 3;
private SelectionPolicy policy = SelectionPolicy.SHORTEST_QUEUE;
private Dispatcher dispatcher;
private Queue<Task> tasks;
private CoraGUI gui;
public void init(){
dispatcher = new Dispatcher(maxNumberOfServers, numberOfClients);
dispatcher.setStrategy(policy, threshold);
tasks = new ArrayDeque<Task>(numberOfClients + 1);
for (int i = 0; i < numberOfClients; i++){
tasks.add(TaskGenerator.instance().getNext(minProcessingTime, maxProcessingTime));
}
System.out.println("[SimulationManager] created");
gui = new CoraGUI(dispatcher.getServers());
}
public int getThreshold() {
return threshold;
}
public void setThreshold(int threshold) {
this.threshold = threshold;
}
@Override
public void run() {
gui.init();
timeLimit += now();
System.out.println("[SimulationManager] started");
Timer t = new Timer();
t.schedule(new TimerTask(){
@Override
public void run() {
dispatcher.removeClosed();
gui.update(dispatcher.getServers());
}}, 0, 30);
while (now() < timeLimit){
updateInterval = minUpdateInterval + (new Random()).nextInt(maxUpdateInterval - minUpdateInterval);
if(delay(now(), updateInterval)){
dispatcher.dispatchTask(tasks.poll());
System.out.println("[SimulationManager] tick");
}
if (dispatcher.isDone() && tasks.isEmpty()){
gui.displayStats(dispatcher.getStats());
}
}
System.out.println("[SimulationManager] ended");
}
public long now(){
return (System.currentTimeMillis() % Long.MAX_VALUE);
}
private boolean delay(long now, int deltaT){
if (now < lastNow){
lastNow = Long.MAX_VALUE - lastNow + now;
}
if (now - lastNow > deltaT){
lastNow = now;
return true;
}
else
return false;
}
public int getMinProcessingTime() {
return minProcessingTime;
}
public void setMinProcessingTime(int minProcessingTime) {
this.minProcessingTime = minProcessingTime;
}
public long getTimeLimit() {
return timeLimit;
}
public void setTimeLimit(long timeLimit) {
this.timeLimit = timeLimit;
}
public int getMaxProcessingTime() {
return maxProcessingTime;
}
public void setMaxProcessingTime(int maxProcessingTime) {
this.maxProcessingTime = maxProcessingTime;
}
public int getMaxNumberOfServers() {
return maxNumberOfServers;
}
public void setMaxNumberOfServers(int maxNumberOfServers) {
this.maxNumberOfServers = maxNumberOfServers;
}
public int getNumberOfClients() {
return numberOfClients;
}
public void setNumberOfClients(int numberOfClients) {
this.numberOfClients = numberOfClients;
}
public int getMinUpdateInterval() {
return minUpdateInterval;
}
public void setMinUpdateInterval(int minUpdateInterval) {
this.minUpdateInterval = minUpdateInterval;
}
public int getMaxUpdateInterval() {
return maxUpdateInterval;
}
public void setMaxUpdateInterval(int maxUpdateInterval) {
this.maxUpdateInterval = maxUpdateInterval;
}
public SelectionPolicy getPolicy() {
return policy;
}
public void setPolicy(SelectionPolicy policy) {
this.policy = policy;
}
}
| 3,837 | 0.728955 | 0.719312 | 163 | 22.539877 | 20.731188 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.809816 | false | false |
3
|
79b35312a2d8ee9908f0c260c0084f7a9766144f
| 31,396,210,947,328 |
addb7120de4186c43b136a0d10b172dc2f215c7c
|
/src/main/java/ilielucian/demo/notes/webapp/notes/rest/NoteResource.java
|
989387cc9503159ad41434085589d563020c0fa5
|
[] |
no_license
|
ilielucian/notes-webapp
|
https://github.com/ilielucian/notes-webapp
|
cc47f9673cec9b02af2abab4fbb82dc3c5bbec56
|
44f256c3703d6c3988f6ecfd5d0ac1d6f075373c
|
refs/heads/master
| 2018-01-09T14:42:10.155000 | 2015-12-05T10:32:19 | 2015-12-05T10:32:19 | 46,669,111 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package ilielucian.demo.notes.webapp.notes.rest;
import java.util.List;
import java.util.NoSuchElementException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import ilielucian.demo.notes.webapp.notes.model.Note;
import ilielucian.demo.notes.webapp.notes.service.NoteService;
/**
* Created by Lucian Ilie.
*/
@RestController
public class NoteResource {
private final NoteService noteService;
@Autowired
public NoteResource(NoteService noteService) {
this.noteService = noteService;
}
@RequestMapping(method = RequestMethod.GET, value = "/notes")
public List<Note> getAllNotes() {
return noteService.getAllNotes();
}
@RequestMapping(method = RequestMethod.GET, value = "/notes/{id}")
public Note getOneNote(@PathVariable("id") long noteId) {
Note note = noteService.getNote(noteId);
if (note == null) {
throw new NoSuchElementException();
} else {
return note;
}
}
@RequestMapping(method = RequestMethod.POST, value = "/notes/new")
public long saveNote(@RequestBody Note note) {
return noteService.saveNote(note);
}
@RequestMapping(method = RequestMethod.DELETE, value = "/notes/{id}")
public void deleteNote(@PathVariable("id") long noteId) {
noteService.deleteNote(noteId);
}
}
|
UTF-8
|
Java
| 1,412 |
java
|
NoteResource.java
|
Java
|
[
{
"context": "bapp.notes.service.NoteService;\n\n/**\n * Created by Lucian Ilie.\n */\n@RestController\npublic class NoteResource {\n",
"end": 376,
"score": 0.999876081943512,
"start": 365,
"tag": "NAME",
"value": "Lucian Ilie"
}
] | null |
[] |
package ilielucian.demo.notes.webapp.notes.rest;
import java.util.List;
import java.util.NoSuchElementException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import ilielucian.demo.notes.webapp.notes.model.Note;
import ilielucian.demo.notes.webapp.notes.service.NoteService;
/**
* Created by <NAME>.
*/
@RestController
public class NoteResource {
private final NoteService noteService;
@Autowired
public NoteResource(NoteService noteService) {
this.noteService = noteService;
}
@RequestMapping(method = RequestMethod.GET, value = "/notes")
public List<Note> getAllNotes() {
return noteService.getAllNotes();
}
@RequestMapping(method = RequestMethod.GET, value = "/notes/{id}")
public Note getOneNote(@PathVariable("id") long noteId) {
Note note = noteService.getNote(noteId);
if (note == null) {
throw new NoSuchElementException();
} else {
return note;
}
}
@RequestMapping(method = RequestMethod.POST, value = "/notes/new")
public long saveNote(@RequestBody Note note) {
return noteService.saveNote(note);
}
@RequestMapping(method = RequestMethod.DELETE, value = "/notes/{id}")
public void deleteNote(@PathVariable("id") long noteId) {
noteService.deleteNote(noteId);
}
}
| 1,407 | 0.686969 | 0.686969 | 50 | 27.24 | 24.422579 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.38 | false | false |
3
|
269ec62a4a6a7715baf6e827535331a66387fd6a
| 27,487,790,730,313 |
2a58bac44d9a1fbfb4c4528fadc0df7322d2bd7f
|
/sooltoryteller/src/test/java/com/sooltoryteller/mapper/MemberFavDrkTests.java
|
7f97d52c5094d514e43a124c8710e6979d05cd35
|
[] |
no_license
|
Limhyeonsu/sooltoryteller
|
https://github.com/Limhyeonsu/sooltoryteller
|
ab71adadb5d790aecdf04b0205be1f4504004dce
|
f62249834d02792b7f26f07492862f7c4b9e20ec
|
refs/heads/main
| 2023-02-13T14:46:10.340000 | 2021-01-15T15:41:22 | 2021-01-15T15:41:22 | 329,936,778 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.sooltoryteller.mapper;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.sooltoryteller.domain.MemberFavDrkVO;
import lombok.Setter;
import lombok.extern.log4j.Log4j;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("file:src/main/webapp/WEB-INF/spring/root-context.xml")
@Log4j
public class MemberFavDrkTests {
@Setter(onMethod_ = @Autowired)
private MemberFavDrkMapper mapper;
// @Test
public void testInsert() {
MemberFavDrkVO memberFavDrk = new MemberFavDrkVO();
int[] drink = {1,7};
memberFavDrk.setMemberId(11L);
for(int i =0; i<2; i++) {
memberFavDrk.setDrkCdId(drink[i]);
mapper.insert(memberFavDrk);
}
System.out.println(memberFavDrk);
}
// @Test
public void testGet() {
List<Integer> list = mapper.get(11L);
list.forEach(drink -> log.info(drink));
}
// @Test
public void testGetFavDrkId() {
List<Long> list = mapper.getFavDrkId(11L);
list.forEach(drkId -> log.info(drkId));
}
// @Test
public void testUpdateFavDrk() {
MemberFavDrkVO memberFavDrk = new MemberFavDrkVO();
List<Long> list = mapper.getFavDrkId(11L);
int[] drink = {5,6};
for(int i=0; i<list.size(); i++) {
memberFavDrk.setDrkCdId(drink[i]);
memberFavDrk.setFavDrkId(list.get(i));
mapper.updateFavDrk(memberFavDrk);
}
}
}
|
UTF-8
|
Java
| 1,541 |
java
|
MemberFavDrkTests.java
|
Java
|
[] | null |
[] |
package com.sooltoryteller.mapper;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.sooltoryteller.domain.MemberFavDrkVO;
import lombok.Setter;
import lombok.extern.log4j.Log4j;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("file:src/main/webapp/WEB-INF/spring/root-context.xml")
@Log4j
public class MemberFavDrkTests {
@Setter(onMethod_ = @Autowired)
private MemberFavDrkMapper mapper;
// @Test
public void testInsert() {
MemberFavDrkVO memberFavDrk = new MemberFavDrkVO();
int[] drink = {1,7};
memberFavDrk.setMemberId(11L);
for(int i =0; i<2; i++) {
memberFavDrk.setDrkCdId(drink[i]);
mapper.insert(memberFavDrk);
}
System.out.println(memberFavDrk);
}
// @Test
public void testGet() {
List<Integer> list = mapper.get(11L);
list.forEach(drink -> log.info(drink));
}
// @Test
public void testGetFavDrkId() {
List<Long> list = mapper.getFavDrkId(11L);
list.forEach(drkId -> log.info(drkId));
}
// @Test
public void testUpdateFavDrk() {
MemberFavDrkVO memberFavDrk = new MemberFavDrkVO();
List<Long> list = mapper.getFavDrkId(11L);
int[] drink = {5,6};
for(int i=0; i<list.size(); i++) {
memberFavDrk.setDrkCdId(drink[i]);
memberFavDrk.setFavDrkId(list.get(i));
mapper.updateFavDrk(memberFavDrk);
}
}
}
| 1,541 | 0.728099 | 0.714471 | 65 | 22.723078 | 20.336029 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.646154 | false | false |
3
|
4ce9215faa368fb3a1f1d303fc386f80a69a9398
| 21,638,045,241,690 |
54a53aa1dd1074bd255b0e498a888338d113d9ab
|
/CarsSorter/src/RentalcarsSorter/JsonParser.java
|
90354c460a27d67fb3e0aa8c119c2cb11f05ce08
|
[] |
no_license
|
mhasan2/RentalcarsSorter
|
https://github.com/mhasan2/RentalcarsSorter
|
cf708de7d6ed497be2c556228b21d3c211f0ea94
|
c86e0a92731d1a0aa88757a693226a21f6eec9d2
|
refs/heads/master
| 2020-07-22T10:19:06.609000 | 2019-02-28T13:02:30 | 2019-02-28T13:02:30 | 73,815,417 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package RentalcarsSorter;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import com.google.gson.Gson;
import RentalcarsSorter.Models.car;
import RentalcarsSorter.Models.Result;
public class JsonParser {
public static String readFile(String filename)
{
try (BufferedReader lineReader = new BufferedReader(new FileReader(filename)))
{
StringBuilder sb = new StringBuilder();
String line = lineReader.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = lineReader.readLine();
}
return sb.toString();
} catch (FileNotFoundException e) {
System.err.println("FileNotFoundException: " + e.getMessage());
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
}
return null;
}
public static car[] parseJson(String filename)
{
Result parsed = new Gson().fromJson(readFile(filename), Result.class);
return parsed.Search.VehicleList;
}
}
|
UTF-8
|
Java
| 1,132 |
java
|
JsonParser.java
|
Java
|
[] | null |
[] |
package RentalcarsSorter;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import com.google.gson.Gson;
import RentalcarsSorter.Models.car;
import RentalcarsSorter.Models.Result;
public class JsonParser {
public static String readFile(String filename)
{
try (BufferedReader lineReader = new BufferedReader(new FileReader(filename)))
{
StringBuilder sb = new StringBuilder();
String line = lineReader.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = lineReader.readLine();
}
return sb.toString();
} catch (FileNotFoundException e) {
System.err.println("FileNotFoundException: " + e.getMessage());
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
}
return null;
}
public static car[] parseJson(String filename)
{
Result parsed = new Gson().fromJson(readFile(filename), Result.class);
return parsed.Search.VehicleList;
}
}
| 1,132 | 0.663428 | 0.663428 | 45 | 23.155556 | 21.531326 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.622222 | false | false |
3
|
83f3bf672fe6ffd6ed9389c7e8fca6031da5d82c
| 32,624,571,615,891 |
72b380486aad640ab04f0b2903023ca342914f94
|
/src/models/FixedValuesTransaction.java
|
fa23d5d95a279945c214311666e25b29c2336149
|
[] |
no_license
|
lastbulletbender/mini-splitwise-takehome
|
https://github.com/lastbulletbender/mini-splitwise-takehome
|
c24377b53279a758ba0ef59f482d7b6d62ab9e1e
|
d826dece922595000dbde94324e5825494bdd767
|
refs/heads/main
| 2023-04-09T10:13:18.248000 | 2021-04-19T08:41:18 | 2021-04-19T08:41:18 | 359,388,035 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package models;
import java.util.List;
public class FixedValuesTransaction extends Transaction {
public FixedValuesTransaction(String transactionName, User paidBy, List<FixedValuesTransactionDTO> fixedValuesTransactionDTOS, Float amount) throws Exception {
super(transactionName, paidBy, amount);
if (!validate(fixedValuesTransactionDTOS)) {
throw new Exception("Fixed values split is invalid");
}
split(fixedValuesTransactionDTOS);
}
private void split(List<FixedValuesTransactionDTO> fixedValuesTransactionDTOS) {
for (FixedValuesTransactionDTO fixedValuesTransactionDTO : fixedValuesTransactionDTOS) {
this.amountMapping.put(fixedValuesTransactionDTO.getUser(), fixedValuesTransactionDTO.getValue());
}
}
private boolean validate(List<FixedValuesTransactionDTO> fixedValuesTransactionDTOS) {
Float total = 0F;
for (FixedValuesTransactionDTO fixedValuesTransactionDTO : fixedValuesTransactionDTOS) {
total += fixedValuesTransactionDTO.getValue();
}
return total.equals(this.amount);
}
}
|
UTF-8
|
Java
| 1,136 |
java
|
FixedValuesTransaction.java
|
Java
|
[] | null |
[] |
package models;
import java.util.List;
public class FixedValuesTransaction extends Transaction {
public FixedValuesTransaction(String transactionName, User paidBy, List<FixedValuesTransactionDTO> fixedValuesTransactionDTOS, Float amount) throws Exception {
super(transactionName, paidBy, amount);
if (!validate(fixedValuesTransactionDTOS)) {
throw new Exception("Fixed values split is invalid");
}
split(fixedValuesTransactionDTOS);
}
private void split(List<FixedValuesTransactionDTO> fixedValuesTransactionDTOS) {
for (FixedValuesTransactionDTO fixedValuesTransactionDTO : fixedValuesTransactionDTOS) {
this.amountMapping.put(fixedValuesTransactionDTO.getUser(), fixedValuesTransactionDTO.getValue());
}
}
private boolean validate(List<FixedValuesTransactionDTO> fixedValuesTransactionDTOS) {
Float total = 0F;
for (FixedValuesTransactionDTO fixedValuesTransactionDTO : fixedValuesTransactionDTOS) {
total += fixedValuesTransactionDTO.getValue();
}
return total.equals(this.amount);
}
}
| 1,136 | 0.731514 | 0.730634 | 31 | 35.677418 | 41.599773 | 163 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.483871 | false | false |
3
|
cbfdf3fe4e7323c71dbaba7d4393cc6fb0e90405
| 9,088,150,831,781 |
4bdc6a8113f8dbd326f758d2d044c224fd2fd4d0
|
/源码/QuestionLibrary/src/com/silence/questionlib/i18n/I18nUtils.java
|
748e5d3e4f4dc12fff297f0fe76ef7d075b4c22a
|
[] |
no_license
|
gybing/SoftwareEngineeringDesign
|
https://github.com/gybing/SoftwareEngineeringDesign
|
5d8aab181640f9adfaa469f6079af7ceecd638ed
|
92d9ef0e8fed6bc0602cc636ad0762a2b50de0a4
|
refs/heads/master
| 2020-12-30T23:21:37.430000 | 2016-06-27T07:24:08 | 2016-06-27T07:24:08 | 65,610,902 | 82 | 22 | null | true | 2016-08-13T09:49:14 | 2016-08-13T09:49:13 | 2016-06-28T07:36:49 | 2016-06-27T07:24:08 | 7,654 | 0 | 0 | 0 | null | null | null |
package com.silence.questionlib.i18n;
import java.util.Locale;
import java.util.ResourceBundle;
/**
* 国际化工具类
*
* @author 林宇强 2015-12-05
*
*/
public class I18nUtils {
/**
* 国际化参数提取测试
*
* @param args
*/
public static void main(String[] args) {
ResourceBundle bundle = ResourceBundle.getBundle(
"com.silence.questionlib.i18n.resource", Locale.CHINA);
String username = bundle.getString("usex_male");
String password = bundle.getString("password");
System.out.println(username);
System.out.println(password);
System.out
.println(I18nUtils.getI18nProperty(Locale.CHINA, "usex_male"));
}
/**
* 从国家化文件中提取相应的信息
*
* @param locale要提取的地区
* @param name要提取信息名
* @return 返回指定地区的对应信息名的信息
*/
public static String getI18nProperty(Locale locale, String name) {
ResourceBundle bundle = ResourceBundle.getBundle(
"com.silence.questionlib.i18n.resource", locale);
return bundle.getString(name);
}
}
|
GB18030
|
Java
| 1,064 |
java
|
I18nUtils.java
|
Java
|
[
{
"context": "til.ResourceBundle;\n\n/**\n * 国际化工具类\n * \n * @author 林宇强 2015-12-05\n * \n */\npublic class I18nUtils {\n\n\t/**",
"end": 130,
"score": 0.9997918605804443,
"start": 127,
"tag": "NAME",
"value": "林宇强"
},
{
"context": "ale.CHINA);\n\t\tString username = bundle.getString(\"usex_male\");\n\t\tString password = bundle.getString(\"password",
"end": 422,
"score": 0.6612338423728943,
"start": 413,
"tag": "USERNAME",
"value": "usex_male"
}
] | null |
[] |
package com.silence.questionlib.i18n;
import java.util.Locale;
import java.util.ResourceBundle;
/**
* 国际化工具类
*
* @author 林宇强 2015-12-05
*
*/
public class I18nUtils {
/**
* 国际化参数提取测试
*
* @param args
*/
public static void main(String[] args) {
ResourceBundle bundle = ResourceBundle.getBundle(
"com.silence.questionlib.i18n.resource", Locale.CHINA);
String username = bundle.getString("usex_male");
String password = bundle.getString("password");
System.out.println(username);
System.out.println(password);
System.out
.println(I18nUtils.getI18nProperty(Locale.CHINA, "usex_male"));
}
/**
* 从国家化文件中提取相应的信息
*
* @param locale要提取的地区
* @param name要提取信息名
* @return 返回指定地区的对应信息名的信息
*/
public static String getI18nProperty(Locale locale, String name) {
ResourceBundle bundle = ResourceBundle.getBundle(
"com.silence.questionlib.i18n.resource", locale);
return bundle.getString(name);
}
}
| 1,064 | 0.706131 | 0.682875 | 43 | 21 | 20.453009 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.372093 | false | false |
3
|
9e81c5e5254d72ca3f0596425b234a8e82686dca
| 3,015,067,107,810 |
a2df6764e9f4350e0d9184efadb6c92c40d40212
|
/aliyun-java-sdk-hbr/src/main/java/com/aliyuncs/hbr/transform/v20170908/UpdateVmBackupPlanResponseUnmarshaller.java
|
08cdf0cecd12095683f6e9838edc14b1e1628eb2
|
[
"Apache-2.0"
] |
permissive
|
warriorsZXX/aliyun-openapi-java-sdk
|
https://github.com/warriorsZXX/aliyun-openapi-java-sdk
|
567840c4bdd438d43be6bd21edde86585cd6274a
|
f8fd2b81a5f2cd46b1e31974ff6a7afed111a245
|
refs/heads/master
| 2022-12-06T15:45:20.418000 | 2020-08-20T08:37:31 | 2020-08-26T06:17:49 | 290,450,773 | 1 | 0 |
NOASSERTION
| true | 2020-08-26T09:15:48 | 2020-08-26T09:15:47 | 2020-08-26T06:17:55 | 2020-08-26T08:27:38 | 37,198 | 0 | 0 | 0 | null | false | false |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.aliyuncs.hbr.transform.v20170908;
import com.aliyuncs.hbr.model.v20170908.UpdateVmBackupPlanResponse;
import com.aliyuncs.transform.UnmarshallerContext;
public class UpdateVmBackupPlanResponseUnmarshaller {
public static UpdateVmBackupPlanResponse unmarshall(UpdateVmBackupPlanResponse updateVmBackupPlanResponse, UnmarshallerContext _ctx) {
updateVmBackupPlanResponse.setRequestId(_ctx.stringValue("UpdateVmBackupPlanResponse.RequestId"));
updateVmBackupPlanResponse.setSuccess(_ctx.booleanValue("UpdateVmBackupPlanResponse.Success"));
updateVmBackupPlanResponse.setCode(_ctx.stringValue("UpdateVmBackupPlanResponse.Code"));
updateVmBackupPlanResponse.setMessage(_ctx.stringValue("UpdateVmBackupPlanResponse.Message"));
return updateVmBackupPlanResponse;
}
}
|
UTF-8
|
Java
| 1,358 |
java
|
UpdateVmBackupPlanResponseUnmarshaller.java
|
Java
|
[] | null |
[] |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.aliyuncs.hbr.transform.v20170908;
import com.aliyuncs.hbr.model.v20170908.UpdateVmBackupPlanResponse;
import com.aliyuncs.transform.UnmarshallerContext;
public class UpdateVmBackupPlanResponseUnmarshaller {
public static UpdateVmBackupPlanResponse unmarshall(UpdateVmBackupPlanResponse updateVmBackupPlanResponse, UnmarshallerContext _ctx) {
updateVmBackupPlanResponse.setRequestId(_ctx.stringValue("UpdateVmBackupPlanResponse.RequestId"));
updateVmBackupPlanResponse.setSuccess(_ctx.booleanValue("UpdateVmBackupPlanResponse.Success"));
updateVmBackupPlanResponse.setCode(_ctx.stringValue("UpdateVmBackupPlanResponse.Code"));
updateVmBackupPlanResponse.setMessage(_ctx.stringValue("UpdateVmBackupPlanResponse.Message"));
return updateVmBackupPlanResponse;
}
}
| 1,358 | 0.805596 | 0.790869 | 32 | 41.3125 | 38.459751 | 135 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.90625 | false | false |
3
|
1cd4a1c7fe6f50830db37b1f526d97eca03f079a
| 27,625,229,712,717 |
bd8c490041b4f1508c7bd0d5456c27b7cf9c83a0
|
/orgecsite/src/com/internousdev/orgecsite/action/GoItemDetailAction.java
|
5b8219a0adff75dab0e75383bd6984f614058142
|
[] |
no_license
|
HirokiYuri-0315/myECsite
|
https://github.com/HirokiYuri-0315/myECsite
|
4280d601ba10b64926e88becf10f3ccc2e161dc5
|
c20cae8ec379bb669de8c7ab0f7c933d88c707ea
|
refs/heads/master
| 2020-03-26T05:24:15.397000 | 2018-09-13T01:35:32 | 2018-09-13T01:35:32 | 144,555,261 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.internousdev.orgecsite.action;
import java.sql.SQLException;
import java.util.Map;
import org.apache.struts2.interceptor.SessionAware;
import com.internousdev.orgecsite.dao.ItemDataDAO;
import com.internousdev.orgecsite.dto.ItemDataDTO;
import com.opensymphony.xwork2.ActionSupport;
public class GoItemDetailAction extends ActionSupport implements SessionAware {
private ItemDataDAO itemDataDAO = new ItemDataDAO();
private String selectId;
public Map<String,Object> session;
public String execute() throws SQLException {
if(selectId.equals(null)) {
return ERROR;
} /* sessionのidを持たずに(何らかのおかしな操作で)来てしまった場合、エラーとして弾く。 */
ItemDataDTO anItemAllDataDTO = itemDataDAO.getAnItemData(selectId);
session.put("selectId", anItemAllDataDTO.getId());
session.put("selectItemName", anItemAllDataDTO.getItemName());
session.put("selectItemPrice", anItemAllDataDTO.getItemPrice());
session.put("selectItemStock", anItemAllDataDTO.getItemStock());
session.put("selectItemNameKana", anItemAllDataDTO.getItemNameKana());
session.put("selectItemDescription", anItemAllDataDTO.getItemDescription());
session.put("selectImageFilePath", anItemAllDataDTO.getImageFilePath());
session.put("selectImageFileName", anItemAllDataDTO.getImageFileName());
session.put("selectCategoryId", anItemAllDataDTO.getCategoryId());
String result = SUCCESS;
return result;
}
@Override
public void setSession(Map<String, Object> session) {
this.session = session;
}
public String getSelectId() {
return selectId;
}
public void setSelectId(String selectId) {
this.selectId = selectId;
}
}
|
UTF-8
|
Java
| 1,693 |
java
|
GoItemDetailAction.java
|
Java
|
[] | null |
[] |
package com.internousdev.orgecsite.action;
import java.sql.SQLException;
import java.util.Map;
import org.apache.struts2.interceptor.SessionAware;
import com.internousdev.orgecsite.dao.ItemDataDAO;
import com.internousdev.orgecsite.dto.ItemDataDTO;
import com.opensymphony.xwork2.ActionSupport;
public class GoItemDetailAction extends ActionSupport implements SessionAware {
private ItemDataDAO itemDataDAO = new ItemDataDAO();
private String selectId;
public Map<String,Object> session;
public String execute() throws SQLException {
if(selectId.equals(null)) {
return ERROR;
} /* sessionのidを持たずに(何らかのおかしな操作で)来てしまった場合、エラーとして弾く。 */
ItemDataDTO anItemAllDataDTO = itemDataDAO.getAnItemData(selectId);
session.put("selectId", anItemAllDataDTO.getId());
session.put("selectItemName", anItemAllDataDTO.getItemName());
session.put("selectItemPrice", anItemAllDataDTO.getItemPrice());
session.put("selectItemStock", anItemAllDataDTO.getItemStock());
session.put("selectItemNameKana", anItemAllDataDTO.getItemNameKana());
session.put("selectItemDescription", anItemAllDataDTO.getItemDescription());
session.put("selectImageFilePath", anItemAllDataDTO.getImageFilePath());
session.put("selectImageFileName", anItemAllDataDTO.getImageFileName());
session.put("selectCategoryId", anItemAllDataDTO.getCategoryId());
String result = SUCCESS;
return result;
}
@Override
public void setSession(Map<String, Object> session) {
this.session = session;
}
public String getSelectId() {
return selectId;
}
public void setSelectId(String selectId) {
this.selectId = selectId;
}
}
| 1,693 | 0.78567 | 0.784435 | 51 | 30.745098 | 27.015495 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.705882 | false | false |
3
|
459206fb8d0e83e8bc3c9e7e4d45ab08ba8147a5
| 1,382,979,514,141 |
3c5aae36c0fd2844193d98a32882973712caa8a3
|
/DWS/src/main/java/com/jpmc/hlt/utils/ReportLog.java
|
94ae599cf7aba7374a2a57b9c1602dfbe77d2036
|
[] |
no_license
|
AdilMollamat/FrameWork
|
https://github.com/AdilMollamat/FrameWork
|
a07fea1f34096b3f6d44d2f55f58ee2ce84ca2a0
|
cf2e1cb373324aed313fefe24fad4534636b4ea0
|
refs/heads/master
| 2020-04-24T04:38:27.625000 | 2019-02-20T16:45:39 | 2019-02-20T16:45:39 | 171,711,337 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.jpmc.hlt.utils;
import java.io.File;
import org.apache.log4j.*;
import org.jsoup.helper.DescendableLinkedList;
import org.openqa.selenium.WebDriver;
import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;
public class ReportLog {
static Logger log = Logger.getLogger(ReportLog.class);
public static ExtentReports report;
public static ExtentTest extLog;
public static String Reportfolder;
private static final boolean REALLY_CAPTURE_SCREENSHOTS = false;
public static void CreateHtmlReport() {
log.info("TimeStamp: " + CommonInit.sTimeStamp);
report = new ExtentReports(CommonInit.projPath + "\\Reports\\" + ReportLog.Reportfolder
+ "\\DW automation Report_" + CommonInit.sTimeStamp + ".html");
report.loadConfig(new File(CommonInit.projPath + "\\extent-config.xml"));
}
public static void StartTestCase(String sTestCaseName) {
extLog = report.startTest(sTestCaseName);
}
public static void EndTestCase() {
report.endTest(extLog);
report.flush();
}
public static void reportAStep(WebDriver driver, String status, String desc, String imageName, boolean imgCapture) {
String image = null;
if (imgCapture && REALLY_CAPTURE_SCREENSHOTS) {
String scrnshot = UIControls.capturescreenshot(driver, imageName);
image = extLog.addScreenCapture(scrnshot);
}
if (imgCapture && REALLY_CAPTURE_SCREENSHOTS) {
switch (status.toLowerCase()) {
case "pass":
extLog.log(LogStatus.PASS, desc + image);
break;
case "fail":
extLog.log(LogStatus.FAIL, desc + image);
break;
case "warning":
extLog.log(LogStatus.WARNING, desc + image);
break;
case "info":
extLog.log(LogStatus.INFO, desc + image);
break;
}
} else if (!imgCapture) {
switch (status.toLowerCase()) {
case "pass":
extLog.log(LogStatus.PASS, desc);
break;
case "fail":
extLog.log(LogStatus.FAIL, desc);
break;
case "warning":
extLog.log(LogStatus.WARNING, desc);
break;
case "info":
extLog.log(LogStatus.INFO, desc);
break;
}
}
}
}
|
UTF-8
|
Java
| 2,229 |
java
|
ReportLog.java
|
Java
|
[] | null |
[] |
package com.jpmc.hlt.utils;
import java.io.File;
import org.apache.log4j.*;
import org.jsoup.helper.DescendableLinkedList;
import org.openqa.selenium.WebDriver;
import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;
public class ReportLog {
static Logger log = Logger.getLogger(ReportLog.class);
public static ExtentReports report;
public static ExtentTest extLog;
public static String Reportfolder;
private static final boolean REALLY_CAPTURE_SCREENSHOTS = false;
public static void CreateHtmlReport() {
log.info("TimeStamp: " + CommonInit.sTimeStamp);
report = new ExtentReports(CommonInit.projPath + "\\Reports\\" + ReportLog.Reportfolder
+ "\\DW automation Report_" + CommonInit.sTimeStamp + ".html");
report.loadConfig(new File(CommonInit.projPath + "\\extent-config.xml"));
}
public static void StartTestCase(String sTestCaseName) {
extLog = report.startTest(sTestCaseName);
}
public static void EndTestCase() {
report.endTest(extLog);
report.flush();
}
public static void reportAStep(WebDriver driver, String status, String desc, String imageName, boolean imgCapture) {
String image = null;
if (imgCapture && REALLY_CAPTURE_SCREENSHOTS) {
String scrnshot = UIControls.capturescreenshot(driver, imageName);
image = extLog.addScreenCapture(scrnshot);
}
if (imgCapture && REALLY_CAPTURE_SCREENSHOTS) {
switch (status.toLowerCase()) {
case "pass":
extLog.log(LogStatus.PASS, desc + image);
break;
case "fail":
extLog.log(LogStatus.FAIL, desc + image);
break;
case "warning":
extLog.log(LogStatus.WARNING, desc + image);
break;
case "info":
extLog.log(LogStatus.INFO, desc + image);
break;
}
} else if (!imgCapture) {
switch (status.toLowerCase()) {
case "pass":
extLog.log(LogStatus.PASS, desc);
break;
case "fail":
extLog.log(LogStatus.FAIL, desc);
break;
case "warning":
extLog.log(LogStatus.WARNING, desc);
break;
case "info":
extLog.log(LogStatus.INFO, desc);
break;
}
}
}
}
| 2,229 | 0.685509 | 0.685061 | 78 | 26.576923 | 23.880322 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.666667 | false | false |
3
|
0227868abcb55c9411ec29ad3e28b6359f928156
| 335,007,455,346 |
bc9878a0f63f59ed816b32be2addde4b3cbec4e4
|
/Chpt 1~2__Basic/EX03_02.java
|
4d62ff55d74c0d519189ffbff6243858050179c1
|
[] |
no_license
|
KangYunHo1221/Java_Basic_Book
|
https://github.com/KangYunHo1221/Java_Basic_Book
|
223076cad701c1bc6ddfbd4d52db5cbff87d0a6e
|
58b4de97dd63404c2a171142e1f83964d95141d6
|
refs/heads/main
| 2023-09-02T14:50:23.094000 | 2021-11-18T01:40:19 | 2021-11-18T01:40:19 | 419,349,326 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class EX_03_02 {
int i = 10;
String str;
double a = 10;
double b = 20;
public static void main(String[] args) {
float _amugeona = 0.0f;
boolean Succeed = true;
short $age = 18;
byte lol = 2;
char asdfd = 'c';
int i = 20;
}
}
|
UTF-8
|
Java
| 253 |
java
|
EX03_02.java
|
Java
|
[] | null |
[] |
public class EX_03_02 {
int i = 10;
String str;
double a = 10;
double b = 20;
public static void main(String[] args) {
float _amugeona = 0.0f;
boolean Succeed = true;
short $age = 18;
byte lol = 2;
char asdfd = 'c';
int i = 20;
}
}
| 253 | 0.58498 | 0.517787 | 15 | 15.8 | 10.127192 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.933333 | false | false |
3
|
39b2e6986e1d5dd9ed6f45495197cb5c2e3a4eef
| 13,073,880,489,639 |
166dbc52b3f630db1348c89223fda42cbefd7a98
|
/app/src/test/java/com/katmandu/katmandu/AccessActivityTest.java
|
107db6db2e44a00c7e3087ef38b2e2953ac739c6
|
[
"Apache-2.0"
] |
permissive
|
jonatantierno/huggingNepal
|
https://github.com/jonatantierno/huggingNepal
|
254ced46156ce8215c7b126542d8d1c43fc718be
|
5f7d38bdad03e324d0422af4c1e6cba7b3ee53e4
|
refs/heads/master
| 2021-01-17T05:58:16.194000 | 2015-05-11T12:10:24 | 2015-05-11T12:10:24 | 35,416,759 | 2 | 0 | null | false | 2015-05-11T12:10:25 | 2015-05-11T10:17:33 | 2015-05-11T10:21:32 | 2015-05-11T12:10:24 | 0 | 0 | 0 | 0 |
Java
| null | null |
package com.katmandu.katmandu;
import android.content.Intent;
import android.view.View;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.util.ActivityController;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* Created by jonatan on 11/05/15.
*/
@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class, emulateSdk = 21)
public class AccessActivityTest {
private ActivityController<AccessActivity> controller;
@Before
public void setup(){
controller = Robolectric.buildActivity(AccessActivity.class);
controller.get().passwordStore = mock(PasswordStore.class);
}
@Test
public void ifWrongPasswordThenShowMesage(){
testVisibility(true, View.VISIBLE);
verify(controller.get().passwordStore).delete(controller.get());
}
@Test
public void ifNoWrongPasswordThenHideMesage(){
testVisibility(false, View.GONE);
}
private void testVisibility(boolean wrongPasswdExtra, int visibility) {
controller.withIntent(new Intent().putExtra(AccessActivity.WRONG_PASSWORD, wrongPasswdExtra));
AccessActivity accessActivity = controller.create().resume().get();
assertEquals(visibility, accessActivity.findViewById(R.id.wrongPasswordTextView).getVisibility());
}
}
|
UTF-8
|
Java
| 1,553 |
java
|
AccessActivityTest.java
|
Java
|
[
{
"context": "tic org.mockito.Mockito.verify;\n\n/**\n * Created by jonatan on 11/05/15.\n */\n@RunWith(RobolectricGradleTestRu",
"end": 492,
"score": 0.9994921684265137,
"start": 485,
"tag": "USERNAME",
"value": "jonatan"
}
] | null |
[] |
package com.katmandu.katmandu;
import android.content.Intent;
import android.view.View;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.util.ActivityController;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* Created by jonatan on 11/05/15.
*/
@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class, emulateSdk = 21)
public class AccessActivityTest {
private ActivityController<AccessActivity> controller;
@Before
public void setup(){
controller = Robolectric.buildActivity(AccessActivity.class);
controller.get().passwordStore = mock(PasswordStore.class);
}
@Test
public void ifWrongPasswordThenShowMesage(){
testVisibility(true, View.VISIBLE);
verify(controller.get().passwordStore).delete(controller.get());
}
@Test
public void ifNoWrongPasswordThenHideMesage(){
testVisibility(false, View.GONE);
}
private void testVisibility(boolean wrongPasswdExtra, int visibility) {
controller.withIntent(new Intent().putExtra(AccessActivity.WRONG_PASSWORD, wrongPasswdExtra));
AccessActivity accessActivity = controller.create().resume().get();
assertEquals(visibility, accessActivity.findViewById(R.id.wrongPasswordTextView).getVisibility());
}
}
| 1,553 | 0.752093 | 0.746941 | 53 | 28.320755 | 27.855946 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.528302 | false | false |
3
|
25f27a68a8a442a29d0e702f14a6819d90c18728
| 26,834,955,684,023 |
cd829863b59d607cd36d927b85c8457d2c5255c7
|
/src/array/FindAPeakElement.java
|
671509a3dd79bc595eeea56216bebaaf22f2e635
|
[] |
no_license
|
howei/codingzone
|
https://github.com/howei/codingzone
|
0af2c43e95ee371add5e8d47510ecfb0734c8348
|
7139aa90c45acb22c49fec0fa419614cd346ae68
|
refs/heads/master
| 2020-06-02T08:23:54.125000 | 2015-02-10T06:05:01 | 2015-02-10T06:05:01 | 19,186,277 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package array;
public class FindAPeakElement {
public static void main(String[] args) {
int[] num = {3,4,3,2,1};
System.out.println(findPeakElement(num));
}
public static int findPeakElement(int[] num) {
if (num == null || num.length == 0) {
return -1;
}
if (num.length == 1) {
return 0;
}
if (num.length == 2) {
if (num[0] > num[1]) {
return 0;
} else {
return 1;
}
}
int low = 0;
int high = num.length - 1;
int mid = (low + high)/2;
while (high - low > 2) {
if (num[mid] > num[mid - 1] && num[mid] > num[mid + 1]) {
return mid;
} else if (num[mid] < num[mid - 1]) {
high = mid;
mid = (low + high)/2;
} else {
low = mid;
mid = (low + high)/2;
}
mid = (low + high)/2;
}
if (num[low] > num[low + 1]) {
return low;
} else if (num[high] > num[high - 1]) {
return high;
} else {
return low + 1;
}
}
}
|
UTF-8
|
Java
| 1,138 |
java
|
FindAPeakElement.java
|
Java
|
[] | null |
[] |
package array;
public class FindAPeakElement {
public static void main(String[] args) {
int[] num = {3,4,3,2,1};
System.out.println(findPeakElement(num));
}
public static int findPeakElement(int[] num) {
if (num == null || num.length == 0) {
return -1;
}
if (num.length == 1) {
return 0;
}
if (num.length == 2) {
if (num[0] > num[1]) {
return 0;
} else {
return 1;
}
}
int low = 0;
int high = num.length - 1;
int mid = (low + high)/2;
while (high - low > 2) {
if (num[mid] > num[mid - 1] && num[mid] > num[mid + 1]) {
return mid;
} else if (num[mid] < num[mid - 1]) {
high = mid;
mid = (low + high)/2;
} else {
low = mid;
mid = (low + high)/2;
}
mid = (low + high)/2;
}
if (num[low] > num[low + 1]) {
return low;
} else if (num[high] > num[high - 1]) {
return high;
} else {
return low + 1;
}
}
}
| 1,138 | 0.405097 | 0.381371 | 48 | 22.708334 | 14.588749 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.208333 | false | false |
3
|
dd9eca80c6d41b29387ef81534eb983e7988b2b5
| 15,590,731,295,935 |
09b6fbbf17b10f587dcabe729033b09948684117
|
/LunchList/src/edu/mines/csci498/ybakos/lunchlist/OnAlarmReceiver.java
|
2f530c639d7667530c75d94758cdaad001b00cf9
|
[] |
no_license
|
ybakos/csci498android
|
https://github.com/ybakos/csci498android
|
ce6679c2837cdf216421ea38d33239dc27108f9b
|
43353032d3a071ec3e3f92fdeea50645c01a6239
|
refs/heads/master
| 2021-01-01T20:01:16.139000 | 2013-01-03T20:58:14 | 2013-01-03T20:58:14 | 4,009,061 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package edu.mines.csci498.ybakos.lunchlist;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.RingtoneManager;
import android.net.Uri;
import android.preference.PreferenceManager;
public class OnAlarmReceiver extends BroadcastReceiver {
private static final int NOTIFY_ME_ID = 0;
@Override
public void onReceive(Context context, Intent intent) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
if (preferences.getBoolean("use_notification", true)) generateNotification(context);
else showAlarmActivity(context);
}
private void generateNotification(Context context) {
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, new Intent(context, AlarmActivity.class), 0);
NotificationManager manager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
// Uri uri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Notification notice = new Notification.Builder(context)
.setTicker("Time for a drink OMG squeeal!")
.setContentTitle(context.getString(R.string.alarmMessage))
.setSmallIcon(R.drawable.ic_popup_reminder)
.setContentText(context.getString(R.string.app_name))
// .setSound(uri)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND).getNotification();
manager.notify(NOTIFY_ME_ID, notice);
}
private void showAlarmActivity(Context context) {
Intent alarmIntent = new Intent(context, AlarmActivity.class);
alarmIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // Necessary when calling startActivity outside of an Activity.
context.startActivity(alarmIntent);
}
}
|
UTF-8
|
Java
| 1,924 |
java
|
OnAlarmReceiver.java
|
Java
|
[] | null |
[] |
package edu.mines.csci498.ybakos.lunchlist;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.RingtoneManager;
import android.net.Uri;
import android.preference.PreferenceManager;
public class OnAlarmReceiver extends BroadcastReceiver {
private static final int NOTIFY_ME_ID = 0;
@Override
public void onReceive(Context context, Intent intent) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
if (preferences.getBoolean("use_notification", true)) generateNotification(context);
else showAlarmActivity(context);
}
private void generateNotification(Context context) {
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, new Intent(context, AlarmActivity.class), 0);
NotificationManager manager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
// Uri uri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Notification notice = new Notification.Builder(context)
.setTicker("Time for a drink OMG squeeal!")
.setContentTitle(context.getString(R.string.alarmMessage))
.setSmallIcon(R.drawable.ic_popup_reminder)
.setContentText(context.getString(R.string.app_name))
// .setSound(uri)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND).getNotification();
manager.notify(NOTIFY_ME_ID, notice);
}
private void showAlarmActivity(Context context) {
Intent alarmIntent = new Intent(context, AlarmActivity.class);
alarmIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // Necessary when calling startActivity outside of an Activity.
context.startActivity(alarmIntent);
}
}
| 1,924 | 0.804054 | 0.800936 | 47 | 39.936169 | 31.482792 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.914894 | false | false |
3
|
dc2b57fa2380d9a78deeec2bfeca3c939d279739
| 12,309,376,271,520 |
7b18cd74419095eff35ef9c5a77e20b833d13800
|
/Supermercado/src/Modal.java
|
cccf1e0397c4143b661b006ba728a6bb355c6343
|
[] |
no_license
|
iarani5/Ejericicios-Java-parte-1
|
https://github.com/iarani5/Ejericicios-Java-parte-1
|
c7b77de2dbe8db5c731aa3ba091e0a4909690d75
|
62a2e5109bc13cb5bd088abaac081248f35faaab
|
refs/heads/master
| 2022-11-14T02:03:38.220000 | 2020-07-10T20:05:33 | 2020-07-10T20:05:33 | 278,720,772 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
public class Modal extends JFrame{
// ***** A T R I B U T O S ***** //
private static final long serialVersionUID = 1L;
JButton atras;
JButton adelante;
JButton calcular;
JTextField input_precio;
JTextField input_cantidad;
JTextField total_pagar;
DefaultListModel<String> dlm = new DefaultListModel<String>();
DefaultListModel<String> dlm2 = new DefaultListModel<String>();
JList<String> tInforme = new JList<String>(dlm);
JList<String> lPedido = new JList<String>();
JPanel p = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();
ArrayList <String> cTipoProductos;
Supermercado supermercado = new Supermercado();
// ***** M E T O D O S ***** //
public Modal() throws IOException, FileNotFoundException {
//estilos de la ventana
setTitle("Compra Virtual <Nizza>");
setSize(450,200);
p.setBackground(Color.pink);
p2.setBackground(Color.pink);
JScrollPane scrollPane1 = new JScrollPane(tInforme);
JScrollPane scrollPane2 = new JScrollPane(lPedido);
tInforme.setVisibleRowCount(5);
tInforme.setFixedCellHeight(12);
tInforme.setFixedCellWidth(100);
lPedido.setVisibleRowCount(5);
lPedido.setFixedCellHeight(12);
lPedido.setFixedCellWidth(100);
//BOTON ELIMINAR
atras = new JButton("<");
atras.setBackground(java.awt.Color.black);
atras.setForeground(java.awt.Color.pink);
atras.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
eliminar_item_seleccionado();
}
});
//BOTON INGRESAR
adelante = new JButton(">");
adelante.setBackground(java.awt.Color.black);
adelante.setForeground(java.awt.Color.pink);
adelante.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
cargar_item_seleccionado();
}
});
//BOTON CALCULAR
calcular = new JButton("Calcular");
calcular.setForeground(java.awt.Color.pink);
calcular.setBackground(java.awt.Color.black);
calcular.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
calcular_precio();
}
});
//INPUT $
JTextField input_precio_signo = new JTextField("$");
input_precio_signo.setEditable(false);
input_precio_signo.setPreferredSize( new Dimension( 20, 26 ) );
//INPUT PRECIO
input_precio = new JTextField("0.00");
input_precio.setEditable(false);
input_precio.setPreferredSize( new Dimension( 60, 26 ) );
//INPUT CANTIDAD
input_cantidad = new JTextField();
input_cantidad.setPreferredSize( new Dimension( 40, 25 ) );
//INPUT TOTAL A PAGAR
total_pagar = new JTextField("Total a pagar");
total_pagar.setEditable(false);
total_pagar.setPreferredSize( new Dimension( 200, 26 ) );
//SELECT TIPO PRODUCTO
JComboBox<String> lProductos = new JComboBox<String>();
cTipoProductos = new ArrayList<String>();
cTipoProductos.add(supermercado.un_super.get(0).tipo);
for(int i = 0; i < supermercado.un_super.size(); i++) {
boolean ya_existe = false;
for(int j=0;j<cTipoProductos.size();j++) {
if(cTipoProductos.get(j).equals(supermercado.un_super.get(i).tipo)) {
ya_existe = true;
}
}
if(!ya_existe) {
cTipoProductos.add(supermercado.un_super.get(i).tipo);
}
}
for(int j=0;j<cTipoProductos.size();j++) {
lProductos.addItem(cTipoProductos.get(j));
}
//Accion
lProductos.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
cargar_subitems(lProductos.getSelectedItem().toString());
}
});
//LIST SUBITEMS (por primera vez)
cargar_subitems(supermercado.un_super.get(0).tipo);
//APPEND DE ELEMENTOS
p.add(lProductos);
p.add(scrollPane1, BorderLayout.NORTH);
p2.add(adelante);
p2.add(atras);
p2.add(input_cantidad);
p2.setPreferredSize( new Dimension( 70, 95 ) );
p.add(p2);
p.add(scrollPane2, BorderLayout.NORTH);
p3.add(total_pagar);
p3.add(calcular);
p3.add(input_precio_signo);
p3.add(input_precio);
add(p,"North");
add(p3,"South");
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void cargar_subitems(String producto) {
dlm = new DefaultListModel<String>();
for(int i = 0; i < supermercado.un_super.size(); i++) {
if(producto.equals(supermercado.un_super.get(i).tipo)) {
dlm.addElement(supermercado.un_super.get(i).desc);
}
}
tInforme.setModel(dlm);
}
private void cargar_item_seleccionado() {
if(tInforme.getSelectedValue()!=null) {
for(int i=0;i<supermercado.un_super.size();i++) {
if(supermercado.un_super.get(i).desc.equals(tInforme.getSelectedValue())) {
int cant=0;
if(input_cantidad.getText().length()>0) {
try{
cant=Integer.parseInt(input_cantidad.getText());
}
catch(NumberFormatException e){
JOptionPane.showMessageDialog(null, "Error, debe ingresar solo numeros.");
}
}
else {
cant=1;
}
if(cant!=0) {
int num=supermercado.un_super.get(i).restar_cantidad(cant);
if(num<0) {
if((cant+num)==0) {
JOptionPane.showMessageDialog(null, "Ups! Ya no quedan unidades de "+supermercado.un_super.get(i).desc);
supermercado.un_super.get(i).sumar_cantidad(cant);
}
else {
supermercado.un_super.get(i).sumar_cantidad(cant);
JOptionPane.showMessageDialog(null, "Ups! Solo quedan " +(cant+num)+ " unidades de "+supermercado.un_super.get(i).desc);
}
}
else {
dlm2.addElement(supermercado.un_super.get(i).desc+":"+cant);
lPedido.setModel(dlm2);
}
}
}
}
}
lPedido.setModel(dlm2);
}
private void eliminar_item_seleccionado() {
int index = lPedido.getSelectedIndex();
if(index >= 0){
for(int i = 0; i < lPedido.getModel().getSize(); i++) {
if(index==i) {
lPedido.getModel().getElementAt(i);
String[] texto = lPedido.getModel().getElementAt(i).toString().split(":");
for(int j = 0; j < supermercado.un_super.size(); j++) {
if(texto[0].toString().equals(supermercado.un_super.get(j).desc)) {
supermercado.un_super.get(j).sumar_cantidad(Integer.parseInt(texto[1]));
}
}
}
}
dlm2.removeElementAt(index);
}
}
private void calcular_precio() {
double cantidad=0;
for(int i = 0; i < lPedido.getModel().getSize(); i++) {
String[] texto = lPedido.getModel().getElementAt(i).toString().split(":");
for(int j = 0; j < supermercado.un_super.size(); j++) {
if(texto[0].toString().equals(supermercado.un_super.get(j).desc)) {
cantidad+=supermercado.un_super.get(j).precio*Integer.parseInt(texto[1]);
}
}
}
if(cantidad>1000) {
input_precio.setBackground(java.awt.Color.red);
}
else{
input_precio.setBackground(java.awt.Color.green);
}
input_precio.setText(String.valueOf(new DecimalFormat("##.##").format(cantidad)));
}
}
|
UTF-8
|
Java
| 7,619 |
java
|
Modal.java
|
Java
|
[] | null |
[] |
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
public class Modal extends JFrame{
// ***** A T R I B U T O S ***** //
private static final long serialVersionUID = 1L;
JButton atras;
JButton adelante;
JButton calcular;
JTextField input_precio;
JTextField input_cantidad;
JTextField total_pagar;
DefaultListModel<String> dlm = new DefaultListModel<String>();
DefaultListModel<String> dlm2 = new DefaultListModel<String>();
JList<String> tInforme = new JList<String>(dlm);
JList<String> lPedido = new JList<String>();
JPanel p = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();
ArrayList <String> cTipoProductos;
Supermercado supermercado = new Supermercado();
// ***** M E T O D O S ***** //
public Modal() throws IOException, FileNotFoundException {
//estilos de la ventana
setTitle("Compra Virtual <Nizza>");
setSize(450,200);
p.setBackground(Color.pink);
p2.setBackground(Color.pink);
JScrollPane scrollPane1 = new JScrollPane(tInforme);
JScrollPane scrollPane2 = new JScrollPane(lPedido);
tInforme.setVisibleRowCount(5);
tInforme.setFixedCellHeight(12);
tInforme.setFixedCellWidth(100);
lPedido.setVisibleRowCount(5);
lPedido.setFixedCellHeight(12);
lPedido.setFixedCellWidth(100);
//BOTON ELIMINAR
atras = new JButton("<");
atras.setBackground(java.awt.Color.black);
atras.setForeground(java.awt.Color.pink);
atras.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
eliminar_item_seleccionado();
}
});
//BOTON INGRESAR
adelante = new JButton(">");
adelante.setBackground(java.awt.Color.black);
adelante.setForeground(java.awt.Color.pink);
adelante.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
cargar_item_seleccionado();
}
});
//BOTON CALCULAR
calcular = new JButton("Calcular");
calcular.setForeground(java.awt.Color.pink);
calcular.setBackground(java.awt.Color.black);
calcular.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
calcular_precio();
}
});
//INPUT $
JTextField input_precio_signo = new JTextField("$");
input_precio_signo.setEditable(false);
input_precio_signo.setPreferredSize( new Dimension( 20, 26 ) );
//INPUT PRECIO
input_precio = new JTextField("0.00");
input_precio.setEditable(false);
input_precio.setPreferredSize( new Dimension( 60, 26 ) );
//INPUT CANTIDAD
input_cantidad = new JTextField();
input_cantidad.setPreferredSize( new Dimension( 40, 25 ) );
//INPUT TOTAL A PAGAR
total_pagar = new JTextField("Total a pagar");
total_pagar.setEditable(false);
total_pagar.setPreferredSize( new Dimension( 200, 26 ) );
//SELECT TIPO PRODUCTO
JComboBox<String> lProductos = new JComboBox<String>();
cTipoProductos = new ArrayList<String>();
cTipoProductos.add(supermercado.un_super.get(0).tipo);
for(int i = 0; i < supermercado.un_super.size(); i++) {
boolean ya_existe = false;
for(int j=0;j<cTipoProductos.size();j++) {
if(cTipoProductos.get(j).equals(supermercado.un_super.get(i).tipo)) {
ya_existe = true;
}
}
if(!ya_existe) {
cTipoProductos.add(supermercado.un_super.get(i).tipo);
}
}
for(int j=0;j<cTipoProductos.size();j++) {
lProductos.addItem(cTipoProductos.get(j));
}
//Accion
lProductos.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
cargar_subitems(lProductos.getSelectedItem().toString());
}
});
//LIST SUBITEMS (por primera vez)
cargar_subitems(supermercado.un_super.get(0).tipo);
//APPEND DE ELEMENTOS
p.add(lProductos);
p.add(scrollPane1, BorderLayout.NORTH);
p2.add(adelante);
p2.add(atras);
p2.add(input_cantidad);
p2.setPreferredSize( new Dimension( 70, 95 ) );
p.add(p2);
p.add(scrollPane2, BorderLayout.NORTH);
p3.add(total_pagar);
p3.add(calcular);
p3.add(input_precio_signo);
p3.add(input_precio);
add(p,"North");
add(p3,"South");
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void cargar_subitems(String producto) {
dlm = new DefaultListModel<String>();
for(int i = 0; i < supermercado.un_super.size(); i++) {
if(producto.equals(supermercado.un_super.get(i).tipo)) {
dlm.addElement(supermercado.un_super.get(i).desc);
}
}
tInforme.setModel(dlm);
}
private void cargar_item_seleccionado() {
if(tInforme.getSelectedValue()!=null) {
for(int i=0;i<supermercado.un_super.size();i++) {
if(supermercado.un_super.get(i).desc.equals(tInforme.getSelectedValue())) {
int cant=0;
if(input_cantidad.getText().length()>0) {
try{
cant=Integer.parseInt(input_cantidad.getText());
}
catch(NumberFormatException e){
JOptionPane.showMessageDialog(null, "Error, debe ingresar solo numeros.");
}
}
else {
cant=1;
}
if(cant!=0) {
int num=supermercado.un_super.get(i).restar_cantidad(cant);
if(num<0) {
if((cant+num)==0) {
JOptionPane.showMessageDialog(null, "Ups! Ya no quedan unidades de "+supermercado.un_super.get(i).desc);
supermercado.un_super.get(i).sumar_cantidad(cant);
}
else {
supermercado.un_super.get(i).sumar_cantidad(cant);
JOptionPane.showMessageDialog(null, "Ups! Solo quedan " +(cant+num)+ " unidades de "+supermercado.un_super.get(i).desc);
}
}
else {
dlm2.addElement(supermercado.un_super.get(i).desc+":"+cant);
lPedido.setModel(dlm2);
}
}
}
}
}
lPedido.setModel(dlm2);
}
private void eliminar_item_seleccionado() {
int index = lPedido.getSelectedIndex();
if(index >= 0){
for(int i = 0; i < lPedido.getModel().getSize(); i++) {
if(index==i) {
lPedido.getModel().getElementAt(i);
String[] texto = lPedido.getModel().getElementAt(i).toString().split(":");
for(int j = 0; j < supermercado.un_super.size(); j++) {
if(texto[0].toString().equals(supermercado.un_super.get(j).desc)) {
supermercado.un_super.get(j).sumar_cantidad(Integer.parseInt(texto[1]));
}
}
}
}
dlm2.removeElementAt(index);
}
}
private void calcular_precio() {
double cantidad=0;
for(int i = 0; i < lPedido.getModel().getSize(); i++) {
String[] texto = lPedido.getModel().getElementAt(i).toString().split(":");
for(int j = 0; j < supermercado.un_super.size(); j++) {
if(texto[0].toString().equals(supermercado.un_super.get(j).desc)) {
cantidad+=supermercado.un_super.get(j).precio*Integer.parseInt(texto[1]);
}
}
}
if(cantidad>1000) {
input_precio.setBackground(java.awt.Color.red);
}
else{
input_precio.setBackground(java.awt.Color.green);
}
input_precio.setText(String.valueOf(new DecimalFormat("##.##").format(cantidad)));
}
}
| 7,619 | 0.62646 | 0.614254 | 235 | 30.204256 | 23.506649 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.944681 | false | false |
3
|
69ee796af52d6445e4c44d1ffcda9fb5fafe6a11
| 3,444,563,837,046 |
e6750574b1c0aca9ee0709acdea55c0edf4d31eb
|
/src/ro/redeul/google/go/compilation/GoCompilerOutputStreamParser.java
|
8c7e55ca3800c9f6c22956950e6e990531dd5672
|
[] |
no_license
|
LarryBattle/google-go-lang-idea-plugin
|
https://github.com/LarryBattle/google-go-lang-idea-plugin
|
2a15c10dec9e2d93ee62f3f0ce5589f4958101ca
|
b6b4e153bf2a5092eaabf7f985f1b136c38689f4
|
refs/heads/master
| 2021-01-15T10:59:13.744000 | 2013-12-05T07:46:09 | 2013-12-05T07:46:09 | 14,947,799 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package ro.redeul.google.go.compilation;
import com.intellij.openapi.compiler.CompilerMessageCategory;
import ro.redeul.google.go.util.ProcessUtil;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Author: Toader Mihai Claudiu <mtoader@gmail.com>
* <p/>
* Date: 8/21/11
* Time: 1:27 PM
*/
class GoCompilerOutputStreamParser implements ProcessUtil.StreamParser<List<CompilerMessage>> {
private final static Pattern pattern = Pattern.compile("([^:]+):(\\d+): ((?:(?:.)|(?:\\n(?!/)))+)", Pattern.UNIX_LINES);
private final String basePath;
public GoCompilerOutputStreamParser(String basePath) {
this.basePath = basePath;
}
public List<CompilerMessage> parseStream(String data) {
List<CompilerMessage> messages = new ArrayList<CompilerMessage>();
Matcher matcher = pattern.matcher(data);
if (matcher.find()) {
String filename = matcher.group(1);
String url = CompilationTaskWorker.generateFileUrl(basePath, filename);
messages.add(new CompilerMessage(CompilerMessageCategory.ERROR, matcher.group(3), url, Integer.parseInt(matcher.group(2)), -1));
} else {
messages.add(new CompilerMessage(CompilerMessageCategory.WARNING, data, null, -1, -1));
}
return messages;
}
}
|
UTF-8
|
Java
| 1,372 |
java
|
GoCompilerOutputStreamParser.java
|
Java
|
[
{
"context": "er;\nimport java.util.regex.Pattern;\n\n/**\n* Author: Toader Mihai Claudiu <mtoader@gmail.com>\n* <p/>\n* Date: 8/21/11\n* Time",
"end": 300,
"score": 0.9998707175254822,
"start": 280,
"tag": "NAME",
"value": "Toader Mihai Claudiu"
},
{
"context": "gex.Pattern;\n\n/**\n* Author: Toader Mihai Claudiu <mtoader@gmail.com>\n* <p/>\n* Date: 8/21/11\n* Time: 1:27 PM\n*/\nclass ",
"end": 319,
"score": 0.9999319911003113,
"start": 302,
"tag": "EMAIL",
"value": "mtoader@gmail.com"
}
] | null |
[] |
package ro.redeul.google.go.compilation;
import com.intellij.openapi.compiler.CompilerMessageCategory;
import ro.redeul.google.go.util.ProcessUtil;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Author: <NAME> <<EMAIL>>
* <p/>
* Date: 8/21/11
* Time: 1:27 PM
*/
class GoCompilerOutputStreamParser implements ProcessUtil.StreamParser<List<CompilerMessage>> {
private final static Pattern pattern = Pattern.compile("([^:]+):(\\d+): ((?:(?:.)|(?:\\n(?!/)))+)", Pattern.UNIX_LINES);
private final String basePath;
public GoCompilerOutputStreamParser(String basePath) {
this.basePath = basePath;
}
public List<CompilerMessage> parseStream(String data) {
List<CompilerMessage> messages = new ArrayList<CompilerMessage>();
Matcher matcher = pattern.matcher(data);
if (matcher.find()) {
String filename = matcher.group(1);
String url = CompilationTaskWorker.generateFileUrl(basePath, filename);
messages.add(new CompilerMessage(CompilerMessageCategory.ERROR, matcher.group(3), url, Integer.parseInt(matcher.group(2)), -1));
} else {
messages.add(new CompilerMessage(CompilerMessageCategory.WARNING, data, null, -1, -1));
}
return messages;
}
}
| 1,348 | 0.686589 | 0.676385 | 42 | 31.666666 | 35.472771 | 140 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false |
3
|
dd69505d5caf0f14862966e478b67e85ce617717
| 16,776,142,259,606 |
1c363d26d61c0047bbb54d57abc594a75c220172
|
/EasyGreenCampus_V2/src/main/java/fr/igs/easygreencampus/security/UserDetailsAdapter.java
|
94a5daa66e5c83bd721206d38066887986ee774e
|
[] |
no_license
|
CfrancCyrille/egc
|
https://github.com/CfrancCyrille/egc
|
ac62cad66a251fd8b014e1e8846b704b89f6f00e
|
6d6197c02d48eacf1023352f3cb7446bf5214e04
|
refs/heads/master
| 2020-12-26T02:50:01.375000 | 2014-04-01T08:26:10 | 2014-04-01T08:26:10 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package fr.igs.easygreencampus.security;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import fr.igs.easygreencampus.model.Personne;
import fr.igs.easygreencampus.model.Role;
/**
*
* @author deborahlivet
*
* Classe permettant de mapper la classe personne vers la classe
* userDetails de spring
*/
public class UserDetailsAdapter implements UserDetails {
private Personne personne;
private String password;
public UserDetailsAdapter(Personne personne) {
this.setPersonne(personne);
}
public Personne getPersonne() {
return personne;
}
public void setPersonne(Personne personne) {
this.personne = personne;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
for (Role role : personne.getRoles()){
authorities.add(new GrantedAuthorityImpl(role.getNomRole()));
}
return authorities;
}
@Override
public String getUsername() {
// le userName utilisé comme login correspond à l'email de la personne
return personne.getMail();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
|
UTF-8
|
Java
| 1,721 |
java
|
UserDetailsAdapter.java
|
Java
|
[
{
"context": "gs.easygreencampus.model.Role;\n\n/**\n * \n * @author deborahlivet\n * \n * Classe permettant de mapper la cla",
"end": 439,
"score": 0.9995169639587402,
"start": 427,
"tag": "USERNAME",
"value": "deborahlivet"
},
{
"context": "d setPassword(String password) {\n\t\tthis.password = password;\n\t}\n\n\t@Override\n\tpublic Collection<? extends Gran",
"end": 1006,
"score": 0.7193574905395508,
"start": 998,
"tag": "PASSWORD",
"value": "password"
}
] | null |
[] |
package fr.igs.easygreencampus.security;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import fr.igs.easygreencampus.model.Personne;
import fr.igs.easygreencampus.model.Role;
/**
*
* @author deborahlivet
*
* Classe permettant de mapper la classe personne vers la classe
* userDetails de spring
*/
public class UserDetailsAdapter implements UserDetails {
private Personne personne;
private String password;
public UserDetailsAdapter(Personne personne) {
this.setPersonne(personne);
}
public Personne getPersonne() {
return personne;
}
public void setPersonne(Personne personne) {
this.personne = personne;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
for (Role role : personne.getRoles()){
authorities.add(new GrantedAuthorityImpl(role.getNomRole()));
}
return authorities;
}
@Override
public String getUsername() {
// le userName utilisé comme login correspond à l'email de la personne
return personne.getMail();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
| 1,723 | 0.752182 | 0.752182 | 80 | 20.487499 | 21.734186 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.0875 | false | false |
3
|
e4250f4b012f29bf06df6e630cf6d7e40cfa379c
| 39,161,511,829,176 |
6e7f5448cc6a70654be2f6eb99dddac661f8a99a
|
/ecom-goods/src/main/java/com/service/impl/CommentsServiceImpl.java
|
2032f69e3ff2c1345088f84be003f23550bdcae5
|
[] |
no_license
|
hnluke/ecommerce
|
https://github.com/hnluke/ecommerce
|
7121ebee7aea75f81149a67fa18acb1138e14273
|
31563c7d727caf30c0e5da3629c498a5ac9069e8
|
refs/heads/master
| 2022-12-12T21:11:23.425000 | 2020-08-30T02:11:25 | 2020-08-30T02:11:25 | 291,382,370 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.service.impl;
import com.mapper.CommentsMapper;
import com.mapper.UnionMapper;
import com.model.Comments;
import com.service.ICommentsService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class CommentsServiceImpl implements ICommentsService {
@Resource
CommentsMapper commentsMapper;
@Resource
UnionMapper unionMapper;
// 新增评论
@Override
public boolean insertComment(Comments comments) {
return commentsMapper.insertComment(comments);
}
// 查询评论
@Override
public List<Comments> findCommentById(Integer commId) {
return commentsMapper.findCommentById(commId);
}
@Override
public List<Comments> findCommentUnionById(Integer commId) {
return unionMapper.queryCommentByGoodId(commId);
}
}
|
UTF-8
|
Java
| 876 |
java
|
CommentsServiceImpl.java
|
Java
|
[] | null |
[] |
package com.service.impl;
import com.mapper.CommentsMapper;
import com.mapper.UnionMapper;
import com.model.Comments;
import com.service.ICommentsService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class CommentsServiceImpl implements ICommentsService {
@Resource
CommentsMapper commentsMapper;
@Resource
UnionMapper unionMapper;
// 新增评论
@Override
public boolean insertComment(Comments comments) {
return commentsMapper.insertComment(comments);
}
// 查询评论
@Override
public List<Comments> findCommentById(Integer commId) {
return commentsMapper.findCommentById(commId);
}
@Override
public List<Comments> findCommentUnionById(Integer commId) {
return unionMapper.queryCommentByGoodId(commId);
}
}
| 876 | 0.747674 | 0.747674 | 34 | 24.294117 | 20.703125 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.382353 | false | false |
3
|
c527ddcc7269f249ae0e70ef275738ca9920fa12
| 39,221,641,356,199 |
4efbda06537d8899b9f92d566ee711d4551b3200
|
/Stefan/src/com/stefanmuenchow/battleship/field/Tile.java
|
fc2e0b09c64dd301b65f6f455c4fce20e38cc2b4
|
[] |
no_license
|
stefanmuenchow/Battleship
|
https://github.com/stefanmuenchow/Battleship
|
fc1976d7c682289982573f939d714f416c4f0b70
|
e0b21fdcf0dd48f74da7d37b2af356741721d26d
|
refs/heads/master
| 2020-05-20T01:17:53.813000 | 2013-12-19T13:33:28 | 2013-12-19T13:33:28 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.stefanmuenchow.battleship.field;
public class Tile {
private final Coordinate coordinate;
private ETileState state;
public Tile(Coordinate coordinate) {
this.coordinate = coordinate;
this.state = ETileState.Unknown;
}
public Coordinate getCoordinate() {
return coordinate;
}
public ETileState getState() {
return state;
}
public void setState(final ETileState state) {
this.state = state;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((coordinate == null) ? 0 : coordinate.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Tile other = (Tile) obj;
if (coordinate == null) {
if (other.coordinate != null)
return false;
} else if (!coordinate.equals(other.coordinate))
return false;
return true;
}
@Override
public String toString() {
return "(" + getCoordinate() + "; " + getState() + ")";
}
}
|
UTF-8
|
Java
| 1,086 |
java
|
Tile.java
|
Java
|
[] | null |
[] |
package com.stefanmuenchow.battleship.field;
public class Tile {
private final Coordinate coordinate;
private ETileState state;
public Tile(Coordinate coordinate) {
this.coordinate = coordinate;
this.state = ETileState.Unknown;
}
public Coordinate getCoordinate() {
return coordinate;
}
public ETileState getState() {
return state;
}
public void setState(final ETileState state) {
this.state = state;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((coordinate == null) ? 0 : coordinate.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Tile other = (Tile) obj;
if (coordinate == null) {
if (other.coordinate != null)
return false;
} else if (!coordinate.equals(other.coordinate))
return false;
return true;
}
@Override
public String toString() {
return "(" + getCoordinate() + "; " + getState() + ")";
}
}
| 1,086 | 0.6593 | 0.655617 | 55 | 18.745455 | 15.635878 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.872727 | false | false |
3
|
c9e4648c84343c152557ad28048142b3b56f6084
| 32,641,751,508,728 |
722388d3625c3f7cc6ec072910da4648299856d3
|
/HackerRank/ModifiedKaprekarNumbers.java
|
935e57d176ada9f90dcd6909375013646425f7b4
|
[] |
no_license
|
activesince93/JAVA-Problems
|
https://github.com/activesince93/JAVA-Problems
|
dcfffaf489983fb2c3d291798942ba7ab5094568
|
1fbcac7ab46de7300809f00e28a8ce9b32d1d459
|
refs/heads/master
| 2021-01-02T08:46:35.854000 | 2020-10-15T05:00:20 | 2020-10-15T05:00:20 | 41,656,133 | 1 | 0 | null | false | 2020-10-15T05:00:22 | 2015-08-31T04:41:15 | 2020-10-06T09:02:20 | 2020-10-15T05:00:22 | 61 | 1 | 0 | 0 |
Java
| false | false |
package HackerRank;
import java.util.Scanner;
public class ModifiedKaprekarNumbers {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
long start = sc.nextInt();
long end = sc.nextInt();
long count = 0;
for(long i = start; i <= end; i++) {
if(isKaprekarNumber(i)) {
System.out.print(i + " ");
count ++;
}
}
if(count == 0) {
System.out.print("INVALID RANGE");
}
}
private static boolean isKaprekarNumber(long i) {
// TODO Auto-generated method stub
String squareString = String.valueOf(i * i);
if(Long.parseLong(squareString) != i) {
if(squareString.length() > 1) {
long firstPart = Long.parseLong(squareString.substring(0, squareString.length()/2));
long secondpart = Long.parseLong(squareString.substring(squareString.length()/2, squareString.length()));
if(firstPart + secondpart == i) {
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return true;
}
}
}
|
UTF-8
|
Java
| 1,005 |
java
|
ModifiedKaprekarNumbers.java
|
Java
|
[] | null |
[] |
package HackerRank;
import java.util.Scanner;
public class ModifiedKaprekarNumbers {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
long start = sc.nextInt();
long end = sc.nextInt();
long count = 0;
for(long i = start; i <= end; i++) {
if(isKaprekarNumber(i)) {
System.out.print(i + " ");
count ++;
}
}
if(count == 0) {
System.out.print("INVALID RANGE");
}
}
private static boolean isKaprekarNumber(long i) {
// TODO Auto-generated method stub
String squareString = String.valueOf(i * i);
if(Long.parseLong(squareString) != i) {
if(squareString.length() > 1) {
long firstPart = Long.parseLong(squareString.substring(0, squareString.length()/2));
long secondpart = Long.parseLong(squareString.substring(squareString.length()/2, squareString.length()));
if(firstPart + secondpart == i) {
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return true;
}
}
}
| 1,005 | 0.638806 | 0.632836 | 41 | 23.512196 | 22.608137 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.756098 | false | false |
3
|
a06049207415e85fc94e3463f9cdec59f2670f08
| 2,113,123,941,726 |
ed5159d056e98d6715357d0d14a9b3f20b764f89
|
/src/irvine/oeis/a164/A164532.java
|
24ba0f5f28eb577265ad3f692e9cbba468149279
|
[] |
no_license
|
flywind2/joeis
|
https://github.com/flywind2/joeis
|
c5753169cf562939b04dd246f8a2958e97f74558
|
e5efd6971a0062ac99f4fae21a7c78c9f9e74fea
|
refs/heads/master
| 2020-09-13T18:34:35.080000 | 2019-11-19T05:40:55 | 2019-11-19T05:40:55 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package irvine.oeis.a164;
import irvine.oeis.LinearRecurrence;
/**
* A164532 <code>a(n) = 6*a(n-2)</code> for <code>n > 2; a(1) = 1, a(2) = 4</code>.
* @author Sean A. Irvine
*/
public class A164532 extends LinearRecurrence {
/** Construct the sequence. */
public A164532() {
super(new long[] {6, 0}, new long[] {1, 4});
}
}
|
UTF-8
|
Java
| 344 |
java
|
A164532.java
|
Java
|
[
{
"context": "de>n > 2; a(1) = 1, a(2) = 4</code>.\n * @author Sean A. Irvine\n */\npublic class A164532 extends LinearRecurrence",
"end": 181,
"score": 0.9998885989189148,
"start": 167,
"tag": "NAME",
"value": "Sean A. Irvine"
}
] | null |
[] |
package irvine.oeis.a164;
import irvine.oeis.LinearRecurrence;
/**
* A164532 <code>a(n) = 6*a(n-2)</code> for <code>n > 2; a(1) = 1, a(2) = 4</code>.
* @author <NAME>
*/
public class A164532 extends LinearRecurrence {
/** Construct the sequence. */
public A164532() {
super(new long[] {6, 0}, new long[] {1, 4});
}
}
| 336 | 0.607558 | 0.514535 | 15 | 21.933332 | 24.070637 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false |
3
|
a3eea0be8c5adfa2f92683712e19c6d3cc7290fe
| 21,345,987,525,866 |
d2ce8528d79892fc7cdd2dcca20cb909e46a48d9
|
/src/main/java/com/euromoby/mail/command/SmtpCommandBase.java
|
ab5fcbb27154ad1fcd02f69fdaba8433f503899c
|
[] |
no_license
|
Lameaux/agent
|
https://github.com/Lameaux/agent
|
a429e768b93f9754b75b0613a2f773906a031f46
|
56f338bdda7c29de03e127982ed9441a6783732c
|
refs/heads/master
| 2016-09-05T16:31:19.697000 | 2015-05-13T13:56:19 | 2015-05-13T13:56:19 | 31,919,779 | 3 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.euromoby.mail.command;
import com.euromoby.mail.MailSession;
import com.euromoby.mail.util.DSNStatus;
import com.euromoby.model.Tuple;
import com.euromoby.utils.StringUtils;
public abstract class SmtpCommandBase implements SmtpCommand {
@Override
public abstract String name();
@Override
public String execute(MailSession mailSession, Tuple<String, String> request) {
return "502 " + DSNStatus.getStatus(DSNStatus.PERMANENT, DSNStatus.SYSTEM_NOT_CAPABLE) + " Command is not supported";
}
@Override
public boolean match(Tuple<String, String> request) {
if (StringUtils.nullOrEmpty(request.getFirst())) {
return false;
}
return name().equalsIgnoreCase(request.getFirst());
}
}
|
UTF-8
|
Java
| 712 |
java
|
SmtpCommandBase.java
|
Java
|
[] | null |
[] |
package com.euromoby.mail.command;
import com.euromoby.mail.MailSession;
import com.euromoby.mail.util.DSNStatus;
import com.euromoby.model.Tuple;
import com.euromoby.utils.StringUtils;
public abstract class SmtpCommandBase implements SmtpCommand {
@Override
public abstract String name();
@Override
public String execute(MailSession mailSession, Tuple<String, String> request) {
return "502 " + DSNStatus.getStatus(DSNStatus.PERMANENT, DSNStatus.SYSTEM_NOT_CAPABLE) + " Command is not supported";
}
@Override
public boolean match(Tuple<String, String> request) {
if (StringUtils.nullOrEmpty(request.getFirst())) {
return false;
}
return name().equalsIgnoreCase(request.getFirst());
}
}
| 712 | 0.768258 | 0.764045 | 26 | 26.384615 | 29.653223 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.230769 | false | false |
3
|
8f14a82a06671e6b3dbf0f5e6c5d381a7e18ee8f
| 16,054,587,755,140 |
04895a7240e8b279287b7169e52fa63753ab1256
|
/Java/src/pkg17bce7066/Multi2.java
|
39f0760d2a41b83df650a11c4f1970f710f37d25
|
[] |
no_license
|
adityajain17/College-Stuff
|
https://github.com/adityajain17/College-Stuff
|
40206d5bb5fdf74a1ff4b8e57a60e56d75f96706
|
dd7ff4b48c5c373228ffa4fff2cd1308589058b2
|
refs/heads/master
| 2020-05-21T01:07:09.242000 | 2019-05-09T18:35:11 | 2019-05-09T18:35:11 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pkg17bce7066;
/**
*
* @author User
*/
class X extends Thread
{
synchronized public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println(Thread.currentThread().getName()+" "+i);
}
}
}
public class Multi2
{
public static void main(String[] args) throws InterruptedException
{
X t1=new X();
X t2=new X();
System.out.println(t1.getName()+" ID: "+t1.getId());
System.out.println(t2.getName()+" ID: "+t2.getId());
t1.start();
t1.join();
X.yield();
t2.start();
}
}
|
UTF-8
|
Java
| 821 |
java
|
Multi2.java
|
Java
|
[
{
"context": "\n */\r\npackage pkg17bce7066;\r\n\r\n/**\r\n *\r\n * @author User\r\n */\r\nclass X extends Thread \r\n{\r\n synchronize",
"end": 239,
"score": 0.6826827526092529,
"start": 235,
"tag": "NAME",
"value": "User"
}
] | 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 pkg17bce7066;
/**
*
* @author User
*/
class X extends Thread
{
synchronized public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println(Thread.currentThread().getName()+" "+i);
}
}
}
public class Multi2
{
public static void main(String[] args) throws InterruptedException
{
X t1=new X();
X t2=new X();
System.out.println(t1.getName()+" ID: "+t1.getId());
System.out.println(t2.getName()+" ID: "+t2.getId());
t1.start();
t1.join();
X.yield();
t2.start();
}
}
| 821 | 0.542022 | 0.520097 | 35 | 21.457144 | 22.969971 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false |
3
|
90273e7ed6da1768511a6b56f434489df452598e
| 28,252,294,938,555 |
f484a8253cb803cf754c26ff7c2478c41234d46c
|
/LastFmScraper/src/main/java/net/mylesputnam/lastfm/scraper/db/requests/update/DbUpdateRequest.java
|
dd8b45209be5f61fd4a94aa7ac0865966b1f76d6
|
[] |
no_license
|
mylesmyles/lastfmscraper
|
https://github.com/mylesmyles/lastfmscraper
|
bf50a2fd3dccf9068d411a0315b70183cdada12e
|
bf5ea73642105a73011ff1b847c11dadaf50f8d6
|
refs/heads/master
| 2021-09-01T17:36:28.048000 | 2017-12-28T03:33:30 | 2017-12-28T03:33:30 | 107,864,704 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package net.mylesputnam.lastfm.scraper.db.requests.update;
import java.sql.Connection;
import java.sql.SQLException;
public interface DbUpdateRequest {
public void makeUpdateRequest(Connection connection) throws SQLException;
}
|
UTF-8
|
Java
| 231 |
java
|
DbUpdateRequest.java
|
Java
|
[] | null |
[] |
package net.mylesputnam.lastfm.scraper.db.requests.update;
import java.sql.Connection;
import java.sql.SQLException;
public interface DbUpdateRequest {
public void makeUpdateRequest(Connection connection) throws SQLException;
}
| 231 | 0.835498 | 0.835498 | 8 | 27.875 | 25.862316 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.625 | false | false |
3
|
303eda24b1dd1c4c7fd1709da5e07f554c214104
| 25,271,587,597,879 |
40d1f88a511ea80936a0d69083f0f43d96cec7bd
|
/app/src/main/java/com/ypc/accelerometer/currentPara.java
|
af98c32e511a6ab6f6f10aa3a9cf410767a10179
|
[] |
no_license
|
yangpeicheng/accData
|
https://github.com/yangpeicheng/accData
|
1110a861a05e077a011165f4c287863f0ad36924
|
8ed41ae4dc0ef76576c8f739a0e02656ba870dbc
|
refs/heads/master
| 2021-01-11T10:47:04.103000 | 2016-11-05T11:02:38 | 2016-11-05T11:02:38 | 72,913,395 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.ypc.accelerometer;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.opengl.Matrix;
import android.os.Environment;
import android.provider.Settings;
import android.support.v4.widget.TextViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.LineGraphSeries;
import org.w3c.dom.Text;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
public class currentPara extends AppCompatActivity implements SensorEventListener{
private SensorManager sm;
private Sensor sensor_Acc;
private Sensor sensor_Magn;
private Button button;
public LineGraphSeries<DataPoint> series1,series2,series3;
public LineGraphSeries<DataPoint> series6,series4,series5,series7;
private final int LENGTH=5;
TextView biasX;
TextView biasY;
TextView biasZ;
private float[] gravity = new float[3];
private float[] linear_acceleration = new float[3];
private float[] magneticValue=null;
final float alpha = 0.8f;
int count1=0;
int count2=0;
GraphView graph1;
GraphView graph2;
GraphView graph3;
public float [] tempX=new float[LENGTH];
public float [] tempY=new float[LENGTH];
public float [] tempZ=new float[LENGTH];
float[] smoothAcc=new float[3];
float magnitude;
float[] bias=new float[3];
DataBaseHelper AccDb;
Thread dBthread;
boolean stopFlag;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_current_para);
sm=(SensorManager)getSystemService(SENSOR_SERVICE);
sensor_Acc=sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensor_Magn=sm.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
button=(Button)findViewById(R.id.pause);
biasX=(TextView)findViewById(R.id.biasX);
biasY=(TextView)findViewById(R.id.biasY);
biasZ=(TextView)findViewById(R.id.biasZ);
try{
getBias(bias);
}
catch (IOException e){}
biasX.setText(String.valueOf(bias[0]));
biasY.setText(String.valueOf(bias[1]));
biasZ.setText(String.valueOf(bias[2]));
graph1=(GraphView)findViewById(R.id.view1);
graph2=(GraphView)findViewById(R.id.view2);
graph3=(GraphView)findViewById(R.id.view3);
graph1.getViewport().setScalable(true);
graph1.getViewport().setScrollable(true);
graph1.getViewport().setScalableY(true);
graph1.getViewport().setScrollableY(true);
graph1.getViewport().setYAxisBoundsManual(true);
graph1.getViewport().setMinY(-10);
graph1.getViewport().setMaxY(10);
graph1.getViewport().setXAxisBoundsManual(true);
graph1.getViewport().setMinX(200);
graph1.getViewport().setMaxX(500);
graph1.getGridLabelRenderer().setHorizontalAxisTitle("count");
series1=new LineGraphSeries<DataPoint>();
series2=new LineGraphSeries<DataPoint>();
series3=new LineGraphSeries<DataPoint>();
series1.setColor(Color.GREEN);
series1.setTitle("linear_X");
series2.setColor(Color.BLUE);
series2.setTitle("linear_Y");
series3.setColor(Color.RED);
series3.setTitle("linear_Z");
series4=new LineGraphSeries<DataPoint>();
series5=new LineGraphSeries<DataPoint>();
series6=new LineGraphSeries<DataPoint>();
series4.setColor(Color.GREEN);
series4.setTitle("linear_X");
series5.setColor(Color.BLUE);
series5.setTitle("linear_Y");
series6.setColor(Color.RED);
series6.setTitle("linear_Z");
graph1.addSeries(series1);
graph1.addSeries(series2);
graph1.addSeries(series3);
graph2.getViewport().setScalable(true);
graph2.getViewport().setScrollable(true);
graph2.getViewport().setScalableY(true);
graph2.getViewport().setScrollableY(true);
graph2.getViewport().setYAxisBoundsManual(true);
graph2.getViewport().setMinY(-10);
graph2.getViewport().setMaxY(10);
graph2.getViewport().setXAxisBoundsManual(true);
graph2.getViewport().setMinX(200);
graph2.getViewport().setMaxX(500);
graph2.getGridLabelRenderer().setHorizontalAxisTitle("count");
graph2.addSeries(series4);
graph2.addSeries(series5);
graph2.addSeries(series6);
series7=new LineGraphSeries<DataPoint>();
series7.setColor(Color.GREEN);
graph3.getViewport().setScalable(true);
graph3.getViewport().setScrollable(true);
graph3.getViewport().setScalableY(true);
graph3.getViewport().setScrollableY(true);
graph3.getViewport().setYAxisBoundsManual(true);
graph3.getViewport().setMinY(-10);
graph3.getViewport().setMaxY(10);
graph3.getViewport().setXAxisBoundsManual(true);
graph3.getViewport().setMinX(200);
graph3.getViewport().setMaxX(500);
graph3.getGridLabelRenderer().setHorizontalAxisTitle("count");
graph3.addSeries(series7);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sm.unregisterListener(currentPara.this);
}
});
}
@Override
public void onSensorChanged(SensorEvent event) {
if(event.sensor.getType()==Sensor.TYPE_ACCELEROMETER) {
gravity[0] = alpha * gravity[0] + (1 - alpha) * event.values[0];
gravity[1] = alpha * gravity[1] + (1 - alpha) * event.values[1];
gravity[2] = alpha * gravity[2] + (1 - alpha) * event.values[2];
linear_acceleration[0] = event.values[0] - gravity[0]-bias[0];
linear_acceleration[1] = event.values[1] - gravity[1]-bias[1];
linear_acceleration[2] = event.values[2] - gravity[2]-bias[2];
int index = count2 % LENGTH;
tempX[index] = linear_acceleration[0];
tempY[index] = linear_acceleration[1];
tempZ[index] = linear_acceleration[2];
smoothAcc[0] = SensorUtil.realTimeSmooth(tempX);
smoothAcc[1] = SensorUtil.realTimeSmooth(tempY);
smoothAcc[2] = SensorUtil.realTimeSmooth(tempZ);
series4.appendData(new DataPoint(count2, smoothAcc[0]), true, 500);
series5.appendData(new DataPoint(count2, smoothAcc[1]), true, 500);
series6.appendData(new DataPoint(count2, smoothAcc[2]), true, 500);
magnitude= (float) Math.sqrt(smoothAcc[0]*smoothAcc[0]+smoothAcc[1]*smoothAcc[1]+smoothAcc[2]*smoothAcc[2]);
if(magnitude<0.5)
magnitude=0;
series7.appendData(new DataPoint(count2++, magnitude),true,500);
if(magneticValue!=null) {
float[] R = new float[9], I = new float[9], earthAcc = new float[3];
SensorManager.getRotationMatrix(R, I, gravity, magneticValue);
// android.opengl.Matrix.transposeM(t, 0, R, 0);
// android.opengl.Matrix.invertM(inv, 0, t, 0);
//android.opengl.Matrix.multiplyMV(earthAcc, 0, R, 0, smoothAcc, 0);
earthAcc[0]=R[0]*smoothAcc[0]+R[1]*smoothAcc[1]+R[2]*smoothAcc[2];
earthAcc[1]=R[3]*smoothAcc[0]+R[4]*smoothAcc[1]+R[5]*smoothAcc[2];
earthAcc[2]=R[6]*smoothAcc[0]+R[7]*smoothAcc[1]+R[8]*smoothAcc[2];
series1.appendData(new DataPoint(count1, earthAcc[0]), true, 500);
series2.appendData(new DataPoint(count1, earthAcc[1]), true, 500);
series3.appendData(new DataPoint(count1++, earthAcc[2]), true, 500);
//linearX.setText(String.valueOf(earthAcc[0]));
//linearY.setText(String.valueOf(earthAcc[1]));
//linearZ.setText(String.valueOf(earthAcc[2]));
}
}
if(event.sensor.getType()==Sensor.TYPE_MAGNETIC_FIELD){
magneticValue=event.values;
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
@Override
public void onResume(){
super.onResume();
stopFlag=false;
AccDb=new DataBaseHelper(this);
if(dBthread==null) {
dBthread = new Thread(new DBthread());
dBthread.start();
}
Toast.makeText(this,AccDb.SQL_CREATE_ACC,Toast.LENGTH_SHORT).show();
sm.registerListener(currentPara.this,sensor_Acc,SensorManager.SENSOR_DELAY_GAME);
sm.registerListener(currentPara.this,sensor_Magn,SensorManager.SENSOR_DELAY_GAME);
}
@Override
public void onPause(){
super.onPause();
stopFlag=true;
sm.unregisterListener(this);
//dBthread.stop();
AccDb.close();
}
@Override
protected void onDestroy() {
super.onDestroy();
stopFlag=true;
sm.unregisterListener(this);
//dBthread.stop();
AccDb.close();
}
public void getBias(float [] bias) throws FileNotFoundException {
bias[0]=0;
bias[1]=0;
bias[2]=0;
int count=0;
File sdcard=Environment.getExternalStorageDirectory();
File inurl = new File (sdcard.getAbsolutePath() + "/SensorData/acc.txt");
try {
InputStreamReader isr = new InputStreamReader(new FileInputStream(inurl), "UTF-8");
BufferedReader br=new BufferedReader(isr);
String str=null;
String[] temp;
while((str=br.readLine())!=null){
temp=str.split(",");
for(int i=0;i<temp.length;i++){
bias[i]+=Float.parseFloat(temp[i]);
}
count++;
}
Log.d("bias",String.valueOf(bias[0]));
Log.d("bias",String.valueOf(bias[1]));
Log.d("bias",String.valueOf(bias[2]));
}
catch (IOException e){
Log.e("bias",e.toString());
}
for(float f:bias){
f /= count;
//Log.d("bias",String.valueOf(f));
}
}
public class DBthread implements Runnable{
int count=0;
@Override
public void run() {
if (!stopFlag&&count != count2) {
count=count2;
AccDb.insertAccData(smoothAcc[0], smoothAcc[1], smoothAcc[2], magnitude);
}
}
}
}
|
UTF-8
|
Java
| 10,948 |
java
|
currentPara.java
|
Java
|
[] | null |
[] |
package com.ypc.accelerometer;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.opengl.Matrix;
import android.os.Environment;
import android.provider.Settings;
import android.support.v4.widget.TextViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.LineGraphSeries;
import org.w3c.dom.Text;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
public class currentPara extends AppCompatActivity implements SensorEventListener{
private SensorManager sm;
private Sensor sensor_Acc;
private Sensor sensor_Magn;
private Button button;
public LineGraphSeries<DataPoint> series1,series2,series3;
public LineGraphSeries<DataPoint> series6,series4,series5,series7;
private final int LENGTH=5;
TextView biasX;
TextView biasY;
TextView biasZ;
private float[] gravity = new float[3];
private float[] linear_acceleration = new float[3];
private float[] magneticValue=null;
final float alpha = 0.8f;
int count1=0;
int count2=0;
GraphView graph1;
GraphView graph2;
GraphView graph3;
public float [] tempX=new float[LENGTH];
public float [] tempY=new float[LENGTH];
public float [] tempZ=new float[LENGTH];
float[] smoothAcc=new float[3];
float magnitude;
float[] bias=new float[3];
DataBaseHelper AccDb;
Thread dBthread;
boolean stopFlag;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_current_para);
sm=(SensorManager)getSystemService(SENSOR_SERVICE);
sensor_Acc=sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensor_Magn=sm.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
button=(Button)findViewById(R.id.pause);
biasX=(TextView)findViewById(R.id.biasX);
biasY=(TextView)findViewById(R.id.biasY);
biasZ=(TextView)findViewById(R.id.biasZ);
try{
getBias(bias);
}
catch (IOException e){}
biasX.setText(String.valueOf(bias[0]));
biasY.setText(String.valueOf(bias[1]));
biasZ.setText(String.valueOf(bias[2]));
graph1=(GraphView)findViewById(R.id.view1);
graph2=(GraphView)findViewById(R.id.view2);
graph3=(GraphView)findViewById(R.id.view3);
graph1.getViewport().setScalable(true);
graph1.getViewport().setScrollable(true);
graph1.getViewport().setScalableY(true);
graph1.getViewport().setScrollableY(true);
graph1.getViewport().setYAxisBoundsManual(true);
graph1.getViewport().setMinY(-10);
graph1.getViewport().setMaxY(10);
graph1.getViewport().setXAxisBoundsManual(true);
graph1.getViewport().setMinX(200);
graph1.getViewport().setMaxX(500);
graph1.getGridLabelRenderer().setHorizontalAxisTitle("count");
series1=new LineGraphSeries<DataPoint>();
series2=new LineGraphSeries<DataPoint>();
series3=new LineGraphSeries<DataPoint>();
series1.setColor(Color.GREEN);
series1.setTitle("linear_X");
series2.setColor(Color.BLUE);
series2.setTitle("linear_Y");
series3.setColor(Color.RED);
series3.setTitle("linear_Z");
series4=new LineGraphSeries<DataPoint>();
series5=new LineGraphSeries<DataPoint>();
series6=new LineGraphSeries<DataPoint>();
series4.setColor(Color.GREEN);
series4.setTitle("linear_X");
series5.setColor(Color.BLUE);
series5.setTitle("linear_Y");
series6.setColor(Color.RED);
series6.setTitle("linear_Z");
graph1.addSeries(series1);
graph1.addSeries(series2);
graph1.addSeries(series3);
graph2.getViewport().setScalable(true);
graph2.getViewport().setScrollable(true);
graph2.getViewport().setScalableY(true);
graph2.getViewport().setScrollableY(true);
graph2.getViewport().setYAxisBoundsManual(true);
graph2.getViewport().setMinY(-10);
graph2.getViewport().setMaxY(10);
graph2.getViewport().setXAxisBoundsManual(true);
graph2.getViewport().setMinX(200);
graph2.getViewport().setMaxX(500);
graph2.getGridLabelRenderer().setHorizontalAxisTitle("count");
graph2.addSeries(series4);
graph2.addSeries(series5);
graph2.addSeries(series6);
series7=new LineGraphSeries<DataPoint>();
series7.setColor(Color.GREEN);
graph3.getViewport().setScalable(true);
graph3.getViewport().setScrollable(true);
graph3.getViewport().setScalableY(true);
graph3.getViewport().setScrollableY(true);
graph3.getViewport().setYAxisBoundsManual(true);
graph3.getViewport().setMinY(-10);
graph3.getViewport().setMaxY(10);
graph3.getViewport().setXAxisBoundsManual(true);
graph3.getViewport().setMinX(200);
graph3.getViewport().setMaxX(500);
graph3.getGridLabelRenderer().setHorizontalAxisTitle("count");
graph3.addSeries(series7);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sm.unregisterListener(currentPara.this);
}
});
}
@Override
public void onSensorChanged(SensorEvent event) {
if(event.sensor.getType()==Sensor.TYPE_ACCELEROMETER) {
gravity[0] = alpha * gravity[0] + (1 - alpha) * event.values[0];
gravity[1] = alpha * gravity[1] + (1 - alpha) * event.values[1];
gravity[2] = alpha * gravity[2] + (1 - alpha) * event.values[2];
linear_acceleration[0] = event.values[0] - gravity[0]-bias[0];
linear_acceleration[1] = event.values[1] - gravity[1]-bias[1];
linear_acceleration[2] = event.values[2] - gravity[2]-bias[2];
int index = count2 % LENGTH;
tempX[index] = linear_acceleration[0];
tempY[index] = linear_acceleration[1];
tempZ[index] = linear_acceleration[2];
smoothAcc[0] = SensorUtil.realTimeSmooth(tempX);
smoothAcc[1] = SensorUtil.realTimeSmooth(tempY);
smoothAcc[2] = SensorUtil.realTimeSmooth(tempZ);
series4.appendData(new DataPoint(count2, smoothAcc[0]), true, 500);
series5.appendData(new DataPoint(count2, smoothAcc[1]), true, 500);
series6.appendData(new DataPoint(count2, smoothAcc[2]), true, 500);
magnitude= (float) Math.sqrt(smoothAcc[0]*smoothAcc[0]+smoothAcc[1]*smoothAcc[1]+smoothAcc[2]*smoothAcc[2]);
if(magnitude<0.5)
magnitude=0;
series7.appendData(new DataPoint(count2++, magnitude),true,500);
if(magneticValue!=null) {
float[] R = new float[9], I = new float[9], earthAcc = new float[3];
SensorManager.getRotationMatrix(R, I, gravity, magneticValue);
// android.opengl.Matrix.transposeM(t, 0, R, 0);
// android.opengl.Matrix.invertM(inv, 0, t, 0);
//android.opengl.Matrix.multiplyMV(earthAcc, 0, R, 0, smoothAcc, 0);
earthAcc[0]=R[0]*smoothAcc[0]+R[1]*smoothAcc[1]+R[2]*smoothAcc[2];
earthAcc[1]=R[3]*smoothAcc[0]+R[4]*smoothAcc[1]+R[5]*smoothAcc[2];
earthAcc[2]=R[6]*smoothAcc[0]+R[7]*smoothAcc[1]+R[8]*smoothAcc[2];
series1.appendData(new DataPoint(count1, earthAcc[0]), true, 500);
series2.appendData(new DataPoint(count1, earthAcc[1]), true, 500);
series3.appendData(new DataPoint(count1++, earthAcc[2]), true, 500);
//linearX.setText(String.valueOf(earthAcc[0]));
//linearY.setText(String.valueOf(earthAcc[1]));
//linearZ.setText(String.valueOf(earthAcc[2]));
}
}
if(event.sensor.getType()==Sensor.TYPE_MAGNETIC_FIELD){
magneticValue=event.values;
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
@Override
public void onResume(){
super.onResume();
stopFlag=false;
AccDb=new DataBaseHelper(this);
if(dBthread==null) {
dBthread = new Thread(new DBthread());
dBthread.start();
}
Toast.makeText(this,AccDb.SQL_CREATE_ACC,Toast.LENGTH_SHORT).show();
sm.registerListener(currentPara.this,sensor_Acc,SensorManager.SENSOR_DELAY_GAME);
sm.registerListener(currentPara.this,sensor_Magn,SensorManager.SENSOR_DELAY_GAME);
}
@Override
public void onPause(){
super.onPause();
stopFlag=true;
sm.unregisterListener(this);
//dBthread.stop();
AccDb.close();
}
@Override
protected void onDestroy() {
super.onDestroy();
stopFlag=true;
sm.unregisterListener(this);
//dBthread.stop();
AccDb.close();
}
public void getBias(float [] bias) throws FileNotFoundException {
bias[0]=0;
bias[1]=0;
bias[2]=0;
int count=0;
File sdcard=Environment.getExternalStorageDirectory();
File inurl = new File (sdcard.getAbsolutePath() + "/SensorData/acc.txt");
try {
InputStreamReader isr = new InputStreamReader(new FileInputStream(inurl), "UTF-8");
BufferedReader br=new BufferedReader(isr);
String str=null;
String[] temp;
while((str=br.readLine())!=null){
temp=str.split(",");
for(int i=0;i<temp.length;i++){
bias[i]+=Float.parseFloat(temp[i]);
}
count++;
}
Log.d("bias",String.valueOf(bias[0]));
Log.d("bias",String.valueOf(bias[1]));
Log.d("bias",String.valueOf(bias[2]));
}
catch (IOException e){
Log.e("bias",e.toString());
}
for(float f:bias){
f /= count;
//Log.d("bias",String.valueOf(f));
}
}
public class DBthread implements Runnable{
int count=0;
@Override
public void run() {
if (!stopFlag&&count != count2) {
count=count2;
AccDb.insertAccData(smoothAcc[0], smoothAcc[1], smoothAcc[2], magnitude);
}
}
}
}
| 10,948 | 0.629247 | 0.604677 | 300 | 35.493332 | 23.799929 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.893333 | false | false |
3
|
8451e3a61bcb81f6c99c2f1a17ea817f3ed0a72e
| 4,140,348,484,752 |
c93723d2d26536605292ab0fee533183ff1d3740
|
/src/Main.java
|
a7462ed82ffa12131673d9b571d67f148f23d761
|
[] |
no_license
|
derekstephen/CS570_Programming_Foundations_-_Programming_Assignment_7
|
https://github.com/derekstephen/CS570_Programming_Foundations_-_Programming_Assignment_7
|
6d601573ecfa20971f2f831cbb03896f8dc634e3
|
ed431c961838c6cae215b72522c66a004dfb695e
|
refs/heads/master
| 2020-05-26T19:26:53.454000 | 2019-06-03T20:45:23 | 2019-06-03T20:45:23 | 188,348,513 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ArrayList<Shape> shapes = new ArrayList<>();
Scanner inFile = null;
try {
inFile = new Scanner(new File("shapes.txt"));
while(inFile.hasNext()){
String line = inFile.nextLine();
String[] parameters = line.split(" ");
int x, y, r, b, h;
switch(parameters[0]) {
case "circle":
x = Integer.parseInt(parameters[1]);
y = Integer.parseInt(parameters[2]);
r = Integer.parseInt(parameters[3]);
shapes.add(new Circle(x, y, r));
break;
case "square":
x = Integer.parseInt(parameters[1]);
y = Integer.parseInt(parameters[2]);
r = Integer.parseInt(parameters[3]);
shapes.add(new Square(x, y, r));
break;
case "triangle":
x = Integer.parseInt(parameters[1]);
y = Integer.parseInt(parameters[2]);
b = Integer.parseInt(parameters[3]);
h = Integer.parseInt(parameters[4]);
shapes.add(new Triangle(x, y, b, h));
break;
case "sphere":
x = Integer.parseInt(parameters[1]);
y = Integer.parseInt(parameters[2]);
r = Integer.parseInt(parameters[3]);
shapes.add(new Sphere(x, y, r));
break;
case "cube":
x = Integer.parseInt(parameters[1]);
y = Integer.parseInt(parameters[2]);
r = Integer.parseInt(parameters[3]);
shapes.add(new Cube(x, y, r));
break;
case "tetrahedron":
x = Integer.parseInt(parameters[1]);
y = Integer.parseInt(parameters[2]);
r = Integer.parseInt(parameters[3]);
shapes.add(new Tetrahedron(x, y, r));
break;
}
}
inFile.close();
try {
Formatter outFile = new Formatter("output.txt");
for (int i = 0; i < shapes.size(); i++) {
outFile.format("%s%n", shapes.get(i));
}
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
|
UTF-8
|
Java
| 3,002 |
java
|
Main.java
|
Java
|
[] | null |
[] |
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ArrayList<Shape> shapes = new ArrayList<>();
Scanner inFile = null;
try {
inFile = new Scanner(new File("shapes.txt"));
while(inFile.hasNext()){
String line = inFile.nextLine();
String[] parameters = line.split(" ");
int x, y, r, b, h;
switch(parameters[0]) {
case "circle":
x = Integer.parseInt(parameters[1]);
y = Integer.parseInt(parameters[2]);
r = Integer.parseInt(parameters[3]);
shapes.add(new Circle(x, y, r));
break;
case "square":
x = Integer.parseInt(parameters[1]);
y = Integer.parseInt(parameters[2]);
r = Integer.parseInt(parameters[3]);
shapes.add(new Square(x, y, r));
break;
case "triangle":
x = Integer.parseInt(parameters[1]);
y = Integer.parseInt(parameters[2]);
b = Integer.parseInt(parameters[3]);
h = Integer.parseInt(parameters[4]);
shapes.add(new Triangle(x, y, b, h));
break;
case "sphere":
x = Integer.parseInt(parameters[1]);
y = Integer.parseInt(parameters[2]);
r = Integer.parseInt(parameters[3]);
shapes.add(new Sphere(x, y, r));
break;
case "cube":
x = Integer.parseInt(parameters[1]);
y = Integer.parseInt(parameters[2]);
r = Integer.parseInt(parameters[3]);
shapes.add(new Cube(x, y, r));
break;
case "tetrahedron":
x = Integer.parseInt(parameters[1]);
y = Integer.parseInt(parameters[2]);
r = Integer.parseInt(parameters[3]);
shapes.add(new Tetrahedron(x, y, r));
break;
}
}
inFile.close();
try {
Formatter outFile = new Formatter("output.txt");
for (int i = 0; i < shapes.size(); i++) {
outFile.format("%s%n", shapes.get(i));
}
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
| 3,002 | 0.423384 | 0.416389 | 79 | 37 | 21.12051 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.860759 | false | false |
3
|
b1bd33a89907cfb4f1511ec5b09c580da9628825
| 4,140,348,485,583 |
3b43dbc8bf14ccae80fb0224e190a2dda84b534e
|
/solrsherlock-parent/topicquests-support/src/main/java/org/topicquests/util/TextFileHandler.java
|
71071e631ee4dd5ba040db147d622dea98ae050f
|
[
"Apache-2.0"
] |
permissive
|
agibsonccc/solrsherlock-maven
|
https://github.com/agibsonccc/solrsherlock-maven
|
f9612b05bfa0f1a12d217e56e5b4c6e14075fc30
|
1b0b278d118a859ea0ba58055c2e2d3628b58dd9
|
refs/heads/master
| 2021-01-06T20:42:30.478000 | 2013-09-23T02:34:05 | 2013-09-23T02:34:05 | 12,635,070 | 0 | 0 |
Apache-2.0
| false | 2021-05-12T00:16:53 | 2013-09-06T03:34:08 | 2014-06-04T14:11:34 | 2021-05-12T00:16:51 | 196 | 0 | 0 | 2 |
Java
| false | false |
/*
* Copyright 2013, TopicQuests
*
* 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.topicquests.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.io.InputStreamReader;
import java.io.FileInputStream;
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileNotFoundException;
import javax.swing.JFileChooser;
import java.util.zip.*;
/**
* TextFileHandler.java
* General purpose Text File handler
* @author Jack Park
*/
/**
* FIXME: Errors should throw new RuntimeException
*/
public class TextFileHandler {
private String fName = null;
private String body = null;
private BufferedReader inStream = null;
private JFileChooser chooser = null;
public TextFileHandler() {
}
//////////////////////////////////////
// Directory services
// To use:
// First save:
// // caller gets a file e.g. to set a document name
// File newFile = handler._saveAs();
// // callser uses that file
// if (newFile != null)
// handler.writeFile(newFile, bodyString);
//////////////////////////////////////
public File _saveAs() {
File result = null;
if (chooser==null)chooser = new JFileChooser(new File("."));
int retVal = chooser.showSaveDialog(null);
if(retVal == JFileChooser.APPROVE_OPTION) {
result = chooser.getSelectedFile();
}
return result;
}
public void saveAs(String body) {
File myFile = _saveAs();
if (myFile != null) {
writeFile(myFile, body);
}
}
public File openFile() {
return openFile(null);
}
public File openFile(String title) {
File result = null;
JFileChooser chooser = new JFileChooser(new File("."));
if (title != null)
chooser.setDialogTitle(title);
int retVal = chooser.showOpenDialog(null);
if(retVal == JFileChooser.APPROVE_OPTION) {
result = chooser.getSelectedFile();
}
return result;
}
public File [] openFiles(String title) {
File [] result = null;
JFileChooser chooser = new JFileChooser(new File("."));
if (title != null)
chooser.setDialogTitle(title);
chooser.setMultiSelectionEnabled(true);
int retVal = chooser.showOpenDialog(null);
if(retVal == JFileChooser.APPROVE_OPTION) {
result = chooser.getSelectedFiles();
}
return result;
}
public File openDirectory() {
return openDirectory(null);
}
public File openDirectory(String title) {
File result = null;
JFileChooser chooser = new JFileChooser(new File("."));
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (title != null)
chooser.setDialogTitle(title);
int retVal = chooser.showOpenDialog(null);
if(retVal == JFileChooser.APPROVE_OPTION) {
result = chooser.getSelectedFile();
}
return result;
}
//////////////////////////////////////
// Simple File handlers
/////////////////////////////////////
public String readFile(String fileName) { // fully qualified name
File f = new File(fileName);
fName = fileName;
return readFile(f);
}
public String readFile(File f) {
int size = (int) f.length();
int bytesRead = 0 ;
body = null;
try {
FileInputStream in = new FileInputStream(f) ;
byte[] data = new byte[size] ;
in.read(data, 0, size);
body = new String(data) ;
in.close() ;
} catch (IOException e) {
System.out.println("Error: TextFileHandler couldn't read from " + f + "\n") ;
}
return body;
}
public String readFile16(File f) throws IOException {
StringBuilder sb = new StringBuilder();
String line;
Reader in = null;
try {
in = new InputStreamReader(new FileInputStream(f), "UTF-16");
BufferedReader reader = new BufferedReader(in);
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
} finally {
in.close();
}
return sb.toString();
}
public void writeFile(String fileName, String inBody) {
File f = new File(fileName) ;
fName = fileName;
writeFile(f, inBody);
}
public void writeFile(File f, String inBody) {
// System.out.println("WRITING "+f);
int size = (int) inBody.length();
int bytesOut = 0 ;
byte data[] = inBody.getBytes(); //new byte[size] ;
// data = body.getBytes();
try {
FileOutputStream out = new FileOutputStream(f) ;
out.write(data, 0, size);
out.flush() ;
out.close() ;
}
catch (IOException e) {
System.out.println("Error: TextFileHandler couldn't write to " + fName + "\n");
}
}
//////////////////////////////////////
// Line-oriented File readers
/////////////////////////////////////
public String readFirstLine(String fileName) {
File f = new File(fileName);
return readFirstLine(f);
}
public String readFirstLine(File f) {
fName = f.getName();
try {
FileInputStream in = new FileInputStream(f);
inStream = new BufferedReader(new InputStreamReader(in));
} catch (IOException e) {
System.out.println("Error: TextFileHandler couldn't open a DataInputStream on " + fName + "\n");
}
return readNextLine();
}
/**
* Read a line from an open file
* Return null when done
*/
public String readNextLine() {
String str = null;
try {
str = inStream.readLine();
} catch (IOException e) {
System.out.println("Error: TextFileHandler couldn't read from " + fName + "\n");
}
return str;
}
////////////////////////////////////////////
// Serialized Java Class utilities
////////////////////////////////////////////
public void persist(String fileName, Object obj) {
try {
new ObjectOutputStream(
new FileOutputStream(new File(fileName))).writeObject(obj);
} catch (Exception e) {
// e.printStackTrace();
throw new RuntimeException(e);
}
}
public Object restore(String fileName) {
Object result = null;
try {
result = new ObjectInputStream(
new FileInputStream(new File(fileName))).readObject();
}
catch (Exception e) {
// e.printStackTrace();
System.out.println("Restoring "+fileName);
// e.printStackTrace();
// throw new RuntimeException("Failed");
}
return result;
}
////////////////////////////////////////////
// GZip utilities
////////////////////////////////////////////
/**
* Save content to a .gz file
* @param fileName e.g. foo.txt.gz
* @param content
*/
public void saveGZipFile(String fileName, String content) {
try {
GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(fileName));
PrintWriter pw = new PrintWriter(out);
pw.write(content);
pw.flush();
pw.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public PrintWriter getGZipWriter(String fileName) throws Exception {
GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(fileName));
return new PrintWriter(out);
}
public void saveGZipFile(File outFile, String content) throws Exception{
GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(outFile));
PrintWriter pw = new PrintWriter(out);
pw.write(content);
pw.flush();
pw.close();
}
/**
* Retrieve a String from a .gz file
* @param fileName e.g. bar.xml.gz
* @return
*/
public String openGZipFile(String fileName) {
try {
GZIPInputStream in = new GZIPInputStream(new FileInputStream(
fileName));
StringBuffer buf = new StringBuffer();
byte [] b = new byte[1024];
int length;
while ((length = in.read(b)) > 0) {
String s = new String(b);
buf.append(s);
}
return buf.toString().trim();
} catch (Exception e) {
System.out.println(e.getMessage());
}
return null;
}
public GZIPInputStream getGZipInputStream(FileInputStream fis) throws IOException {
return new GZIPInputStream(fis);
}
}
/**
ChangeLog
20020512 JP: minor fix in readFile
**/
|
UTF-8
|
Java
| 9,113 |
java
|
TextFileHandler.java
|
Java
|
[
{
"context": "\n * General purpose Text File handler\n * @author Jack Park\n */\n/**\n * FIXME: Errors should throw new Runtime",
"end": 1215,
"score": 0.9995322227478027,
"start": 1206,
"tag": "NAME",
"value": "Jack Park"
}
] | null |
[] |
/*
* Copyright 2013, TopicQuests
*
* 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.topicquests.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.io.InputStreamReader;
import java.io.FileInputStream;
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileNotFoundException;
import javax.swing.JFileChooser;
import java.util.zip.*;
/**
* TextFileHandler.java
* General purpose Text File handler
* @author <NAME>
*/
/**
* FIXME: Errors should throw new RuntimeException
*/
public class TextFileHandler {
private String fName = null;
private String body = null;
private BufferedReader inStream = null;
private JFileChooser chooser = null;
public TextFileHandler() {
}
//////////////////////////////////////
// Directory services
// To use:
// First save:
// // caller gets a file e.g. to set a document name
// File newFile = handler._saveAs();
// // callser uses that file
// if (newFile != null)
// handler.writeFile(newFile, bodyString);
//////////////////////////////////////
public File _saveAs() {
File result = null;
if (chooser==null)chooser = new JFileChooser(new File("."));
int retVal = chooser.showSaveDialog(null);
if(retVal == JFileChooser.APPROVE_OPTION) {
result = chooser.getSelectedFile();
}
return result;
}
public void saveAs(String body) {
File myFile = _saveAs();
if (myFile != null) {
writeFile(myFile, body);
}
}
public File openFile() {
return openFile(null);
}
public File openFile(String title) {
File result = null;
JFileChooser chooser = new JFileChooser(new File("."));
if (title != null)
chooser.setDialogTitle(title);
int retVal = chooser.showOpenDialog(null);
if(retVal == JFileChooser.APPROVE_OPTION) {
result = chooser.getSelectedFile();
}
return result;
}
public File [] openFiles(String title) {
File [] result = null;
JFileChooser chooser = new JFileChooser(new File("."));
if (title != null)
chooser.setDialogTitle(title);
chooser.setMultiSelectionEnabled(true);
int retVal = chooser.showOpenDialog(null);
if(retVal == JFileChooser.APPROVE_OPTION) {
result = chooser.getSelectedFiles();
}
return result;
}
public File openDirectory() {
return openDirectory(null);
}
public File openDirectory(String title) {
File result = null;
JFileChooser chooser = new JFileChooser(new File("."));
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (title != null)
chooser.setDialogTitle(title);
int retVal = chooser.showOpenDialog(null);
if(retVal == JFileChooser.APPROVE_OPTION) {
result = chooser.getSelectedFile();
}
return result;
}
//////////////////////////////////////
// Simple File handlers
/////////////////////////////////////
public String readFile(String fileName) { // fully qualified name
File f = new File(fileName);
fName = fileName;
return readFile(f);
}
public String readFile(File f) {
int size = (int) f.length();
int bytesRead = 0 ;
body = null;
try {
FileInputStream in = new FileInputStream(f) ;
byte[] data = new byte[size] ;
in.read(data, 0, size);
body = new String(data) ;
in.close() ;
} catch (IOException e) {
System.out.println("Error: TextFileHandler couldn't read from " + f + "\n") ;
}
return body;
}
public String readFile16(File f) throws IOException {
StringBuilder sb = new StringBuilder();
String line;
Reader in = null;
try {
in = new InputStreamReader(new FileInputStream(f), "UTF-16");
BufferedReader reader = new BufferedReader(in);
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
} finally {
in.close();
}
return sb.toString();
}
public void writeFile(String fileName, String inBody) {
File f = new File(fileName) ;
fName = fileName;
writeFile(f, inBody);
}
public void writeFile(File f, String inBody) {
// System.out.println("WRITING "+f);
int size = (int) inBody.length();
int bytesOut = 0 ;
byte data[] = inBody.getBytes(); //new byte[size] ;
// data = body.getBytes();
try {
FileOutputStream out = new FileOutputStream(f) ;
out.write(data, 0, size);
out.flush() ;
out.close() ;
}
catch (IOException e) {
System.out.println("Error: TextFileHandler couldn't write to " + fName + "\n");
}
}
//////////////////////////////////////
// Line-oriented File readers
/////////////////////////////////////
public String readFirstLine(String fileName) {
File f = new File(fileName);
return readFirstLine(f);
}
public String readFirstLine(File f) {
fName = f.getName();
try {
FileInputStream in = new FileInputStream(f);
inStream = new BufferedReader(new InputStreamReader(in));
} catch (IOException e) {
System.out.println("Error: TextFileHandler couldn't open a DataInputStream on " + fName + "\n");
}
return readNextLine();
}
/**
* Read a line from an open file
* Return null when done
*/
public String readNextLine() {
String str = null;
try {
str = inStream.readLine();
} catch (IOException e) {
System.out.println("Error: TextFileHandler couldn't read from " + fName + "\n");
}
return str;
}
////////////////////////////////////////////
// Serialized Java Class utilities
////////////////////////////////////////////
public void persist(String fileName, Object obj) {
try {
new ObjectOutputStream(
new FileOutputStream(new File(fileName))).writeObject(obj);
} catch (Exception e) {
// e.printStackTrace();
throw new RuntimeException(e);
}
}
public Object restore(String fileName) {
Object result = null;
try {
result = new ObjectInputStream(
new FileInputStream(new File(fileName))).readObject();
}
catch (Exception e) {
// e.printStackTrace();
System.out.println("Restoring "+fileName);
// e.printStackTrace();
// throw new RuntimeException("Failed");
}
return result;
}
////////////////////////////////////////////
// GZip utilities
////////////////////////////////////////////
/**
* Save content to a .gz file
* @param fileName e.g. foo.txt.gz
* @param content
*/
public void saveGZipFile(String fileName, String content) {
try {
GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(fileName));
PrintWriter pw = new PrintWriter(out);
pw.write(content);
pw.flush();
pw.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public PrintWriter getGZipWriter(String fileName) throws Exception {
GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(fileName));
return new PrintWriter(out);
}
public void saveGZipFile(File outFile, String content) throws Exception{
GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(outFile));
PrintWriter pw = new PrintWriter(out);
pw.write(content);
pw.flush();
pw.close();
}
/**
* Retrieve a String from a .gz file
* @param fileName e.g. bar.xml.gz
* @return
*/
public String openGZipFile(String fileName) {
try {
GZIPInputStream in = new GZIPInputStream(new FileInputStream(
fileName));
StringBuffer buf = new StringBuffer();
byte [] b = new byte[1024];
int length;
while ((length = in.read(b)) > 0) {
String s = new String(b);
buf.append(s);
}
return buf.toString().trim();
} catch (Exception e) {
System.out.println(e.getMessage());
}
return null;
}
public GZIPInputStream getGZipInputStream(FileInputStream fis) throws IOException {
return new GZIPInputStream(fis);
}
}
/**
ChangeLog
20020512 JP: minor fix in readFile
**/
| 9,110 | 0.597827 | 0.594645 | 310 | 28.4 | 21.17625 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.577419 | false | false |
3
|
71c658061e612544fc84ef6ac0bd33337ad1b2e5
| 25,821,343,418,729 |
c2ed2b1e50b6a83422d11fd317ef96b36822d4b4
|
/examples/src/main/java/com/inspiresoftware/lib/dto/geda/examples/usecases/dsl/RunDSLReuseMapping.java
|
a0963a2681e9c9e846ef87cc23b8e4705b6f44ff
|
[] |
no_license
|
inspire-software/geda-genericdto
|
https://github.com/inspire-software/geda-genericdto
|
48006aec3c9cd98c2178f5a83a644495d3805dcb
|
5e453c78a61c38f72c21e75a754ff19b96cb8dc1
|
refs/heads/master
| 2022-12-21T15:36:22.950000 | 2021-02-27T16:34:47 | 2021-02-27T16:34:47 | 32,479,235 | 23 | 10 | null | false | 2022-12-16T05:21:07 | 2015-03-18T19:18:47 | 2022-06-13T23:09:56 | 2022-12-16T05:21:04 | 3,235 | 22 | 6 | 5 |
Java
| false | false |
/*
* This code is distributed under The GNU Lesser General Public License (LGPLv3)
* Please visit GNU site for LGPLv3 http://www.gnu.org/copyleft/lesser.html
*
* Copyright Denis Pavlov 2009
* Web: http://www.genericdtoassembler.org
* SVN: https://svn.code.sf.net/p/geda-genericdto/code/trunk/
* SVN (mirror): http://geda-genericdto.googlecode.com/svn/trunk/
*/
package com.inspiresoftware.lib.dto.geda.examples.usecases.dsl;
import com.inspiresoftware.lib.dto.geda.adapter.BeanFactory;
import com.inspiresoftware.lib.dto.geda.adapter.EntityRetriever;
import com.inspiresoftware.lib.dto.geda.adapter.ExtensibleBeanFactory;
import com.inspiresoftware.lib.dto.geda.adapter.ValueConverter;
import com.inspiresoftware.lib.dto.geda.assembler.DTOAssembler;
import com.inspiresoftware.lib.dto.geda.dsl.Registries;
import com.inspiresoftware.lib.dto.geda.examples.usecases.SimpleMapExtensibleBeanFactory;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.*;
/**
* User: denispavlov
* Date: 13-04-22
* Time: 5:59 PM
*/
public class RunDSLReuseMapping {
/**
* Example of how mapping from one DTO-Entity context can be copied to
* another DTO-Entity context to reduce code duplication.
*/
public void reuseMapping() {
final ExtensibleBeanFactory bf = new SimpleMapExtensibleBeanFactory();
final com.inspiresoftware.lib.dto.geda.dsl.Registry registry = Registries.registry(bf);
bf.registerDto("myDto", MyDtoClass.class.getCanonicalName());
bf.registerDto("myDtoField3Dto", MyDtoField3Class.class.getCanonicalName());
bf.registerEntity("myEntityField3Entity", MyEntityField3Class.class.getCanonicalName(), MyEntityField3Class.class.getCanonicalName());
bf.registerDto("field4ParentDto", MyDtoField4Class.class.getCanonicalName());
bf.registerEntity("field4ParentEntity", MyEntityField4Class.class.getCanonicalName(), MyEntityField4Class.class.getCanonicalName());
registry
// main mapping
.dto("myDto").forEntity(MyEntity.class)
// field 1
.withField("field1").forField("field1")
.readOnly()
.converter("field1Converter")
// field 2
.and()
.withField("field2").forField("field2.subField1").entityBeanKeys("field2")
// field 5
.and()
.withField("field5virtual").forVirtual()
.converter("field5VirtualConverter")
;
registry.dto("myDto").useContextFor(
registry
// main mapping
.dto("myDto").forEntity(MyEntity.class),
Map.class
);
final Map<String, Object> conv = new HashMap<String, Object>();
conv.put("field1Converter", new ValueConverter() {
public Object convertToDto(final Object object, final BeanFactory beanFactory) {
final MyEntity.Field1 field1 = (MyEntity.Field1) object;
return Boolean.valueOf(field1 == MyEntity.Field1.YES);
}
public Object convertToEntity(final Object object, final Object oldEntity, final BeanFactory beanFactory) {
if ((Boolean) object) {
return MyEntity.Field1.YES;
}
return MyEntity.Field1.NO;
}
});
conv.put("field5VirtualConverter", new ValueConverter() {
public Object convertToDto(final Object object, final BeanFactory beanFactory) {
return String.valueOf(object.hashCode());
}
public Object convertToEntity(final Object object, final Object oldEntity, final BeanFactory beanFactory) {
((Map) oldEntity).put("virtual5", object);
return null;
}
});
conv.put("parentFieldEntityById", new EntityRetriever() {
public Object retrieveByPrimaryKey(final Class entityInterface, final Class entityClass, final Object primaryKey) {
final MyEntityField4Class parent = new MyEntityField4Class();
parent.setId(99L);
parent.setSubField1("Parent 99");
return parent;
}
});
// create asm for interface
DTOAssembler.newAssembler(MyDtoClass.class, Map.class, registry);
final Map<String, Object> entity = new HashMap<String, Object>();
entity.put("field1", MyEntity.Field1.YES);
entity.put("field2", "my sub data 1");
entity.put("field5virtual", "virtual");
final MyDtoClass dto = new MyDtoClass();
// create asm for class and make sure it picks up on interface
DTOAssembler.newAssembler(MyDtoClass.class, entity.getClass(), registry).assembleDto(dto, entity, conv, bf);
assertTrue(dto.getField1());
assertEquals(dto.getField2(), "my sub data 1");
assertEquals(dto.getField5virtual(), String.valueOf(entity.hashCode()));
final Map<String, Object> toEntity = new HashMap<String, Object>();
// create asm for class and make sure it picks up on interface
DTOAssembler.newAssembler(MyDtoClass.class, entity.getClass(), registry).assembleEntity(dto, toEntity, conv, bf);
assertNull(toEntity.get("field1")); // it is read only
assertEquals(toEntity.get("field2"), "my sub data 1");
assertEquals(toEntity.get("virtual5"), dto.getField5virtual());
}
public static void main(String[] args) {
new RunDSLReuseMapping().reuseMapping();
}
}
|
UTF-8
|
Java
| 5,667 |
java
|
RunDSLReuseMapping.java
|
Java
|
[
{
"context": "//www.gnu.org/copyleft/lesser.html\n *\n * Copyright Denis Pavlov 2009\n * Web: http://www.genericdtoassembler.org\n ",
"end": 188,
"score": 0.9998108148574829,
"start": 176,
"tag": "NAME",
"value": "Denis Pavlov"
},
{
"context": ";\n\nimport static org.junit.Assert.*;\n\n/**\n * User: denispavlov\n * Date: 13-04-22\n * Time: 5:59 PM\n */\npublic cla",
"end": 1015,
"score": 0.9988970756530762,
"start": 1004,
"tag": "USERNAME",
"value": "denispavlov"
}
] | null |
[] |
/*
* This code is distributed under The GNU Lesser General Public License (LGPLv3)
* Please visit GNU site for LGPLv3 http://www.gnu.org/copyleft/lesser.html
*
* Copyright <NAME> 2009
* Web: http://www.genericdtoassembler.org
* SVN: https://svn.code.sf.net/p/geda-genericdto/code/trunk/
* SVN (mirror): http://geda-genericdto.googlecode.com/svn/trunk/
*/
package com.inspiresoftware.lib.dto.geda.examples.usecases.dsl;
import com.inspiresoftware.lib.dto.geda.adapter.BeanFactory;
import com.inspiresoftware.lib.dto.geda.adapter.EntityRetriever;
import com.inspiresoftware.lib.dto.geda.adapter.ExtensibleBeanFactory;
import com.inspiresoftware.lib.dto.geda.adapter.ValueConverter;
import com.inspiresoftware.lib.dto.geda.assembler.DTOAssembler;
import com.inspiresoftware.lib.dto.geda.dsl.Registries;
import com.inspiresoftware.lib.dto.geda.examples.usecases.SimpleMapExtensibleBeanFactory;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.*;
/**
* User: denispavlov
* Date: 13-04-22
* Time: 5:59 PM
*/
public class RunDSLReuseMapping {
/**
* Example of how mapping from one DTO-Entity context can be copied to
* another DTO-Entity context to reduce code duplication.
*/
public void reuseMapping() {
final ExtensibleBeanFactory bf = new SimpleMapExtensibleBeanFactory();
final com.inspiresoftware.lib.dto.geda.dsl.Registry registry = Registries.registry(bf);
bf.registerDto("myDto", MyDtoClass.class.getCanonicalName());
bf.registerDto("myDtoField3Dto", MyDtoField3Class.class.getCanonicalName());
bf.registerEntity("myEntityField3Entity", MyEntityField3Class.class.getCanonicalName(), MyEntityField3Class.class.getCanonicalName());
bf.registerDto("field4ParentDto", MyDtoField4Class.class.getCanonicalName());
bf.registerEntity("field4ParentEntity", MyEntityField4Class.class.getCanonicalName(), MyEntityField4Class.class.getCanonicalName());
registry
// main mapping
.dto("myDto").forEntity(MyEntity.class)
// field 1
.withField("field1").forField("field1")
.readOnly()
.converter("field1Converter")
// field 2
.and()
.withField("field2").forField("field2.subField1").entityBeanKeys("field2")
// field 5
.and()
.withField("field5virtual").forVirtual()
.converter("field5VirtualConverter")
;
registry.dto("myDto").useContextFor(
registry
// main mapping
.dto("myDto").forEntity(MyEntity.class),
Map.class
);
final Map<String, Object> conv = new HashMap<String, Object>();
conv.put("field1Converter", new ValueConverter() {
public Object convertToDto(final Object object, final BeanFactory beanFactory) {
final MyEntity.Field1 field1 = (MyEntity.Field1) object;
return Boolean.valueOf(field1 == MyEntity.Field1.YES);
}
public Object convertToEntity(final Object object, final Object oldEntity, final BeanFactory beanFactory) {
if ((Boolean) object) {
return MyEntity.Field1.YES;
}
return MyEntity.Field1.NO;
}
});
conv.put("field5VirtualConverter", new ValueConverter() {
public Object convertToDto(final Object object, final BeanFactory beanFactory) {
return String.valueOf(object.hashCode());
}
public Object convertToEntity(final Object object, final Object oldEntity, final BeanFactory beanFactory) {
((Map) oldEntity).put("virtual5", object);
return null;
}
});
conv.put("parentFieldEntityById", new EntityRetriever() {
public Object retrieveByPrimaryKey(final Class entityInterface, final Class entityClass, final Object primaryKey) {
final MyEntityField4Class parent = new MyEntityField4Class();
parent.setId(99L);
parent.setSubField1("Parent 99");
return parent;
}
});
// create asm for interface
DTOAssembler.newAssembler(MyDtoClass.class, Map.class, registry);
final Map<String, Object> entity = new HashMap<String, Object>();
entity.put("field1", MyEntity.Field1.YES);
entity.put("field2", "my sub data 1");
entity.put("field5virtual", "virtual");
final MyDtoClass dto = new MyDtoClass();
// create asm for class and make sure it picks up on interface
DTOAssembler.newAssembler(MyDtoClass.class, entity.getClass(), registry).assembleDto(dto, entity, conv, bf);
assertTrue(dto.getField1());
assertEquals(dto.getField2(), "my sub data 1");
assertEquals(dto.getField5virtual(), String.valueOf(entity.hashCode()));
final Map<String, Object> toEntity = new HashMap<String, Object>();
// create asm for class and make sure it picks up on interface
DTOAssembler.newAssembler(MyDtoClass.class, entity.getClass(), registry).assembleEntity(dto, toEntity, conv, bf);
assertNull(toEntity.get("field1")); // it is read only
assertEquals(toEntity.get("field2"), "my sub data 1");
assertEquals(toEntity.get("virtual5"), dto.getField5virtual());
}
public static void main(String[] args) {
new RunDSLReuseMapping().reuseMapping();
}
}
| 5,661 | 0.644433 | 0.632433 | 144 | 38.354168 | 35.005054 | 142 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false |
3
|
4e404ac6bf2540e675c2964775f0f1bc16fde2b2
| 28,991,029,279,150 |
5cf8f676881cf477f352a2e4a9752f1c2dfa959d
|
/bex-common/src/test/java/io/hs/bex/common/utils/StringUtilsTest.java
|
40f45cfa51603e731d6bbbf1f4f604ce908cdd09
|
[] |
no_license
|
horizontalsystems/blockchain-meta
|
https://github.com/horizontalsystems/blockchain-meta
|
ce1187401b56a31893d099238ca6231fa8400692
|
27413ade07c45fc38348b3e44afbb624a12673ef
|
refs/heads/master
| 2020-04-01T09:27:36.059000 | 2020-01-22T04:10:14 | 2020-01-22T04:10:14 | 153,075,894 | 6 | 2 | null | false | 2020-10-14T05:39:05 | 2018-10-15T08:08:06 | 2020-09-26T06:19:53 | 2020-10-14T05:39:04 | 42,824 | 5 | 3 | 4 |
JavaScript
| false | false |
package io.hs.bex.common.utils;
import static org.junit.Assert.assertTrue;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import org.junit.Test;
public class StringUtilsTest
{
@Test
public void testDoubleToString()
{
double a1 = 1.2;
double a2 = 0.12345678910;
double a3 = 123.120000;
double a4 = 123456;
String out1 = StringUtils.doubleToString( a1 );
String out2 = StringUtils.doubleToString( a2 );
String out3 = StringUtils.doubleToString( a3 );
String out4 = StringUtils.doubleToString( a4 );
System.out.println("Out1:" + out1 );
System.out.println("Out2:" + out2 );
System.out.println("Out3:" + out3 );
System.out.println("Out4:" + out4 );
}
@Test
public void testStringToNChar()
{
String out1 = "12312";
int size = 3;
String out[] = StringUtils.splitToNChar( out1, size );
for(String pOut:out )
{
System.out.println("StringToNChar Original:" + out1 + " Out:" + pOut );
}
assertTrue( out.length == 2 );
}
@Test
public void testCreateDirStructure()
{
String out1 = "dir/1dir2";
int size = 4;
String dir = StringUtils.createDirStructure( out1, size );
System.out.println("StringToNChar Original:" + out1 + " Dir:" + dir );
assertTrue( dir.length() == 11 );
}
@Test
public void testCreateDirStructurePartsCount()
{
String out1 = "dir1dir2asdasdasdasdasd";
int size = 4;
int partsCount = 2;
String dir = StringUtils.createDirStructure( out1, size , partsCount);
System.out.println("StringToNChar Parts Original:" + out1 + " Dir:" + dir );
//assertTrue( dir.charAt( 3 ) == '1' );
}
@Test
public void testStringTimeZoneToDate()
{
String dateStr = "2018-03-01T06:00:00Z";
DateTimeFormatter formatter = DateTimeFormatter.ISO_ZONED_DATE_TIME;
LocalDateTime dateTime = LocalDateTime.parse( dateStr, formatter );
System.out.println( "Zoned String to Date:" + dateTime.toString() );
}
}
|
UTF-8
|
Java
| 2,328 |
java
|
StringUtilsTest.java
|
Java
|
[] | null |
[] |
package io.hs.bex.common.utils;
import static org.junit.Assert.assertTrue;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import org.junit.Test;
public class StringUtilsTest
{
@Test
public void testDoubleToString()
{
double a1 = 1.2;
double a2 = 0.12345678910;
double a3 = 123.120000;
double a4 = 123456;
String out1 = StringUtils.doubleToString( a1 );
String out2 = StringUtils.doubleToString( a2 );
String out3 = StringUtils.doubleToString( a3 );
String out4 = StringUtils.doubleToString( a4 );
System.out.println("Out1:" + out1 );
System.out.println("Out2:" + out2 );
System.out.println("Out3:" + out3 );
System.out.println("Out4:" + out4 );
}
@Test
public void testStringToNChar()
{
String out1 = "12312";
int size = 3;
String out[] = StringUtils.splitToNChar( out1, size );
for(String pOut:out )
{
System.out.println("StringToNChar Original:" + out1 + " Out:" + pOut );
}
assertTrue( out.length == 2 );
}
@Test
public void testCreateDirStructure()
{
String out1 = "dir/1dir2";
int size = 4;
String dir = StringUtils.createDirStructure( out1, size );
System.out.println("StringToNChar Original:" + out1 + " Dir:" + dir );
assertTrue( dir.length() == 11 );
}
@Test
public void testCreateDirStructurePartsCount()
{
String out1 = "dir1dir2asdasdasdasdasd";
int size = 4;
int partsCount = 2;
String dir = StringUtils.createDirStructure( out1, size , partsCount);
System.out.println("StringToNChar Parts Original:" + out1 + " Dir:" + dir );
//assertTrue( dir.charAt( 3 ) == '1' );
}
@Test
public void testStringTimeZoneToDate()
{
String dateStr = "2018-03-01T06:00:00Z";
DateTimeFormatter formatter = DateTimeFormatter.ISO_ZONED_DATE_TIME;
LocalDateTime dateTime = LocalDateTime.parse( dateStr, formatter );
System.out.println( "Zoned String to Date:" + dateTime.toString() );
}
}
| 2,328 | 0.56701 | 0.528351 | 87 | 25.758621 | 23.822603 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.482759 | false | false |
3
|
59d6830740967b421baa5a15b27de55be99e600a
| 29,566,554,876,948 |
f3f39134842f7621e9dde032c0c26676c653e2fb
|
/src/test/TestForSum.java
|
a408cf860977a51e9813fe59b723e689ced60eb2
|
[] |
no_license
|
hieuhcmus/algorithm
|
https://github.com/hieuhcmus/algorithm
|
7864518a1cf19eb95f1dcf88dd61b42a6311d8fd
|
a367e2181603f6c6ad1f4b4c5cb59a9a2eb9724a
|
refs/heads/master
| 2020-03-30T16:54:31.252000 | 2019-08-01T03:02:51 | 2019-08-01T03:02:51 | 151,432,620 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package test;
public class TestForSum {
public static void main(String[] args) {
int[] intArr = new int[] {5, 1, 23, 21, 17, 2, 3, 9, 12};
System.out.println(testForSum(intArr, 22));
System.out.println(testForSum(intArr, 21));
System.out.println(testForSum(intArr, 20));
System.out.println(testForSum(intArr, 19));
System.out.println(testForSum(intArr, 29));
System.out.println(testForSum(intArr, 1));
System.out.println(testForSum(intArr, 8));
}
public static boolean testForSum(int[] intArr, int testInt) {
int length = intArr.length;
for (int i = 0; i < length - 2; i++) {
// System.out.println("i=" + i);
if (intArr[i] >= testInt) {
continue;
}
for (int j = i + 1; j < length - 1; j++) {
// System.out.println("i=" + i + ", j= " + j);
if ((intArr[i] + intArr[j]) >= testInt) {
continue;
}
for (int k = j + 1; k < length; k++) {
// System.out.println("i=" + i + ", j=" + j + ", k=" + k);
if ((intArr[i] + intArr[j] + intArr[k]) == testInt) {
System.out.println(intArr[i] + " " + intArr[j] + " " + intArr[k]);
return true;
}
}
}
}
return false;
}
}
|
UTF-8
|
Java
| 1,149 |
java
|
TestForSum.java
|
Java
|
[] | null |
[] |
package test;
public class TestForSum {
public static void main(String[] args) {
int[] intArr = new int[] {5, 1, 23, 21, 17, 2, 3, 9, 12};
System.out.println(testForSum(intArr, 22));
System.out.println(testForSum(intArr, 21));
System.out.println(testForSum(intArr, 20));
System.out.println(testForSum(intArr, 19));
System.out.println(testForSum(intArr, 29));
System.out.println(testForSum(intArr, 1));
System.out.println(testForSum(intArr, 8));
}
public static boolean testForSum(int[] intArr, int testInt) {
int length = intArr.length;
for (int i = 0; i < length - 2; i++) {
// System.out.println("i=" + i);
if (intArr[i] >= testInt) {
continue;
}
for (int j = i + 1; j < length - 1; j++) {
// System.out.println("i=" + i + ", j= " + j);
if ((intArr[i] + intArr[j]) >= testInt) {
continue;
}
for (int k = j + 1; k < length; k++) {
// System.out.println("i=" + i + ", j=" + j + ", k=" + k);
if ((intArr[i] + intArr[j] + intArr[k]) == testInt) {
System.out.println(intArr[i] + " " + intArr[j] + " " + intArr[k]);
return true;
}
}
}
}
return false;
}
}
| 1,149 | 0.565709 | 0.5396 | 38 | 29.236841 | 21.440781 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.736842 | false | false |
3
|
aee58129313a0c59d2de8bb57c208ea0b4401bb1
| 16,140,487,143,641 |
54f294d2c30ad037d5124ea75c4dde840fbe0856
|
/LevelUp/app/src/main/java/com/laytonlabs/android/levelup/shapes/TextUnderscore.java
|
b705586c94dc1d49a0f488b54eda3bc6ee235f55
|
[] |
no_license
|
mlayton20/android
|
https://github.com/mlayton20/android
|
7cc740f6e9ae4d3d5eb56e37d02f5e45af8e5b0e
|
53b56aca1b5d8fac9cc34d71919c26bdcdc044f3
|
refs/heads/master
| 2021-01-15T15:33:19.773000 | 2016-06-08T18:29:13 | 2016-06-08T18:29:13 | 38,998,074 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.laytonlabs.android.levelup.shapes;
public class TextUnderscore extends Shape {
private static final float originalCoords[] = {
-0.3f, -0.4f, 0.0f, //0
-0.3f, -0.5f, 0.0f, //1
0.3f, -0.5f, 0.0f, //2
0.3f, -0.4f, 0.0f }; //3
private static final short drawOrder[] = { 0,1,3,3,1,2 }; // order to draw vertices
public TextUnderscore(float scale, float centreX, float centreY, float[] color) {
super(originalCoords, drawOrder, color, scale, centreX, centreY);
}
@Override
public float getCentreX() {
// TODO Auto-generated method stub
return 0;
}
@Override
public float getCentreY() {
// TODO Auto-generated method stub
return 0;
}
}
|
UTF-8
|
Java
| 726 |
java
|
TextUnderscore.java
|
Java
|
[] | null |
[] |
package com.laytonlabs.android.levelup.shapes;
public class TextUnderscore extends Shape {
private static final float originalCoords[] = {
-0.3f, -0.4f, 0.0f, //0
-0.3f, -0.5f, 0.0f, //1
0.3f, -0.5f, 0.0f, //2
0.3f, -0.4f, 0.0f }; //3
private static final short drawOrder[] = { 0,1,3,3,1,2 }; // order to draw vertices
public TextUnderscore(float scale, float centreX, float centreY, float[] color) {
super(originalCoords, drawOrder, color, scale, centreX, centreY);
}
@Override
public float getCentreX() {
// TODO Auto-generated method stub
return 0;
}
@Override
public float getCentreY() {
// TODO Auto-generated method stub
return 0;
}
}
| 726 | 0.623967 | 0.57438 | 28 | 24.964285 | 25.205559 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.642857 | false | false |
3
|
ee7b4e52ec5aea3ad18f2779e2754821555ff209
| 20,770,461,895,538 |
139b2d9e7a39a8acf1ab6d31b0d6882912fef0aa
|
/basic/chap8(인터페이스)/Car1.java
|
78b6165fa7bed734537ccc6ff44eea6bfb8b1b17
|
[] |
no_license
|
skss25/JavaExamples
|
https://github.com/skss25/JavaExamples
|
ae18470bf2fa38d1872025fc96c8c27816869dd5
|
f94c9e5e28d5a4b9dece1e7ee918f0a4275d26aa
|
refs/heads/master
| 2020-03-30T15:25:31.109000 | 2018-10-06T01:25:11 | 2018-10-06T01:25:11 | 149,774,909 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package chap8;
//369p 예제 : 인터페이스 배열로 구현 객체 관리
public class Car1 {
Tire[] tires = {
new HankookTire(),
new HankookTire(),
new HankookTire(),
new HankookTire()
};
void run() {
for(Tire tire : tires) {
tire.roll();
}
}
}
|
UHC
|
Java
| 293 |
java
|
Car1.java
|
Java
|
[] | null |
[] |
package chap8;
//369p 예제 : 인터페이스 배열로 구현 객체 관리
public class Car1 {
Tire[] tires = {
new HankookTire(),
new HankookTire(),
new HankookTire(),
new HankookTire()
};
void run() {
for(Tire tire : tires) {
tire.roll();
}
}
}
| 293 | 0.547893 | 0.528736 | 17 | 13.352942 | 9.492667 | 30 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.764706 | false | false |
3
|
260708e2bc9a87c28f3eae6507ddc74fcee4e609
| 14,070,312,862,432 |
8bd2fb80031229f4135f6c1df82ade1225750dfa
|
/morip/src/main/java/hashtag/bean/HashtagDTO.java
|
4f65599d4fa08095296c447a53cc08c5f97db4d0
|
[] |
no_license
|
BaekGihwan/morip
|
https://github.com/BaekGihwan/morip
|
c00ecea622fdd6e08fe87ac6522b3631b71b08a4
|
a779a77a00c9bf95d5aeb5f3d4bf08e97be20eb8
|
refs/heads/master
| 2022-12-21T06:29:38.040000 | 2020-09-14T00:56:57 | 2020-09-14T00:56:57 | 285,704,827 | 2 | 17 | null | false | 2020-09-14T00:56:58 | 2020-08-07T01:06:58 | 2020-09-08T12:45:20 | 2020-09-14T00:56:57 | 484,817 | 2 | 6 | 0 |
JavaScript
| false | false |
package hashtag.bean;
import lombok.Data;
@Data
public class HashtagDTO {
private int blogBoardTable_Seq;
private String hashtag;
}
|
UTF-8
|
Java
| 136 |
java
|
HashtagDTO.java
|
Java
|
[] | null |
[] |
package hashtag.bean;
import lombok.Data;
@Data
public class HashtagDTO {
private int blogBoardTable_Seq;
private String hashtag;
}
| 136 | 0.779412 | 0.779412 | 9 | 14.111111 | 11.836332 | 32 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false |
3
|
cbffb9141c951032812d9f6a6e6c96137b692f79
| 16,183,436,798,575 |
180656cc0db8f3b0b0b08510e3e0a58a47bea846
|
/src/Ch14/Exercise/CompilerIntelligence.java
|
a9d8b822ac9e04247eda254ce88ac54054239653
|
[] |
no_license
|
HBhakunamatata/TiJ
|
https://github.com/HBhakunamatata/TiJ
|
eca8e5dc5f1aa0a1663dc2ab2fbeac4d18aa873f
|
82da59a3aff2bdf600e5055e979100d47923a239
|
refs/heads/master
| 2021-12-15T18:54:21.068000 | 2021-12-08T13:23:43 | 2021-12-08T13:23:43 | 232,248,386 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package Ch14.Exercise;
import java.util.*;
public class CompilerIntelligence {
public static void main(String[] args) {
List <? extends Fruit> flist = Arrays.asList(new Apple());
// flist.add(new Apple()); // still cannot
Apple apple = (Apple) flist.get(0);
System.out.println(apple);
System.out.println(flist.contains(new Apple()));
}
}
|
UTF-8
|
Java
| 392 |
java
|
CompilerIntelligence.java
|
Java
|
[] | null |
[] |
package Ch14.Exercise;
import java.util.*;
public class CompilerIntelligence {
public static void main(String[] args) {
List <? extends Fruit> flist = Arrays.asList(new Apple());
// flist.add(new Apple()); // still cannot
Apple apple = (Apple) flist.get(0);
System.out.println(apple);
System.out.println(flist.contains(new Apple()));
}
}
| 392 | 0.622449 | 0.614796 | 16 | 23.5 | 22.767851 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4375 | false | false |
3
|
aa147eb248a0e1206d25eb93d8fe1b13bb42d883
| 8,821,862,892,076 |
f4a7a8f0eeba22db6c5eca223d7724abeeb739c5
|
/Leecode/src/easy/RemoveDuplicatesfromSortedList_83.java
|
f4010b91f48336c326a90d62c85d1f34963c6021
|
[] |
no_license
|
lisiyan/leecode
|
https://github.com/lisiyan/leecode
|
b49cbf69940802d0839f7aa3f79bd32ecf9db449
|
1a1fb1cfeabbf69366839978fea8e4e827b0f7a7
|
refs/heads/master
| 2021-01-10T08:45:37.057000 | 2016-03-22T10:47:37 | 2016-03-22T10:47:37 | 51,676,591 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package easy;
public class RemoveDuplicatesfromSortedList_83 {
public ListNode deleteDuplicates(ListNode head) {
ListNode current=head;
while(current!=null){
ListNode next=current.next;
if(next==null)
break;
if(current.val==next.val){
current.next=next.next;
continue;
}
current=current.next;
}
return head;
}
}
|
UTF-8
|
Java
| 437 |
java
|
RemoveDuplicatesfromSortedList_83.java
|
Java
|
[] | null |
[] |
package easy;
public class RemoveDuplicatesfromSortedList_83 {
public ListNode deleteDuplicates(ListNode head) {
ListNode current=head;
while(current!=null){
ListNode next=current.next;
if(next==null)
break;
if(current.val==next.val){
current.next=next.next;
continue;
}
current=current.next;
}
return head;
}
}
| 437 | 0.556064 | 0.551487 | 18 | 22.277779 | 14.375154 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.222222 | false | false |
3
|
1d13d873b27fe667087698947913a3f75090a867
| 27,084,063,769,239 |
50c3ace4193dfb1e29f099ea4fc30ac6a11344f2
|
/circle_line_progressbar/src/main/java/com/example/circle_line_progressbar/View/ImgView.java
|
583624177db04813853a3a7cd0b6cfca5d292ab3
|
[] |
no_license
|
YYwishp/MyDemo
|
https://github.com/YYwishp/MyDemo
|
e4b6f5c6d2f613c8fbb27cdaf67284984ad38771
|
dfaec6171f0c79aae55643c9f16cf7ef94e274ed
|
refs/heads/master
| 2021-03-16T07:57:28.481000 | 2018-07-28T07:02:46 | 2018-07-28T07:02:46 | 111,404,542 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.circle_line_progressbar.View;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import com.example.circle_line_progressbar.R;
/**
* Created by gyx on 2018/1/17.
*/
public class ImgView extends View {
private Bitmap mBitmap;
private Paint mPaint;// 画笔
public ImgView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.abc);
// 实例化画笔并打开抗锯齿
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//声明一个临时变量来存储计算出的测量值
int resultWidth = 0;
//获取宽度测量规格中的mode
int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
//获取宽度测量规格中的size
int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
/**
* 如果爹心里有数
*/
if (modeWidth == MeasureSpec.EXACTLY) {
//那么儿子也不要让爹为难,就取爹给的大小吧
resultWidth = sizeWidth;
}
/**
* 如果爹心里没数
*/
else {
//那么儿子可是要自己看看自己需要多大了
resultWidth = mBitmap.getWidth()+getPaddingLeft()+getPaddingRight();
/**
* 如果爹给儿子的是一个限制值
*/
if (modeWidth == MeasureSpec.AT_MOST) {
//那么儿子自己的需求就要跟爹的限制比比看谁最小
resultWidth = Math.min(resultWidth, sizeWidth);
}
}
int resultHeight = 0;
int modeHeight = MeasureSpec.getMode(heightMeasureSpec);
int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);
if (modeHeight == MeasureSpec.EXACTLY) {
resultHeight = sizeHeight;
} else {
resultHeight = mBitmap.getHeight()+getPaddingTop()+getPaddingBottom();
if (modeHeight == MeasureSpec.AT_MOST) {
resultHeight = Math.min(resultHeight, sizeHeight);
}
}
//设置测量尺寸
setMeasuredDimension(resultWidth, resultHeight);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawBitmap(mBitmap, getPaddingLeft(), getPaddingTop(), mPaint);
}
}
|
UTF-8
|
Java
| 2,516 |
java
|
ImgView.java
|
Java
|
[
{
"context": "mple.circle_line_progressbar.R;\n\n/**\n * Created by gyx on 2018/1/17.\n */\npublic class ImgView extends Vi",
"end": 463,
"score": 0.9995908737182617,
"start": 460,
"tag": "USERNAME",
"value": "gyx"
}
] | null |
[] |
package com.example.circle_line_progressbar.View;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import com.example.circle_line_progressbar.R;
/**
* Created by gyx on 2018/1/17.
*/
public class ImgView extends View {
private Bitmap mBitmap;
private Paint mPaint;// 画笔
public ImgView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.abc);
// 实例化画笔并打开抗锯齿
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//声明一个临时变量来存储计算出的测量值
int resultWidth = 0;
//获取宽度测量规格中的mode
int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
//获取宽度测量规格中的size
int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
/**
* 如果爹心里有数
*/
if (modeWidth == MeasureSpec.EXACTLY) {
//那么儿子也不要让爹为难,就取爹给的大小吧
resultWidth = sizeWidth;
}
/**
* 如果爹心里没数
*/
else {
//那么儿子可是要自己看看自己需要多大了
resultWidth = mBitmap.getWidth()+getPaddingLeft()+getPaddingRight();
/**
* 如果爹给儿子的是一个限制值
*/
if (modeWidth == MeasureSpec.AT_MOST) {
//那么儿子自己的需求就要跟爹的限制比比看谁最小
resultWidth = Math.min(resultWidth, sizeWidth);
}
}
int resultHeight = 0;
int modeHeight = MeasureSpec.getMode(heightMeasureSpec);
int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);
if (modeHeight == MeasureSpec.EXACTLY) {
resultHeight = sizeHeight;
} else {
resultHeight = mBitmap.getHeight()+getPaddingTop()+getPaddingBottom();
if (modeHeight == MeasureSpec.AT_MOST) {
resultHeight = Math.min(resultHeight, sizeHeight);
}
}
//设置测量尺寸
setMeasuredDimension(resultWidth, resultHeight);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawBitmap(mBitmap, getPaddingLeft(), getPaddingTop(), mPaint);
}
}
| 2,516 | 0.725763 | 0.721723 | 89 | 23.685392 | 21.832146 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.853933 | false | false |
3
|
a615b152920984b82eb2bdf5a238877abad832d0
| 31,301,721,661,487 |
5021452137fb748aff160c9b8ef636e6ef5b960e
|
/src/main/java/com/up/jdk8/Array.java
|
e06a1f29d26c2cb2101e625327b844c6f51b8ee6
|
[] |
no_license
|
CarvilMars/dsal-source-all
|
https://github.com/CarvilMars/dsal-source-all
|
122457ec6133b1c77fc5afb9f4285a49703e3a80
|
236784b6b8ae02731814c83b188a894af08f99a2
|
refs/heads/main
| 2023-01-31T00:28:19.982000 | 2020-12-16T09:56:03 | 2020-12-16T09:56:03 | 321,831,064 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.up.jdk8;
import cn.hutool.core.util.ArrayUtil;
import org.springframework.util.StopWatch;
import java.util.Arrays;
import java.util.OptionalInt;
/**
* @author songdaxin
*/
public class Array {
public static void main(String[] args) {
int[] arr = new int[]{1, 5, 4, 3, 1};
OptionalInt max = Arrays.stream(arr).max();
System.out.println(max.getAsInt());
System.out.println(ArrayUtil.max(arr));
StopWatch stopWatch = new StopWatch();
stopWatch.start();
Arrays.sort(arr);
stopWatch.stop();
System.out.println(Arrays.toString(arr) + "耗时:"+stopWatch.getTotalTimeMillis());
}
}
|
UTF-8
|
Java
| 674 |
java
|
Array.java
|
Java
|
[
{
"context": "ays;\nimport java.util.OptionalInt;\n\n/**\n * @author songdaxin\n */\npublic class Array {\n public static void m",
"end": 184,
"score": 0.9996103048324585,
"start": 175,
"tag": "USERNAME",
"value": "songdaxin"
}
] | null |
[] |
package com.up.jdk8;
import cn.hutool.core.util.ArrayUtil;
import org.springframework.util.StopWatch;
import java.util.Arrays;
import java.util.OptionalInt;
/**
* @author songdaxin
*/
public class Array {
public static void main(String[] args) {
int[] arr = new int[]{1, 5, 4, 3, 1};
OptionalInt max = Arrays.stream(arr).max();
System.out.println(max.getAsInt());
System.out.println(ArrayUtil.max(arr));
StopWatch stopWatch = new StopWatch();
stopWatch.start();
Arrays.sort(arr);
stopWatch.stop();
System.out.println(Arrays.toString(arr) + "耗时:"+stopWatch.getTotalTimeMillis());
}
}
| 674 | 0.642216 | 0.633234 | 24 | 26.833334 | 21.330078 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false |
3
|
0688a69f9c80ec6a3ce99338412c21f666c9a518
| 6,897,717,482,701 |
d1f7ea9893d7e10790ae848bd5646615922b3ef0
|
/TD/TD5/Copy.java
|
ddfb9922230eca02649ce0679ab48b9bcd1d1e79
|
[] |
no_license
|
ewilys/ELP
|
https://github.com/ewilys/ELP
|
6227687473eeb673f288ce65da58281e69eae6b3
|
0c35e9d3e36a3dec56d4f8cd47ca527097ed9ae6
|
refs/heads/master
| 2016-09-14T10:02:33.015000 | 2016-05-22T14:16:53 | 2016-05-22T14:16:53 | 59,375,642 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.util.*;
import java.io.*;
public class Copy{
public static void main (String[]args) throws IOException, FileNotFoundException{
InputStream fin ;
OutputStream fout;
switch(args.length){
case 2 :
fin=new FileInputStream(new File(args[0]));
fout=new FileOutputStream(new File(args[1]));
break;
case 1 :
fin=new FileInputStream(new File (args[0]));
fout=System.out;
break;
default:
fin=System.in;
fout=System.out;
break;
}
copy(fin, fout);
fin.close();
fout.close();
}
private static void copy(InputStream is, OutputStream os) throws IOException {
int octet=is.read();
while ( octet !=-1) {
os.write(octet);
octet=is.read();
}
}
}
|
UTF-8
|
Java
| 739 |
java
|
Copy.java
|
Java
|
[] | null |
[] |
import java.util.*;
import java.io.*;
public class Copy{
public static void main (String[]args) throws IOException, FileNotFoundException{
InputStream fin ;
OutputStream fout;
switch(args.length){
case 2 :
fin=new FileInputStream(new File(args[0]));
fout=new FileOutputStream(new File(args[1]));
break;
case 1 :
fin=new FileInputStream(new File (args[0]));
fout=System.out;
break;
default:
fin=System.in;
fout=System.out;
break;
}
copy(fin, fout);
fin.close();
fout.close();
}
private static void copy(InputStream is, OutputStream os) throws IOException {
int octet=is.read();
while ( octet !=-1) {
os.write(octet);
octet=is.read();
}
}
}
| 739 | 0.630582 | 0.622463 | 46 | 15.065217 | 18.779501 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.326087 | false | false |
3
|
3b99a23123fd6d3884e39281dc3be0b7f4ed051c
| 18,159,121,796,328 |
7e54d5f8ee24b3ba1db94405bdbaaee5dbda6c59
|
/nacionesRugby/src/nacionesRugby/Partido.java
|
8dd0d021fce6af6a5c80c8b9b48000fba2eb7db5
|
[] |
no_license
|
Manumk13/practicarugby
|
https://github.com/Manumk13/practicarugby
|
d4817e5f59dbc1f8f283969c2c7e4f3bfd484f49
|
32d5237f0345e4766238ed6fe2ebf93fd6505cea
|
refs/heads/master
| 2021-03-29T17:28:35.426000 | 2020-03-17T14:56:32 | 2020-03-17T14:56:32 | 247,970,549 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package nacionesRugby;
public class Partido {
private int puntosLocal;
private int puntosVisitante;
private int bonusLocal;
private int bonusVisitante;
public Arbitro arbitra;
public Equipo equipoLocal;
public Equipo equipoVisitante;
public Partido(int puntosLocal, int puntosVisitante, int bonusLocal, int bonusVisitante) {
this.puntosLocal = puntosLocal;
this.puntosVisitante = puntosVisitante;
this.bonusLocal = bonusLocal;
this.bonusVisitante = bonusVisitante;
}
public int getPuntosLocal() {
return puntosLocal;
}
public void setPuntosLocal(int puntosLocal) {
this.puntosLocal = puntosLocal;
}
public int getPuntosVisitante() {
return puntosVisitante;
}
public void setPuntosVisitante(int puntosVisitante) {
this.puntosVisitante = puntosVisitante;
}
public int getBonusLocal() {
return bonusLocal;
}
public void setBonusLocal(int bonusLocal) {
this.bonusLocal = bonusLocal;
}
public int getBonusVisitante() {
return bonusVisitante;
}
public void setBonusVisitante(int bonusVisitante) {
this.bonusVisitante = bonusVisitante;
}
public void resultado() {
}
}
|
UTF-8
|
Java
| 1,180 |
java
|
Partido.java
|
Java
|
[] | null |
[] |
package nacionesRugby;
public class Partido {
private int puntosLocal;
private int puntosVisitante;
private int bonusLocal;
private int bonusVisitante;
public Arbitro arbitra;
public Equipo equipoLocal;
public Equipo equipoVisitante;
public Partido(int puntosLocal, int puntosVisitante, int bonusLocal, int bonusVisitante) {
this.puntosLocal = puntosLocal;
this.puntosVisitante = puntosVisitante;
this.bonusLocal = bonusLocal;
this.bonusVisitante = bonusVisitante;
}
public int getPuntosLocal() {
return puntosLocal;
}
public void setPuntosLocal(int puntosLocal) {
this.puntosLocal = puntosLocal;
}
public int getPuntosVisitante() {
return puntosVisitante;
}
public void setPuntosVisitante(int puntosVisitante) {
this.puntosVisitante = puntosVisitante;
}
public int getBonusLocal() {
return bonusLocal;
}
public void setBonusLocal(int bonusLocal) {
this.bonusLocal = bonusLocal;
}
public int getBonusVisitante() {
return bonusVisitante;
}
public void setBonusVisitante(int bonusVisitante) {
this.bonusVisitante = bonusVisitante;
}
public void resultado() {
}
}
| 1,180 | 0.728814 | 0.728814 | 98 | 11.040816 | 17.301008 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.877551 | false | false |
3
|
db6b6224076410c3ccf255a821f4359a2336f287
| 1,967,095,046,846 |
54ee2cc4ad95cea30b39e43426771420556b25cb
|
/src/test/java/com/datasync/models/barco/embarcacao/TesteTblcombustivelembarcacao.java
|
470bbbf62f7ac5d65c0f59c8c035c201f692f9fc
|
[] |
no_license
|
tulios/datasync
|
https://github.com/tulios/datasync
|
55bb518733a0201c66c5f927d9160e5ba6edebaf
|
9773cf4f084a9a5dae133da4d4d0d0a5df49ba2c
|
refs/heads/master
| 2016-09-05T19:23:37.657000 | 2010-06-09T01:00:35 | 2010-06-09T01:00:35 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.datasync.models.barco.embarcacao;
import static org.junit.Assert.assertEquals;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.junit.Test;
import com.datasync.models.TesteBarco;
import com.datasync.models.IndexableEntity;
import com.datasync.models.barco.embarcacao.Tblcombustivelembarcacao;
import com.datasync.processor.IndexProcessor;
import com.datasync.service.SyncDatabasesService;
import com.datasync.service.runner.ServiceRunner;
import com.datasync.service.runner.SyncServiceRunner;
public class TesteTblcombustivelembarcacao extends TesteBarco {
@Test
public void verificaSincronismo() throws Exception{
open();
List<IndexableEntity> indexables = new ArrayList<IndexableEntity>();
indexables.add(new Tblcombustivelembarcacao());
Number local = (Number) getLocalEm().createQuery("select count(t.idformulario) from Tblcombustivelembarcacao t").getSingleResult();
assertEquals(0, local.intValue());
Number server = (Number) getServerEm().createQuery("select count(t.idformulario) from Tblcombustivelembarcacao t").getSingleResult();
assertEquals(0, server.intValue());
Tblcabecalhoembarcacao cabecalho = new Tblcabecalhoembarcacao();
cabecalho.setIdformulario("1");
cabecalho.setPesquisador("Pesquisador");
cabecalho.setData(new Timestamp(new Date().getTime()));
cabecalho.setIdmunicipio(1);
cabecalho.setIdrota(1);
cabecalho.setRota("rota");
cabecalho.setHorainicial("10:10");
cabecalho.setHorafinal("11:10");
getLocalEm().persist(cabecalho);
getServerEm().persist(cabecalho);
Tblcaracterizacaoembarcacao caracterizacaoEmbarcacao = new Tblcaracterizacaoembarcacao();
caracterizacaoEmbarcacao.setIdformulario("1");
caracterizacaoEmbarcacao.setTipopropulsao(1);
caracterizacaoEmbarcacao.setQuaisoutraspropulsao("outro");
caracterizacaoEmbarcacao.setQuantidademotores(1);
caracterizacaoEmbarcacao.setSabepotenciamotor1("não");
caracterizacaoEmbarcacao.setSabepotenciamotor2("não");
caracterizacaoEmbarcacao.setSabepotenciamotor3("não");
caracterizacaoEmbarcacao.setPotenciamotor1("100");
caracterizacaoEmbarcacao.setMarcamotor1("marca");
caracterizacaoEmbarcacao.setModelomotor1("modelo");
caracterizacaoEmbarcacao.setPotenciamotor2("100");
caracterizacaoEmbarcacao.setMarcamotor2("marca");
caracterizacaoEmbarcacao.setModelomotor2("modelo");
caracterizacaoEmbarcacao.setPotenciamotor3("100");
caracterizacaoEmbarcacao.setMarcamotor3("marca");
caracterizacaoEmbarcacao.setModelomotor3("modelo");
caracterizacaoEmbarcacao.setPossuireverso("não");
caracterizacaoEmbarcacao.setMarcareverso("marca");
caracterizacaoEmbarcacao.setRelacaoreverso("relacao");
caracterizacaoEmbarcacao.setComandomotor(1);
caracterizacaoEmbarcacao.setQuaisoutroscomandos("quais");
caracterizacaoEmbarcacao.setSabelitros1("não");
caracterizacaoEmbarcacao.setQuantidadelitros1("10");
caracterizacaoEmbarcacao.setSabelitros2("não");
caracterizacaoEmbarcacao.setQuantidadelitros2("10");
caracterizacaoEmbarcacao.setSabelitros3("não");
caracterizacaoEmbarcacao.setQuantidadelitros3("10");
caracterizacaoEmbarcacao.setPosicaocomando(1);
getLocalEm().persist(caracterizacaoEmbarcacao);
getServerEm().persist(caracterizacaoEmbarcacao);
Tblcombustivelembarcacao var = new Tblcombustivelembarcacao();
var.setIdformulario("1");
var.setIdtipocombustivel(1);
var.setQuaisoutros("quais");
getLocalEm().persist(var);
local = (Number) getLocalEm().createQuery("select count(t.idformulario) from Tblcombustivelembarcacao t").getSingleResult();
assertEquals(1, local.intValue());
IndexProcessor processor = new IndexProcessor();
assertEquals(0, processor.getIdsList(var.getFullClassName()).size());
close();
ServiceRunner runner = new SyncServiceRunner();
runner.run(new SyncDatabasesService(indexables));
processor = new IndexProcessor();
assertEquals(1, processor.getIdsList(var.getFullClassName()).size());
open();
server = (Number) getServerEm().createQuery("select count(t.idformulario) from Tblcombustivelembarcacao t").getSingleResult();
assertEquals(1, server.intValue());
close();
}
}
|
UTF-8
|
Java
| 4,613 |
java
|
TesteTblcombustivelembarcacao.java
|
Java
|
[
{
"context": "ormulario(\"1\");\n cabecalho.setPesquisador(\"Pesquisador\");\n cabecalho.setData(new Timestamp(new Da",
"end": 1384,
"score": 0.6981765627861023,
"start": 1373,
"tag": "NAME",
"value": "Pesquisador"
}
] | null |
[] |
package com.datasync.models.barco.embarcacao;
import static org.junit.Assert.assertEquals;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.junit.Test;
import com.datasync.models.TesteBarco;
import com.datasync.models.IndexableEntity;
import com.datasync.models.barco.embarcacao.Tblcombustivelembarcacao;
import com.datasync.processor.IndexProcessor;
import com.datasync.service.SyncDatabasesService;
import com.datasync.service.runner.ServiceRunner;
import com.datasync.service.runner.SyncServiceRunner;
public class TesteTblcombustivelembarcacao extends TesteBarco {
@Test
public void verificaSincronismo() throws Exception{
open();
List<IndexableEntity> indexables = new ArrayList<IndexableEntity>();
indexables.add(new Tblcombustivelembarcacao());
Number local = (Number) getLocalEm().createQuery("select count(t.idformulario) from Tblcombustivelembarcacao t").getSingleResult();
assertEquals(0, local.intValue());
Number server = (Number) getServerEm().createQuery("select count(t.idformulario) from Tblcombustivelembarcacao t").getSingleResult();
assertEquals(0, server.intValue());
Tblcabecalhoembarcacao cabecalho = new Tblcabecalhoembarcacao();
cabecalho.setIdformulario("1");
cabecalho.setPesquisador("Pesquisador");
cabecalho.setData(new Timestamp(new Date().getTime()));
cabecalho.setIdmunicipio(1);
cabecalho.setIdrota(1);
cabecalho.setRota("rota");
cabecalho.setHorainicial("10:10");
cabecalho.setHorafinal("11:10");
getLocalEm().persist(cabecalho);
getServerEm().persist(cabecalho);
Tblcaracterizacaoembarcacao caracterizacaoEmbarcacao = new Tblcaracterizacaoembarcacao();
caracterizacaoEmbarcacao.setIdformulario("1");
caracterizacaoEmbarcacao.setTipopropulsao(1);
caracterizacaoEmbarcacao.setQuaisoutraspropulsao("outro");
caracterizacaoEmbarcacao.setQuantidademotores(1);
caracterizacaoEmbarcacao.setSabepotenciamotor1("não");
caracterizacaoEmbarcacao.setSabepotenciamotor2("não");
caracterizacaoEmbarcacao.setSabepotenciamotor3("não");
caracterizacaoEmbarcacao.setPotenciamotor1("100");
caracterizacaoEmbarcacao.setMarcamotor1("marca");
caracterizacaoEmbarcacao.setModelomotor1("modelo");
caracterizacaoEmbarcacao.setPotenciamotor2("100");
caracterizacaoEmbarcacao.setMarcamotor2("marca");
caracterizacaoEmbarcacao.setModelomotor2("modelo");
caracterizacaoEmbarcacao.setPotenciamotor3("100");
caracterizacaoEmbarcacao.setMarcamotor3("marca");
caracterizacaoEmbarcacao.setModelomotor3("modelo");
caracterizacaoEmbarcacao.setPossuireverso("não");
caracterizacaoEmbarcacao.setMarcareverso("marca");
caracterizacaoEmbarcacao.setRelacaoreverso("relacao");
caracterizacaoEmbarcacao.setComandomotor(1);
caracterizacaoEmbarcacao.setQuaisoutroscomandos("quais");
caracterizacaoEmbarcacao.setSabelitros1("não");
caracterizacaoEmbarcacao.setQuantidadelitros1("10");
caracterizacaoEmbarcacao.setSabelitros2("não");
caracterizacaoEmbarcacao.setQuantidadelitros2("10");
caracterizacaoEmbarcacao.setSabelitros3("não");
caracterizacaoEmbarcacao.setQuantidadelitros3("10");
caracterizacaoEmbarcacao.setPosicaocomando(1);
getLocalEm().persist(caracterizacaoEmbarcacao);
getServerEm().persist(caracterizacaoEmbarcacao);
Tblcombustivelembarcacao var = new Tblcombustivelembarcacao();
var.setIdformulario("1");
var.setIdtipocombustivel(1);
var.setQuaisoutros("quais");
getLocalEm().persist(var);
local = (Number) getLocalEm().createQuery("select count(t.idformulario) from Tblcombustivelembarcacao t").getSingleResult();
assertEquals(1, local.intValue());
IndexProcessor processor = new IndexProcessor();
assertEquals(0, processor.getIdsList(var.getFullClassName()).size());
close();
ServiceRunner runner = new SyncServiceRunner();
runner.run(new SyncDatabasesService(indexables));
processor = new IndexProcessor();
assertEquals(1, processor.getIdsList(var.getFullClassName()).size());
open();
server = (Number) getServerEm().createQuery("select count(t.idformulario) from Tblcombustivelembarcacao t").getSingleResult();
assertEquals(1, server.intValue());
close();
}
}
| 4,613 | 0.728615 | 0.71624 | 105 | 42.866665 | 30.380779 | 141 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.828571 | false | false |
3
|
65fc8e33b9d99db38059885d13d6a0b56bb224c5
| 25,924,422,663,480 |
c118eb69df3800177ee0cc0f238291b01e3c5d4a
|
/src/main/java/cc/wanforme/munkblog/vo/blog/BlogResultRecorder.java
|
682f2439f8a34c30f102e64a365c00d5b96612e8
|
[] |
no_license
|
WanneSimon/MunkBlog-core
|
https://github.com/WanneSimon/MunkBlog-core
|
0748c9385af1c39fbdf154fc7af28e2abaf24509
|
6e4aba03267fcbb563aca02fa15f35100d5226f8
|
refs/heads/master
| 2023-07-17T18:33:49.556000 | 2021-09-05T14:02:56 | 2021-09-05T14:02:56 | 296,317,014 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package cc.wanforme.munkblog.vo.blog;
import java.time.LocalDateTime;
/** 搜索结果中的记录
* @author wanne
* 2020年9月20日
*/
public class BlogResultRecorder {
private int id;
// 标题
private String title;
// 编辑器类型
private String editor;
// 创建时间
private LocalDateTime createTime;
// 更新时间
private LocalDateTime updateTime;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getEditor() {
return editor;
}
public void setEditor(String editor) {
this.editor = editor;
}
public LocalDateTime getCreateTime() {
return createTime;
}
public void setCreateTime(LocalDateTime createTime) {
this.createTime = createTime;
}
public LocalDateTime getUpdateTime() {
return updateTime;
}
public void setUpdateTime(LocalDateTime updateTime) {
this.updateTime = updateTime;
}
}
|
UTF-8
|
Java
| 1,058 |
java
|
BlogResultRecorder.java
|
Java
|
[
{
"context": "va.time.LocalDateTime;\r\n\r\n/** 搜索结果中的记录\r\n * @author wanne\r\n * 2020年9月20日\r\n */\r\npublic class BlogResultRecor",
"end": 106,
"score": 0.9989438652992249,
"start": 101,
"tag": "USERNAME",
"value": "wanne"
}
] | null |
[] |
package cc.wanforme.munkblog.vo.blog;
import java.time.LocalDateTime;
/** 搜索结果中的记录
* @author wanne
* 2020年9月20日
*/
public class BlogResultRecorder {
private int id;
// 标题
private String title;
// 编辑器类型
private String editor;
// 创建时间
private LocalDateTime createTime;
// 更新时间
private LocalDateTime updateTime;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getEditor() {
return editor;
}
public void setEditor(String editor) {
this.editor = editor;
}
public LocalDateTime getCreateTime() {
return createTime;
}
public void setCreateTime(LocalDateTime createTime) {
this.createTime = createTime;
}
public LocalDateTime getUpdateTime() {
return updateTime;
}
public void setUpdateTime(LocalDateTime updateTime) {
this.updateTime = updateTime;
}
}
| 1,058 | 0.675944 | 0.668986 | 53 | 16.981133 | 14.812654 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.320755 | false | false |
3
|
1d5854a7dcbafd509e7b84c0b2452061332fde8a
| 3,874,060,534,684 |
d6b80d991f03359693bbc272dd7302898d58b3e7
|
/src/generalpurpose/TwilioSMS.java
|
5b14a81e6b4530e465b213e56302bbcb6ac7db18
|
[] |
no_license
|
GubarevDev/Example
|
https://github.com/GubarevDev/Example
|
d17063a5bd8e7da6d224a4854ec8b8f707d6a6b6
|
0ce677fbb6fac32b3da50c038bfbc2b7574227ee
|
refs/heads/master
| 2020-01-07T02:15:35.279000 | 2015-09-18T16:08:23 | 2015-09-18T16:08:23 | 42,748,314 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package generalpurpose;
/**
* Created by Artem.Gubarev on 10.06.2015.
*/
import com.twilio.sdk.TwilioRestClient;
import com.twilio.sdk.TwilioRestException;
import com.twilio.sdk.resource.factory.MessageFactory;
import com.twilio.sdk.resource.instance.Message;
import com.twilio.sdk.resource.instance.Sms;
import com.twilio.sdk.resource.list.SmsList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TwilioSMS {
protected String errorMessage;
protected String accountSid;
protected String authToken;
protected String phoneNumberTwilio;
public TwilioSMS(String sid, String token, String phoneTwilio) {
accountSid = sid;
authToken = token;
phoneNumberTwilio = phoneTwilio;
}
public String getErrorMessage() {
return errorMessage;
}
public boolean sendSMSToPhoneNumber(String phoneNumber, String textMessage) {
TwilioRestClient client = new TwilioRestClient(accountSid, authToken);
// Build a filter for the MessageList
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Body", textMessage));
params.add(new BasicNameValuePair("To", phoneNumber));
params.add(new BasicNameValuePair("From", phoneNumberTwilio));
MessageFactory messageFactory = client.getAccount().getMessageFactory();
try {
Message message = messageFactory.create(params);
return true;
} catch (TwilioRestException e) {
errorMessage = "Problem with sending message by Twilio";
return false;
}
}
public boolean grabListSMSbyPhoneNumberCheckBody(String phoneNumber, String textMessage) {
// waiting message from dashboard - timeout for TWILIO
waitTime(MainConfig.timeout_for_AJAX * 2);
TwilioRestClient client = new TwilioRestClient(accountSid, authToken);
// prepare filters
// get current date
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
String formatted = format1.format(new java.util.Date());
HashMap<String, String> filters = new HashMap<String, String>();
filters.put("From", phoneNumber);
filters.put("To", phoneNumberTwilio);
filters.put("DateSent", formatted);
SmsList messages = client.getAccount().getSmsMessages(filters);
for (Sms message : messages) {
if (message.getBody().contains(textMessage)) {
return true;
}
}
errorMessage = "SMS with text: " + textMessage + " is not found. Message has not been sent to the client";
return false;
}
public String lastInboundSMSWithValidationCode() {
String lastMessage = "";
// waiting message from dashboard - timeout for TWILIO
waitTime(MainConfig.timeout_for_AJAX * 2);
TwilioRestClient client = new TwilioRestClient(accountSid, authToken);
// prepare filters
// get current date
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
String formatted = format1.format(new java.util.Date());
HashMap<String, String> filters = new HashMap<String, String>();
filters.put("To", phoneNumberTwilio);
filters.put("DateSent", formatted);
Pattern pattern;
pattern = Pattern.compile(MainConfig.VALIDATION_CODE_PATTERN);
Matcher matcher;
SmsList messages = client.getAccount().getSmsMessages(filters);
for (Sms message : messages) {
matcher = pattern.matcher(message.getBody());
if (matcher.find()) {
lastMessage = matcher.group();
return lastMessage;
}
}
return lastMessage;
}
public void waitTime(int Seconds) {
try {
Thread.sleep(Seconds * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// check only last SMS Received Twilio
public boolean grabLastSMSbyPhoneNumberCheckBody(String phoneNumber, String textMessage) {
// waiting message from dashboard - timeout for TWILIO
waitTime(MainConfig.timeout_for_AJAX * 2);
TwilioRestClient client = new TwilioRestClient(accountSid, authToken);
// prepare filters
// get current date
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
String formatted = format1.format(new java.util.Date());
HashMap<String, String> filters = new HashMap<String, String>();
filters.put("From", phoneNumber);
filters.put("To", phoneNumberTwilio);
filters.put("DateSent", formatted);
SmsList messages = client.getAccount().getSmsMessages(filters);
Sms message = messages.getPageData().get(0);
if (message.getBody().contains(textMessage)) {
return true;
}
errorMessage = "Last received SMS not contain text: " + textMessage;
return false;
}
}
|
UTF-8
|
Java
| 5,232 |
java
|
TwilioSMS.java
|
Java
|
[
{
"context": "package generalpurpose;\n\n/**\n * Created by Artem.Gubarev on 10.06.2015.\n */\n\nimport com.twilio.sdk.TwilioR",
"end": 56,
"score": 0.9998795390129089,
"start": 43,
"tag": "NAME",
"value": "Artem.Gubarev"
}
] | null |
[] |
package generalpurpose;
/**
* Created by Artem.Gubarev on 10.06.2015.
*/
import com.twilio.sdk.TwilioRestClient;
import com.twilio.sdk.TwilioRestException;
import com.twilio.sdk.resource.factory.MessageFactory;
import com.twilio.sdk.resource.instance.Message;
import com.twilio.sdk.resource.instance.Sms;
import com.twilio.sdk.resource.list.SmsList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TwilioSMS {
protected String errorMessage;
protected String accountSid;
protected String authToken;
protected String phoneNumberTwilio;
public TwilioSMS(String sid, String token, String phoneTwilio) {
accountSid = sid;
authToken = token;
phoneNumberTwilio = phoneTwilio;
}
public String getErrorMessage() {
return errorMessage;
}
public boolean sendSMSToPhoneNumber(String phoneNumber, String textMessage) {
TwilioRestClient client = new TwilioRestClient(accountSid, authToken);
// Build a filter for the MessageList
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Body", textMessage));
params.add(new BasicNameValuePair("To", phoneNumber));
params.add(new BasicNameValuePair("From", phoneNumberTwilio));
MessageFactory messageFactory = client.getAccount().getMessageFactory();
try {
Message message = messageFactory.create(params);
return true;
} catch (TwilioRestException e) {
errorMessage = "Problem with sending message by Twilio";
return false;
}
}
public boolean grabListSMSbyPhoneNumberCheckBody(String phoneNumber, String textMessage) {
// waiting message from dashboard - timeout for TWILIO
waitTime(MainConfig.timeout_for_AJAX * 2);
TwilioRestClient client = new TwilioRestClient(accountSid, authToken);
// prepare filters
// get current date
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
String formatted = format1.format(new java.util.Date());
HashMap<String, String> filters = new HashMap<String, String>();
filters.put("From", phoneNumber);
filters.put("To", phoneNumberTwilio);
filters.put("DateSent", formatted);
SmsList messages = client.getAccount().getSmsMessages(filters);
for (Sms message : messages) {
if (message.getBody().contains(textMessage)) {
return true;
}
}
errorMessage = "SMS with text: " + textMessage + " is not found. Message has not been sent to the client";
return false;
}
public String lastInboundSMSWithValidationCode() {
String lastMessage = "";
// waiting message from dashboard - timeout for TWILIO
waitTime(MainConfig.timeout_for_AJAX * 2);
TwilioRestClient client = new TwilioRestClient(accountSid, authToken);
// prepare filters
// get current date
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
String formatted = format1.format(new java.util.Date());
HashMap<String, String> filters = new HashMap<String, String>();
filters.put("To", phoneNumberTwilio);
filters.put("DateSent", formatted);
Pattern pattern;
pattern = Pattern.compile(MainConfig.VALIDATION_CODE_PATTERN);
Matcher matcher;
SmsList messages = client.getAccount().getSmsMessages(filters);
for (Sms message : messages) {
matcher = pattern.matcher(message.getBody());
if (matcher.find()) {
lastMessage = matcher.group();
return lastMessage;
}
}
return lastMessage;
}
public void waitTime(int Seconds) {
try {
Thread.sleep(Seconds * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// check only last SMS Received Twilio
public boolean grabLastSMSbyPhoneNumberCheckBody(String phoneNumber, String textMessage) {
// waiting message from dashboard - timeout for TWILIO
waitTime(MainConfig.timeout_for_AJAX * 2);
TwilioRestClient client = new TwilioRestClient(accountSid, authToken);
// prepare filters
// get current date
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
String formatted = format1.format(new java.util.Date());
HashMap<String, String> filters = new HashMap<String, String>();
filters.put("From", phoneNumber);
filters.put("To", phoneNumberTwilio);
filters.put("DateSent", formatted);
SmsList messages = client.getAccount().getSmsMessages(filters);
Sms message = messages.getPageData().get(0);
if (message.getBody().contains(textMessage)) {
return true;
}
errorMessage = "Last received SMS not contain text: " + textMessage;
return false;
}
}
| 5,232 | 0.660933 | 0.656728 | 134 | 38.044777 | 25.361818 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.761194 | false | false |
3
|
a26497a851cfaa829958908593325c3cddb1fd38
| 704,374,659,076 |
adcf00117af0383d338cac9305b4381b031e7d0f
|
/ares-cluster/src/main/java/com/cy/onepush/dcommon/raft/RFEventCst.java
|
586e308f96881fb74eb24650cd0554379ab45675
|
[] |
no_license
|
ChengYingOpenSource/ares
|
https://github.com/ChengYingOpenSource/ares
|
c3a47f746c155e3acf4267c594cd77d9f7e9ce20
|
b8768273a287a1b15d99522a40593e0b3bf3cd5c
|
refs/heads/master
| 2023-02-10T22:15:12.529000 | 2020-12-31T03:16:48 | 2020-12-31T03:16:48 | 302,838,544 | 19 | 2 | null | false | 2020-12-24T07:22:30 | 2020-10-10T07:07:11 | 2020-11-16T02:23:52 | 2020-12-24T07:22:29 | 5,560 | 9 | 1 | 0 |
Java
| false | false |
package com.cy.onepush.dcommon.raft;
public class RFEventCst {
// 投票通知
public static final String VOTE_NOTICE = "VOTE_NOTICE";
public static final String HEARTBEAT = "HEARTBEAT";
public static final String LOG_COMMIT = "LOG_COMMIT";
public static final String LOG_REPLICATION = "LOG_REPLICATION";
}
|
UTF-8
|
Java
| 353 |
java
|
RFEventCst.java
|
Java
|
[] | null |
[] |
package com.cy.onepush.dcommon.raft;
public class RFEventCst {
// 投票通知
public static final String VOTE_NOTICE = "VOTE_NOTICE";
public static final String HEARTBEAT = "HEARTBEAT";
public static final String LOG_COMMIT = "LOG_COMMIT";
public static final String LOG_REPLICATION = "LOG_REPLICATION";
}
| 353 | 0.669565 | 0.669565 | 14 | 23.642857 | 24.699934 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.357143 | false | false |
3
|
def9f684738a76231794e5b65a375b18961c75c5
| 21,483,426,442,339 |
f9c2ea2627916105922b641986628898273a5751
|
/app/src/main/java/org/jacr/instragramreader/model/api/managers/PopularMediaManager.java
|
4ee1de6ae8d29d6b09221e4e462551ae35478320
|
[] |
no_license
|
castrojr913/InstagramTrendReader
|
https://github.com/castrojr913/InstagramTrendReader
|
f203fff9a1645057ffa55c24d78f919eaded316c
|
11aea07a2dd7ed0a11fdc82fcf7172331386a087
|
refs/heads/master
| 2021-01-10T13:29:14.448000 | 2016-03-28T22:14:51 | 2016-03-28T22:14:51 | 54,927,365 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.jacr.instragramreader.model.api.managers;
import com.google.gson.reflect.TypeToken;
import org.jacr.instragramreader.model.api.ApiUrls;
import org.jacr.instragramreader.model.api.WSError;
import org.jacr.instragramreader.model.api.dtos.details.PhotoDetailDto;
import org.jacr.instragramreader.model.api.dtos.PhotoDto;
import org.jacr.instragramreader.model.api.managers.listeners.ApiListener;
import org.jacr.instragramreader.model.api.managers.listeners.PopularMediaListener;
import org.jacr.instragramreader.utilities.helpers.LogHelper;
import org.jacr.instragramreader.utilities.helpers.StringHelper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* PopularMediaManager
* Created by Jesus on 3/16/2016.
*/
public class PopularMediaManager extends ApiManager {
// <editor-fold desc="Constants">
private static final Class<?> LOG_TAG = PopularMediaManager.class;
private static final String PREFERENCE_PHOTO_DETAILS = LOG_TAG.getSimpleName() + ".photoDetails";
private static final String PREFERENCE_PHOTO_DETAILS_KEY = PREFERENCE_PHOTO_DETAILS + ".key";
//</editor-fold>
//<editor-fold desc="Manager Overrides">
@Override
protected Class<?> getLogTag() {
return LOG_TAG;
}
@Override
protected void manageResponse(String url, byte[] response, ApiListener listener) {
try {
if (url.equals(ApiUrls.POPULAR_PHOTOS) && listener instanceof PopularMediaListener) {
PhotoDto dto = (PhotoDto) parseJSONObject(response, PhotoDto.class);
serializeJSON(PREFERENCE_PHOTO_DETAILS, PREFERENCE_PHOTO_DETAILS_KEY, dto.getPhotoDetails());
((PopularMediaListener) listener).onLoadPhotos(dto.getPhotoDetails());
}
} catch (Exception e) {
LogHelper.getInstance().exception(getLogTag(), e);
listener.onError(WSError.BAD_FORMED_RESPONSE);
}
}
//</editor-fold>
public void getPhotos(boolean forceUpdate, PopularMediaListener listener) {
List<PhotoDetailDto> photos = parseSerializedPhotos(PREFERENCE_PHOTO_DETAILS, PREFERENCE_PHOTO_DETAILS_KEY);
if (forceUpdate || photos.isEmpty()) {
HashMap<String, String> parameters = new HashMap<String, String>() {{
put("client_id", "05132c49e9f148ec9b8282af33f88ac7");
}};
sendGetRequest(ApiUrls.POPULAR_PHOTOS, parameters, null, listener);
} else {
listener.onLoadPhotos(photos);
}
}
protected List<PhotoDetailDto> parseSerializedPhotos(String preference, String preferenceKey) {
String serializedModel = getPreferences(preference).getString(preferenceKey, null);
List<PhotoDetailDto> list = new ArrayList<>();
if (!StringHelper.isEmpty(serializedModel)) {
list.addAll((List<PhotoDetailDto>) gson.fromJson(serializedModel, new TypeToken<List<PhotoDetailDto>>() {
}.getType()));
}
return list;
}
}
|
UTF-8
|
Java
| 3,034 |
java
|
PopularMediaManager.java
|
Java
|
[] | null |
[] |
package org.jacr.instragramreader.model.api.managers;
import com.google.gson.reflect.TypeToken;
import org.jacr.instragramreader.model.api.ApiUrls;
import org.jacr.instragramreader.model.api.WSError;
import org.jacr.instragramreader.model.api.dtos.details.PhotoDetailDto;
import org.jacr.instragramreader.model.api.dtos.PhotoDto;
import org.jacr.instragramreader.model.api.managers.listeners.ApiListener;
import org.jacr.instragramreader.model.api.managers.listeners.PopularMediaListener;
import org.jacr.instragramreader.utilities.helpers.LogHelper;
import org.jacr.instragramreader.utilities.helpers.StringHelper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* PopularMediaManager
* Created by Jesus on 3/16/2016.
*/
public class PopularMediaManager extends ApiManager {
// <editor-fold desc="Constants">
private static final Class<?> LOG_TAG = PopularMediaManager.class;
private static final String PREFERENCE_PHOTO_DETAILS = LOG_TAG.getSimpleName() + ".photoDetails";
private static final String PREFERENCE_PHOTO_DETAILS_KEY = PREFERENCE_PHOTO_DETAILS + ".key";
//</editor-fold>
//<editor-fold desc="Manager Overrides">
@Override
protected Class<?> getLogTag() {
return LOG_TAG;
}
@Override
protected void manageResponse(String url, byte[] response, ApiListener listener) {
try {
if (url.equals(ApiUrls.POPULAR_PHOTOS) && listener instanceof PopularMediaListener) {
PhotoDto dto = (PhotoDto) parseJSONObject(response, PhotoDto.class);
serializeJSON(PREFERENCE_PHOTO_DETAILS, PREFERENCE_PHOTO_DETAILS_KEY, dto.getPhotoDetails());
((PopularMediaListener) listener).onLoadPhotos(dto.getPhotoDetails());
}
} catch (Exception e) {
LogHelper.getInstance().exception(getLogTag(), e);
listener.onError(WSError.BAD_FORMED_RESPONSE);
}
}
//</editor-fold>
public void getPhotos(boolean forceUpdate, PopularMediaListener listener) {
List<PhotoDetailDto> photos = parseSerializedPhotos(PREFERENCE_PHOTO_DETAILS, PREFERENCE_PHOTO_DETAILS_KEY);
if (forceUpdate || photos.isEmpty()) {
HashMap<String, String> parameters = new HashMap<String, String>() {{
put("client_id", "05132c49e9f148ec9b8282af33f88ac7");
}};
sendGetRequest(ApiUrls.POPULAR_PHOTOS, parameters, null, listener);
} else {
listener.onLoadPhotos(photos);
}
}
protected List<PhotoDetailDto> parseSerializedPhotos(String preference, String preferenceKey) {
String serializedModel = getPreferences(preference).getString(preferenceKey, null);
List<PhotoDetailDto> list = new ArrayList<>();
if (!StringHelper.isEmpty(serializedModel)) {
list.addAll((List<PhotoDetailDto>) gson.fromJson(serializedModel, new TypeToken<List<PhotoDetailDto>>() {
}.getType()));
}
return list;
}
}
| 3,034 | 0.699077 | 0.689848 | 77 | 38.415585 | 34.889194 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.649351 | false | false |
3
|
ae7d92a2afb70f56a8eb29487ae815094c460d3c
| 4,587,025,075,613 |
b0085cc9f373a43a274e75bca78067d2d0b2e869
|
/slloan/src/main/java/com/slloan/util/SessionFilter.java
|
b39303b61d2c74148c14a129aa9c496023889248
|
[] |
no_license
|
michunhua/shulou
|
https://github.com/michunhua/shulou
|
ef3b3bbe3f922f2d02d4bec68930f4b2a9f7232b
|
1ac8504d064fae9be8b245661a361a30926385ee
|
refs/heads/master
| 2020-03-07T10:02:03.817000 | 2018-06-05T11:24:15 | 2018-06-05T11:24:15 | 127,419,529 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.slloan.util;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.TreeMap;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.slloan.entity.AddRole;
import com.slloan.entity.UserLogin;
public class SessionFilter implements Filter{
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
//chain.doFilter(req, resp);
HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)resp;
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding("utf-8");
response.setHeader( "Pragma", "no-cache" );
response.setDateHeader("Expires", 0);
response.addHeader( "Cache-Control", "no-cache" );//浏览器和缓存服务器都不应该缓存页面信息
response.addHeader( "Cache-Control", "no-store" );
// HttpSession session = request.getSession();
// PrintWriter out = response.getWriter();
// String path = request.getContextPath();
// String basePath = req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort()+path;
// UserLogin user = (UserLogin)session.getAttribute("user");
String str = (String) request.getSession().getAttribute("username");
System.out.println("查到会话是否有值---------- "+str+" ----------------------存在 ");
// AddRole role = (AddRole)session.getAttribute("role");
if(str != null){
chain.doFilter(request,response);
} else{
PrintWriter out = response.getWriter();
response.setHeader("session-status", "timeout");
// String str02 = "用户会话已过期或未登录,安全过滤器禁止访问,并跳转到错误页面";
// response.setContentType("text/html;charset=UTF-8");// 解决中文乱码
// out.write(str02);
// response.sendRedirect("../user/signin");
// response.getWriter().print("用户会话已过期或未登录,安全过滤器禁止访问,并跳转到错误页面");
// PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
// session.setMaxInactiveInterval(600); // Session保存两小时
Cookie cookie = new Cookie("JSESSIONID", session.getId());
cookie.setMaxAge(0); // 客户端的JSESSIONID也保存两小时
// session.setMaxInactiveInterval(600);
cookie.setPath("/");
// response.addCookie(cookie);
Map<String, String> loginMap = (Map<String, String>)request.getSession().getServletContext().getAttribute("loginMap");
if(str == null){
}else{
loginMap.remove(str);
}
request.getSession().getServletContext().setAttribute("loginMap",loginMap);
System.out.println(request.getSession().getAttribute("username"));
request.getSession().invalidate();
StringBuilder builder = new StringBuilder();
builder.append("<script type=\"text/javascript\" charset=\"UTF-8\">");
// builder.append("alert(\"未登录或登录已过时,请重新登陆!\");");
// builder.append("parent.window.location.href='http://"+req.getServerName()+":"+req.getServerPort()+"/slloan/user/expirytime';");
builder.append("parent.window.location.href='http://"+req.getServerName()+":"+req.getServerPort()+"/slloan/user/signin';");
builder.append("</script>");
out.print(builder.toString());
// out.flush();
// out.close();
// out.println("您还未登陆,三秒钟后跳转至登录页面");
//out.println("<script language='javascript'>alert('你还未登录');");
// response.setHeader("refresh","3");
// response.sendRedirect("/slloan/jsp/index/index.html");
// logger.debug("用户会话已过期或未登录,安全过滤器禁止访问,并跳转到错误页面 ");
// System.out.println("用户会话已过期或未登录,安全过滤器禁止访问,并跳转到错误页面");
// request.getRequestDispatcher("http://localhost:8082/slloan/user/signin").forward(request, response);
// request.getRequestDispatcher("/slloan/user/signin").forward(request,response);
}
}
@Override
public void destroy() {
}
}
|
UTF-8
|
Java
| 5,235 |
java
|
SessionFilter.java
|
Java
|
[] | null |
[] |
package com.slloan.util;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.TreeMap;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.slloan.entity.AddRole;
import com.slloan.entity.UserLogin;
public class SessionFilter implements Filter{
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
//chain.doFilter(req, resp);
HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)resp;
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding("utf-8");
response.setHeader( "Pragma", "no-cache" );
response.setDateHeader("Expires", 0);
response.addHeader( "Cache-Control", "no-cache" );//浏览器和缓存服务器都不应该缓存页面信息
response.addHeader( "Cache-Control", "no-store" );
// HttpSession session = request.getSession();
// PrintWriter out = response.getWriter();
// String path = request.getContextPath();
// String basePath = req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort()+path;
// UserLogin user = (UserLogin)session.getAttribute("user");
String str = (String) request.getSession().getAttribute("username");
System.out.println("查到会话是否有值---------- "+str+" ----------------------存在 ");
// AddRole role = (AddRole)session.getAttribute("role");
if(str != null){
chain.doFilter(request,response);
} else{
PrintWriter out = response.getWriter();
response.setHeader("session-status", "timeout");
// String str02 = "用户会话已过期或未登录,安全过滤器禁止访问,并跳转到错误页面";
// response.setContentType("text/html;charset=UTF-8");// 解决中文乱码
// out.write(str02);
// response.sendRedirect("../user/signin");
// response.getWriter().print("用户会话已过期或未登录,安全过滤器禁止访问,并跳转到错误页面");
// PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
// session.setMaxInactiveInterval(600); // Session保存两小时
Cookie cookie = new Cookie("JSESSIONID", session.getId());
cookie.setMaxAge(0); // 客户端的JSESSIONID也保存两小时
// session.setMaxInactiveInterval(600);
cookie.setPath("/");
// response.addCookie(cookie);
Map<String, String> loginMap = (Map<String, String>)request.getSession().getServletContext().getAttribute("loginMap");
if(str == null){
}else{
loginMap.remove(str);
}
request.getSession().getServletContext().setAttribute("loginMap",loginMap);
System.out.println(request.getSession().getAttribute("username"));
request.getSession().invalidate();
StringBuilder builder = new StringBuilder();
builder.append("<script type=\"text/javascript\" charset=\"UTF-8\">");
// builder.append("alert(\"未登录或登录已过时,请重新登陆!\");");
// builder.append("parent.window.location.href='http://"+req.getServerName()+":"+req.getServerPort()+"/slloan/user/expirytime';");
builder.append("parent.window.location.href='http://"+req.getServerName()+":"+req.getServerPort()+"/slloan/user/signin';");
builder.append("</script>");
out.print(builder.toString());
// out.flush();
// out.close();
// out.println("您还未登陆,三秒钟后跳转至登录页面");
//out.println("<script language='javascript'>alert('你还未登录');");
// response.setHeader("refresh","3");
// response.sendRedirect("/slloan/jsp/index/index.html");
// logger.debug("用户会话已过期或未登录,安全过滤器禁止访问,并跳转到错误页面 ");
// System.out.println("用户会话已过期或未登录,安全过滤器禁止访问,并跳转到错误页面");
// request.getRequestDispatcher("http://localhost:8082/slloan/user/signin").forward(request, response);
// request.getRequestDispatcher("/slloan/user/signin").forward(request,response);
}
}
@Override
public void destroy() {
}
}
| 5,235 | 0.612114 | 0.60755 | 107 | 43.056076 | 31.954357 | 141 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.271028 | false | false |
3
|
ae744eec27439718a54069508017b1760ce5cfaf
| 4,587,025,075,611 |
ff8534dffb377f3b273c239738d37842c83ef6f3
|
/app/src/main/java/com/example/doanltandroid/Credit.java
|
2641a2cbb99b56ca29604fba7eb6c8fdd0d99d39
|
[] |
no_license
|
NguyenHuyenThoai-CDTH17PMC/DoAnLTAndroid
|
https://github.com/NguyenHuyenThoai-CDTH17PMC/DoAnLTAndroid
|
0f7b86587eff7f42370fe1a11166c43ad57d403d
|
7b09ed087fa3e4860c08f174ad3576626d433294
|
refs/heads/master
| 2020-09-11T23:17:20.262000 | 2020-01-03T13:29:47 | 2020-01-03T13:29:47 | 222,222,535 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.doanltandroid;
public class Credit {
private String id;
private String ten_goi;
private String credit;
private String so_tien;
public Credit(String id, String ten_goi, String credit, String so_tien) {
this.id = id;
this.ten_goi = ten_goi;
this.credit = credit;
this.so_tien = so_tien;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTen_goi() {
return ten_goi;
}
public void setTen_goi(String ten_goi) {
this.ten_goi = ten_goi;
}
public String getCredit() {
return credit;
}
public void setCredit(String credit) {
this.credit = credit;
}
public String getSo_tien() {
return so_tien;
}
public void setSo_tien(String so_tien) {
this.so_tien = so_tien;
}
}
|
UTF-8
|
Java
| 923 |
java
|
Credit.java
|
Java
|
[] | null |
[] |
package com.example.doanltandroid;
public class Credit {
private String id;
private String ten_goi;
private String credit;
private String so_tien;
public Credit(String id, String ten_goi, String credit, String so_tien) {
this.id = id;
this.ten_goi = ten_goi;
this.credit = credit;
this.so_tien = so_tien;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTen_goi() {
return ten_goi;
}
public void setTen_goi(String ten_goi) {
this.ten_goi = ten_goi;
}
public String getCredit() {
return credit;
}
public void setCredit(String credit) {
this.credit = credit;
}
public String getSo_tien() {
return so_tien;
}
public void setSo_tien(String so_tien) {
this.so_tien = so_tien;
}
}
| 923 | 0.570964 | 0.570964 | 47 | 18.638298 | 16.532915 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.425532 | false | false |
3
|
b2fa95722f8bc5a55fc440757c8287036482b8b7
| 32,667,521,317,747 |
bc453e3285abc1db891ff4ee47571cfaa750b49d
|
/src/wangyiran/dealing/with/generalization/collapse/hierarchy/Test.java
|
ac962ca2a4a06a50cdd7c3a4c5bf7897f1b5a59d
|
[] |
no_license
|
wangyiran125/refactor
|
https://github.com/wangyiran125/refactor
|
908123ef219b26bced29cdaec09b494c13f63317
|
240c068b0dfa89d82d137fd38ae07e8cb9280251
|
refs/heads/master
| 2021-01-01T20:17:48.459000 | 2015-05-25T05:16:46 | 2015-05-25T05:16:46 | 35,585,504 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package wangyiran.dealing.with.generalization.collapse.hierarchy;
/**
* Created by wyr on 2015/5/25.
*/
//If you have been working for a while with a class hierarchy, it can easily become
// too tangled for its own good. Refactoring the hierarchy often involves pushing
// methods and fields up and down the hierarchy. After you¡¯ve done this you can well
// find you have a subclass that isn¡¯t adding any value, so you need to merge the
// classes together
public class Test {
}
|
ISO-8859-9
|
Java
| 516 |
java
|
Test.java
|
Java
|
[
{
"context": "eralization.collapse.hierarchy;\n\n/**\n * Created by wyr on 2015/5/25.\n */\n//If you have been working for ",
"end": 88,
"score": 0.999679446220398,
"start": 85,
"tag": "USERNAME",
"value": "wyr"
}
] | null |
[] |
package wangyiran.dealing.with.generalization.collapse.hierarchy;
/**
* Created by wyr on 2015/5/25.
*/
//If you have been working for a while with a class hierarchy, it can easily become
// too tangled for its own good. Refactoring the hierarchy often involves pushing
// methods and fields up and down the hierarchy. After you¡¯ve done this you can well
// find you have a subclass that isn¡¯t adding any value, so you need to merge the
// classes together
public class Test {
}
| 516 | 0.714844 | 0.701172 | 12 | 41.666668 | 36.998497 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false |
3
|
2e63ac045a89070f45af708df0d04c3a7f5e42f6
| 386,547,057,208 |
b3e2d2f9c284dee79543cb22edf57129a84511d0
|
/app/src/main/java/com/example/neumaps/Archivo.java
|
f5634fbe08c360901431d431014c80c9cbee0ba2
|
[] |
no_license
|
andreazs25/neumaps2
|
https://github.com/andreazs25/neumaps2
|
4616ea951e1764bb454c7e5eb974d5f5ea994446
|
bf28b5704476fdf16a4ea8b352d6d5cae24b2da9
|
refs/heads/master
| 2022-04-23T14:00:22.035000 | 2020-04-26T23:52:36 | 2020-04-26T23:52:36 | 258,351,260 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.neumaps;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import java.io.File;
import androidx.appcompat.app.AppCompatActivity;
public class Archivo extends AppCompatActivity {
private ListView lv1;
private ImageView iv1;
private String[] archivos;
private ArrayAdapter<String> adaptador1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_archivo);
File dir=getExternalFilesDir(null);
archivos=dir.list();
adaptador1=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,archivos);
lv1=(ListView)findViewById(R.id.listwiew);
lv1.setAdapter(adaptador1);
iv1=(ImageView)findViewById(R.id.imageView);
lv1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Bitmap bitmap1= BitmapFactory.decodeFile(getExternalFilesDir(null)+"/"+archivos[position]);
iv1.setImageBitmap(bitmap1);
}
});
}
}
|
UTF-8
|
Java
| 1,397 |
java
|
Archivo.java
|
Java
|
[] | null |
[] |
package com.example.neumaps;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import java.io.File;
import androidx.appcompat.app.AppCompatActivity;
public class Archivo extends AppCompatActivity {
private ListView lv1;
private ImageView iv1;
private String[] archivos;
private ArrayAdapter<String> adaptador1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_archivo);
File dir=getExternalFilesDir(null);
archivos=dir.list();
adaptador1=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,archivos);
lv1=(ListView)findViewById(R.id.listwiew);
lv1.setAdapter(adaptador1);
iv1=(ImageView)findViewById(R.id.imageView);
lv1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Bitmap bitmap1= BitmapFactory.decodeFile(getExternalFilesDir(null)+"/"+archivos[position]);
iv1.setImageBitmap(bitmap1);
}
});
}
}
| 1,397 | 0.712241 | 0.702935 | 41 | 33.07317 | 25.893206 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.756098 | false | false |
3
|
ab58775cab387d3a2dccfc3f731e9f2ed2d11c1b
| 21,114,059,287,610 |
d4d7977fde80dc72fb271d5f795f6c659386d245
|
/noname/src/javaStudy/Car.java
|
1ba1d9f1bfb971094db938bad916753765dcc768
|
[] |
no_license
|
ids1207/JavaStudy
|
https://github.com/ids1207/JavaStudy
|
34b1c966a6d47d41066c362d44bee657727f8b80
|
37979d53fdcbf430ba40e6a13833f28b7949b398
|
refs/heads/master
| 2020-02-28T16:54:56.247000 | 2018-07-23T12:06:23 | 2018-07-23T12:06:23 | 87,800,169 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package javaStudy;
public class Car {
String name;
int number;
}
|
UTF-8
|
Java
| 68 |
java
|
Car.java
|
Java
|
[] | null |
[] |
package javaStudy;
public class Car {
String name;
int number;
}
| 68 | 0.720588 | 0.720588 | 6 | 10.333333 | 7.318166 | 18 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.833333 | false | false |
3
|
3b99a3407af200ed8de0088d1046aabe06950518
| 26,499,948,255,857 |
e108d65747c07078ae7be6dcd6369ac359d098d7
|
/com/itextpdf/text/pdf/LabColor.java
|
c5701064886a0d27768ee6af97fd3b3b092a5bde
|
[
"MIT"
] |
permissive
|
kelu124/pyS3
|
https://github.com/kelu124/pyS3
|
50f30b51483bf8f9581427d2a424e239cfce5604
|
86eb139d971921418d6a62af79f2868f9c7704d5
|
refs/heads/master
| 2020-03-13T01:51:42.054000 | 2018-04-24T21:03:03 | 2018-04-24T21:03:03 | 130,913,008 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.itextpdf.text.pdf;
import com.itextpdf.text.BaseColor;
public class LabColor extends ExtendedColor {
private float f114a;
private float f115b;
private float f116l;
PdfLabColor labColorSpace;
public LabColor(PdfLabColor labColorSpace, float l, float a, float b) {
super(7);
this.labColorSpace = labColorSpace;
this.f116l = l;
this.f114a = a;
this.f115b = b;
BaseColor altRgbColor = labColorSpace.lab2Rgb(l, a, b);
setValue(altRgbColor.getRed(), altRgbColor.getGreen(), altRgbColor.getBlue(), 255);
}
public PdfLabColor getLabColorSpace() {
return this.labColorSpace;
}
public float getL() {
return this.f116l;
}
public float getA() {
return this.f114a;
}
public float getB() {
return this.f115b;
}
public BaseColor toRgb() {
return this.labColorSpace.lab2Rgb(this.f116l, this.f114a, this.f115b);
}
CMYKColor toCmyk() {
return this.labColorSpace.lab2Cmyk(this.f116l, this.f114a, this.f115b);
}
}
|
UTF-8
|
Java
| 1,091 |
java
|
LabColor.java
|
Java
|
[] | null |
[] |
package com.itextpdf.text.pdf;
import com.itextpdf.text.BaseColor;
public class LabColor extends ExtendedColor {
private float f114a;
private float f115b;
private float f116l;
PdfLabColor labColorSpace;
public LabColor(PdfLabColor labColorSpace, float l, float a, float b) {
super(7);
this.labColorSpace = labColorSpace;
this.f116l = l;
this.f114a = a;
this.f115b = b;
BaseColor altRgbColor = labColorSpace.lab2Rgb(l, a, b);
setValue(altRgbColor.getRed(), altRgbColor.getGreen(), altRgbColor.getBlue(), 255);
}
public PdfLabColor getLabColorSpace() {
return this.labColorSpace;
}
public float getL() {
return this.f116l;
}
public float getA() {
return this.f114a;
}
public float getB() {
return this.f115b;
}
public BaseColor toRgb() {
return this.labColorSpace.lab2Rgb(this.f116l, this.f114a, this.f115b);
}
CMYKColor toCmyk() {
return this.labColorSpace.lab2Cmyk(this.f116l, this.f114a, this.f115b);
}
}
| 1,091 | 0.63703 | 0.589368 | 44 | 23.795454 | 23.524242 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.704545 | false | false |
3
|
73e0b8e527bcb6d2daa46c7d30d5d6f61142f39e
| 17,952,963,310,615 |
a1956b7e77a7ffa7e5658818e7a2019eabc1eeb6
|
/app/src/main/java/com/ziv/demo/publishbintray/MainActivity.java
|
16048df55cdd72effe30b625f0a60ec687e34557
|
[] |
no_license
|
Ziv-Android/PublishBintray
|
https://github.com/Ziv-Android/PublishBintray
|
db43cde9e886a299af972d345552f9b5326f8540
|
f44c0214631f305381b18ad1bbacea1952ffae04
|
refs/heads/master
| 2023-01-19T10:47:27.684000 | 2020-11-26T10:16:35 | 2020-11-26T10:16:35 | 251,551,389 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.ziv.demo.publishbintray;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.ziv.develop.utils.LogUtil;
import com.ziv.develop.utils.TimeUtil;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
public static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LogUtil.d(TAG, "onCreate");
new Thread(new Runnable() {
@Override
public void run() {
long currentTime = TimeUtil.getCurrentTime();
LogUtil.d(TAG, "currentTime: " + new Date(currentTime));
}
}).start();
}
}
|
UTF-8
|
Java
| 793 |
java
|
MainActivity.java
|
Java
|
[] | null |
[] |
package com.ziv.demo.publishbintray;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.ziv.develop.utils.LogUtil;
import com.ziv.develop.utils.TimeUtil;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
public static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LogUtil.d(TAG, "onCreate");
new Thread(new Runnable() {
@Override
public void run() {
long currentTime = TimeUtil.getCurrentTime();
LogUtil.d(TAG, "currentTime: " + new Date(currentTime));
}
}).start();
}
}
| 793 | 0.655738 | 0.655738 | 30 | 25.433332 | 21.836794 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
3
|
52d77f930e4ed56dd0a539a719a5fedd41b0f526
| 7,284,264,568,962 |
cd2ce10831dc34b635b21bdfa1d59347cb837eed
|
/spring-test/src/main/java/com/cbj/example/jdk/JDKDynamicProxy.java
|
6d8c50738c8b1ac8f061a47ca6da55f0a6c2f4ae
|
[] |
no_license
|
chengbingjun/SpringSample
|
https://github.com/chengbingjun/SpringSample
|
7a5ccba55a84ae8d882652a87e0e14c2f9dde3bb
|
ff2e5e016949fc82b6f78aed189659ab97c76be7
|
refs/heads/master
| 2022-12-22T14:56:14.878000 | 2021-04-29T08:47:29 | 2021-04-29T08:47:29 | 179,035,838 | 0 | 0 | null | false | 2022-12-16T08:23:07 | 2019-04-02T08:45:12 | 2021-04-29T08:49:06 | 2022-12-16T08:23:05 | 137 | 0 | 0 | 11 |
Java
| false | false |
package com.cbj.example.jdk;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class JDKDynamicProxy implements InvocationHandler {
private Object target;
public JDKDynamicProxy(Object target){
this.target = target;
}
//ClassLoader loader用来指明生成代理对象使用哪个类装载器,Class<?>[] interfaces用来指明生成哪个对象的代理对象,通过接口指定,InvocationHandler h用来指明产生的这个代理对象要做什么事情
public <T> T getProxy(){
//实例.getClass().getInterfaces():获取该对象所有实现的接口
return (T) Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
}
//参数 proxy 指代理类,method表示被代理的方法,args为 method 中的参数数组,返回值Object为代理实例的方法调用返回的值。这个抽象方法在代理类中动态实现
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = null;
if(method.getName().equals("sing")){
System.out.println("唱歌前");
result = method.invoke(target,args);
System.out.println("唱歌后");
}else{
System.out.println("跳舞前");
result = method.invoke(target,args);
System.out.println("跳舞后");
}
return result;
}
}
|
UTF-8
|
Java
| 1,514 |
java
|
JDKDynamicProxy.java
|
Java
|
[] | null |
[] |
package com.cbj.example.jdk;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class JDKDynamicProxy implements InvocationHandler {
private Object target;
public JDKDynamicProxy(Object target){
this.target = target;
}
//ClassLoader loader用来指明生成代理对象使用哪个类装载器,Class<?>[] interfaces用来指明生成哪个对象的代理对象,通过接口指定,InvocationHandler h用来指明产生的这个代理对象要做什么事情
public <T> T getProxy(){
//实例.getClass().getInterfaces():获取该对象所有实现的接口
return (T) Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
}
//参数 proxy 指代理类,method表示被代理的方法,args为 method 中的参数数组,返回值Object为代理实例的方法调用返回的值。这个抽象方法在代理类中动态实现
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = null;
if(method.getName().equals("sing")){
System.out.println("唱歌前");
result = method.invoke(target,args);
System.out.println("唱歌后");
}else{
System.out.println("跳舞前");
result = method.invoke(target,args);
System.out.println("跳舞后");
}
return result;
}
}
| 1,514 | 0.673203 | 0.673203 | 35 | 33.971428 | 31.528206 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false |
3
|
300bc728bb71aee2446e8464ac753143bd23f92a
| 26,998,164,456,266 |
bb93ba300dd9e34501b71e9b206b2ee852febbb7
|
/src/main/java/aoc2018_11/a2/Main.java
|
c2370fb6185e80801332dcb252a1a68592eb45d8
|
[] |
no_license
|
anderserikpersson/advent_2017
|
https://github.com/anderserikpersson/advent_2017
|
771ffea610646bea7f756467acb06e07fa02432c
|
38d3135f7b713c3eef33cb2d92bfa384beb56495
|
refs/heads/master
| 2021-10-09T11:53:57.469000 | 2018-12-27T13:23:00 | 2018-12-27T13:23:00 | 113,899,077 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package aoc2018_11.a2;
import java.util.Comparator;
import java.util.Optional;
import java.util.stream.IntStream;
public class Main {
private static final int CELLS_SIZE = 300;
private static int counter = 0;
public static void main(String[] args) {
Main main = new Main();
main.solve(3999);
}
private void solve(int gridSerialNr) {
Integer[] cells = buildCells(gridSerialNr);
Optional<Result> optRes = IntStream
.range(0, cells.length)
.mapToObj(idx -> maxSumSquareAllSquares(cells, idx))
.parallel()
.max(Comparator.comparing(Result::getSum));
if (optRes.isPresent()) {
Result res = optRes.get();
int x = 1 + res.getIndex() % CELLS_SIZE;
int y = 1 + res.getIndex() / CELLS_SIZE;
System.out.println("Sum:" + res.getSum());
System.out.println("x:" + x);
System.out.println("y:" + y);
System.out.println("Size:" + res.getSize());
}
}
private Result maxSumSquareAllSquares(Integer[] cells, int start) {
Result result = null;
int maxSum = Integer.MIN_VALUE;
for (int size = 1; size <= 300; size++) {
int sum = sumSquare(cells, start, size);
if (sum > maxSum) {
maxSum = sum;
result = new Result(sum, start, size);
}
}
counter++;
if (counter % 1000 == 0) System.out.println(counter);
return result;
}
private int sumSquare(Integer[] cells, int start, int size) {
int sum = 0;
for (int dy = 0; dy < size; dy++) {
for (int dx = 0; dx < size; dx++) {
int index = start + dx + (dy * CELLS_SIZE);
if (index < cells.length) {
sum += cells[index];
}
}
}
return sum;
}
private Integer[] buildCells(int gridSerialNr) {
Integer[] cells = new Integer[CELLS_SIZE * CELLS_SIZE];
for (int y = 1; y <= CELLS_SIZE; y++) {
for (int x = 1; x <= CELLS_SIZE; x++) {
int rackId = x + 10;
int powerLevel = (rackId * y + gridSerialNr) * rackId;
powerLevel = (powerLevel / 100) % 10;
powerLevel = powerLevel - 5;
int index = (y - 1) * CELLS_SIZE + (x - 1);
cells[index] = powerLevel;
}
}
return cells;
}
private class Result {
int sum;
int index;
int size;
public Result(int sum, int index, int size) {
this.sum = sum;
this.index = index;
this.size = size;
}
public int getSum() {
return sum;
}
public int getIndex() {
return index;
}
public int getSize() {
return size;
}
@Override
public String toString() {
return "Result{" +
"sum=" + sum +
", index=" + index +
", size=" + size +
'}';
}
}
}
|
UTF-8
|
Java
| 3,217 |
java
|
Main.java
|
Java
|
[] | null |
[] |
package aoc2018_11.a2;
import java.util.Comparator;
import java.util.Optional;
import java.util.stream.IntStream;
public class Main {
private static final int CELLS_SIZE = 300;
private static int counter = 0;
public static void main(String[] args) {
Main main = new Main();
main.solve(3999);
}
private void solve(int gridSerialNr) {
Integer[] cells = buildCells(gridSerialNr);
Optional<Result> optRes = IntStream
.range(0, cells.length)
.mapToObj(idx -> maxSumSquareAllSquares(cells, idx))
.parallel()
.max(Comparator.comparing(Result::getSum));
if (optRes.isPresent()) {
Result res = optRes.get();
int x = 1 + res.getIndex() % CELLS_SIZE;
int y = 1 + res.getIndex() / CELLS_SIZE;
System.out.println("Sum:" + res.getSum());
System.out.println("x:" + x);
System.out.println("y:" + y);
System.out.println("Size:" + res.getSize());
}
}
private Result maxSumSquareAllSquares(Integer[] cells, int start) {
Result result = null;
int maxSum = Integer.MIN_VALUE;
for (int size = 1; size <= 300; size++) {
int sum = sumSquare(cells, start, size);
if (sum > maxSum) {
maxSum = sum;
result = new Result(sum, start, size);
}
}
counter++;
if (counter % 1000 == 0) System.out.println(counter);
return result;
}
private int sumSquare(Integer[] cells, int start, int size) {
int sum = 0;
for (int dy = 0; dy < size; dy++) {
for (int dx = 0; dx < size; dx++) {
int index = start + dx + (dy * CELLS_SIZE);
if (index < cells.length) {
sum += cells[index];
}
}
}
return sum;
}
private Integer[] buildCells(int gridSerialNr) {
Integer[] cells = new Integer[CELLS_SIZE * CELLS_SIZE];
for (int y = 1; y <= CELLS_SIZE; y++) {
for (int x = 1; x <= CELLS_SIZE; x++) {
int rackId = x + 10;
int powerLevel = (rackId * y + gridSerialNr) * rackId;
powerLevel = (powerLevel / 100) % 10;
powerLevel = powerLevel - 5;
int index = (y - 1) * CELLS_SIZE + (x - 1);
cells[index] = powerLevel;
}
}
return cells;
}
private class Result {
int sum;
int index;
int size;
public Result(int sum, int index, int size) {
this.sum = sum;
this.index = index;
this.size = size;
}
public int getSum() {
return sum;
}
public int getIndex() {
return index;
}
public int getSize() {
return size;
}
@Override
public String toString() {
return "Result{" +
"sum=" + sum +
", index=" + index +
", size=" + size +
'}';
}
}
}
| 3,217 | 0.470314 | 0.457258 | 117 | 26.487179 | 20.279507 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.598291 | false | false |
3
|
1deaac90e822692e066d9e8f5d9b88525ea92944
| 26,998,164,455,915 |
32758cb92f9795aec3ed2aa40309bac0d71f9acb
|
/src/test/java/br/com/eiconbrasil/ecommerce/APITest.java
|
12264bf88e3c8161a6668be704c24152b2680185
|
[] |
no_license
|
walessonramos/eicon-mmerce
|
https://github.com/walessonramos/eicon-mmerce
|
03488fc7305cb1079a1702e2a92dd78f46f5ea0b
|
e0709ed18cf35a60b5ae27a14b7b0703ad5bcd49
|
refs/heads/master
| 2022-12-04T11:01:40.854000 | 2020-08-27T19:18:18 | 2020-08-27T19:18:18 | 290,859,610 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package br.com.eiconbrasil.ecommerce;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.HttpStatus;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class APITest {
@LocalServerPort
private int port;
@Test
public void deveRetornarStatus200_QuandoConsultarPedidos() {
RestAssured.given()
.basePath("/pedidos")
.port(port)
.accept(ContentType.JSON)
.when()
.get()
.then()
.statusCode(HttpStatus.OK.value());
}
}
|
UTF-8
|
Java
| 697 |
java
|
APITest.java
|
Java
|
[] | null |
[] |
package br.com.eiconbrasil.ecommerce;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.HttpStatus;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class APITest {
@LocalServerPort
private int port;
@Test
public void deveRetornarStatus200_QuandoConsultarPedidos() {
RestAssured.given()
.basePath("/pedidos")
.port(port)
.accept(ContentType.JSON)
.when()
.get()
.then()
.statusCode(HttpStatus.OK.value());
}
}
| 697 | 0.767575 | 0.763271 | 31 | 21.483871 | 21.252508 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.322581 | false | false |
3
|
70991ac583dabaa9dceb5a5dc51041d38043761e
| 11,527,692,267,236 |
73bf6b6eb7b2ed912b17205910b6a92972c6149e
|
/src/main/java/com/acc/service/EmployeeServiceFacade.java
|
b7117a44ca1206ae9af31628dd365390d8de1781
|
[] |
no_license
|
EngagementDashBd/EngagementDashBoard
|
https://github.com/EngagementDashBd/EngagementDashBoard
|
9e9927801427350e9564592c96d115c35c12feea
|
53fc66d266fc75d0df744207629e1a60dc78b6f3
|
refs/heads/master
| 2021-07-22T18:04:24.257000 | 2017-11-08T10:50:45 | 2017-11-08T10:50:45 | 104,872,751 | 0 | 1 | null | false | 2017-10-22T02:12:42 | 2017-09-26T10:49:02 | 2017-09-26T11:38:50 | 2017-10-03T11:30:47 | 68,294 | 0 | 1 | 1 |
Java
| false | null |
package com.acc.service;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.acc.entity.EmployeeHub;
import com.acc.entity.EmployeeProject;
import com.acc.entity.Location;
import com.acc.entity.ResourceMaster;
import com.acc.entity.RoleName;
public interface EmployeeServiceFacade {
public ArrayList<ResourceMaster> approve(long employeeId);
public ArrayList<ResourceMaster> allEmployeeDetails();
public int addNewEmployee(ResourceMaster resource, String password, String creatorName);
public List<ResourceMaster> getEmployeeDetailsByProject(Integer projectId);
public ArrayList<ResourceMaster> allSupervisorDetails();
public int deleteEmployee(String enterpriseId);
public int updateSupervisor(Long employeeId, Long supervisorId);
public int updateEmployee(ResourceMaster resource,String creatorName);
public int insertPersonaldetails(Long ContactNo,String PassportNo,String PanNo, String enterpriseId);
public List<String> checkSupervisor(String Name, int careerLevel);
public int recommendToHoldEmployee(Long employeeId, String potentialFutureRole,Date roleEndDate,String creator);
public List<Location> getAllLocations();
public int changePassword(ResourceMaster resource, String password);
public ResourceMaster searchEmployee(String enterpriseId);
public String getSupervisorName(Long supervisorId);
public int holdOrRoleOff(Long employeeId, String potentialFutureRole, Date roleOffDate);
public EmployeeHub getEmployeeOnHub(Long employeeId);
public int updateContact(Long employeeId,Long contactNo);
public Integer getEmpLocationIdByName(String locationName);
public Integer uploadEmployeePicture(byte[] imageData, Long employeeId);
public List<RoleName> getAllRoleNames();
public String getEmployeeEntId(Long employeeId);
public List<String> getRoles(Long employeeId);
}
|
UTF-8
|
Java
| 1,839 |
java
|
EmployeeServiceFacade.java
|
Java
|
[] | null |
[] |
package com.acc.service;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.acc.entity.EmployeeHub;
import com.acc.entity.EmployeeProject;
import com.acc.entity.Location;
import com.acc.entity.ResourceMaster;
import com.acc.entity.RoleName;
public interface EmployeeServiceFacade {
public ArrayList<ResourceMaster> approve(long employeeId);
public ArrayList<ResourceMaster> allEmployeeDetails();
public int addNewEmployee(ResourceMaster resource, String password, String creatorName);
public List<ResourceMaster> getEmployeeDetailsByProject(Integer projectId);
public ArrayList<ResourceMaster> allSupervisorDetails();
public int deleteEmployee(String enterpriseId);
public int updateSupervisor(Long employeeId, Long supervisorId);
public int updateEmployee(ResourceMaster resource,String creatorName);
public int insertPersonaldetails(Long ContactNo,String PassportNo,String PanNo, String enterpriseId);
public List<String> checkSupervisor(String Name, int careerLevel);
public int recommendToHoldEmployee(Long employeeId, String potentialFutureRole,Date roleEndDate,String creator);
public List<Location> getAllLocations();
public int changePassword(ResourceMaster resource, String password);
public ResourceMaster searchEmployee(String enterpriseId);
public String getSupervisorName(Long supervisorId);
public int holdOrRoleOff(Long employeeId, String potentialFutureRole, Date roleOffDate);
public EmployeeHub getEmployeeOnHub(Long employeeId);
public int updateContact(Long employeeId,Long contactNo);
public Integer getEmpLocationIdByName(String locationName);
public Integer uploadEmployeePicture(byte[] imageData, Long employeeId);
public List<RoleName> getAllRoleNames();
public String getEmployeeEntId(Long employeeId);
public List<String> getRoles(Long employeeId);
}
| 1,839 | 0.836324 | 0.836324 | 37 | 48.675674 | 26.929392 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.918919 | false | false |
3
|
2abd88fd673578f614d396cdaca3ca2197319522
| 4,389,456,623,980 |
b49690b7cb538b585894f06b7bb6bae6eddc3194
|
/src/test/java/org/seras/classes/tests/GenericClassParserTestClassToClass.java
|
c8a748b1d9f298dd6581735999399bb66f6f63ef
|
[] |
no_license
|
altugK/JavaReflectionGenericClassParser
|
https://github.com/altugK/JavaReflectionGenericClassParser
|
318ab88614aac0ddb102fa50bf72e87a1a2de4e2
|
7f440a0511827afd09e7ddcfff00d8a31819c6d6
|
refs/heads/master
| 2023-07-14T10:31:30.776000 | 2021-08-24T12:37:32 | 2021-08-24T12:37:32 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.seras.classes.tests;
import org.junit.Assert;
import org.seras.Classes.Exceptions.NullClassException;
import org.seras.Classes.Exceptions.NullClassFieldException;
import org.seras.Classes.Exceptions.NullFieldMatchMapException;
import org.seras.Classes.Pojos.*;
import org.seras.GenericClassParser;
import org.seras.classes.bases.GenericClassParserBaseClassToClass;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class GenericClassParserTestClassToClass extends GenericClassParserBaseClassToClass {
@Override
public void initDestinationClass() {
super.initDestinationClass();
}
@Override
public void testStringToString() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
this.fieldMatchMap.put("stringVal", "stringVal");
genericClassParser.parseClassToClass(this.sourceClass,this.destinationClass,this.fieldMatchMap);
Assert.assertEquals(destinationClass.stringVal, sourceClass.stringVal);
}
@Override
public void testNullToString() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.stringVal=null;
this.fieldMatchMap.put("stringVal", "stringVal");
genericClassParser.parseClassToClass(this.sourceClass,this.destinationClass,this.fieldMatchMap);
Assert.assertNull(destinationClass.stringVal);
}
@Override
public void testIntegerToInteger() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
this.fieldMatchMap.put("integerValue", "integerValue");
genericClassParser.parseClassToClass(this.sourceClass,this.destinationClass,this.fieldMatchMap);
Assert.assertEquals(destinationClass.integerValue, sourceClass.integerValue);
}
@Override
public void testNullToInteger() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.integerValue=null;
this.fieldMatchMap.put("integerValue", "integerValue");
genericClassParser.parseClassToClass(this.sourceClass,this.destinationClass,this.fieldMatchMap);
Assert.assertNull(destinationClass.integerValue);
}
@Override
public void testIntegerToString() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
this.fieldMatchMap.put("integerValue", "stringVal");
genericClassParser.parseClassToClass(this.sourceClass,this.destinationClass,this.fieldMatchMap);
Assert.assertEquals(destinationClass.stringVal,sourceClass.integerValue.toString());
}
@Override
public void testStringToInteger() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.stringVal="50";
fieldMatchMap.put("stringVal", "integerValue");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.integerValue, new Integer(50));
}
@Override
public void testBigDecimalToBigDecimal() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
fieldMatchMap.put("decimal","decimal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(sourceClass.decimal,destinationClass.decimal);
}
@Override
public void testNullToBigDecimal() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.decimal=null;
fieldMatchMap.put("decimal","decimal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertNull(destinationClass.decimal);
}
@Override
public void testBigDecimalToString() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
fieldMatchMap.put("decimal","stringVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.stringVal,sourceClass.decimal.toString());
}
@Override
public void testStringToBigDecimal() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.stringVal="50";
fieldMatchMap.put("stringVal","decimal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.decimal,new BigDecimal("50"));
}
@Override
public void testLongToLong() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
fieldMatchMap.put("longVal","longVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.longVal,sourceClass.longVal);
}
@Override
public void testNullToLong() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.longVal=null;
fieldMatchMap.put("longVal","longVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertNull(destinationClass.longVal);
}
@Override
public void testLongToString() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
fieldMatchMap.put("longVal","stringVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.stringVal,sourceClass.longVal.toString());
}
@Override
public void testStringToLong() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.stringVal="50";
fieldMatchMap.put("stringVal","longVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.longVal, new Long(50L));
}
@Override
public void testFloatToFloat() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
fieldMatchMap.put("floatVal","floatVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.floatVal,sourceClass.floatVal);
}
@Override
public void testNullToFloat() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.floatVal=null;
fieldMatchMap.put("floatVal","floatVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertNull(destinationClass.floatVal);
}
@Override
public void testFloatToString() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.floatVal=60f;
fieldMatchMap.put("floatVal","stringVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.stringVal,"60.0");
}
@Override
public void testStringToFloat() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.stringVal="10";
fieldMatchMap.put("stringVal","floatVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.floatVal,new Float(10f));
}
@Override
public void testByteToByte() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
fieldMatchMap.put("byteVal","byteVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.byteVal,sourceClass.byteVal);
}
@Override
public void testNullToByte() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.byteVal=null;
fieldMatchMap.put("byteVal","byteVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertNull(destinationClass.byteVal);
}
@Override
public void testByteToString() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
fieldMatchMap.put("byteVal","stringVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.stringVal,sourceClass.byteVal.toString());
}
@Override
public void testStringToByte() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.stringVal="10";
fieldMatchMap.put("stringVal","byteVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.byteVal,new Byte("10"));
}
@Override
public void testDoubleToDouble() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
fieldMatchMap.put("doubleVal","doubleVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.doubleVal,sourceClass.doubleVal);
}
@Override
public void testNullToDouble() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.doubleVal=null;
fieldMatchMap.put("doubleVal","doubleVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertNull(destinationClass.doubleVal);
}
@Override
public void testDoubleToString() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
fieldMatchMap.put("doubleVal","stringVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.stringVal,sourceClass.doubleVal.toString());
}
@Override
public void testStringToDouble() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.stringVal="50";
fieldMatchMap.put("stringVal","doubleVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.doubleVal,new Double("50"));
}
@Override
public void testCharacterToCharacter() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
fieldMatchMap.put("charVal","charVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.charVal,sourceClass.charVal);
}
@Override
public void testNullToCharacter() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.charVal=null;
fieldMatchMap.put("charVal","charVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertNull(destinationClass.charVal);
}
@Override
public void testCharacterToString() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
fieldMatchMap.put("charVal","stringVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.stringVal,sourceClass.charVal.toString());
}
@Override
public void testStringToCharacter() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.stringVal="C";
fieldMatchMap.put("stringVal","charVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.charVal,new Character('C'));
}
@Override
public void testBooleanToBoolean() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
fieldMatchMap.put("boolVal","boolVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.boolVal,sourceClass.boolVal);
}
@Override
public void testNullToBoolean() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.boolVal=null;
fieldMatchMap.put("boolVal","boolVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertNull(destinationClass.boolVal);
}
@Override
public void testBooleanToString() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.boolVal=Boolean.TRUE;
fieldMatchMap.put("boolVal","stringVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.stringVal,"true");
}
@Override
public void testStringToBoolean() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.stringVal="true";
fieldMatchMap.put("stringVal","boolVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.boolVal,Boolean.TRUE);
}
@Override
public void testUtilDateToUtilDate() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
fieldMatchMap.put("dateUtil","dateUtil");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.dateUtil,sourceClass.dateUtil);
}
@Override
public void testNullToUtilDate() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.dateUtil=null;
fieldMatchMap.put("dateUtil","dateUtil");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertNull(destinationClass.dateUtil);
}
@Override
public void testUtilDateToString() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
fieldMatchMap.put("dateUtil","stringVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.stringVal,sourceClass.dateUtil.toString());
}
@Override
public void testStringToUtilDate() throws ParseException, NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.stringVal="2021-01-01";
fieldMatchMap.put("stringVal","dateUtil");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.dateUtil, new SimpleDateFormat("yyyy-MM-dd").parse("2021-01-01"));
}
@Override
public void testSqlDateToSqlDate() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
fieldMatchMap.put("dateSql", "dateSql");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.dateSql,sourceClass.dateSql);
}
@Override
public void testNullToSqlDate() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.dateSql=null;
fieldMatchMap.put("dateSql","dateSql");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertNull(destinationClass.dateSql);
}
@Override
public void testSqlDateToString() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
fieldMatchMap.put("dateSql","stringVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.stringVal,sourceClass.dateSql.toString());
}
@Override
public void testStringToSqlDate() throws ParseException, NullClassException, NullClassFieldException, NullFieldMatchMapException {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String dateAsString="2021-01-01";
Date dateToBeParsed = simpleDateFormat.parse(dateAsString );
// Timestamp timestampForSqlDate = new Timestamp(dateToBeParsed.getTime());
java.sql.Date dateSql = new java.sql.Date(dateToBeParsed.getTime());
sourceClass.stringVal=dateAsString;
fieldMatchMap.put("stringVal","dateSql");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.dateSql,dateSql);
}
@Override
public void testTimestampToTimestamp() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
fieldMatchMap.put("timestamp","timestamp");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.timestamp,sourceClass.timestamp);
}
@Override
public void testNullToTimestamp() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.timestamp=null;
fieldMatchMap.put("timestamp","timestamp");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertNull(destinationClass.timestamp);
}
@Override
public void testTimestampToString() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
fieldMatchMap.put("timestamp","stringVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.stringVal,sourceClass.timestamp.toString());
}
@Override
public void testStringToTimestamp() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.stringVal= "11111";
fieldMatchMap.put("stringVal","timestamp");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.timestamp, new Timestamp(11111));
}
@Override
public void testNullFieldList() {
fieldMatchMap=null;
Assert.assertThrows(NullFieldMatchMapException.class,()->genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap));
}
@Override
public void testNullDestinationClass() {
destinationClass=null;
Assert.assertThrows(NullClassException.class,()-> genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap) );
}
@Override
public void testNullSourceClass() {
sourceClass=null;
Assert.assertThrows(NullClassException.class,()-> genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap));
}
@Override
public void testNotDeclaredFieldInSourceClass() {
GenericClassParser<NullFieldSourceClass, DestinationClass> genericClassParser
= new GenericClassParser<>();
Assert.assertThrows(NullClassFieldException.class,()->genericClassParser.parseClassToClass(nullFieldSourceClass,destinationClass,fieldMatchMap));
}
@Override
public void testNotDeclaredFieldInDestinationClass() {
GenericClassParser<SourceClass, NullFieldDestinationClass> genericClassParser = new GenericClassParser<>();
Assert.assertThrows(NullClassFieldException.class,()->genericClassParser.parseClassToClass(sourceClass,nullFieldDestinationClass,fieldMatchMap));
}
@Override
public void testMultipleFieldMatchList() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
fieldMatchMap.put("stringVal","stringVal");
fieldMatchMap.put("integerValue","integerValue");
fieldMatchMap.put("decimal","decimal");
fieldMatchMap.put("floatVal","floatVal");
fieldMatchMap.put("boolVal","boolVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(sourceClass.stringVal,destinationClass.stringVal);
Assert.assertEquals(sourceClass.integerValue,destinationClass.integerValue);
Assert.assertEquals(sourceClass.decimal,destinationClass.decimal);
Assert.assertEquals(sourceClass.floatVal,destinationClass.floatVal);
Assert.assertEquals(sourceClass.boolVal,destinationClass.boolVal);
}
@Override
public void testPrivateFieldSourceClassToPublicFieldDestinationClass() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
GenericClassParser<PrivateFieldSourceClass,DestinationClass> genericClassParser
= new GenericClassParser<PrivateFieldSourceClass, DestinationClass>();
fieldMatchMap.put("stringVal","stringVal");
fieldMatchMap.put("integerValue","integerValue");
fieldMatchMap.put("timestamp","timestamp");
PrivateFieldSourceClass privateFieldSourceClass = new PrivateFieldSourceClass();
genericClassParser.parseClassToClass(privateFieldSourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(privateFieldSourceClass.getStringVal(),destinationClass.stringVal);
Assert.assertEquals(privateFieldSourceClass.getIntegerValue(),destinationClass.integerValue);
Assert.assertEquals(privateFieldSourceClass.getTimestamp(),destinationClass.timestamp);
}
@Override
public void testPublicFieldSourceClassToPrivateFieldDestinationClass() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
GenericClassParser<SourceClass,PrivateFieldDestinationClass> genericClassParser
= new GenericClassParser<SourceClass,PrivateFieldDestinationClass>();
fieldMatchMap.put("stringVal","stringVal");
fieldMatchMap.put("integerValue","integerValue");
fieldMatchMap.put("timestamp","timestamp");
PrivateFieldDestinationClass privateFieldDestinationClass=new PrivateFieldDestinationClass();
genericClassParser.parseClassToClass(sourceClass,privateFieldDestinationClass,fieldMatchMap);
Assert.assertEquals(sourceClass.stringVal,privateFieldDestinationClass.getStringVal());
Assert.assertEquals(sourceClass.integerValue,privateFieldDestinationClass.getIntegerValue());
Assert.assertEquals(sourceClass.timestamp,privateFieldDestinationClass.getTimestamp());
}
@Override
public void testPrivateFieldSourceClassToPrivateFieldDestinationClass() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
GenericClassParser<PrivateFieldSourceClass,PrivateFieldDestinationClass> genericClassParser
= new GenericClassParser<PrivateFieldSourceClass,PrivateFieldDestinationClass>();
fieldMatchMap.put("stringVal","stringVal");
fieldMatchMap.put("integerValue","integerValue");
fieldMatchMap.put("timestamp","timestamp");
PrivateFieldSourceClass privateFieldSourceClass=new PrivateFieldSourceClass();
PrivateFieldDestinationClass privateFieldDestinationClass = new PrivateFieldDestinationClass();
genericClassParser.parseClassToClass(privateFieldSourceClass,privateFieldDestinationClass,fieldMatchMap);
Assert.assertEquals(privateFieldSourceClass.getStringVal(),privateFieldDestinationClass.getStringVal() );
Assert.assertEquals(privateFieldSourceClass.getIntegerValue(),privateFieldDestinationClass.getIntegerValue());
Assert.assertEquals(privateFieldSourceClass.getTimestamp(),privateFieldDestinationClass.getTimestamp());
}
}
|
UTF-8
|
Java
| 23,862 |
java
|
GenericClassParserTestClassToClass.java
|
Java
|
[] | null |
[] |
package org.seras.classes.tests;
import org.junit.Assert;
import org.seras.Classes.Exceptions.NullClassException;
import org.seras.Classes.Exceptions.NullClassFieldException;
import org.seras.Classes.Exceptions.NullFieldMatchMapException;
import org.seras.Classes.Pojos.*;
import org.seras.GenericClassParser;
import org.seras.classes.bases.GenericClassParserBaseClassToClass;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class GenericClassParserTestClassToClass extends GenericClassParserBaseClassToClass {
@Override
public void initDestinationClass() {
super.initDestinationClass();
}
@Override
public void testStringToString() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
this.fieldMatchMap.put("stringVal", "stringVal");
genericClassParser.parseClassToClass(this.sourceClass,this.destinationClass,this.fieldMatchMap);
Assert.assertEquals(destinationClass.stringVal, sourceClass.stringVal);
}
@Override
public void testNullToString() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.stringVal=null;
this.fieldMatchMap.put("stringVal", "stringVal");
genericClassParser.parseClassToClass(this.sourceClass,this.destinationClass,this.fieldMatchMap);
Assert.assertNull(destinationClass.stringVal);
}
@Override
public void testIntegerToInteger() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
this.fieldMatchMap.put("integerValue", "integerValue");
genericClassParser.parseClassToClass(this.sourceClass,this.destinationClass,this.fieldMatchMap);
Assert.assertEquals(destinationClass.integerValue, sourceClass.integerValue);
}
@Override
public void testNullToInteger() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.integerValue=null;
this.fieldMatchMap.put("integerValue", "integerValue");
genericClassParser.parseClassToClass(this.sourceClass,this.destinationClass,this.fieldMatchMap);
Assert.assertNull(destinationClass.integerValue);
}
@Override
public void testIntegerToString() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
this.fieldMatchMap.put("integerValue", "stringVal");
genericClassParser.parseClassToClass(this.sourceClass,this.destinationClass,this.fieldMatchMap);
Assert.assertEquals(destinationClass.stringVal,sourceClass.integerValue.toString());
}
@Override
public void testStringToInteger() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.stringVal="50";
fieldMatchMap.put("stringVal", "integerValue");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.integerValue, new Integer(50));
}
@Override
public void testBigDecimalToBigDecimal() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
fieldMatchMap.put("decimal","decimal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(sourceClass.decimal,destinationClass.decimal);
}
@Override
public void testNullToBigDecimal() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.decimal=null;
fieldMatchMap.put("decimal","decimal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertNull(destinationClass.decimal);
}
@Override
public void testBigDecimalToString() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
fieldMatchMap.put("decimal","stringVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.stringVal,sourceClass.decimal.toString());
}
@Override
public void testStringToBigDecimal() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.stringVal="50";
fieldMatchMap.put("stringVal","decimal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.decimal,new BigDecimal("50"));
}
@Override
public void testLongToLong() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
fieldMatchMap.put("longVal","longVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.longVal,sourceClass.longVal);
}
@Override
public void testNullToLong() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.longVal=null;
fieldMatchMap.put("longVal","longVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertNull(destinationClass.longVal);
}
@Override
public void testLongToString() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
fieldMatchMap.put("longVal","stringVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.stringVal,sourceClass.longVal.toString());
}
@Override
public void testStringToLong() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.stringVal="50";
fieldMatchMap.put("stringVal","longVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.longVal, new Long(50L));
}
@Override
public void testFloatToFloat() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
fieldMatchMap.put("floatVal","floatVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.floatVal,sourceClass.floatVal);
}
@Override
public void testNullToFloat() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.floatVal=null;
fieldMatchMap.put("floatVal","floatVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertNull(destinationClass.floatVal);
}
@Override
public void testFloatToString() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.floatVal=60f;
fieldMatchMap.put("floatVal","stringVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.stringVal,"60.0");
}
@Override
public void testStringToFloat() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.stringVal="10";
fieldMatchMap.put("stringVal","floatVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.floatVal,new Float(10f));
}
@Override
public void testByteToByte() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
fieldMatchMap.put("byteVal","byteVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.byteVal,sourceClass.byteVal);
}
@Override
public void testNullToByte() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.byteVal=null;
fieldMatchMap.put("byteVal","byteVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertNull(destinationClass.byteVal);
}
@Override
public void testByteToString() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
fieldMatchMap.put("byteVal","stringVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.stringVal,sourceClass.byteVal.toString());
}
@Override
public void testStringToByte() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.stringVal="10";
fieldMatchMap.put("stringVal","byteVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.byteVal,new Byte("10"));
}
@Override
public void testDoubleToDouble() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
fieldMatchMap.put("doubleVal","doubleVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.doubleVal,sourceClass.doubleVal);
}
@Override
public void testNullToDouble() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.doubleVal=null;
fieldMatchMap.put("doubleVal","doubleVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertNull(destinationClass.doubleVal);
}
@Override
public void testDoubleToString() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
fieldMatchMap.put("doubleVal","stringVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.stringVal,sourceClass.doubleVal.toString());
}
@Override
public void testStringToDouble() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.stringVal="50";
fieldMatchMap.put("stringVal","doubleVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.doubleVal,new Double("50"));
}
@Override
public void testCharacterToCharacter() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
fieldMatchMap.put("charVal","charVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.charVal,sourceClass.charVal);
}
@Override
public void testNullToCharacter() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.charVal=null;
fieldMatchMap.put("charVal","charVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertNull(destinationClass.charVal);
}
@Override
public void testCharacterToString() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
fieldMatchMap.put("charVal","stringVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.stringVal,sourceClass.charVal.toString());
}
@Override
public void testStringToCharacter() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.stringVal="C";
fieldMatchMap.put("stringVal","charVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.charVal,new Character('C'));
}
@Override
public void testBooleanToBoolean() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
fieldMatchMap.put("boolVal","boolVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.boolVal,sourceClass.boolVal);
}
@Override
public void testNullToBoolean() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.boolVal=null;
fieldMatchMap.put("boolVal","boolVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertNull(destinationClass.boolVal);
}
@Override
public void testBooleanToString() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.boolVal=Boolean.TRUE;
fieldMatchMap.put("boolVal","stringVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.stringVal,"true");
}
@Override
public void testStringToBoolean() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.stringVal="true";
fieldMatchMap.put("stringVal","boolVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.boolVal,Boolean.TRUE);
}
@Override
public void testUtilDateToUtilDate() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
fieldMatchMap.put("dateUtil","dateUtil");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.dateUtil,sourceClass.dateUtil);
}
@Override
public void testNullToUtilDate() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.dateUtil=null;
fieldMatchMap.put("dateUtil","dateUtil");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertNull(destinationClass.dateUtil);
}
@Override
public void testUtilDateToString() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
fieldMatchMap.put("dateUtil","stringVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.stringVal,sourceClass.dateUtil.toString());
}
@Override
public void testStringToUtilDate() throws ParseException, NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.stringVal="2021-01-01";
fieldMatchMap.put("stringVal","dateUtil");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.dateUtil, new SimpleDateFormat("yyyy-MM-dd").parse("2021-01-01"));
}
@Override
public void testSqlDateToSqlDate() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
fieldMatchMap.put("dateSql", "dateSql");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.dateSql,sourceClass.dateSql);
}
@Override
public void testNullToSqlDate() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.dateSql=null;
fieldMatchMap.put("dateSql","dateSql");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertNull(destinationClass.dateSql);
}
@Override
public void testSqlDateToString() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
fieldMatchMap.put("dateSql","stringVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.stringVal,sourceClass.dateSql.toString());
}
@Override
public void testStringToSqlDate() throws ParseException, NullClassException, NullClassFieldException, NullFieldMatchMapException {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String dateAsString="2021-01-01";
Date dateToBeParsed = simpleDateFormat.parse(dateAsString );
// Timestamp timestampForSqlDate = new Timestamp(dateToBeParsed.getTime());
java.sql.Date dateSql = new java.sql.Date(dateToBeParsed.getTime());
sourceClass.stringVal=dateAsString;
fieldMatchMap.put("stringVal","dateSql");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.dateSql,dateSql);
}
@Override
public void testTimestampToTimestamp() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
fieldMatchMap.put("timestamp","timestamp");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.timestamp,sourceClass.timestamp);
}
@Override
public void testNullToTimestamp() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.timestamp=null;
fieldMatchMap.put("timestamp","timestamp");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertNull(destinationClass.timestamp);
}
@Override
public void testTimestampToString() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
fieldMatchMap.put("timestamp","stringVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.stringVal,sourceClass.timestamp.toString());
}
@Override
public void testStringToTimestamp() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
sourceClass.stringVal= "11111";
fieldMatchMap.put("stringVal","timestamp");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(destinationClass.timestamp, new Timestamp(11111));
}
@Override
public void testNullFieldList() {
fieldMatchMap=null;
Assert.assertThrows(NullFieldMatchMapException.class,()->genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap));
}
@Override
public void testNullDestinationClass() {
destinationClass=null;
Assert.assertThrows(NullClassException.class,()-> genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap) );
}
@Override
public void testNullSourceClass() {
sourceClass=null;
Assert.assertThrows(NullClassException.class,()-> genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap));
}
@Override
public void testNotDeclaredFieldInSourceClass() {
GenericClassParser<NullFieldSourceClass, DestinationClass> genericClassParser
= new GenericClassParser<>();
Assert.assertThrows(NullClassFieldException.class,()->genericClassParser.parseClassToClass(nullFieldSourceClass,destinationClass,fieldMatchMap));
}
@Override
public void testNotDeclaredFieldInDestinationClass() {
GenericClassParser<SourceClass, NullFieldDestinationClass> genericClassParser = new GenericClassParser<>();
Assert.assertThrows(NullClassFieldException.class,()->genericClassParser.parseClassToClass(sourceClass,nullFieldDestinationClass,fieldMatchMap));
}
@Override
public void testMultipleFieldMatchList() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
fieldMatchMap.put("stringVal","stringVal");
fieldMatchMap.put("integerValue","integerValue");
fieldMatchMap.put("decimal","decimal");
fieldMatchMap.put("floatVal","floatVal");
fieldMatchMap.put("boolVal","boolVal");
genericClassParser.parseClassToClass(sourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(sourceClass.stringVal,destinationClass.stringVal);
Assert.assertEquals(sourceClass.integerValue,destinationClass.integerValue);
Assert.assertEquals(sourceClass.decimal,destinationClass.decimal);
Assert.assertEquals(sourceClass.floatVal,destinationClass.floatVal);
Assert.assertEquals(sourceClass.boolVal,destinationClass.boolVal);
}
@Override
public void testPrivateFieldSourceClassToPublicFieldDestinationClass() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
GenericClassParser<PrivateFieldSourceClass,DestinationClass> genericClassParser
= new GenericClassParser<PrivateFieldSourceClass, DestinationClass>();
fieldMatchMap.put("stringVal","stringVal");
fieldMatchMap.put("integerValue","integerValue");
fieldMatchMap.put("timestamp","timestamp");
PrivateFieldSourceClass privateFieldSourceClass = new PrivateFieldSourceClass();
genericClassParser.parseClassToClass(privateFieldSourceClass,destinationClass,fieldMatchMap);
Assert.assertEquals(privateFieldSourceClass.getStringVal(),destinationClass.stringVal);
Assert.assertEquals(privateFieldSourceClass.getIntegerValue(),destinationClass.integerValue);
Assert.assertEquals(privateFieldSourceClass.getTimestamp(),destinationClass.timestamp);
}
@Override
public void testPublicFieldSourceClassToPrivateFieldDestinationClass() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
GenericClassParser<SourceClass,PrivateFieldDestinationClass> genericClassParser
= new GenericClassParser<SourceClass,PrivateFieldDestinationClass>();
fieldMatchMap.put("stringVal","stringVal");
fieldMatchMap.put("integerValue","integerValue");
fieldMatchMap.put("timestamp","timestamp");
PrivateFieldDestinationClass privateFieldDestinationClass=new PrivateFieldDestinationClass();
genericClassParser.parseClassToClass(sourceClass,privateFieldDestinationClass,fieldMatchMap);
Assert.assertEquals(sourceClass.stringVal,privateFieldDestinationClass.getStringVal());
Assert.assertEquals(sourceClass.integerValue,privateFieldDestinationClass.getIntegerValue());
Assert.assertEquals(sourceClass.timestamp,privateFieldDestinationClass.getTimestamp());
}
@Override
public void testPrivateFieldSourceClassToPrivateFieldDestinationClass() throws NullClassException, NullClassFieldException, NullFieldMatchMapException {
GenericClassParser<PrivateFieldSourceClass,PrivateFieldDestinationClass> genericClassParser
= new GenericClassParser<PrivateFieldSourceClass,PrivateFieldDestinationClass>();
fieldMatchMap.put("stringVal","stringVal");
fieldMatchMap.put("integerValue","integerValue");
fieldMatchMap.put("timestamp","timestamp");
PrivateFieldSourceClass privateFieldSourceClass=new PrivateFieldSourceClass();
PrivateFieldDestinationClass privateFieldDestinationClass = new PrivateFieldDestinationClass();
genericClassParser.parseClassToClass(privateFieldSourceClass,privateFieldDestinationClass,fieldMatchMap);
Assert.assertEquals(privateFieldSourceClass.getStringVal(),privateFieldDestinationClass.getStringVal() );
Assert.assertEquals(privateFieldSourceClass.getIntegerValue(),privateFieldDestinationClass.getIntegerValue());
Assert.assertEquals(privateFieldSourceClass.getTimestamp(),privateFieldDestinationClass.getTimestamp());
}
}
| 23,862 | 0.77043 | 0.76779 | 498 | 46.915661 | 42.732952 | 156 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.13253 | false | false |
3
|
655260c3fe03f84db369f9636b256d6f6ad85f0d
| 25,125,558,735,591 |
41fff2bfe5160f2b09bcb88dde0f03380ec76e98
|
/model/src/main/java/com/mysimplework/model/generic/AbstractBaseDomain.java
|
f6514a9acc4a362a27429b7fde70fcbf520654af
|
[] |
no_license
|
dongzhao/my-webapp
|
https://github.com/dongzhao/my-webapp
|
4a3dcc026d42df0352ca182156ebe3a18a28ec50
|
e8891d5e03ca6d95b088d2de1e0a938c7a4d0acb
|
refs/heads/master
| 2020-12-31T07:33:21.585000 | 2016-05-23T13:43:47 | 2016-05-23T13:43:47 | 58,931,412 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.mysimplework.model.generic;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
/**
* Created by dzhao on 19/08/2015.
*/
@MappedSuperclass
public abstract class AbstractBaseDomain implements BaseDomain<String> {
@Id
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "uuid2")
@Column(name = "ID")
protected String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
|
UTF-8
|
Java
| 545 |
java
|
AbstractBaseDomain.java
|
Java
|
[
{
"context": "r;\n\nimport javax.persistence.*;\n\n/**\n * Created by dzhao on 19/08/2015.\n */\n@MappedSuperclass\npublic abstr",
"end": 145,
"score": 0.9996852874755859,
"start": 140,
"tag": "USERNAME",
"value": "dzhao"
}
] | null |
[] |
package com.mysimplework.model.generic;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
/**
* Created by dzhao on 19/08/2015.
*/
@MappedSuperclass
public abstract class AbstractBaseDomain implements BaseDomain<String> {
@Id
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "uuid2")
@Column(name = "ID")
protected String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
| 545 | 0.673395 | 0.656881 | 25 | 20.799999 | 20.560156 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.28 | false | false |
3
|
d0e6785c4e010d83f484b6cb3caa879807f6ca31
| 15,333,033,302,392 |
2b0c3027624b45380824a97ced49670c28cc03b9
|
/src/bfs/Bfs.java
|
8ce7a76470bea00e0adff010a09cb0fe002fa828
|
[] |
no_license
|
catchJava/strategyPattern
|
https://github.com/catchJava/strategyPattern
|
1ea7d01aa357f72abfc71138f0d754fea7b3e5f7
|
8a38ecd40c6ee5bb17249c8b5c3ae432d0fdedbd
|
refs/heads/master
| 2020-12-10T09:31:12.171000 | 2020-07-30T01:09:49 | 2020-07-30T01:09:49 | 233,557,113 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package bfs;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Bfs {
int N, M;
boolean visit[][];
int map[][];
int moveX[] = {0, 1, -1, 0};
int moveY[] = {1, 0, 0, -1};
Queue<Map> queue = new LinkedList<>();
public Bfs(int N, int M, int[][] map){
this.N = N;
this.M = M;
visit = new boolean[N][M];
this.map = map;
}
public int search(int x, int y, int length){
queue.add(new Map(x, y, length));
while(!queue.isEmpty()){
Map currentMap = queue.poll();
visit[currentMap.x][currentMap.y] = true;
System.out.println("현재 좌표 : " + currentMap.x + " / " + currentMap.y);
System.out.println("현재 길 : " + currentMap.length);
for(int i=0 ; i<4 ; i++){
int nextX = currentMap.x + moveX[i];
int nextY = currentMap.y + moveY[i];
if(nextX == N-1 && nextY == M-1){
return currentMap.length + 1;
}
if(nextX >= 0 && nextX < N && nextY >= 0 && nextY < M){
if(visit[nextX][nextY] == false && map[nextX][nextY] == 1){
queue.add(new Map(nextX, nextY, currentMap.length + 1));
}
}
}
}
return -1;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] NM = scanner.nextLine().split(" ");
int N = Integer.parseInt(NM[0]);
int M = Integer.parseInt(NM[1]);
int map[][] = new int[N][M];
for(int i=0 ; i < N ; i++){
String str = scanner.nextLine().trim();
for(int j=0 ; j<str.length() ; j++){
map[i][j] = str.charAt(j) - '0';
}
}
Bfs bfs = new Bfs(N, M, map);
int result = bfs.search(0, 0, 1);
System.out.println("result : " + result);
}
}
|
UTF-8
|
Java
| 2,018 |
java
|
Bfs.java
|
Java
|
[] | null |
[] |
package bfs;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Bfs {
int N, M;
boolean visit[][];
int map[][];
int moveX[] = {0, 1, -1, 0};
int moveY[] = {1, 0, 0, -1};
Queue<Map> queue = new LinkedList<>();
public Bfs(int N, int M, int[][] map){
this.N = N;
this.M = M;
visit = new boolean[N][M];
this.map = map;
}
public int search(int x, int y, int length){
queue.add(new Map(x, y, length));
while(!queue.isEmpty()){
Map currentMap = queue.poll();
visit[currentMap.x][currentMap.y] = true;
System.out.println("현재 좌표 : " + currentMap.x + " / " + currentMap.y);
System.out.println("현재 길 : " + currentMap.length);
for(int i=0 ; i<4 ; i++){
int nextX = currentMap.x + moveX[i];
int nextY = currentMap.y + moveY[i];
if(nextX == N-1 && nextY == M-1){
return currentMap.length + 1;
}
if(nextX >= 0 && nextX < N && nextY >= 0 && nextY < M){
if(visit[nextX][nextY] == false && map[nextX][nextY] == 1){
queue.add(new Map(nextX, nextY, currentMap.length + 1));
}
}
}
}
return -1;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] NM = scanner.nextLine().split(" ");
int N = Integer.parseInt(NM[0]);
int M = Integer.parseInt(NM[1]);
int map[][] = new int[N][M];
for(int i=0 ; i < N ; i++){
String str = scanner.nextLine().trim();
for(int j=0 ; j<str.length() ; j++){
map[i][j] = str.charAt(j) - '0';
}
}
Bfs bfs = new Bfs(N, M, map);
int result = bfs.search(0, 0, 1);
System.out.println("result : " + result);
}
}
| 2,018 | 0.46008 | 0.447106 | 77 | 25.025974 | 22.605007 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.766234 | false | false |
3
|
cb1c925ac78a587a00688efcc1616129b404db8b
| 12,326,556,142,638 |
bbe21af8c36ac464e196319b7bf5e635e9b43c08
|
/src/main/java/com/tryton/small_world/matcher/model/PersonCriteria.java
|
903d0fb88f95a34d352cd6266cbed0df1f96bcae
|
[] |
no_license
|
mephisto2120/sw-matcher
|
https://github.com/mephisto2120/sw-matcher
|
13e0ecb2c409442d935f658ca72f32772f48ee98
|
288287b6637e81c775d6df3a958fa4d56a4fbd9a
|
refs/heads/main
| 2023-03-24T23:51:33.083000 | 2021-01-29T20:48:45 | 2021-01-29T20:48:45 | 332,491,136 | 0 | 0 | null | false | 2021-03-22T14:18:36 | 2021-01-24T15:59:28 | 2021-01-29T20:48:48 | 2021-03-22T14:18:36 | 12 | 0 | 0 | 1 |
Java
| false | false |
package com.tryton.small_world.matcher.model;
import lombok.Builder;
import lombok.ToString;
import lombok.Value;
@Builder
@Value
@ToString
public class PersonCriteria {
private Long customerId;
private String firstName;
private String lastName;
}
|
UTF-8
|
Java
| 262 |
java
|
PersonCriteria.java
|
Java
|
[] | null |
[] |
package com.tryton.small_world.matcher.model;
import lombok.Builder;
import lombok.ToString;
import lombok.Value;
@Builder
@Value
@ToString
public class PersonCriteria {
private Long customerId;
private String firstName;
private String lastName;
}
| 262 | 0.774809 | 0.774809 | 14 | 17.714285 | 13.301066 | 45 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
3
|
343482a59738d2950f93569e347cbe1bd2be683a
| 12,326,556,139,904 |
71a9df89ab4bced21cf1608539a777e58744e4c0
|
/src/Task3/IncomeTaxCalculator.java
|
233c2cfac0169ef1e68bfdde20e0882771818676
|
[] |
no_license
|
KYespayeva/Java
|
https://github.com/KYespayeva/Java
|
7a237648b20649502b6ffbcf94a79967c7fc1965
|
296f87d925277da70d502a1ab5036d0ef7cb1cd0
|
refs/heads/master
| 2023-04-12T20:19:05.298000 | 2021-04-24T19:47:19 | 2021-04-24T19:47:19 | 348,037,147 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package Task3;
import java.util.Scanner;
public class IncomeTaxCalculator {
public static void main(String[] args) {
Scanner in = new Scanner((System.in));
final double TAX_RATE_ABOVE_20K = 0.1;
final double TAX_RATE_ABOVE_40K = 0.2;
final double TAX_RATE_ABOVE_60K = 0.3;
final double TAX_RATE = 0.0;
int taxableIncome;
double i;
double taxPayable;
System.out.print("Введите налогооблогаемый доход: ");
taxableIncome = in.nextInt();
System.out.print(" доллара США" + "\n");
if (taxableIncome>=60000){
double ost = taxableIncome - 60000;
taxPayable = (ost * TAX_RATE_ABOVE_60K) + (20000 * TAX_RATE_ABOVE_40K) + (20000 * TAX_RATE_ABOVE_20K);
}
else if (taxableIncome >=40000) // 35000 - 20000 // 40000-20000
{
double ost = taxableIncome - 40000;
taxPayable = (ost * TAX_RATE_ABOVE_40K) + (20000 * TAX_RATE_ABOVE_20K); // 50000 0 0.1
}
else if (taxableIncome >=20000)
{
double ost = taxableIncome - 20000;
taxPayable = (ost * TAX_RATE_ABOVE_20K) ;
}
else {
taxPayable = taxableIncome * TAX_RATE;
}
System.out.print("Подоходный налог, подлежащий уплате, составляет: " + taxPayable);
System.out.print(" долларов США");
}
}
|
UTF-8
|
Java
| 1,628 |
java
|
IncomeTaxCalculator.java
|
Java
|
[] | null |
[] |
package Task3;
import java.util.Scanner;
public class IncomeTaxCalculator {
public static void main(String[] args) {
Scanner in = new Scanner((System.in));
final double TAX_RATE_ABOVE_20K = 0.1;
final double TAX_RATE_ABOVE_40K = 0.2;
final double TAX_RATE_ABOVE_60K = 0.3;
final double TAX_RATE = 0.0;
int taxableIncome;
double i;
double taxPayable;
System.out.print("Введите налогооблогаемый доход: ");
taxableIncome = in.nextInt();
System.out.print(" доллара США" + "\n");
if (taxableIncome>=60000){
double ost = taxableIncome - 60000;
taxPayable = (ost * TAX_RATE_ABOVE_60K) + (20000 * TAX_RATE_ABOVE_40K) + (20000 * TAX_RATE_ABOVE_20K);
}
else if (taxableIncome >=40000) // 35000 - 20000 // 40000-20000
{
double ost = taxableIncome - 40000;
taxPayable = (ost * TAX_RATE_ABOVE_40K) + (20000 * TAX_RATE_ABOVE_20K); // 50000 0 0.1
}
else if (taxableIncome >=20000)
{
double ost = taxableIncome - 20000;
taxPayable = (ost * TAX_RATE_ABOVE_20K) ;
}
else {
taxPayable = taxableIncome * TAX_RATE;
}
System.out.print("Подоходный налог, подлежащий уплате, составляет: " + taxPayable);
System.out.print(" долларов США");
}
}
| 1,628 | 0.518205 | 0.453186 | 46 | 32.45652 | 29.300323 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.521739 | false | false |
3
|
c30c4ed4802d7a69d8a02a856bc886b951d10c37
| 10,075,993,341,119 |
3a5f44fc232e369e84ef908eeda4218eb538d631
|
/partnerdevapp/partnersdevapp-service/src/main/java/ar/edu/unq/partnersdevapp/service/dto/plandecarreradto/NivelListaDto.java
|
ab96dc09c238c7538f39eea1c8988f8a0c16b429
|
[] |
no_license
|
cdmarchionne/devapp-partners-devapp
|
https://github.com/cdmarchionne/devapp-partners-devapp
|
20ac68e95c85b67c8785d4e2b0fe6fde00804afe
|
0e79ad833cf60ef440b141aca4643e72cfbe2269
|
refs/heads/master
| 2021-01-22T17:22:06.741000 | 2011-07-14T07:37:16 | 2011-07-14T07:37:16 | 32,325,176 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package ar.edu.unq.partnersdevapp.service.dto.plandecarreradto;
import java.util.ArrayList;
import java.util.List;
import ar.edu.unq.partnersdevapp.service.dto.Dto;
/**
* Para transferir lista de niveles
*/
public class NivelListaDto implements Dto {
private static final long serialVersionUID = 1L;
private List<NivelDto> opciones = new ArrayList<NivelDto>();
private NivelDto seleccion;
public void setOpciones(final List<NivelDto> opciones) {
this.opciones = opciones;
}
public List<NivelDto> getOpciones() {
return opciones;
}
public NivelDto getSeleccion() {
return seleccion;
}
public void setSeleccion(final NivelDto seleccion) {
this.seleccion = seleccion;
}
}
|
UTF-8
|
Java
| 757 |
java
|
NivelListaDto.java
|
Java
|
[] | null |
[] |
package ar.edu.unq.partnersdevapp.service.dto.plandecarreradto;
import java.util.ArrayList;
import java.util.List;
import ar.edu.unq.partnersdevapp.service.dto.Dto;
/**
* Para transferir lista de niveles
*/
public class NivelListaDto implements Dto {
private static final long serialVersionUID = 1L;
private List<NivelDto> opciones = new ArrayList<NivelDto>();
private NivelDto seleccion;
public void setOpciones(final List<NivelDto> opciones) {
this.opciones = opciones;
}
public List<NivelDto> getOpciones() {
return opciones;
}
public NivelDto getSeleccion() {
return seleccion;
}
public void setSeleccion(final NivelDto seleccion) {
this.seleccion = seleccion;
}
}
| 757 | 0.698811 | 0.69749 | 34 | 21.264706 | 21.956251 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.323529 | false | false |
3
|
3e3cbcec6b652247a070128b6e07702204a32c04
| 14,929,306,323,132 |
6d0110102105204985a9c318dfaf952b63b10b3c
|
/ajax02/src/bean/city.java
|
b8f552a1f053ad0b4c647ec4dde9cb2ac68ac43b
|
[] |
no_license
|
ah-kevin/ajaxDemo
|
https://github.com/ah-kevin/ajaxDemo
|
f6ca567eccf88dd6669f4850fcfe6b017ea182b3
|
5c05757b4fa1c43b2364bed6850bbdf27e3cb1dd
|
refs/heads/master
| 2021-01-10T21:05:15.427000 | 2014-12-21T13:25:21 | 2014-12-21T13:25:21 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package bean;
/**
* Created by Administrator on 2014/12/21.
*/
public class city {
private String name;
private String value;
public city() {
}
public city(String name, String value) {
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
|
UTF-8
|
Java
| 540 |
java
|
city.java
|
Java
|
[
{
"context": "package bean;\n\n/**\n * Created by Administrator on 2014/12/21.\n */\npublic class city {\n privat",
"end": 46,
"score": 0.9488586187362671,
"start": 33,
"tag": "NAME",
"value": "Administrator"
}
] | null |
[] |
package bean;
/**
* Created by Administrator on 2014/12/21.
*/
public class city {
private String name;
private String value;
public city() {
}
public city(String name, String value) {
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
| 540 | 0.559259 | 0.544444 | 33 | 15.363636 | 14.148173 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.30303 | false | false |
3
|
d6ebbdbcf1d8e433b4c98c43543119c671d03ef4
| 4,183,298,206,648 |
07077b188bb5285476d0aad8ba12193292ac4e7c
|
/src/com/sed/graph/undirected/HasCycle.java
|
1907989d62416586a4121dcfa8ad32982155e219
|
[] |
no_license
|
piyushGithub01/basic-algorithm-datastructure
|
https://github.com/piyushGithub01/basic-algorithm-datastructure
|
e053a0bf757f83263a29b60137c3dfe6dec392fb
|
8afdaf4910942943edb8d6a3d9038fc1ad602dc4
|
refs/heads/master
| 2021-07-13T17:32:50.931000 | 2021-07-10T06:00:32 | 2021-07-10T06:00:32 | 86,923,060 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.sed.graph.undirected;
public class HasCycle {
private boolean[] marked;
private boolean hasCycle;
public HasCycle(GraphAdjList g) {
marked = new boolean[g.getVertexCount()];
for(int i=0; i<g.getVertexCount(); i++) {
if(!marked[i]) {
dfs(g, i, i);
}
}
}
private void dfs(GraphAdjList g, int v, int u) {
marked[v] = true;
for(int w: g.getAdjListOf(v)) {
if(!marked[w]) {
dfs(g, w, v);
} else {
if(w!=u) {
hasCycle = true;
}
}
}
}
public boolean hasCycle() {
return hasCycle;
}
}
|
UTF-8
|
Java
| 557 |
java
|
HasCycle.java
|
Java
|
[] | null |
[] |
package com.sed.graph.undirected;
public class HasCycle {
private boolean[] marked;
private boolean hasCycle;
public HasCycle(GraphAdjList g) {
marked = new boolean[g.getVertexCount()];
for(int i=0; i<g.getVertexCount(); i++) {
if(!marked[i]) {
dfs(g, i, i);
}
}
}
private void dfs(GraphAdjList g, int v, int u) {
marked[v] = true;
for(int w: g.getAdjListOf(v)) {
if(!marked[w]) {
dfs(g, w, v);
} else {
if(w!=u) {
hasCycle = true;
}
}
}
}
public boolean hasCycle() {
return hasCycle;
}
}
| 557 | 0.581688 | 0.579892 | 34 | 15.382353 | 14.233379 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.323529 | false | false |
3
|
bddbd05f478b8586e6ee86f79017b34f82fb63bb
| 7,327,214,228,975 |
4304a1c350fb6e5c1813c04b84d4786b8b089fdf
|
/xiezi44/src/main/java/com/csc/xiezi44/web/action/FavouriteAction.java
|
6fed59baef62298ab7a0daef036bfffe42dd9d47
|
[] |
no_license
|
Kris6Wu/YoungOG
|
https://github.com/Kris6Wu/YoungOG
|
779ae3f4898858bb119b081a32f10bdb5a7b6cc4
|
0493019a054ff8c7da2e9e417b3cc1f22a634fc0
|
refs/heads/master
| 2020-03-26T13:53:57.840000 | 2018-08-31T06:14:23 | 2018-08-31T06:14:23 | 144,962,174 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.csc.xiezi44.web.action;
public class FavouriteAction {
}
|
UTF-8
|
Java
| 71 |
java
|
FavouriteAction.java
|
Java
|
[] | null |
[] |
package com.csc.xiezi44.web.action;
public class FavouriteAction {
}
| 71 | 0.774648 | 0.746479 | 5 | 13.2 | 15.841717 | 35 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false |
3
|
b2cad03d33f3932dd6c3117340853421de79d0dd
| 16,363,825,406,713 |
ee361252912fbb242aa4d7a16b35d132736a94ff
|
/fj-db-hibernate/src/main/java/org/forumj/hibernate/db/util/DaoFactory.java
|
bbedda7045f0301b3272d87f4b378d54e576a9d6
|
[] |
no_license
|
AndrewVP/forumJ
|
https://github.com/AndrewVP/forumJ
|
08c470fbc8c9852302aa2a918b9c14a3d38cb521
|
5a9db4dc11329f9787d5c879f34b4954e17c18a8
|
refs/heads/master
| 2021-01-10T18:23:47.981000 | 2017-02-22T13:33:26 | 2017-02-22T13:33:26 | 1,754,665 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.forumj.hibernate.db.util;
public class DaoFactory {
}
|
UTF-8
|
Java
| 73 |
java
|
DaoFactory.java
|
Java
|
[] | null |
[] |
package org.forumj.hibernate.db.util;
public class DaoFactory {
}
| 73 | 0.712329 | 0.712329 | 5 | 12.6 | 15.499678 | 37 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false |
3
|
304faf26d794506fc620eb43f6d4f6b675c3daa3
| 13,125,420,075,148 |
2d3ac9f3d52159a05b9b769f5d428de299edf3d3
|
/app/src/main/java/com/a2z/deliver/Activities/insurancePolicy/InsurancePolicyActivity.java
|
2bbd990bf7f07f29fd5f6652ec864ca0bce77501
|
[] |
no_license
|
milindsolanki/a2z
|
https://github.com/milindsolanki/a2z
|
794f48512b64f0018d83c1633ef448d586c8831d
|
cbc78b0a29f56e82e9d07208b9bf5026d5b05f24
|
refs/heads/master
| 2023-03-08T08:28:22.331000 | 2021-03-01T05:25:31 | 2021-03-01T05:25:31 | 343,299,465 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.a2z.deliver.activities.insurancePolicy;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.databinding.DataBindingUtil;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.a2z.deliver.BaseApp;
import com.a2z.deliver.R;
import com.a2z.deliver.databinding.ActivityInsurancePolicyBinding;
import com.a2z.deliver.models.GetImageDetails;
import com.a2z.deliver.models.GetImageMaster;
import com.a2z.deliver.models.insurancePolicy.InsurancePolicyMaster;
import com.a2z.deliver.models.login.LoginDetails;
import com.a2z.deliver.networking.Service;
import com.a2z.deliver.utils.CommonUtils;
import com.a2z.deliver.utils.SharedPref;
import com.a2z.deliver.webService.API_Params;
import com.a2z.deliver.webService.ApiManager;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.harmis.imagepicker.CameraUtils.CameraIntentHelper;
import com.harmis.imagepicker.model.Images;
import com.harmis.imagepicker.utils.CommonKeyword;
import org.json.JSONObject;
import java.util.EventListener;
import java.util.List;
import javax.inject.Inject;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
public class InsurancePolicyActivity extends BaseApp implements View.OnClickListener, InsurancePolicyView {
ActivityInsurancePolicyBinding binding;
InsurancePolicyPresenter presenter;
@Inject
public Service service;
Activity activity;
GetImageDetails getImageDetails;
String usertImage1 = null;
String usertImage2 = null;
String usertImage3 = null;
String usertImage4 = null;
String image1 = "";
String image2 = "";
String image3 = "";
String image4 = "";
String[] cameraPermissions = {Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
private final int REQUEST_PERMISSION_CAMERA = 1;
CameraIntentHelper mCameraIntentHelper;
int whichImage;
SharedPref sharedPref;
LoginDetails loginDetails;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
getDeps( ).injectInsurancePolicy( this );
binding = DataBindingUtil.setContentView( this, R.layout.activity_insurance_policy );
binding.setClickListener( this );
binding.insuranceHeader.setClickListener( this );
activity = this;
init( );
}
public void init() {
binding.insuranceHeader.tvHomeUpdate.setVisibility( View.GONE );
binding.insuranceHeader.tvHeaderText.setText( R.string.incurancepolicyreceipt );
binding.insuranceHeader.ivHomeFilter.setImageResource( R.drawable.ic_back_30 );
binding.insuranceHeader.tvHomeUpdate.setText( R.string.update );
activity = this;
presenter = new InsurancePolicyPresenter( this, service, this );
mCameraIntentHelper = presenter.getCameraIntentHelper( );
sharedPref = SharedPref.getInstance( this );
loginDetails = sharedPref.getLoginDetailsModel( );
getImageApi( );
}
private void getImageApi() {
presenter.getImageApi( getImagePrams( ) );
}
private JsonObject getImagePrams() {
JsonObject gsonObject = new JsonObject( );
try {
JSONObject jsonObject = new JSONObject( );
jsonObject.put( API_Params.userId, loginDetails.getUserId( ) );
jsonObject.put( API_Params.flag, "3" );
JsonParser parser = new JsonParser( );
gsonObject = ( JsonObject ) parser.parse( jsonObject.toString( ) );
} catch (Exception e) {
e.printStackTrace( );
}
return gsonObject;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
super.onRequestPermissionsResult( requestCode, permissions, grantResults );
if (requestCode == REQUEST_PERMISSION_CAMERA) {
if (grantResults != null && grantResults.length > 0) {
boolean isGranted = true;
for (int i = 0; i < grantResults.length; i++) {
if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
isGranted = false;
break;
}
}
if (isGranted) {
presenter.UploadImage( whichImage );
}
}
}
}
@Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState( savedInstanceState );
mCameraIntentHelper.onSaveInstanceState( savedInstanceState );
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState( savedInstanceState );
mCameraIntentHelper.onRestoreInstanceState( savedInstanceState );
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
mCameraIntentHelper.onActivityResult( requestCode, resultCode, data );
super.onActivityResult( requestCode, resultCode, data );
Log.e( "Tag", " insert resultCode requestCode GALLERY" );
if (resultCode == CommonKeyword.RESULT_CODE_GALLERY) {
if (requestCode == CommonKeyword.REQUEST_CODE_GALLERY) {
Log.e( "Tag", "First insert resultCode requestCode GALLERY" );
List <Images> images = ( List <Images> ) data.getSerializableExtra( CommonKeyword.RESULT );
if (images != null && images.size( ) > 0) {
usertImage1 = images.get( 0 ).getImageUrl( );
}
if (usertImage1 != null) {
binding.insuranceHeader.tvHomeUpdate.setVisibility( View.VISIBLE );
binding.tvFirstUpload.setText( R.string.edit );
binding.insuranceHeader.tvHomeUpdate.setTextColor( getResources( ).getColor( R.color.colorPrimary ) );
CommonUtils.setImageUsingGlide( activity, usertImage1, binding.ivFirstUploadimage, null );
}
} else if (requestCode == CommonKeyword.SECOND_REQUEST_CODE_GALLERY) {
Log.e( "Tag", "Second insert resultCode requestCode GALLERY" );
List <Images> images = ( List <Images> ) data.getSerializableExtra( CommonKeyword.RESULT );
if (images != null && images.size( ) > 0) {
usertImage2 = images.get( 0 ).getImageUrl( );
}
if (usertImage2 != null) {
binding.insuranceHeader.tvHomeUpdate.setVisibility( View.VISIBLE );
binding.tvSecondUpload.setText( R.string.edit );
binding.insuranceHeader.tvHomeUpdate.setTextColor( getResources( ).getColor( R.color.colorPrimary ) );
CommonUtils.setImageUsingGlide( activity, usertImage2, binding.ivSecondUploadimage, null );
}
} else if (requestCode == CommonKeyword.THIRD_REQUEST_CODE_GALLERY) {
Log.e( "Tag", "Therd insert resultCode requestCode CAMERA" );
List <Images> images = ( List <Images> ) data.getSerializableExtra( CommonKeyword.RESULT );
if (images != null && images.size( ) > 0) {
usertImage3 = images.get( 0 ).getImageUrl( );
}
if (usertImage3 != null) {
binding.insuranceHeader.tvHomeUpdate.setVisibility( View.VISIBLE );
binding.tvSecondUpload.setText( R.string.edit );
binding.insuranceHeader.tvHomeUpdate.setTextColor( getResources( ).getColor( R.color.colorPrimary ) );
CommonUtils.setImageUsingGlide( activity, usertImage3, binding.ivThirdUploadimage, null );
}
} else if (requestCode == CommonKeyword.FORTH_REQUEST_CODE_GALLERY) {
Log.e( "Tag", "Therd insert resultCode requestCode CAMERA" );
List <Images> images = ( List <Images> ) data.getSerializableExtra( CommonKeyword.RESULT );
if (images != null && images.size( ) > 0) {
usertImage4 = images.get( 0 ).getImageUrl( );
}
if (usertImage4 != null) {
binding.insuranceHeader.tvHomeUpdate.setVisibility( View.VISIBLE );
binding.tvSecondUpload.setText( R.string.edit );
binding.insuranceHeader.tvHomeUpdate.setTextColor( getResources( ).getColor( R.color.colorPrimary ) );
CommonUtils.setImageUsingGlide( activity, usertImage4, binding.ivForthUploadimage, null );
}
}
} else if (resultCode == CommonKeyword.RESULT_CODE_CROP_IMAGE) {
if (requestCode == CommonKeyword.REQUEST_CODE_CAMERA) {
Log.e( "Tag", "First Cam Request" );
List <Images> images = ( List <Images> ) data.getSerializableExtra( CommonKeyword.RESULT );
if (images != null && images.size( ) > 0) {
usertImage1 = images.get( 0 ).getImageUrl( );
}
if (usertImage1 != null) {
binding.insuranceHeader.tvHomeUpdate.setVisibility( View.VISIBLE );
binding.tvFirstUpload.setText( R.string.edit );
binding.insuranceHeader.tvHomeUpdate.setTextColor( getResources( ).getColor( R.color.colorPrimary ) );
CommonUtils.setImageUsingGlide( activity, usertImage1, binding.ivFirstUploadimage, null );
}
} else if (requestCode == CommonKeyword.SECOND_REQUEST_CODE_CAMERA) {
Log.e( "Tag", "Second Cam Request" );
List <Images> images = ( List <Images> ) data.getSerializableExtra( CommonKeyword.RESULT );
if (images != null && images.size( ) > 0) {
usertImage2 = images.get( 0 ).getImageUrl( );
}
if (usertImage2 != null) {
binding.insuranceHeader.tvHomeUpdate.setVisibility( View.VISIBLE );
binding.tvSecondUpload.setText( R.string.edit );
binding.insuranceHeader.tvHomeUpdate.setTextColor( getResources( ).getColor( R.color.colorPrimary ) );
CommonUtils.setImageUsingGlide( activity, usertImage2, binding.ivSecondUploadimage, null );
}
} else if (requestCode == CommonKeyword.THIRD_REQUEST_CODE_CAMERA) {
Log.e( "Tag", "Third Cam Request" );
List <Images> images = ( List <Images> ) data.getSerializableExtra( CommonKeyword.RESULT );
if (images != null && images.size( ) > 0) {
usertImage3 = images.get( 0 ).getImageUrl( );
}
if (usertImage3 != null) {
binding.insuranceHeader.tvHomeUpdate.setVisibility( View.VISIBLE );
binding.tvSecondUpload.setText( R.string.edit );
binding.insuranceHeader.tvHomeUpdate.setTextColor( getResources( ).getColor( R.color.colorPrimary ) );
CommonUtils.setImageUsingGlide( activity, usertImage3, binding.ivThirdUploadimage, null );
}
} else if (requestCode == CommonKeyword.FORTH_REQUEST_CODE_CAMERA) {
Log.e( "Tag", "Forth Cam Request" );
List <Images> images = ( List <Images> ) data.getSerializableExtra( CommonKeyword.RESULT );
if (images != null && images.size( ) > 0) {
usertImage4 = images.get( 0 ).getImageUrl( );
}
if (usertImage4 != null) {
binding.insuranceHeader.tvHomeUpdate.setVisibility( View.VISIBLE );
binding.tvSecondUpload.setText( R.string.edit );
binding.insuranceHeader.tvHomeUpdate.setTextColor( getResources( ).getColor( R.color.colorPrimary ) );
CommonUtils.setImageUsingGlide( activity, usertImage4, binding.ivForthUploadimage, null );
}
}
}
}
@Override
public void onClick(View v) {
if (v == binding.tvFirstUpload) {
uploadFirstImage( );
} else if (v == binding.tvSecondUpload) {
uploadSecondImage( );
} else if (v == binding.tvThirdUpload) {
uploadThirdImage( );
} else if (v == binding.tvForthUpload) {
uploadFourthImage( );
} else if (v == binding.insuranceHeader.tvHomeUpdate) {
imageUploadApi( );
}else if (v==binding.insuranceHeader.ivHomeFilter){
finish();
}
}
private void imageUploadApi() {
RequestBody isUpdate = RequestBody.create( MediaType.parse( "multipart/form-data" ), "1" );
RequestBody userId = RequestBody.create( MediaType.parse( "multipart/form-data" ), loginDetails.getUserId( ) );
if (image1 != null || image2 != null || image3 != null || image4 != null) {
RequestBody isUpdateImage = RequestBody.create( MediaType.parse( "multipart/form-data" ), "1" );
MultipartBody.Part body1 = ApiManager.getMultipartImageBody( usertImage1, API_Params.image1 );
MultipartBody.Part body2 = ApiManager.getMultipartImageBody( usertImage2, API_Params.image2 );
MultipartBody.Part body3 = ApiManager.getMultipartImageBody( usertImage3, API_Params.image3 );
MultipartBody.Part body4 = ApiManager.getMultipartImageBody( usertImage4, API_Params.image4 );
presenter.getUploadIPImageAPI( isUpdate, userId, isUpdateImage, body1, body2, body3, body4 );
}else {
RequestBody isUpdateImage = RequestBody.create( MediaType.parse( "multipart/form-data" ), "0" );
MultipartBody.Part body1 = ApiManager.getMultipartImageBody( usertImage1, API_Params.image1 );
MultipartBody.Part body2 = ApiManager.getMultipartImageBody( usertImage2, API_Params.image2 );
MultipartBody.Part body3 = ApiManager.getMultipartImageBody( usertImage3, API_Params.image3 );
MultipartBody.Part body4 = ApiManager.getMultipartImageBody( usertImage4, API_Params.image4 );
presenter.getUploadIPImageAPI( isUpdate, userId, isUpdateImage, body1, body2, body3, body4 );
}
}
private void uploadFirstImage() {
whichImage = API_Params.FIRST_IMAGE;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission( Manifest.permission.READ_EXTERNAL_STORAGE ) == PackageManager.PERMISSION_GRANTED
&& checkSelfPermission( Manifest.permission.CAMERA ) == PackageManager.PERMISSION_GRANTED) {
presenter.UploadImage( whichImage );
} else {
ActivityCompat.requestPermissions( InsurancePolicyActivity.this, cameraPermissions, REQUEST_PERMISSION_CAMERA );
}
} else { //permission is automatically granted on sdk<23 upon installation
presenter.UploadImage( whichImage );
}
}
private void uploadSecondImage() {
whichImage = API_Params.SECOND_IMAGE;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission( Manifest.permission.READ_EXTERNAL_STORAGE ) == PackageManager.PERMISSION_GRANTED
&& checkSelfPermission( Manifest.permission.CAMERA ) == PackageManager.PERMISSION_GRANTED) {
presenter.UploadImage( whichImage );
} else {
ActivityCompat.requestPermissions( InsurancePolicyActivity.this, cameraPermissions, REQUEST_PERMISSION_CAMERA );
}
} else { //permission is automatically granted on sdk<23 upon installation
presenter.UploadImage( whichImage );
}
}
private void uploadThirdImage() {
whichImage = API_Params.THIRD_IMAGE;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission( Manifest.permission.READ_EXTERNAL_STORAGE ) == PackageManager.PERMISSION_GRANTED
&& checkSelfPermission( Manifest.permission.CAMERA ) == PackageManager.PERMISSION_GRANTED) {
presenter.UploadImage( whichImage );
} else {
ActivityCompat.requestPermissions( InsurancePolicyActivity.this, cameraPermissions, REQUEST_PERMISSION_CAMERA );
}
} else { //permission is automatically granted on sdk<23 upon installation
presenter.UploadImage( whichImage );
}
}
private void uploadFourthImage() {
whichImage = API_Params.FOURTH_IMAGE;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission( Manifest.permission.READ_EXTERNAL_STORAGE ) == PackageManager.PERMISSION_GRANTED
&& checkSelfPermission( Manifest.permission.CAMERA ) == PackageManager.PERMISSION_GRANTED) {
presenter.UploadImage( whichImage );
} else {
ActivityCompat.requestPermissions( InsurancePolicyActivity.this, cameraPermissions, REQUEST_PERMISSION_CAMERA );
}
} else { //permission is automatically granted on sdk<23 upon installation
presenter.UploadImage( whichImage );
}
}
@Override
public void showWait() {
CommonUtils.setProgressDialog( this, getResources( ).getString( R.string.app_name ), getResources( ).getString( R.string.uploading ) );
}
@Override
public void removeWait() {
CommonUtils.hideProgressDialog( );
}
@Override
public void onFailure(String appErrorMessage) {
Log.e( "onFailure", "0" );
}
@Override
public void getInsurancePolicySuccess(InsurancePolicyMaster insurancePolicyMaster) {
if (insurancePolicyMaster.getSuccess( ) == 1) {
Log.e( "JSON RESPONSE: ", new Gson( ).toJson( insurancePolicyMaster ).toString( ) );
/* DriverDetails driverDetails = sharedPref.getDriverDetailsModel( );
if (driverDetails == null) {
driverDetails = new DriverDetails( );
}
String front = drivingLicenceMaster.getImageFront();
String back = drivingLicenceMaster.getImageBack();
driverDetails.setImageFront( front );
driverDetails.setImageBack( back );
sharedPref.storeDriverDetails( driverDetails.toString() );
*/
getImageApi();
binding.insuranceHeader.tvHomeUpdate.setVisibility( View.GONE );
} else if (insurancePolicyMaster.getSuccess( ) == 0) {
Log.e( "getSuccess", "0" );
}
}
@Override
public void getInsurancePolicyImageSuccess(GetImageMaster getImageMaster) {
if (getImageMaster != null) {
if (getImageMaster.getSuccess( ) == 1) {
Log.e( "getSuccess", "1" );
Log.e( "JSON RESPONSE: ", new Gson( ).toJson( getImageMaster ).toString( ) );
CommonUtils.setImageUsingGlide( ( Activity ) binding.ivFirstUploadimage.getContext( ), getImageMaster.getGetImageDetails( ).get( 0 ).getImageUrl( ),
binding.ivFirstUploadimage, null );
CommonUtils.setImageUsingGlide( ( Activity ) binding.ivFirstUploadimage.getContext( ), getImageMaster.getGetImageDetails( ).get( 1 ).getImageUrl( ),
binding.ivSecondUploadimage, null );
CommonUtils.setImageUsingGlide( ( Activity ) binding.ivFirstUploadimage.getContext( ), getImageMaster.getGetImageDetails( ).get( 2 ).getImageUrl( ),
binding.ivThirdUploadimage, null );
CommonUtils.setImageUsingGlide( ( Activity ) binding.ivFirstUploadimage.getContext( ), getImageMaster.getGetImageDetails( ).get( 3 ).getImageUrl( ),
binding.ivForthUploadimage, null );
image1 = getImageMaster.getGetImageDetails( ).get( 0 ).getImageUrl( );
image2 = getImageMaster.getGetImageDetails( ).get( 1 ).getImageUrl( );
image3 = getImageMaster.getGetImageDetails( ).get( 2 ).getImageUrl( );
image4 = getImageMaster.getGetImageDetails( ).get( 3 ).getImageUrl( );
binding.tvFirstUpload.setText( getResources().getString( R.string.edit ));
binding.tvSecondUpload.setText( getResources().getString( R.string.edit ) );
binding.tvThirdUpload.setText(getResources().getString( R.string.edit ) );
binding.tvForthUpload.setText( getResources().getString( R.string.edit ) );
} else if (getImageMaster.getSuccess( ) == 0) {
Log.e( "getSuccess", "0" );
}
}
}
}
|
UTF-8
|
Java
| 21,270 |
java
|
InsurancePolicyActivity.java
|
Java
|
[] | null |
[] |
package com.a2z.deliver.activities.insurancePolicy;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.databinding.DataBindingUtil;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.a2z.deliver.BaseApp;
import com.a2z.deliver.R;
import com.a2z.deliver.databinding.ActivityInsurancePolicyBinding;
import com.a2z.deliver.models.GetImageDetails;
import com.a2z.deliver.models.GetImageMaster;
import com.a2z.deliver.models.insurancePolicy.InsurancePolicyMaster;
import com.a2z.deliver.models.login.LoginDetails;
import com.a2z.deliver.networking.Service;
import com.a2z.deliver.utils.CommonUtils;
import com.a2z.deliver.utils.SharedPref;
import com.a2z.deliver.webService.API_Params;
import com.a2z.deliver.webService.ApiManager;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.harmis.imagepicker.CameraUtils.CameraIntentHelper;
import com.harmis.imagepicker.model.Images;
import com.harmis.imagepicker.utils.CommonKeyword;
import org.json.JSONObject;
import java.util.EventListener;
import java.util.List;
import javax.inject.Inject;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
public class InsurancePolicyActivity extends BaseApp implements View.OnClickListener, InsurancePolicyView {
ActivityInsurancePolicyBinding binding;
InsurancePolicyPresenter presenter;
@Inject
public Service service;
Activity activity;
GetImageDetails getImageDetails;
String usertImage1 = null;
String usertImage2 = null;
String usertImage3 = null;
String usertImage4 = null;
String image1 = "";
String image2 = "";
String image3 = "";
String image4 = "";
String[] cameraPermissions = {Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
private final int REQUEST_PERMISSION_CAMERA = 1;
CameraIntentHelper mCameraIntentHelper;
int whichImage;
SharedPref sharedPref;
LoginDetails loginDetails;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
getDeps( ).injectInsurancePolicy( this );
binding = DataBindingUtil.setContentView( this, R.layout.activity_insurance_policy );
binding.setClickListener( this );
binding.insuranceHeader.setClickListener( this );
activity = this;
init( );
}
public void init() {
binding.insuranceHeader.tvHomeUpdate.setVisibility( View.GONE );
binding.insuranceHeader.tvHeaderText.setText( R.string.incurancepolicyreceipt );
binding.insuranceHeader.ivHomeFilter.setImageResource( R.drawable.ic_back_30 );
binding.insuranceHeader.tvHomeUpdate.setText( R.string.update );
activity = this;
presenter = new InsurancePolicyPresenter( this, service, this );
mCameraIntentHelper = presenter.getCameraIntentHelper( );
sharedPref = SharedPref.getInstance( this );
loginDetails = sharedPref.getLoginDetailsModel( );
getImageApi( );
}
private void getImageApi() {
presenter.getImageApi( getImagePrams( ) );
}
private JsonObject getImagePrams() {
JsonObject gsonObject = new JsonObject( );
try {
JSONObject jsonObject = new JSONObject( );
jsonObject.put( API_Params.userId, loginDetails.getUserId( ) );
jsonObject.put( API_Params.flag, "3" );
JsonParser parser = new JsonParser( );
gsonObject = ( JsonObject ) parser.parse( jsonObject.toString( ) );
} catch (Exception e) {
e.printStackTrace( );
}
return gsonObject;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
super.onRequestPermissionsResult( requestCode, permissions, grantResults );
if (requestCode == REQUEST_PERMISSION_CAMERA) {
if (grantResults != null && grantResults.length > 0) {
boolean isGranted = true;
for (int i = 0; i < grantResults.length; i++) {
if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
isGranted = false;
break;
}
}
if (isGranted) {
presenter.UploadImage( whichImage );
}
}
}
}
@Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState( savedInstanceState );
mCameraIntentHelper.onSaveInstanceState( savedInstanceState );
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState( savedInstanceState );
mCameraIntentHelper.onRestoreInstanceState( savedInstanceState );
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
mCameraIntentHelper.onActivityResult( requestCode, resultCode, data );
super.onActivityResult( requestCode, resultCode, data );
Log.e( "Tag", " insert resultCode requestCode GALLERY" );
if (resultCode == CommonKeyword.RESULT_CODE_GALLERY) {
if (requestCode == CommonKeyword.REQUEST_CODE_GALLERY) {
Log.e( "Tag", "First insert resultCode requestCode GALLERY" );
List <Images> images = ( List <Images> ) data.getSerializableExtra( CommonKeyword.RESULT );
if (images != null && images.size( ) > 0) {
usertImage1 = images.get( 0 ).getImageUrl( );
}
if (usertImage1 != null) {
binding.insuranceHeader.tvHomeUpdate.setVisibility( View.VISIBLE );
binding.tvFirstUpload.setText( R.string.edit );
binding.insuranceHeader.tvHomeUpdate.setTextColor( getResources( ).getColor( R.color.colorPrimary ) );
CommonUtils.setImageUsingGlide( activity, usertImage1, binding.ivFirstUploadimage, null );
}
} else if (requestCode == CommonKeyword.SECOND_REQUEST_CODE_GALLERY) {
Log.e( "Tag", "Second insert resultCode requestCode GALLERY" );
List <Images> images = ( List <Images> ) data.getSerializableExtra( CommonKeyword.RESULT );
if (images != null && images.size( ) > 0) {
usertImage2 = images.get( 0 ).getImageUrl( );
}
if (usertImage2 != null) {
binding.insuranceHeader.tvHomeUpdate.setVisibility( View.VISIBLE );
binding.tvSecondUpload.setText( R.string.edit );
binding.insuranceHeader.tvHomeUpdate.setTextColor( getResources( ).getColor( R.color.colorPrimary ) );
CommonUtils.setImageUsingGlide( activity, usertImage2, binding.ivSecondUploadimage, null );
}
} else if (requestCode == CommonKeyword.THIRD_REQUEST_CODE_GALLERY) {
Log.e( "Tag", "Therd insert resultCode requestCode CAMERA" );
List <Images> images = ( List <Images> ) data.getSerializableExtra( CommonKeyword.RESULT );
if (images != null && images.size( ) > 0) {
usertImage3 = images.get( 0 ).getImageUrl( );
}
if (usertImage3 != null) {
binding.insuranceHeader.tvHomeUpdate.setVisibility( View.VISIBLE );
binding.tvSecondUpload.setText( R.string.edit );
binding.insuranceHeader.tvHomeUpdate.setTextColor( getResources( ).getColor( R.color.colorPrimary ) );
CommonUtils.setImageUsingGlide( activity, usertImage3, binding.ivThirdUploadimage, null );
}
} else if (requestCode == CommonKeyword.FORTH_REQUEST_CODE_GALLERY) {
Log.e( "Tag", "Therd insert resultCode requestCode CAMERA" );
List <Images> images = ( List <Images> ) data.getSerializableExtra( CommonKeyword.RESULT );
if (images != null && images.size( ) > 0) {
usertImage4 = images.get( 0 ).getImageUrl( );
}
if (usertImage4 != null) {
binding.insuranceHeader.tvHomeUpdate.setVisibility( View.VISIBLE );
binding.tvSecondUpload.setText( R.string.edit );
binding.insuranceHeader.tvHomeUpdate.setTextColor( getResources( ).getColor( R.color.colorPrimary ) );
CommonUtils.setImageUsingGlide( activity, usertImage4, binding.ivForthUploadimage, null );
}
}
} else if (resultCode == CommonKeyword.RESULT_CODE_CROP_IMAGE) {
if (requestCode == CommonKeyword.REQUEST_CODE_CAMERA) {
Log.e( "Tag", "First Cam Request" );
List <Images> images = ( List <Images> ) data.getSerializableExtra( CommonKeyword.RESULT );
if (images != null && images.size( ) > 0) {
usertImage1 = images.get( 0 ).getImageUrl( );
}
if (usertImage1 != null) {
binding.insuranceHeader.tvHomeUpdate.setVisibility( View.VISIBLE );
binding.tvFirstUpload.setText( R.string.edit );
binding.insuranceHeader.tvHomeUpdate.setTextColor( getResources( ).getColor( R.color.colorPrimary ) );
CommonUtils.setImageUsingGlide( activity, usertImage1, binding.ivFirstUploadimage, null );
}
} else if (requestCode == CommonKeyword.SECOND_REQUEST_CODE_CAMERA) {
Log.e( "Tag", "Second Cam Request" );
List <Images> images = ( List <Images> ) data.getSerializableExtra( CommonKeyword.RESULT );
if (images != null && images.size( ) > 0) {
usertImage2 = images.get( 0 ).getImageUrl( );
}
if (usertImage2 != null) {
binding.insuranceHeader.tvHomeUpdate.setVisibility( View.VISIBLE );
binding.tvSecondUpload.setText( R.string.edit );
binding.insuranceHeader.tvHomeUpdate.setTextColor( getResources( ).getColor( R.color.colorPrimary ) );
CommonUtils.setImageUsingGlide( activity, usertImage2, binding.ivSecondUploadimage, null );
}
} else if (requestCode == CommonKeyword.THIRD_REQUEST_CODE_CAMERA) {
Log.e( "Tag", "Third Cam Request" );
List <Images> images = ( List <Images> ) data.getSerializableExtra( CommonKeyword.RESULT );
if (images != null && images.size( ) > 0) {
usertImage3 = images.get( 0 ).getImageUrl( );
}
if (usertImage3 != null) {
binding.insuranceHeader.tvHomeUpdate.setVisibility( View.VISIBLE );
binding.tvSecondUpload.setText( R.string.edit );
binding.insuranceHeader.tvHomeUpdate.setTextColor( getResources( ).getColor( R.color.colorPrimary ) );
CommonUtils.setImageUsingGlide( activity, usertImage3, binding.ivThirdUploadimage, null );
}
} else if (requestCode == CommonKeyword.FORTH_REQUEST_CODE_CAMERA) {
Log.e( "Tag", "Forth Cam Request" );
List <Images> images = ( List <Images> ) data.getSerializableExtra( CommonKeyword.RESULT );
if (images != null && images.size( ) > 0) {
usertImage4 = images.get( 0 ).getImageUrl( );
}
if (usertImage4 != null) {
binding.insuranceHeader.tvHomeUpdate.setVisibility( View.VISIBLE );
binding.tvSecondUpload.setText( R.string.edit );
binding.insuranceHeader.tvHomeUpdate.setTextColor( getResources( ).getColor( R.color.colorPrimary ) );
CommonUtils.setImageUsingGlide( activity, usertImage4, binding.ivForthUploadimage, null );
}
}
}
}
@Override
public void onClick(View v) {
if (v == binding.tvFirstUpload) {
uploadFirstImage( );
} else if (v == binding.tvSecondUpload) {
uploadSecondImage( );
} else if (v == binding.tvThirdUpload) {
uploadThirdImage( );
} else if (v == binding.tvForthUpload) {
uploadFourthImage( );
} else if (v == binding.insuranceHeader.tvHomeUpdate) {
imageUploadApi( );
}else if (v==binding.insuranceHeader.ivHomeFilter){
finish();
}
}
private void imageUploadApi() {
RequestBody isUpdate = RequestBody.create( MediaType.parse( "multipart/form-data" ), "1" );
RequestBody userId = RequestBody.create( MediaType.parse( "multipart/form-data" ), loginDetails.getUserId( ) );
if (image1 != null || image2 != null || image3 != null || image4 != null) {
RequestBody isUpdateImage = RequestBody.create( MediaType.parse( "multipart/form-data" ), "1" );
MultipartBody.Part body1 = ApiManager.getMultipartImageBody( usertImage1, API_Params.image1 );
MultipartBody.Part body2 = ApiManager.getMultipartImageBody( usertImage2, API_Params.image2 );
MultipartBody.Part body3 = ApiManager.getMultipartImageBody( usertImage3, API_Params.image3 );
MultipartBody.Part body4 = ApiManager.getMultipartImageBody( usertImage4, API_Params.image4 );
presenter.getUploadIPImageAPI( isUpdate, userId, isUpdateImage, body1, body2, body3, body4 );
}else {
RequestBody isUpdateImage = RequestBody.create( MediaType.parse( "multipart/form-data" ), "0" );
MultipartBody.Part body1 = ApiManager.getMultipartImageBody( usertImage1, API_Params.image1 );
MultipartBody.Part body2 = ApiManager.getMultipartImageBody( usertImage2, API_Params.image2 );
MultipartBody.Part body3 = ApiManager.getMultipartImageBody( usertImage3, API_Params.image3 );
MultipartBody.Part body4 = ApiManager.getMultipartImageBody( usertImage4, API_Params.image4 );
presenter.getUploadIPImageAPI( isUpdate, userId, isUpdateImage, body1, body2, body3, body4 );
}
}
private void uploadFirstImage() {
whichImage = API_Params.FIRST_IMAGE;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission( Manifest.permission.READ_EXTERNAL_STORAGE ) == PackageManager.PERMISSION_GRANTED
&& checkSelfPermission( Manifest.permission.CAMERA ) == PackageManager.PERMISSION_GRANTED) {
presenter.UploadImage( whichImage );
} else {
ActivityCompat.requestPermissions( InsurancePolicyActivity.this, cameraPermissions, REQUEST_PERMISSION_CAMERA );
}
} else { //permission is automatically granted on sdk<23 upon installation
presenter.UploadImage( whichImage );
}
}
private void uploadSecondImage() {
whichImage = API_Params.SECOND_IMAGE;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission( Manifest.permission.READ_EXTERNAL_STORAGE ) == PackageManager.PERMISSION_GRANTED
&& checkSelfPermission( Manifest.permission.CAMERA ) == PackageManager.PERMISSION_GRANTED) {
presenter.UploadImage( whichImage );
} else {
ActivityCompat.requestPermissions( InsurancePolicyActivity.this, cameraPermissions, REQUEST_PERMISSION_CAMERA );
}
} else { //permission is automatically granted on sdk<23 upon installation
presenter.UploadImage( whichImage );
}
}
private void uploadThirdImage() {
whichImage = API_Params.THIRD_IMAGE;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission( Manifest.permission.READ_EXTERNAL_STORAGE ) == PackageManager.PERMISSION_GRANTED
&& checkSelfPermission( Manifest.permission.CAMERA ) == PackageManager.PERMISSION_GRANTED) {
presenter.UploadImage( whichImage );
} else {
ActivityCompat.requestPermissions( InsurancePolicyActivity.this, cameraPermissions, REQUEST_PERMISSION_CAMERA );
}
} else { //permission is automatically granted on sdk<23 upon installation
presenter.UploadImage( whichImage );
}
}
private void uploadFourthImage() {
whichImage = API_Params.FOURTH_IMAGE;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission( Manifest.permission.READ_EXTERNAL_STORAGE ) == PackageManager.PERMISSION_GRANTED
&& checkSelfPermission( Manifest.permission.CAMERA ) == PackageManager.PERMISSION_GRANTED) {
presenter.UploadImage( whichImage );
} else {
ActivityCompat.requestPermissions( InsurancePolicyActivity.this, cameraPermissions, REQUEST_PERMISSION_CAMERA );
}
} else { //permission is automatically granted on sdk<23 upon installation
presenter.UploadImage( whichImage );
}
}
@Override
public void showWait() {
CommonUtils.setProgressDialog( this, getResources( ).getString( R.string.app_name ), getResources( ).getString( R.string.uploading ) );
}
@Override
public void removeWait() {
CommonUtils.hideProgressDialog( );
}
@Override
public void onFailure(String appErrorMessage) {
Log.e( "onFailure", "0" );
}
@Override
public void getInsurancePolicySuccess(InsurancePolicyMaster insurancePolicyMaster) {
if (insurancePolicyMaster.getSuccess( ) == 1) {
Log.e( "JSON RESPONSE: ", new Gson( ).toJson( insurancePolicyMaster ).toString( ) );
/* DriverDetails driverDetails = sharedPref.getDriverDetailsModel( );
if (driverDetails == null) {
driverDetails = new DriverDetails( );
}
String front = drivingLicenceMaster.getImageFront();
String back = drivingLicenceMaster.getImageBack();
driverDetails.setImageFront( front );
driverDetails.setImageBack( back );
sharedPref.storeDriverDetails( driverDetails.toString() );
*/
getImageApi();
binding.insuranceHeader.tvHomeUpdate.setVisibility( View.GONE );
} else if (insurancePolicyMaster.getSuccess( ) == 0) {
Log.e( "getSuccess", "0" );
}
}
@Override
public void getInsurancePolicyImageSuccess(GetImageMaster getImageMaster) {
if (getImageMaster != null) {
if (getImageMaster.getSuccess( ) == 1) {
Log.e( "getSuccess", "1" );
Log.e( "JSON RESPONSE: ", new Gson( ).toJson( getImageMaster ).toString( ) );
CommonUtils.setImageUsingGlide( ( Activity ) binding.ivFirstUploadimage.getContext( ), getImageMaster.getGetImageDetails( ).get( 0 ).getImageUrl( ),
binding.ivFirstUploadimage, null );
CommonUtils.setImageUsingGlide( ( Activity ) binding.ivFirstUploadimage.getContext( ), getImageMaster.getGetImageDetails( ).get( 1 ).getImageUrl( ),
binding.ivSecondUploadimage, null );
CommonUtils.setImageUsingGlide( ( Activity ) binding.ivFirstUploadimage.getContext( ), getImageMaster.getGetImageDetails( ).get( 2 ).getImageUrl( ),
binding.ivThirdUploadimage, null );
CommonUtils.setImageUsingGlide( ( Activity ) binding.ivFirstUploadimage.getContext( ), getImageMaster.getGetImageDetails( ).get( 3 ).getImageUrl( ),
binding.ivForthUploadimage, null );
image1 = getImageMaster.getGetImageDetails( ).get( 0 ).getImageUrl( );
image2 = getImageMaster.getGetImageDetails( ).get( 1 ).getImageUrl( );
image3 = getImageMaster.getGetImageDetails( ).get( 2 ).getImageUrl( );
image4 = getImageMaster.getGetImageDetails( ).get( 3 ).getImageUrl( );
binding.tvFirstUpload.setText( getResources().getString( R.string.edit ));
binding.tvSecondUpload.setText( getResources().getString( R.string.edit ) );
binding.tvThirdUpload.setText(getResources().getString( R.string.edit ) );
binding.tvForthUpload.setText( getResources().getString( R.string.edit ) );
} else if (getImageMaster.getSuccess( ) == 0) {
Log.e( "getSuccess", "0" );
}
}
}
}
| 21,270 | 0.629525 | 0.623037 | 437 | 47.672768 | 37.613419 | 164 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75286 | false | false |
3
|
d1ecbfc1dcdeac928f1a9323071b9829aace026c
| 17,179,937,981 |
1702982561569df407472f4dc91c5e88d5fd4b38
|
/src/test/java/MergeIntervalTest.java
|
dfc2bc5ba9e679de9c0b7cb4dc2101a0bcc6b0ed
|
[] |
no_license
|
darcy1990/darcy-leetcode
|
https://github.com/darcy1990/darcy-leetcode
|
9f635354a07f46bf2ad1a99d3b955951d12078b1
|
c92ada4ef6676161fb4d3ed0af9ffbafa70b5137
|
refs/heads/master
| 2023-02-24T00:44:18.771000 | 2023-02-11T01:36:06 | 2023-02-11T01:36:06 | 38,557,608 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import org.junit.Test;
/**
* @Author: Zhongming Yuan
* @Date: 2021/5/11 5:05 下午
*/
public class MergeIntervalTest {
@Test
public void merge() {
MergeInterval mi = new MergeInterval();
mi.merge(new int[][]{{1,3},{2,6},{8,10},{15,18}});
}
}
|
UTF-8
|
Java
| 275 |
java
|
MergeIntervalTest.java
|
Java
|
[
{
"context": "import org.junit.Test;\n\n/**\n * @Author: Zhongming Yuan\n * @Date: 2021/5/11 5:05 下午\n */\npublic class Merg",
"end": 54,
"score": 0.9998227953910828,
"start": 40,
"tag": "NAME",
"value": "Zhongming Yuan"
}
] | null |
[] |
import org.junit.Test;
/**
* @Author: <NAME>
* @Date: 2021/5/11 5:05 下午
*/
public class MergeIntervalTest {
@Test
public void merge() {
MergeInterval mi = new MergeInterval();
mi.merge(new int[][]{{1,3},{2,6},{8,10},{15,18}});
}
}
| 267 | 0.571956 | 0.494465 | 14 | 18.428572 | 17.891396 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.714286 | false | false |
3
|
0c2fae43a96cb2321d4468ce9b02f8f1489fd081
| 29,154,238,021,219 |
5b3806bf69273deeffa1864954562b368f82323d
|
/tdp-core/src/main/java/cn/goldencis/tdp/core/entity/ScheduledTaskDO.java
|
4e2155783a28d88413f9dfc8f04bf1318f9656ab
|
[] |
no_license
|
UniqueSuccess/tdp-portal-parent
|
https://github.com/UniqueSuccess/tdp-portal-parent
|
a78d67aa1cd96d64743ac9c8089ffcee3fb68e42
|
b499bbc8399fa5e5dcaa140ccf8c93a5adb779c8
|
refs/heads/master
| 2020-04-01T20:41:41.744000 | 2018-11-16T03:02:04 | 2018-11-16T03:02:18 | 153,616,201 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package cn.goldencis.tdp.core.entity;
import cn.goldencis.tdp.common.entity.BaseEntity;
import java.io.Serializable;
import java.util.Date;
public class ScheduledTaskDO extends BaseEntity implements Serializable {
private Integer id;
private String guid;
private String taskReference;
private String corn;
private String period;
private String time;
private Integer processing;
private Integer taskSwitch;
private Date lastExecutionTime;
private Date createTime;
private static final long serialVersionUID = 1L;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getGuid() {
return guid;
}
public void setGuid(String guid) {
this.guid = guid == null ? null : guid.trim();
}
public String getTaskReference() {
return taskReference;
}
public void setTaskReference(String taskReference) {
this.taskReference = taskReference == null ? null : taskReference.trim();
}
public String getCorn() {
return corn;
}
public void setCorn(String corn) {
this.corn = corn == null ? null : corn.trim();
}
public String getPeriod() {
return period;
}
public void setPeriod(String period) {
this.period = period;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public Integer getProcessing() {
return processing;
}
public void setProcessing(Integer processing) {
this.processing = processing;
}
public Integer getTaskSwitch() {
return taskSwitch;
}
public void setTaskSwitch(Integer taskSwitch) {
this.taskSwitch = taskSwitch;
}
public Date getLastExecutionTime() {
return lastExecutionTime;
}
public void setLastExecutionTime(Date lastExecutionTime) {
this.lastExecutionTime = lastExecutionTime;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getPrimaryKey() {
return getId().toString();
}
}
|
UTF-8
|
Java
| 2,281 |
java
|
ScheduledTaskDO.java
|
Java
|
[] | null |
[] |
package cn.goldencis.tdp.core.entity;
import cn.goldencis.tdp.common.entity.BaseEntity;
import java.io.Serializable;
import java.util.Date;
public class ScheduledTaskDO extends BaseEntity implements Serializable {
private Integer id;
private String guid;
private String taskReference;
private String corn;
private String period;
private String time;
private Integer processing;
private Integer taskSwitch;
private Date lastExecutionTime;
private Date createTime;
private static final long serialVersionUID = 1L;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getGuid() {
return guid;
}
public void setGuid(String guid) {
this.guid = guid == null ? null : guid.trim();
}
public String getTaskReference() {
return taskReference;
}
public void setTaskReference(String taskReference) {
this.taskReference = taskReference == null ? null : taskReference.trim();
}
public String getCorn() {
return corn;
}
public void setCorn(String corn) {
this.corn = corn == null ? null : corn.trim();
}
public String getPeriod() {
return period;
}
public void setPeriod(String period) {
this.period = period;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public Integer getProcessing() {
return processing;
}
public void setProcessing(Integer processing) {
this.processing = processing;
}
public Integer getTaskSwitch() {
return taskSwitch;
}
public void setTaskSwitch(Integer taskSwitch) {
this.taskSwitch = taskSwitch;
}
public Date getLastExecutionTime() {
return lastExecutionTime;
}
public void setLastExecutionTime(Date lastExecutionTime) {
this.lastExecutionTime = lastExecutionTime;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getPrimaryKey() {
return getId().toString();
}
}
| 2,281 | 0.634809 | 0.634371 | 113 | 19.194691 | 19.295494 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.318584 | false | false |
3
|
ce2590857aa266fad511eee14d0e95a002d4808f
| 31,258,772,019,953 |
f9bc650dc71b9534700ee615ff3062d41031de33
|
/log4j2/src/main/java/com/xinchen/log/App.java
|
b1d42028aa763f4297b18e7c56f696084413c608
|
[] |
no_license
|
melodyfff/log-practices
|
https://github.com/melodyfff/log-practices
|
8a22c2a9adc35724ce31ca31fb4c62f52289de74
|
02844d45ffb88b73d944349bc72346c7552671c5
|
refs/heads/master
| 2022-11-20T16:23:49.319000 | 2019-03-01T08:05:10 | 2019-03-01T08:05:10 | 168,287,584 | 0 | 0 | null | false | 2022-11-16T11:39:19 | 2019-01-30T05:56:35 | 2019-03-01T08:06:18 | 2022-11-16T11:39:16 | 328 | 0 | 0 | 12 |
Java
| false | false |
package com.xinchen.log;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* Hello world!
*/
public class App {
private static final Logger log = LogManager.getLogger("OK");
public static void main(String[] args) {
for (int i = 0; i < 10000; i++) {
log.info("Hello World!");
log.debug("Hello World!");
log.error("Hello World!");
log.trace("Hello World!");
}
}
}
|
UTF-8
|
Java
| 484 |
java
|
App.java
|
Java
|
[] | null |
[] |
package com.xinchen.log;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* Hello world!
*/
public class App {
private static final Logger log = LogManager.getLogger("OK");
public static void main(String[] args) {
for (int i = 0; i < 10000; i++) {
log.info("Hello World!");
log.debug("Hello World!");
log.error("Hello World!");
log.trace("Hello World!");
}
}
}
| 484 | 0.57438 | 0.557851 | 23 | 20.043478 | 19.696564 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.434783 | false | false |
3
|
80ccd9ff1e48bc0c5c8521853a163423a54dfe43
| 3,874,060,508,188 |
43c1c68bed6644b25e61118e75a6f42743226078
|
/gateway/src/main/java/com/bibliotheque/zuulserver/gateway/services/UserServiceImpl.java
|
702653ca42c7b32d66d95fece7f3c653265943aa
|
[] |
no_license
|
Zyknafein92/bibliotheque
|
https://github.com/Zyknafein92/bibliotheque
|
55fee0ef4a1b05faccd3d5f0d52e9f006c6dfa25
|
b72ecc74a32dadfc6603921e4f22eb32a0a987cf
|
refs/heads/master
| 2023-01-23T07:52:15.285000 | 2019-12-12T08:42:55 | 2019-12-12T08:42:55 | 218,281,466 | 0 | 0 | null | false | 2023-01-07T11:58:01 | 2019-10-29T12:26:51 | 2019-12-12T08:54:32 | 2023-01-07T11:58:01 | 1,924 | 0 | 0 | 29 |
Java
| false | false |
package com.bibliotheque.zuulserver.gateway.services;
import com.bibliotheque.zuulserver.gateway.exceptions.UserCreationException;
import com.bibliotheque.zuulserver.gateway.exceptions.UserNotFoundException;
import com.bibliotheque.zuulserver.gateway.model.Role;
import com.bibliotheque.zuulserver.gateway.model.RoleName;
import com.bibliotheque.zuulserver.gateway.model.User;
import com.bibliotheque.zuulserver.gateway.repository.RoleRepository;
import com.bibliotheque.zuulserver.gateway.repository.UserRepository;
import com.bibliotheque.zuulserver.gateway.services.dto.UserDTO;
import com.bibliotheque.zuulserver.gateway.services.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.HashSet;
import java.util.Set;
@Service
public class UserServiceImpl implements UserService {
@Autowired
RoleRepository roleRepository;
@Autowired
UserMapper userMapper;
@Autowired
UserRepository userRepository;
@Autowired
PasswordEncoder encoder;
@Override
public User getUser(Long id) {
User user = userRepository.getOne(id);
if(user == null) throw new UserNotFoundException(" L'utilisateur n'existe pas");
return user;
}
@Override
public User createUser(UserDTO userDTO) {
if( userDTO.getEmail() == null ) {
throw new UserCreationException("Veuillez à renseigner un Email ");
}
if( userDTO.getPassword() == null ) {
throw new UserCreationException(" Veuillez rajouter un password");
}
if( userDTO.getRoles() == null ) {
Set<Role> roles = new HashSet<>();
Role roleUser = roleRepository.findByName(RoleName.ROLE_USER);
roles.add(roleUser);
userDTO.setRoles(roles);
}
User user = userMapper.userDtoToUser(userDTO);
user.setPassword(encoder.encode(user.getPassword()));
return userRepository.save(user);
}
@Override
public void updateUser(UserDTO userDTO) {
User user = userRepository.getOne(userDTO.getId());
if(user == null) throw new UserNotFoundException(" L'utilisateur n'existe pas");
userMapper.updateUserFromUserDTO(userDTO, user);
userRepository.save(user);
}
@Override
public void deleteUser(Long id) {
userRepository.deleteById(id);
}
}
|
UTF-8
|
Java
| 2,502 |
java
|
UserServiceImpl.java
|
Java
|
[] | null |
[] |
package com.bibliotheque.zuulserver.gateway.services;
import com.bibliotheque.zuulserver.gateway.exceptions.UserCreationException;
import com.bibliotheque.zuulserver.gateway.exceptions.UserNotFoundException;
import com.bibliotheque.zuulserver.gateway.model.Role;
import com.bibliotheque.zuulserver.gateway.model.RoleName;
import com.bibliotheque.zuulserver.gateway.model.User;
import com.bibliotheque.zuulserver.gateway.repository.RoleRepository;
import com.bibliotheque.zuulserver.gateway.repository.UserRepository;
import com.bibliotheque.zuulserver.gateway.services.dto.UserDTO;
import com.bibliotheque.zuulserver.gateway.services.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.HashSet;
import java.util.Set;
@Service
public class UserServiceImpl implements UserService {
@Autowired
RoleRepository roleRepository;
@Autowired
UserMapper userMapper;
@Autowired
UserRepository userRepository;
@Autowired
PasswordEncoder encoder;
@Override
public User getUser(Long id) {
User user = userRepository.getOne(id);
if(user == null) throw new UserNotFoundException(" L'utilisateur n'existe pas");
return user;
}
@Override
public User createUser(UserDTO userDTO) {
if( userDTO.getEmail() == null ) {
throw new UserCreationException("Veuillez à renseigner un Email ");
}
if( userDTO.getPassword() == null ) {
throw new UserCreationException(" Veuillez rajouter un password");
}
if( userDTO.getRoles() == null ) {
Set<Role> roles = new HashSet<>();
Role roleUser = roleRepository.findByName(RoleName.ROLE_USER);
roles.add(roleUser);
userDTO.setRoles(roles);
}
User user = userMapper.userDtoToUser(userDTO);
user.setPassword(encoder.encode(user.getPassword()));
return userRepository.save(user);
}
@Override
public void updateUser(UserDTO userDTO) {
User user = userRepository.getOne(userDTO.getId());
if(user == null) throw new UserNotFoundException(" L'utilisateur n'existe pas");
userMapper.updateUserFromUserDTO(userDTO, user);
userRepository.save(user);
}
@Override
public void deleteUser(Long id) {
userRepository.deleteById(id);
}
}
| 2,502 | 0.716114 | 0.716114 | 77 | 31.48052 | 26.912369 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.480519 | false | false |
3
|
2facbe1064947e3204d37f9ee8cf455e724fe7da
| 26,886,495,300,970 |
d407b55ffcfd4883f48e81de28677293530e4fc2
|
/app/src/main/java/rehab/reality/alsuti/UploadActivity.java
|
3f1ed44fc70c15166d60ee47e936c6bce3ec9c28
|
[] |
no_license
|
alsuti/alsuti-android
|
https://github.com/alsuti/alsuti-android
|
9e18d222b86121dba4c9057004773ad4a18a1a89
|
83f5b1a224bf4154cc259b0e1522ad0085de927f
|
refs/heads/master
| 2020-12-31T00:09:37.697000 | 2017-02-02T16:37:30 | 2017-02-02T16:37:30 | 80,550,672 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package rehab.reality.alsuti;
import android.Manifest;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import org.apache.commons.lang3.RandomStringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.liquidplayer.javascript.JSException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
public class UploadActivity extends AppCompatActivity {
SharedPreferences prefs;
String waitingFileName;
Encrypter encrypter;
boolean encrypted = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
View decorView = getWindow().getDecorView();
int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);
setContentView(R.layout.activity_upload);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
String action = intent.getAction();
prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (intent.ACTION_SEND.equals(action) && extras.containsKey(Intent.EXTRA_STREAM)) {
Uri uri = (Uri) extras.getParcelable(Intent.EXTRA_STREAM);
waitingFileName = parseUriToFilename(uri);
}
}
public void hideButtons() {
EditText progressBox = (EditText) findViewById(R.id.editText);
Button rawUploadButton = (Button) findViewById(R.id.rawUploadButton);
Button encUploadButton = (Button) findViewById(R.id.encryptUploadButton);
rawUploadButton.setVisibility(View.INVISIBLE);
encUploadButton.setVisibility(View.INVISIBLE);
progressBox.setVisibility(View.VISIBLE);
}
public void onEncUploadBtn(View v) throws IOException, JSException {
hideButtons();
EditText progressBox = (EditText) findViewById(R.id.editText);
String password = RandomStringUtils.randomAlphanumeric(10);
progressBox.setText("Encrypting");
encrypted = true;
try {
encrypter = new Encrypter(this, getBaseContext(), waitingFileName, password);
encrypter.runEncryption();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "unable to load things", Toast.LENGTH_LONG).show();
}
}
public void onRawUploadBtn(View v) throws IOException {
hideButtons();
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
}
} else {
postFile();
}
}
public void doneEncryption(final String fName, final String password) {
runOnUiThread(new Runnable() {
@Override
public void run() {
EditText progressBox = (EditText) findViewById(R.id.editText);
waitingFileName = fName; // move this to an argument
progressBox.setText("Uploading...");
postFile(password);
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
postFile();
} else {
}
return;
}
}
}
// Taken from http://twigstechtips.blogspot.co.uk/2011/10/android-sharing-images-or-files-through.html
public String parseUriToFilename(Uri uri) {
String selectedImagePath = null;
String filemanagerPath = uri.getPath();
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
// Here you will get a null pointer if cursor is null
// This can be if you used OI file manager for picking the media
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
selectedImagePath = cursor.getString(column_index);
}
if (selectedImagePath != null) {
return selectedImagePath;
} else if (filemanagerPath != null) {
return filemanagerPath;
}
return null;
}
private void postFile() {
postFile("");
}
private void postFile(final String password) {
AsyncHttpClient client = new AsyncHttpClient();
if(prefs.getBoolean("useTor", false)) {
client.setProxy("localhost", 8118);
}
RequestParams params = new RequestParams();
client.setBasicAuth(this.prefs.getString("apiUsername", ""), this.prefs.getString("apiPassword", ""));
client.addHeader("api", "true");
try {
params.put("file", new File(waitingFileName));
} catch (FileNotFoundException e) {
Toast.makeText(this, "Error: Cannot find file", Toast.LENGTH_LONG).show();
}
if(encrypted == true) {
params.put("encrypted", true);
}
client.setConnectTimeout(60000);
client.setResponseTimeout(60000);
client.setTimeout(60000);
client.post(prefs.getString("apiEndpoint", "") + "/upload", params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, cz.msebera.android.httpclient.Header[] headers, byte[] responseBody) {
EditText linkBox = (EditText) findViewById(R.id.editText);
if(responseBody != null) {
try {
JSONObject response = new JSONObject(new String(responseBody));
if(response.getBoolean("error") != false) {
linkBox.setText("Error: " + response.getString("error"));
} else {
String link = prefs.getString("apiEndpoint", "") + "/" + response.getString("fileName");
if (password != "") {
link += "#" + password;
}
System.out.println(password);
linkBox.setText(link);
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText(link, link);
clipboard.setPrimaryClip(clip);
Toast.makeText(getBaseContext(), "Link copied to clipboard", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
linkBox.setText("Failed");
Toast.makeText(getBaseContext(), "Failed to parse response", Toast.LENGTH_LONG).show();
}
}
}
@Override
public void onFailure(int statusCode, cz.msebera.android.httpclient.Header[] headers, byte[] responseBody, Throwable error) {
if (responseBody != null) {
try {
Toast.makeText(getBaseContext(), new String(responseBody, "UTF-8"), Toast.LENGTH_LONG).show();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getBaseContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
@Override
public void onStart() {
super.onStart();
}
@Override
public void onStop() {
super.onStop();
}
}
|
UTF-8
|
Java
| 9,142 |
java
|
UploadActivity.java
|
Java
|
[
{
"context": "ViewById(R.id.editText);\n String password = RandomStringUtils.randomAlphanumeric(10);\n\n progressBox.setT",
"end": 2766,
"score": 0.7390755414962769,
"start": 2749,
"tag": "PASSWORD",
"value": "RandomStringUtils"
},
{
"context": "ext);\n String password = RandomStringUtils.randomAlphanumeric(10);\n\n progressBox.setText(\"Encrypting\");\n",
"end": 2785,
"score": 0.6919960975646973,
"start": 2767,
"tag": "PASSWORD",
"value": "randomAlphanumeric"
}
] | null |
[] |
package rehab.reality.alsuti;
import android.Manifest;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import org.apache.commons.lang3.RandomStringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.liquidplayer.javascript.JSException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
public class UploadActivity extends AppCompatActivity {
SharedPreferences prefs;
String waitingFileName;
Encrypter encrypter;
boolean encrypted = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
View decorView = getWindow().getDecorView();
int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);
setContentView(R.layout.activity_upload);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
String action = intent.getAction();
prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (intent.ACTION_SEND.equals(action) && extras.containsKey(Intent.EXTRA_STREAM)) {
Uri uri = (Uri) extras.getParcelable(Intent.EXTRA_STREAM);
waitingFileName = parseUriToFilename(uri);
}
}
public void hideButtons() {
EditText progressBox = (EditText) findViewById(R.id.editText);
Button rawUploadButton = (Button) findViewById(R.id.rawUploadButton);
Button encUploadButton = (Button) findViewById(R.id.encryptUploadButton);
rawUploadButton.setVisibility(View.INVISIBLE);
encUploadButton.setVisibility(View.INVISIBLE);
progressBox.setVisibility(View.VISIBLE);
}
public void onEncUploadBtn(View v) throws IOException, JSException {
hideButtons();
EditText progressBox = (EditText) findViewById(R.id.editText);
String password = <PASSWORD>.<PASSWORD>(10);
progressBox.setText("Encrypting");
encrypted = true;
try {
encrypter = new Encrypter(this, getBaseContext(), waitingFileName, password);
encrypter.runEncryption();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "unable to load things", Toast.LENGTH_LONG).show();
}
}
public void onRawUploadBtn(View v) throws IOException {
hideButtons();
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
}
} else {
postFile();
}
}
public void doneEncryption(final String fName, final String password) {
runOnUiThread(new Runnable() {
@Override
public void run() {
EditText progressBox = (EditText) findViewById(R.id.editText);
waitingFileName = fName; // move this to an argument
progressBox.setText("Uploading...");
postFile(password);
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
postFile();
} else {
}
return;
}
}
}
// Taken from http://twigstechtips.blogspot.co.uk/2011/10/android-sharing-images-or-files-through.html
public String parseUriToFilename(Uri uri) {
String selectedImagePath = null;
String filemanagerPath = uri.getPath();
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
// Here you will get a null pointer if cursor is null
// This can be if you used OI file manager for picking the media
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
selectedImagePath = cursor.getString(column_index);
}
if (selectedImagePath != null) {
return selectedImagePath;
} else if (filemanagerPath != null) {
return filemanagerPath;
}
return null;
}
private void postFile() {
postFile("");
}
private void postFile(final String password) {
AsyncHttpClient client = new AsyncHttpClient();
if(prefs.getBoolean("useTor", false)) {
client.setProxy("localhost", 8118);
}
RequestParams params = new RequestParams();
client.setBasicAuth(this.prefs.getString("apiUsername", ""), this.prefs.getString("apiPassword", ""));
client.addHeader("api", "true");
try {
params.put("file", new File(waitingFileName));
} catch (FileNotFoundException e) {
Toast.makeText(this, "Error: Cannot find file", Toast.LENGTH_LONG).show();
}
if(encrypted == true) {
params.put("encrypted", true);
}
client.setConnectTimeout(60000);
client.setResponseTimeout(60000);
client.setTimeout(60000);
client.post(prefs.getString("apiEndpoint", "") + "/upload", params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, cz.msebera.android.httpclient.Header[] headers, byte[] responseBody) {
EditText linkBox = (EditText) findViewById(R.id.editText);
if(responseBody != null) {
try {
JSONObject response = new JSONObject(new String(responseBody));
if(response.getBoolean("error") != false) {
linkBox.setText("Error: " + response.getString("error"));
} else {
String link = prefs.getString("apiEndpoint", "") + "/" + response.getString("fileName");
if (password != "") {
link += "#" + password;
}
System.out.println(password);
linkBox.setText(link);
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText(link, link);
clipboard.setPrimaryClip(clip);
Toast.makeText(getBaseContext(), "Link copied to clipboard", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
linkBox.setText("Failed");
Toast.makeText(getBaseContext(), "Failed to parse response", Toast.LENGTH_LONG).show();
}
}
}
@Override
public void onFailure(int statusCode, cz.msebera.android.httpclient.Header[] headers, byte[] responseBody, Throwable error) {
if (responseBody != null) {
try {
Toast.makeText(getBaseContext(), new String(responseBody, "UTF-8"), Toast.LENGTH_LONG).show();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getBaseContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
@Override
public void onStart() {
super.onStart();
}
@Override
public void onStop() {
super.onStop();
}
}
| 9,127 | 0.602603 | 0.598665 | 252 | 35.281746 | 30.053326 | 137 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.638889 | false | false |
3
|
66353a7b958d54a9e49c03486b364802d69f2065
| 2,087,354,119,111 |
6d6cf4e29e3eb942d59cc1ac0bbacab93a69f13b
|
/src/main/java/gov/idaho/isp/saktrack/validation/PasswordPresentIfRequiredValidator.java
|
c0753489ba61bb42fc25f8207fa18ad1b7806d9f
|
[
"Apache-2.0"
] |
permissive
|
BriceRoncace/SexualAssaultKitTracking
|
https://github.com/BriceRoncace/SexualAssaultKitTracking
|
dbe792befecb7ade917d4fa86af1a4e14ac77e40
|
f211afa7f29ff5899588f2b7a61e4929bb1889e8
|
refs/heads/master
| 2022-08-12T18:42:55.906000 | 2022-08-01T16:19:08 | 2022-08-01T16:19:08 | 114,917,309 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* Copyright 2017 Idaho State Police.
*
* 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 gov.idaho.isp.saktrack.validation;
import gov.idaho.isp.saktrack.domain.user.AbstractUser;
import gov.idaho.isp.saktrack.domain.user.dto.UserForm;
import gov.idaho.isp.saktrack.domain.user.password.dto.PasswordPair;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.apache.commons.lang3.StringUtils;
public class PasswordPresentIfRequiredValidator implements ConstraintValidator<PasswordPresentIfRequired, UserForm> {
@Override
public void initialize(PasswordPresentIfRequired a) {
}
@Override
public boolean isValid(UserForm userForm, ConstraintValidatorContext cvc) {
if (userForm == null || userForm.getAbstractUser() == null || userForm.getPasswordPair() == null) {
return true;
}
AbstractUser user = userForm.getAbstractUser();
PasswordPair passwordPair = userForm.getPasswordPair();
return !(user.getId() == null && StringUtils.isBlank(passwordPair.getPasswordOne()));
}
}
|
UTF-8
|
Java
| 1,610 |
java
|
PasswordPresentIfRequiredValidator.java
|
Java
|
[] | null |
[] |
/*
* Copyright 2017 Idaho State Police.
*
* 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 gov.idaho.isp.saktrack.validation;
import gov.idaho.isp.saktrack.domain.user.AbstractUser;
import gov.idaho.isp.saktrack.domain.user.dto.UserForm;
import gov.idaho.isp.saktrack.domain.user.password.dto.PasswordPair;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.apache.commons.lang3.StringUtils;
public class PasswordPresentIfRequiredValidator implements ConstraintValidator<PasswordPresentIfRequired, UserForm> {
@Override
public void initialize(PasswordPresentIfRequired a) {
}
@Override
public boolean isValid(UserForm userForm, ConstraintValidatorContext cvc) {
if (userForm == null || userForm.getAbstractUser() == null || userForm.getPasswordPair() == null) {
return true;
}
AbstractUser user = userForm.getAbstractUser();
PasswordPair passwordPair = userForm.getPasswordPair();
return !(user.getId() == null && StringUtils.isBlank(passwordPair.getPasswordOne()));
}
}
| 1,610 | 0.756522 | 0.750932 | 42 | 36.952381 | 32.758823 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.52381 | false | false |
3
|
e4f8a32887340103297871a923b5f3ae8bcbf875
| 19,155,554,148,117 |
03cdad3eacc0edb5e240adfda6dd64dda0de27a5
|
/Tusanuncios.com/PaginaTusAnuncios/src/java/Controller/EstratoJpaController.java
|
146ac98353f715030edd4c1841d146ab6f53f4fe
|
[] |
no_license
|
CarmenJaramillo/PaginaWebJPA
|
https://github.com/CarmenJaramillo/PaginaWebJPA
|
dd4c92dffeb6194bf505ca38a64698d57c57e19c
|
81da534a739abb713c1d6ff5c659337b6461f89b
|
refs/heads/master
| 2016-09-05T12:18:11.498000 | 2015-02-24T02:25:41 | 2015-02-24T02:25:41 | 30,969,669 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Controller;
import Controller.exceptions.IllegalOrphanException;
import Controller.exceptions.NonexistentEntityException;
import Controller.exceptions.PreexistingEntityException;
import Controller.exceptions.RollbackFailureException;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import Entities.Empleado;
import Entities.Estrato;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.transaction.UserTransaction;
/**
*
* @author Carmen
*/
public class EstratoJpaController implements Serializable {
public EstratoJpaController(UserTransaction utx, EntityManagerFactory emf) {
this.utx = utx;
this.emf = emf;
}
private UserTransaction utx = null;
private EntityManagerFactory emf = null;
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
public void create(Estrato estrato) throws PreexistingEntityException, RollbackFailureException, Exception {
if (estrato.getEmpleadoList() == null) {
estrato.setEmpleadoList(new ArrayList<Empleado>());
}
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
List<Empleado> attachedEmpleadoList = new ArrayList<Empleado>();
for (Empleado empleadoListEmpleadoToAttach : estrato.getEmpleadoList()) {
empleadoListEmpleadoToAttach = em.getReference(empleadoListEmpleadoToAttach.getClass(), empleadoListEmpleadoToAttach.getIdEmpleado());
attachedEmpleadoList.add(empleadoListEmpleadoToAttach);
}
estrato.setEmpleadoList(attachedEmpleadoList);
em.persist(estrato);
for (Empleado empleadoListEmpleado : estrato.getEmpleadoList()) {
Estrato oldIdEstratoOfEmpleadoListEmpleado = empleadoListEmpleado.getIdEstrato();
empleadoListEmpleado.setIdEstrato(estrato);
empleadoListEmpleado = em.merge(empleadoListEmpleado);
if (oldIdEstratoOfEmpleadoListEmpleado != null) {
oldIdEstratoOfEmpleadoListEmpleado.getEmpleadoList().remove(empleadoListEmpleado);
oldIdEstratoOfEmpleadoListEmpleado = em.merge(oldIdEstratoOfEmpleadoListEmpleado);
}
}
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
if (findEstrato(estrato.getIdEstrato()) != null) {
throw new PreexistingEntityException("Estrato " + estrato + " already exists.", ex);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void edit(Estrato estrato) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
Estrato persistentEstrato = em.find(Estrato.class, estrato.getIdEstrato());
List<Empleado> empleadoListOld = persistentEstrato.getEmpleadoList();
List<Empleado> empleadoListNew = estrato.getEmpleadoList();
List<String> illegalOrphanMessages = null;
for (Empleado empleadoListOldEmpleado : empleadoListOld) {
if (!empleadoListNew.contains(empleadoListOldEmpleado)) {
if (illegalOrphanMessages == null) {
illegalOrphanMessages = new ArrayList<String>();
}
illegalOrphanMessages.add("You must retain Empleado " + empleadoListOldEmpleado + " since its idEstrato field is not nullable.");
}
}
if (illegalOrphanMessages != null) {
throw new IllegalOrphanException(illegalOrphanMessages);
}
List<Empleado> attachedEmpleadoListNew = new ArrayList<Empleado>();
for (Empleado empleadoListNewEmpleadoToAttach : empleadoListNew) {
empleadoListNewEmpleadoToAttach = em.getReference(empleadoListNewEmpleadoToAttach.getClass(), empleadoListNewEmpleadoToAttach.getIdEmpleado());
attachedEmpleadoListNew.add(empleadoListNewEmpleadoToAttach);
}
empleadoListNew = attachedEmpleadoListNew;
estrato.setEmpleadoList(empleadoListNew);
estrato = em.merge(estrato);
for (Empleado empleadoListNewEmpleado : empleadoListNew) {
if (!empleadoListOld.contains(empleadoListNewEmpleado)) {
Estrato oldIdEstratoOfEmpleadoListNewEmpleado = empleadoListNewEmpleado.getIdEstrato();
empleadoListNewEmpleado.setIdEstrato(estrato);
empleadoListNewEmpleado = em.merge(empleadoListNewEmpleado);
if (oldIdEstratoOfEmpleadoListNewEmpleado != null && !oldIdEstratoOfEmpleadoListNewEmpleado.equals(estrato)) {
oldIdEstratoOfEmpleadoListNewEmpleado.getEmpleadoList().remove(empleadoListNewEmpleado);
oldIdEstratoOfEmpleadoListNewEmpleado = em.merge(oldIdEstratoOfEmpleadoListNewEmpleado);
}
}
}
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
String msg = ex.getLocalizedMessage();
if (msg == null || msg.length() == 0) {
Integer id = estrato.getIdEstrato();
if (findEstrato(id) == null) {
throw new NonexistentEntityException("The estrato with id " + id + " no longer exists.");
}
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
Estrato estrato;
try {
estrato = em.getReference(Estrato.class, id);
estrato.getIdEstrato();
} catch (EntityNotFoundException enfe) {
throw new NonexistentEntityException("The estrato with id " + id + " no longer exists.", enfe);
}
List<String> illegalOrphanMessages = null;
List<Empleado> empleadoListOrphanCheck = estrato.getEmpleadoList();
for (Empleado empleadoListOrphanCheckEmpleado : empleadoListOrphanCheck) {
if (illegalOrphanMessages == null) {
illegalOrphanMessages = new ArrayList<String>();
}
illegalOrphanMessages.add("This Estrato (" + estrato + ") cannot be destroyed since the Empleado " + empleadoListOrphanCheckEmpleado + " in its empleadoList field has a non-nullable idEstrato field.");
}
if (illegalOrphanMessages != null) {
throw new IllegalOrphanException(illegalOrphanMessages);
}
em.remove(estrato);
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public List<Estrato> findEstratoEntities() {
return findEstratoEntities(true, -1, -1);
}
public List<Estrato> findEstratoEntities(int maxResults, int firstResult) {
return findEstratoEntities(false, maxResults, firstResult);
}
private List<Estrato> findEstratoEntities(boolean all, int maxResults, int firstResult) {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(Estrato.class));
Query q = em.createQuery(cq);
if (!all) {
q.setMaxResults(maxResults);
q.setFirstResult(firstResult);
}
return q.getResultList();
} finally {
em.close();
}
}
public Estrato findEstrato(Integer id) {
EntityManager em = getEntityManager();
try {
return em.find(Estrato.class, id);
} finally {
em.close();
}
}
public int getEstratoCount() {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
Root<Estrato> rt = cq.from(Estrato.class);
cq.select(em.getCriteriaBuilder().count(rt));
Query q = em.createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
} finally {
em.close();
}
}
}
|
UTF-8
|
Java
| 10,021 |
java
|
EstratoJpaController.java
|
Java
|
[
{
"context": "ransaction.UserTransaction;\r\n\r\n/**\r\n *\r\n * @author Carmen\r\n */\r\npublic class EstratoJpaController implements ",
"end": 910,
"score": 0.9401852488517761,
"start": 904,
"tag": "NAME",
"value": "Carmen"
}
] | 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;
import Controller.exceptions.IllegalOrphanException;
import Controller.exceptions.NonexistentEntityException;
import Controller.exceptions.PreexistingEntityException;
import Controller.exceptions.RollbackFailureException;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import Entities.Empleado;
import Entities.Estrato;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.transaction.UserTransaction;
/**
*
* @author Carmen
*/
public class EstratoJpaController implements Serializable {
public EstratoJpaController(UserTransaction utx, EntityManagerFactory emf) {
this.utx = utx;
this.emf = emf;
}
private UserTransaction utx = null;
private EntityManagerFactory emf = null;
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
public void create(Estrato estrato) throws PreexistingEntityException, RollbackFailureException, Exception {
if (estrato.getEmpleadoList() == null) {
estrato.setEmpleadoList(new ArrayList<Empleado>());
}
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
List<Empleado> attachedEmpleadoList = new ArrayList<Empleado>();
for (Empleado empleadoListEmpleadoToAttach : estrato.getEmpleadoList()) {
empleadoListEmpleadoToAttach = em.getReference(empleadoListEmpleadoToAttach.getClass(), empleadoListEmpleadoToAttach.getIdEmpleado());
attachedEmpleadoList.add(empleadoListEmpleadoToAttach);
}
estrato.setEmpleadoList(attachedEmpleadoList);
em.persist(estrato);
for (Empleado empleadoListEmpleado : estrato.getEmpleadoList()) {
Estrato oldIdEstratoOfEmpleadoListEmpleado = empleadoListEmpleado.getIdEstrato();
empleadoListEmpleado.setIdEstrato(estrato);
empleadoListEmpleado = em.merge(empleadoListEmpleado);
if (oldIdEstratoOfEmpleadoListEmpleado != null) {
oldIdEstratoOfEmpleadoListEmpleado.getEmpleadoList().remove(empleadoListEmpleado);
oldIdEstratoOfEmpleadoListEmpleado = em.merge(oldIdEstratoOfEmpleadoListEmpleado);
}
}
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
if (findEstrato(estrato.getIdEstrato()) != null) {
throw new PreexistingEntityException("Estrato " + estrato + " already exists.", ex);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void edit(Estrato estrato) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
Estrato persistentEstrato = em.find(Estrato.class, estrato.getIdEstrato());
List<Empleado> empleadoListOld = persistentEstrato.getEmpleadoList();
List<Empleado> empleadoListNew = estrato.getEmpleadoList();
List<String> illegalOrphanMessages = null;
for (Empleado empleadoListOldEmpleado : empleadoListOld) {
if (!empleadoListNew.contains(empleadoListOldEmpleado)) {
if (illegalOrphanMessages == null) {
illegalOrphanMessages = new ArrayList<String>();
}
illegalOrphanMessages.add("You must retain Empleado " + empleadoListOldEmpleado + " since its idEstrato field is not nullable.");
}
}
if (illegalOrphanMessages != null) {
throw new IllegalOrphanException(illegalOrphanMessages);
}
List<Empleado> attachedEmpleadoListNew = new ArrayList<Empleado>();
for (Empleado empleadoListNewEmpleadoToAttach : empleadoListNew) {
empleadoListNewEmpleadoToAttach = em.getReference(empleadoListNewEmpleadoToAttach.getClass(), empleadoListNewEmpleadoToAttach.getIdEmpleado());
attachedEmpleadoListNew.add(empleadoListNewEmpleadoToAttach);
}
empleadoListNew = attachedEmpleadoListNew;
estrato.setEmpleadoList(empleadoListNew);
estrato = em.merge(estrato);
for (Empleado empleadoListNewEmpleado : empleadoListNew) {
if (!empleadoListOld.contains(empleadoListNewEmpleado)) {
Estrato oldIdEstratoOfEmpleadoListNewEmpleado = empleadoListNewEmpleado.getIdEstrato();
empleadoListNewEmpleado.setIdEstrato(estrato);
empleadoListNewEmpleado = em.merge(empleadoListNewEmpleado);
if (oldIdEstratoOfEmpleadoListNewEmpleado != null && !oldIdEstratoOfEmpleadoListNewEmpleado.equals(estrato)) {
oldIdEstratoOfEmpleadoListNewEmpleado.getEmpleadoList().remove(empleadoListNewEmpleado);
oldIdEstratoOfEmpleadoListNewEmpleado = em.merge(oldIdEstratoOfEmpleadoListNewEmpleado);
}
}
}
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
String msg = ex.getLocalizedMessage();
if (msg == null || msg.length() == 0) {
Integer id = estrato.getIdEstrato();
if (findEstrato(id) == null) {
throw new NonexistentEntityException("The estrato with id " + id + " no longer exists.");
}
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
Estrato estrato;
try {
estrato = em.getReference(Estrato.class, id);
estrato.getIdEstrato();
} catch (EntityNotFoundException enfe) {
throw new NonexistentEntityException("The estrato with id " + id + " no longer exists.", enfe);
}
List<String> illegalOrphanMessages = null;
List<Empleado> empleadoListOrphanCheck = estrato.getEmpleadoList();
for (Empleado empleadoListOrphanCheckEmpleado : empleadoListOrphanCheck) {
if (illegalOrphanMessages == null) {
illegalOrphanMessages = new ArrayList<String>();
}
illegalOrphanMessages.add("This Estrato (" + estrato + ") cannot be destroyed since the Empleado " + empleadoListOrphanCheckEmpleado + " in its empleadoList field has a non-nullable idEstrato field.");
}
if (illegalOrphanMessages != null) {
throw new IllegalOrphanException(illegalOrphanMessages);
}
em.remove(estrato);
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public List<Estrato> findEstratoEntities() {
return findEstratoEntities(true, -1, -1);
}
public List<Estrato> findEstratoEntities(int maxResults, int firstResult) {
return findEstratoEntities(false, maxResults, firstResult);
}
private List<Estrato> findEstratoEntities(boolean all, int maxResults, int firstResult) {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(Estrato.class));
Query q = em.createQuery(cq);
if (!all) {
q.setMaxResults(maxResults);
q.setFirstResult(firstResult);
}
return q.getResultList();
} finally {
em.close();
}
}
public Estrato findEstrato(Integer id) {
EntityManager em = getEntityManager();
try {
return em.find(Estrato.class, id);
} finally {
em.close();
}
}
public int getEstratoCount() {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
Root<Estrato> rt = cq.from(Estrato.class);
cq.select(em.getCriteriaBuilder().count(rt));
Query q = em.createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
} finally {
em.close();
}
}
}
| 10,021 | 0.596447 | 0.596148 | 230 | 41.569565 | 35.22699 | 217 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.608696 | false | false |
3
|
4a726e678cd30714c80fecfd263b3dec0e623cd3
| 26,396,869,045,239 |
6a96d6c6f8c18490b2dceab569e6355cd0ca7c31
|
/src/main/java/org/sunbit/addressbook/MyKeyValueStorage.java
|
73b04a67132a2c50254fb89fbbe328aea29b5c85
|
[] |
no_license
|
yoaviStr/sunbit
|
https://github.com/yoaviStr/sunbit
|
00217b8bb984b4a9ebe9c66bc88c35fdee021bbe
|
1bc9fb512642c87703d27e33799175a349a01d2c
|
refs/heads/main
| 2023-07-27T01:07:52.499000 | 2021-08-27T17:53:48 | 2021-08-27T17:53:48 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.sunbit.addressbook;
import org.springframework.stereotype.Component;
import org.sunbit.addressbook.exception.ResourceNotFoundException;
import org.sunbit.addressbook.model.BaseEntity;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicLong;
@Component
public class MyKeyValueStorage<V extends BaseEntity> {
private Map<Long, V> m = new HashMap<>();
private AtomicLong generator = new AtomicLong(1L);
public V getById(Long id) {
return Optional.ofNullable(m.get(id))
.orElseThrow(() -> new ResourceNotFoundException("contact id " + id));
}
public V create(V c) {
Long andIncrement = generator.getAndIncrement();
c.setId(andIncrement);
m.put(andIncrement, c);
return c;
}
public V removeById(Long id) {
return m.remove(id);
}
public V update(Long id, V c) {
return m.put(id, c);
}
}
|
UTF-8
|
Java
| 979 |
java
|
MyKeyValueStorage.java
|
Java
|
[] | null |
[] |
package org.sunbit.addressbook;
import org.springframework.stereotype.Component;
import org.sunbit.addressbook.exception.ResourceNotFoundException;
import org.sunbit.addressbook.model.BaseEntity;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicLong;
@Component
public class MyKeyValueStorage<V extends BaseEntity> {
private Map<Long, V> m = new HashMap<>();
private AtomicLong generator = new AtomicLong(1L);
public V getById(Long id) {
return Optional.ofNullable(m.get(id))
.orElseThrow(() -> new ResourceNotFoundException("contact id " + id));
}
public V create(V c) {
Long andIncrement = generator.getAndIncrement();
c.setId(andIncrement);
m.put(andIncrement, c);
return c;
}
public V removeById(Long id) {
return m.remove(id);
}
public V update(Long id, V c) {
return m.put(id, c);
}
}
| 979 | 0.6762 | 0.675179 | 38 | 24.763159 | 22.205303 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.552632 | false | false |
3
|
1adc8d1ccfb252080c9047918ed2cc41b91becb9
| 28,235,115,047,283 |
323bbe1a34647f65bb6f0fb24b1bf00940a1f316
|
/twitter2elastic/src/main/java/com/github/julian_mateu/kafka/twitter2elastic/consumer/elastic/ElasticSearchWriter.java
|
916852d813e06c08e170ed9b175cc8a373b131b0
|
[] |
no_license
|
julian-mateu/kafka-beginners-course
|
https://github.com/julian-mateu/kafka-beginners-course
|
d02a201d29af14f217f50665ac3609c3c5e16e80
|
e2b58159486ff42e5cf6ce9fe442b2ab7a688740
|
refs/heads/main
| 2023-07-18T15:23:08.909000 | 2021-08-31T12:25:52 | 2021-08-31T12:53:33 | 400,669,858 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.github.julian_mateu.kafka.twitter2elastic.consumer.elastic;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.common.xcontent.XContentType;
import java.io.IOException;
import java.util.List;
import java.util.Map;
/**
* Allows to submit a document to an ElasticSearch Index.
*/
@Slf4j
@RequiredArgsConstructor
public class ElasticSearchWriter implements AutoCloseable {
@NonNull
private final ElasticClient client;
@NonNull
private final String indexName;
@SneakyThrows(IOException.class)
public void submitDocumentBatch(@NonNull List<Map.Entry<String, String>> documentBatch) {
if (documentBatch.isEmpty()) {
return;
}
BulkRequest bulkRequest = new BulkRequest();
for (Map.Entry<String, String> document : documentBatch) {
IndexRequest indexRequest = new IndexRequest(indexName);
indexRequest.id(document.getKey());
indexRequest.source(document.getValue(), XContentType.JSON);
bulkRequest.add(indexRequest);
}
try {
BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
log.info(bulkResponse.toString());
if (bulkResponse.hasFailures()) {
log.warn("There were failures while submitting to elastic search. "
+ bulkResponse.buildFailureMessage());
}
} catch (ElasticsearchException exception) {
log.error("failed to submit to elastic search", exception);
}
}
@Override
public void close() throws Exception {
client.close();
}
}
|
UTF-8
|
Java
| 1,995 |
java
|
ElasticSearchWriter.java
|
Java
|
[
{
"context": "package com.github.julian_mateu.kafka.twitter2elastic.consumer.elastic;\n\nimport l",
"end": 31,
"score": 0.9996612668037415,
"start": 19,
"tag": "USERNAME",
"value": "julian_mateu"
}
] | null |
[] |
package com.github.julian_mateu.kafka.twitter2elastic.consumer.elastic;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.common.xcontent.XContentType;
import java.io.IOException;
import java.util.List;
import java.util.Map;
/**
* Allows to submit a document to an ElasticSearch Index.
*/
@Slf4j
@RequiredArgsConstructor
public class ElasticSearchWriter implements AutoCloseable {
@NonNull
private final ElasticClient client;
@NonNull
private final String indexName;
@SneakyThrows(IOException.class)
public void submitDocumentBatch(@NonNull List<Map.Entry<String, String>> documentBatch) {
if (documentBatch.isEmpty()) {
return;
}
BulkRequest bulkRequest = new BulkRequest();
for (Map.Entry<String, String> document : documentBatch) {
IndexRequest indexRequest = new IndexRequest(indexName);
indexRequest.id(document.getKey());
indexRequest.source(document.getValue(), XContentType.JSON);
bulkRequest.add(indexRequest);
}
try {
BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
log.info(bulkResponse.toString());
if (bulkResponse.hasFailures()) {
log.warn("There were failures while submitting to elastic search. "
+ bulkResponse.buildFailureMessage());
}
} catch (ElasticsearchException exception) {
log.error("failed to submit to elastic search", exception);
}
}
@Override
public void close() throws Exception {
client.close();
}
}
| 1,995 | 0.695739 | 0.693734 | 62 | 31.17742 | 25.941948 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.516129 | false | false |
3
|
3cdf9351e2706455081dd4ab4abe2531164e96e3
| 18,322,330,520,405 |
1ba6a8be7f7d9232004d5bf48276037459a11350
|
/src/main/java/com/mattdahepic/exchangeorb/ExchangeOrb.java
|
4e0dc55a1119b15ecb1cfe09ec3943c9cbbbd4f7
|
[] |
no_license
|
MattDahEpic/ExchangeOrb
|
https://github.com/MattDahEpic/ExchangeOrb
|
e9431970bd5f3270d11bcff3f6e737124ba9a611
|
3052e2b2f5555ce25257db60aff7bfa7877091a8
|
refs/heads/1.11.X
| 2020-05-21T12:38:18.127000 | 2017-01-13T15:39:33 | 2017-01-13T15:39:33 | 28,241,699 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.mattdahepic.exchangeorb;
import com.mattdahepic.exchangeorb.config.GeneralConfig;
import com.mattdahepic.exchangeorb.config.MobDropConfig;
import com.mattdahepic.exchangeorb.config.ResourceConfig;
import com.mattdahepic.exchangeorb.item.ItemEssence;
import com.mattdahepic.exchangeorb.item.ItemOrb;
import com.mattdahepic.mdecore.config.sync.ConfigSyncable;
import net.minecraft.item.Item;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@Mod(modid = ExchangeOrb.MODID, name = ExchangeOrb.NAME, version = ExchangeOrb.VERSION, dependencies = ExchangeOrb.DEPENDENCIES,updateJSON = ExchangeOrb.UPDATE_JSON)
public class ExchangeOrb {
public static final String MODID = "exchangeorb";
static final String VERSION = "@VERSION@";
static final String NAME = "Exchange Orb";
static final String DEPENDENCIES = "required-after:mdecore@[1.11-0.1,);";
static final String UPDATE_JSON = "https://raw.githubusercontent.com/MattDahEpic/Version/master/"+MODID+".json";
public static final Logger logger = LogManager.getLogger(MODID);
@SidedProxy(clientSide = "com.mattdahepic.exchangeorb.ClientProxy", serverSide = "com.mattdahepic.exchangeorb.CommonProxy")
public static CommonProxy proxy;
public static Item itemOrb = new ItemOrb();
public static Item itemEssence = new ItemEssence();
@Mod.EventHandler
public void preInit(FMLPreInitializationEvent e) {
MinecraftForge.EVENT_BUS.register(this);
new GeneralConfig().initalize(e);
new ResourceConfig().initalize(e);
new MobDropConfig().initalize(e);
proxy.registerItems();
proxy.registerRenders();
}
@Mod.EventHandler
public void init(FMLInitializationEvent e) {
proxy.registerRecipes();
}
private int configsSynced = 0;
@SubscribeEvent
public void onConfigSync (ConfigSyncable.ConfigSyncEvent e) {
if (e.configName.equals(MODID) || e.configName.equals(MODID+"-mobdrops") || e.configName.equals(MODID+"-resources")) configsSynced++;
if (configsSynced == 3) {
logger.info("Config values synced. Reloading recipes.");
proxy.registerRecipes();
configsSynced = 0;
}
}
}
|
UTF-8
|
Java
| 2,595 |
java
|
ExchangeOrb.java
|
Java
|
[
{
"context": " UPDATE_JSON = \"https://raw.githubusercontent.com/MattDahEpic/Version/master/\"+MODID+\".json\";\n\n public stati",
"end": 1334,
"score": 0.9897013902664185,
"start": 1323,
"tag": "USERNAME",
"value": "MattDahEpic"
}
] | null |
[] |
package com.mattdahepic.exchangeorb;
import com.mattdahepic.exchangeorb.config.GeneralConfig;
import com.mattdahepic.exchangeorb.config.MobDropConfig;
import com.mattdahepic.exchangeorb.config.ResourceConfig;
import com.mattdahepic.exchangeorb.item.ItemEssence;
import com.mattdahepic.exchangeorb.item.ItemOrb;
import com.mattdahepic.mdecore.config.sync.ConfigSyncable;
import net.minecraft.item.Item;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@Mod(modid = ExchangeOrb.MODID, name = ExchangeOrb.NAME, version = ExchangeOrb.VERSION, dependencies = ExchangeOrb.DEPENDENCIES,updateJSON = ExchangeOrb.UPDATE_JSON)
public class ExchangeOrb {
public static final String MODID = "exchangeorb";
static final String VERSION = "@VERSION@";
static final String NAME = "Exchange Orb";
static final String DEPENDENCIES = "required-after:mdecore@[1.11-0.1,);";
static final String UPDATE_JSON = "https://raw.githubusercontent.com/MattDahEpic/Version/master/"+MODID+".json";
public static final Logger logger = LogManager.getLogger(MODID);
@SidedProxy(clientSide = "com.mattdahepic.exchangeorb.ClientProxy", serverSide = "com.mattdahepic.exchangeorb.CommonProxy")
public static CommonProxy proxy;
public static Item itemOrb = new ItemOrb();
public static Item itemEssence = new ItemEssence();
@Mod.EventHandler
public void preInit(FMLPreInitializationEvent e) {
MinecraftForge.EVENT_BUS.register(this);
new GeneralConfig().initalize(e);
new ResourceConfig().initalize(e);
new MobDropConfig().initalize(e);
proxy.registerItems();
proxy.registerRenders();
}
@Mod.EventHandler
public void init(FMLInitializationEvent e) {
proxy.registerRecipes();
}
private int configsSynced = 0;
@SubscribeEvent
public void onConfigSync (ConfigSyncable.ConfigSyncEvent e) {
if (e.configName.equals(MODID) || e.configName.equals(MODID+"-mobdrops") || e.configName.equals(MODID+"-resources")) configsSynced++;
if (configsSynced == 3) {
logger.info("Config values synced. Reloading recipes.");
proxy.registerRecipes();
configsSynced = 0;
}
}
}
| 2,595 | 0.746435 | 0.742582 | 59 | 42.983051 | 33.427124 | 165 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.813559 | false | false |
3
|
605faa69c28edb18cf115aef8a881b16052feafc
| 29,051,158,834,369 |
49facbc93cb6d5ee5cac3dda10155aa93d667ef9
|
/src/main/java/com/hunter/db/PositionDAO.java
|
12814d697d9a6fe7ed2fbd27bf7be29ff9c049e6
|
[
"MIT"
] |
permissive
|
deividi86/hunter
|
https://github.com/deividi86/hunter
|
4b4ebbe12af3859b8e2aa75fc3462961208d74a0
|
8daa90b2d41135a3633df2037bb52a2475ab8115
|
refs/heads/master
| 2016-09-23T20:06:34.881000 | 2016-06-10T11:17:36 | 2016-06-10T11:17:36 | 60,430,045 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.hunter.db;
/**
* Created by User on 04/06/2016.
*/
public class PositionDAO {
}
|
UTF-8
|
Java
| 95 |
java
|
PositionDAO.java
|
Java
|
[] | null |
[] |
package com.hunter.db;
/**
* Created by User on 04/06/2016.
*/
public class PositionDAO {
}
| 95 | 0.663158 | 0.578947 | 7 | 12.571428 | 12.882515 | 33 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.142857 | false | false |
3
|
4cad46b36416a4bfb2fd2c5f11de68bc652a3a1e
| 14,456,859,929,675 |
76977b17f2dae38027cc1c052aaccc0c9b1985cc
|
/src/UnweightedGraph.java
|
48b7d71b80b09e924fca07f374193b8a95989121
|
[] |
no_license
|
yinzhicheng66/WordChain
|
https://github.com/yinzhicheng66/WordChain
|
fbc9511e4244118a539e304a0258d68b42df8083
|
ad6862d1e55485a9f0f15acfda3c0944272d9580
|
refs/heads/master
| 2021-09-18T15:16:50.019000 | 2018-07-16T08:37:37 | 2018-07-16T08:37:37 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.util.List;
public class UnweightedGraph<V> extends AbstractGraph<V> {
protected UnweightedGraph(int[][] edges,int numOfVertices) {
super(edges, numOfVertices);
}
public UnweightedGraph(int[][] edges,V[] vertices){
super(edges, vertices);
}
public UnweightedGraph(List<AbstractGraph.Edge> edges,int numOfVertices){
super(edges, numOfVertices);
}
public UnweightedGraph(List<AbstractGraph.Edge> edges,List<V> vertices) {
super(edges, vertices);
}
}
|
UTF-8
|
Java
| 529 |
java
|
UnweightedGraph.java
|
Java
|
[] | null |
[] |
import java.util.List;
public class UnweightedGraph<V> extends AbstractGraph<V> {
protected UnweightedGraph(int[][] edges,int numOfVertices) {
super(edges, numOfVertices);
}
public UnweightedGraph(int[][] edges,V[] vertices){
super(edges, vertices);
}
public UnweightedGraph(List<AbstractGraph.Edge> edges,int numOfVertices){
super(edges, numOfVertices);
}
public UnweightedGraph(List<AbstractGraph.Edge> edges,List<V> vertices) {
super(edges, vertices);
}
}
| 529 | 0.674858 | 0.674858 | 21 | 24.190475 | 26.862293 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.619048 | false | false |
3
|
e5da7fe883304657142c13a3ebb23883a56718b0
| 14,516,989,509,465 |
2c992e297a3f8fe3b3bc8a557465d37be0390cb4
|
/src/main/java/com/hzzd/protocol/protocal3761/internal/wrap/Wrapper.java
|
191b80507c0f9a7be551f4a16c047a01bc9c8ca7
|
[] |
no_license
|
ocean-wave/hzzdtcp
|
https://github.com/ocean-wave/hzzdtcp
|
c50ae42dd8264686b87d3d75684f70b68031f91d
|
379135003fbdf679ba3491d892584c17d987502c
|
refs/heads/master
| 2020-06-21T15:43:24.777000 | 2018-12-07T10:54:17 | 2018-12-07T10:54:17 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.hzzd.protocol.protocal3761.internal.wrap;
import com.hzzd.protocol.protocal3761.CodecConfig;
import com.hzzd.protocol.protocal3761.Packet;
import com.hzzd.protocol.protocal3761.internal.ProtocalTemplate;
import com.hzzd.protocol.protocal3761.internal.packetSegment.PacketSegmentContext;
/**
* Created by PETER on 2015/3/24.
*/
public abstract class Wrapper {
protected Wrapper next;
abstract void encode(Packet in,PacketSegmentContext packetSegmentContext,
ProtocalTemplate protocalTemplate,CodecConfig codecConfig) throws Exception;
public void setNext(Wrapper next) {
this.next = next;
}
}
|
UTF-8
|
Java
| 649 |
java
|
Wrapper.java
|
Java
|
[
{
"context": "etSegment.PacketSegmentContext;\n\n/**\n * Created by PETER on 2015/3/24.\n */\npublic abstract class Wrapper {",
"end": 324,
"score": 0.9991991519927979,
"start": 319,
"tag": "USERNAME",
"value": "PETER"
}
] | null |
[] |
package com.hzzd.protocol.protocal3761.internal.wrap;
import com.hzzd.protocol.protocal3761.CodecConfig;
import com.hzzd.protocol.protocal3761.Packet;
import com.hzzd.protocol.protocal3761.internal.ProtocalTemplate;
import com.hzzd.protocol.protocal3761.internal.packetSegment.PacketSegmentContext;
/**
* Created by PETER on 2015/3/24.
*/
public abstract class Wrapper {
protected Wrapper next;
abstract void encode(Packet in,PacketSegmentContext packetSegmentContext,
ProtocalTemplate protocalTemplate,CodecConfig codecConfig) throws Exception;
public void setNext(Wrapper next) {
this.next = next;
}
}
| 649 | 0.776579 | 0.734977 | 19 | 33.157894 | 29.581757 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.578947 | false | false |
3
|
02a38e6b47e8e667a61ec75c6729047f4767372f
| 10,496,900,117,655 |
034313fd999fa0aac06b5cd83e4829a3acbbfc98
|
/secondary.java
|
1968ac3b2aa4c3788262a7c140d76ad5ea3144e0
|
[] |
no_license
|
VinnyOhri/Wikipedia-Search-Engine
|
https://github.com/VinnyOhri/Wikipedia-Search-Engine
|
136844e70ffa728fa765a05d636bb4aea026455e
|
d314d4a91a6ca29def87e0d2ec9f78adeb7019ee
|
refs/heads/master
| 2021-09-15T08:11:18.545000 | 2018-05-29T03:13:28 | 2018-05-29T03:13:28 | 111,385,331 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.charset.Charset;
public class secondary {
public static void main(String[] args) {
// TODO Auto-generated method stub
FileInputStream instream = null;
PrintWriter outstream = null;
try {
outstream = new PrintWriter(new BufferedWriter(new FileWriter("secondtitle.txt")));
instream = new FileInputStream("/home/vinny/Desktop/IRE/title_id");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader in = new BufferedReader(new InputStreamReader(instream,Charset.forName("iso-8859-1")));
Integer offset=0;
outstream.write(offset+"\n");
String line;
try {
while((line=in.readLine())!=null)
{
offset=offset+1+line.codePointCount(0,line.length());
outstream.write(offset+"\n");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
outstream.close();
try {
instream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
UTF-8
|
Java
| 1,380 |
java
|
secondary.java
|
Java
|
[
{
"context": "xt\")));\n\n\t\t\tinstream = new FileInputStream(\"/home/vinny/Desktop/IRE/title_id\");\n\t\t} catch (FileNotFoundEx",
"end": 597,
"score": 0.9606354236602783,
"start": 592,
"tag": "USERNAME",
"value": "vinny"
}
] | null |
[] |
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.charset.Charset;
public class secondary {
public static void main(String[] args) {
// TODO Auto-generated method stub
FileInputStream instream = null;
PrintWriter outstream = null;
try {
outstream = new PrintWriter(new BufferedWriter(new FileWriter("secondtitle.txt")));
instream = new FileInputStream("/home/vinny/Desktop/IRE/title_id");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader in = new BufferedReader(new InputStreamReader(instream,Charset.forName("iso-8859-1")));
Integer offset=0;
outstream.write(offset+"\n");
String line;
try {
while((line=in.readLine())!=null)
{
offset=offset+1+line.codePointCount(0,line.length());
outstream.write(offset+"\n");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
outstream.close();
try {
instream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| 1,380 | 0.712319 | 0.706522 | 52 | 25.538462 | 20.82663 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.211539 | false | false |
3
|
759949d7aea4e809b8ac76ba482924e0b3485845
| 7,859,790,173,719 |
de8627f903e111876d5920e999378fc6b132b929
|
/src/com/sgb/servlet/appliance/ListThisMonthApplianceServlet.java
|
9e503859a8aa0f1d65dcc776e4d13f16beab654a
|
[] |
no_license
|
YXK666/early
|
https://github.com/YXK666/early
|
242c5cd2f6f50018594321c81c2c9af0ce5692d3
|
0edf59dc10085ec96a026deaaa94a079ebccd0ec
|
refs/heads/master
| 2020-04-24T15:33:18.930000 | 2019-02-22T13:44:39 | 2019-02-22T13:44:39 | 172,072,454 | 4 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.sgb.servlet.appliance;
import com.sgb.dao.ApplianceDao;
import com.sgb.utils.FormatDate;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
/**
* TO :查看某年某月的检查计划
* @author YINXIAOKAI
*
*/
@WebServlet("/listThisMonthApplianceServlet.do")
public class ListThisMonthApplianceServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置响应字符编码,类型,创建json对象
resp.setCharacterEncoding("UTF-8");
resp.setContentType("application/json; charset=UTF-8");
PrintWriter out = resp.getWriter();
JSONObject json = new JSONObject();
// 获取参数 pageNum, pageSize,totalRows
/**
* easyUI传递过来的参数page,size 请求传输过去的数据total ,rows
*/
int pageNum = 1;//默认第一页
if (req.getParameter("page") != null
&& !req.getParameter("page").isEmpty()) {
pageNum = Integer.parseInt(req.getParameter("page"));
}
int pageSize = 10;//默认一页十行
if (req.getParameter("rows") != null
&& !req.getParameter("rows").isEmpty()) {
pageSize = Integer.parseInt(req.getParameter("rows"));
}
//获取查询条件
String MeteringNumber=req.getParameter("MeteringNumber");
String QCNumber=req.getParameter("QCNumber");
String ApplianceName=req.getParameter("ApplianceName");
String date=req.getParameter("ExpireDate");
System.out.println("日期参数"+date);
int year = 0;
int month = 0;
if(date!=null&&!date.equals("")) {
int [] array = FormatDate.getYearMonth(date);
year = array[0];
month = array[1];
System.out.println("前端传来的日期"+year+" " +month);
}
//传递参数
List<Map<String,String>> result = ApplianceDao.getThisMonthExpire(pageNum, pageSize, year, month,MeteringNumber,QCNumber,ApplianceName);
JSONArray jsonArray = new JSONArray();
for(Map<String, String> map : result) {
jsonArray.add(map);
}
int totalRows = ApplianceDao.getThisMonthSearchRows( year, month,MeteringNumber,QCNumber,ApplianceName);
json.put("total", totalRows);
json.put("rows", jsonArray);
out.print(json);
out.flush();
out.close();
}
}
|
UTF-8
|
Java
| 2,809 |
java
|
ListThisMonthApplianceServlet.java
|
Java
|
[
{
"context": "a.util.Map;\r\n\r\n/**\r\n * TO :查看某年某月的检查计划\r\n * @author YINXIAOKAI\r\n *\r\n */\r\n@WebServlet(\"/listThisMonthApplianceSer",
"end": 544,
"score": 0.830923318862915,
"start": 534,
"tag": "NAME",
"value": "YINXIAOKAI"
}
] | null |
[] |
package com.sgb.servlet.appliance;
import com.sgb.dao.ApplianceDao;
import com.sgb.utils.FormatDate;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
/**
* TO :查看某年某月的检查计划
* @author YINXIAOKAI
*
*/
@WebServlet("/listThisMonthApplianceServlet.do")
public class ListThisMonthApplianceServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置响应字符编码,类型,创建json对象
resp.setCharacterEncoding("UTF-8");
resp.setContentType("application/json; charset=UTF-8");
PrintWriter out = resp.getWriter();
JSONObject json = new JSONObject();
// 获取参数 pageNum, pageSize,totalRows
/**
* easyUI传递过来的参数page,size 请求传输过去的数据total ,rows
*/
int pageNum = 1;//默认第一页
if (req.getParameter("page") != null
&& !req.getParameter("page").isEmpty()) {
pageNum = Integer.parseInt(req.getParameter("page"));
}
int pageSize = 10;//默认一页十行
if (req.getParameter("rows") != null
&& !req.getParameter("rows").isEmpty()) {
pageSize = Integer.parseInt(req.getParameter("rows"));
}
//获取查询条件
String MeteringNumber=req.getParameter("MeteringNumber");
String QCNumber=req.getParameter("QCNumber");
String ApplianceName=req.getParameter("ApplianceName");
String date=req.getParameter("ExpireDate");
System.out.println("日期参数"+date);
int year = 0;
int month = 0;
if(date!=null&&!date.equals("")) {
int [] array = FormatDate.getYearMonth(date);
year = array[0];
month = array[1];
System.out.println("前端传来的日期"+year+" " +month);
}
//传递参数
List<Map<String,String>> result = ApplianceDao.getThisMonthExpire(pageNum, pageSize, year, month,MeteringNumber,QCNumber,ApplianceName);
JSONArray jsonArray = new JSONArray();
for(Map<String, String> map : result) {
jsonArray.add(map);
}
int totalRows = ApplianceDao.getThisMonthSearchRows( year, month,MeteringNumber,QCNumber,ApplianceName);
json.put("total", totalRows);
json.put("rows", jsonArray);
out.print(json);
out.flush();
out.close();
}
}
| 2,809 | 0.713638 | 0.70986 | 80 | 31.0875 | 26.983881 | 138 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.2125 | false | false |
3
|
c450e8354054fbea81852852c680b54331bc676b
| 9,586,367,069,035 |
30de844cfe897d97a96a0e780335a44a1707b91f
|
/src/com/algorithmers/SelectionSort.java
|
7302b9161e928b4d03338d2c6ca52b734cb55da4
|
[] |
no_license
|
DevFatani/Algorithmers-Sorting
|
https://github.com/DevFatani/Algorithmers-Sorting
|
13e4571b94c58d656b6e8532e911271eb091e023
|
91371241323d18183bb9188c9c6c1da94f9f69f1
|
refs/heads/master
| 2021-01-09T20:12:42.646000 | 2016-07-17T12:36:57 | 2016-07-17T12:36:57 | 63,529,493 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.algorithmers;
public class SelectionSort {
/*
*
* src = http://www.java2novice.com/java-sorting-algorithms/selection-sort/
*
*/
public static void run(int[] arrNum) {
int n = arrNum.length;
for (int i = 0; i < n - 1; i++) {
int index = i;
for (int j = i + 1; j < n; j++) {
if (arrNum[j] < arrNum[index]) {
index = j;
}
}
int smallerNumber = arrNum[index];
arrNum[index] = arrNum[i];
arrNum[i] = smallerNumber;
}
System.out.print("Selection Sort [");
for (int num : arrNum) {
System.out.print(num + " ");
}
System.out.println("]");
}
}
|
UTF-8
|
Java
| 786 |
java
|
SelectionSort.java
|
Java
|
[] | null |
[] |
package com.algorithmers;
public class SelectionSort {
/*
*
* src = http://www.java2novice.com/java-sorting-algorithms/selection-sort/
*
*/
public static void run(int[] arrNum) {
int n = arrNum.length;
for (int i = 0; i < n - 1; i++) {
int index = i;
for (int j = i + 1; j < n; j++) {
if (arrNum[j] < arrNum[index]) {
index = j;
}
}
int smallerNumber = arrNum[index];
arrNum[index] = arrNum[i];
arrNum[i] = smallerNumber;
}
System.out.print("Selection Sort [");
for (int num : arrNum) {
System.out.print(num + " ");
}
System.out.println("]");
}
}
| 786 | 0.441476 | 0.436387 | 53 | 13.830189 | 18.78351 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.264151 | false | false |
3
|
d333d565e6bcb97ace0e6468dce886199f04f05b
| 21,363,167,339,847 |
819d0508e66c6ca5ab4b70880e2353896088e7d7
|
/src/chaptervi/ChapterVIApproachITest.java
|
cce8dd02027523adba65487059554a61a12109ba
|
[] |
no_license
|
ccalebjewett/CTCI
|
https://github.com/ccalebjewett/CTCI
|
8f98366e0fc403c5fc792eb0264d2ea97300fd2c
|
93b8e378e2176911791583ec45dc44cb0682d1f1
|
refs/heads/master
| 2021-01-10T13:26:11.174000 | 2016-02-24T02:50:59 | 2016-02-24T02:50:59 | 47,859,542 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* @author Clifton Caleb Jewett
*/
package chaptervi;
import static org.junit.Assert.*;
public class ChapterVIApproachITest {
@org.junit.Test
public void testClockHandsAngle() throws Exception {
assertEquals(157.5, ChapterVIApproachI.clockHandsAngle(3, 45), 0.00001);
assertEquals(61.0, ChapterVIApproachI.clockHandsAngle(2, 22), 0.00001);
assertEquals(ChapterVIApproachI.clockHandsAngle(11, 57), ChapterVIApproachI.clockHandsAngle(23, 57), 0.00001);
assertEquals(16.5, ChapterVIApproachI.clockHandsAngle(11, 57), 0.00001);
}
}
|
UTF-8
|
Java
| 580 |
java
|
ChapterVIApproachITest.java
|
Java
|
[
{
"context": "/**\n * @author Clifton Caleb Jewett\n */\n\npackage chaptervi;\n\nimport static org.junit.",
"end": 35,
"score": 0.9998692274093628,
"start": 15,
"tag": "NAME",
"value": "Clifton Caleb Jewett"
}
] | null |
[] |
/**
* @author <NAME>
*/
package chaptervi;
import static org.junit.Assert.*;
public class ChapterVIApproachITest {
@org.junit.Test
public void testClockHandsAngle() throws Exception {
assertEquals(157.5, ChapterVIApproachI.clockHandsAngle(3, 45), 0.00001);
assertEquals(61.0, ChapterVIApproachI.clockHandsAngle(2, 22), 0.00001);
assertEquals(ChapterVIApproachI.clockHandsAngle(11, 57), ChapterVIApproachI.clockHandsAngle(23, 57), 0.00001);
assertEquals(16.5, ChapterVIApproachI.clockHandsAngle(11, 57), 0.00001);
}
}
| 566 | 0.724138 | 0.634483 | 18 | 31.277779 | 35.464859 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.055556 | false | false |
3
|
e350ab7f0be2873d82370e401aa7f90f7f91ce85
| 2,482,491,143,446 |
d16724e97358f301e99af0687f5db82d9ac4ff7e
|
/rawdata/java/snippets/497.java
|
c42b7307ba7f4818f8feedf72e93614202021216
|
[] |
no_license
|
kaushik-rohit/code2seq
|
https://github.com/kaushik-rohit/code2seq
|
39b562f79e9555083c18c73c05ffc4f379d1f3b8
|
c942b95d7d5997e5b2d45ed8c3161ca9296ddde3
|
refs/heads/master
| 2022-11-29T11:46:43.105000 | 2020-01-04T02:04:04 | 2020-01-04T02:04:04 | 225,870,854 | 0 | 0 | null | false | 2022-11-16T09:21:10 | 2019-12-04T13:12:59 | 2020-01-04T02:04:42 | 2022-11-16T09:21:07 | 1,033 | 0 | 0 | 2 |
C#
| false | false |
private static int getTimeout(final Ticket ticket) {
val ttl = ticket.getExpirationPolicy().getTimeToLive().intValue();
if (ttl == 0) {
return 1;
}
return ttl;
}
|
UTF-8
|
Java
| 209 |
java
|
497.java
|
Java
|
[] | null |
[] |
private static int getTimeout(final Ticket ticket) {
val ttl = ticket.getExpirationPolicy().getTimeToLive().intValue();
if (ttl == 0) {
return 1;
}
return ttl;
}
| 209 | 0.559809 | 0.550239 | 7 | 29 | 23.083698 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false |
3
|
f6dd8b238e39fd7e6580ef842e99fec3c8e01333
| 8,143,257,994,509 |
8ef7f71f7939ebeae6a86304e0f1cc9a5184c3f5
|
/src/main/java/net/floodlightcontroller/pronghornmodule/IPronghornService.java
|
ac43b827e8e171cea2833c8ad37ea88ee23959be
|
[
"Apache-2.0"
] |
permissive
|
bmistree/floodlight
|
https://github.com/bmistree/floodlight
|
da12eb01beec6424a067714477dc16fbdaca7406
|
4794a7fe5de37cd59fdb9437287461ced1a51bad
|
refs/heads/master
| 2021-01-22T17:22:54.400000 | 2014-10-28T23:25:45 | 2014-10-28T23:25:45 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package net.floodlightcontroller.pronghornmodule;
import java.io.IOException;
import java.util.concurrent.Future;
import java.util.List;
import org.openflow.protocol.statistics.OFStatistics;
import org.openflow.protocol.OFStatisticsRequest;
import org.openflow.protocol.OFFlowMod;
import net.floodlightcontroller.core.IOFSwitchListener;
import net.floodlightcontroller.core.module.IFloodlightService;
import net.floodlightcontroller.linkdiscovery.ILinkDiscoveryListener;
public interface IPronghornService extends IFloodlightService {
public String sendBarrier(String switchId);
/**
Returns unique id associated with
*/
public void issue_flow_mod(OFFlowMod flow_mod, String switch_id)
throws IOException, IllegalArgumentException;
public void barrier (
String switch_id,IPronghornBarrierCallback cb) throws IOException;
public void register_switch_listener(IOFSwitchListener switch_listener);
public void unregister_switch_listener(IOFSwitchListener switch_listener);
public void register_link_discovery_listener(ILinkDiscoveryListener listener);
/**
@returns {List<OFStatistics> or null} --- null if switch does
not exist.
*/
public Future<List<OFStatistics>> get_aggregate_stats(String switch_id)
throws IOException;
/**
@returns {List<OFStatistics> or null} --- null if switch does
not exist.
*/
public Future<List<OFStatistics>> get_port_stats(String switch_id)
throws IOException;
// note: link discovery service provides no way to actually unregister.
//public void unregister_link_discovery_listener(ILinkDiscoveryListener listener);
public void shutdown_all_now();
}
|
UTF-8
|
Java
| 1,737 |
java
|
IPronghornService.java
|
Java
|
[] | null |
[] |
package net.floodlightcontroller.pronghornmodule;
import java.io.IOException;
import java.util.concurrent.Future;
import java.util.List;
import org.openflow.protocol.statistics.OFStatistics;
import org.openflow.protocol.OFStatisticsRequest;
import org.openflow.protocol.OFFlowMod;
import net.floodlightcontroller.core.IOFSwitchListener;
import net.floodlightcontroller.core.module.IFloodlightService;
import net.floodlightcontroller.linkdiscovery.ILinkDiscoveryListener;
public interface IPronghornService extends IFloodlightService {
public String sendBarrier(String switchId);
/**
Returns unique id associated with
*/
public void issue_flow_mod(OFFlowMod flow_mod, String switch_id)
throws IOException, IllegalArgumentException;
public void barrier (
String switch_id,IPronghornBarrierCallback cb) throws IOException;
public void register_switch_listener(IOFSwitchListener switch_listener);
public void unregister_switch_listener(IOFSwitchListener switch_listener);
public void register_link_discovery_listener(ILinkDiscoveryListener listener);
/**
@returns {List<OFStatistics> or null} --- null if switch does
not exist.
*/
public Future<List<OFStatistics>> get_aggregate_stats(String switch_id)
throws IOException;
/**
@returns {List<OFStatistics> or null} --- null if switch does
not exist.
*/
public Future<List<OFStatistics>> get_port_stats(String switch_id)
throws IOException;
// note: link discovery service provides no way to actually unregister.
//public void unregister_link_discovery_listener(ILinkDiscoveryListener listener);
public void shutdown_all_now();
}
| 1,737 | 0.751295 | 0.751295 | 53 | 31.773584 | 29.517275 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.433962 | false | false |
3
|
1995cd675730eb7e040d67ab8a198d81ef8460f2
| 28,767,691,010,636 |
35cd06a64f1b5c50c0e400217ac75ecf13936fea
|
/src/Util/Text.java
|
aae668dd170ce69d70a44d97e01170c8e857a834
|
[] |
no_license
|
lpslpsl/diancan-server
|
https://github.com/lpslpsl/diancan-server
|
724ee1e378c19fc50df29fb2db6cd7ac92aec548
|
4b662a28b227193848e05a0356b01866afaa5cc8
|
refs/heads/master
| 2021-01-01T05:13:45.178000 | 2016-05-20T08:29:01 | 2016-05-20T08:29:01 | 59,277,911 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package Util;
import com.tencent.xinge.XingeApp;
import org.json.JSONObject;
import static javax.accessibility.AccessibleRole.ALERT;
/**
* Created by Administrator on 2016/3/23 0023.
*/
public class Text {
public static void main(String args[]) {
int n=0;
for (int i=0;i<100;i++){
n=n++;
System.out.print(n);
}
System.out.print(n);
}
// }
}
|
UTF-8
|
Java
| 417 |
java
|
Text.java
|
Java
|
[] | null |
[] |
package Util;
import com.tencent.xinge.XingeApp;
import org.json.JSONObject;
import static javax.accessibility.AccessibleRole.ALERT;
/**
* Created by Administrator on 2016/3/23 0023.
*/
public class Text {
public static void main(String args[]) {
int n=0;
for (int i=0;i<100;i++){
n=n++;
System.out.print(n);
}
System.out.print(n);
}
// }
}
| 417 | 0.580336 | 0.541966 | 23 | 17.130434 | 16.822098 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.434783 | false | false |
3
|
b7d928ec667469d957fb7ac3a4bdff4f3c5464dd
| 30,605,936,963,420 |
bbafdf08db35dc943bfb2f6a5b48b32f9571839b
|
/lagou-cloud-gateway-9002/src/main/java/com/lagou/edu/filter/BlackListFilter.java
|
393c2a335138d67868fb0a2b1fc1f781d24d1472
|
[] |
no_license
|
xiaolianggu/lagou-parent1
|
https://github.com/xiaolianggu/lagou-parent1
|
fbfe3a75f553eb8b402778325ae30d1d4356c721
|
af85328937abd4280619f3a9d0e85e6c0375ceb0
|
refs/heads/master
| 2022-07-18T04:05:48.246000 | 2020-05-17T11:10:59 | 2020-05-17T11:10:59 | 264,645,819 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*package com.lagou.edu.filter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
*//**
* 定义全局过滤器,会对所有路由生效
*//*
@Slf4j
@Component // 让容器扫描到,等同于注册了
public class BlackListFilter implements GlobalFilter, Ordered {
private static final String MAX_AGE = "18000L";
private static final Integer OPEN_TIME = 5*1000;
private static final Integer COUNT = 10;
// 模拟黑名单(实际可以去数据库或者redis中查询)
private static List<String> blackList = new ArrayList<>();
private Map<String,List<Long>> clientIpRecord = new HashMap<String,List<Long>>();
static {
blackList.add("0:0:0:0:0:0:0:1"); // 模拟本机地址
}
*//**
* 过滤器核心方法
* @param exchange 封装了request和response对象的上下文
* @param chain 网关过滤器链(包含全局过滤器和单路由过滤器)
* @return
*//*
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
// 思路:获取客户端ip,判断是否在黑名单中,在的话就拒绝访问,不在的话就放行
// 从上下文中取出request和response对象
ServerHttpRequest request = exchange.getRequest();
ServerHttpResponse response = exchange.getResponse();
HttpHeaders requestHeaders = request.getHeaders();
HttpHeaders headers = response.getHeaders();
if(StringUtils.isNotBlank(requestHeaders.getOrigin())){
headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, requestHeaders.getOrigin());
}
headers.addAll(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, requestHeaders
.getAccessControlRequestHeaders());
headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
headers.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, "*");
headers.add(HttpHeaders.ACCESS_CONTROL_MAX_AGE, MAX_AGE);
// 从request对象中获取客户端ip
String clientIp = request.getRemoteAddress().getHostString();
URI uri = request.getURI();
String path = uri.getPath();
if(path.contains("register")){
List<Long> times = clientIpRecord.get(clientIp);
if(times != null){
Long currentTime = System.currentTimeMillis();
times.add(currentTime);
int count = 0;
for(int i = times.size()-1;i>=0;i--){
if(currentTime-OPEN_TIME>=times.get(i)){
count++;
}else{
break;
}
}
if(count>=COUNT){
response.setStatusCode(HttpStatus.SEE_OTHER); // 状态码
String data = "Request be denied!";
DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
return response.writeWith(Mono.just(wrap));
}
}else{
List<Long> timeList = new ArrayList<Long>();
timeList.add(System.currentTimeMillis());
clientIpRecord.put(clientIp,timeList);
}
}
// 拿着clientIp去黑名单中查询,存在的话就决绝访问
if(blackList.contains(clientIp)) {
// 决绝访问,返回
response.setStatusCode(HttpStatus.UNAUTHORIZED); // 状态码
//log.debug("=====>IP:" + clientIp + " 在黑名单中,将被拒绝访问!");
String data = "Request be denied!";
DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
//return response.writeWith(Mono.just(wrap));
}
// 合法请求,放行,执行后续的过滤器
return chain.filter(exchange);
}
*//**
* 返回值表示当前过滤器的顺序(优先级),数值越小,优先级越高
* @return
*//*
@Override
public int getOrder() {
return 0;
}
}
*/
|
UTF-8
|
Java
| 4,792 |
java
|
BlackListFilter.java
|
Java
|
[
{
"context": "ist<Long>>();\n static {\n blackList.add(\"0:0:0:0:0:0:0:1\"); // 模拟本机地址\n }\n\n *//**\n * 过滤器核心方法\n ",
"end": 1339,
"score": 0.9992620944976807,
"start": 1324,
"tag": "IP_ADDRESS",
"value": "0:0:0:0:0:0:0:1"
}
] | null |
[] |
/*package com.lagou.edu.filter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
*//**
* 定义全局过滤器,会对所有路由生效
*//*
@Slf4j
@Component // 让容器扫描到,等同于注册了
public class BlackListFilter implements GlobalFilter, Ordered {
private static final String MAX_AGE = "18000L";
private static final Integer OPEN_TIME = 5*1000;
private static final Integer COUNT = 10;
// 模拟黑名单(实际可以去数据库或者redis中查询)
private static List<String> blackList = new ArrayList<>();
private Map<String,List<Long>> clientIpRecord = new HashMap<String,List<Long>>();
static {
blackList.add("0:0:0:0:0:0:0:1"); // 模拟本机地址
}
*//**
* 过滤器核心方法
* @param exchange 封装了request和response对象的上下文
* @param chain 网关过滤器链(包含全局过滤器和单路由过滤器)
* @return
*//*
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
// 思路:获取客户端ip,判断是否在黑名单中,在的话就拒绝访问,不在的话就放行
// 从上下文中取出request和response对象
ServerHttpRequest request = exchange.getRequest();
ServerHttpResponse response = exchange.getResponse();
HttpHeaders requestHeaders = request.getHeaders();
HttpHeaders headers = response.getHeaders();
if(StringUtils.isNotBlank(requestHeaders.getOrigin())){
headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, requestHeaders.getOrigin());
}
headers.addAll(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, requestHeaders
.getAccessControlRequestHeaders());
headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
headers.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, "*");
headers.add(HttpHeaders.ACCESS_CONTROL_MAX_AGE, MAX_AGE);
// 从request对象中获取客户端ip
String clientIp = request.getRemoteAddress().getHostString();
URI uri = request.getURI();
String path = uri.getPath();
if(path.contains("register")){
List<Long> times = clientIpRecord.get(clientIp);
if(times != null){
Long currentTime = System.currentTimeMillis();
times.add(currentTime);
int count = 0;
for(int i = times.size()-1;i>=0;i--){
if(currentTime-OPEN_TIME>=times.get(i)){
count++;
}else{
break;
}
}
if(count>=COUNT){
response.setStatusCode(HttpStatus.SEE_OTHER); // 状态码
String data = "Request be denied!";
DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
return response.writeWith(Mono.just(wrap));
}
}else{
List<Long> timeList = new ArrayList<Long>();
timeList.add(System.currentTimeMillis());
clientIpRecord.put(clientIp,timeList);
}
}
// 拿着clientIp去黑名单中查询,存在的话就决绝访问
if(blackList.contains(clientIp)) {
// 决绝访问,返回
response.setStatusCode(HttpStatus.UNAUTHORIZED); // 状态码
//log.debug("=====>IP:" + clientIp + " 在黑名单中,将被拒绝访问!");
String data = "Request be denied!";
DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
//return response.writeWith(Mono.just(wrap));
}
// 合法请求,放行,执行后续的过滤器
return chain.filter(exchange);
}
*//**
* 返回值表示当前过滤器的顺序(优先级),数值越小,优先级越高
* @return
*//*
@Override
public int getOrder() {
return 0;
}
}
*/
| 4,792 | 0.629167 | 0.622917 | 118 | 35.618645 | 24.539459 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.584746 | false | false |
3
|
f678b8fbf4ae9df170c69e59c5061f92284dc478
| 5,274,219,849,225 |
2c52577ef7660c8283bf6286c52c83390ebd2184
|
/ProyectoClaudioHernandez/app/src/main/java/com/example/myapplication/Cola.java
|
a791f177fe81c01f81799c0ff14adc241dbc3a9c
|
[] |
no_license
|
Claudio-Hernandez/ProyectoClaudioHernandezED1Banco
|
https://github.com/Claudio-Hernandez/ProyectoClaudioHernandezED1Banco
|
0ad1290de7ae24912b475a39c1176ed2baf60399
|
a013336f8b417235b6d3356718898cec23038b36
|
refs/heads/main
| 2023-08-24T19:37:55.347000 | 2021-09-23T22:44:01 | 2021-09-23T22:44:01 | 409,754,040 | 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.example.myapplication;
/**
*
* @author Usuario
*/
public class Cola extends Lista{
public Persona p = new Persona();
public Object frente(){
return recupera(this.primero(this), this);
}
public void pone(Object x, Cola cola){
cola.inserta(x, this.finL(), cola);
}
public void quita(Cola cola){
cola.suprime(primero(cola), cola);
}
public boolean vacio(Cola cola){
if (cola.lista.isEmpty()) {
return true;
}else{
return false;
}
}
}
|
UTF-8
|
Java
| 739 |
java
|
Cola.java
|
Java
|
[
{
"context": "kage com.example.myapplication;\n\n/**\n *\n * @author Usuario\n */\npublic class Cola extends Lista{\n public P",
"end": 246,
"score": 0.8724104762077332,
"start": 239,
"tag": "NAME",
"value": "Usuario"
}
] | 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.example.myapplication;
/**
*
* @author Usuario
*/
public class Cola extends Lista{
public Persona p = new Persona();
public Object frente(){
return recupera(this.primero(this), this);
}
public void pone(Object x, Cola cola){
cola.inserta(x, this.finL(), cola);
}
public void quita(Cola cola){
cola.suprime(primero(cola), cola);
}
public boolean vacio(Cola cola){
if (cola.lista.isEmpty()) {
return true;
}else{
return false;
}
}
}
| 739 | 0.61299 | 0.61299 | 33 | 21.39394 | 19.838652 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false |
3
|
5c4ff0c6d6fa62d40446ffbef64ca3f32de5243f
| 5,274,219,846,418 |
da7e49cd985f3fb0b4ef51874b27c3d95a9011ef
|
/WirelessMIC_v4.2.1_apkpure.com_source_from_JADX/com/google/android/gms/common/internal/C0462j.java
|
a9843156ee11b3025d22a9b1e6b637c9ff477ac6
|
[] |
no_license
|
Manesx/linuxHelp
|
https://github.com/Manesx/linuxHelp
|
76c628d3b0a6034c5320f444036ffaf38e093833
|
c4299b15fd7f5e57a34a306f7cb529794efa8133
|
refs/heads/master
| 2017-11-24T23:12:11.125000 | 2016-08-05T16:03:43 | 2016-08-05T16:03:43 | 64,486,325 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.google.android.gms.common.internal;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.util.Log;
/* renamed from: com.google.android.gms.common.internal.j */
public final class C0462j implements OnClickListener {
private final Activity f3190a;
private final Fragment f3191b;
private final Intent f3192c;
private final int f3193d;
public C0462j(Activity activity, Intent intent) {
this.f3190a = activity;
this.f3191b = null;
this.f3192c = intent;
this.f3193d = 2;
}
public C0462j(Fragment fragment, Intent intent) {
this.f3190a = null;
this.f3191b = fragment;
this.f3192c = intent;
this.f3193d = 2;
}
public final void onClick(DialogInterface dialogInterface, int i) {
try {
if (this.f3192c != null && this.f3191b != null) {
this.f3191b.startActivityForResult(this.f3192c, this.f3193d);
} else if (this.f3192c != null) {
this.f3190a.startActivityForResult(this.f3192c, this.f3193d);
}
dialogInterface.dismiss();
} catch (ActivityNotFoundException e) {
Log.e("SettingsRedirect", "Can't redirect to app settings for Google Play services");
}
}
}
|
UTF-8
|
Java
| 1,490 |
java
|
C0462j.java
|
Java
|
[] | null |
[] |
package com.google.android.gms.common.internal;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.util.Log;
/* renamed from: com.google.android.gms.common.internal.j */
public final class C0462j implements OnClickListener {
private final Activity f3190a;
private final Fragment f3191b;
private final Intent f3192c;
private final int f3193d;
public C0462j(Activity activity, Intent intent) {
this.f3190a = activity;
this.f3191b = null;
this.f3192c = intent;
this.f3193d = 2;
}
public C0462j(Fragment fragment, Intent intent) {
this.f3190a = null;
this.f3191b = fragment;
this.f3192c = intent;
this.f3193d = 2;
}
public final void onClick(DialogInterface dialogInterface, int i) {
try {
if (this.f3192c != null && this.f3191b != null) {
this.f3191b.startActivityForResult(this.f3192c, this.f3193d);
} else if (this.f3192c != null) {
this.f3190a.startActivityForResult(this.f3192c, this.f3193d);
}
dialogInterface.dismiss();
} catch (ActivityNotFoundException e) {
Log.e("SettingsRedirect", "Can't redirect to app settings for Google Play services");
}
}
}
| 1,490 | 0.665772 | 0.599329 | 44 | 32.863636 | 23.424532 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.681818 | false | false |
3
|
3676e4741939453d2267409249a2437fceb98d5d
| 13,039,520,712,675 |
253fad39dd2404fa0c1980e2fc70763bcb174d76
|
/src/test/java/com/khimin/shop/JpaTest.java
|
6400a8c09c64972f2bc79a505a4b5f2f70604d0d
|
[
"MIT"
] |
permissive
|
naz1719/Spring-Shop
|
https://github.com/naz1719/Spring-Shop
|
5387b39d5a454ce25bbb94ef460e23acd272dfa2
|
d652d5c69d6c9499c95c954ee266b5f42aa4276a
|
refs/heads/master
| 2021-03-22T02:45:13.197000 | 2017-06-12T11:10:55 | 2017-06-12T11:10:55 | 81,176,381 | 5 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.khimin.shop;
import com.khimin.shop.models.Product;
import com.khimin.shop.models.Role;
import com.khimin.shop.models.User;
import com.khimin.shop.repositories.ProductRepository;
import com.khimin.shop.repositories.UserRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.test.context.junit4.SpringRunner;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Created by nazar on 3/7/17.
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class JpaTest {
@Autowired
ProductRepository productRepository;
@Autowired
UserRepository userRepository;
@Test
public void readsFirstPageCorrectly() {
Page<Product> persons = productRepository.findAll(new PageRequest(0, 10));
assertThat(persons.isFirst(), is(true));
}
@Test
public void testUserOpertation() {
User nazar = new User("us","us@gmail.com","123456", Role.ADMIN,true);
userRepository.save(nazar);
User user =userRepository.findByUsername("us");
assertEquals(nazar, user);
}
@Test
public void testProductOperation(){
Product product = new Product(1,"v","bto",50,"boot.png");
productRepository.save(product);
assertEquals(product, productRepository.findOne(product.getId()));
}
}
|
UTF-8
|
Java
| 1,677 |
java
|
JpaTest.java
|
Java
|
[
{
"context": "ic org.junit.Assert.assertTrue;\n\n/**\n * Created by nazar on 3/7/17.\n */\n@RunWith(SpringRunner.class)\n@Spri",
"end": 788,
"score": 0.9365745186805725,
"start": 783,
"tag": "USERNAME",
"value": "nazar"
},
{
"context": "pertation() {\n User nazar = new User(\"us\",\"us@gmail.com\",\"123456\", Role.ADMIN,true);\n userReposito",
"end": 1270,
"score": 0.9999246597290039,
"start": 1258,
"tag": "EMAIL",
"value": "us@gmail.com"
},
{
"context": " User user =userRepository.findByUsername(\"us\");\n assertEquals(nazar, user);\n\n }\n ",
"end": 1388,
"score": 0.7046529054641724,
"start": 1386,
"tag": "USERNAME",
"value": "us"
}
] | null |
[] |
package com.khimin.shop;
import com.khimin.shop.models.Product;
import com.khimin.shop.models.Role;
import com.khimin.shop.models.User;
import com.khimin.shop.repositories.ProductRepository;
import com.khimin.shop.repositories.UserRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.test.context.junit4.SpringRunner;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Created by nazar on 3/7/17.
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class JpaTest {
@Autowired
ProductRepository productRepository;
@Autowired
UserRepository userRepository;
@Test
public void readsFirstPageCorrectly() {
Page<Product> persons = productRepository.findAll(new PageRequest(0, 10));
assertThat(persons.isFirst(), is(true));
}
@Test
public void testUserOpertation() {
User nazar = new User("us","<EMAIL>","123456", Role.ADMIN,true);
userRepository.save(nazar);
User user =userRepository.findByUsername("us");
assertEquals(nazar, user);
}
@Test
public void testProductOperation(){
Product product = new Product(1,"v","bto",50,"boot.png");
productRepository.save(product);
assertEquals(product, productRepository.findOne(product.getId()));
}
}
| 1,672 | 0.741205 | 0.731067 | 54 | 30.018518 | 23.05267 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.740741 | false | false |
3
|
a3e75509675d0154ff2fb20232c31f95e9ba93ce
| 8,589,950,706 |
1a5127fb8927bdacdaa22f2c1573e74db623ec1b
|
/Java/Eclipse/NLPIR/src/Test.java
|
0b0d890f35b3238be267bd345cb83b0615a46fd0
|
[] |
no_license
|
riskyhe309/MyCode
|
https://github.com/riskyhe309/MyCode
|
2b315b07c5c0004c2151c3735fb9e237573d2588
|
d9b7784b52204c4980b62eff25f5e2b45f679d13
|
refs/heads/master
| 2020-05-06T19:59:07.884000 | 2015-03-02T06:11:52 | 2015-03-02T06:11:52 | 31,525,378 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
public class Test {
public static void main(String[] args) throws IOException {
String input = "C:/Users/Risky/Desktop/1.txt";;
BufferedReader br = new BufferedReader(new FileReader(new File(input)));
Set<String> candidateSet = new HashSet<String>();
String line;
while ((line = br.readLine()) != null) {
String[] strings = line.split("\\s+");
if (!strings[0].equals(" "))
Split_Data_NLPIR.split(strings[0]);
}
br.close();
}
}
|
UTF-8
|
Java
| 620 |
java
|
Test.java
|
Java
|
[
{
"context": " throws IOException {\n\n\t\tString input = \"C:/Users/Risky/Desktop/1.txt\";;\n\t\t\n\t\tBufferedReader br = new Buf",
"end": 271,
"score": 0.7643880844116211,
"start": 266,
"tag": "USERNAME",
"value": "Risky"
}
] | null |
[] |
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
public class Test {
public static void main(String[] args) throws IOException {
String input = "C:/Users/Risky/Desktop/1.txt";;
BufferedReader br = new BufferedReader(new FileReader(new File(input)));
Set<String> candidateSet = new HashSet<String>();
String line;
while ((line = br.readLine()) != null) {
String[] strings = line.split("\\s+");
if (!strings[0].equals(" "))
Split_Data_NLPIR.split(strings[0]);
}
br.close();
}
}
| 620 | 0.679032 | 0.674194 | 28 | 21.142857 | 20.708374 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.571429 | false | false |
3
|
977d0ab6e1bddae8841a6783cccf62d096fa0ed2
| 32,530,082,331,027 |
f9073e04b90fcc411ad3c146aae6109654b69a06
|
/src/main/java/com/example/baike/service/impl/ChangeStateServiceImpl.java
|
fba93c10d2c17f8b1591beca7838df2c49c1c89c
|
[] |
no_license
|
twintial/Baike-back-end
|
https://github.com/twintial/Baike-back-end
|
f7194c82917be2831945e3378d70bd1da50310b8
|
626e2c1f88c3c8c52dc47b5e0458772da992b1db
|
refs/heads/master
| 2021-06-24T23:39:56.869000 | 2019-12-16T16:45:34 | 2019-12-16T16:45:34 | 222,475,468 | 1 | 1 | null | false | 2021-04-26T19:44:58 | 2019-11-18T15:00:14 | 2019-12-16T16:45:47 | 2021-04-26T19:44:58 | 76,410 | 1 | 1 | 1 |
Java
| false | false |
package com.example.baike.service.impl;
import com.example.baike.mapper.ChangeStateMapper;
import com.example.baike.service.ChangeStateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ChangeStateServiceImpl implements ChangeStateService {
@Autowired
ChangeStateMapper changeStateMapper;
@Override
public Long changeUser(Integer ID) {
return changeStateMapper.changeUser(ID);
}
@Override
public Long changeVideo(Integer ID) {
return changeStateMapper.changeVideo(ID);
}
}
|
UTF-8
|
Java
| 615 |
java
|
ChangeStateServiceImpl.java
|
Java
|
[] | null |
[] |
package com.example.baike.service.impl;
import com.example.baike.mapper.ChangeStateMapper;
import com.example.baike.service.ChangeStateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ChangeStateServiceImpl implements ChangeStateService {
@Autowired
ChangeStateMapper changeStateMapper;
@Override
public Long changeUser(Integer ID) {
return changeStateMapper.changeUser(ID);
}
@Override
public Long changeVideo(Integer ID) {
return changeStateMapper.changeVideo(ID);
}
}
| 615 | 0.773984 | 0.773984 | 22 | 26.954546 | 22.788507 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.363636 | false | false |
3
|
1ac90ebdbb65f1386b97aa3b3fae162236b3463e
| 25,958,782,405,370 |
e2b91e4d5f09961bc0b39e4a9199eb14ad73006e
|
/demo/demo.spring/src/main/java/com/demo/spring/SpringClient.java
|
78752d1de0597c217412084e3884eaf6cecb1dbf
|
[] |
no_license
|
yanyang/training
|
https://github.com/yanyang/training
|
ef0cbc63e45c6f43954ab7857006e47457892941
|
08806dfa55f6acbdcfb9d179a72c2a8c6b7d384a
|
refs/heads/master
| 2021-04-09T16:50:15.175000 | 2013-06-02T02:18:17 | 2013-06-02T02:18:17 | 10,470,850 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.demo.spring;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import com.demo.spring.system.security.account.AccountAccessor;
public class SpringClient {
public static void main(String[] args) {
DefaultListableBeanFactory factory = buildBeanFactory();
AccountAccessor accessor = factory.getBean(AccountAccessor.class);
System.out.println(accessor.getAccount("alice"));
factory.destroySingletons();
}
static DefaultListableBeanFactory buildBeanFactory() {
Resource config = new ClassPathResource("spring/service.xml");
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);
reader.loadBeanDefinitions(config);
return factory;
}
}
|
UTF-8
|
Java
| 1,023 |
java
|
SpringClient.java
|
Java
|
[
{
"context": "\n\n System.out.println(accessor.getAccount(\"alice\"));\n\n factory.destroySingletons();\n }\n\n",
"end": 607,
"score": 0.9571198225021362,
"start": 602,
"tag": "USERNAME",
"value": "alice"
}
] | null |
[] |
package com.demo.spring;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import com.demo.spring.system.security.account.AccountAccessor;
public class SpringClient {
public static void main(String[] args) {
DefaultListableBeanFactory factory = buildBeanFactory();
AccountAccessor accessor = factory.getBean(AccountAccessor.class);
System.out.println(accessor.getAccount("alice"));
factory.destroySingletons();
}
static DefaultListableBeanFactory buildBeanFactory() {
Resource config = new ClassPathResource("spring/service.xml");
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);
reader.loadBeanDefinitions(config);
return factory;
}
}
| 1,023 | 0.761486 | 0.761486 | 31 | 32 | 29.906305 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.483871 | false | false |
3
|
22ccfe0ff640ffb634b1a6fa89016e974b3a9348
| 9,560,597,233,299 |
81b2bd37d986db99904c0dd6f9e68d4c5b55fe0d
|
/sawmill/src/main/java/core/repository/dao/AddressDao.java
|
f945673ce73a495b79c9a7948534b5cbb30fdbf3
|
[] |
no_license
|
Kristjan-Kiolein/IDU0200
|
https://github.com/Kristjan-Kiolein/IDU0200
|
1e66d7dcfa113c095294f03452085b80cad74339
|
d50fc24efe62c77b4da2a17b4c15531080872672
|
refs/heads/master
| 2016-08-30T19:47:31.373000 | 2016-06-16T07:33:28 | 2016-06-16T07:33:28 | 51,360,152 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package core.repository.dao;
import core.constant.AddressType;
import core.constant.SubjectType;
import core.repository.model.Address;
import java.util.List;
/**
* Created by Kriku on 28.05.2016.
*/
public interface AddressDao extends BaseDao<Address, Integer> {
Address findPrimaryBySubject(Integer subjectId, core.repository.model.SubjectType subjectType);
void delete(Integer id);
List<Address> findAll(Integer id, SubjectType subjectType);
Address findPrimaryBySubjectAndType(Integer subjectFk, Integer subjectType, AddressType addressType);
}
|
UTF-8
|
Java
| 557 |
java
|
AddressDao.java
|
Java
|
[
{
"context": "ddress;\n\nimport java.util.List;\n\n/**\n * Created by Kriku on 28.05.2016.\n */\npublic interface AddressDao ex",
"end": 184,
"score": 0.9990261197090149,
"start": 179,
"tag": "USERNAME",
"value": "Kriku"
}
] | null |
[] |
package core.repository.dao;
import core.constant.AddressType;
import core.constant.SubjectType;
import core.repository.model.Address;
import java.util.List;
/**
* Created by Kriku on 28.05.2016.
*/
public interface AddressDao extends BaseDao<Address, Integer> {
Address findPrimaryBySubject(Integer subjectId, core.repository.model.SubjectType subjectType);
void delete(Integer id);
List<Address> findAll(Integer id, SubjectType subjectType);
Address findPrimaryBySubjectAndType(Integer subjectFk, Integer subjectType, AddressType addressType);
}
| 557 | 0.809695 | 0.795332 | 17 | 31.764706 | 31.296551 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.058824 | false | false |
3
|
eb7dc35f40a2847d53530a95c541dd2fdbc88322
| 9,285,719,311,481 |
187e5404c6f8bcdf0556e11a4f5a59f56f8c2f3e
|
/src/ch11/StringSubstringExam.java
|
530e8437d9b314bea1ea8087d49b58f733ede402
|
[] |
no_license
|
snagwuk/JAVA
|
https://github.com/snagwuk/JAVA
|
6e5f751b70de7fdababc7dcad84c412adcccec90
|
6d583b3b916e8b34666f1ea2bad11de7e9db7e00
|
refs/heads/master
| 2022-03-04T22:02:47.031000 | 2019-11-18T08:09:02 | 2019-11-18T08:09:02 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package ch11;
public class StringSubstringExam
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
String sn = "123456-1234567";
String f = sn.substring(0,6);
System.out.println(f);
String b = sn.substring(7);
System.out.println(b);
}
}
|
UTF-8
|
Java
| 370 |
java
|
StringSubstringExam.java
|
Java
|
[] | null |
[] |
package ch11;
public class StringSubstringExam
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
String sn = "123456-1234567";
String f = sn.substring(0,6);
System.out.println(f);
String b = sn.substring(7);
System.out.println(b);
}
}
| 370 | 0.518919 | 0.47027 | 18 | 18.555555 | 15.808655 | 42 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.388889 | false | false |
3
|
e1c19286e69ebc9388cda8729dff89a2799628db
| 11,982,958,787,899 |
78899754a5e9e7d3870dc9a027ee577227373acd
|
/api.task.preparation.drill/src/api/drill/Program.java
|
db95d9bf657e68d7c5d2c733364d173aa3909cd7
|
[] |
no_license
|
eldarba/82202-1-jerusalem
|
https://github.com/eldarba/82202-1-jerusalem
|
c058ccc7963a8153cc27a01315cb22b771c2edab
|
f24494403e45821c2f04eba423a8a477d6017bcf
|
refs/heads/master
| 2023-07-08T01:45:48.607000 | 2021-08-25T13:23:58 | 2021-08-25T13:23:58 | 373,507,732 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package api.drill;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Scanner;
public class Program {
private Scanner sc = new Scanner(System.in);
private int nextTaskId = 1;
private Schedualler schedualler = new Schedualler();
public static void main(String[] args) {
Program program = new Program();
program.start();
}
public void start() {
lbl: while (true) {
showMenu();
String command = sc.nextLine();
try {
switch (command) {
case "start":
if (!this.schedualler.isMonitoringActive()) {
this.schedualler.sartMonitoringTasks();
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
System.out.println("schedualler already running");
}
break;
case "stop":
this.sc.close();
this.schedualler.stopMonitoringTasks();
break lbl;
case "add":
Task task = getTaskFromUser();
schedualler.addTask(task);
System.out.println("addded: " + task);
break;
case "show":
this.schedualler.displayTasks();
break;
case "do":
System.out.print("enter task id to do: ");
int taskId = Integer.parseInt(sc.nextLine());
Task taskToDo = this.schedualler.getTask(taskId);
if (taskToDo != null) {
taskToDo.doTask();
System.out.println("task done");
}
break;
default:
System.out.println("invalid command: " + command);
break;
}
} catch (Exception e) {
System.out.println("ERROR: " + e.getMessage());
}
}
System.out.println("Bye!");
}
private static void showMenu() {
System.out.println("\nMENU");
System.out.println("start task schedualler .............. start");
System.out.println("stop task schedualler ............... stop");
System.out.println("add task ............................ add");
System.out.println("show task ........................... show");
System.out.println("do task ............................. do");
System.out.print("your choice: ");
}
public Task getTaskFromUser() {
int id = nextTaskId++;
System.out.print("enter task description: ");
String description = sc.nextLine();
System.out.print("enter hour: ");
int hour = Integer.parseInt(sc.nextLine());
System.out.print("enter minute: ");
int minute = Integer.parseInt(sc.nextLine());
System.out.print("enter second: ");
int second = Integer.parseInt(sc.nextLine());
LocalDateTime deadline = LocalDateTime.of(LocalDate.now(), LocalTime.of(hour, minute, second));
Task task = new Task(id, description, deadline);
return task;
}
}
|
UTF-8
|
Java
| 2,651 |
java
|
Program.java
|
Java
|
[] | null |
[] |
package api.drill;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Scanner;
public class Program {
private Scanner sc = new Scanner(System.in);
private int nextTaskId = 1;
private Schedualler schedualler = new Schedualler();
public static void main(String[] args) {
Program program = new Program();
program.start();
}
public void start() {
lbl: while (true) {
showMenu();
String command = sc.nextLine();
try {
switch (command) {
case "start":
if (!this.schedualler.isMonitoringActive()) {
this.schedualler.sartMonitoringTasks();
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
System.out.println("schedualler already running");
}
break;
case "stop":
this.sc.close();
this.schedualler.stopMonitoringTasks();
break lbl;
case "add":
Task task = getTaskFromUser();
schedualler.addTask(task);
System.out.println("addded: " + task);
break;
case "show":
this.schedualler.displayTasks();
break;
case "do":
System.out.print("enter task id to do: ");
int taskId = Integer.parseInt(sc.nextLine());
Task taskToDo = this.schedualler.getTask(taskId);
if (taskToDo != null) {
taskToDo.doTask();
System.out.println("task done");
}
break;
default:
System.out.println("invalid command: " + command);
break;
}
} catch (Exception e) {
System.out.println("ERROR: " + e.getMessage());
}
}
System.out.println("Bye!");
}
private static void showMenu() {
System.out.println("\nMENU");
System.out.println("start task schedualler .............. start");
System.out.println("stop task schedualler ............... stop");
System.out.println("add task ............................ add");
System.out.println("show task ........................... show");
System.out.println("do task ............................. do");
System.out.print("your choice: ");
}
public Task getTaskFromUser() {
int id = nextTaskId++;
System.out.print("enter task description: ");
String description = sc.nextLine();
System.out.print("enter hour: ");
int hour = Integer.parseInt(sc.nextLine());
System.out.print("enter minute: ");
int minute = Integer.parseInt(sc.nextLine());
System.out.print("enter second: ");
int second = Integer.parseInt(sc.nextLine());
LocalDateTime deadline = LocalDateTime.of(LocalDate.now(), LocalTime.of(hour, minute, second));
Task task = new Task(id, description, deadline);
return task;
}
}
| 2,651 | 0.61788 | 0.617126 | 101 | 25.247524 | 20.594822 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.277228 | false | false |
3
|
dae40293d7ac8576141ba82ec335d80b19c9bff4
| 31,722,628,465,271 |
3fc68d5fa9cd5ae684fec377242793f57d3dde46
|
/src/main/java/com/hhh/dao/entity/fenfa/SsOrder.java
|
37e842d75190d4c7ecdab9d4a4dc8e65f43983f3
|
[] |
no_license
|
ygj111/fenfa
|
https://github.com/ygj111/fenfa
|
11fa825eef4e93a1878be26f854acd068b8c4dd8
|
59f50abe8659650ef83ee23ad4f596715117061d
|
refs/heads/master
| 2021-01-12T11:58:00.815000 | 2016-09-22T02:01:42 | 2016-09-22T02:01:42 | 68,874,635 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.hhh.dao.entity.fenfa;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
import org.springframework.format.annotation.DateTimeFormat;
/**
* The persistent class for the ss_orders database table.
*
*/
@Entity
@Table(name="ss_orders")
@NamedQuery(name="SsOrder.findAll", query="SELECT s FROM SsOrder s")
public class SsOrder implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator="idGenerator")
@GenericGenerator(name="idGenerator", strategy="uuid")
private String id;
@Column(name="customer_id")
private String customerId;
private double discount;
@Column(name="order_date")
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date orderDate;
@Column(name="org_name")
private String orgName;
private String services;
private String status;//0:市场人员未审核;1:实施管理人员未审核;2:实施人员未审核;3:已实施
private double total;
private Date expired;
private String appname;
@OneToMany(mappedBy="ssOrder",cascade=CascadeType.ALL,fetch=FetchType.LAZY)
private List<SsOrdersService> ssOrdersServices;
@Column(name="company_id")
private String companyId;
public SsOrder() {
}
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
public String getCustomerId() {
return this.customerId;
}
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
public double getDiscount() {
return this.discount;
}
public void setDiscount(double discount) {
this.discount = discount;
}
public Date getOrderDate() {
return this.orderDate;
}
public void setOrderDate(Date orderDate) {
this.orderDate = orderDate;
}
public String getOrgName() {
return this.orgName;
}
public void setOrgName(String orgName) {
this.orgName = orgName;
}
public String getServices() {
return this.services;
}
public void setServices(String services) {
this.services = services;
}
public String getStatus() {
return this.status;
}
public void setStatus(String status) {
this.status = status;
}
public double getTotal() {
return this.total;
}
public void setTotal(double total) {
this.total = total;
}
public Date getExpired() {
return expired;
}
public void setExpired(Date expired) {
this.expired = expired;
}
public String getAppname() {
return appname;
}
public void setAppname(String appname) {
this.appname = appname;
}
public List<SsOrdersService> getSsOrdersServices() {
return ssOrdersServices;
}
public void setSsOrdersServices(List<SsOrdersService> ssOrdersServices) {
this.ssOrdersServices = ssOrdersServices;
}
public String getCompanyId() {
return companyId;
}
public void setCompanyId(String companyId) {
this.companyId = companyId;
}
}
|
UTF-8
|
Java
| 3,377 |
java
|
SsOrder.java
|
Java
|
[] | null |
[] |
package com.hhh.dao.entity.fenfa;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
import org.springframework.format.annotation.DateTimeFormat;
/**
* The persistent class for the ss_orders database table.
*
*/
@Entity
@Table(name="ss_orders")
@NamedQuery(name="SsOrder.findAll", query="SELECT s FROM SsOrder s")
public class SsOrder implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator="idGenerator")
@GenericGenerator(name="idGenerator", strategy="uuid")
private String id;
@Column(name="customer_id")
private String customerId;
private double discount;
@Column(name="order_date")
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date orderDate;
@Column(name="org_name")
private String orgName;
private String services;
private String status;//0:市场人员未审核;1:实施管理人员未审核;2:实施人员未审核;3:已实施
private double total;
private Date expired;
private String appname;
@OneToMany(mappedBy="ssOrder",cascade=CascadeType.ALL,fetch=FetchType.LAZY)
private List<SsOrdersService> ssOrdersServices;
@Column(name="company_id")
private String companyId;
public SsOrder() {
}
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
public String getCustomerId() {
return this.customerId;
}
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
public double getDiscount() {
return this.discount;
}
public void setDiscount(double discount) {
this.discount = discount;
}
public Date getOrderDate() {
return this.orderDate;
}
public void setOrderDate(Date orderDate) {
this.orderDate = orderDate;
}
public String getOrgName() {
return this.orgName;
}
public void setOrgName(String orgName) {
this.orgName = orgName;
}
public String getServices() {
return this.services;
}
public void setServices(String services) {
this.services = services;
}
public String getStatus() {
return this.status;
}
public void setStatus(String status) {
this.status = status;
}
public double getTotal() {
return this.total;
}
public void setTotal(double total) {
this.total = total;
}
public Date getExpired() {
return expired;
}
public void setExpired(Date expired) {
this.expired = expired;
}
public String getAppname() {
return appname;
}
public void setAppname(String appname) {
this.appname = appname;
}
public List<SsOrdersService> getSsOrdersServices() {
return ssOrdersServices;
}
public void setSsOrdersServices(List<SsOrdersService> ssOrdersServices) {
this.ssOrdersServices = ssOrdersServices;
}
public String getCompanyId() {
return companyId;
}
public void setCompanyId(String companyId) {
this.companyId = companyId;
}
}
| 3,377 | 0.707692 | 0.706184 | 162 | 18.475309 | 18.400282 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.12963 | false | false |
3
|
9f997693b795f27e200485fa4334b34ad2c9e5c9
| 30,150,670,460,073 |
bdf8d901c2bd49b18248656d70283fe0e8cc358d
|
/src/net/teamfps/savage/xml/XmlNode.java
|
d794eae818833e585e085ac267a4ee81378236c9
|
[] |
no_license
|
XzekyeX/Savage
|
https://github.com/XzekyeX/Savage
|
0845dca31c4caed89bbfdebcd548bedf0c9b5f4b
|
38e7cf9fcd8746b566d055c562eb2a56faf1cd4b
|
refs/heads/master
| 2020-04-08T00:54:00.446000 | 2018-11-23T19:51:52 | 2018-11-23T19:51:52 | 158,872,673 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package net.teamfps.savage.xml;
import java.util.HashMap;
import java.util.List;
/**
*
* @author Zekye
*
*/
public class XmlNode {
protected String name, data;
protected HashMap<String, String> attributes = new HashMap<String, String>();
protected HashMap<String, List<XmlNode>> childNodes = new HashMap<String, List<XmlNode>>();
protected XmlNode(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String getData() {
return data;
}
public String getAttribute(String attr) {
if (attributes.containsKey(attr)) return attributes.get(attr);
return null;
}
public List<XmlNode> getChildren(String name) {
if (childNodes.containsKey(name)) return childNodes.get(name);
return null;
}
public XmlNode getChild(String name, int index) {
List<XmlNode> nodes = getChildren(name);
if (nodes != null && index <= nodes.size() - 1) {
return nodes.get(index);
}
return null;
}
public XmlNode getChildWithAttribute(String name, String attr, String value) {
List<XmlNode> children = getChildren(name);
for (XmlNode n : children) {
String v = n.getAttribute(attr);
if (value.equals(v)) return n;
}
return null;
}
protected void addAttribute(String attr, String value) {
attributes.put(attr, value);
}
protected void addChild(String key, List<XmlNode> value) {
childNodes.put(key, value);
}
protected void addChild(XmlNode n) {
List<XmlNode> list = getChildren(n.getName());
if (list != null) addChild(n.getName(), list);
list.add(n);
}
protected void setData(String data) {
this.data = data;
}
}
|
UTF-8
|
Java
| 1,604 |
java
|
XmlNode.java
|
Java
|
[
{
"context": "ashMap;\nimport java.util.List;\n\n/**\n * \n * @author Zekye\n *\n */\npublic class XmlNode {\n\tprotected String n",
"end": 107,
"score": 0.7769016623497009,
"start": 102,
"tag": "USERNAME",
"value": "Zekye"
}
] | null |
[] |
package net.teamfps.savage.xml;
import java.util.HashMap;
import java.util.List;
/**
*
* @author Zekye
*
*/
public class XmlNode {
protected String name, data;
protected HashMap<String, String> attributes = new HashMap<String, String>();
protected HashMap<String, List<XmlNode>> childNodes = new HashMap<String, List<XmlNode>>();
protected XmlNode(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String getData() {
return data;
}
public String getAttribute(String attr) {
if (attributes.containsKey(attr)) return attributes.get(attr);
return null;
}
public List<XmlNode> getChildren(String name) {
if (childNodes.containsKey(name)) return childNodes.get(name);
return null;
}
public XmlNode getChild(String name, int index) {
List<XmlNode> nodes = getChildren(name);
if (nodes != null && index <= nodes.size() - 1) {
return nodes.get(index);
}
return null;
}
public XmlNode getChildWithAttribute(String name, String attr, String value) {
List<XmlNode> children = getChildren(name);
for (XmlNode n : children) {
String v = n.getAttribute(attr);
if (value.equals(v)) return n;
}
return null;
}
protected void addAttribute(String attr, String value) {
attributes.put(attr, value);
}
protected void addChild(String key, List<XmlNode> value) {
childNodes.put(key, value);
}
protected void addChild(XmlNode n) {
List<XmlNode> list = getChildren(n.getName());
if (list != null) addChild(n.getName(), list);
list.add(n);
}
protected void setData(String data) {
this.data = data;
}
}
| 1,604 | 0.692643 | 0.69202 | 72 | 21.277779 | 22.808516 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.597222 | false | false |
3
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.