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
8f426ae1882cd5b192ccff88ca6985e7f356214b
37,134,287,254,973
5d35858bfa1baeef80f1e2bc790f71eb86547ddf
/src/main/java/com/company/domain/Contribution.java
3226e2fd1d5bf2a271c873d635d0ac9708d39822
[]
no_license
roy-shantanu/domain-model
https://github.com/roy-shantanu/domain-model
2985a2c7bd4773446e5bdf97b497fbe21fce4295
aa4654027411b4d978f639b5251645aec81e4946
refs/heads/master
2021-08-12T08:18:09.543000
2017-11-14T15:30:44
2017-11-14T15:30:44
110,708,077
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.company.domain; public abstract class Contribution extends BaseEntity { private static final long serialVersionUID = -3507339722743065342L; private User user; public Contribution(User user) { this.user = user; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
UTF-8
Java
378
java
Contribution.java
Java
[]
null
[]
package com.company.domain; public abstract class Contribution extends BaseEntity { private static final long serialVersionUID = -3507339722743065342L; private User user; public Contribution(User user) { this.user = user; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
378
0.650794
0.600529
19
18.947369
19.874537
71
false
false
0
0
0
0
0
0
0.315789
false
false
5
70cbeb3e8e4e8d206bd7625f520b09af21401098
34,411,278,016,245
23df8b64f6d162963a623f41b8300daadd40cc78
/src/test/java/com/liuqi/v13/ClientTest.java
5046af5f49f2fccca3a075bac7f7b66bf0f65e8f
[]
no_license
LiuQiV5/java-design-pattern
https://github.com/LiuQiV5/java-design-pattern
3691892af2d7fe6bb19c2e9dede81d5c50865e32
868564a43f8ae6e9ad194bcab13315435305931d
refs/heads/master
2020-04-18T21:40:40.530000
2019-02-08T11:22:38
2019-02-08T11:22:38
167,771,420
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.liuqi.v13; import org.junit.Test; public class ClientTest { @Test public void clientTestV1(){ ActorController actorController = new ActorController(); Actor actor = actorController.construct(new DevilBuilder()); System.out.println(actor.getSex()); System.out.println(actor.getCostume()); System.out.println(actor.getFace()); System.out.println(actor.getHairstyle()); System.out.println(actor.getType()); } }
UTF-8
Java
492
java
ClientTest.java
Java
[]
null
[]
package com.liuqi.v13; import org.junit.Test; public class ClientTest { @Test public void clientTestV1(){ ActorController actorController = new ActorController(); Actor actor = actorController.construct(new DevilBuilder()); System.out.println(actor.getSex()); System.out.println(actor.getCostume()); System.out.println(actor.getFace()); System.out.println(actor.getHairstyle()); System.out.println(actor.getType()); } }
492
0.664634
0.658537
17
27.941177
22.451178
68
false
false
0
0
0
0
0
0
0.529412
false
false
5
f60049c05f3c4588e6efa7cbaa876dce16e8e847
23,656,679,914,096
0dac78154f1a5df87cd0da359ef1bc41f530bdbe
/edu-web/src/main/java/com/yunzhi/edu/web/service/NoticeService.java
5dc4df1dd71e03666714ba2cb7d9554f0af7d58d
[]
no_license
0top/edu-yunzhi
https://github.com/0top/edu-yunzhi
9218ea2487a925bdb5932733a98c290a7abdf7a9
bc23accaab93e75da30e77e66b728969be5c9854
refs/heads/master
2020-03-23T09:56:27.188000
2018-08-22T13:57:26
2018-08-22T13:57:26
141,415,962
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yunzhi.edu.web.service; import java.util.List; import com.yunzhi.edu.entity.EduNotice; import com.yunzhi.edu.entity.SchoolNotice; import com.yunzhi.edu.entity.User; public interface NoticeService { //给用户发通知 public int insertNoticeToUser(EduNotice notice); public int insertNoticeToSchoolStaff(String staffNum, SchoolNotice schoolNotice); public int insertNoticeToSchoolMutiStaff(String orgCode, String classId, String departmentId, SchoolNotice schoolNotice); public List<SchoolNotice> listSchoolNotice(User user); public List<SchoolNotice> listSchoolNoticeBySend(String orgCode, String sendFrom, int type); }
UTF-8
Java
657
java
NoticeService.java
Java
[]
null
[]
package com.yunzhi.edu.web.service; import java.util.List; import com.yunzhi.edu.entity.EduNotice; import com.yunzhi.edu.entity.SchoolNotice; import com.yunzhi.edu.entity.User; public interface NoticeService { //给用户发通知 public int insertNoticeToUser(EduNotice notice); public int insertNoticeToSchoolStaff(String staffNum, SchoolNotice schoolNotice); public int insertNoticeToSchoolMutiStaff(String orgCode, String classId, String departmentId, SchoolNotice schoolNotice); public List<SchoolNotice> listSchoolNotice(User user); public List<SchoolNotice> listSchoolNoticeBySend(String orgCode, String sendFrom, int type); }
657
0.809302
0.809302
23
27.043478
33.765789
122
false
false
0
0
0
0
0
0
1.26087
false
false
5
ea8f6c2b8e92790e934d7b339d978b94a7c6508b
34,866,544,547,953
5ec4ca4c59743a603470d7d447724ad3011e48f7
/slowlife/src/main/java/com/slowlife/table/LoveAuditTable.java
bbd337df8357c12e8b78f8f65ccea8f97bab5fa5
[]
no_license
LongYunLiMing/love
https://github.com/LongYunLiMing/love
c03f9bb8e33d7a0fb754f1bc2a7dd14da966c277
1fbebf4e545427d76b393ba687da494b3b3c391b
refs/heads/master
2020-03-31T12:16:56.353000
2018-10-09T08:48:26
2018-10-09T08:48:26
152,209,950
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.slowlife.table; import io.github.biezhi.anima.Model; import io.github.biezhi.anima.annotation.Table; @Table(name = "love_audit_table") public class LoveAuditTable extends Model { private String id; private String loveId; private String administratorId; private String time; public void setTime(String time) { this.time = time; } public String getTime() { return time; } public void setAdministratorId(String administratorId) { this.administratorId = administratorId; } public String getAdministratorId() { return administratorId; } public void setLoveId(String loveId) { this.loveId = loveId; } public String getLoveId() { return loveId; } public void setId(String id) { this.id = id; } public String getId() { return id; } }
UTF-8
Java
893
java
LoveAuditTable.java
Java
[]
null
[]
package com.slowlife.table; import io.github.biezhi.anima.Model; import io.github.biezhi.anima.annotation.Table; @Table(name = "love_audit_table") public class LoveAuditTable extends Model { private String id; private String loveId; private String administratorId; private String time; public void setTime(String time) { this.time = time; } public String getTime() { return time; } public void setAdministratorId(String administratorId) { this.administratorId = administratorId; } public String getAdministratorId() { return administratorId; } public void setLoveId(String loveId) { this.loveId = loveId; } public String getLoveId() { return loveId; } public void setId(String id) { this.id = id; } public String getId() { return id; } }
893
0.638298
0.638298
45
18.844444
16.821884
60
false
false
0
0
0
0
0
0
0.333333
false
false
5
cfcbe2fc62bd85a02c6668d33d6307f57908b194
34,041,910,832,775
708cc1a44c5a097fc937d0c7d5a55f347d973a03
/java/mr/src/main/java/com/cloudera/recordservice/mapreduce/RecordServiceInputFormatBase.java
4c6166c0a186b603efb84d62b2be7c6b97a43727
[ "Apache-2.0" ]
permissive
Eevee33/RecordServiceClient
https://github.com/Eevee33/RecordServiceClient
756ce346cb1b903800ac8ad6ff4a32a257dc1803
c08931a5ec3873a818531fb905ce8b1a99a65c21
refs/heads/master
2021-01-23T04:19:34.239000
2016-03-16T21:53:56
2016-03-22T01:39:48
54,481,147
1
0
null
true
2016-03-22T14:21:29
2016-03-22T14:21:29
2016-02-23T18:29:55
2016-03-22T01:40:09
4,692
0
0
0
null
null
null
// Copyright 2012 Cloudera Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.cloudera.recordservice.mapreduce; import java.io.IOException; import java.util.List; import org.apache.hadoop.mapreduce.InputFormat; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.JobContext; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.cloudera.recordservice.core.RecordServiceException; import com.cloudera.recordservice.core.TaskStatus.Stats; import com.cloudera.recordservice.mr.PlanUtil; import com.cloudera.recordservice.mr.RecordReaderCore; /** * The base RecordService input format that handles functionality common to * all RecordService InputFormats. */ public abstract class RecordServiceInputFormatBase<K, V> extends InputFormat<K, V> { // Name of record service counters group. public final static String COUNTERS_GROUP_NAME = "Record Service Counters"; private final static Logger LOG = LoggerFactory.getLogger(RecordServiceInputFormatBase.class); @Override public List<InputSplit> getSplits(JobContext context) throws IOException, InterruptedException { return PlanUtil.getSplits( context.getConfiguration(), context.getCredentials()).splits; } /** * Populates RecordService counters in ctx from counters. */ public static void setCounters(TaskAttemptContext ctx, Stats counters) { if (ctx == null) return; ctx.getCounter(COUNTERS_GROUP_NAME, "Records Read").setValue( counters.numRecordsRead); ctx.getCounter(COUNTERS_GROUP_NAME, "Records Returned").setValue( counters.numRecordsReturned); ctx.getCounter(COUNTERS_GROUP_NAME, "Record Serialization Time(ms)").setValue( counters.serializeTimeMs); ctx.getCounter(COUNTERS_GROUP_NAME, "Client Time(ms)").setValue( counters.clientTimeMs); if (counters.hdfsCountersSet) { ctx.getCounter(COUNTERS_GROUP_NAME, "Bytes Read").setValue( counters.bytesRead); ctx.getCounter(COUNTERS_GROUP_NAME, "Decompression Time(ms)").setValue( counters.decompressTimeMs); ctx.getCounter(COUNTERS_GROUP_NAME, "Bytes Read Local").setValue( counters.bytesReadLocal); ctx.getCounter(COUNTERS_GROUP_NAME, "HDFS Throughput(MB/s)").setValue( (long)(counters.hdfsThroughput / (1024 * 1024))); } } /** * Base class of RecordService based record readers. */ protected abstract static class RecordReaderBase<K,V> extends RecordReader<K, V> { private static final Logger LOG = LoggerFactory.getLogger(RecordReaderBase.class); protected TaskAttemptContext context_; protected RecordReaderCore reader_; /** * Initializes the RecordReader and starts execution of the task. */ @Override public void initialize(InputSplit split, TaskAttemptContext context) throws IOException { RecordServiceInputSplit rsSplit = (RecordServiceInputSplit) split; try { reader_ = new RecordReaderCore(context.getConfiguration(), context.getCredentials(), rsSplit.getTaskInfo()); } catch (RecordServiceException e) { throw new IOException("Failed to execute task.", e); } context_ = context; } @Override public void close() throws IOException { if (reader_ != null) { try { RecordServiceInputFormatBase.setCounters( context_, reader_.records().getStatus().stats); } catch (RecordServiceException e) { LOG.debug("Could not populate counters: " + e); } reader_.close(); reader_ = null; } } @Override public float getProgress() throws IOException { if (reader_ == null) return 1; return reader_.records().progress(); } } }
UTF-8
Java
4,419
java
RecordServiceInputFormatBase.java
Java
[]
null
[]
// Copyright 2012 Cloudera Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.cloudera.recordservice.mapreduce; import java.io.IOException; import java.util.List; import org.apache.hadoop.mapreduce.InputFormat; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.JobContext; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.cloudera.recordservice.core.RecordServiceException; import com.cloudera.recordservice.core.TaskStatus.Stats; import com.cloudera.recordservice.mr.PlanUtil; import com.cloudera.recordservice.mr.RecordReaderCore; /** * The base RecordService input format that handles functionality common to * all RecordService InputFormats. */ public abstract class RecordServiceInputFormatBase<K, V> extends InputFormat<K, V> { // Name of record service counters group. public final static String COUNTERS_GROUP_NAME = "Record Service Counters"; private final static Logger LOG = LoggerFactory.getLogger(RecordServiceInputFormatBase.class); @Override public List<InputSplit> getSplits(JobContext context) throws IOException, InterruptedException { return PlanUtil.getSplits( context.getConfiguration(), context.getCredentials()).splits; } /** * Populates RecordService counters in ctx from counters. */ public static void setCounters(TaskAttemptContext ctx, Stats counters) { if (ctx == null) return; ctx.getCounter(COUNTERS_GROUP_NAME, "Records Read").setValue( counters.numRecordsRead); ctx.getCounter(COUNTERS_GROUP_NAME, "Records Returned").setValue( counters.numRecordsReturned); ctx.getCounter(COUNTERS_GROUP_NAME, "Record Serialization Time(ms)").setValue( counters.serializeTimeMs); ctx.getCounter(COUNTERS_GROUP_NAME, "Client Time(ms)").setValue( counters.clientTimeMs); if (counters.hdfsCountersSet) { ctx.getCounter(COUNTERS_GROUP_NAME, "Bytes Read").setValue( counters.bytesRead); ctx.getCounter(COUNTERS_GROUP_NAME, "Decompression Time(ms)").setValue( counters.decompressTimeMs); ctx.getCounter(COUNTERS_GROUP_NAME, "Bytes Read Local").setValue( counters.bytesReadLocal); ctx.getCounter(COUNTERS_GROUP_NAME, "HDFS Throughput(MB/s)").setValue( (long)(counters.hdfsThroughput / (1024 * 1024))); } } /** * Base class of RecordService based record readers. */ protected abstract static class RecordReaderBase<K,V> extends RecordReader<K, V> { private static final Logger LOG = LoggerFactory.getLogger(RecordReaderBase.class); protected TaskAttemptContext context_; protected RecordReaderCore reader_; /** * Initializes the RecordReader and starts execution of the task. */ @Override public void initialize(InputSplit split, TaskAttemptContext context) throws IOException { RecordServiceInputSplit rsSplit = (RecordServiceInputSplit) split; try { reader_ = new RecordReaderCore(context.getConfiguration(), context.getCredentials(), rsSplit.getTaskInfo()); } catch (RecordServiceException e) { throw new IOException("Failed to execute task.", e); } context_ = context; } @Override public void close() throws IOException { if (reader_ != null) { try { RecordServiceInputFormatBase.setCounters( context_, reader_.records().getStatus().stats); } catch (RecordServiceException e) { LOG.debug("Could not populate counters: " + e); } reader_.close(); reader_ = null; } } @Override public float getProgress() throws IOException { if (reader_ == null) return 1; return reader_.records().progress(); } } }
4,419
0.712152
0.707852
122
35.22131
26.412401
84
false
false
0
0
0
0
0
0
0.52459
false
false
5
3927b2deae087db0f57b5b37d5ef00dac318a865
8,727,373,596,204
fa04a9f8b10f58049b6676fc5f57e0786850350c
/ linjianglou-project1 --username yzh8609@gmail.com/TroopsSystem/src/org/troops/xueji/action/StuGraduateAdmitAction.java
9e0cb2dc5011c74212aae211c091ff3bfc1c4b04
[]
no_license
dalinhuang/linjianglou-project1
https://github.com/dalinhuang/linjianglou-project1
cc03f5910938cf148502876b47402edb227e83e9
c987fb1345478c7814bd9b2f32ff015dd21980ae
refs/heads/master
2018-01-08T22:05:34.751000
2009-11-01T08:11:27
2009-11-01T08:11:27
46,656,818
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.troops.xueji.action; import java.util.List; import org.troops.model.User; import org.troops.xueji.service.UserService; import com.opensymphony.xwork2.ActionSupport; public class StuGraduateAdmitAction extends ActionSupport { private List<User> unGraduatedStu; private UserService userSer; public List<User> getUnGraduatedStu() { return unGraduatedStu; } public void setUnGraduatedStu(List<User> unGraduatedStu) { this.unGraduatedStu = unGraduatedStu; } public UserService getUserSer() { return userSer; } public void setUserSer(UserService userSer) { this.userSer = userSer; } @Override public String execute() throws Exception { unGraduatedStu = userSer.unGraduateStuList(); return SUCCESS; } }
UTF-8
Java
785
java
StuGraduateAdmitAction.java
Java
[]
null
[]
package org.troops.xueji.action; import java.util.List; import org.troops.model.User; import org.troops.xueji.service.UserService; import com.opensymphony.xwork2.ActionSupport; public class StuGraduateAdmitAction extends ActionSupport { private List<User> unGraduatedStu; private UserService userSer; public List<User> getUnGraduatedStu() { return unGraduatedStu; } public void setUnGraduatedStu(List<User> unGraduatedStu) { this.unGraduatedStu = unGraduatedStu; } public UserService getUserSer() { return userSer; } public void setUserSer(UserService userSer) { this.userSer = userSer; } @Override public String execute() throws Exception { unGraduatedStu = userSer.unGraduateStuList(); return SUCCESS; } }
785
0.732484
0.73121
38
18.657894
19.508806
59
false
false
0
0
0
0
0
0
1.052632
false
false
5
4cfd1aa550b4af1733f8712b19b5ace9b3ad0344
35,167,192,254,848
571b0477a28d4648d999a56d4c8720bc4d8e7ae2
/common-lib-web/src/main/java/net/geektop/web/handler/ApiExceptionHandler.java
61b7519a5cb157ae6669c3f7db3fdd18041eb4f0
[]
no_license
springwindyike/OneStack
https://github.com/springwindyike/OneStack
5cb0e3014ef9ee5fe5dfb4ffe9bd692513e4dfbc
9f4228a22945d5d29eb1d142a48a2552b10f78a0
refs/heads/master
2023-07-18T21:31:22.088000
2021-09-08T08:39:40
2021-09-08T08:39:40
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.geektop.web.handler; import lombok.extern.slf4j.Slf4j; import net.geektop.web.exception.CommonException; import net.geektop.web.model.BaseResponse; import org.hibernate.validator.internal.engine.path.PathImpl; import org.springframework.dao.DuplicateKeyException; import org.springframework.http.HttpStatus; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.validation.BindException; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.HttpMediaTypeNotSupportedException; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; import org.springframework.web.servlet.NoHandlerFoundException; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import javax.validation.ValidationException; import java.sql.SQLException; /** * @author Alex * @version V1.0 * @Package net.geektop.common.handler * @date 2020/1/13 10:58 */ @Slf4j @RestControllerAdvice public class ApiExceptionHandler { @ExceptionHandler(MissingServletRequestParameterException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public BaseResponse handlerError(MissingServletRequestParameterException e) { String message = String.format("Missing Request Parameter: %s", e.getParameterName()); return BaseResponse .builder() .message(message) .code(HttpStatus.BAD_REQUEST.value()) .build(); } @ExceptionHandler(MethodArgumentTypeMismatchException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public BaseResponse handleError(MethodArgumentTypeMismatchException e) { log.warn("Method Argument Type Mismatch", e); String message = String.format("Method Argument Type Mismatch: %s", e.getName()); return BaseResponse .builder() .message(message) .code(HttpStatus.BAD_REQUEST.value()) .build(); } @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public BaseResponse handleError(MethodArgumentNotValidException e) { log.warn("Method Argument Not Valid", e); BindingResult result = e.getBindingResult(); FieldError error = result.getFieldError(); String message = String.format("%s:%s", error.getField(), error.getDefaultMessage()); return BaseResponse .builder() .message(message) .code(HttpStatus.BAD_REQUEST.value()) .build(); } @ExceptionHandler(BindException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public BaseResponse handleError(BindException e) { log.warn("Bind Exception", e); FieldError error = e.getFieldError(); assert error != null; String message = String.format("%s:%s", error.getField(), error.getDefaultMessage()); return BaseResponse .builder() .message(message) .code(HttpStatus.BAD_REQUEST.value()) .build(); } @ExceptionHandler(ConstraintViolationException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public BaseResponse handleError(ConstraintViolationException e) { log.warn("Constraint Violation", e); ConstraintViolation<?> violation = e.getConstraintViolations().iterator().next(); String path = ((PathImpl) violation.getPropertyPath()).getLeafNode().getName(); String message = String.format("%s:%s", path, violation.getMessage()); return BaseResponse .builder() .message(message) .code(HttpStatus.BAD_REQUEST.value()) .build(); } @ExceptionHandler(NoHandlerFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) public BaseResponse handleError(NoHandlerFoundException e) { log.error("404 Not Found", e); return BaseResponse .builder() .message(e.getMessage()) .code(HttpStatus.NOT_FOUND.value()) .build(); } @ExceptionHandler(HttpMessageNotReadableException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public BaseResponse handleError(HttpMessageNotReadableException e) { log.error("Message Not Readable", e); return BaseResponse .builder() .message(e.getMessage()) .code(HttpStatus.BAD_REQUEST.value()) .build(); } @ExceptionHandler(HttpRequestMethodNotSupportedException.class) @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED) public BaseResponse handleError(HttpRequestMethodNotSupportedException e) { log.error("Request Method Not Supported", e); return BaseResponse .builder() .message(e.getMessage()) .code(HttpStatus.METHOD_NOT_ALLOWED.value()) .build(); } @ExceptionHandler(HttpMediaTypeNotSupportedException.class) @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE) public BaseResponse handleError(HttpMediaTypeNotSupportedException e) { log.error("Media Type Not Supported", e); return BaseResponse .builder() .message(e.getMessage()) .code(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value()) .build(); } @ExceptionHandler(ValidationException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public BaseResponse handleError(ValidationException e) { log.error("Parameter error", e); return BaseResponse.builder() .message(e.getMessage()) .code(HttpStatus.BAD_REQUEST.value()) .build(); } @ExceptionHandler(DuplicateKeyException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public BaseResponse handleError(DuplicateKeyException e) { log.error("Data Duplicate", e); return BaseResponse.builder() .message("Data Duplicate") .code(HttpStatus.BAD_REQUEST.value()) .build(); } @ExceptionHandler(SQLException.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public BaseResponse handleError(SQLException e) { log.error("database error: ", e); return BaseResponse .builder() .message(e.getMessage()) .code(HttpStatus.INTERNAL_SERVER_ERROR.value()) .build(); } @ExceptionHandler(CommonException.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public BaseResponse handleError(CommonException e) { log.error("Service Exception", e); return BaseResponse .builder() .message(e.getMessage()) .code(HttpStatus.INTERNAL_SERVER_ERROR.value()) .build(); } @ExceptionHandler(Throwable.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public BaseResponse handleError(Throwable e) { log.error("Internal Server Error", e); return BaseResponse .builder() .message(e.getMessage()) .code(HttpStatus.INTERNAL_SERVER_ERROR.value()) .build(); } }
UTF-8
Java
7,035
java
ApiExceptionHandler.java
Java
[ { "context": "ion;\nimport java.sql.SQLException;\n\n/**\n * @author Alex\n * @version V1.0\n * @Package net.geektop.common.h", "end": 1378, "score": 0.9987196922302246, "start": 1374, "tag": "NAME", "value": "Alex" } ]
null
[]
package net.geektop.web.handler; import lombok.extern.slf4j.Slf4j; import net.geektop.web.exception.CommonException; import net.geektop.web.model.BaseResponse; import org.hibernate.validator.internal.engine.path.PathImpl; import org.springframework.dao.DuplicateKeyException; import org.springframework.http.HttpStatus; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.validation.BindException; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.HttpMediaTypeNotSupportedException; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; import org.springframework.web.servlet.NoHandlerFoundException; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import javax.validation.ValidationException; import java.sql.SQLException; /** * @author Alex * @version V1.0 * @Package net.geektop.common.handler * @date 2020/1/13 10:58 */ @Slf4j @RestControllerAdvice public class ApiExceptionHandler { @ExceptionHandler(MissingServletRequestParameterException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public BaseResponse handlerError(MissingServletRequestParameterException e) { String message = String.format("Missing Request Parameter: %s", e.getParameterName()); return BaseResponse .builder() .message(message) .code(HttpStatus.BAD_REQUEST.value()) .build(); } @ExceptionHandler(MethodArgumentTypeMismatchException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public BaseResponse handleError(MethodArgumentTypeMismatchException e) { log.warn("Method Argument Type Mismatch", e); String message = String.format("Method Argument Type Mismatch: %s", e.getName()); return BaseResponse .builder() .message(message) .code(HttpStatus.BAD_REQUEST.value()) .build(); } @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public BaseResponse handleError(MethodArgumentNotValidException e) { log.warn("Method Argument Not Valid", e); BindingResult result = e.getBindingResult(); FieldError error = result.getFieldError(); String message = String.format("%s:%s", error.getField(), error.getDefaultMessage()); return BaseResponse .builder() .message(message) .code(HttpStatus.BAD_REQUEST.value()) .build(); } @ExceptionHandler(BindException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public BaseResponse handleError(BindException e) { log.warn("Bind Exception", e); FieldError error = e.getFieldError(); assert error != null; String message = String.format("%s:%s", error.getField(), error.getDefaultMessage()); return BaseResponse .builder() .message(message) .code(HttpStatus.BAD_REQUEST.value()) .build(); } @ExceptionHandler(ConstraintViolationException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public BaseResponse handleError(ConstraintViolationException e) { log.warn("Constraint Violation", e); ConstraintViolation<?> violation = e.getConstraintViolations().iterator().next(); String path = ((PathImpl) violation.getPropertyPath()).getLeafNode().getName(); String message = String.format("%s:%s", path, violation.getMessage()); return BaseResponse .builder() .message(message) .code(HttpStatus.BAD_REQUEST.value()) .build(); } @ExceptionHandler(NoHandlerFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) public BaseResponse handleError(NoHandlerFoundException e) { log.error("404 Not Found", e); return BaseResponse .builder() .message(e.getMessage()) .code(HttpStatus.NOT_FOUND.value()) .build(); } @ExceptionHandler(HttpMessageNotReadableException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public BaseResponse handleError(HttpMessageNotReadableException e) { log.error("Message Not Readable", e); return BaseResponse .builder() .message(e.getMessage()) .code(HttpStatus.BAD_REQUEST.value()) .build(); } @ExceptionHandler(HttpRequestMethodNotSupportedException.class) @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED) public BaseResponse handleError(HttpRequestMethodNotSupportedException e) { log.error("Request Method Not Supported", e); return BaseResponse .builder() .message(e.getMessage()) .code(HttpStatus.METHOD_NOT_ALLOWED.value()) .build(); } @ExceptionHandler(HttpMediaTypeNotSupportedException.class) @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE) public BaseResponse handleError(HttpMediaTypeNotSupportedException e) { log.error("Media Type Not Supported", e); return BaseResponse .builder() .message(e.getMessage()) .code(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value()) .build(); } @ExceptionHandler(ValidationException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public BaseResponse handleError(ValidationException e) { log.error("Parameter error", e); return BaseResponse.builder() .message(e.getMessage()) .code(HttpStatus.BAD_REQUEST.value()) .build(); } @ExceptionHandler(DuplicateKeyException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public BaseResponse handleError(DuplicateKeyException e) { log.error("Data Duplicate", e); return BaseResponse.builder() .message("Data Duplicate") .code(HttpStatus.BAD_REQUEST.value()) .build(); } @ExceptionHandler(SQLException.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public BaseResponse handleError(SQLException e) { log.error("database error: ", e); return BaseResponse .builder() .message(e.getMessage()) .code(HttpStatus.INTERNAL_SERVER_ERROR.value()) .build(); } @ExceptionHandler(CommonException.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public BaseResponse handleError(CommonException e) { log.error("Service Exception", e); return BaseResponse .builder() .message(e.getMessage()) .code(HttpStatus.INTERNAL_SERVER_ERROR.value()) .build(); } @ExceptionHandler(Throwable.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public BaseResponse handleError(Throwable e) { log.error("Internal Server Error", e); return BaseResponse .builder() .message(e.getMessage()) .code(HttpStatus.INTERNAL_SERVER_ERROR.value()) .build(); } }
7,035
0.743284
0.740583
200
34.174999
23.44215
90
false
false
0
0
0
0
0
0
0.415
false
false
5
5eb678cc28825c7072673c76cd9a0dd65e0ca460
37,099,927,521,252
caa125234a3c3e8fff496a9d4e11f49ac7701309
/main/java/com/maywide/test/BossInterTest.java
fd01851718c95c165c78b1bc721430d0b7427ea7
[]
no_license
lisongkang/my-first-project-for-revcocomcmms
https://github.com/lisongkang/my-first-project-for-revcocomcmms
1885f49fa1a7ef8686c3d8b7d9b5a50585bb3b8d
6079a3d9d24bd44ae3af24dc603846d460910f3b
refs/heads/master
2022-05-01T16:34:20.261000
2022-04-18T13:55:04
2022-04-18T13:55:04
207,246,589
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.maywide.test; import com.maywide.biz.pay.weixin.PayCallbackNotify; import com.maywide.biz.pay.weixin.Util; import com.maywide.core.util.PinYinUtils; public class BossInterTest { public static void main(String[] args) { try { /*JSONObject requestContent = new JSONObject(); requestContent.put("keyno", "8440710109083803"); requestContent.put("pagesize", "20"); System.out.println(requestContent.toString()); RemotecallLog remotecallLog = BossHttpClientImpl.requestPost("QUE_SERVPRDINFO", requestContent.toString()); System.out.println(remotecallLog.getResponse());*/ /*Set set = new HashSet(); set.add(new Long(1)); set.add(new Long(2)); set.add(new Long(3)); System.out.println(set.size()); set.remove(new Long(2)); System.out.println(set.size());*/ /*JSONObject requestContent = new JSONObject(); requestContent.put("custid", "1304497"); System.out.println(requestContent.toString()); RemotecallLog remotecallLog = BossHttpClientImpl.requestPost("QUE_BIZLOGBYPAGE", requestContent.toString()); System.out.println(remotecallLog.getResponse());*/ //System.out.println(Double.valueOf("79.60").intValue()); //XmlMapper xmlMapper = new XmlMapper(); //String content = "<xml><appid><![CDATA[wxa7621a1ce2ed3064]]></appid><attach><![CDATA[test]]></attach><bank_type><![CDATA[CFT]]></bank_type><cash_fee><![CDATA[1]]></cash_fee><fee_type><![CDATA[CNY]]></fee_type><is_subscribe><![CDATA[Y]]></is_subscribe><mch_id><![CDATA[1220331001]]></mch_id><nonce_str><![CDATA[72zcp2dbhzczsxxa10033028wha4v4fi]]></nonce_str><openid><![CDATA[oyJ5ot6GCkxDshfJ5i0ojNpagHMQ]]></openid><out_trade_no><![CDATA[1000000002]]></out_trade_no><result_code><![CDATA[SUCCESS]]></result_code><return_code><![CDATA[SUCCESS]]></return_code><sign><![CDATA[79111538CF141828A624553EA7EAD618]]></sign><time_end><![CDATA[20151010112059]]></time_end><total_fee>1</total_fee><trade_type><![CDATA[NATIVE]]></trade_type><transaction_id><![CDATA[1007760614201510101147259346]]></transaction_id></xml>"; //XmlMapper xmlMapper = new XmlMapper(); //PayCallbackNotify payCallbackNotify = xmlMapper.readValue(content, PayCallbackNotify.class); //PayCallbackNotify payCallbackNotify = (PayCallbackNotify) Util.getObjectFromXML(content, PayCallbackNotify.class); /*int totalfee = Integer.valueOf("10"); double fee = totalfee / 100.0; System.out.println(fee);*/ /*String pinyin1 = PinYinUtils.converterToFirstSpell("21分部"); String pinyin2 = PinYinUtils.converterToFirstSpell("FG分部"); System.out.println(pinyin1.compareTo(pinyin2));*/ String path = "http://210.21.65.94:6062/moss/api"; int pos = path.indexOf("/", 8); System.out.println(path.substring(0, pos)); //System.out.println(path.substring(0, pos)); } catch (Exception e) { e.printStackTrace(); } } }
UTF-8
Java
2,958
java
BossInterTest.java
Java
[ { "context": "NObject(); \n\t requestContent.put(\"keyno\", \"8440710109083803\");\n\t requestContent.put(\"pagesize\", \"20\");", "end": 348, "score": 0.999699056148529, "start": 332, "tag": "KEY", "value": "8440710109083803" }, { "context": "mpareTo(pinyin2));*/\n\t\t\t\n\t\t\tString path = \"http://210.21.65.94:6062/moss/api\";\n\t\t\tint pos = path.indexOf(\"/\", 8)", "end": 2743, "score": 0.9996140599250793, "start": 2731, "tag": "IP_ADDRESS", "value": "210.21.65.94" } ]
null
[]
package com.maywide.test; import com.maywide.biz.pay.weixin.PayCallbackNotify; import com.maywide.biz.pay.weixin.Util; import com.maywide.core.util.PinYinUtils; public class BossInterTest { public static void main(String[] args) { try { /*JSONObject requestContent = new JSONObject(); requestContent.put("keyno", "8440710109083803"); requestContent.put("pagesize", "20"); System.out.println(requestContent.toString()); RemotecallLog remotecallLog = BossHttpClientImpl.requestPost("QUE_SERVPRDINFO", requestContent.toString()); System.out.println(remotecallLog.getResponse());*/ /*Set set = new HashSet(); set.add(new Long(1)); set.add(new Long(2)); set.add(new Long(3)); System.out.println(set.size()); set.remove(new Long(2)); System.out.println(set.size());*/ /*JSONObject requestContent = new JSONObject(); requestContent.put("custid", "1304497"); System.out.println(requestContent.toString()); RemotecallLog remotecallLog = BossHttpClientImpl.requestPost("QUE_BIZLOGBYPAGE", requestContent.toString()); System.out.println(remotecallLog.getResponse());*/ //System.out.println(Double.valueOf("79.60").intValue()); //XmlMapper xmlMapper = new XmlMapper(); //String content = "<xml><appid><![CDATA[wxa7621a1ce2ed3064]]></appid><attach><![CDATA[test]]></attach><bank_type><![CDATA[CFT]]></bank_type><cash_fee><![CDATA[1]]></cash_fee><fee_type><![CDATA[CNY]]></fee_type><is_subscribe><![CDATA[Y]]></is_subscribe><mch_id><![CDATA[1220331001]]></mch_id><nonce_str><![CDATA[72zcp2dbhzczsxxa10033028wha4v4fi]]></nonce_str><openid><![CDATA[oyJ5ot6GCkxDshfJ5i0ojNpagHMQ]]></openid><out_trade_no><![CDATA[1000000002]]></out_trade_no><result_code><![CDATA[SUCCESS]]></result_code><return_code><![CDATA[SUCCESS]]></return_code><sign><![CDATA[79111538CF141828A624553EA7EAD618]]></sign><time_end><![CDATA[20151010112059]]></time_end><total_fee>1</total_fee><trade_type><![CDATA[NATIVE]]></trade_type><transaction_id><![CDATA[1007760614201510101147259346]]></transaction_id></xml>"; //XmlMapper xmlMapper = new XmlMapper(); //PayCallbackNotify payCallbackNotify = xmlMapper.readValue(content, PayCallbackNotify.class); //PayCallbackNotify payCallbackNotify = (PayCallbackNotify) Util.getObjectFromXML(content, PayCallbackNotify.class); /*int totalfee = Integer.valueOf("10"); double fee = totalfee / 100.0; System.out.println(fee);*/ /*String pinyin1 = PinYinUtils.converterToFirstSpell("21分部"); String pinyin2 = PinYinUtils.converterToFirstSpell("FG分部"); System.out.println(pinyin1.compareTo(pinyin2));*/ String path = "http://192.168.3.11:6062/moss/api"; int pos = path.indexOf("/", 8); System.out.println(path.substring(0, pos)); //System.out.println(path.substring(0, pos)); } catch (Exception e) { e.printStackTrace(); } } }
2,958
0.68678
0.627119
60
48.166668
103.79084
814
false
false
0
0
0
0
0
0
2.916667
false
false
5
72e01d4fa2151c9fcfcc3d6677b4b69543c083c6
38,482,906,974,857
ebbb9ffa448d4e67f64ab3baa34ec84caa3712f9
/src/main/java/com/test/controllers/MainController.java
8e204567d09412bc0ec204ce1680eb468b00e6dc
[ "MIT" ]
permissive
Ssstlis/TestProj
https://github.com/Ssstlis/TestProj
85a3d74a410c7ae4226a4b51489c458fccbaa197
6670878a0f408212c3da4e1795f47c533b0aea7c
refs/heads/master
2020-03-19T10:30:38.216000
2018-06-06T19:39:42
2018-06-06T19:39:42
136,377,731
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.test.controllers; import com.test.entyties.*; import com.test.repos.AuthorsRepository; import com.test.repos.BooksAuthorsRepository; import com.test.repos.BooksRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.*; @Controller @RequestMapping(path="/test") public class MainController { @Autowired private BooksRepository booksRepository; @Autowired private AuthorsRepository authorsRepository; @Autowired private BooksAuthorsRepository booksAuthorsRepository; //Create @RequestMapping(value="/add", method = RequestMethod.POST, produces = "application/json", consumes = "application/json") @ResponseBody public StatusResponse addNewBook(@RequestBody RequestBook json) { if (json == null) return new StatusResponse(3, "Unexpected request"); if (json.getTitle() == null) return new StatusResponse(4, "Illegal object"); if (json.getAuthors() == null) return new StatusResponse(2, "No one author was find, no one saved"); try { List<Integer> authorsIDs = new ArrayList<>(5); List<Author> tobase = new ArrayList<>(5); for (Author reqAuthor : json.getAuthors()) { reqAuthor.cleanup(); boolean exist = false; for (Author author : authorsRepository.findAll()) if (author.equals(reqAuthor)) { authorsIDs.add(author.getID()); exist = true; break; } if (!exist) tobase.add(reqAuthor); } for (Author author : authorsRepository.saveAll(tobase)) authorsIDs.add(author.getID()); Integer bookID = booksRepository.save(json.explicit()).getID(); List<Books_has_Authors> books_has_authors = new ArrayList<>(0); for (Integer authorsID : authorsIDs) books_has_authors.add(new Books_has_Authors(bookID, authorsID)); booksAuthorsRepository.saveAll(books_has_authors); return new StatusResponse(1, "Book and authors successfully saved"); } catch (Exception exc) { exc.printStackTrace(System.out); return new StatusResponse(400, "Unexpected DB error"); } } //Read @RequestMapping(value="/books", method = RequestMethod.GET) public @ResponseBody ResponseBooks getAllBooks(boolean authors) { ResponseBooks books = new ResponseBooks(); books.setBooks(RequestBook.explicit(booksRepository.findAll(), authors ? authorsRepository.findAll() : null)); return books; } //Update @RequestMapping(value="/update", method = RequestMethod.POST, produces = "application/json", consumes = "application/json") public @ResponseBody StatusResponse UpdateBook(@RequestBody RequestBook json) { if (json == null) return new StatusResponse(3, "Unexpected request"); if (json.getID() == null || json.getAuthors() == null) return new StatusResponse(4, "Illegal request body"); try { Iterable<Book> books = booksRepository.findAll(); Book find; block: { for (Book book : books) if (book.getID().equals(json.getID())) { find = book; break block; } return new StatusResponse(5, "Can't find record in table"); } Integer saved = booksRepository.save(find.merge(json.explicit())).getID(); Iterable<Author> authors = authorsRepository.findAll(); List<Integer> newAuthorIDs = new ArrayList<>(5); List<Integer> oldAuthorIDs = new ArrayList<>(5); Set<Books_has_Authors> old = find.getBooks_has_authors(); Set<Books_has_Authors> young = new HashSet<>(5); Set<Books_has_Authors> trash = new HashSet<>(5); for (Author author : json.getAuthors()) { if (author.getID() == null) { newAuthorIDs.add(authorsRepository.save(author).getID()); } else { for (Author author1 : authors) if (author1.getID().equals(author.getID())) { oldAuthorIDs.add(authorsRepository.save(author1.merge(author)).getID()); break; } } } for (Books_has_Authors hasAuthors : old) { int i = 0; block: { for (Integer authorid : oldAuthorIDs) { if (hasAuthors.getAuthorsID().equals(authorid)) { break block; } i++; } if (i == old.size()) { trash.add(hasAuthors); } } } booksAuthorsRepository.deleteAll(trash); for(Integer authID : newAuthorIDs) young.add(new Books_has_Authors(saved, authID)); booksAuthorsRepository.saveAll(young); } catch (Exception exc) { exc.printStackTrace(System.out); return new StatusResponse(400, "Unexpected DB error"); } return new StatusResponse(1, "Book and authors successfully saved"); } //Delete @GetMapping(path="/deletebook") public @ResponseBody StatusResponse getAllBooksAuthors(Integer id) { if (id == null || id <= 0) return new StatusResponse(4, "Illegal request body"); try { for (Book book : booksRepository.findAll()) { if (book.getID().equals(id)) { List<Books_has_Authors> trash = new ArrayList<>(5); for (Books_has_Authors books_has_authors : booksAuthorsRepository.findAll()) if (books_has_authors.getBooksID().equals(id)) trash.add(books_has_authors); booksAuthorsRepository.deleteAll(trash); booksRepository.delete(book); return new StatusResponse(1, "Successfully deleted"); } } } catch (Exception exc) { exc.printStackTrace(System.out); return new StatusResponse(400, "Unexpected DB error"); } return new StatusResponse(5, "Can't find record in table"); } }
UTF-8
Java
6,854
java
MainController.java
Java
[]
null
[]
package com.test.controllers; import com.test.entyties.*; import com.test.repos.AuthorsRepository; import com.test.repos.BooksAuthorsRepository; import com.test.repos.BooksRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.*; @Controller @RequestMapping(path="/test") public class MainController { @Autowired private BooksRepository booksRepository; @Autowired private AuthorsRepository authorsRepository; @Autowired private BooksAuthorsRepository booksAuthorsRepository; //Create @RequestMapping(value="/add", method = RequestMethod.POST, produces = "application/json", consumes = "application/json") @ResponseBody public StatusResponse addNewBook(@RequestBody RequestBook json) { if (json == null) return new StatusResponse(3, "Unexpected request"); if (json.getTitle() == null) return new StatusResponse(4, "Illegal object"); if (json.getAuthors() == null) return new StatusResponse(2, "No one author was find, no one saved"); try { List<Integer> authorsIDs = new ArrayList<>(5); List<Author> tobase = new ArrayList<>(5); for (Author reqAuthor : json.getAuthors()) { reqAuthor.cleanup(); boolean exist = false; for (Author author : authorsRepository.findAll()) if (author.equals(reqAuthor)) { authorsIDs.add(author.getID()); exist = true; break; } if (!exist) tobase.add(reqAuthor); } for (Author author : authorsRepository.saveAll(tobase)) authorsIDs.add(author.getID()); Integer bookID = booksRepository.save(json.explicit()).getID(); List<Books_has_Authors> books_has_authors = new ArrayList<>(0); for (Integer authorsID : authorsIDs) books_has_authors.add(new Books_has_Authors(bookID, authorsID)); booksAuthorsRepository.saveAll(books_has_authors); return new StatusResponse(1, "Book and authors successfully saved"); } catch (Exception exc) { exc.printStackTrace(System.out); return new StatusResponse(400, "Unexpected DB error"); } } //Read @RequestMapping(value="/books", method = RequestMethod.GET) public @ResponseBody ResponseBooks getAllBooks(boolean authors) { ResponseBooks books = new ResponseBooks(); books.setBooks(RequestBook.explicit(booksRepository.findAll(), authors ? authorsRepository.findAll() : null)); return books; } //Update @RequestMapping(value="/update", method = RequestMethod.POST, produces = "application/json", consumes = "application/json") public @ResponseBody StatusResponse UpdateBook(@RequestBody RequestBook json) { if (json == null) return new StatusResponse(3, "Unexpected request"); if (json.getID() == null || json.getAuthors() == null) return new StatusResponse(4, "Illegal request body"); try { Iterable<Book> books = booksRepository.findAll(); Book find; block: { for (Book book : books) if (book.getID().equals(json.getID())) { find = book; break block; } return new StatusResponse(5, "Can't find record in table"); } Integer saved = booksRepository.save(find.merge(json.explicit())).getID(); Iterable<Author> authors = authorsRepository.findAll(); List<Integer> newAuthorIDs = new ArrayList<>(5); List<Integer> oldAuthorIDs = new ArrayList<>(5); Set<Books_has_Authors> old = find.getBooks_has_authors(); Set<Books_has_Authors> young = new HashSet<>(5); Set<Books_has_Authors> trash = new HashSet<>(5); for (Author author : json.getAuthors()) { if (author.getID() == null) { newAuthorIDs.add(authorsRepository.save(author).getID()); } else { for (Author author1 : authors) if (author1.getID().equals(author.getID())) { oldAuthorIDs.add(authorsRepository.save(author1.merge(author)).getID()); break; } } } for (Books_has_Authors hasAuthors : old) { int i = 0; block: { for (Integer authorid : oldAuthorIDs) { if (hasAuthors.getAuthorsID().equals(authorid)) { break block; } i++; } if (i == old.size()) { trash.add(hasAuthors); } } } booksAuthorsRepository.deleteAll(trash); for(Integer authID : newAuthorIDs) young.add(new Books_has_Authors(saved, authID)); booksAuthorsRepository.saveAll(young); } catch (Exception exc) { exc.printStackTrace(System.out); return new StatusResponse(400, "Unexpected DB error"); } return new StatusResponse(1, "Book and authors successfully saved"); } //Delete @GetMapping(path="/deletebook") public @ResponseBody StatusResponse getAllBooksAuthors(Integer id) { if (id == null || id <= 0) return new StatusResponse(4, "Illegal request body"); try { for (Book book : booksRepository.findAll()) { if (book.getID().equals(id)) { List<Books_has_Authors> trash = new ArrayList<>(5); for (Books_has_Authors books_has_authors : booksAuthorsRepository.findAll()) if (books_has_authors.getBooksID().equals(id)) trash.add(books_has_authors); booksAuthorsRepository.deleteAll(trash); booksRepository.delete(book); return new StatusResponse(1, "Successfully deleted"); } } } catch (Exception exc) { exc.printStackTrace(System.out); return new StatusResponse(400, "Unexpected DB error"); } return new StatusResponse(5, "Can't find record in table"); } }
6,854
0.548585
0.54377
193
34.512955
27.250729
127
false
false
0
0
0
0
0
0
0.512953
false
false
5
fc292cdc407473d8a96e7c94d47e0045026cab35
20,864,951,138,323
b0c0af7e6da28f7a991bb63fb31a39aae3a27fd9
/app/src/main/java/com/ske/minitrello/views/adapters/CommentAdapter.java
39da1de55e50fa19da0b97b86f83272299357bd8
[]
no_license
chinnonae/SW-spec-mini-trello
https://github.com/chinnonae/SW-spec-mini-trello
22b358e8eacdffa620b96975fc823b0997763cf4
3474ed3469d6e328a6e6ab455e708391df3080ae
refs/heads/master
2021-01-10T13:03:58.047000
2016-04-02T08:51:23
2016-04-02T08:51:23
52,772,382
4
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ske.minitrello.views.adapters; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.ske.minitrello.R; import com.ske.minitrello.models.Comment; import java.util.List; public class CommentAdapter extends RecyclerView.Adapter<CommentAdapter.ViewHolder> { private List<Comment> comments; private CommentItemClickListener listener; public CommentAdapter(List<Comment> comments, CommentItemClickListener listener) { this.comments = comments; this.listener = listener; } public static class ViewHolder extends RecyclerView.ViewHolder { TextView content; TextView createdTime; public ViewHolder(View v) { super(v); content = (TextView)v.findViewById(R.id.comment_content); createdTime = (TextView)v.findViewById(R.id.comment_creation_time); } } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()) .inflate(R.layout.comment_list_item, parent, false); final ViewHolder vh = new ViewHolder(v); v.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { listener.onLongClick(v, vh.getAdapterPosition()); return false; } }); v.setLongClickable(true); return vh; } @Override public void onBindViewHolder(ViewHolder holder, int position) { Comment comment = comments.get(position); holder.content.setText(comment.getContent()); holder.createdTime.setText(comment.getRelativeTime()); } @Override public int getItemCount() { return comments.size(); } }
UTF-8
Java
1,929
java
CommentAdapter.java
Java
[]
null
[]
package com.ske.minitrello.views.adapters; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.ske.minitrello.R; import com.ske.minitrello.models.Comment; import java.util.List; public class CommentAdapter extends RecyclerView.Adapter<CommentAdapter.ViewHolder> { private List<Comment> comments; private CommentItemClickListener listener; public CommentAdapter(List<Comment> comments, CommentItemClickListener listener) { this.comments = comments; this.listener = listener; } public static class ViewHolder extends RecyclerView.ViewHolder { TextView content; TextView createdTime; public ViewHolder(View v) { super(v); content = (TextView)v.findViewById(R.id.comment_content); createdTime = (TextView)v.findViewById(R.id.comment_creation_time); } } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()) .inflate(R.layout.comment_list_item, parent, false); final ViewHolder vh = new ViewHolder(v); v.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { listener.onLongClick(v, vh.getAdapterPosition()); return false; } }); v.setLongClickable(true); return vh; } @Override public void onBindViewHolder(ViewHolder holder, int position) { Comment comment = comments.get(position); holder.content.setText(comment.getContent()); holder.createdTime.setText(comment.getRelativeTime()); } @Override public int getItemCount() { return comments.size(); } }
1,929
0.669777
0.669259
69
26.971014
25.485416
86
false
false
0
0
0
0
0
0
0.507246
false
false
5
aa34ae7e322dfc967456dfd69de1e3b7e30ebba3
5,102,421,206,353
cbe8f798fefe7409552a295362d2cb850d3929c5
/app/src/main/java/arnoabomo/appalbums/pages/pages_accueil/HomePage.java
e32384acdba565da63acfe1d737ef6ab636b9c42
[]
no_license
abomoarno/appAlbums
https://github.com/abomoarno/appAlbums
5481dd82fd209f36f5d881e0ae066e8f31ed8137
baddf141f73fd56a1505c5a04d5996e4e8af9363
refs/heads/master
2020-11-23T20:50:32.436000
2019-12-13T10:34:31
2019-12-13T10:34:31
227,815,636
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package arnoabomo.appalbums.pages.pages_accueil; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import com.facebook.AccessToken; import com.facebook.GraphRequest; import com.facebook.GraphResponse; import com.squareup.picasso.Picasso; import org.json.JSONException; import org.json.JSONObject; import arnoabomo.appalbums.R; import arnoabomo.appalbums.activities.Accueil; import arnoabomo.appalbums.activities.AlbumsActivity; public class HomePage extends Fragment implements View.OnClickListener { private ImageView photo; private TextView name; private Accueil context; private ProgressDialog dialog; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.home_page, container, false); photo = view.findViewById(R.id.photo); name = view.findViewById(R.id.name); context = (Accueil)getActivity(); view.findViewById(R.id.voir_albums).setOnClickListener(this); view.findViewById(R.id.quit).setOnClickListener(this); dialog = new ProgressDialog(context); dialog.setTitle("Chargement"); dialog.setMessage("Chargement des données en cours. Patientez quelques instants"); dialog.setCancelable(false); return view; } private void loadUserProfile(AccessToken newAccessToken) { dialog.show(); GraphRequest request = GraphRequest.newMeRequest(newAccessToken, new GraphRequest.GraphJSONObjectCallback() { @Override public void onCompleted(JSONObject object, GraphResponse response) { try { String first_name = object.getString("first_name"); String last_name = object.getString("last_name"); String id = object.getString("id"); String image_url = "https://graph.facebook.com/"+id+ "/picture?type=normal"; String nom = first_name + " " + last_name; name.setText(nom); Picasso.get().load(image_url).into(photo); context.setHeader(image_url,nom); dialog.dismiss(); } catch (JSONException e) { dialog.dismiss(); e.printStackTrace(); } } }); Bundle parameters = new Bundle(); parameters.putString("fields","first_name,last_name,id"); request.setParameters(parameters); request.executeAsync(); } @Override public void onStart() { super.onStart(); context.setTitre("Accueil"); context.toggleNavigation(true); loadUserProfile(AccessToken.getCurrentAccessToken()); } @Override public void onClick(View view) { if (view.getId() == R.id.voir_albums){ startActivity(new Intent(context, AlbumsActivity.class)); } else { context.quit(); } } }
UTF-8
Java
3,399
java
HomePage.java
Java
[]
null
[]
package arnoabomo.appalbums.pages.pages_accueil; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import com.facebook.AccessToken; import com.facebook.GraphRequest; import com.facebook.GraphResponse; import com.squareup.picasso.Picasso; import org.json.JSONException; import org.json.JSONObject; import arnoabomo.appalbums.R; import arnoabomo.appalbums.activities.Accueil; import arnoabomo.appalbums.activities.AlbumsActivity; public class HomePage extends Fragment implements View.OnClickListener { private ImageView photo; private TextView name; private Accueil context; private ProgressDialog dialog; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.home_page, container, false); photo = view.findViewById(R.id.photo); name = view.findViewById(R.id.name); context = (Accueil)getActivity(); view.findViewById(R.id.voir_albums).setOnClickListener(this); view.findViewById(R.id.quit).setOnClickListener(this); dialog = new ProgressDialog(context); dialog.setTitle("Chargement"); dialog.setMessage("Chargement des données en cours. Patientez quelques instants"); dialog.setCancelable(false); return view; } private void loadUserProfile(AccessToken newAccessToken) { dialog.show(); GraphRequest request = GraphRequest.newMeRequest(newAccessToken, new GraphRequest.GraphJSONObjectCallback() { @Override public void onCompleted(JSONObject object, GraphResponse response) { try { String first_name = object.getString("first_name"); String last_name = object.getString("last_name"); String id = object.getString("id"); String image_url = "https://graph.facebook.com/"+id+ "/picture?type=normal"; String nom = first_name + " " + last_name; name.setText(nom); Picasso.get().load(image_url).into(photo); context.setHeader(image_url,nom); dialog.dismiss(); } catch (JSONException e) { dialog.dismiss(); e.printStackTrace(); } } }); Bundle parameters = new Bundle(); parameters.putString("fields","first_name,last_name,id"); request.setParameters(parameters); request.executeAsync(); } @Override public void onStart() { super.onStart(); context.setTitre("Accueil"); context.toggleNavigation(true); loadUserProfile(AccessToken.getCurrentAccessToken()); } @Override public void onClick(View view) { if (view.getId() == R.id.voir_albums){ startActivity(new Intent(context, AlbumsActivity.class)); } else { context.quit(); } } }
3,399
0.64744
0.64744
103
31.990292
26.377945
132
false
false
0
0
0
0
0
0
0.679612
false
false
5
e1954ee66b076f54321266b7357b060eae8bf47c
15,659,450,825,960
b9e2007f7ca5de37a47d5ad2ea3b4d28386f7303
/d2cmall-main/d2cmall-main-rest/src/main/java/com/d2c/flame/controller/member/PartnerController.java
873233b486fa6566382973e39be51c19ac45bbf4
[]
no_license
bellmit/d2cmall
https://github.com/bellmit/d2cmall
da3711f282f9c6a8d7a6714fc329bd82758bb724
ab9668932c17559b5900f3f24eb06971a10de2d1
refs/heads/master
2022-10-13T17:25:08.005000
2020-06-11T06:08:47
2020-06-11T06:08:47
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.d2c.flame.controller.member; import com.alibaba.dubbo.config.annotation.Reference; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.d2c.common.api.page.PageModel; import com.d2c.common.api.page.PageResult; import com.d2c.common.api.response.ResponseResult; import com.d2c.common.base.exception.BusinessException; import com.d2c.common.base.utils.security.MD5Util; import com.d2c.common.mq.enums.MqEnum; import com.d2c.flame.controller.base.BaseController; import com.d2c.flame.property.ASE; import com.d2c.member.enums.DeviceTypeEnum; import com.d2c.member.model.*; import com.d2c.member.query.MemberSearcher; import com.d2c.member.query.PartnerCounselorSearcher; import com.d2c.member.query.PartnerInviteSearcher; import com.d2c.member.query.PartnerSearcher; import com.d2c.member.service.*; import com.d2c.order.dto.OrderItemDto; import com.d2c.order.enums.TaxRule2StepEnum; import com.d2c.order.model.PartnerCash; import com.d2c.order.model.PartnerCash.PayType; import com.d2c.order.model.PartnerGift; import com.d2c.order.model.PartnerItem; import com.d2c.order.model.Setting; import com.d2c.order.query.OrderSearcher; import com.d2c.order.query.PartnerCashSearcher; import com.d2c.order.query.PartnerGiftSearcher; import com.d2c.order.query.PartnerItemSearcher; import com.d2c.order.service.*; import com.d2c.order.service.tx.PartnerTxService; import com.d2c.order.third.payment.gongmall.client.GongmallClient; import com.d2c.order.third.payment.gongmall.core.GongmallConfig; import com.d2c.product.dto.ProductDto; import com.d2c.product.model.Product; import com.d2c.product.model.ProductPartnerRelation; import com.d2c.product.query.ProductSearcher; import com.d2c.product.search.model.SearcherProduct; import com.d2c.product.search.service.ProductSearcherQueryService; import com.d2c.product.service.ProductPartnerRelationService; import com.d2c.product.service.ProductService; import com.d2c.util.date.DateUtil; import com.d2c.util.string.StringUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.math.BigDecimal; import java.net.URLEncoder; import java.util.*; /** * 无人买手店 * * @author Cai * @version 3.0 */ @RestController @RequestMapping(value = "/v3/api/partner") public class PartnerController extends BaseController { @Autowired private OrderItemService orderItemService; @Autowired private MemberInfoService memberInfoService; @Autowired private PartnerService partnerService; @Autowired private PartnerItemService partnerItemService; @Autowired private PartnerInviteService partnerInviteService; @Autowired private PartnerBillService partnerBillService; @Autowired private PartnerCashService partnerCashService; @Autowired private PartnerGiftService partnerGiftService; @Autowired private PartnerStoreService partnerStoreService; @Autowired private PartnerCounselorService partnerCounselorService; @Autowired private SettingService settingService; @Autowired private ProductService productService; @Reference private ProductSearcherQueryService productSearcherQueryService; @Autowired private ProductPartnerRelationService productPartnerRelationService; @Autowired private GongmallConfig gongmallConfig; @Reference private PartnerTxService partnerTxService; /** * 我的分销信息 TODO * * @return */ @RequestMapping(value = "/mine", method = RequestMethod.GET) public ResponseResult myInfo(String appTerminal) { ResponseResult result = new ResponseResult(); MemberInfo memberInfo = this.getLoginMemberInfo(); Partner partner = partnerService.findByMemberId(memberInfo.getId()); if (partner != null) { if (DeviceTypeEnum.APPIOS.toString().equalsIgnoreCase(appTerminal)) { if (partner.getStatus() < 0) { result.setStatus(-1); result.setData(null); return result; } } result.put("member", memberInfo.toJson()); result.put("partner", partner.toJson()); result.put("applyCashAmount", partner.getApplyAmount()); } else { result.setStatus(-1); result.setData(null); return result; } return result; } /** * 分销商信息 * * @param id * @return */ @RequestMapping(value = "/{id}", method = RequestMethod.GET) public ResponseResult detail(@PathVariable Long id) { ResponseResult result = new ResponseResult(); Partner partner = partnerService.findById(id); if (partner == null) { throw new BusinessException("分销商不存在!"); } result.put("partner", partner.toSimpleJson()); return result; } /** * 我的下级分销 * * @param page * @return */ @RequestMapping(value = "/children", method = RequestMethod.GET) public ResponseResult children(PageModel page) { ResponseResult result = new ResponseResult(); MemberInfo memberInfo = this.getLoginMemberInfo(); if (memberInfo.getPartnerId() == null) { throw new BusinessException("您没有权限!"); } PartnerSearcher searcher = new PartnerSearcher(); searcher.setParentId(memberInfo.getPartnerId()); PageResult<Partner> pager = partnerService.findBySearcher(searcher, page); JSONArray array = new JSONArray(); pager.getList().forEach(partner -> array.add(partner.toJson())); result.putPage("children", pager, array); return result; } /** * 我的下级客户 * * @param page * @return */ @RequestMapping(value = "/customers", method = RequestMethod.GET) public ResponseResult customer(PageModel page) { ResponseResult result = new ResponseResult(); MemberInfo memberInfo = this.getLoginMemberInfo(); if (memberInfo.getPartnerId() == null) { throw new BusinessException("您没有权限!"); } MemberSearcher searcher = new MemberSearcher(); searcher.setParentId(memberInfo.getPartnerId()); PageResult<MemberInfo> pager = memberInfoService.findBySearch(searcher, page); JSONArray array = new JSONArray(); pager.getList().forEach(item -> array.add(item.toJson())); result.putPage("customers", pager, array); return result; } /** * 删除团队成员 * * @param childId * @return */ @RequestMapping(value = "/separate", method = RequestMethod.POST) public ResponseResult separate(Long childId) { ResponseResult result = new ResponseResult(); MemberInfo memberInfo = this.getLoginMemberInfo(); Partner partner = partnerService.findById(memberInfo.getPartnerId()); if (partner == null || partner.getLevel() == 2) { throw new BusinessException("您没有权限!"); } partnerService.doSeparate(partner.getId(), childId, memberInfo.getLoginCode()); return result; } /** * 我邀请的成员列表 * * @param page * @return */ @RequestMapping(value = "/invite/list", method = RequestMethod.GET) public ResponseResult inviteList(PageModel page) { ResponseResult result = new ResponseResult(); MemberInfo memberInfo = this.getLoginMemberInfo(); if (memberInfo.getPartnerId() == null) { throw new BusinessException("您没有权限!"); } PartnerInviteSearcher searcher = new PartnerInviteSearcher(); searcher.setFromMemberId(memberInfo.getId()); PageResult<PartnerInvite> pager = partnerInviteService.findBySearcher(searcher, page); JSONArray array = new JSONArray(); pager.getList().forEach(item -> array.add(item.toJson())); result.putPage("invites", pager, array); return result; } /** * 更新分销商 * * @param partner * @return */ @RequestMapping(value = "/update", method = RequestMethod.POST) public ResponseResult updatePartner(Partner partner) { ResponseResult result = new ResponseResult(); MemberInfo memberInfo = this.getLoginMemberInfo(); Partner old = partnerService.findById(partner.getId()); if (old == null || !old.getMemberId().equals(memberInfo.getId())) { throw new BusinessException("分销商数据不正确!"); } partner.setMemberId(old.getMemberId()); partner.setLoginCode(old.getLoginCode()); partner.setTotalAmount(null); partner.setTotalOrderAmount(null); partner.setCashAmount(null); partner.setApplyAmount(null); partner.setBalanceAmount(null); partner.setLastModifyMan(memberInfo.getLoginCode()); if (partner.getAlipay() != null && partner.getAlipay().contains("*")) { partner.setAlipay(null); } if (partner.getBankSn() != null && partner.getBankSn().contains("*")) { partner.setBankSn(null); } if (partner.getIdentityCard() != null && partner.getIdentityCard().contains("*")) { partner.setIdentityCard(null); } if (partner.getRealName() != null && partner.getRealName().contains("*")) { partner.setRealName(null); } if (partner.getLicenseNum() != null && partner.getLicenseNum().contains("*")) { partner.setLicenseNum(null); } partnerService.update(partner); partner = partnerService.findById(partner.getId()); result.put("partner", partner.toJson()); return result; } /** * 返利单列表 * * @param searcher * @param page * @return */ @RequestMapping(value = "/bill", method = RequestMethod.GET) public ResponseResult partnerBill(OrderSearcher searcher, Integer index, PageModel page) { ResponseResult result = new ResponseResult(); MemberInfo memberInfo = this.getLoginMemberInfo(); if (memberInfo.getPartnerId() == null) { throw new BusinessException("您没有权限!"); } if (index != null) { searcher.handleIndexForPartner(index); } page.setPageSize(10); if (searcher.getPartnerId() == null && searcher.getParentId() == null && searcher.getSuperId() == null && searcher.getMasterId() == null) { searcher.setPartnerId(memberInfo.getPartnerId()); } PageResult<OrderItemDto> pager = orderItemService.findPartnerOrder(searcher, page); JSONArray array = new JSONArray(); pager.getList().forEach(pb -> array.add(pb.toJson())); result.putPage("partnerBill", pager, array); Setting setting = settingService.findByCode(Setting.ORDERAFTERCLOSE); result.put("expireDay", Setting.defaultValue(setting, new Integer(7))); return result; } /** * 提现单列表 * * @param searcher * @param page * @return */ @RequestMapping(value = "/cash", method = RequestMethod.GET) public ResponseResult partnerCash(PartnerCashSearcher searcher, PageModel page) { ResponseResult result = new ResponseResult(); MemberInfo memberInfo = this.getLoginMemberInfo(); if (memberInfo.getPartnerId() == null) { throw new BusinessException("您没有权限!"); } searcher.setPartnerId(memberInfo.getPartnerId()); searcher.setWaitConfirm(1); PageResult<PartnerCash> pager = partnerCashService.findBySearcher(searcher, page); JSONArray array = new JSONArray(); pager.getList().forEach(pc -> array.add(pc.toJson())); result.putPage("partnerCash", pager, array); return result; } /** * 流水明细列表 * * @param searcher * @param page * @return */ @RequestMapping(value = "/log", method = RequestMethod.GET) public ResponseResult partnerItem(PartnerItemSearcher searcher, PageModel page) { ResponseResult result = new ResponseResult(); MemberInfo memberInfo = this.getLoginMemberInfo(); if (memberInfo.getPartnerId() == null) { throw new BusinessException("您没有权限!"); } searcher.setPartnerId(memberInfo.getPartnerId()); PageResult<PartnerItem> pager = partnerItemService.findBySearcher(searcher, page); JSONArray array = new JSONArray(); pager.getList().forEach(log -> array.add(log.toJson())); result.putPage("partnerLog", pager, array); return result; } /** * 最小提现金额 * * @return */ @RequestMapping(value = "/min/withdraw", method = RequestMethod.GET) public ResponseResult minWithdrawCash() { ResponseResult result = new ResponseResult(); BigDecimal minWithdraw = new BigDecimal(0); result.put("minWithdraw", minWithdraw); return result; } /** * 本月已提现金额 * * @param taxType * @return */ @RequestMapping(value = "/month/withdraw", method = RequestMethod.GET) public ResponseResult monthWithdrawCash(Integer taxType) { ResponseResult result = new ResponseResult(); MemberInfo memberInfo = this.getLoginMemberInfo(); Partner partner = partnerService.findById(memberInfo.getPartnerId()); if (partner == null) { throw new BusinessException("您没有权限!"); } Date today = new Date(); Date sMonthDate = DateUtil.getStartOfMonth(today); Date eMonthDate = DateUtil.getEndOfMonth(today); BigDecimal monthWithdraw = partnerCashService.findWithCashByDate(partner.getId(), sMonthDate, eMonthDate, taxType); result.put("monthWithdraw", monthWithdraw); PartnerCash lastOne = partnerCashService.findLastSuccessOne(partner.getId(), sMonthDate, eMonthDate, taxType); result.put("taxAmount", lastOne == null ? new BigDecimal(0) : lastOne.getTotalTaxAmount()); return result; } /** * 个人信息确认,工猫电签 * * @param realName * @param identityCard * @param region * @param bank * @param bankType * @param bankSn * @return * @throws Exception */ @RequestMapping(value = "/gongmall/contract", method = RequestMethod.POST) public ResponseResult confirmContract(String realName, String identityCard, String region, String bank, String bankType, String bankSn) throws Exception { ResponseResult result = new ResponseResult(); MemberInfo memberInfo = this.getLoginMemberInfo(); Partner partner = partnerService.findById(memberInfo.getPartnerId()); if (partner == null) { throw new BusinessException("您没有权限!"); } if (identityCard != null && identityCard.contains("*")) { identityCard = partner.getIdentityCard(); } if (realName != null && realName.contains("*")) { realName = partner.getRealName(); } if (bankSn != null && bankSn.contains("*")) { bankSn = partner.getBankSn(); } partner.setRegion(region); partner.setBank(bank); partner.setBankType(bankType); partner.setIdentityCard(identityCard); partner.setRealName(realName); partner.setBankSn(bankSn); partnerService.update(partner); if (partner.getContract() == 0) { Partner contracted = partnerService.findContract(identityCard); if (contracted != null) { throw new BusinessException("该身份证号已在工猫电签,请勿重复申请!"); } String url = this.getContractUrl(gongmallConfig, partner.getRealName(), partner.getLoginCode(), "1", partner.getIdentityCard(), partner.getBankSn(), partner.getBankType(), partner.getId().toString(), ""); result.put("url", URLEncoder.encode(url, "UTF-8")); } return result; } /** * 电签功能对接 * * @param config * @param name * @param mobile * @param certificateType * @param idNumber * @param bankNum * @param bankName * @param workNumber * @param extraParam */ private String getContractUrl(GongmallConfig config, String name, String mobile, String certificateType, String idNumber, String bankNum, String bankName, String workNumber, String extraParam) { TreeMap<String, String> map = new TreeMap<>(); map.put("name", name); map.put("mobile", mobile); map.put("certificateType", certificateType); map.put("idNumber", idNumber); map.put("bankNum", bankNum); map.put("bankName", bankName); map.put("workNumber", workNumber); map.put("extraParam", extraParam); StringBuilder sb = new StringBuilder(); Set<String> keys = map.keySet(); for (String key : keys) { if (StringUtil.isNotBlank(map.get(key))) { sb.append(key).append("=").append(map.get(key)).append("&"); } } String dataTemp = sb.toString(); String data = ASE.aesEncrypt(dataTemp.substring(0, dataTemp.length() - 1), MD5Util.encodeMD5Hex(config.getAppkey() + config.getAppSecret()).toUpperCase()); return config.getContractUrl() + "&data=" + data; } /** * 更新个人银行卡信息 * * @param realName * @param identityCard * @param region * @param bank * @param bankType * @param bankSn * @return */ @RequestMapping(value = "/gongmall/update", method = RequestMethod.POST) public ResponseResult confirmUpdate(String realName, String identityCard, String region, String bank, String bankType, String bankSn) { ResponseResult result = new ResponseResult(); MemberInfo memberInfo = this.getLoginMemberInfo(); Partner partner = partnerService.findById(memberInfo.getPartnerId()); if (partner == null) { throw new BusinessException("您没有权限!"); } if (identityCard != null && identityCard.contains("*")) { identityCard = partner.getIdentityCard(); } if (realName != null && realName.contains("*")) { realName = partner.getRealName(); } if (bankSn != null && bankSn.contains("*")) { bankSn = partner.getBankSn(); } JSONObject json = GongmallClient.getInstance().doBankAccount(gongmallConfig, partner.getRealName(), partner.getLoginCode(), partner.getIdentityCard(), partner.getBankType(), partner.getBankSn(), bankType, bankSn); if (!json.getString("success").equals("true")) { throw new BusinessException(json.getString("errorMsg")); } partner.setRegion(region); partner.setBank(bank); partner.setBankType(bankType); partner.setIdentityCard(identityCard); partner.setRealName(realName); partner.setBankSn(bankSn); partnerService.update(partner); return result; } /** * 提现申请 * * @param applyAmount 提现金额 * @param applyAccount 提现账号 * @param payType 提现方式 * @return */ @RequestMapping(value = "/withdraw/cash", method = RequestMethod.POST) public ResponseResult withdrawCash(BigDecimal applyAmount, String applyAccount, String payType) { ResponseResult result = new ResponseResult(); MemberInfo memberInfo = this.getLoginMemberInfo(); Partner partner = partnerService.findById(memberInfo.getPartnerId()); if (partner == null) { throw new BusinessException("您没有权限!"); } if (partner.getStatus() < 0) { throw new BusinessException("用户状态异常!"); } if (partner.getWithdraw() == 0) { throw new BusinessException("该账户提现功能被关闭!"); } if (payType != null && !PayType.contain(payType)) { throw new BusinessException("提现方式异常!"); } if (applyAmount.compareTo(new BigDecimal(0)) < 0) { throw new BusinessException("提现金额异常!"); } if (applyAmount.compareTo( partner.getTotalAmount().subtract(partner.getCashAmount()).subtract(partner.getApplyAmount())) > 0) { throw new BusinessException("超出可提现金额!"); } PartnerCash oldActive = partnerCashService.findActiveByMobile(partner.getLoginCode()); if (oldActive != null && !payType.equals(PayType.wallet.name()) && !oldActive.getPayType().equals(PayType.wallet.name())) { throw new BusinessException("您有一笔正在处理的提现单,请处理完后再申请!"); } PartnerCash partnerCash = new PartnerCash(partner, payType); partnerCash.setApplyAccount(applyAccount); partnerCash.setApplyAmount(applyAmount); Integer taxType = payType.equals(PayType.wallet.name()) ? 1 : 0; partnerCash.setTaxType(taxType); Date today = new Date(); Date sMonthDate = DateUtil.getStartOfMonth(today); Date eMonthDate = DateUtil.getEndOfMonth(today); BigDecimal monthWithdraw = partnerCashService.findWithCashByDate(partner.getId(), sMonthDate, eMonthDate, taxType); PartnerCash lastOne = partnerCashService.findLastSuccessOne(partner.getId(), sMonthDate, eMonthDate, taxType); BigDecimal taxAmount = new BigDecimal(0); if (taxType == 0) { int limit = TaxRule2StepEnum.STEP1.getOpenEnd(); if (monthWithdraw.compareTo(new BigDecimal(0)) > 0 && monthWithdraw.compareTo(new BigDecimal(limit)) < 0) { if ((monthWithdraw.add(applyAmount)).compareTo(new BigDecimal(limit)) >= 0) { throw new BusinessException("您本月最多可提现金额为" + limit + "元!"); } } taxAmount = TaxRule2StepEnum.calculateTax(monthWithdraw.add(applyAmount)); } partnerCash.setTotalTaxAmount(taxAmount); taxAmount = taxAmount.subtract(lastOne == null ? new BigDecimal(0) : lastOne.getTotalTaxAmount()); partnerCash.setApplyTaxAmount(applyAmount.subtract(taxAmount)); partnerCash = partnerTxService.doApplyCash(partnerCash); if (partnerCash.getPayType().equals(PayType.wallet.name())) { Map<String, Object> mq = new HashMap<>(); mq.put("id", partnerCash.getId()); mq.put("sn", partnerCash.getSn()); MqEnum.PARTNER_CASH.send(mq, 3L); } return result; } /** * 根据类型分组<br/> * <p> * 数据结构(类型,总金额)<br/> * * @param partnerId * @return */ @RequestMapping(value = "/summary", method = RequestMethod.GET) public ResponseResult summaryItem(Long partnerId) { ResponseResult result = new ResponseResult(); if (partnerId == null) { MemberInfo memberInfo = this.getLoginMemberInfo(); if (memberInfo.getPartnerId() == null) { throw new BusinessException("您没有权限!"); } partnerId = memberInfo.getPartnerId(); } Partner partner = partnerService.findById(partnerId); if (partner == null) { throw new BusinessException("买手数据不存在!"); } result.put("partner", partner.toJson()); List<Map<String, Object>> incomeData = partnerItemService.findSummaryByType(partner.getId()); result.put("incomeData", incomeData); return result; } /** * 根据状态分组<br/> * <p> * 直接订单(数量,返利金额,实付金额)<br/> * 团队订单(数量,返利金额,实付金额)<br/> * 间接团队订单(数量,返利金额,实付金额)<br/> * AM订单(数量,返利金额,实付金额)<br/> * * @return */ @RequestMapping(value = "/bill/summary", method = RequestMethod.GET) public ResponseResult summaryBill() { ResponseResult result = new ResponseResult(); MemberInfo memberInfo = this.getLoginMemberInfo(); Partner partner = partnerService.findById(memberInfo.getPartnerId()); if (partner == null) { throw new BusinessException("您没有权限!"); } if (partner.getLevel() <= 0) { List<Map<String, Object>> masterData = partnerBillService.findBillSummary(partner.getId(), "master_id", "master_ratio"); result.put("masterData", masterData); } if (partner.getLevel() <= 1) { List<Map<String, Object>> superData = partnerBillService.findBillSummary(partner.getId(), "super_id", "super_ratio"); result.put("superData", superData); List<Map<String, Object>> parentData = partnerBillService.findBillSummary(partner.getId(), "parent_id", "parent_ratio"); result.put("parentData", parentData); } if (partner.getLevel() <= 2) { List<Map<String, Object>> partnerData = partnerBillService.findBillSummary(partner.getId(), "partner_id", "partner_ratio"); result.put("partnerData", partnerData); } return result; } /** * 根据等级分组<br/> * <p> * 当买手/DM进入数据中心时,是parent_id=DM 的买手/DM 人数<br/> * 当AM进入数据中心时,是master_id=AM 的买手/DM 人数<br/> * * @param partnerId * @return */ @RequestMapping(value = "/children/summary", method = RequestMethod.GET) public ResponseResult summaryChildren(Long partnerId) { ResponseResult result = new ResponseResult(); if (partnerId == null) { MemberInfo memberInfo = this.getLoginMemberInfo(); if (memberInfo.getPartnerId() == null) { throw new BusinessException("您没有权限!"); } partnerId = memberInfo.getPartnerId(); } Partner partner = partnerService.findById(partnerId); if (partner == null) { throw new BusinessException("您没有权限!"); } Date now = new Date(); if (partner.getLevel() == 0) { List<Map<String, Object>> amData = partnerService.countChildrenGroup(partner.getId(), "master_id"); result.put("amData", amData); List<Map<String, Object>> todayData = partnerService.countChildrenToday(partner.getId(), "master_id", DateUtil.getStartOfDay(now), DateUtil.getEndOfDay(now)); result.put("todayData", todayData); } else if (partner.getLevel() == 1) { List<Map<String, Object>> dmData = partnerService.countChildrenGroup(partner.getId(), "parent_id"); result.put("dmData", dmData); List<Map<String, Object>> todayData = partnerService.countChildrenToday(partner.getId(), "parent_id", DateUtil.getStartOfDay(now), DateUtil.getEndOfDay(now)); result.put("todayData", todayData); } else if (partner.getLevel() == 2) { List<Map<String, Object>> buyerData = partnerService.countChildrenGroup(partner.getId(), "parent_id"); result.put("buyerData", buyerData); List<Map<String, Object>> todayData = partnerService.countChildrenToday(partner.getId(), "parent_id", DateUtil.getStartOfDay(now), DateUtil.getEndOfDay(now)); result.put("todayData", todayData); } return result; } /** * 我的店铺 * * @return */ @RequestMapping(value = "/store", method = RequestMethod.GET) public ResponseResult store(PageModel page, Long memberId, Long partnerId) { ResponseResult result = new ResponseResult(); PartnerStore partnerStore = null; if (memberId == null && partnerId != null) { partnerStore = partnerStoreService.findByPartnerId(partnerId); } else if (memberId != null && partnerId == null) { partnerStore = partnerStoreService.findByMemberId(memberId); } else if (memberId == null && partnerId == null) { MemberInfo memberInfo = this.getLoginMemberInfo(); partnerStore = partnerStoreService.findByMemberId(memberInfo.getId()); } if (partnerStore == null) { throw new BusinessException("您还未开通小店!"); } result.put("partnerStore", partnerStore.toJson()); return result; } /** * 更新店铺 * * @param partnerStore * @return */ @RequestMapping(value = "/update/store", method = RequestMethod.POST) public ResponseResult updateStore(PartnerStore partnerStore) { ResponseResult result = new ResponseResult(); MemberInfo memberInfo = this.getLoginMemberInfo(); PartnerStore old = partnerStoreService.findByMemberId(memberInfo.getId()); if (old == null) { throw new BusinessException("您还未开通小店!"); } if (partnerStore.getId() == null || !old.getId().equals(partnerStore.getId())) { throw new BusinessException("不是您本人的小店!"); } partnerStore.setMemberId(memberInfo.getId()); partnerStore.setPartnerId(memberInfo.getPartnerId()); partnerStoreService.update(partnerStore); return result; } /** * 是否选品 * * @param productId * @return */ @RequestMapping(value = "/select/product", method = RequestMethod.GET) public ResponseResult selected(Long productId) { ResponseResult result = new ResponseResult(); MemberInfo memberInfo = this.getLoginMemberInfo(); PartnerStore partnerStore = partnerStoreService.findByMemberId(memberInfo.getId()); if (partnerStore == null) { result.put("selected", 0); return result; } ProductPartnerRelation productPartnerRelation = productPartnerRelationService.findOne(partnerStore.getId(), productId); if (productPartnerRelation == null) { result.put("selected", 0); return result; } result.put("selected", 1); return result; } /** * 店铺选品 * * @param productId * @return */ @RequestMapping(value = "/select/product", method = RequestMethod.POST) public ResponseResult selectProduct(Long productId) { ResponseResult result = new ResponseResult(); MemberInfo memberInfo = this.getLoginMemberInfo(); PartnerStore partnerStore = partnerStoreService.findByMemberId(memberInfo.getId()); if (partnerStore == null) { throw new BusinessException("您还未开通小店!"); } productPartnerRelationService.insert(partnerStore.getId(), productId); return result; } /** * 店铺取消选品 * * @param productId * @return */ @RequestMapping(value = "/cancel/product", method = RequestMethod.POST) public ResponseResult cancelProduct(Long productId) { ResponseResult result = new ResponseResult(); MemberInfo memberInfo = this.getLoginMemberInfo(); PartnerStore partnerStore = partnerStoreService.findByMemberId(memberInfo.getId()); if (partnerStore == null) { throw new BusinessException("您还未开通小店!"); } productPartnerRelationService.deleteOne(partnerStore.getId(), productId); return result; } /** * 店铺商品列表 * * @param page * @return */ @RequestMapping(value = "/product/list", method = RequestMethod.GET) public ResponseResult productList(PageModel page, Long memberId, Long partnerId) { ResponseResult result = new ResponseResult(); PartnerStore partnerStore = null; if (memberId == null && partnerId != null) { partnerStore = partnerStoreService.findByPartnerId(partnerId); } else if (memberId != null && partnerId == null) { partnerStore = partnerStoreService.findByMemberId(memberId); } else if (memberId == null && partnerId == null) { MemberInfo memberInfo = this.getLoginMemberInfo(); partnerStore = partnerStoreService.findByMemberId(memberInfo.getId()); } if (partnerStore == null) { throw new BusinessException("您还未开通小店!"); } PageResult<Product> productPager = productPartnerRelationService.findProductByStoreId(partnerStore.getId(), page); List<String> productIds = new ArrayList<>(); productPager.getList().forEach(product -> productIds.add(product.getId().toString())); List<SearcherProduct> productList = productSearcherQueryService.findByIds(productIds, 1); JSONArray productArray = new JSONArray(); productList.forEach(product -> productArray.add(product.toJson())); result.putPage("products", productPager, productArray); // 全局返利系数 Setting ratio = settingService.findByCode(Setting.REBATERATIO); result.put("ratio", Setting.defaultValue(ratio, new Integer(1))); return result; } /** * 运营顾问 * * @param id * @return */ @RequestMapping(value = "/counselor/{id}", method = RequestMethod.GET) public ResponseResult counselor(@PathVariable Long id) { ResponseResult result = new ResponseResult(); PartnerCounselor partnerCounselor = partnerCounselorService.findById(id); if (partnerCounselor == null) { throw new BusinessException("运营顾问不存在!"); } result.put("partnerCounselor", partnerCounselor.toJson()); return result; } /** * 运营顾问列表 * * @param searcher * @return */ @RequestMapping(value = "/counselor/list", method = RequestMethod.GET) public ResponseResult counselorList(PartnerCounselorSearcher searcher) { ResponseResult result = new ResponseResult(); searcher.setStatus(1); PageResult<PartnerCounselor> pager = partnerCounselorService.findBySearcher(new PageModel(1, 10), searcher); JSONArray array = new JSONArray(); pager.getList().forEach(item -> array.add(item.toJson())); result.put("counselors", array); return result; } /** * 选择运营顾问 * * @param counselorId * @return */ @RequestMapping(value = "/select/counselor", method = RequestMethod.POST) public ResponseResult selectCounselor(Long counselorId) { ResponseResult result = new ResponseResult(); MemberInfo memberInfo = this.getLoginMemberInfo(); if (memberInfo.getPartnerId() == null) { throw new BusinessException("您没有权限!"); } PartnerCounselor partnerCounselor = partnerCounselorService.findById(counselorId); if (partnerCounselor == null) { throw new BusinessException("运营顾问不存在!"); } partnerService.doBindCounselor(memberInfo.getPartnerId(), counselorId, memberInfo.getLoginCode()); // couponDefGroupService.doClaimedCoupon(157L, memberInfo.getId(), // memberInfo.getLoginCode(), // memberInfo.getLoginCode(), CouponSourceEnum.APP.name()); result.put("partnerCounselor", partnerCounselor); return result; } /** * 礼包商品列表 * * @param page * @return */ @RequestMapping(value = "/gift/list", method = RequestMethod.GET) public ResponseResult giftList(PageModel page) { ResponseResult result = new ResponseResult(); ProductSearcher searcher = new ProductSearcher(); searcher.setStatus(-1); searcher.setMark(1); PageResult<ProductDto> pager = productService.findBySearch(searcher, page); JSONArray array = new JSONArray(); pager.getList().forEach(item -> array.add(item.toJson(null))); result.putPage("products", pager, array); return result; } /** * 我的礼包列表 * * @param page * @return */ @RequestMapping(value = "/package/list", method = RequestMethod.GET) public ResponseResult packageList(PageModel page) { ResponseResult result = new ResponseResult(); MemberInfo memberInfo = this.getLoginMemberInfo(); if (memberInfo.getPartnerId() == null) { throw new BusinessException("您没有权限!"); } Partner partner = partnerService.findById(memberInfo.getPartnerId()); if (partner == null) { throw new BusinessException("分销商不存在!"); } PartnerGiftSearcher searcher = new PartnerGiftSearcher(); if (partner.getLevel() == 2) { searcher.setPartnerId(partner.getId()); } else if (partner.getLevel() == 1) { searcher.setParentId(partner.getId()); } else if (partner.getLevel() == 0) { searcher.setMasterId(partner.getId()); } PageResult<PartnerGift> pager = partnerGiftService.findBySearcher(searcher, page); JSONArray array = new JSONArray(); pager.getList().forEach(item -> array.add(item.toJson(partner.getId()))); result.putPage("gifts", pager, array); return result; } }
UTF-8
Java
38,492
java
PartnerController.java
Java
[ { "context": "r;\nimport java.util.*;\n\n/**\n * 无人买手店\n *\n * @author Cai\n * @version 3.0\n */\n@RestController\n@RequestMappi", "end": 2435, "score": 0.9982250928878784, "start": 2432, "tag": "NAME", "value": "Cai" }, { "context": "tyCard(identityCard);\n partner.setRealName(realName);\n partner.setBankSn(bankSn);\n part", "end": 15598, "score": 0.9981064796447754, "start": 15590, "tag": "NAME", "value": "realName" }, { "context": "ng> map = new TreeMap<>();\n map.put(\"name\", name);\n map.put(\"mobile\", mobile);\n map.", "end": 16837, "score": 0.5207273960113525, "start": 16833, "tag": "NAME", "value": "name" }, { "context": "tyCard(identityCard);\n partner.setRealName(realName);\n partner.setBankSn(bankSn);\n ", "end": 19347, "score": 0.5027154088020325, "start": 19343, "tag": "NAME", "value": "real" } ]
null
[]
package com.d2c.flame.controller.member; import com.alibaba.dubbo.config.annotation.Reference; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.d2c.common.api.page.PageModel; import com.d2c.common.api.page.PageResult; import com.d2c.common.api.response.ResponseResult; import com.d2c.common.base.exception.BusinessException; import com.d2c.common.base.utils.security.MD5Util; import com.d2c.common.mq.enums.MqEnum; import com.d2c.flame.controller.base.BaseController; import com.d2c.flame.property.ASE; import com.d2c.member.enums.DeviceTypeEnum; import com.d2c.member.model.*; import com.d2c.member.query.MemberSearcher; import com.d2c.member.query.PartnerCounselorSearcher; import com.d2c.member.query.PartnerInviteSearcher; import com.d2c.member.query.PartnerSearcher; import com.d2c.member.service.*; import com.d2c.order.dto.OrderItemDto; import com.d2c.order.enums.TaxRule2StepEnum; import com.d2c.order.model.PartnerCash; import com.d2c.order.model.PartnerCash.PayType; import com.d2c.order.model.PartnerGift; import com.d2c.order.model.PartnerItem; import com.d2c.order.model.Setting; import com.d2c.order.query.OrderSearcher; import com.d2c.order.query.PartnerCashSearcher; import com.d2c.order.query.PartnerGiftSearcher; import com.d2c.order.query.PartnerItemSearcher; import com.d2c.order.service.*; import com.d2c.order.service.tx.PartnerTxService; import com.d2c.order.third.payment.gongmall.client.GongmallClient; import com.d2c.order.third.payment.gongmall.core.GongmallConfig; import com.d2c.product.dto.ProductDto; import com.d2c.product.model.Product; import com.d2c.product.model.ProductPartnerRelation; import com.d2c.product.query.ProductSearcher; import com.d2c.product.search.model.SearcherProduct; import com.d2c.product.search.service.ProductSearcherQueryService; import com.d2c.product.service.ProductPartnerRelationService; import com.d2c.product.service.ProductService; import com.d2c.util.date.DateUtil; import com.d2c.util.string.StringUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.math.BigDecimal; import java.net.URLEncoder; import java.util.*; /** * 无人买手店 * * @author Cai * @version 3.0 */ @RestController @RequestMapping(value = "/v3/api/partner") public class PartnerController extends BaseController { @Autowired private OrderItemService orderItemService; @Autowired private MemberInfoService memberInfoService; @Autowired private PartnerService partnerService; @Autowired private PartnerItemService partnerItemService; @Autowired private PartnerInviteService partnerInviteService; @Autowired private PartnerBillService partnerBillService; @Autowired private PartnerCashService partnerCashService; @Autowired private PartnerGiftService partnerGiftService; @Autowired private PartnerStoreService partnerStoreService; @Autowired private PartnerCounselorService partnerCounselorService; @Autowired private SettingService settingService; @Autowired private ProductService productService; @Reference private ProductSearcherQueryService productSearcherQueryService; @Autowired private ProductPartnerRelationService productPartnerRelationService; @Autowired private GongmallConfig gongmallConfig; @Reference private PartnerTxService partnerTxService; /** * 我的分销信息 TODO * * @return */ @RequestMapping(value = "/mine", method = RequestMethod.GET) public ResponseResult myInfo(String appTerminal) { ResponseResult result = new ResponseResult(); MemberInfo memberInfo = this.getLoginMemberInfo(); Partner partner = partnerService.findByMemberId(memberInfo.getId()); if (partner != null) { if (DeviceTypeEnum.APPIOS.toString().equalsIgnoreCase(appTerminal)) { if (partner.getStatus() < 0) { result.setStatus(-1); result.setData(null); return result; } } result.put("member", memberInfo.toJson()); result.put("partner", partner.toJson()); result.put("applyCashAmount", partner.getApplyAmount()); } else { result.setStatus(-1); result.setData(null); return result; } return result; } /** * 分销商信息 * * @param id * @return */ @RequestMapping(value = "/{id}", method = RequestMethod.GET) public ResponseResult detail(@PathVariable Long id) { ResponseResult result = new ResponseResult(); Partner partner = partnerService.findById(id); if (partner == null) { throw new BusinessException("分销商不存在!"); } result.put("partner", partner.toSimpleJson()); return result; } /** * 我的下级分销 * * @param page * @return */ @RequestMapping(value = "/children", method = RequestMethod.GET) public ResponseResult children(PageModel page) { ResponseResult result = new ResponseResult(); MemberInfo memberInfo = this.getLoginMemberInfo(); if (memberInfo.getPartnerId() == null) { throw new BusinessException("您没有权限!"); } PartnerSearcher searcher = new PartnerSearcher(); searcher.setParentId(memberInfo.getPartnerId()); PageResult<Partner> pager = partnerService.findBySearcher(searcher, page); JSONArray array = new JSONArray(); pager.getList().forEach(partner -> array.add(partner.toJson())); result.putPage("children", pager, array); return result; } /** * 我的下级客户 * * @param page * @return */ @RequestMapping(value = "/customers", method = RequestMethod.GET) public ResponseResult customer(PageModel page) { ResponseResult result = new ResponseResult(); MemberInfo memberInfo = this.getLoginMemberInfo(); if (memberInfo.getPartnerId() == null) { throw new BusinessException("您没有权限!"); } MemberSearcher searcher = new MemberSearcher(); searcher.setParentId(memberInfo.getPartnerId()); PageResult<MemberInfo> pager = memberInfoService.findBySearch(searcher, page); JSONArray array = new JSONArray(); pager.getList().forEach(item -> array.add(item.toJson())); result.putPage("customers", pager, array); return result; } /** * 删除团队成员 * * @param childId * @return */ @RequestMapping(value = "/separate", method = RequestMethod.POST) public ResponseResult separate(Long childId) { ResponseResult result = new ResponseResult(); MemberInfo memberInfo = this.getLoginMemberInfo(); Partner partner = partnerService.findById(memberInfo.getPartnerId()); if (partner == null || partner.getLevel() == 2) { throw new BusinessException("您没有权限!"); } partnerService.doSeparate(partner.getId(), childId, memberInfo.getLoginCode()); return result; } /** * 我邀请的成员列表 * * @param page * @return */ @RequestMapping(value = "/invite/list", method = RequestMethod.GET) public ResponseResult inviteList(PageModel page) { ResponseResult result = new ResponseResult(); MemberInfo memberInfo = this.getLoginMemberInfo(); if (memberInfo.getPartnerId() == null) { throw new BusinessException("您没有权限!"); } PartnerInviteSearcher searcher = new PartnerInviteSearcher(); searcher.setFromMemberId(memberInfo.getId()); PageResult<PartnerInvite> pager = partnerInviteService.findBySearcher(searcher, page); JSONArray array = new JSONArray(); pager.getList().forEach(item -> array.add(item.toJson())); result.putPage("invites", pager, array); return result; } /** * 更新分销商 * * @param partner * @return */ @RequestMapping(value = "/update", method = RequestMethod.POST) public ResponseResult updatePartner(Partner partner) { ResponseResult result = new ResponseResult(); MemberInfo memberInfo = this.getLoginMemberInfo(); Partner old = partnerService.findById(partner.getId()); if (old == null || !old.getMemberId().equals(memberInfo.getId())) { throw new BusinessException("分销商数据不正确!"); } partner.setMemberId(old.getMemberId()); partner.setLoginCode(old.getLoginCode()); partner.setTotalAmount(null); partner.setTotalOrderAmount(null); partner.setCashAmount(null); partner.setApplyAmount(null); partner.setBalanceAmount(null); partner.setLastModifyMan(memberInfo.getLoginCode()); if (partner.getAlipay() != null && partner.getAlipay().contains("*")) { partner.setAlipay(null); } if (partner.getBankSn() != null && partner.getBankSn().contains("*")) { partner.setBankSn(null); } if (partner.getIdentityCard() != null && partner.getIdentityCard().contains("*")) { partner.setIdentityCard(null); } if (partner.getRealName() != null && partner.getRealName().contains("*")) { partner.setRealName(null); } if (partner.getLicenseNum() != null && partner.getLicenseNum().contains("*")) { partner.setLicenseNum(null); } partnerService.update(partner); partner = partnerService.findById(partner.getId()); result.put("partner", partner.toJson()); return result; } /** * 返利单列表 * * @param searcher * @param page * @return */ @RequestMapping(value = "/bill", method = RequestMethod.GET) public ResponseResult partnerBill(OrderSearcher searcher, Integer index, PageModel page) { ResponseResult result = new ResponseResult(); MemberInfo memberInfo = this.getLoginMemberInfo(); if (memberInfo.getPartnerId() == null) { throw new BusinessException("您没有权限!"); } if (index != null) { searcher.handleIndexForPartner(index); } page.setPageSize(10); if (searcher.getPartnerId() == null && searcher.getParentId() == null && searcher.getSuperId() == null && searcher.getMasterId() == null) { searcher.setPartnerId(memberInfo.getPartnerId()); } PageResult<OrderItemDto> pager = orderItemService.findPartnerOrder(searcher, page); JSONArray array = new JSONArray(); pager.getList().forEach(pb -> array.add(pb.toJson())); result.putPage("partnerBill", pager, array); Setting setting = settingService.findByCode(Setting.ORDERAFTERCLOSE); result.put("expireDay", Setting.defaultValue(setting, new Integer(7))); return result; } /** * 提现单列表 * * @param searcher * @param page * @return */ @RequestMapping(value = "/cash", method = RequestMethod.GET) public ResponseResult partnerCash(PartnerCashSearcher searcher, PageModel page) { ResponseResult result = new ResponseResult(); MemberInfo memberInfo = this.getLoginMemberInfo(); if (memberInfo.getPartnerId() == null) { throw new BusinessException("您没有权限!"); } searcher.setPartnerId(memberInfo.getPartnerId()); searcher.setWaitConfirm(1); PageResult<PartnerCash> pager = partnerCashService.findBySearcher(searcher, page); JSONArray array = new JSONArray(); pager.getList().forEach(pc -> array.add(pc.toJson())); result.putPage("partnerCash", pager, array); return result; } /** * 流水明细列表 * * @param searcher * @param page * @return */ @RequestMapping(value = "/log", method = RequestMethod.GET) public ResponseResult partnerItem(PartnerItemSearcher searcher, PageModel page) { ResponseResult result = new ResponseResult(); MemberInfo memberInfo = this.getLoginMemberInfo(); if (memberInfo.getPartnerId() == null) { throw new BusinessException("您没有权限!"); } searcher.setPartnerId(memberInfo.getPartnerId()); PageResult<PartnerItem> pager = partnerItemService.findBySearcher(searcher, page); JSONArray array = new JSONArray(); pager.getList().forEach(log -> array.add(log.toJson())); result.putPage("partnerLog", pager, array); return result; } /** * 最小提现金额 * * @return */ @RequestMapping(value = "/min/withdraw", method = RequestMethod.GET) public ResponseResult minWithdrawCash() { ResponseResult result = new ResponseResult(); BigDecimal minWithdraw = new BigDecimal(0); result.put("minWithdraw", minWithdraw); return result; } /** * 本月已提现金额 * * @param taxType * @return */ @RequestMapping(value = "/month/withdraw", method = RequestMethod.GET) public ResponseResult monthWithdrawCash(Integer taxType) { ResponseResult result = new ResponseResult(); MemberInfo memberInfo = this.getLoginMemberInfo(); Partner partner = partnerService.findById(memberInfo.getPartnerId()); if (partner == null) { throw new BusinessException("您没有权限!"); } Date today = new Date(); Date sMonthDate = DateUtil.getStartOfMonth(today); Date eMonthDate = DateUtil.getEndOfMonth(today); BigDecimal monthWithdraw = partnerCashService.findWithCashByDate(partner.getId(), sMonthDate, eMonthDate, taxType); result.put("monthWithdraw", monthWithdraw); PartnerCash lastOne = partnerCashService.findLastSuccessOne(partner.getId(), sMonthDate, eMonthDate, taxType); result.put("taxAmount", lastOne == null ? new BigDecimal(0) : lastOne.getTotalTaxAmount()); return result; } /** * 个人信息确认,工猫电签 * * @param realName * @param identityCard * @param region * @param bank * @param bankType * @param bankSn * @return * @throws Exception */ @RequestMapping(value = "/gongmall/contract", method = RequestMethod.POST) public ResponseResult confirmContract(String realName, String identityCard, String region, String bank, String bankType, String bankSn) throws Exception { ResponseResult result = new ResponseResult(); MemberInfo memberInfo = this.getLoginMemberInfo(); Partner partner = partnerService.findById(memberInfo.getPartnerId()); if (partner == null) { throw new BusinessException("您没有权限!"); } if (identityCard != null && identityCard.contains("*")) { identityCard = partner.getIdentityCard(); } if (realName != null && realName.contains("*")) { realName = partner.getRealName(); } if (bankSn != null && bankSn.contains("*")) { bankSn = partner.getBankSn(); } partner.setRegion(region); partner.setBank(bank); partner.setBankType(bankType); partner.setIdentityCard(identityCard); partner.setRealName(realName); partner.setBankSn(bankSn); partnerService.update(partner); if (partner.getContract() == 0) { Partner contracted = partnerService.findContract(identityCard); if (contracted != null) { throw new BusinessException("该身份证号已在工猫电签,请勿重复申请!"); } String url = this.getContractUrl(gongmallConfig, partner.getRealName(), partner.getLoginCode(), "1", partner.getIdentityCard(), partner.getBankSn(), partner.getBankType(), partner.getId().toString(), ""); result.put("url", URLEncoder.encode(url, "UTF-8")); } return result; } /** * 电签功能对接 * * @param config * @param name * @param mobile * @param certificateType * @param idNumber * @param bankNum * @param bankName * @param workNumber * @param extraParam */ private String getContractUrl(GongmallConfig config, String name, String mobile, String certificateType, String idNumber, String bankNum, String bankName, String workNumber, String extraParam) { TreeMap<String, String> map = new TreeMap<>(); map.put("name", name); map.put("mobile", mobile); map.put("certificateType", certificateType); map.put("idNumber", idNumber); map.put("bankNum", bankNum); map.put("bankName", bankName); map.put("workNumber", workNumber); map.put("extraParam", extraParam); StringBuilder sb = new StringBuilder(); Set<String> keys = map.keySet(); for (String key : keys) { if (StringUtil.isNotBlank(map.get(key))) { sb.append(key).append("=").append(map.get(key)).append("&"); } } String dataTemp = sb.toString(); String data = ASE.aesEncrypt(dataTemp.substring(0, dataTemp.length() - 1), MD5Util.encodeMD5Hex(config.getAppkey() + config.getAppSecret()).toUpperCase()); return config.getContractUrl() + "&data=" + data; } /** * 更新个人银行卡信息 * * @param realName * @param identityCard * @param region * @param bank * @param bankType * @param bankSn * @return */ @RequestMapping(value = "/gongmall/update", method = RequestMethod.POST) public ResponseResult confirmUpdate(String realName, String identityCard, String region, String bank, String bankType, String bankSn) { ResponseResult result = new ResponseResult(); MemberInfo memberInfo = this.getLoginMemberInfo(); Partner partner = partnerService.findById(memberInfo.getPartnerId()); if (partner == null) { throw new BusinessException("您没有权限!"); } if (identityCard != null && identityCard.contains("*")) { identityCard = partner.getIdentityCard(); } if (realName != null && realName.contains("*")) { realName = partner.getRealName(); } if (bankSn != null && bankSn.contains("*")) { bankSn = partner.getBankSn(); } JSONObject json = GongmallClient.getInstance().doBankAccount(gongmallConfig, partner.getRealName(), partner.getLoginCode(), partner.getIdentityCard(), partner.getBankType(), partner.getBankSn(), bankType, bankSn); if (!json.getString("success").equals("true")) { throw new BusinessException(json.getString("errorMsg")); } partner.setRegion(region); partner.setBank(bank); partner.setBankType(bankType); partner.setIdentityCard(identityCard); partner.setRealName(realName); partner.setBankSn(bankSn); partnerService.update(partner); return result; } /** * 提现申请 * * @param applyAmount 提现金额 * @param applyAccount 提现账号 * @param payType 提现方式 * @return */ @RequestMapping(value = "/withdraw/cash", method = RequestMethod.POST) public ResponseResult withdrawCash(BigDecimal applyAmount, String applyAccount, String payType) { ResponseResult result = new ResponseResult(); MemberInfo memberInfo = this.getLoginMemberInfo(); Partner partner = partnerService.findById(memberInfo.getPartnerId()); if (partner == null) { throw new BusinessException("您没有权限!"); } if (partner.getStatus() < 0) { throw new BusinessException("用户状态异常!"); } if (partner.getWithdraw() == 0) { throw new BusinessException("该账户提现功能被关闭!"); } if (payType != null && !PayType.contain(payType)) { throw new BusinessException("提现方式异常!"); } if (applyAmount.compareTo(new BigDecimal(0)) < 0) { throw new BusinessException("提现金额异常!"); } if (applyAmount.compareTo( partner.getTotalAmount().subtract(partner.getCashAmount()).subtract(partner.getApplyAmount())) > 0) { throw new BusinessException("超出可提现金额!"); } PartnerCash oldActive = partnerCashService.findActiveByMobile(partner.getLoginCode()); if (oldActive != null && !payType.equals(PayType.wallet.name()) && !oldActive.getPayType().equals(PayType.wallet.name())) { throw new BusinessException("您有一笔正在处理的提现单,请处理完后再申请!"); } PartnerCash partnerCash = new PartnerCash(partner, payType); partnerCash.setApplyAccount(applyAccount); partnerCash.setApplyAmount(applyAmount); Integer taxType = payType.equals(PayType.wallet.name()) ? 1 : 0; partnerCash.setTaxType(taxType); Date today = new Date(); Date sMonthDate = DateUtil.getStartOfMonth(today); Date eMonthDate = DateUtil.getEndOfMonth(today); BigDecimal monthWithdraw = partnerCashService.findWithCashByDate(partner.getId(), sMonthDate, eMonthDate, taxType); PartnerCash lastOne = partnerCashService.findLastSuccessOne(partner.getId(), sMonthDate, eMonthDate, taxType); BigDecimal taxAmount = new BigDecimal(0); if (taxType == 0) { int limit = TaxRule2StepEnum.STEP1.getOpenEnd(); if (monthWithdraw.compareTo(new BigDecimal(0)) > 0 && monthWithdraw.compareTo(new BigDecimal(limit)) < 0) { if ((monthWithdraw.add(applyAmount)).compareTo(new BigDecimal(limit)) >= 0) { throw new BusinessException("您本月最多可提现金额为" + limit + "元!"); } } taxAmount = TaxRule2StepEnum.calculateTax(monthWithdraw.add(applyAmount)); } partnerCash.setTotalTaxAmount(taxAmount); taxAmount = taxAmount.subtract(lastOne == null ? new BigDecimal(0) : lastOne.getTotalTaxAmount()); partnerCash.setApplyTaxAmount(applyAmount.subtract(taxAmount)); partnerCash = partnerTxService.doApplyCash(partnerCash); if (partnerCash.getPayType().equals(PayType.wallet.name())) { Map<String, Object> mq = new HashMap<>(); mq.put("id", partnerCash.getId()); mq.put("sn", partnerCash.getSn()); MqEnum.PARTNER_CASH.send(mq, 3L); } return result; } /** * 根据类型分组<br/> * <p> * 数据结构(类型,总金额)<br/> * * @param partnerId * @return */ @RequestMapping(value = "/summary", method = RequestMethod.GET) public ResponseResult summaryItem(Long partnerId) { ResponseResult result = new ResponseResult(); if (partnerId == null) { MemberInfo memberInfo = this.getLoginMemberInfo(); if (memberInfo.getPartnerId() == null) { throw new BusinessException("您没有权限!"); } partnerId = memberInfo.getPartnerId(); } Partner partner = partnerService.findById(partnerId); if (partner == null) { throw new BusinessException("买手数据不存在!"); } result.put("partner", partner.toJson()); List<Map<String, Object>> incomeData = partnerItemService.findSummaryByType(partner.getId()); result.put("incomeData", incomeData); return result; } /** * 根据状态分组<br/> * <p> * 直接订单(数量,返利金额,实付金额)<br/> * 团队订单(数量,返利金额,实付金额)<br/> * 间接团队订单(数量,返利金额,实付金额)<br/> * AM订单(数量,返利金额,实付金额)<br/> * * @return */ @RequestMapping(value = "/bill/summary", method = RequestMethod.GET) public ResponseResult summaryBill() { ResponseResult result = new ResponseResult(); MemberInfo memberInfo = this.getLoginMemberInfo(); Partner partner = partnerService.findById(memberInfo.getPartnerId()); if (partner == null) { throw new BusinessException("您没有权限!"); } if (partner.getLevel() <= 0) { List<Map<String, Object>> masterData = partnerBillService.findBillSummary(partner.getId(), "master_id", "master_ratio"); result.put("masterData", masterData); } if (partner.getLevel() <= 1) { List<Map<String, Object>> superData = partnerBillService.findBillSummary(partner.getId(), "super_id", "super_ratio"); result.put("superData", superData); List<Map<String, Object>> parentData = partnerBillService.findBillSummary(partner.getId(), "parent_id", "parent_ratio"); result.put("parentData", parentData); } if (partner.getLevel() <= 2) { List<Map<String, Object>> partnerData = partnerBillService.findBillSummary(partner.getId(), "partner_id", "partner_ratio"); result.put("partnerData", partnerData); } return result; } /** * 根据等级分组<br/> * <p> * 当买手/DM进入数据中心时,是parent_id=DM 的买手/DM 人数<br/> * 当AM进入数据中心时,是master_id=AM 的买手/DM 人数<br/> * * @param partnerId * @return */ @RequestMapping(value = "/children/summary", method = RequestMethod.GET) public ResponseResult summaryChildren(Long partnerId) { ResponseResult result = new ResponseResult(); if (partnerId == null) { MemberInfo memberInfo = this.getLoginMemberInfo(); if (memberInfo.getPartnerId() == null) { throw new BusinessException("您没有权限!"); } partnerId = memberInfo.getPartnerId(); } Partner partner = partnerService.findById(partnerId); if (partner == null) { throw new BusinessException("您没有权限!"); } Date now = new Date(); if (partner.getLevel() == 0) { List<Map<String, Object>> amData = partnerService.countChildrenGroup(partner.getId(), "master_id"); result.put("amData", amData); List<Map<String, Object>> todayData = partnerService.countChildrenToday(partner.getId(), "master_id", DateUtil.getStartOfDay(now), DateUtil.getEndOfDay(now)); result.put("todayData", todayData); } else if (partner.getLevel() == 1) { List<Map<String, Object>> dmData = partnerService.countChildrenGroup(partner.getId(), "parent_id"); result.put("dmData", dmData); List<Map<String, Object>> todayData = partnerService.countChildrenToday(partner.getId(), "parent_id", DateUtil.getStartOfDay(now), DateUtil.getEndOfDay(now)); result.put("todayData", todayData); } else if (partner.getLevel() == 2) { List<Map<String, Object>> buyerData = partnerService.countChildrenGroup(partner.getId(), "parent_id"); result.put("buyerData", buyerData); List<Map<String, Object>> todayData = partnerService.countChildrenToday(partner.getId(), "parent_id", DateUtil.getStartOfDay(now), DateUtil.getEndOfDay(now)); result.put("todayData", todayData); } return result; } /** * 我的店铺 * * @return */ @RequestMapping(value = "/store", method = RequestMethod.GET) public ResponseResult store(PageModel page, Long memberId, Long partnerId) { ResponseResult result = new ResponseResult(); PartnerStore partnerStore = null; if (memberId == null && partnerId != null) { partnerStore = partnerStoreService.findByPartnerId(partnerId); } else if (memberId != null && partnerId == null) { partnerStore = partnerStoreService.findByMemberId(memberId); } else if (memberId == null && partnerId == null) { MemberInfo memberInfo = this.getLoginMemberInfo(); partnerStore = partnerStoreService.findByMemberId(memberInfo.getId()); } if (partnerStore == null) { throw new BusinessException("您还未开通小店!"); } result.put("partnerStore", partnerStore.toJson()); return result; } /** * 更新店铺 * * @param partnerStore * @return */ @RequestMapping(value = "/update/store", method = RequestMethod.POST) public ResponseResult updateStore(PartnerStore partnerStore) { ResponseResult result = new ResponseResult(); MemberInfo memberInfo = this.getLoginMemberInfo(); PartnerStore old = partnerStoreService.findByMemberId(memberInfo.getId()); if (old == null) { throw new BusinessException("您还未开通小店!"); } if (partnerStore.getId() == null || !old.getId().equals(partnerStore.getId())) { throw new BusinessException("不是您本人的小店!"); } partnerStore.setMemberId(memberInfo.getId()); partnerStore.setPartnerId(memberInfo.getPartnerId()); partnerStoreService.update(partnerStore); return result; } /** * 是否选品 * * @param productId * @return */ @RequestMapping(value = "/select/product", method = RequestMethod.GET) public ResponseResult selected(Long productId) { ResponseResult result = new ResponseResult(); MemberInfo memberInfo = this.getLoginMemberInfo(); PartnerStore partnerStore = partnerStoreService.findByMemberId(memberInfo.getId()); if (partnerStore == null) { result.put("selected", 0); return result; } ProductPartnerRelation productPartnerRelation = productPartnerRelationService.findOne(partnerStore.getId(), productId); if (productPartnerRelation == null) { result.put("selected", 0); return result; } result.put("selected", 1); return result; } /** * 店铺选品 * * @param productId * @return */ @RequestMapping(value = "/select/product", method = RequestMethod.POST) public ResponseResult selectProduct(Long productId) { ResponseResult result = new ResponseResult(); MemberInfo memberInfo = this.getLoginMemberInfo(); PartnerStore partnerStore = partnerStoreService.findByMemberId(memberInfo.getId()); if (partnerStore == null) { throw new BusinessException("您还未开通小店!"); } productPartnerRelationService.insert(partnerStore.getId(), productId); return result; } /** * 店铺取消选品 * * @param productId * @return */ @RequestMapping(value = "/cancel/product", method = RequestMethod.POST) public ResponseResult cancelProduct(Long productId) { ResponseResult result = new ResponseResult(); MemberInfo memberInfo = this.getLoginMemberInfo(); PartnerStore partnerStore = partnerStoreService.findByMemberId(memberInfo.getId()); if (partnerStore == null) { throw new BusinessException("您还未开通小店!"); } productPartnerRelationService.deleteOne(partnerStore.getId(), productId); return result; } /** * 店铺商品列表 * * @param page * @return */ @RequestMapping(value = "/product/list", method = RequestMethod.GET) public ResponseResult productList(PageModel page, Long memberId, Long partnerId) { ResponseResult result = new ResponseResult(); PartnerStore partnerStore = null; if (memberId == null && partnerId != null) { partnerStore = partnerStoreService.findByPartnerId(partnerId); } else if (memberId != null && partnerId == null) { partnerStore = partnerStoreService.findByMemberId(memberId); } else if (memberId == null && partnerId == null) { MemberInfo memberInfo = this.getLoginMemberInfo(); partnerStore = partnerStoreService.findByMemberId(memberInfo.getId()); } if (partnerStore == null) { throw new BusinessException("您还未开通小店!"); } PageResult<Product> productPager = productPartnerRelationService.findProductByStoreId(partnerStore.getId(), page); List<String> productIds = new ArrayList<>(); productPager.getList().forEach(product -> productIds.add(product.getId().toString())); List<SearcherProduct> productList = productSearcherQueryService.findByIds(productIds, 1); JSONArray productArray = new JSONArray(); productList.forEach(product -> productArray.add(product.toJson())); result.putPage("products", productPager, productArray); // 全局返利系数 Setting ratio = settingService.findByCode(Setting.REBATERATIO); result.put("ratio", Setting.defaultValue(ratio, new Integer(1))); return result; } /** * 运营顾问 * * @param id * @return */ @RequestMapping(value = "/counselor/{id}", method = RequestMethod.GET) public ResponseResult counselor(@PathVariable Long id) { ResponseResult result = new ResponseResult(); PartnerCounselor partnerCounselor = partnerCounselorService.findById(id); if (partnerCounselor == null) { throw new BusinessException("运营顾问不存在!"); } result.put("partnerCounselor", partnerCounselor.toJson()); return result; } /** * 运营顾问列表 * * @param searcher * @return */ @RequestMapping(value = "/counselor/list", method = RequestMethod.GET) public ResponseResult counselorList(PartnerCounselorSearcher searcher) { ResponseResult result = new ResponseResult(); searcher.setStatus(1); PageResult<PartnerCounselor> pager = partnerCounselorService.findBySearcher(new PageModel(1, 10), searcher); JSONArray array = new JSONArray(); pager.getList().forEach(item -> array.add(item.toJson())); result.put("counselors", array); return result; } /** * 选择运营顾问 * * @param counselorId * @return */ @RequestMapping(value = "/select/counselor", method = RequestMethod.POST) public ResponseResult selectCounselor(Long counselorId) { ResponseResult result = new ResponseResult(); MemberInfo memberInfo = this.getLoginMemberInfo(); if (memberInfo.getPartnerId() == null) { throw new BusinessException("您没有权限!"); } PartnerCounselor partnerCounselor = partnerCounselorService.findById(counselorId); if (partnerCounselor == null) { throw new BusinessException("运营顾问不存在!"); } partnerService.doBindCounselor(memberInfo.getPartnerId(), counselorId, memberInfo.getLoginCode()); // couponDefGroupService.doClaimedCoupon(157L, memberInfo.getId(), // memberInfo.getLoginCode(), // memberInfo.getLoginCode(), CouponSourceEnum.APP.name()); result.put("partnerCounselor", partnerCounselor); return result; } /** * 礼包商品列表 * * @param page * @return */ @RequestMapping(value = "/gift/list", method = RequestMethod.GET) public ResponseResult giftList(PageModel page) { ResponseResult result = new ResponseResult(); ProductSearcher searcher = new ProductSearcher(); searcher.setStatus(-1); searcher.setMark(1); PageResult<ProductDto> pager = productService.findBySearch(searcher, page); JSONArray array = new JSONArray(); pager.getList().forEach(item -> array.add(item.toJson(null))); result.putPage("products", pager, array); return result; } /** * 我的礼包列表 * * @param page * @return */ @RequestMapping(value = "/package/list", method = RequestMethod.GET) public ResponseResult packageList(PageModel page) { ResponseResult result = new ResponseResult(); MemberInfo memberInfo = this.getLoginMemberInfo(); if (memberInfo.getPartnerId() == null) { throw new BusinessException("您没有权限!"); } Partner partner = partnerService.findById(memberInfo.getPartnerId()); if (partner == null) { throw new BusinessException("分销商不存在!"); } PartnerGiftSearcher searcher = new PartnerGiftSearcher(); if (partner.getLevel() == 2) { searcher.setPartnerId(partner.getId()); } else if (partner.getLevel() == 1) { searcher.setParentId(partner.getId()); } else if (partner.getLevel() == 0) { searcher.setMasterId(partner.getId()); } PageResult<PartnerGift> pager = partnerGiftService.findBySearcher(searcher, page); JSONArray array = new JSONArray(); pager.getList().forEach(item -> array.add(item.toJson(partner.getId()))); result.putPage("gifts", pager, array); return result; } }
38,492
0.630418
0.627629
955
38.036648
27.983536
123
false
false
0
0
0
0
0
0
0.660733
false
false
5
13efe95c92b90d83eb040ba9e0c561880970dbb3
31,516,470,069,165
af09aba983422f1b7c2ddc9acdfd865dd8e54d5b
/PriceDetails.java
31395249068e2001ce18757d048470c1c3b2b84b
[]
no_license
ManivannaBalaji/movie_booking_app
https://github.com/ManivannaBalaji/movie_booking_app
3dd0629879004757e7fe6fdc87305c2a7c607c90
67c0bcb0557770921d2cf0007e932635120e287f
refs/heads/main
2023-04-03T17:04:20.740000
2021-04-16T12:16:43
2021-04-16T12:16:43
358,588,591
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.manivannabalaji.moviebookingapp; import java.time.LocalDate; import java.time.LocalTime; public class PriceDetails { /** * This method prints the movie ticket fare details * @param categoryName * @param noOfTickets * @param price * @param gst * @param seniorCitizen * @param bookingDate * @param showDate * @param bookingTime * @param showTime */ public static void printStatement(String categoryName, int noOfTickets, int price, int gst, boolean seniorCitizen, LocalDate bookingDate, LocalDate showDate, LocalTime bookingTime, LocalTime showTime) { System.out.println("=================================================="); System.out.println("Price Details :)"); System.out.println("=================================================="); System.out.println("Ticket Category : " + categoryName); System.out.println("No of Tickets : " + noOfTickets); System.out.println("Booking Date : " + bookingDate); System.out.println("Booking Time : " + bookingTime); System.out.println("Show Date : " + showDate); System.out.println("Show Time : " + showTime); if(seniorCitizen) { System.out.println("Senior Citizen : Yes"); }else { System.out.println("Senior Citizen : No"); } System.out.println("Price : " + price); System.out.println("GST : " + gst); System.out.println("Total : " + (price + gst)); System.out.println("=================================================="); } }
UTF-8
Java
1,488
java
PriceDetails.java
Java
[ { "context": "package com.manivannabalaji.moviebookingapp;\r\n\r\nimport java.time.LocalDate;\r\n", "end": 27, "score": 0.6689332723617554, "start": 15, "tag": "USERNAME", "value": "ivannabalaji" } ]
null
[]
package com.manivannabalaji.moviebookingapp; import java.time.LocalDate; import java.time.LocalTime; public class PriceDetails { /** * This method prints the movie ticket fare details * @param categoryName * @param noOfTickets * @param price * @param gst * @param seniorCitizen * @param bookingDate * @param showDate * @param bookingTime * @param showTime */ public static void printStatement(String categoryName, int noOfTickets, int price, int gst, boolean seniorCitizen, LocalDate bookingDate, LocalDate showDate, LocalTime bookingTime, LocalTime showTime) { System.out.println("=================================================="); System.out.println("Price Details :)"); System.out.println("=================================================="); System.out.println("Ticket Category : " + categoryName); System.out.println("No of Tickets : " + noOfTickets); System.out.println("Booking Date : " + bookingDate); System.out.println("Booking Time : " + bookingTime); System.out.println("Show Date : " + showDate); System.out.println("Show Time : " + showTime); if(seniorCitizen) { System.out.println("Senior Citizen : Yes"); }else { System.out.println("Senior Citizen : No"); } System.out.println("Price : " + price); System.out.println("GST : " + gst); System.out.println("Total : " + (price + gst)); System.out.println("=================================================="); } }
1,488
0.606183
0.606183
40
35.200001
26.394318
115
false
false
0
0
0
0
0
0
2.025
false
false
5
482e6b05e7a3c1a2b0d18226b352812613328e83
26,740,466,402,939
57ee3bae6afcd94f0d468cb2a9cbe872e50e020b
/src/main/java/hex/gbm/DHistogram.java
860d8d3a10e11fd98fe38078d8c1ccce7b57d7a5
[ "Apache-2.0" ]
permissive
woobe/h2o
https://github.com/woobe/h2o
626b3595251c75ed6d72469b442c467b21cbdeaa
5a7bbb6d82f6dcc1384dc51dcde227665ce1baf6
refs/heads/master
2021-01-24T16:47:36.786000
2014-07-28T04:48:02
2014-07-28T04:48:02
22,338,992
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package hex.gbm; import sun.misc.Unsafe; import water.*; import water.fvec.Frame; import water.fvec.Vec; import water.nbhm.UtilUnsafe; import water.util.Utils; /** A Histogram, computed in parallel over a Vec. <p> A {@code DHistogram} bins every value added to it, and computes a the vec min and max (for use in the next split), and response mean and variance for each bin. {@code DHistogram}s are initialized with a min, max and number-of- elements to be added (all of which are generally available from a Vec). Bins run from min to max in uniform sizes. If the {@code DHistogram} can determine that fewer bins are needed (e.g. boolean columns run from 0 to 1, but only ever take on 2 values, so only 2 bins are needed), then fewer bins are used. <p> {@code DHistogram} are shared per-node, and atomically updated. There's an {@code add} call to help cross-node reductions. The data is stored in primitive arrays, so it can be sent over the wire. <p> If we are successively splitting rows (e.g. in a decision tree), then a fresh {@code DHistogram} for each split will dynamically re-bin the data. Each successive split will logarithmically divide the data. At the first split, outliers will end up in their own bins - but perhaps some central bins may be very full. At the next split(s), the full bins will get split, and again until (with a log number of splits) each bin holds roughly the same amount of data. This dynamic binning resolves a lot of problems with picking the proper bin count or limits - generally a few more tree levels will equal any fancy but fixed-size binning strategy. <p> @author Cliff Click */ public abstract class DHistogram<TDH extends DHistogram> extends Iced { public final transient String _name; // Column name (for debugging) public final byte _isInt; // 0: float col, 1: int col, 2: enum & int col public final char _nbin; // Bin count public final float _step; // Linear interpolation step per bin public final float _min, _maxEx; // Conservative Min/Max over whole collection. _maxEx is Exclusive. public int _bins[]; // Bins, shared, atomically incremented public final boolean _doGrpSplit; // Atomically updated float min/max protected float _min2, _maxIn; // Min/Max, shared, atomically updated. _maxIn is Inclusive. private static final Unsafe _unsafe = UtilUnsafe.getUnsafe(); static private final long _min2Offset; static private final long _max2Offset; static { try { _min2Offset = _unsafe.objectFieldOffset(DHistogram.class.getDeclaredField("_min2")); _max2Offset = _unsafe.objectFieldOffset(DHistogram.class.getDeclaredField("_maxIn")); } catch( Exception e ) { throw H2O.fail(); } } public void setMin( float min ) { int imin = Float.floatToRawIntBits(min); float old = _min2; while( min < old && !_unsafe.compareAndSwapInt(this, _min2Offset, Float.floatToRawIntBits(old), imin ) ) old = _min2; } // Find Inclusive _max2 public void setMax( float max ) { int imax = Float.floatToRawIntBits(max); float old = _maxIn; while( max > old && !_unsafe.compareAndSwapInt(this, _max2Offset, Float.floatToRawIntBits(old), imax ) ) old = _maxIn; } public DHistogram( String name, final int nbins, final byte isInt, final float min, final float maxEx, long nelems, boolean doGrpSplit ) { assert nelems > 0; assert nbins >= 1; assert maxEx > min : "Caller ensures "+maxEx+">"+min+", since if max==min== the column "+name+" is all constants"; _isInt = isInt; _name = name; _doGrpSplit = doGrpSplit; _min=min; _maxEx=maxEx; // Set Exclusive max _min2 = Float.MAX_VALUE; // Set min/max to outer bounds _maxIn= -Float.MAX_VALUE; // See if we can show there are fewer unique elements than nbins. // Common for e.g. boolean columns, or near leaves. int xbins = nbins; float step; if( isInt>0 && maxEx-min <= nbins ) { assert ((long)min)==min; // No overflow xbins = (char)((long)maxEx-(long)min); // Shrink bins assert xbins > 1; // Caller ensures enough range to bother step = 1.0f; // Fixed stepsize } else { step = (maxEx-min)/nbins; // Step size for linear interpolation assert step > 0; } _step = 1.0f/step; // Use multiply instead of division during frequent binning math _nbin = (char)xbins; // Do not allocate the big arrays here; wait for scoreCols to pick which cols will be used. } abstract boolean isBinom(); // Interpolate d to find bin# int bin( float col_data ) { if( Float.isNaN(col_data) ) return 0; // Always NAs to bin 0 // When the model is exposed to new test data, we could have data that is // out of range of any bin - however this binning call only happens during // model-building. assert _min <= col_data && col_data < _maxEx : "Coldata "+col_data+" out of range "+this; int idx1 = (int)((col_data-_min)*_step); assert 0 <= idx1 && idx1 <= _bins.length; if( idx1 == _bins.length) idx1--; // Roundoff error allows idx1 to hit upper bound, so truncate return idx1; } float binAt( int b ) { return _min+b/_step; } public int nbins() { return _nbin; } public int bins(int b) { return _bins[b]; } public float mins(int b) { return _min2; } public float maxsIn(int b) { return _maxIn; } // Always an Inclusive max abstract public double mean(int b); abstract public double var (int b); // Big allocation of arrays abstract void init0(); final void init() { assert _bins == null; _bins = MemoryManager.malloc4(_nbin); init0(); } // Add one row to a bin found via simple linear interpolation. // Compute bin min/max. // Compute response mean & variance. abstract void incr0( int b, double y ); final void incr( float col_data, double y ) { assert Float.isNaN(col_data) || (_min <= col_data && col_data < _maxEx) : "col_data "+col_data+" out of range "+this; int b = bin(col_data); // Compute bin# via linear interpolation Utils.AtomicIntArray.incr(_bins,b); // Bump count in bin // Track actual lower/upper bound per-bin setMin(col_data); setMax(col_data); if( y != 0 ) incr0(b,y); } // Merge two equal histograms together. Done in a F/J reduce, so no // synchronization needed. abstract void add0( TDH dsh ); void add( TDH dsh ) { assert _isInt == dsh._isInt && _nbin == dsh._nbin && _step == dsh._step && _min == dsh._min && _maxEx == dsh._maxEx; assert (_bins == null && dsh._bins == null) || (_bins != null && dsh._bins != null); if( _bins == null ) return; Utils.add(_bins,dsh._bins); if( _min2 > dsh._min2 ) _min2 = dsh._min2 ; if( _maxIn < dsh._maxIn ) _maxIn = dsh._maxIn; add0(dsh); } // Inclusive min & max public float find_min () { return _min2 ; } public float find_maxIn() { return _maxIn; } // Exclusive max public float find_maxEx() { return find_maxEx(_maxIn,_isInt); } static public float find_maxEx(float maxIn, int isInt ) { float ulp = Math.ulp(maxIn); if( isInt > 0 && 1 > ulp ) ulp = 1; return maxIn+ulp; } // Compute a "score" for a column; lower score "wins" (is a better split). // Score is the sum of the MSEs when the data is split at a single point. // mses[1] == MSE for splitting between bins 0 and 1. // mses[n] == MSE for splitting between bins n-1 and n. abstract public DTree.Split scoreMSE( int col ); // The initial histogram bins are setup from the Vec rollups. static public DHistogram[] initialHist(Frame fr, int ncols, int nbins, DHistogram hs[], boolean doGrpSplit, boolean isBinom) { Vec vecs[] = fr.vecs(); for( int c=0; c<ncols; c++ ) { Vec v = vecs[c]; final float maxIn = (float)v.max(); final float maxEx = find_maxEx(maxIn,v.isInt()?1:0); hs[c] = v.naCnt()==v.length() || v.min()==v.max() ? null : make(fr._names[c],nbins,(byte)(v.isEnum() ? 2 : (v.isInt()?1:0)),(float)v.min(),maxEx,v.length(),doGrpSplit,isBinom); } return hs; } static public DHistogram make( String name, final int nbins, byte isInt, float min, float maxEx, long nelems, boolean doGrpSplit, boolean isBinom ) { return isBinom ? new DBinomHistogram(name,nbins,isInt,min,maxEx,nelems,doGrpSplit) : new DRealHistogram(name,nbins,isInt,min,maxEx,nelems,doGrpSplit); } // Check for a constant response variable public boolean isConstantResponse() { double m = Double.NaN; for( int b=0; b<_bins.length; b++ ) { if( _bins[b] == 0 ) continue; if( var(b) > 1e-14 ) return false; double mean = mean(b); if( mean != m ) if( Double.isNaN(m) ) m=mean; else if(Math.abs(m - mean) > 1e-6) return false; } return true; } // Pretty-print a histogram @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(_name).append(":").append(_min).append("-").append(_maxEx).append(" step="+(1/_step)+" nbins="+nbins()+" isInt="+_isInt); if( _bins != null ) { for( int b=0; b<_bins.length; b++ ) { sb.append(String.format("\ncnt=%d, [%f - %f], mean/var=", _bins[b],mins(b),maxsIn(b))); sb.append(String.format("%6.2f/%6.2f,", mean(b), var(b))); } sb.append('\n'); } return sb.toString(); } abstract public long byteSize0(); public long byteSize() { long sum = 8+8; // Self header sum += 1+2; // enum; nbin sum += 4+4+4+4+4; // step,min,max,min2,max2 sum += 8*1; // 1 internal arrays if( _bins == null ) return sum; // + 20(array header) + len<<2 (array body) sum += 24+_bins.length<<3; sum += byteSize0(); return sum; } }
UTF-8
Java
9,934
java
DHistogram.java
Java
[ { "context": "but fixed-size binning strategy.\n <p>\n @author Cliff Click\n*/\npublic abstract class DHistogram<TDH extends D", "end": 1704, "score": 0.9995386004447937, "start": 1693, "tag": "NAME", "value": "Cliff Click" } ]
null
[]
package hex.gbm; import sun.misc.Unsafe; import water.*; import water.fvec.Frame; import water.fvec.Vec; import water.nbhm.UtilUnsafe; import water.util.Utils; /** A Histogram, computed in parallel over a Vec. <p> A {@code DHistogram} bins every value added to it, and computes a the vec min and max (for use in the next split), and response mean and variance for each bin. {@code DHistogram}s are initialized with a min, max and number-of- elements to be added (all of which are generally available from a Vec). Bins run from min to max in uniform sizes. If the {@code DHistogram} can determine that fewer bins are needed (e.g. boolean columns run from 0 to 1, but only ever take on 2 values, so only 2 bins are needed), then fewer bins are used. <p> {@code DHistogram} are shared per-node, and atomically updated. There's an {@code add} call to help cross-node reductions. The data is stored in primitive arrays, so it can be sent over the wire. <p> If we are successively splitting rows (e.g. in a decision tree), then a fresh {@code DHistogram} for each split will dynamically re-bin the data. Each successive split will logarithmically divide the data. At the first split, outliers will end up in their own bins - but perhaps some central bins may be very full. At the next split(s), the full bins will get split, and again until (with a log number of splits) each bin holds roughly the same amount of data. This dynamic binning resolves a lot of problems with picking the proper bin count or limits - generally a few more tree levels will equal any fancy but fixed-size binning strategy. <p> @author <NAME> */ public abstract class DHistogram<TDH extends DHistogram> extends Iced { public final transient String _name; // Column name (for debugging) public final byte _isInt; // 0: float col, 1: int col, 2: enum & int col public final char _nbin; // Bin count public final float _step; // Linear interpolation step per bin public final float _min, _maxEx; // Conservative Min/Max over whole collection. _maxEx is Exclusive. public int _bins[]; // Bins, shared, atomically incremented public final boolean _doGrpSplit; // Atomically updated float min/max protected float _min2, _maxIn; // Min/Max, shared, atomically updated. _maxIn is Inclusive. private static final Unsafe _unsafe = UtilUnsafe.getUnsafe(); static private final long _min2Offset; static private final long _max2Offset; static { try { _min2Offset = _unsafe.objectFieldOffset(DHistogram.class.getDeclaredField("_min2")); _max2Offset = _unsafe.objectFieldOffset(DHistogram.class.getDeclaredField("_maxIn")); } catch( Exception e ) { throw H2O.fail(); } } public void setMin( float min ) { int imin = Float.floatToRawIntBits(min); float old = _min2; while( min < old && !_unsafe.compareAndSwapInt(this, _min2Offset, Float.floatToRawIntBits(old), imin ) ) old = _min2; } // Find Inclusive _max2 public void setMax( float max ) { int imax = Float.floatToRawIntBits(max); float old = _maxIn; while( max > old && !_unsafe.compareAndSwapInt(this, _max2Offset, Float.floatToRawIntBits(old), imax ) ) old = _maxIn; } public DHistogram( String name, final int nbins, final byte isInt, final float min, final float maxEx, long nelems, boolean doGrpSplit ) { assert nelems > 0; assert nbins >= 1; assert maxEx > min : "Caller ensures "+maxEx+">"+min+", since if max==min== the column "+name+" is all constants"; _isInt = isInt; _name = name; _doGrpSplit = doGrpSplit; _min=min; _maxEx=maxEx; // Set Exclusive max _min2 = Float.MAX_VALUE; // Set min/max to outer bounds _maxIn= -Float.MAX_VALUE; // See if we can show there are fewer unique elements than nbins. // Common for e.g. boolean columns, or near leaves. int xbins = nbins; float step; if( isInt>0 && maxEx-min <= nbins ) { assert ((long)min)==min; // No overflow xbins = (char)((long)maxEx-(long)min); // Shrink bins assert xbins > 1; // Caller ensures enough range to bother step = 1.0f; // Fixed stepsize } else { step = (maxEx-min)/nbins; // Step size for linear interpolation assert step > 0; } _step = 1.0f/step; // Use multiply instead of division during frequent binning math _nbin = (char)xbins; // Do not allocate the big arrays here; wait for scoreCols to pick which cols will be used. } abstract boolean isBinom(); // Interpolate d to find bin# int bin( float col_data ) { if( Float.isNaN(col_data) ) return 0; // Always NAs to bin 0 // When the model is exposed to new test data, we could have data that is // out of range of any bin - however this binning call only happens during // model-building. assert _min <= col_data && col_data < _maxEx : "Coldata "+col_data+" out of range "+this; int idx1 = (int)((col_data-_min)*_step); assert 0 <= idx1 && idx1 <= _bins.length; if( idx1 == _bins.length) idx1--; // Roundoff error allows idx1 to hit upper bound, so truncate return idx1; } float binAt( int b ) { return _min+b/_step; } public int nbins() { return _nbin; } public int bins(int b) { return _bins[b]; } public float mins(int b) { return _min2; } public float maxsIn(int b) { return _maxIn; } // Always an Inclusive max abstract public double mean(int b); abstract public double var (int b); // Big allocation of arrays abstract void init0(); final void init() { assert _bins == null; _bins = MemoryManager.malloc4(_nbin); init0(); } // Add one row to a bin found via simple linear interpolation. // Compute bin min/max. // Compute response mean & variance. abstract void incr0( int b, double y ); final void incr( float col_data, double y ) { assert Float.isNaN(col_data) || (_min <= col_data && col_data < _maxEx) : "col_data "+col_data+" out of range "+this; int b = bin(col_data); // Compute bin# via linear interpolation Utils.AtomicIntArray.incr(_bins,b); // Bump count in bin // Track actual lower/upper bound per-bin setMin(col_data); setMax(col_data); if( y != 0 ) incr0(b,y); } // Merge two equal histograms together. Done in a F/J reduce, so no // synchronization needed. abstract void add0( TDH dsh ); void add( TDH dsh ) { assert _isInt == dsh._isInt && _nbin == dsh._nbin && _step == dsh._step && _min == dsh._min && _maxEx == dsh._maxEx; assert (_bins == null && dsh._bins == null) || (_bins != null && dsh._bins != null); if( _bins == null ) return; Utils.add(_bins,dsh._bins); if( _min2 > dsh._min2 ) _min2 = dsh._min2 ; if( _maxIn < dsh._maxIn ) _maxIn = dsh._maxIn; add0(dsh); } // Inclusive min & max public float find_min () { return _min2 ; } public float find_maxIn() { return _maxIn; } // Exclusive max public float find_maxEx() { return find_maxEx(_maxIn,_isInt); } static public float find_maxEx(float maxIn, int isInt ) { float ulp = Math.ulp(maxIn); if( isInt > 0 && 1 > ulp ) ulp = 1; return maxIn+ulp; } // Compute a "score" for a column; lower score "wins" (is a better split). // Score is the sum of the MSEs when the data is split at a single point. // mses[1] == MSE for splitting between bins 0 and 1. // mses[n] == MSE for splitting between bins n-1 and n. abstract public DTree.Split scoreMSE( int col ); // The initial histogram bins are setup from the Vec rollups. static public DHistogram[] initialHist(Frame fr, int ncols, int nbins, DHistogram hs[], boolean doGrpSplit, boolean isBinom) { Vec vecs[] = fr.vecs(); for( int c=0; c<ncols; c++ ) { Vec v = vecs[c]; final float maxIn = (float)v.max(); final float maxEx = find_maxEx(maxIn,v.isInt()?1:0); hs[c] = v.naCnt()==v.length() || v.min()==v.max() ? null : make(fr._names[c],nbins,(byte)(v.isEnum() ? 2 : (v.isInt()?1:0)),(float)v.min(),maxEx,v.length(),doGrpSplit,isBinom); } return hs; } static public DHistogram make( String name, final int nbins, byte isInt, float min, float maxEx, long nelems, boolean doGrpSplit, boolean isBinom ) { return isBinom ? new DBinomHistogram(name,nbins,isInt,min,maxEx,nelems,doGrpSplit) : new DRealHistogram(name,nbins,isInt,min,maxEx,nelems,doGrpSplit); } // Check for a constant response variable public boolean isConstantResponse() { double m = Double.NaN; for( int b=0; b<_bins.length; b++ ) { if( _bins[b] == 0 ) continue; if( var(b) > 1e-14 ) return false; double mean = mean(b); if( mean != m ) if( Double.isNaN(m) ) m=mean; else if(Math.abs(m - mean) > 1e-6) return false; } return true; } // Pretty-print a histogram @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(_name).append(":").append(_min).append("-").append(_maxEx).append(" step="+(1/_step)+" nbins="+nbins()+" isInt="+_isInt); if( _bins != null ) { for( int b=0; b<_bins.length; b++ ) { sb.append(String.format("\ncnt=%d, [%f - %f], mean/var=", _bins[b],mins(b),maxsIn(b))); sb.append(String.format("%6.2f/%6.2f,", mean(b), var(b))); } sb.append('\n'); } return sb.toString(); } abstract public long byteSize0(); public long byteSize() { long sum = 8+8; // Self header sum += 1+2; // enum; nbin sum += 4+4+4+4+4; // step,min,max,min2,max2 sum += 8*1; // 1 internal arrays if( _bins == null ) return sum; // + 20(array header) + len<<2 (array body) sum += 24+_bins.length<<3; sum += byteSize0(); return sum; } }
9,929
0.634588
0.624421
238
40.739494
31.59791
151
false
false
0
0
0
0
0
0
0.92437
false
false
5
b057c74c95fffea1eee640a5949bc4edaffb8faa
14,903,536,535,218
1063d3492bc031ddf2b9f6206d89f9c6d787c23f
/platform-ui/plugins/org.eclipse.ui.ide.markers.compatibility/src/org/eclipse/ui/ide/markers/compatibility/internal/AddTaskHandler.java
a26764d7da837dbf2c8aaf8742431eb71e8ea9f0
[]
no_license
eclipse/eclipse
https://github.com/eclipse/eclipse
db61562e0c46ad140cef0fa07edc54c607466997
7932fc75c64ee4e5b4a154abbeb8ea0a9f40d1c3
refs/heads/master
2021-05-22T03:16:48.688000
2021-05-18T10:10:16
2021-05-18T10:10:16
7,426,465
328
188
null
false
2021-02-25T15:06:32
2013-01-03T16:56:31
2021-02-24T18:15:54
2021-02-25T14:58:57
58,159
249
151
4
HTML
false
false
package org.eclipse.ui.ide.markers.compatibility.internal; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.ui.ide.markers.compatibility.api.MarkerViewHandler; import org.eclipse.ui.views.markers.internal.DialogTaskProperties; import org.eclipse.ui.views.markers.internal.MarkerMessages; /** * AddTaskHandler is the handler for adding a new task to the task list. * * @since 3.4 * */ public class AddTaskHandler extends MarkerViewHandler { /* * (non-Javadoc) * * @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.ExecutionEvent) */ public Object execute(ExecutionEvent event) { final ExtendedMarkersView view = getView(event); if (view == null) return this; DialogTaskProperties dialog = new DialogTaskProperties(view.getSite() .getShell()); dialog.create(); dialog.getShell().setText(MarkerMessages.addGlobalTaskDialog_title); dialog.open(); return this; } }
UTF-8
Java
948
java
AddTaskHandler.java
Java
[]
null
[]
package org.eclipse.ui.ide.markers.compatibility.internal; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.ui.ide.markers.compatibility.api.MarkerViewHandler; import org.eclipse.ui.views.markers.internal.DialogTaskProperties; import org.eclipse.ui.views.markers.internal.MarkerMessages; /** * AddTaskHandler is the handler for adding a new task to the task list. * * @since 3.4 * */ public class AddTaskHandler extends MarkerViewHandler { /* * (non-Javadoc) * * @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.ExecutionEvent) */ public Object execute(ExecutionEvent event) { final ExtendedMarkersView view = getView(event); if (view == null) return this; DialogTaskProperties dialog = new DialogTaskProperties(view.getSite() .getShell()); dialog.create(); dialog.getShell().setText(MarkerMessages.addGlobalTaskDialog_title); dialog.open(); return this; } }
948
0.757384
0.755274
34
26.882353
28.470589
93
false
false
0
0
0
0
0
0
1.176471
false
false
5
3196d9831df475b4fef2793d91c680c88c01d697
4,724,464,031,153
1673ee346121c80fce44814e55963552cf37c4d0
/note/in_action/back_end/group_buy/by_spring_in_mooc/my_source/source_code/Service/src/main/java/com/tortuousroad/groupon/deal/dao/DealCategoryDAO.java
ad614fde04182982b2f93daba5f43c498b0bb5ad
[]
no_license
zoy2control/computer-science
https://github.com/zoy2control/computer-science
d271e5b85595c2d01a01c431d440ba83f2693f96
882a2ef3ab9041693bf12ad7343f349319d02634
refs/heads/master
2020-05-19T07:43:44.341000
2020-05-17T11:40:38
2020-05-17T11:40:38
184,901,487
1
0
null
false
2020-07-02T03:40:45
2019-05-04T13:55:28
2020-06-29T09:05:18
2020-07-02T03:40:43
377,403
1
0
7
TSQL
false
false
package com.tortuousroad.groupon.deal.dao; import com.tortuousroad.groupon.deal.constant.DealConstant; import com.tortuousroad.groupon.deal.entity.DealCategory; import com.tortuousroad.framework.common.page.PagingResult; import com.tortuousroad.framework.common.persistence.BaseMybatisDAO; import com.tortuousroad.framework.common.search.Search; import org.springframework.stereotype.Repository; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Deal分类 */ @Repository public class DealCategoryDAO extends BaseMybatisDAO { /** * Mapper映射命名空间 */ private static final String MAPPER_NAMESPACE = "com.tortuousroad.groupon.deal.entity.DealCategoryMapper"; /** * 查询所有未删除的商品类别 * @return */ public List<DealCategory> getAllWithoutDeleted() { return super.findAll(MAPPER_NAMESPACE + ".selectAllWithoutDeleted", DealConstant.DEAL_PUBLISH_STATUS_DELETED); } /** * 查询直接下级 * @param parentId * @return */ public List<DealCategory> getDirectSubs(Long parentId) { Map<String, Object> params = new HashMap<>(); params.put("publishStatus", DealConstant.DEAL_PUBLISH_STATUS_DELETED); params.put("parentId", parentId); return findAll(MAPPER_NAMESPACE + ".selectDirectSubs", params); } /** * 根据ID查询 * @param id * @return */ public DealCategory getById(Long id) { return findOne(MAPPER_NAMESPACE + ".selectByPrimaryKey", id); } /** * 分页查询 * @param search * @return */ public PagingResult<DealCategory> getPageCategories(Search search) { return findForPage(MAPPER_NAMESPACE + ".countPageCategories", MAPPER_NAMESPACE + ".selectPageCategories", search); } /** * 更新 * @param category * @return */ public int updateById(DealCategory category) { return update(MAPPER_NAMESPACE + ".updateByPrimaryKeySelective", category); } /** * 保存 * @param category * @return */ public int save(DealCategory category) { return save(MAPPER_NAMESPACE + ".insertSelective", category); } /** * 根据ID删除 * @param id * @return */ public int deleteById(Long id) { return delete(MAPPER_NAMESPACE + ".deleteByPrimaryKey", id); } /** * 根据urlName查询 * @param urlName * @return */ public DealCategory getByUrlName(String urlName) { Map<String, Object> params = new HashMap<String, Object>(); params.put("urlName", urlName); return findOne(MAPPER_NAMESPACE + ".selectByUrlName", params); } /** * 获取某个商品类别下的子类别中最大的排序序号 * @param parentId * @return */ public int getMaxOrderByParentId(Long parentId) { Map<String, Object> params = new HashMap<>(); params.put("parentId", parentId); // Map<String, Object> data = findData(MAPPER_NAMESPACE + ".selectMaxOrderByParentId", params); // if (data == null) { // return 0; // } // // Object maxOrder = data.get("maxOrder"); // if (maxOrder == null) { // return 0; // } else { // return Integer.parseInt(maxOrder.toString()); // } Integer maxOrder = super.findOneObject(MAPPER_NAMESPACE + ".selectMaxOrderByParentId", params); return null == maxOrder ? 0 : maxOrder; } /** * 交换两个商品类别的排序序号 * @param id1 * @param id2 * @return */ public int swapOrder(Long id1, Long id2) { Map<String, Object> params = new HashMap<>(); params.put("id1", id1); params.put("id2", id2); return update(MAPPER_NAMESPACE + ".swapOrder", params); } }
UTF-8
Java
3,896
java
DealCategoryDAO.java
Java
[]
null
[]
package com.tortuousroad.groupon.deal.dao; import com.tortuousroad.groupon.deal.constant.DealConstant; import com.tortuousroad.groupon.deal.entity.DealCategory; import com.tortuousroad.framework.common.page.PagingResult; import com.tortuousroad.framework.common.persistence.BaseMybatisDAO; import com.tortuousroad.framework.common.search.Search; import org.springframework.stereotype.Repository; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Deal分类 */ @Repository public class DealCategoryDAO extends BaseMybatisDAO { /** * Mapper映射命名空间 */ private static final String MAPPER_NAMESPACE = "com.tortuousroad.groupon.deal.entity.DealCategoryMapper"; /** * 查询所有未删除的商品类别 * @return */ public List<DealCategory> getAllWithoutDeleted() { return super.findAll(MAPPER_NAMESPACE + ".selectAllWithoutDeleted", DealConstant.DEAL_PUBLISH_STATUS_DELETED); } /** * 查询直接下级 * @param parentId * @return */ public List<DealCategory> getDirectSubs(Long parentId) { Map<String, Object> params = new HashMap<>(); params.put("publishStatus", DealConstant.DEAL_PUBLISH_STATUS_DELETED); params.put("parentId", parentId); return findAll(MAPPER_NAMESPACE + ".selectDirectSubs", params); } /** * 根据ID查询 * @param id * @return */ public DealCategory getById(Long id) { return findOne(MAPPER_NAMESPACE + ".selectByPrimaryKey", id); } /** * 分页查询 * @param search * @return */ public PagingResult<DealCategory> getPageCategories(Search search) { return findForPage(MAPPER_NAMESPACE + ".countPageCategories", MAPPER_NAMESPACE + ".selectPageCategories", search); } /** * 更新 * @param category * @return */ public int updateById(DealCategory category) { return update(MAPPER_NAMESPACE + ".updateByPrimaryKeySelective", category); } /** * 保存 * @param category * @return */ public int save(DealCategory category) { return save(MAPPER_NAMESPACE + ".insertSelective", category); } /** * 根据ID删除 * @param id * @return */ public int deleteById(Long id) { return delete(MAPPER_NAMESPACE + ".deleteByPrimaryKey", id); } /** * 根据urlName查询 * @param urlName * @return */ public DealCategory getByUrlName(String urlName) { Map<String, Object> params = new HashMap<String, Object>(); params.put("urlName", urlName); return findOne(MAPPER_NAMESPACE + ".selectByUrlName", params); } /** * 获取某个商品类别下的子类别中最大的排序序号 * @param parentId * @return */ public int getMaxOrderByParentId(Long parentId) { Map<String, Object> params = new HashMap<>(); params.put("parentId", parentId); // Map<String, Object> data = findData(MAPPER_NAMESPACE + ".selectMaxOrderByParentId", params); // if (data == null) { // return 0; // } // // Object maxOrder = data.get("maxOrder"); // if (maxOrder == null) { // return 0; // } else { // return Integer.parseInt(maxOrder.toString()); // } Integer maxOrder = super.findOneObject(MAPPER_NAMESPACE + ".selectMaxOrderByParentId", params); return null == maxOrder ? 0 : maxOrder; } /** * 交换两个商品类别的排序序号 * @param id1 * @param id2 * @return */ public int swapOrder(Long id1, Long id2) { Map<String, Object> params = new HashMap<>(); params.put("id1", id1); params.put("id2", id2); return update(MAPPER_NAMESPACE + ".swapOrder", params); } }
3,896
0.619914
0.61697
138
26.072464
27.466618
122
false
false
0
0
0
0
0
0
0.449275
false
false
5
0f137b6245ec281faa0c79c1c510825f4eb6789f
27,986,006,923,650
d88d374a8ed393a11a83fd0fe590c5dd9713d91c
/gwtTest/gwtTest-server/src/main/java/com/ajs/service/payment/LoadPaymentDetailService.java
5976c6a07d7529d31c661f00cdad9b513b734e58
[]
no_license
andyuser727/blah
https://github.com/andyuser727/blah
81cfd82402b6bdb8566c23524c743a0a0ae33f1f
877946dfe2ee2bb0af9d53746198acb64bd62fda
refs/heads/master
2021-01-22T22:56:58.129000
2014-10-11T12:17:59
2014-10-11T12:17:59
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ajs.service.payment; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import com.ajs.dao.PaymentDao; import com.ajs.dao.PaymentInvoiceAllocationDao; import com.ajs.domain.Payment; import com.ajs.domain.PaymentInvoiceAllocation; import com.ajs.service.Handler; import com.ajs.shared.AppResponse; import com.ajs.shared.commands.payment.LoadPaymentDetail; import com.ajs.shared.dto.payment.PaymentDetailDto; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; @SuppressWarnings("serial") @Component @Transactional public class LoadPaymentDetailService implements Handler<LoadPaymentDetail> { @Autowired PaymentDao paymentDao; @Autowired PaymentInvoiceAllocationDao paymentInvoiceAllocationDao; public AppResponse execute(LoadPaymentDetail dto) throws IllegalArgumentException { AppResponse response = new AppResponse(); Payment payment = paymentDao.find(dto.getPaymentId()); PaymentDetailDto paymentDetailDto = new PaymentDetailDto(); paymentDetailDto.setCustomerReference(payment.getCustomerReference()); paymentDetailDto.setDescription(payment.getDescription()); paymentDetailDto.setPaymentNumber(payment.getPaymentNumber()); paymentDetailDto.setPaymentDate(payment.getPaymentDate()); paymentDetailDto.setTotalAmount(payment.getTotalAmount()); if (payment.getCustomer() != null) { paymentDetailDto.setCustomerId(payment.getCustomer().getId()); } paymentDetailDto.setId(payment.getId()); // TODO CHANGE List<PaymentInvoiceAllocation> paymentInvoiceAllocations = paymentInvoiceAllocationDao.findByPaymentId(payment.getId()); BigDecimal amountAllocated = new BigDecimal("0"); if (paymentInvoiceAllocations != null){ for (PaymentInvoiceAllocation paymentInvoiceAllocation : paymentInvoiceAllocations){ amountAllocated = amountAllocated.add(paymentInvoiceAllocation.getAllocatedAmount() == null ? new BigDecimal("0") : paymentInvoiceAllocation.getAllocatedAmount()) ; } } paymentDetailDto.setRemainingAmount(payment.getTotalAmount().subtract(amountAllocated)); paymentDetailDto.setAllocatedAmount(amountAllocated); List<PaymentDetailDto> paymentDetailDtos = new ArrayList<PaymentDetailDto>(); paymentDetailDtos.add(paymentDetailDto); response.setDtos(paymentDetailDtos); return response; } public Class getIncomingCommandClass() { return LoadPaymentDetail.class; } }
UTF-8
Java
2,716
java
LoadPaymentDetailService.java
Java
[]
null
[]
package com.ajs.service.payment; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import com.ajs.dao.PaymentDao; import com.ajs.dao.PaymentInvoiceAllocationDao; import com.ajs.domain.Payment; import com.ajs.domain.PaymentInvoiceAllocation; import com.ajs.service.Handler; import com.ajs.shared.AppResponse; import com.ajs.shared.commands.payment.LoadPaymentDetail; import com.ajs.shared.dto.payment.PaymentDetailDto; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; @SuppressWarnings("serial") @Component @Transactional public class LoadPaymentDetailService implements Handler<LoadPaymentDetail> { @Autowired PaymentDao paymentDao; @Autowired PaymentInvoiceAllocationDao paymentInvoiceAllocationDao; public AppResponse execute(LoadPaymentDetail dto) throws IllegalArgumentException { AppResponse response = new AppResponse(); Payment payment = paymentDao.find(dto.getPaymentId()); PaymentDetailDto paymentDetailDto = new PaymentDetailDto(); paymentDetailDto.setCustomerReference(payment.getCustomerReference()); paymentDetailDto.setDescription(payment.getDescription()); paymentDetailDto.setPaymentNumber(payment.getPaymentNumber()); paymentDetailDto.setPaymentDate(payment.getPaymentDate()); paymentDetailDto.setTotalAmount(payment.getTotalAmount()); if (payment.getCustomer() != null) { paymentDetailDto.setCustomerId(payment.getCustomer().getId()); } paymentDetailDto.setId(payment.getId()); // TODO CHANGE List<PaymentInvoiceAllocation> paymentInvoiceAllocations = paymentInvoiceAllocationDao.findByPaymentId(payment.getId()); BigDecimal amountAllocated = new BigDecimal("0"); if (paymentInvoiceAllocations != null){ for (PaymentInvoiceAllocation paymentInvoiceAllocation : paymentInvoiceAllocations){ amountAllocated = amountAllocated.add(paymentInvoiceAllocation.getAllocatedAmount() == null ? new BigDecimal("0") : paymentInvoiceAllocation.getAllocatedAmount()) ; } } paymentDetailDto.setRemainingAmount(payment.getTotalAmount().subtract(amountAllocated)); paymentDetailDto.setAllocatedAmount(amountAllocated); List<PaymentDetailDto> paymentDetailDtos = new ArrayList<PaymentDetailDto>(); paymentDetailDtos.add(paymentDetailDto); response.setDtos(paymentDetailDtos); return response; } public Class getIncomingCommandClass() { return LoadPaymentDetail.class; } }
2,716
0.755155
0.754418
73
36.19178
34.77586
180
false
false
0
0
0
0
0
0
0.506849
false
false
5
173675fa5168ad8b12a5676e693fdadc5420a56e
16,638,703,371,413
9a58af6bbc99b7e9a663ed24697a98a397eb9b69
/src/superkeyword_uses/Child.java
5d8091a9dfdfc1b217b8209e051848c0b09b70a4
[]
no_license
vasantidatta/JavaProject
https://github.com/vasantidatta/JavaProject
e8c0caa240b2bbafd420cabb5da13e0694e3c4e2
cfd708bf95ba3ef744ce064e1a1514c0982d718c
refs/heads/master
2023-03-29T15:48:21.934000
2021-03-27T20:22:00
2021-03-27T20:22:00
351,219,323
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package superkeyword_uses; public class Child extends Mom { int num = 110; public void display() { //System.out.println("Num value = "+num); System.out.println("Num value = "+super.num); } public static void main(String[] args) { Child kid = new Child(); kid.display(); } }
UTF-8
Java
312
java
Child.java
Java
[]
null
[]
package superkeyword_uses; public class Child extends Mom { int num = 110; public void display() { //System.out.println("Num value = "+num); System.out.println("Num value = "+super.num); } public static void main(String[] args) { Child kid = new Child(); kid.display(); } }
312
0.608974
0.599359
22
13.136364
15.96102
47
false
false
0
0
0
0
0
0
1.409091
false
false
5
bc35f6ed057186b23410613207448fec8a50d2eb
28,338,194,224,163
f34379a5c6a57c086b6213ed3490d658b916f6d0
/src/main/java/com/springmvc/imp/MyTimerService.java
a7078430d9d16d5859276b88469aa914fab1d0dd
[]
no_license
xzm1102207843/JavaSSMDemo
https://github.com/xzm1102207843/JavaSSMDemo
8e8736b8823481f495c1cf2cb3d2553a50c4a1f6
86e3009152d20830f3ef7664c5deb7a224374bc4
refs/heads/master
2018-02-08T18:09:48.283000
2017-08-18T05:18:00
2017-08-18T05:18:00
95,101,374
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.springmvc.imp; /** * Created by xuzongmeng on 2017/7/13. */ public interface MyTimerService { void runTime(); }
UTF-8
Java
135
java
MyTimerService.java
Java
[ { "context": "package com.springmvc.imp;\n\n/**\n * Created by xuzongmeng on 2017/7/13.\n */\npublic interface MyTimerService", "end": 56, "score": 0.9994639158248901, "start": 46, "tag": "USERNAME", "value": "xuzongmeng" } ]
null
[]
package com.springmvc.imp; /** * Created by xuzongmeng on 2017/7/13. */ public interface MyTimerService { void runTime(); }
135
0.666667
0.614815
8
15.875
14.751589
38
false
false
0
0
0
0
0
0
0.25
false
false
5
9159b1e541a84771bea95e1e1d8a0185a4934608
4,294,967,345,095
ab21bfa35db1295d5fceb438f933125faef27c43
/app/src/main/java/com/example/seecloud/RankActivity.java
8adc68a3cd781041a0029aa282ec89bc2050ba61
[ "Apache-2.0" ]
permissive
Edward-Chow/SeeCloud
https://github.com/Edward-Chow/SeeCloud
52273e8de5ffbfb965c1811ff8b27cfb6c116b28
95b39c69489990456d3d6f6485a689c3f87d6343
refs/heads/master
2021-06-13T05:13:19.285000
2017-04-15T00:57:24
2017-04-15T00:57:24
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.seecloud; import android.content.Intent; import android.os.Build; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Toast; import com.example.seecloud.database.Attribute; import com.example.seecloud.database.CloudServer; import com.example.seecloud.database.InitCloudServer; import java.util.ArrayList; import java.util.List; public class RankActivity extends AppCompatActivity { private DrawerLayout drawerLayout; private Attribute attributes[]; private List<Attribute> attributeList = new ArrayList<>(); private AttributeAdapter adapter; private List<CloudServer> cloudServers = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_rank); //设置沉浸式状态栏 if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) { Window window = this.getWindow(); window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark, this.getTheme())); } Toolbar toolbar = (Toolbar) findViewById(R.id.rank_toolbar); setSupportActionBar(toolbar); initAttributes(); InitCloudServer initCloudServer = new InitCloudServer(); cloudServers.addAll(initCloudServer.getClouds()); RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view); GridLayoutManager layoutManager = new GridLayoutManager(this, 2); recyclerView.setLayoutManager(layoutManager); adapter = new AttributeAdapter(attributeList); adapter.setOnItemClickListener(new AttributeAdapter.OnItemClickListener() { @Override public void onItemClick(View view, int position) { String name = attributeList.get(position).getName(); double[] numbers = new double[13]; Intent intent; switch (name) { case "建联时间": int k = 0; for (CloudServer cloud:cloudServers) { numbers[k++] = cloud.getAttributes().get(0).getNumber(); } intent = new Intent(RankActivity.this, ChartActivity.class); intent.putExtra("index", numbers); intent.putExtra("name", "建联时间"); startActivity(intent); break; case "首包时间": numbers = function(cloudServers, 1); intent = new Intent(RankActivity.this, ChartActivity.class); intent.putExtra("index", numbers); intent.putExtra("name", "首包时间"); startActivity(intent); break; case "首屏时间": numbers = function(cloudServers, 2); intent = new Intent(RankActivity.this, ChartActivity.class); intent.putExtra("index", numbers); intent.putExtra("name", "首屏时间"); startActivity(intent); break; case "总下载时间": numbers = function(cloudServers, 3); intent = new Intent(RankActivity.this, ChartActivity.class); intent.putExtra("index", numbers); intent.putExtra("name", "总下载时间"); startActivity(intent); break; case "应用服务器响应时间": numbers = function(cloudServers, 4); intent = new Intent(RankActivity.this, ChartActivity.class); intent.putExtra("index", numbers); intent.putExtra("name", "应用服务器响应时间"); startActivity(intent); break; case "CPU使用率": numbers = function(cloudServers, 5); intent = new Intent(RankActivity.this, ChartActivity.class); intent.putExtra("index", numbers); intent.putExtra("name", "CPU使用率"); startActivity(intent); break; case "数据库调用时间": numbers = function(cloudServers, 6); intent = new Intent(RankActivity.this, ChartActivity.class); intent.putExtra("index", numbers); intent.putExtra("name", "数据库调用时间"); startActivity(intent); break; case "Apdex指标": numbers = function(cloudServers, 7); intent = new Intent(RankActivity.this, ChartActivity.class); intent.putExtra("index", numbers); intent.putExtra("name", "Apdex指标"); startActivity(intent); break; case "服务器内存占用": numbers = function(cloudServers, 8); intent = new Intent(RankActivity.this, ChartActivity.class); intent.putExtra("index", numbers); intent.putExtra("name", "服务器内存占用"); startActivity(intent); break; case "听云综合排行": numbers = function(cloudServers, 9); intent = new Intent(RankActivity.this, ChartActivity.class); intent.putExtra("index", numbers); intent.putExtra("name", "听云综合排行"); startActivity(intent); break; default: break; } } }); adapter.setOnItemLongClickListener(new AttributeAdapter.OnItemLongClickListener() { @Override public void onItemLongClick(View view, int position) { String name = attributeList.get(position).getName(); double[] numbers = new double[13]; Intent intent; switch (name) { case "建联时间": int k = 0; for (CloudServer cloud:cloudServers) { numbers[k++] = cloud.getAttributes().get(0).getNumber(); } intent = new Intent(RankActivity.this, ChartActivity.class); intent.putExtra("index", numbers); intent.putExtra("name", "建联时间"); startActivity(intent); break; case "首包时间": numbers = function(cloudServers, 1); intent = new Intent(RankActivity.this, ChartActivity.class); intent.putExtra("index", numbers); intent.putExtra("name", "首包时间"); startActivity(intent); break; case "首屏时间": numbers = function(cloudServers, 2); intent = new Intent(RankActivity.this, ChartActivity.class); intent.putExtra("index", numbers); intent.putExtra("name", "首屏时间"); startActivity(intent); break; case "总下载时间": numbers = function(cloudServers, 3); intent = new Intent(RankActivity.this, ChartActivity.class); intent.putExtra("index", numbers); intent.putExtra("name", "总下载时间"); startActivity(intent); break; case "应用服务器响应时间": numbers = function(cloudServers, 4); intent = new Intent(RankActivity.this, ChartActivity.class); intent.putExtra("index", numbers); intent.putExtra("name", "应用服务器响应时间"); startActivity(intent); break; case "CPU使用率": numbers = function(cloudServers, 5); intent = new Intent(RankActivity.this, ChartActivity.class); intent.putExtra("index", numbers); intent.putExtra("name", "CPU使用率"); startActivity(intent); break; case "数据库调用时间": numbers = function(cloudServers, 6); intent = new Intent(RankActivity.this, ChartActivity.class); intent.putExtra("index", numbers); intent.putExtra("name", "数据库调用时间"); startActivity(intent); break; case "Apdex指标": numbers = function(cloudServers, 7); intent = new Intent(RankActivity.this, ChartActivity.class); intent.putExtra("index", numbers); intent.putExtra("name", "Apdex指标"); startActivity(intent); break; case "服务器内存占用": numbers = function(cloudServers, 8); intent = new Intent(RankActivity.this, ChartActivity.class); intent.putExtra("index", numbers); intent.putExtra("name", "服务器内存占用"); startActivity(intent); break; case "听云综合排行": numbers = function(cloudServers, 9); intent = new Intent(RankActivity.this, ChartActivity.class); intent.putExtra("index", numbers); intent.putExtra("name", "听云综合排行"); startActivity(intent); break; default: break; } } }); recyclerView.setAdapter(adapter); } private double[] function(List<CloudServer> cloudservers, int k) { double[] numbers = new double[13]; int m = 0; for (int i = 0; i < numbers.length; i++) { numbers[i] = cloudServers.get(i).getAttributes().get(k).getNumber(); } /*for (CloudServer cloud:cloudServers) { numbers[m] = cloud.getAttributes().get(k).getNumber(); m++; }*/ return numbers; } private void initAttributes() { //数据初始化 Attribute attributes[] = { new Attribute("建联时间", R.drawable.connectingtime), new Attribute("首包时间", R.drawable.firstpackagetime), new Attribute("首屏时间", R.drawable.firstscreentime), new Attribute("总下载时间", R.drawable.totaldownloadtime), new Attribute("应用服务器响应时间", R.drawable.applicationserverresponsetime), new Attribute("CPU使用率", R.drawable.cpuusage), new Attribute("数据库调用时间", R.drawable.databasecallingtime), new Attribute("Apdex指标", R.drawable.apdex), new Attribute("服务器内存占用", R.drawable.servermemorytakeup), new Attribute("听云综合排行", R.drawable.tingyuncomprehensiveranking) }; for (Attribute attr: attributes) { attributeList.add(attr); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.toolbar, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.id_back) { Intent intent = new Intent(RankActivity.this, MainActivity.class); startActivity(intent); RankActivity.this.finish(); return true; } return false; } }
UTF-8
Java
13,328
java
RankActivity.java
Java
[]
null
[]
package com.example.seecloud; import android.content.Intent; import android.os.Build; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Toast; import com.example.seecloud.database.Attribute; import com.example.seecloud.database.CloudServer; import com.example.seecloud.database.InitCloudServer; import java.util.ArrayList; import java.util.List; public class RankActivity extends AppCompatActivity { private DrawerLayout drawerLayout; private Attribute attributes[]; private List<Attribute> attributeList = new ArrayList<>(); private AttributeAdapter adapter; private List<CloudServer> cloudServers = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_rank); //设置沉浸式状态栏 if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) { Window window = this.getWindow(); window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark, this.getTheme())); } Toolbar toolbar = (Toolbar) findViewById(R.id.rank_toolbar); setSupportActionBar(toolbar); initAttributes(); InitCloudServer initCloudServer = new InitCloudServer(); cloudServers.addAll(initCloudServer.getClouds()); RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view); GridLayoutManager layoutManager = new GridLayoutManager(this, 2); recyclerView.setLayoutManager(layoutManager); adapter = new AttributeAdapter(attributeList); adapter.setOnItemClickListener(new AttributeAdapter.OnItemClickListener() { @Override public void onItemClick(View view, int position) { String name = attributeList.get(position).getName(); double[] numbers = new double[13]; Intent intent; switch (name) { case "建联时间": int k = 0; for (CloudServer cloud:cloudServers) { numbers[k++] = cloud.getAttributes().get(0).getNumber(); } intent = new Intent(RankActivity.this, ChartActivity.class); intent.putExtra("index", numbers); intent.putExtra("name", "建联时间"); startActivity(intent); break; case "首包时间": numbers = function(cloudServers, 1); intent = new Intent(RankActivity.this, ChartActivity.class); intent.putExtra("index", numbers); intent.putExtra("name", "首包时间"); startActivity(intent); break; case "首屏时间": numbers = function(cloudServers, 2); intent = new Intent(RankActivity.this, ChartActivity.class); intent.putExtra("index", numbers); intent.putExtra("name", "首屏时间"); startActivity(intent); break; case "总下载时间": numbers = function(cloudServers, 3); intent = new Intent(RankActivity.this, ChartActivity.class); intent.putExtra("index", numbers); intent.putExtra("name", "总下载时间"); startActivity(intent); break; case "应用服务器响应时间": numbers = function(cloudServers, 4); intent = new Intent(RankActivity.this, ChartActivity.class); intent.putExtra("index", numbers); intent.putExtra("name", "应用服务器响应时间"); startActivity(intent); break; case "CPU使用率": numbers = function(cloudServers, 5); intent = new Intent(RankActivity.this, ChartActivity.class); intent.putExtra("index", numbers); intent.putExtra("name", "CPU使用率"); startActivity(intent); break; case "数据库调用时间": numbers = function(cloudServers, 6); intent = new Intent(RankActivity.this, ChartActivity.class); intent.putExtra("index", numbers); intent.putExtra("name", "数据库调用时间"); startActivity(intent); break; case "Apdex指标": numbers = function(cloudServers, 7); intent = new Intent(RankActivity.this, ChartActivity.class); intent.putExtra("index", numbers); intent.putExtra("name", "Apdex指标"); startActivity(intent); break; case "服务器内存占用": numbers = function(cloudServers, 8); intent = new Intent(RankActivity.this, ChartActivity.class); intent.putExtra("index", numbers); intent.putExtra("name", "服务器内存占用"); startActivity(intent); break; case "听云综合排行": numbers = function(cloudServers, 9); intent = new Intent(RankActivity.this, ChartActivity.class); intent.putExtra("index", numbers); intent.putExtra("name", "听云综合排行"); startActivity(intent); break; default: break; } } }); adapter.setOnItemLongClickListener(new AttributeAdapter.OnItemLongClickListener() { @Override public void onItemLongClick(View view, int position) { String name = attributeList.get(position).getName(); double[] numbers = new double[13]; Intent intent; switch (name) { case "建联时间": int k = 0; for (CloudServer cloud:cloudServers) { numbers[k++] = cloud.getAttributes().get(0).getNumber(); } intent = new Intent(RankActivity.this, ChartActivity.class); intent.putExtra("index", numbers); intent.putExtra("name", "建联时间"); startActivity(intent); break; case "首包时间": numbers = function(cloudServers, 1); intent = new Intent(RankActivity.this, ChartActivity.class); intent.putExtra("index", numbers); intent.putExtra("name", "首包时间"); startActivity(intent); break; case "首屏时间": numbers = function(cloudServers, 2); intent = new Intent(RankActivity.this, ChartActivity.class); intent.putExtra("index", numbers); intent.putExtra("name", "首屏时间"); startActivity(intent); break; case "总下载时间": numbers = function(cloudServers, 3); intent = new Intent(RankActivity.this, ChartActivity.class); intent.putExtra("index", numbers); intent.putExtra("name", "总下载时间"); startActivity(intent); break; case "应用服务器响应时间": numbers = function(cloudServers, 4); intent = new Intent(RankActivity.this, ChartActivity.class); intent.putExtra("index", numbers); intent.putExtra("name", "应用服务器响应时间"); startActivity(intent); break; case "CPU使用率": numbers = function(cloudServers, 5); intent = new Intent(RankActivity.this, ChartActivity.class); intent.putExtra("index", numbers); intent.putExtra("name", "CPU使用率"); startActivity(intent); break; case "数据库调用时间": numbers = function(cloudServers, 6); intent = new Intent(RankActivity.this, ChartActivity.class); intent.putExtra("index", numbers); intent.putExtra("name", "数据库调用时间"); startActivity(intent); break; case "Apdex指标": numbers = function(cloudServers, 7); intent = new Intent(RankActivity.this, ChartActivity.class); intent.putExtra("index", numbers); intent.putExtra("name", "Apdex指标"); startActivity(intent); break; case "服务器内存占用": numbers = function(cloudServers, 8); intent = new Intent(RankActivity.this, ChartActivity.class); intent.putExtra("index", numbers); intent.putExtra("name", "服务器内存占用"); startActivity(intent); break; case "听云综合排行": numbers = function(cloudServers, 9); intent = new Intent(RankActivity.this, ChartActivity.class); intent.putExtra("index", numbers); intent.putExtra("name", "听云综合排行"); startActivity(intent); break; default: break; } } }); recyclerView.setAdapter(adapter); } private double[] function(List<CloudServer> cloudservers, int k) { double[] numbers = new double[13]; int m = 0; for (int i = 0; i < numbers.length; i++) { numbers[i] = cloudServers.get(i).getAttributes().get(k).getNumber(); } /*for (CloudServer cloud:cloudServers) { numbers[m] = cloud.getAttributes().get(k).getNumber(); m++; }*/ return numbers; } private void initAttributes() { //数据初始化 Attribute attributes[] = { new Attribute("建联时间", R.drawable.connectingtime), new Attribute("首包时间", R.drawable.firstpackagetime), new Attribute("首屏时间", R.drawable.firstscreentime), new Attribute("总下载时间", R.drawable.totaldownloadtime), new Attribute("应用服务器响应时间", R.drawable.applicationserverresponsetime), new Attribute("CPU使用率", R.drawable.cpuusage), new Attribute("数据库调用时间", R.drawable.databasecallingtime), new Attribute("Apdex指标", R.drawable.apdex), new Attribute("服务器内存占用", R.drawable.servermemorytakeup), new Attribute("听云综合排行", R.drawable.tingyuncomprehensiveranking) }; for (Attribute attr: attributes) { attributeList.add(attr); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.toolbar, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.id_back) { Intent intent = new Intent(RankActivity.this, MainActivity.class); startActivity(intent); RankActivity.this.finish(); return true; } return false; } }
13,328
0.5043
0.501485
283
44.201412
23.692339
105
false
false
0
0
0
0
0
0
1.038869
false
false
5
e11c4656340407dd52972761db42f20105c22168
28,037,546,512,350
c61d0f5990151af824d92697c0b03bec44ba25dc
/src/main/java/cn/com/qiqi/order/web/system/service/ConfigurationService.java
0a4484981da74547e482871e0325a37cbd8fb538
[]
no_license
home45006/order-web
https://github.com/home45006/order-web
930c0dee7ba852669b3b877d1ebe176ce4474a09
1f7e43e4e87871d205f4456e1dc80e6117d58ef3
refs/heads/master
2016-09-05T10:06:53.174000
2015-03-17T16:50:19
2015-03-17T16:50:40
32,406,066
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package cn.com.qiqi.order.web.system.service; import java.util.List; import cn.com.qiqi.order.entity.common.Configuration; import cn.com.qiqi.order.service.EntityService; /** * @Description TODO * @author wuhui * @date 2013-5-2下午1:42:29 * */ public interface ConfigurationService extends EntityService<Configuration, Long> { List<Configuration> findConfigurationByStatus(Boolean status); List<Configuration> findConfigurationByType(String type); void deleteByType(String type); Configuration findByParamKey(String ermName); }
UTF-8
Java
591
java
ConfigurationService.java
Java
[ { "context": "yService;\r\n\r\n/**\r\n * @Description TODO\r\n * @author wuhui\r\n * @date 2013-5-2下午1:42:29\r\n *\r\n */\r\npublic inte", "end": 239, "score": 0.9993865489959717, "start": 234, "tag": "USERNAME", "value": "wuhui" } ]
null
[]
/** * */ package cn.com.qiqi.order.web.system.service; import java.util.List; import cn.com.qiqi.order.entity.common.Configuration; import cn.com.qiqi.order.service.EntityService; /** * @Description TODO * @author wuhui * @date 2013-5-2下午1:42:29 * */ public interface ConfigurationService extends EntityService<Configuration, Long> { List<Configuration> findConfigurationByStatus(Boolean status); List<Configuration> findConfigurationByType(String type); void deleteByType(String type); Configuration findByParamKey(String ermName); }
591
0.725724
0.706985
29
18.241379
23.822121
82
false
false
0
0
0
0
0
0
0.482759
false
false
5
75b0e11f2ced2625600b66be75d3c5f8f72d7bf3
23,742,579,271,266
1aafa630a9c37d41a1e9101597811fba63d0fb29
/FileReadTask5.java
e315713f6ddae0b6865124d2ab463f2fc6d9c75f
[]
no_license
arjun541/Assignment-3.2
https://github.com/arjun541/Assignment-3.2
f1fddbf435223e044bfe43e391bffe4e0c9763c7
4c1915cff2f13902ca48e0a82fc5a4011288e67a
refs/heads/master
2020-04-06T04:07:04.511000
2017-02-25T08:02:34
2017-02-25T08:02:34
83,040,913
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.demo; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IOUtils; public class FileReadTask5 { public static void main(String[] args) { Path path=null; if(args.length!=1) { System.out.println("please enter the atleast one parameter as fully qualified path for file"); System.exit(0); } path=new Path(args[0]); FSDataInputStream in=null; try { Configuration conf=new Configuration(); FileSystem fs=FileSystem.get(path.toUri(),conf); if(fs.exists(path)) { if(fs.isFile(path)) { in=fs.open(path); IOUtils.copyBytes(in, System.out, 4096); System.out.println("End of file reached here"); } else { System.out.println("please enter the file not directory"); } } else { System.out.println("File Doesnot exists"); } } catch(Exception e) { } } }
UTF-8
Java
1,340
java
FileReadTask5.java
Java
[]
null
[]
package com.demo; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IOUtils; public class FileReadTask5 { public static void main(String[] args) { Path path=null; if(args.length!=1) { System.out.println("please enter the atleast one parameter as fully qualified path for file"); System.exit(0); } path=new Path(args[0]); FSDataInputStream in=null; try { Configuration conf=new Configuration(); FileSystem fs=FileSystem.get(path.toUri(),conf); if(fs.exists(path)) { if(fs.isFile(path)) { in=fs.open(path); IOUtils.copyBytes(in, System.out, 4096); System.out.println("End of file reached here"); } else { System.out.println("please enter the file not directory"); } } else { System.out.println("File Doesnot exists"); } } catch(Exception e) { } } }
1,340
0.5
0.49403
56
22.928572
20.928328
106
false
false
0
0
0
0
0
0
0.375
false
false
5
7ca1d93f2da93241619bc6a647e9c821f131058a
30,296,699,355,529
389eecc3b23abbbc8b689b2e9ecba8cec6921969
/app/src/main/java/com/bayer/bayerreward/GetterSetter/FolderList.java
6b4f9448de08fef570fe8fe11bb6d6e911239428
[]
no_license
JGSPL/BayerRewards
https://github.com/JGSPL/BayerRewards
7bbb9c59d8866107928742a37f68f387f4b0af8a
998125fee21b603759b1f86a7673a494335f46ee
refs/heads/master
2023-03-03T19:32:51.763000
2021-02-16T09:53:50
2021-02-16T09:53:50
322,269,108
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bayer.bayerreward.GetterSetter; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.io.Serializable; /** * Created by Naushad on 12/27/2017. */ public class FolderList implements Serializable { @SerializedName("folder_name") @Expose private String folderName; @SerializedName("folder_image") @Expose private String folderImage; public String getFolderName() { return folderName; } public void setFolderName(String folderName) { this.folderName = folderName; } public String getFolderImage() { return folderImage; } public void setFolderImage(String folderImage) { this.folderImage = folderImage; } }
UTF-8
Java
765
java
FolderList.java
Java
[ { "context": ";\n\nimport java.io.Serializable;\n\n/**\n * Created by Naushad on 12/27/2017.\n */\n\npublic class FolderList imple", "end": 195, "score": 0.9775241017341614, "start": 188, "tag": "USERNAME", "value": "Naushad" } ]
null
[]
package com.bayer.bayerreward.GetterSetter; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.io.Serializable; /** * Created by Naushad on 12/27/2017. */ public class FolderList implements Serializable { @SerializedName("folder_name") @Expose private String folderName; @SerializedName("folder_image") @Expose private String folderImage; public String getFolderName() { return folderName; } public void setFolderName(String folderName) { this.folderName = folderName; } public String getFolderImage() { return folderImage; } public void setFolderImage(String folderImage) { this.folderImage = folderImage; } }
765
0.696732
0.686275
36
20.25
18.600142
52
false
false
0
0
0
0
0
0
0.277778
false
false
5
caa5508579112f5d3f221de400646ff7d0e6dc7b
22,419,729,345,671
c1e91087fb685aa0a86d3a9f0e83eb61da28002f
/robot/src/application/Dictionary.java
fec087720f846cf142b11119b17d8316480723da
[]
no_license
myomyintaung3535/fx-projects
https://github.com/myomyintaung3535/fx-projects
b4a066935684eb0127e01a1600e2d0ceb72c7175
25e8223c60e677192fb7f1a02a073b1f68367ebd
refs/heads/master
2022-11-05T15:59:40.780000
2020-06-17T09:50:06
2020-06-17T09:50:06
271,249,721
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package application; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.HashMap; import java.util.Map; public class Dictionary { private Map<String, String> database; private static final String FILE = "data.obj"; @SuppressWarnings("unchecked") public Dictionary() { database = new HashMap<>(); try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(FILE))) { database = (Map<String, String>) in.readObject(); } catch (Exception e) { e.printStackTrace(); } } public String checkAnswer(String word) { return database.get(word); } public void saveToDatabase(String vocabulary, String word) { database.put(vocabulary, word); try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(FILE))) { out.writeObject(database); } catch (Exception e) { e.printStackTrace(); } } }
UTF-8
Java
946
java
Dictionary.java
Java
[]
null
[]
package application; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.HashMap; import java.util.Map; public class Dictionary { private Map<String, String> database; private static final String FILE = "data.obj"; @SuppressWarnings("unchecked") public Dictionary() { database = new HashMap<>(); try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(FILE))) { database = (Map<String, String>) in.readObject(); } catch (Exception e) { e.printStackTrace(); } } public String checkAnswer(String word) { return database.get(word); } public void saveToDatabase(String vocabulary, String word) { database.put(vocabulary, word); try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(FILE))) { out.writeObject(database); } catch (Exception e) { e.printStackTrace(); } } }
946
0.734672
0.734672
39
23.256411
21.549845
85
false
false
0
0
0
0
0
0
1.51282
false
false
5
066d1233c7f97c097796951f3295d668c8efaffa
21,973,052,687,000
fb58953a05c8a4ad6d9810aa71f7317c367a1cf3
/app/src/main/java/in/anukool/dagger2app/di/component/ActivityComponent.java
578fa75e9956ff996b1bd9dfbf66d6cb8b69f364
[]
no_license
anukools/Dagger2App
https://github.com/anukools/Dagger2App
38eb9ead946ce4a77cbe246b3ba547ded17b1750
4d6870ee56c6de3b58c963fe88ee23d81df6e47a
refs/heads/master
2020-03-11T19:13:50.819000
2018-04-19T10:43:03
2018-04-19T10:43:03
130,200,999
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package in.anukool.dagger2app.di.component; import dagger.Component; import in.anukool.dagger2app.MainActivity; import in.anukool.dagger2app.di.PerActivity; import in.anukool.dagger2app.di.module.ActivityModule; /** * Created by Anukool Srivastav on 30/03/18. */ @PerActivity @Component(dependencies = ApplicationComponent.class, modules = ActivityModule.class) public interface ActivityComponent { void inject(MainActivity mainActivity); }
UTF-8
Java
452
java
ActivityComponent.java
Java
[ { "context": "r2app.di.module.ActivityModule;\n\n/**\n * Created by Anukool Srivastav on 30/03/18.\n */\n\n@PerActivity\n@Component(depende", "end": 249, "score": 0.999870240688324, "start": 232, "tag": "NAME", "value": "Anukool Srivastav" } ]
null
[]
package in.anukool.dagger2app.di.component; import dagger.Component; import in.anukool.dagger2app.MainActivity; import in.anukool.dagger2app.di.PerActivity; import in.anukool.dagger2app.di.module.ActivityModule; /** * Created by <NAME> on 30/03/18. */ @PerActivity @Component(dependencies = ApplicationComponent.class, modules = ActivityModule.class) public interface ActivityComponent { void inject(MainActivity mainActivity); }
441
0.800885
0.778761
18
24.111111
24.772047
85
false
false
0
0
0
0
0
0
0.388889
false
false
5
3895a6a3e58135cf79c984258e9ba4f9eca44c99
7,361,574,012,095
93c213af1c018d8d0522eaedc6df8f953655796b
/web/src/test/java/com/lemosen/web/WebApplicationTests.java
137ca1ea7d75ad7c5a1e413cfda8fd67c462b9ec
[]
no_license
lemosen/lemosen
https://github.com/lemosen/lemosen
6efc8c99b02e7df5e3960caea2c9e846b0657c89
8e8437d9df1b23caf4c2dfbcd7ccdbb624b9183a
refs/heads/master
2018-10-08T05:00:29.623000
2018-08-23T10:24:02
2018-08-23T10:24:03
115,318,011
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lemosen.web; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.util.ArrayList; import java.util.Arrays; //@RunWith(SpringRunner.class) //@SpringBootTest //public class WebApplicationTests { // // @Test // public void contextLoads() { // } // //} public class WebApplicationTests { public static void main(String[] args) { long startTime = System.currentTimeMillis(); //获取开始时间 String[] a = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "s", "y", "z", "A", "B", "C", "D", "E", "F"}; String[] print = new String[a.length]; int[] b = new int[a.length]; for (int i = 0; i < a.length; i++) { print[i] = "0"; b[i] = 0; } System.out.println(Arrays.toString(print)); while (true) { for (int k = b.length - 1; k > 0; k--) { if (b[k] < a.length - 1) { b[k]++; for (int j = a.length - 1; j >= 0; j--) { print[j] = a[b[j]]; } StringBuilder aa = new StringBuilder(); boolean flag = false; for (String string : print) { if (!string.equals("0") || flag) { flag = !flag; aa.append(string); } } System.out.println(aa); if (aa.toString().equals("abcde")) { long endTime = System.currentTimeMillis(); //获取结束时间 System.out.println("程序运行时间:" + (endTime - startTime) + "ms"); System.out.println("------------"); return; } break; } else if (b[k] >= a.length - 1) { b[k] -= a.length - 1; b[k - 1]++; for (int l = 1; l < a.length - 1; l++) { if (b[k - l] == a.length) { b[k - l] = 0; b[k - l - 1]++; } } k++; } } } } }
UTF-8
Java
2,553
java
WebApplicationTests.java
Java
[]
null
[]
package com.lemosen.web; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.util.ArrayList; import java.util.Arrays; //@RunWith(SpringRunner.class) //@SpringBootTest //public class WebApplicationTests { // // @Test // public void contextLoads() { // } // //} public class WebApplicationTests { public static void main(String[] args) { long startTime = System.currentTimeMillis(); //获取开始时间 String[] a = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "s", "y", "z", "A", "B", "C", "D", "E", "F"}; String[] print = new String[a.length]; int[] b = new int[a.length]; for (int i = 0; i < a.length; i++) { print[i] = "0"; b[i] = 0; } System.out.println(Arrays.toString(print)); while (true) { for (int k = b.length - 1; k > 0; k--) { if (b[k] < a.length - 1) { b[k]++; for (int j = a.length - 1; j >= 0; j--) { print[j] = a[b[j]]; } StringBuilder aa = new StringBuilder(); boolean flag = false; for (String string : print) { if (!string.equals("0") || flag) { flag = !flag; aa.append(string); } } System.out.println(aa); if (aa.toString().equals("abcde")) { long endTime = System.currentTimeMillis(); //获取结束时间 System.out.println("程序运行时间:" + (endTime - startTime) + "ms"); System.out.println("------------"); return; } break; } else if (b[k] >= a.length - 1) { b[k] -= a.length - 1; b[k - 1]++; for (int l = 1; l < a.length - 1; l++) { if (b[k - l] == a.length) { b[k - l] = 0; b[k - l - 1]++; } } k++; } } } } }
2,553
0.380517
0.369781
76
32.078949
31.37958
232
false
false
0
0
0
0
0
0
1.078947
false
false
5
cb6b6c4938177895a9d7f3173df2da941964c002
16,054,587,822,738
e54922cc3ef1b464f3589a65ca12f28d5768151b
/src/main/java/com/github/jmnarloch/spring/jaxrs/client/resteasy/RestEasyClientProxyFactory.java
a569978738257fae742534979e7802f22f6254d1
[ "Apache-2.0" ]
permissive
SathishkumarKS/spring-jax-rs-client-proxy
https://github.com/SathishkumarKS/spring-jax-rs-client-proxy
a79a6c699f42cfbaaa5d226411504a20ad07f80b
e3eba297ea4724170793c026157699711e0143d4
refs/heads/master
2021-01-17T11:24:32.646000
2015-08-23T06:18:04
2015-08-23T06:18:04
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Copyright (c) 2015 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.jmnarloch.spring.jaxrs.client.resteasy; import com.github.jmnarloch.spring.jaxrs.client.support.ClientBuilderConfigurer; import com.github.jmnarloch.spring.jaxrs.client.support.ClientBuilderHolder; import com.github.jmnarloch.spring.jaxrs.client.support.JaxRsClientProxyFactory; import com.github.jmnarloch.spring.jaxrs.client.support.JaxRsClientProxyFactorySupport; import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; /** * The RESTEasy {@link JaxRsClientProxyFactory} implementation. * It delegates the execution to {@link ResteasyClientBuilder} create the proxy instances. * * @author Jakub Narloch */ class RestEasyClientProxyFactory extends JaxRsClientProxyFactorySupport { /** * {@inheritDoc} */ @Override public <T> T createClientProxy(Class<T> serviceClass, String serviceUrl) { // creates the client builder instance final ClientBuilder builder = clientBuilder(); // configures the builder configure(builder); // creates the proxy instance return proxy(serviceClass, serviceUrl, builder.build()); } /** * Creates the new instance of {@link ClientBuilder}. * * @return the client builder */ private ClientBuilder clientBuilder() { return ClientBuilder.newBuilder(); } /** * Configures the client builder. * * @param builder the client builder */ private void configure(ClientBuilder builder) { final ClientBuilderHolder<?> holder = new ClientBuilderHolder<>(builder); final ClientBuilderConfigurer configurer = new ClientBuilderConfigurer(holder); // configures the builder configureClientBuilder(configurer); // registers the providers registerProviders(holder.getClientBuilder(), getProviders()); } /** * Creates the proxy instance. * * @param serviceClass the service class * @param serviceUrl the service url * @param client the client * @param <T> the proxy type * @return the proxy instance */ private <T> T proxy(Class<T> serviceClass, String serviceUrl, Client client) { final WebTarget target = client.target(serviceUrl); return ((ResteasyWebTarget) target).proxy(serviceClass); } /** * Registers the provider classes. * * @param clientBuilder the client builder * @param providers the providers classes */ private void registerProviders(ClientBuilder clientBuilder, Class<?>[] providers) { for (Class<?> filter : providers) { clientBuilder.register(filter); } } }
UTF-8
Java
3,469
java
RestEasyClientProxyFactory.java
Java
[ { "context": "Builder} create the proxy instances.\n *\n * @author Jakub Narloch\n */\nclass RestEasyClientProxyFactory extends JaxR", "end": 1425, "score": 0.9998685121536255, "start": 1412, "tag": "NAME", "value": "Jakub Narloch" } ]
null
[]
/** * Copyright (c) 2015 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.jmnarloch.spring.jaxrs.client.resteasy; import com.github.jmnarloch.spring.jaxrs.client.support.ClientBuilderConfigurer; import com.github.jmnarloch.spring.jaxrs.client.support.ClientBuilderHolder; import com.github.jmnarloch.spring.jaxrs.client.support.JaxRsClientProxyFactory; import com.github.jmnarloch.spring.jaxrs.client.support.JaxRsClientProxyFactorySupport; import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; /** * The RESTEasy {@link JaxRsClientProxyFactory} implementation. * It delegates the execution to {@link ResteasyClientBuilder} create the proxy instances. * * @author <NAME> */ class RestEasyClientProxyFactory extends JaxRsClientProxyFactorySupport { /** * {@inheritDoc} */ @Override public <T> T createClientProxy(Class<T> serviceClass, String serviceUrl) { // creates the client builder instance final ClientBuilder builder = clientBuilder(); // configures the builder configure(builder); // creates the proxy instance return proxy(serviceClass, serviceUrl, builder.build()); } /** * Creates the new instance of {@link ClientBuilder}. * * @return the client builder */ private ClientBuilder clientBuilder() { return ClientBuilder.newBuilder(); } /** * Configures the client builder. * * @param builder the client builder */ private void configure(ClientBuilder builder) { final ClientBuilderHolder<?> holder = new ClientBuilderHolder<>(builder); final ClientBuilderConfigurer configurer = new ClientBuilderConfigurer(holder); // configures the builder configureClientBuilder(configurer); // registers the providers registerProviders(holder.getClientBuilder(), getProviders()); } /** * Creates the proxy instance. * * @param serviceClass the service class * @param serviceUrl the service url * @param client the client * @param <T> the proxy type * @return the proxy instance */ private <T> T proxy(Class<T> serviceClass, String serviceUrl, Client client) { final WebTarget target = client.target(serviceUrl); return ((ResteasyWebTarget) target).proxy(serviceClass); } /** * Registers the provider classes. * * @param clientBuilder the client builder * @param providers the providers classes */ private void registerProviders(ClientBuilder clientBuilder, Class<?>[] providers) { for (Class<?> filter : providers) { clientBuilder.register(filter); } } }
3,462
0.698472
0.696166
107
31.420561
28.424038
90
false
false
0
0
0
0
0
0
0.308411
false
false
5
aa66f962704333ff7bd53553e649e4c139c1a521
25,838,523,317,210
0008835388b7a542f4782d99b9d86a2bd5f2e571
/PixelCombat/app/src/main/java/com/example/pixelcombat/character/chars/ruffy/attacks/RuffyAttack1.java
6ffa6a468cc2ced7932dc208e63399e05b4bea19
[]
no_license
BillyTheG/pixelCombatSmartPhone
https://github.com/BillyTheG/pixelCombatSmartPhone
8532d286d94af5f72e4c5efed6ec375d176db2bd
571250e6814b25d84ab3605488c60c1347fe35b7
refs/heads/master
2023-01-08T03:06:26.418000
2020-11-07T21:03:20
2020-11-07T21:03:20
296,892,939
0
0
null
false
2020-11-07T21:03:21
2020-09-19T15:02:29
2020-10-30T19:24:51
2020-11-07T21:03:21
12,115
1
0
0
Java
false
false
package com.example.pixelcombat.character.chars.ruffy.attacks; import android.util.Log; import com.example.pixelcombat.GameCharacter; import com.example.pixelcombat.character.attack.Attack; import com.example.pixelcombat.core.config.SparkConfig; import com.example.pixelcombat.core.message.GameMessage; import com.example.pixelcombat.enums.MessageType; import com.example.pixelcombat.math.BoundingRectangle; import com.example.pixelcombat.math.Vector2d; import java.util.Random; public class RuffyAttack1 extends Attack { public RuffyAttack1(GameCharacter character, int id) { super(character, id); } /** * This method proceeds the events during the attack phase. * For each Frame in an Attack there is a different function * involved depending on the attacks specialty. */ @Override public void process() { try { switch (character.getViewManager().getFrameIndex()) { case 0: if (isSwitcher()) { int rand = new Random().nextInt(2) + 1; character.notifyObservers(new GameMessage(MessageType.SOUND, "ruffy_attack" + rand, null, true)); setSwitcher(false); } break; case 2: if (!isSwitcher()) { character.notifyObservers(new GameMessage(MessageType.SOUND, "kohaku_attack1_sonic", null, true)); setSwitcher(false); } break; default: break; } } catch (Exception e) { Log.e("Error", "In processing the attack, following excpetion was thrown: " + e.getMessage()); } } /** * This method is meant for validating the hit on the enemy. If the enemy * was able to block this attack, the procedure will not do anything. If the * hit was successful, the enemy will be charged with lifepoint reduction, status change * and etc. */ @Override public void checkContent() { // getUser().sound("/audio/punches.wav"); // getUser().enemy.damage(getUser().getStrength() * 2); // getUser().sound(getUser().enemy.cry()); getCharacter().getHitManager().setHitDelay(true); try { BoundingRectangle box = character.getBoxManager().getIntersectionBox(); character.notifyObservers(new GameMessage(MessageType.SPARK_CREATION, SparkConfig.ATTACK_SPARK + ";test;", new Vector2d(box.getPos().x, box.getPos().y), true)); character.notifyObservers(new GameMessage(MessageType.SOUND, "kohaku_attack1_hit", null, true)); } catch (Exception e) { Log.e("Error", "The spark could not be created: " + e.getMessage()); } if (!getEnemy().getStatusManager().isKnockbacked()) { // getUser().enemy.timeManager.getDisableTime().setY(Float.valueOf(0.0F)); getEnemy().getHitManager().setKnockBackHeight(-7.0F); getEnemy().getHitManager().setKnockBackRange(10.0F); getEnemy().getHitManager().checkOnAir(); } else { getEnemy().getHitManager().comboTouch(-4.0F, 1.0F); } } /** * This method does the final check, whether the attack reached the final * frame and the animation time has been lapsed. */ @Override public void checkFinished() { } /** * @return the attacking state variable */ @Override public boolean isAttacking() { return getCharacter().getAttackManager().isAttacking1(); } @Override public void resetStats() { } }
UTF-8
Java
3,741
java
RuffyAttack1.java
Java
[]
null
[]
package com.example.pixelcombat.character.chars.ruffy.attacks; import android.util.Log; import com.example.pixelcombat.GameCharacter; import com.example.pixelcombat.character.attack.Attack; import com.example.pixelcombat.core.config.SparkConfig; import com.example.pixelcombat.core.message.GameMessage; import com.example.pixelcombat.enums.MessageType; import com.example.pixelcombat.math.BoundingRectangle; import com.example.pixelcombat.math.Vector2d; import java.util.Random; public class RuffyAttack1 extends Attack { public RuffyAttack1(GameCharacter character, int id) { super(character, id); } /** * This method proceeds the events during the attack phase. * For each Frame in an Attack there is a different function * involved depending on the attacks specialty. */ @Override public void process() { try { switch (character.getViewManager().getFrameIndex()) { case 0: if (isSwitcher()) { int rand = new Random().nextInt(2) + 1; character.notifyObservers(new GameMessage(MessageType.SOUND, "ruffy_attack" + rand, null, true)); setSwitcher(false); } break; case 2: if (!isSwitcher()) { character.notifyObservers(new GameMessage(MessageType.SOUND, "kohaku_attack1_sonic", null, true)); setSwitcher(false); } break; default: break; } } catch (Exception e) { Log.e("Error", "In processing the attack, following excpetion was thrown: " + e.getMessage()); } } /** * This method is meant for validating the hit on the enemy. If the enemy * was able to block this attack, the procedure will not do anything. If the * hit was successful, the enemy will be charged with lifepoint reduction, status change * and etc. */ @Override public void checkContent() { // getUser().sound("/audio/punches.wav"); // getUser().enemy.damage(getUser().getStrength() * 2); // getUser().sound(getUser().enemy.cry()); getCharacter().getHitManager().setHitDelay(true); try { BoundingRectangle box = character.getBoxManager().getIntersectionBox(); character.notifyObservers(new GameMessage(MessageType.SPARK_CREATION, SparkConfig.ATTACK_SPARK + ";test;", new Vector2d(box.getPos().x, box.getPos().y), true)); character.notifyObservers(new GameMessage(MessageType.SOUND, "kohaku_attack1_hit", null, true)); } catch (Exception e) { Log.e("Error", "The spark could not be created: " + e.getMessage()); } if (!getEnemy().getStatusManager().isKnockbacked()) { // getUser().enemy.timeManager.getDisableTime().setY(Float.valueOf(0.0F)); getEnemy().getHitManager().setKnockBackHeight(-7.0F); getEnemy().getHitManager().setKnockBackRange(10.0F); getEnemy().getHitManager().checkOnAir(); } else { getEnemy().getHitManager().comboTouch(-4.0F, 1.0F); } } /** * This method does the final check, whether the attack reached the final * frame and the animation time has been lapsed. */ @Override public void checkFinished() { } /** * @return the attacking state variable */ @Override public boolean isAttacking() { return getCharacter().getAttackManager().isAttacking1(); } @Override public void resetStats() { } }
3,741
0.601711
0.595563
109
33.321102
31.29114
122
false
false
0
0
0
0
0
0
0.541284
false
false
5
7542cb08f61605fb81cc90d2286f4506bb95e89f
28,123,445,912,644
3542b11aed676cebbb44d02850f38795fbbdeda4
/app/src/main/java/com/fdmkst/ltl_pc/brain/MainMenu.java
d52009c834e8578e05136e5cb9eac71ea512b41a
[]
no_license
yacine902/Brain
https://github.com/yacine902/Brain
6a73978371ad63b6902e02a1b7cc7111b71b712b
066324fd1009c8fb17e9a6b0b57a6e6adedb098a
refs/heads/master
2021-01-10T01:11:49.113000
2016-01-03T21:43:51
2016-01-03T21:43:51
48,133,427
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.fdmkst.ltl_pc.brain; import android.app.Activity; import android.app.Fragment; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.Button; import com.facebook.login.LoginManager; import com.facebook.share.ShareApi; import com.facebook.share.model.SharePhoto; import com.facebook.share.model.SharePhotoContent; public class MainMenu extends AppCompatActivity implements View.OnClickListener { private static Button startbtn; private static Button logOut; private static Button getHelpBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_menu); startbtn = (Button) findViewById(R.id.start_button); startbtn.setOnClickListener(this); logOut = (Button)findViewById(R.id.logout_button); logOut.setOnClickListener(this); getHelpBtn = (Button) findViewById(R.id.how_to_play_button); getHelpBtn.setOnClickListener(this); // if (savedInstanceState == null) { // getSupportFragmentManager().beginTransaction() // .add(R.id.container, new PlaceholderFragment()).commit(); // } } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle app bar item clicks here. The app bar // automatically handles clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { //com.fdmkst.ltl_pc.firstapp.R.id.action_settings return true; } return super.onOptionsItemSelected(item); } private void startGame(){ startActivity(new Intent("com.fdmkst.ltl_pc.brain.Game")); } private void getHelp(){ startActivity(new Intent("com.fdmkst.ltl_pc.brain.HowToPlayBtn")); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.start_button: System.out.println("starting game..."); startGame(); break; case R.id.logout_button: System.out.println("Logged out..."); LoginManager.getInstance().logOut(); finish(); break; case R.id.how_to_play_button: System.out.println("Getting help..."); getHelp(); break; } } // public static class PlaceholderFragment extends Fragment { // // public PlaceholderFragment() { } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, // Bundle savedInstanceState) { // View rootView = inflater.inflate(R.layout.main_menu, // container, false); // return rootView; // } // // // @Override // public void onViewCreated(View view, Bundle savedInstanceState) { // super.onViewCreated(view, savedInstanceState); // // } // } // @Override // public void onBackPressed() { // } }
UTF-8
Java
3,461
java
MainMenu.java
Java
[]
null
[]
package com.fdmkst.ltl_pc.brain; import android.app.Activity; import android.app.Fragment; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.Button; import com.facebook.login.LoginManager; import com.facebook.share.ShareApi; import com.facebook.share.model.SharePhoto; import com.facebook.share.model.SharePhotoContent; public class MainMenu extends AppCompatActivity implements View.OnClickListener { private static Button startbtn; private static Button logOut; private static Button getHelpBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_menu); startbtn = (Button) findViewById(R.id.start_button); startbtn.setOnClickListener(this); logOut = (Button)findViewById(R.id.logout_button); logOut.setOnClickListener(this); getHelpBtn = (Button) findViewById(R.id.how_to_play_button); getHelpBtn.setOnClickListener(this); // if (savedInstanceState == null) { // getSupportFragmentManager().beginTransaction() // .add(R.id.container, new PlaceholderFragment()).commit(); // } } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle app bar item clicks here. The app bar // automatically handles clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { //com.fdmkst.ltl_pc.firstapp.R.id.action_settings return true; } return super.onOptionsItemSelected(item); } private void startGame(){ startActivity(new Intent("com.fdmkst.ltl_pc.brain.Game")); } private void getHelp(){ startActivity(new Intent("com.fdmkst.ltl_pc.brain.HowToPlayBtn")); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.start_button: System.out.println("starting game..."); startGame(); break; case R.id.logout_button: System.out.println("Logged out..."); LoginManager.getInstance().logOut(); finish(); break; case R.id.how_to_play_button: System.out.println("Getting help..."); getHelp(); break; } } // public static class PlaceholderFragment extends Fragment { // // public PlaceholderFragment() { } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, // Bundle savedInstanceState) { // View rootView = inflater.inflate(R.layout.main_menu, // container, false); // return rootView; // } // // // @Override // public void onViewCreated(View view, Bundle savedInstanceState) { // super.onViewCreated(view, savedInstanceState); // // } // } // @Override // public void onBackPressed() { // } }
3,461
0.628431
0.628142
105
31.961905
22.411274
81
false
false
0
0
0
0
0
0
0.533333
false
false
5
625ed33d03d8d326731472eb61cba6b67ab6e132
1,297,080,123,691
c2458031530f5eb601e7ba126ed31b63f75b0756
/src/de/dhbwka/java/exercise/classes/Complex.java
592cab6617b772127b6f6d3efddda43a286874fc
[]
no_license
fidsusj/JavaProgramming
https://github.com/fidsusj/JavaProgramming
ea5acb1b5faede11ed5af722eae7e05106d584e8
a8fbce0249c2955b2c5ec20efd71b8627f69cd62
refs/heads/master
2021-01-06T11:26:20.330000
2020-02-18T09:02:50
2020-02-18T09:02:50
241,308,584
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package de.dhbwka.java.exercise.classes; public class Complex { private double a; private double b; public Complex(double a, double b) { this.a = a; this.b = b; } public Complex add(Complex comp) { return new Complex(a + comp.getReal(), b + comp.getImag()); } public Complex sub(Complex comp) { return new Complex(a - comp.getReal(), b - comp.getImag()); } public Complex mult(Complex comp) { return new Complex(a*comp.getReal() - b*comp.getImag(), a*comp.getImag() + b*comp.getReal()); } public Complex div(Complex comp) { return new Complex((a*comp.getReal() + b*comp.getImag())/(Math.pow(comp.getReal(),2) + Math.pow(comp.getImag(), 2)), (b*comp.getReal() - a*comp.getImag())/(Math.pow(comp.getReal(),2) + Math.pow(comp.getImag(), 2))); } public double getMagnitude() { return (Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2))); } public boolean isLess(Complex comp) { return (this.getMagnitude() < comp.getMagnitude()); } public String toString() { return a + " " + getAugury(b) + " " + Math.abs(b) + "i"; } private String getAugury(double val) { return (String) (val < 0 ? "-" : "+"); } public double getReal() { return a; } public double getImag() { return b; } }
UTF-8
Java
1,238
java
Complex.java
Java
[]
null
[]
package de.dhbwka.java.exercise.classes; public class Complex { private double a; private double b; public Complex(double a, double b) { this.a = a; this.b = b; } public Complex add(Complex comp) { return new Complex(a + comp.getReal(), b + comp.getImag()); } public Complex sub(Complex comp) { return new Complex(a - comp.getReal(), b - comp.getImag()); } public Complex mult(Complex comp) { return new Complex(a*comp.getReal() - b*comp.getImag(), a*comp.getImag() + b*comp.getReal()); } public Complex div(Complex comp) { return new Complex((a*comp.getReal() + b*comp.getImag())/(Math.pow(comp.getReal(),2) + Math.pow(comp.getImag(), 2)), (b*comp.getReal() - a*comp.getImag())/(Math.pow(comp.getReal(),2) + Math.pow(comp.getImag(), 2))); } public double getMagnitude() { return (Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2))); } public boolean isLess(Complex comp) { return (this.getMagnitude() < comp.getMagnitude()); } public String toString() { return a + " " + getAugury(b) + " " + Math.abs(b) + "i"; } private String getAugury(double val) { return (String) (val < 0 ? "-" : "+"); } public double getReal() { return a; } public double getImag() { return b; } }
1,238
0.630856
0.625202
53
22.377359
34.621525
217
false
false
0
0
0
0
0
0
1.622642
false
false
5
68cff7615b37248b829bdaa315c037fc7d799907
33,724,083,229,121
255f82aabd067a531d31126f12c1727760bb8273
/Provectus_Java/lessons/lesson6/src/com/company/Employee.java
a3c89ee8912f86ab32396a29c336cf788a3e5317
[]
no_license
gbelonog/java
https://github.com/gbelonog/java
af927c4059abc1865ac50df50cba4249c7f6e2dd
274375e6b66ab07fbeafcb57129a4d988c14e545
refs/heads/master
2021-01-12T05:19:07.617000
2017-02-02T11:13:32
2017-02-02T11:13:32
77,910,386
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.company; /** * Created by galina on 21.12.16. */ public class Employee extends Person{ String Company; //Employee(){ this.Company = "olx";} //super(){} public Employee(String name, String LastName, String company) { super(name, LastName); this.Company = company; } @Override void display() { System.out.println("display"); } }
UTF-8
Java
404
java
Employee.java
Java
[ { "context": "package com.company;\n\n/**\n * Created by galina on 21.12.16.\n */\npublic class Employee extends Pe", "end": 46, "score": 0.8562997579574585, "start": 40, "tag": "USERNAME", "value": "galina" } ]
null
[]
package com.company; /** * Created by galina on 21.12.16. */ public class Employee extends Person{ String Company; //Employee(){ this.Company = "olx";} //super(){} public Employee(String name, String LastName, String company) { super(name, LastName); this.Company = company; } @Override void display() { System.out.println("display"); } }
404
0.594059
0.579208
21
18.238094
17.254137
65
false
false
0
0
0
0
0
0
0.428571
false
false
5
99ffbc12436ed2f0a7052dd289a8c63ce0e9d97a
5,763,846,137,693
bbc82450538ee3d112c3ffb3d3332be9e7c32aff
/app/src/main/java/com/alam_kanak/FragmentOne.java
3a02ef8bd30ea65ce2f238b60c405b5856dac5fa
[]
no_license
MehmetCanAkayy/SchoolManagement
https://github.com/MehmetCanAkayy/SchoolManagement
c290c912725e004598e1c9191b91f0e5d5a0b6a9
ef10175ecab95483af91b05f7318ff2b673e08bc
refs/heads/master
2020-04-28T02:09:36.933000
2018-10-02T22:38:49
2018-10-02T22:38:49
174,888,007
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.alam_kanak; import android.app.Activity; import android.app.Dialog; import android.content.Intent; import android.graphics.Color; import android.graphics.RectF; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.CardView; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.alamkanak.weekview.DateTimeInterpreter; import com.alamkanak.weekview.MonthLoader; import com.alamkanak.weekview.WeekView; import com.alamkanak.weekview.WeekViewEvent; import com.firebaseDemo.Artist; import com.firebaseDemo.LessonInfo; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.onur.easyspeakdemo.EventActvity; import com.onur.easyspeakdemo.R; import com.studentsTabLayout.MyAdapter; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.List; import java.util.Locale; public class FragmentOne extends Fragment implements WeekView.EventClickListener, MonthLoader.MonthChangeListener,WeekView.EmptyViewClickListener, WeekView.EventLongPressListener, WeekView.EmptyViewLongPressListener { private static final int TYPE_DAY_VIEW = 1; private static final int TYPE_THREE_DAY_VIEW = 2; private static final int TYPE_WEEK_VIEW = 3; private int mWeekViewType = TYPE_THREE_DAY_VIEW; private WeekView mWeekView; private ArrayList<WeekViewEvent> mNewEvents; private Calendar selectedDate; private DatabaseReference databaseLessonInfo; private DatabaseReference databaseUpdate; String baslangic; int day; String bitis; String grade; String ders; String teacher; String icerik ; Calendar calendarStartTime; Calendar calendarEndTime; String endHour; String startHour; int a1,a1Plus,a2,b1,b2,c1,advanced; Dialog myDialog; TextView titleTv,messageTv; ImageView closeButton; CardView card; Button delete,update; public static FragmentOne newInstance( int mWeekViewType) { Bundle bundle = new Bundle(); bundle.putInt("mWeekViewType", mWeekViewType); FragmentOne fragment = new FragmentOne(); fragment.setArguments(bundle); return fragment; } private void readBundle(Bundle bundle) { if (bundle != null) { mWeekViewType = bundle.getInt("mWeekViewType"); if (mWeekViewType == 3) { mWeekViewType = TYPE_THREE_DAY_VIEW; mWeekView.setNumberOfVisibleDays(3); // Lets change some dimensions to best fit the view. mWeekView.setColumnGap((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8, getResources().getDisplayMetrics())); mWeekView.setTextSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 12, getResources().getDisplayMetrics())); mWeekView.setEventTextSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 12, getResources().getDisplayMetrics())); } else{ mWeekViewType = TYPE_WEEK_VIEW; mWeekView.setNumberOfVisibleDays(7); // Lets change some dimensions to best fit the view. mWeekView.setColumnGap((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, getResources().getDisplayMetrics())); mWeekView.setTextSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 10, getResources().getDisplayMetrics())); mWeekView.setEventTextSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 10, getResources().getDisplayMetrics())); } } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.activity_sample, container, false); a1=view.getResources().getColor(R.color.a1LessonColor); a1Plus=view.getResources().getColor(R.color.a1PlusLessonColor); a2=view.getResources().getColor(R.color.a2LessonColor); b1=view.getResources().getColor(R.color.b1LessonColor); b2=view.getResources().getColor(R.color.b2LessonColor); c1=view.getResources().getColor(R.color.c1LessonColor); advanced=view.getResources().getColor(R.color.advencedLessonColor); myDialog = new Dialog(view.getContext()); databaseLessonInfo = FirebaseDatabase.getInstance().getReference("lessonInfo"); databaseUpdate = FirebaseDatabase.getInstance().getReference("lessonInfo"); FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Click action selectedDate = Calendar.getInstance(); selectedDate.setFirstDayOfWeek(Calendar.MONDAY); calendarStartTime=Calendar.getInstance(); calendarEndTime=Calendar.getInstance(); calendarStartTime.setFirstDayOfWeek(Calendar.MONDAY); calendarEndTime.setFirstDayOfWeek(Calendar.MONDAY); while (selectedDate.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) { selectedDate.add(Calendar.DATE, -1); calendarStartTime.add(Calendar.DATE, -1); calendarEndTime.add(Calendar.DATE, -1); } Intent eventActivity = new Intent(getActivity(), EventActvity.class); eventActivity.putExtra("hour", 10); eventActivity.putExtra("minute", 30); eventActivity.putExtra("isFloatingButtonClicked", true); eventActivity.putExtra("isUpdate",false); eventActivity.putExtra("Day",0); eventActivity.putExtra("Grade",0); eventActivity.putExtra("Teacher",0); startActivityForResult(eventActivity, 1); } }); // Get a reference for the week view in the layout. mWeekView = (WeekView) view.findViewById(R.id.weekView); // Show a toast message about the touched event. mWeekView.setOnEventClickListener(this); // The week view has infinite scrolling horizontally. We have to provide the events of a // month every time the month changes on the week view. mWeekView.setMonthChangeListener(this); // Set long press listener for events. mWeekView.setEventLongPressListener(this); // Set long press listener for empty view mWeekView.setEmptyViewLongPressListener(this); mWeekView.setEmptyViewClickListener(this); mNewEvents = new ArrayList<WeekViewEvent>(); // Set up a date time interpreter to interpret how the date and time will be formatted in // the week view. This is optional. setupDateTimeInterpreter(false); readBundle(getArguments()); return view; } @Override public void onStart() { super.onStart(); //Retriving data From Firebase databaseLessonInfo.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { mNewEvents.clear(); for (DataSnapshot lessonInfoSnapshot : dataSnapshot.getChildren() ){ //Create Artist Class Object and Returning Value LessonInfo lessonInfo = lessonInfoSnapshot.getValue(LessonInfo.class); Calendar startTime=Calendar.getInstance(); Calendar endTime=Calendar.getInstance(); String[] calendarStartItem = lessonInfo.getBaslangic().split("%"); String[] calendarEndItem = lessonInfo.getBitis().split("%"); for (String t : calendarStartItem) System.out.println(t); startTime.set(Integer.parseInt(calendarStartItem[0]),Integer.parseInt(calendarStartItem[1]),Integer.parseInt(calendarStartItem[2]),Integer.parseInt(calendarStartItem[3]),Integer.parseInt(calendarStartItem[4])); endTime.set(Integer.parseInt(calendarEndItem[0]),Integer.parseInt(calendarEndItem[1]),Integer.parseInt(calendarEndItem[2]),Integer.parseInt(calendarEndItem[3]),Integer.parseInt(calendarEndItem[4])); WeekViewEvent myEvent = new WeekViewEvent(lessonInfo.getGrade(), lessonInfo.getTeacher(), lessonInfo.getIcerik(), startTime, endTime,lessonInfo.getDers()); if(lessonInfo.getGrade().equals("A1")){ myEvent.setColor(a1); }else if(lessonInfo.getGrade().equals("A1+")){ myEvent.setColor(a1Plus); }else if(lessonInfo.getGrade().equals("A2")){ myEvent.setColor(a2); }else if(lessonInfo.getGrade().equals("B1")){ myEvent.setColor(b1); }else if(lessonInfo.getGrade().equals("B2")){ myEvent.setColor(b2); }else if(lessonInfo.getGrade().equals("C1")){ myEvent.setColor(c1); }else if(lessonInfo.getGrade().equals("Advanced")){ myEvent.setColor(advanced); } mNewEvents.add(myEvent); // Refresh the week view. onMonthChange will be called again. } mWeekView.notifyDatasetChanged(); } @Override public void onCancelled(DatabaseError databaseError) { System.out.println("Student Verisi Çekilemedi."); } }); } @Override public List<WeekViewEvent> onMonthChange(int newYear, int newMonth) { // Populate the week view with the events that was added by tapping on empty view. List<WeekViewEvent> events = new ArrayList<WeekViewEvent>(); ArrayList<WeekViewEvent> newEvents = getNewEvents(newYear, newMonth); events.addAll(newEvents); return events; } /** * Get events that were added by tapping on empty view. * * @param year The year currently visible on the week view. * @param month The month currently visible on the week view. * @return The events of the given year and month. */ private ArrayList<WeekViewEvent> getNewEvents(int year, int month) { // Get the starting point and ending point of the given month. We need this to find the // events of the given month. Calendar startOfMonth = Calendar.getInstance(); startOfMonth.set(Calendar.YEAR, year); startOfMonth.set(Calendar.MONTH, month - 1); startOfMonth.set(Calendar.DAY_OF_MONTH, 1); startOfMonth.set(Calendar.HOUR_OF_DAY, 0); startOfMonth.set(Calendar.MINUTE, 0); startOfMonth.set(Calendar.SECOND, 0); startOfMonth.set(Calendar.MILLISECOND, 0); Calendar endOfMonth = (Calendar) startOfMonth.clone(); endOfMonth.set(Calendar.DAY_OF_MONTH, endOfMonth.getMaximum(Calendar.DAY_OF_MONTH)); endOfMonth.set(Calendar.HOUR_OF_DAY, 23); endOfMonth.set(Calendar.MINUTE, 59); endOfMonth.set(Calendar.SECOND, 59); // Find the events that were added by tapping on empty view and that occurs in the given // time frame. ArrayList<WeekViewEvent> events = new ArrayList<WeekViewEvent>(); for (WeekViewEvent event : mNewEvents) { events.add(event); } return events; } private void setupDateTimeInterpreter(final boolean shortDate) { mWeekView.setDateTimeInterpreter(new DateTimeInterpreter() { @Override public String interpretDate(Calendar date) { SimpleDateFormat weekdayNameFormat = new SimpleDateFormat("EEEE", Locale.getDefault()); String weekday = weekdayNameFormat.format(date.getTime()); SimpleDateFormat format = new SimpleDateFormat(" d", Locale.getDefault()); // All android api level do not have a standard way of getting the first letter of // the week day name. Hence we get the first char programmatically. // Details: http://stackoverflow.com/questions/16959502/get-one-letter-abbreviation-of-week-day-of-a-date-in-java#answer-16959657 if (shortDate) weekday = String.valueOf(weekday.charAt(0)); return weekday.toUpperCase() + format.format(date.getTime()); } @Override public String interpretTime(int hour) { if (hour > 12) { return (hour - 12) + " PM"; } else { return (hour) + " AM"; } } }); } protected String getEventTitle(Calendar time) { return String.format("Event of %02d:%02d %s/%d", time.get(Calendar.HOUR_OF_DAY), time.get(Calendar.MINUTE), time.get(Calendar.MONTH) + 1, time.get(Calendar.DAY_OF_MONTH)); } @Override public void onEventClick(final WeekViewEvent event, final RectF eventRect) { Toast.makeText(getActivity(), "Clicked " + event.getContent(), Toast.LENGTH_SHORT).show(); // AlertDialog.Builder builder = new AlertDialog.Builder(AlamKanakActivity.this); // builder.setTitle("Lesson Content"); // builder.setMessage(event.getGrade() + "\n" + event.getTeacher() + "\n" + event.getStartEnd() + "\n" + event.mGetContent()); myDialog.setContentView(R.layout.custom_dialog_box); messageTv = myDialog.findViewById(R.id.content); card = myDialog.findViewById(R.id.mycard); card.setBackgroundColor(event.getColor()); closeButton = myDialog.findViewById(R.id.close); delete = myDialog.findViewById(R.id.delete); update = myDialog.findViewById(R.id.update); messageTv.setText(event.getDers()+"\n"+event.getGrade() + "\n" + event.getTeacher() + "\n" + event.getStartEnd() + "\n" + event.mGetContent()); closeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { myDialog.dismiss(); } }); update.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { selectedDate = Calendar.getInstance(); selectedDate.setFirstDayOfWeek(Calendar.MONDAY); calendarStartTime=Calendar.getInstance(); calendarEndTime=Calendar.getInstance(); calendarStartTime.setFirstDayOfWeek(Calendar.MONDAY); calendarEndTime.setFirstDayOfWeek(Calendar.MONDAY); while (selectedDate.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) { selectedDate.add(Calendar.DATE, -1); calendarStartTime.add(Calendar.DATE, -1); calendarEndTime.add(Calendar.DATE, -1); } //final Intent eventActivity = new Intent(AlamKanakActivity.this, EventActvity.class); databaseUpdate.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for (DataSnapshot lessonInfoSnapshot : dataSnapshot.getChildren() ){ //Create Artist Class Object and Returning Value LessonInfo lessonInfo = lessonInfoSnapshot.getValue(LessonInfo.class); Calendar startTime=Calendar.getInstance(); Calendar endTime=Calendar.getInstance(); String[] calendarStartItem = lessonInfo.getBaslangic().split("%"); String[] calendarEndItem = lessonInfo.getBitis().split("%"); for (String t : calendarStartItem) System.out.println(t); startTime.set(Integer.parseInt(calendarStartItem[0]),Integer.parseInt(calendarStartItem[1]),Integer.parseInt(calendarStartItem[2]),Integer.parseInt(calendarStartItem[3]),Integer.parseInt(calendarStartItem[4])); endTime.set(Integer.parseInt(calendarEndItem[0]),Integer.parseInt(calendarEndItem[1]),Integer.parseInt(calendarEndItem[2]),Integer.parseInt(calendarEndItem[3]),Integer.parseInt(calendarEndItem[4])); WeekViewEvent myEvent = new WeekViewEvent(lessonInfo.getGrade(), lessonInfo.getTeacher(), lessonInfo.getIcerik(), startTime, endTime,lessonInfo.getDers()); if(event.getGrade()==myEvent.getGrade()){ final Intent eventActivity = new Intent(getContext(), EventActvity.class); eventActivity.putExtra("hour", startTime.get(Calendar.HOUR_OF_DAY)); eventActivity.putExtra("minute", startTime.get(Calendar.MINUTE)); eventActivity.putExtra("isFloatingButtonClicked", true); eventActivity.putExtra("isUpdate",true); eventActivity.putExtra("Key",lessonInfoSnapshot.getKey()); eventActivity.putExtra("Content",myEvent.mGetContent()); String[] some_array = getResources().getStringArray(R.array.teachers); for (int i = 0 ; i <some_array.length;i++){ if(some_array[i].equals(myEvent.getTeacher())){ eventActivity.putExtra("Teacher",i); break; } } String[] some_array1 = getResources().getStringArray(R.array.lesson); for (int i = 0 ; i <some_array1.length;i++){ if(some_array1[i].equals(myEvent.getDers())){ eventActivity.putExtra("Ders",i); break; } } if(startTime.get((Calendar.DAY_OF_WEEK))==Calendar.MONDAY){ eventActivity.putExtra("Day",0); }else if(startTime.get((Calendar.DAY_OF_WEEK))==Calendar.TUESDAY){ eventActivity.putExtra("Day",1); }else if(startTime.get((Calendar.DAY_OF_WEEK))==Calendar.WEDNESDAY){ eventActivity.putExtra("Day",2); }else if(startTime.get((Calendar.DAY_OF_WEEK))==Calendar.THURSDAY){ eventActivity.putExtra("Day",3); }else if(startTime.get((Calendar.DAY_OF_WEEK))==Calendar.FRIDAY){ eventActivity.putExtra("Day",4); }else if(startTime.get((Calendar.DAY_OF_WEEK))==Calendar.SATURDAY){ eventActivity.putExtra("Day",5); }else if(startTime.get((Calendar.DAY_OF_WEEK))==Calendar.SUNDAY){ eventActivity.putExtra("Day",6); } if(myEvent.getGrade().equals("A1")){ eventActivity.putExtra("Grade",0); }else if(myEvent.getGrade().equals("A1+")){ eventActivity.putExtra("Grade",1); }else if(myEvent.getGrade().equals("A2")){ eventActivity.putExtra("Grade",2); }else if(myEvent.getGrade().equals("B1")){ eventActivity.putExtra("Grade",3); }else if(myEvent.getGrade().equals("B2")){ eventActivity.putExtra("Grade",4); }else if(myEvent.getGrade().equals("C1")){ eventActivity.putExtra("Grade",5); }else if(myEvent.getGrade().equals("Advanced")){ eventActivity.putExtra("Grade",6); } startActivityForResult(eventActivity, 1); //lessonInfoSnapshot.getRef().removeValue(); } myDialog.dismiss(); // Refresh the week view. onMonthChange will be called again. } } @Override public void onCancelled(DatabaseError databaseError) { System.out.println("Student Verisi Çekilemedi."); } }); // //startActivityForResult(eventActivity, 1); } }); delete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { databaseLessonInfo.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for (DataSnapshot lessonInfoSnapshot : dataSnapshot.getChildren() ){ //Create Artist Class Object and Returning Value LessonInfo lessonInfo = lessonInfoSnapshot.getValue(LessonInfo.class); Calendar startTime=Calendar.getInstance(); Calendar endTime=Calendar.getInstance(); String[] calendarStartItem = lessonInfo.getBaslangic().split("%"); String[] calendarEndItem = lessonInfo.getBitis().split("%"); for (String t : calendarStartItem) System.out.println(t); startTime.set(Integer.parseInt(calendarStartItem[0]),Integer.parseInt(calendarStartItem[1]),Integer.parseInt(calendarStartItem[2]),Integer.parseInt(calendarStartItem[3]),Integer.parseInt(calendarStartItem[4])); endTime.set(Integer.parseInt(calendarEndItem[0]),Integer.parseInt(calendarEndItem[1]),Integer.parseInt(calendarEndItem[2]),Integer.parseInt(calendarEndItem[3]),Integer.parseInt(calendarEndItem[4])); WeekViewEvent myEvent = new WeekViewEvent(lessonInfo.getGrade(), lessonInfo.getTeacher(), lessonInfo.getIcerik(), startTime, endTime,lessonInfo.getDers()); if(event.getGrade()==myEvent.getGrade()){ lessonInfoSnapshot.getRef().removeValue(); } myDialog.dismiss(); // Refresh the week view. onMonthChange will be called again. } } @Override public void onCancelled(DatabaseError databaseError) { System.out.println("Student Verisi Çekilemedi."); } }); } }); myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); myDialog.show(); } // @Override // public void onEmptyViewClicked(Calendar time) { // // Set the new event with duration one hour. // Calendar endTime = (Calendar) time.clone(); // endTime.add(Calendar.HOUR, 1); // // // Create a new event. // WeekViewEvent event = new WeekViewEvent(20, "New event", time, endTime); // mNewEvents.add(event); // // // Refresh the week view. onMonthChange will be called again. // mWeekView.notifyDatasetChanged(); // } @Override public void onEmptyViewClicked(Calendar time) { System.out.println(time.getTime()); selectedDate = time; final Intent eventActivity = new Intent(getContext(), EventActvity.class); eventActivity.putExtra("hour", time.get(Calendar.HOUR_OF_DAY)); eventActivity.putExtra("minute", time.get(Calendar.MINUTE)); eventActivity.putExtra("isFloatingButtonClicked", false); eventActivity.putExtra("isUpdate",false); eventActivity.putExtra("Day",0); eventActivity.putExtra("Grade",0); eventActivity.putExtra("Teacher",0); calendarStartTime=time; calendarEndTime=time; startActivityForResult(eventActivity, 1); Toast.makeText(getActivity(), "Empty view clicked: " + getEventTitle(time), Toast.LENGTH_SHORT).show(); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 1) { if (resultCode == Activity.RESULT_OK) { baslangic = data.getStringExtra("baslangic"); bitis = data.getStringExtra("bitis"); grade = data.getStringExtra("grade"); ders = data.getStringExtra("ders"); teacher = data.getStringExtra("teacher"); icerik = data.getStringExtra("icerik"); day = data.getIntExtra("day",2); System.out.println("dayyyyyyyyyyyyyyyyyyyyyyyyyyy " + day); String[] parse; String[] parse2; parse = baslangic.split(":"); parse2 = bitis.split(":"); System.out.println(baslangic); System.out.println(bitis); System.out.println(grade); System.out.println(teacher); System.out.println(icerik); selectedDate .add(Calendar.DATE,day); calendarStartTime.add(Calendar.DATE,day); calendarEndTime.add(Calendar.DATE,day); Calendar endTime = (Calendar) selectedDate.clone(); endTime.add(Calendar.HOUR, 1); System.out.println("Month = "+selectedDate.get(Calendar.MONTH)); // Create a new event. //WeekViewEvent event = new WeekViewEvent(20, "New event", selectedDate, endTime); // WeekViewEvent myEvent = new WeekViewEvent(grade, teacher, icerik, selectedDate, endTime); // myEvent.setColor(R.color.event_color_02); // mNewEvents.add(myEvent); endHour = parse2[0]; startHour = parse[0]; calendarStartTime.set(Calendar.HOUR_OF_DAY,Integer.parseInt(parse[0])); System.out.println(calendarStartTime.get(Calendar.HOUR_OF_DAY)); calendarEndTime.set(Calendar.HOUR_OF_DAY,Integer.parseInt(parse2[0])); System.out.println(calendarEndTime.get(Calendar.HOUR_OF_DAY)); // Refresh the week view. onMonthChange will be called again. //mWeekView.notifyDatasetChanged(); addLessonInfo(); }else if(resultCode==2){ baslangic = data.getStringExtra("baslangic"); bitis = data.getStringExtra("bitis"); grade = data.getStringExtra("grade"); ders = data.getStringExtra("ders"); teacher = data.getStringExtra("teacher"); icerik = data.getStringExtra("icerik"); day = data.getIntExtra("day",2); System.out.println("dayyyyyyyyyyyyyyyyyyyyyyyyyyy " + day); String[] parse; String[] parse2; parse = baslangic.split(":"); parse2 = bitis.split(":"); System.out.println(baslangic); System.out.println(bitis); System.out.println(grade); System.out.println(teacher); System.out.println(icerik); selectedDate .add(Calendar.DATE,day); calendarStartTime.add(Calendar.DATE,day); calendarEndTime.add(Calendar.DATE,day); Calendar endTime = (Calendar) selectedDate.clone(); endTime.add(Calendar.HOUR, 1); System.out.println("Month = "+selectedDate.get(Calendar.MONTH)); // Create a new event. //WeekViewEvent event = new WeekViewEvent(20, "New event", selectedDate, endTime); // WeekViewEvent myEvent = new WeekViewEvent(grade, teacher, icerik, selectedDate, endTime); // myEvent.setColor(R.color.event_color_02); // mNewEvents.add(myEvent); endHour = parse2[0]; startHour = parse[0]; calendarStartTime.set(Calendar.HOUR_OF_DAY,Integer.parseInt(parse[0])); System.out.println(calendarStartTime.get(Calendar.HOUR_OF_DAY)); calendarEndTime.set(Calendar.HOUR_OF_DAY,Integer.parseInt(parse2[0])); System.out.println(calendarEndTime.get(Calendar.HOUR_OF_DAY)); // Refresh the week view. onMonthChange will be called again. //mWeekView.notifyDatasetChanged(); updateLessonInfo(data.getStringExtra("key")); } else if (resultCode == 0) { System.out.println("RESULT CANCELLED"); } } } @Override public void onEventLongPress(WeekViewEvent event, RectF eventRect) { Toast.makeText(getActivity(), "Long pressed event: " + event.getContent(), Toast.LENGTH_SHORT).show(); } @Override public void onEmptyViewLongPress(Calendar time) { Toast.makeText(getActivity(), "Empty view long pressed: " + getEventTitle(time), Toast.LENGTH_SHORT).show(); } public WeekView getWeekView() { return mWeekView; } private void updateLessonInfo(final String key){ databaseUpdate.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for (DataSnapshot lessonInfoSnapshot : dataSnapshot.getChildren() ){ //Create Artist Class Object and Returning Value //Create An Artist Object int startYear= calendarStartTime.get(Calendar.YEAR); int startMonth = calendarStartTime.get(Calendar.MONTH); int startDay = calendarStartTime.get(Calendar.DAY_OF_MONTH); //int startHour = calendarStartTime.get(Calendar.HOUR_OF_DAY); int startMinute = 30; //calendarEndTime.set(Calendar.HOUR_OF_DAY,(calendarStartTime.get(Calendar.HOUR_OF_DAY)+1)); //int endHour = calendarEndTime.get(Calendar.HOUR_OF_DAY); int endMinute = 30; String startTime = startYear+"%" + startMonth +"%" + startDay + "%" + Integer.parseInt(startHour) + "%" + startMinute; String endTime = startYear+"%" + startMonth+"%" + startDay + "%" + Integer.parseInt(endHour) + "%" + endMinute; System.out.println("start time = " + startTime); System.out.println("end time = " + endTime); LessonInfo lessonInfo= new LessonInfo(startTime,endTime,grade,teacher,icerik,ders,key); if(lessonInfoSnapshot.getKey().equals(key)){ lessonInfoSnapshot.getRef().setValue(lessonInfo); } // Refresh the week view. onMonthChange will be called again. } } @Override public void onCancelled(DatabaseError databaseError) { System.out.println("Student Verisi Çekilemedi."); } }); } private void addLessonInfo(){ String id = databaseLessonInfo.push().getKey(); //Create An Artist Object int startYear= calendarStartTime.get(Calendar.YEAR); int startMonth = calendarStartTime.get(Calendar.MONTH); int startDay = calendarStartTime.get(Calendar.DAY_OF_MONTH); //int startHour = calendarStartTime.get(Calendar.HOUR_OF_DAY); int startMinute = 30; //calendarEndTime.set(Calendar.HOUR_OF_DAY,(calendarStartTime.get(Calendar.HOUR_OF_DAY)+1)); //int endHour = calendarEndTime.get(Calendar.HOUR_OF_DAY); int endMinute = 30; String startTime = startYear+"%" + startMonth +"%" + startDay + "%" + Integer.parseInt(startHour) + "%" + startMinute; String endTime = startYear+"%" + startMonth+"%" + startDay + "%" + Integer.parseInt(endHour) + "%" + endMinute; System.out.println("start time = " + startTime); System.out.println("end time = " + endTime); LessonInfo lessonInfo= new LessonInfo(startTime,endTime,grade,teacher,icerik,ders,id); databaseLessonInfo.child(id).setValue(lessonInfo); Toast.makeText(getActivity(),"Succesfully Stored Data",Toast.LENGTH_LONG).show(); } }
UTF-8
Java
34,492
java
FragmentOne.java
Java
[]
null
[]
package com.alam_kanak; import android.app.Activity; import android.app.Dialog; import android.content.Intent; import android.graphics.Color; import android.graphics.RectF; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.CardView; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.alamkanak.weekview.DateTimeInterpreter; import com.alamkanak.weekview.MonthLoader; import com.alamkanak.weekview.WeekView; import com.alamkanak.weekview.WeekViewEvent; import com.firebaseDemo.Artist; import com.firebaseDemo.LessonInfo; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.onur.easyspeakdemo.EventActvity; import com.onur.easyspeakdemo.R; import com.studentsTabLayout.MyAdapter; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.List; import java.util.Locale; public class FragmentOne extends Fragment implements WeekView.EventClickListener, MonthLoader.MonthChangeListener,WeekView.EmptyViewClickListener, WeekView.EventLongPressListener, WeekView.EmptyViewLongPressListener { private static final int TYPE_DAY_VIEW = 1; private static final int TYPE_THREE_DAY_VIEW = 2; private static final int TYPE_WEEK_VIEW = 3; private int mWeekViewType = TYPE_THREE_DAY_VIEW; private WeekView mWeekView; private ArrayList<WeekViewEvent> mNewEvents; private Calendar selectedDate; private DatabaseReference databaseLessonInfo; private DatabaseReference databaseUpdate; String baslangic; int day; String bitis; String grade; String ders; String teacher; String icerik ; Calendar calendarStartTime; Calendar calendarEndTime; String endHour; String startHour; int a1,a1Plus,a2,b1,b2,c1,advanced; Dialog myDialog; TextView titleTv,messageTv; ImageView closeButton; CardView card; Button delete,update; public static FragmentOne newInstance( int mWeekViewType) { Bundle bundle = new Bundle(); bundle.putInt("mWeekViewType", mWeekViewType); FragmentOne fragment = new FragmentOne(); fragment.setArguments(bundle); return fragment; } private void readBundle(Bundle bundle) { if (bundle != null) { mWeekViewType = bundle.getInt("mWeekViewType"); if (mWeekViewType == 3) { mWeekViewType = TYPE_THREE_DAY_VIEW; mWeekView.setNumberOfVisibleDays(3); // Lets change some dimensions to best fit the view. mWeekView.setColumnGap((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8, getResources().getDisplayMetrics())); mWeekView.setTextSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 12, getResources().getDisplayMetrics())); mWeekView.setEventTextSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 12, getResources().getDisplayMetrics())); } else{ mWeekViewType = TYPE_WEEK_VIEW; mWeekView.setNumberOfVisibleDays(7); // Lets change some dimensions to best fit the view. mWeekView.setColumnGap((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, getResources().getDisplayMetrics())); mWeekView.setTextSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 10, getResources().getDisplayMetrics())); mWeekView.setEventTextSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 10, getResources().getDisplayMetrics())); } } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.activity_sample, container, false); a1=view.getResources().getColor(R.color.a1LessonColor); a1Plus=view.getResources().getColor(R.color.a1PlusLessonColor); a2=view.getResources().getColor(R.color.a2LessonColor); b1=view.getResources().getColor(R.color.b1LessonColor); b2=view.getResources().getColor(R.color.b2LessonColor); c1=view.getResources().getColor(R.color.c1LessonColor); advanced=view.getResources().getColor(R.color.advencedLessonColor); myDialog = new Dialog(view.getContext()); databaseLessonInfo = FirebaseDatabase.getInstance().getReference("lessonInfo"); databaseUpdate = FirebaseDatabase.getInstance().getReference("lessonInfo"); FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Click action selectedDate = Calendar.getInstance(); selectedDate.setFirstDayOfWeek(Calendar.MONDAY); calendarStartTime=Calendar.getInstance(); calendarEndTime=Calendar.getInstance(); calendarStartTime.setFirstDayOfWeek(Calendar.MONDAY); calendarEndTime.setFirstDayOfWeek(Calendar.MONDAY); while (selectedDate.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) { selectedDate.add(Calendar.DATE, -1); calendarStartTime.add(Calendar.DATE, -1); calendarEndTime.add(Calendar.DATE, -1); } Intent eventActivity = new Intent(getActivity(), EventActvity.class); eventActivity.putExtra("hour", 10); eventActivity.putExtra("minute", 30); eventActivity.putExtra("isFloatingButtonClicked", true); eventActivity.putExtra("isUpdate",false); eventActivity.putExtra("Day",0); eventActivity.putExtra("Grade",0); eventActivity.putExtra("Teacher",0); startActivityForResult(eventActivity, 1); } }); // Get a reference for the week view in the layout. mWeekView = (WeekView) view.findViewById(R.id.weekView); // Show a toast message about the touched event. mWeekView.setOnEventClickListener(this); // The week view has infinite scrolling horizontally. We have to provide the events of a // month every time the month changes on the week view. mWeekView.setMonthChangeListener(this); // Set long press listener for events. mWeekView.setEventLongPressListener(this); // Set long press listener for empty view mWeekView.setEmptyViewLongPressListener(this); mWeekView.setEmptyViewClickListener(this); mNewEvents = new ArrayList<WeekViewEvent>(); // Set up a date time interpreter to interpret how the date and time will be formatted in // the week view. This is optional. setupDateTimeInterpreter(false); readBundle(getArguments()); return view; } @Override public void onStart() { super.onStart(); //Retriving data From Firebase databaseLessonInfo.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { mNewEvents.clear(); for (DataSnapshot lessonInfoSnapshot : dataSnapshot.getChildren() ){ //Create Artist Class Object and Returning Value LessonInfo lessonInfo = lessonInfoSnapshot.getValue(LessonInfo.class); Calendar startTime=Calendar.getInstance(); Calendar endTime=Calendar.getInstance(); String[] calendarStartItem = lessonInfo.getBaslangic().split("%"); String[] calendarEndItem = lessonInfo.getBitis().split("%"); for (String t : calendarStartItem) System.out.println(t); startTime.set(Integer.parseInt(calendarStartItem[0]),Integer.parseInt(calendarStartItem[1]),Integer.parseInt(calendarStartItem[2]),Integer.parseInt(calendarStartItem[3]),Integer.parseInt(calendarStartItem[4])); endTime.set(Integer.parseInt(calendarEndItem[0]),Integer.parseInt(calendarEndItem[1]),Integer.parseInt(calendarEndItem[2]),Integer.parseInt(calendarEndItem[3]),Integer.parseInt(calendarEndItem[4])); WeekViewEvent myEvent = new WeekViewEvent(lessonInfo.getGrade(), lessonInfo.getTeacher(), lessonInfo.getIcerik(), startTime, endTime,lessonInfo.getDers()); if(lessonInfo.getGrade().equals("A1")){ myEvent.setColor(a1); }else if(lessonInfo.getGrade().equals("A1+")){ myEvent.setColor(a1Plus); }else if(lessonInfo.getGrade().equals("A2")){ myEvent.setColor(a2); }else if(lessonInfo.getGrade().equals("B1")){ myEvent.setColor(b1); }else if(lessonInfo.getGrade().equals("B2")){ myEvent.setColor(b2); }else if(lessonInfo.getGrade().equals("C1")){ myEvent.setColor(c1); }else if(lessonInfo.getGrade().equals("Advanced")){ myEvent.setColor(advanced); } mNewEvents.add(myEvent); // Refresh the week view. onMonthChange will be called again. } mWeekView.notifyDatasetChanged(); } @Override public void onCancelled(DatabaseError databaseError) { System.out.println("Student Verisi Çekilemedi."); } }); } @Override public List<WeekViewEvent> onMonthChange(int newYear, int newMonth) { // Populate the week view with the events that was added by tapping on empty view. List<WeekViewEvent> events = new ArrayList<WeekViewEvent>(); ArrayList<WeekViewEvent> newEvents = getNewEvents(newYear, newMonth); events.addAll(newEvents); return events; } /** * Get events that were added by tapping on empty view. * * @param year The year currently visible on the week view. * @param month The month currently visible on the week view. * @return The events of the given year and month. */ private ArrayList<WeekViewEvent> getNewEvents(int year, int month) { // Get the starting point and ending point of the given month. We need this to find the // events of the given month. Calendar startOfMonth = Calendar.getInstance(); startOfMonth.set(Calendar.YEAR, year); startOfMonth.set(Calendar.MONTH, month - 1); startOfMonth.set(Calendar.DAY_OF_MONTH, 1); startOfMonth.set(Calendar.HOUR_OF_DAY, 0); startOfMonth.set(Calendar.MINUTE, 0); startOfMonth.set(Calendar.SECOND, 0); startOfMonth.set(Calendar.MILLISECOND, 0); Calendar endOfMonth = (Calendar) startOfMonth.clone(); endOfMonth.set(Calendar.DAY_OF_MONTH, endOfMonth.getMaximum(Calendar.DAY_OF_MONTH)); endOfMonth.set(Calendar.HOUR_OF_DAY, 23); endOfMonth.set(Calendar.MINUTE, 59); endOfMonth.set(Calendar.SECOND, 59); // Find the events that were added by tapping on empty view and that occurs in the given // time frame. ArrayList<WeekViewEvent> events = new ArrayList<WeekViewEvent>(); for (WeekViewEvent event : mNewEvents) { events.add(event); } return events; } private void setupDateTimeInterpreter(final boolean shortDate) { mWeekView.setDateTimeInterpreter(new DateTimeInterpreter() { @Override public String interpretDate(Calendar date) { SimpleDateFormat weekdayNameFormat = new SimpleDateFormat("EEEE", Locale.getDefault()); String weekday = weekdayNameFormat.format(date.getTime()); SimpleDateFormat format = new SimpleDateFormat(" d", Locale.getDefault()); // All android api level do not have a standard way of getting the first letter of // the week day name. Hence we get the first char programmatically. // Details: http://stackoverflow.com/questions/16959502/get-one-letter-abbreviation-of-week-day-of-a-date-in-java#answer-16959657 if (shortDate) weekday = String.valueOf(weekday.charAt(0)); return weekday.toUpperCase() + format.format(date.getTime()); } @Override public String interpretTime(int hour) { if (hour > 12) { return (hour - 12) + " PM"; } else { return (hour) + " AM"; } } }); } protected String getEventTitle(Calendar time) { return String.format("Event of %02d:%02d %s/%d", time.get(Calendar.HOUR_OF_DAY), time.get(Calendar.MINUTE), time.get(Calendar.MONTH) + 1, time.get(Calendar.DAY_OF_MONTH)); } @Override public void onEventClick(final WeekViewEvent event, final RectF eventRect) { Toast.makeText(getActivity(), "Clicked " + event.getContent(), Toast.LENGTH_SHORT).show(); // AlertDialog.Builder builder = new AlertDialog.Builder(AlamKanakActivity.this); // builder.setTitle("Lesson Content"); // builder.setMessage(event.getGrade() + "\n" + event.getTeacher() + "\n" + event.getStartEnd() + "\n" + event.mGetContent()); myDialog.setContentView(R.layout.custom_dialog_box); messageTv = myDialog.findViewById(R.id.content); card = myDialog.findViewById(R.id.mycard); card.setBackgroundColor(event.getColor()); closeButton = myDialog.findViewById(R.id.close); delete = myDialog.findViewById(R.id.delete); update = myDialog.findViewById(R.id.update); messageTv.setText(event.getDers()+"\n"+event.getGrade() + "\n" + event.getTeacher() + "\n" + event.getStartEnd() + "\n" + event.mGetContent()); closeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { myDialog.dismiss(); } }); update.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { selectedDate = Calendar.getInstance(); selectedDate.setFirstDayOfWeek(Calendar.MONDAY); calendarStartTime=Calendar.getInstance(); calendarEndTime=Calendar.getInstance(); calendarStartTime.setFirstDayOfWeek(Calendar.MONDAY); calendarEndTime.setFirstDayOfWeek(Calendar.MONDAY); while (selectedDate.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) { selectedDate.add(Calendar.DATE, -1); calendarStartTime.add(Calendar.DATE, -1); calendarEndTime.add(Calendar.DATE, -1); } //final Intent eventActivity = new Intent(AlamKanakActivity.this, EventActvity.class); databaseUpdate.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for (DataSnapshot lessonInfoSnapshot : dataSnapshot.getChildren() ){ //Create Artist Class Object and Returning Value LessonInfo lessonInfo = lessonInfoSnapshot.getValue(LessonInfo.class); Calendar startTime=Calendar.getInstance(); Calendar endTime=Calendar.getInstance(); String[] calendarStartItem = lessonInfo.getBaslangic().split("%"); String[] calendarEndItem = lessonInfo.getBitis().split("%"); for (String t : calendarStartItem) System.out.println(t); startTime.set(Integer.parseInt(calendarStartItem[0]),Integer.parseInt(calendarStartItem[1]),Integer.parseInt(calendarStartItem[2]),Integer.parseInt(calendarStartItem[3]),Integer.parseInt(calendarStartItem[4])); endTime.set(Integer.parseInt(calendarEndItem[0]),Integer.parseInt(calendarEndItem[1]),Integer.parseInt(calendarEndItem[2]),Integer.parseInt(calendarEndItem[3]),Integer.parseInt(calendarEndItem[4])); WeekViewEvent myEvent = new WeekViewEvent(lessonInfo.getGrade(), lessonInfo.getTeacher(), lessonInfo.getIcerik(), startTime, endTime,lessonInfo.getDers()); if(event.getGrade()==myEvent.getGrade()){ final Intent eventActivity = new Intent(getContext(), EventActvity.class); eventActivity.putExtra("hour", startTime.get(Calendar.HOUR_OF_DAY)); eventActivity.putExtra("minute", startTime.get(Calendar.MINUTE)); eventActivity.putExtra("isFloatingButtonClicked", true); eventActivity.putExtra("isUpdate",true); eventActivity.putExtra("Key",lessonInfoSnapshot.getKey()); eventActivity.putExtra("Content",myEvent.mGetContent()); String[] some_array = getResources().getStringArray(R.array.teachers); for (int i = 0 ; i <some_array.length;i++){ if(some_array[i].equals(myEvent.getTeacher())){ eventActivity.putExtra("Teacher",i); break; } } String[] some_array1 = getResources().getStringArray(R.array.lesson); for (int i = 0 ; i <some_array1.length;i++){ if(some_array1[i].equals(myEvent.getDers())){ eventActivity.putExtra("Ders",i); break; } } if(startTime.get((Calendar.DAY_OF_WEEK))==Calendar.MONDAY){ eventActivity.putExtra("Day",0); }else if(startTime.get((Calendar.DAY_OF_WEEK))==Calendar.TUESDAY){ eventActivity.putExtra("Day",1); }else if(startTime.get((Calendar.DAY_OF_WEEK))==Calendar.WEDNESDAY){ eventActivity.putExtra("Day",2); }else if(startTime.get((Calendar.DAY_OF_WEEK))==Calendar.THURSDAY){ eventActivity.putExtra("Day",3); }else if(startTime.get((Calendar.DAY_OF_WEEK))==Calendar.FRIDAY){ eventActivity.putExtra("Day",4); }else if(startTime.get((Calendar.DAY_OF_WEEK))==Calendar.SATURDAY){ eventActivity.putExtra("Day",5); }else if(startTime.get((Calendar.DAY_OF_WEEK))==Calendar.SUNDAY){ eventActivity.putExtra("Day",6); } if(myEvent.getGrade().equals("A1")){ eventActivity.putExtra("Grade",0); }else if(myEvent.getGrade().equals("A1+")){ eventActivity.putExtra("Grade",1); }else if(myEvent.getGrade().equals("A2")){ eventActivity.putExtra("Grade",2); }else if(myEvent.getGrade().equals("B1")){ eventActivity.putExtra("Grade",3); }else if(myEvent.getGrade().equals("B2")){ eventActivity.putExtra("Grade",4); }else if(myEvent.getGrade().equals("C1")){ eventActivity.putExtra("Grade",5); }else if(myEvent.getGrade().equals("Advanced")){ eventActivity.putExtra("Grade",6); } startActivityForResult(eventActivity, 1); //lessonInfoSnapshot.getRef().removeValue(); } myDialog.dismiss(); // Refresh the week view. onMonthChange will be called again. } } @Override public void onCancelled(DatabaseError databaseError) { System.out.println("Student Verisi Çekilemedi."); } }); // //startActivityForResult(eventActivity, 1); } }); delete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { databaseLessonInfo.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for (DataSnapshot lessonInfoSnapshot : dataSnapshot.getChildren() ){ //Create Artist Class Object and Returning Value LessonInfo lessonInfo = lessonInfoSnapshot.getValue(LessonInfo.class); Calendar startTime=Calendar.getInstance(); Calendar endTime=Calendar.getInstance(); String[] calendarStartItem = lessonInfo.getBaslangic().split("%"); String[] calendarEndItem = lessonInfo.getBitis().split("%"); for (String t : calendarStartItem) System.out.println(t); startTime.set(Integer.parseInt(calendarStartItem[0]),Integer.parseInt(calendarStartItem[1]),Integer.parseInt(calendarStartItem[2]),Integer.parseInt(calendarStartItem[3]),Integer.parseInt(calendarStartItem[4])); endTime.set(Integer.parseInt(calendarEndItem[0]),Integer.parseInt(calendarEndItem[1]),Integer.parseInt(calendarEndItem[2]),Integer.parseInt(calendarEndItem[3]),Integer.parseInt(calendarEndItem[4])); WeekViewEvent myEvent = new WeekViewEvent(lessonInfo.getGrade(), lessonInfo.getTeacher(), lessonInfo.getIcerik(), startTime, endTime,lessonInfo.getDers()); if(event.getGrade()==myEvent.getGrade()){ lessonInfoSnapshot.getRef().removeValue(); } myDialog.dismiss(); // Refresh the week view. onMonthChange will be called again. } } @Override public void onCancelled(DatabaseError databaseError) { System.out.println("Student Verisi Çekilemedi."); } }); } }); myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); myDialog.show(); } // @Override // public void onEmptyViewClicked(Calendar time) { // // Set the new event with duration one hour. // Calendar endTime = (Calendar) time.clone(); // endTime.add(Calendar.HOUR, 1); // // // Create a new event. // WeekViewEvent event = new WeekViewEvent(20, "New event", time, endTime); // mNewEvents.add(event); // // // Refresh the week view. onMonthChange will be called again. // mWeekView.notifyDatasetChanged(); // } @Override public void onEmptyViewClicked(Calendar time) { System.out.println(time.getTime()); selectedDate = time; final Intent eventActivity = new Intent(getContext(), EventActvity.class); eventActivity.putExtra("hour", time.get(Calendar.HOUR_OF_DAY)); eventActivity.putExtra("minute", time.get(Calendar.MINUTE)); eventActivity.putExtra("isFloatingButtonClicked", false); eventActivity.putExtra("isUpdate",false); eventActivity.putExtra("Day",0); eventActivity.putExtra("Grade",0); eventActivity.putExtra("Teacher",0); calendarStartTime=time; calendarEndTime=time; startActivityForResult(eventActivity, 1); Toast.makeText(getActivity(), "Empty view clicked: " + getEventTitle(time), Toast.LENGTH_SHORT).show(); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 1) { if (resultCode == Activity.RESULT_OK) { baslangic = data.getStringExtra("baslangic"); bitis = data.getStringExtra("bitis"); grade = data.getStringExtra("grade"); ders = data.getStringExtra("ders"); teacher = data.getStringExtra("teacher"); icerik = data.getStringExtra("icerik"); day = data.getIntExtra("day",2); System.out.println("dayyyyyyyyyyyyyyyyyyyyyyyyyyy " + day); String[] parse; String[] parse2; parse = baslangic.split(":"); parse2 = bitis.split(":"); System.out.println(baslangic); System.out.println(bitis); System.out.println(grade); System.out.println(teacher); System.out.println(icerik); selectedDate .add(Calendar.DATE,day); calendarStartTime.add(Calendar.DATE,day); calendarEndTime.add(Calendar.DATE,day); Calendar endTime = (Calendar) selectedDate.clone(); endTime.add(Calendar.HOUR, 1); System.out.println("Month = "+selectedDate.get(Calendar.MONTH)); // Create a new event. //WeekViewEvent event = new WeekViewEvent(20, "New event", selectedDate, endTime); // WeekViewEvent myEvent = new WeekViewEvent(grade, teacher, icerik, selectedDate, endTime); // myEvent.setColor(R.color.event_color_02); // mNewEvents.add(myEvent); endHour = parse2[0]; startHour = parse[0]; calendarStartTime.set(Calendar.HOUR_OF_DAY,Integer.parseInt(parse[0])); System.out.println(calendarStartTime.get(Calendar.HOUR_OF_DAY)); calendarEndTime.set(Calendar.HOUR_OF_DAY,Integer.parseInt(parse2[0])); System.out.println(calendarEndTime.get(Calendar.HOUR_OF_DAY)); // Refresh the week view. onMonthChange will be called again. //mWeekView.notifyDatasetChanged(); addLessonInfo(); }else if(resultCode==2){ baslangic = data.getStringExtra("baslangic"); bitis = data.getStringExtra("bitis"); grade = data.getStringExtra("grade"); ders = data.getStringExtra("ders"); teacher = data.getStringExtra("teacher"); icerik = data.getStringExtra("icerik"); day = data.getIntExtra("day",2); System.out.println("dayyyyyyyyyyyyyyyyyyyyyyyyyyy " + day); String[] parse; String[] parse2; parse = baslangic.split(":"); parse2 = bitis.split(":"); System.out.println(baslangic); System.out.println(bitis); System.out.println(grade); System.out.println(teacher); System.out.println(icerik); selectedDate .add(Calendar.DATE,day); calendarStartTime.add(Calendar.DATE,day); calendarEndTime.add(Calendar.DATE,day); Calendar endTime = (Calendar) selectedDate.clone(); endTime.add(Calendar.HOUR, 1); System.out.println("Month = "+selectedDate.get(Calendar.MONTH)); // Create a new event. //WeekViewEvent event = new WeekViewEvent(20, "New event", selectedDate, endTime); // WeekViewEvent myEvent = new WeekViewEvent(grade, teacher, icerik, selectedDate, endTime); // myEvent.setColor(R.color.event_color_02); // mNewEvents.add(myEvent); endHour = parse2[0]; startHour = parse[0]; calendarStartTime.set(Calendar.HOUR_OF_DAY,Integer.parseInt(parse[0])); System.out.println(calendarStartTime.get(Calendar.HOUR_OF_DAY)); calendarEndTime.set(Calendar.HOUR_OF_DAY,Integer.parseInt(parse2[0])); System.out.println(calendarEndTime.get(Calendar.HOUR_OF_DAY)); // Refresh the week view. onMonthChange will be called again. //mWeekView.notifyDatasetChanged(); updateLessonInfo(data.getStringExtra("key")); } else if (resultCode == 0) { System.out.println("RESULT CANCELLED"); } } } @Override public void onEventLongPress(WeekViewEvent event, RectF eventRect) { Toast.makeText(getActivity(), "Long pressed event: " + event.getContent(), Toast.LENGTH_SHORT).show(); } @Override public void onEmptyViewLongPress(Calendar time) { Toast.makeText(getActivity(), "Empty view long pressed: " + getEventTitle(time), Toast.LENGTH_SHORT).show(); } public WeekView getWeekView() { return mWeekView; } private void updateLessonInfo(final String key){ databaseUpdate.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for (DataSnapshot lessonInfoSnapshot : dataSnapshot.getChildren() ){ //Create Artist Class Object and Returning Value //Create An Artist Object int startYear= calendarStartTime.get(Calendar.YEAR); int startMonth = calendarStartTime.get(Calendar.MONTH); int startDay = calendarStartTime.get(Calendar.DAY_OF_MONTH); //int startHour = calendarStartTime.get(Calendar.HOUR_OF_DAY); int startMinute = 30; //calendarEndTime.set(Calendar.HOUR_OF_DAY,(calendarStartTime.get(Calendar.HOUR_OF_DAY)+1)); //int endHour = calendarEndTime.get(Calendar.HOUR_OF_DAY); int endMinute = 30; String startTime = startYear+"%" + startMonth +"%" + startDay + "%" + Integer.parseInt(startHour) + "%" + startMinute; String endTime = startYear+"%" + startMonth+"%" + startDay + "%" + Integer.parseInt(endHour) + "%" + endMinute; System.out.println("start time = " + startTime); System.out.println("end time = " + endTime); LessonInfo lessonInfo= new LessonInfo(startTime,endTime,grade,teacher,icerik,ders,key); if(lessonInfoSnapshot.getKey().equals(key)){ lessonInfoSnapshot.getRef().setValue(lessonInfo); } // Refresh the week view. onMonthChange will be called again. } } @Override public void onCancelled(DatabaseError databaseError) { System.out.println("Student Verisi Çekilemedi."); } }); } private void addLessonInfo(){ String id = databaseLessonInfo.push().getKey(); //Create An Artist Object int startYear= calendarStartTime.get(Calendar.YEAR); int startMonth = calendarStartTime.get(Calendar.MONTH); int startDay = calendarStartTime.get(Calendar.DAY_OF_MONTH); //int startHour = calendarStartTime.get(Calendar.HOUR_OF_DAY); int startMinute = 30; //calendarEndTime.set(Calendar.HOUR_OF_DAY,(calendarStartTime.get(Calendar.HOUR_OF_DAY)+1)); //int endHour = calendarEndTime.get(Calendar.HOUR_OF_DAY); int endMinute = 30; String startTime = startYear+"%" + startMonth +"%" + startDay + "%" + Integer.parseInt(startHour) + "%" + startMinute; String endTime = startYear+"%" + startMonth+"%" + startDay + "%" + Integer.parseInt(endHour) + "%" + endMinute; System.out.println("start time = " + startTime); System.out.println("end time = " + endTime); LessonInfo lessonInfo= new LessonInfo(startTime,endTime,grade,teacher,icerik,ders,id); databaseLessonInfo.child(id).setValue(lessonInfo); Toast.makeText(getActivity(),"Succesfully Stored Data",Toast.LENGTH_LONG).show(); } }
34,492
0.588408
0.582348
810
41.579014
38.889545
238
false
false
0
0
0
0
0
0
0.730864
false
false
5
b642186a04f38eb067175cfc91912e3ab699ca44
15,393,162,815,966
b6a3c5c4e778f5818e423995f5bae57f475d8a87
/src/main/java/com/codeshare/codeexecutor/commandbox/CommadBoxContainerTest.java
9a11abe561c01bb032223f71ee50d0aefa9db3ce
[]
no_license
vibhorrastogi-github/src-code-executor
https://github.com/vibhorrastogi-github/src-code-executor
ffeb475e0494df7f0264a12610cd33649c9e702a
b8e3869693d4722014d1a5fee8a95b471e2f630b
refs/heads/master
2020-05-25T11:20:10.349000
2015-09-04T10:12:32
2015-09-04T10:12:32
41,908,737
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package com.codeshare.codeexecutor.commandbox; import java.io.File; import java.util.HashSet; import java.util.Set; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import com.codeshare.codeexecutor.common.CommandType; /** * @author vibhor * */ public class CommadBoxContainerTest { public static void main(String[] args) throws JAXBException { // System.out.println(System.getProperty("os.name")); // System.getProperties().list(System.out); // generateCommandBox(); System.out.println(new CommandBoxContainer().getComandInfo("java", CommandType.COMPILE)); } public static void generateCommandBox() throws JAXBException { final JAXBContext context = JAXBContext.newInstance(CommandBox.class, Language.class); final Marshaller marshaller = context.createMarshaller(); marshaller.marshal(getCommandBox(), new File("cs_cb.xml")); System.out.println(true); } private static CommandBox getCommandBox() { CommandBox box = new CommandBox(); Set<Language> language = new HashSet<Language>(); box.setLanguage(language); Language lang = new Language(); language.add(lang); lang.setCompileCmd("javac"); lang.setExecuteCmd("java"); lang.setName("java"); lang = new Language(); language.add(lang); lang.setCompileCmd("tcc"); lang.setExecuteCmd(""); lang.setName("c"); return box; } }
UTF-8
Java
1,474
java
CommadBoxContainerTest.java
Java
[ { "context": "odeexecutor.common.CommandType;\r\n\r\n/**\r\n * @author vibhor\r\n * \r\n */\r\npublic class CommadBoxContainerTest {\r", "end": 329, "score": 0.9990382194519043, "start": 323, "tag": "USERNAME", "value": "vibhor" } ]
null
[]
/** * */ package com.codeshare.codeexecutor.commandbox; import java.io.File; import java.util.HashSet; import java.util.Set; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import com.codeshare.codeexecutor.common.CommandType; /** * @author vibhor * */ public class CommadBoxContainerTest { public static void main(String[] args) throws JAXBException { // System.out.println(System.getProperty("os.name")); // System.getProperties().list(System.out); // generateCommandBox(); System.out.println(new CommandBoxContainer().getComandInfo("java", CommandType.COMPILE)); } public static void generateCommandBox() throws JAXBException { final JAXBContext context = JAXBContext.newInstance(CommandBox.class, Language.class); final Marshaller marshaller = context.createMarshaller(); marshaller.marshal(getCommandBox(), new File("cs_cb.xml")); System.out.println(true); } private static CommandBox getCommandBox() { CommandBox box = new CommandBox(); Set<Language> language = new HashSet<Language>(); box.setLanguage(language); Language lang = new Language(); language.add(lang); lang.setCompileCmd("javac"); lang.setExecuteCmd("java"); lang.setName("java"); lang = new Language(); language.add(lang); lang.setCompileCmd("tcc"); lang.setExecuteCmd(""); lang.setName("c"); return box; } }
1,474
0.6981
0.6981
59
22.983051
21.038698
71
false
false
0
0
0
0
0
0
1.542373
false
false
5
52430f1ac68244d94e6ce9c451be5f7cb024f3bd
773,094,143,123
51b09cbd4efde7d8617a8784260b9f7487ec2fea
/app/src/main/java/com/lynx/formi/ulsucanteen/presentation/menu/eat/EatView.java
cb4e995214e149911b6b41bb8eb9159ab6508d23
[]
no_license
AlexUndeRSV/UlsuCanteen
https://github.com/AlexUndeRSV/UlsuCanteen
92f2a9c4b5f10492ee839efe06164799ea6e2436
e1b7ca772f00f267ab761f77a14eb8de70a40afe
refs/heads/master
2020-03-29T13:59:15.256000
2018-12-03T17:11:36
2018-12-03T17:11:36
149,993,140
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lynx.formi.ulsucanteen.presentation.menu.eat; import com.arellomobile.mvp.MvpView; import com.arellomobile.mvp.viewstate.strategy.AddToEndSingleStrategy; import com.arellomobile.mvp.viewstate.strategy.StateStrategyType; import com.lynx.formi.ulsucanteen.domain.dataclass.Food; import java.util.List; public interface EatView extends MvpView { @StateStrategyType(AddToEndSingleStrategy.class) void setFoodList(List<Food> foodList); }
UTF-8
Java
456
java
EatView.java
Java
[]
null
[]
package com.lynx.formi.ulsucanteen.presentation.menu.eat; import com.arellomobile.mvp.MvpView; import com.arellomobile.mvp.viewstate.strategy.AddToEndSingleStrategy; import com.arellomobile.mvp.viewstate.strategy.StateStrategyType; import com.lynx.formi.ulsucanteen.domain.dataclass.Food; import java.util.List; public interface EatView extends MvpView { @StateStrategyType(AddToEndSingleStrategy.class) void setFoodList(List<Food> foodList); }
456
0.828947
0.828947
13
34.076923
25.46026
70
false
false
0
0
0
0
0
0
0.538462
false
false
5
4035a1597876845109d7c8bd7cc4940f25ecbc9a
5,695,126,664,308
9a3ea51139778b78f2876249c3e3c1d0d0957650
/app/src/main/java/sdk/grayweb/com/slientsdk/util/SDKUtils.java
52e77f1f5ba8bb850646001ce282a85374fe343a
[]
no_license
lovekill/androidsdk
https://github.com/lovekill/androidsdk
0c9e9f0d40fc340e355b419248fdbe6b1106415e
ebd253b987e2d1722d1b41fe7658c830178be7f2
refs/heads/master
2021-01-01T04:57:04.680000
2016-05-25T03:24:43
2016-05-25T03:24:43
58,727,732
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package sdk.grayweb.com.slientsdk.util; import java.util.Map; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Environment; public class SDKUtils { public static String getMeteData(Context context, String tag) { ApplicationInfo info; try { info = context.getPackageManager().getApplicationInfo( context.getPackageName(), PackageManager.GET_META_DATA); String rex = info.metaData.getString(tag); if (rex == null) { return null; } if (rex.startsWith(tag + ":")) { return rex.split(":")[1]; } else { return null; } } catch (NameNotFoundException e) { e.printStackTrace(); } return null; } public static String getMeteDataNoTag(Context context, String tag) { ApplicationInfo info; try { info = context.getPackageManager().getApplicationInfo( context.getPackageName(), PackageManager.GET_META_DATA); String rex = info.metaData.getString(tag); if (rex == null) { return null; } return rex; } catch (NameNotFoundException e) { e.printStackTrace(); } return null; } public static String getSKCardPath() { return Environment.getExternalStorageDirectory().getAbsolutePath(); } public static String mapToJsonArrayString(Map<String, Object> map) { if (map.isEmpty()) return null; JSONArray jsonArray = new JSONArray(); for (String key : map.keySet()) { JSONObject jsonObject = new JSONObject(); try { jsonObject.put("key", key); jsonObject.put("value", map.get(key) + ""); jsonArray.put(jsonObject); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return jsonArray.toString(); } public static String mapToJson(Map<String, String> map) { JSONObject jsonObject = new JSONObject(); for (String key : map.keySet()) { try { jsonObject.put(key, map.get(key)); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return jsonObject.toString(); } public static boolean isEmpty(String str) { if (str == null) { return true; } return str.length() == 0; } }
UTF-8
Java
2,344
java
SDKUtils.java
Java
[]
null
[]
package sdk.grayweb.com.slientsdk.util; import java.util.Map; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Environment; public class SDKUtils { public static String getMeteData(Context context, String tag) { ApplicationInfo info; try { info = context.getPackageManager().getApplicationInfo( context.getPackageName(), PackageManager.GET_META_DATA); String rex = info.metaData.getString(tag); if (rex == null) { return null; } if (rex.startsWith(tag + ":")) { return rex.split(":")[1]; } else { return null; } } catch (NameNotFoundException e) { e.printStackTrace(); } return null; } public static String getMeteDataNoTag(Context context, String tag) { ApplicationInfo info; try { info = context.getPackageManager().getApplicationInfo( context.getPackageName(), PackageManager.GET_META_DATA); String rex = info.metaData.getString(tag); if (rex == null) { return null; } return rex; } catch (NameNotFoundException e) { e.printStackTrace(); } return null; } public static String getSKCardPath() { return Environment.getExternalStorageDirectory().getAbsolutePath(); } public static String mapToJsonArrayString(Map<String, Object> map) { if (map.isEmpty()) return null; JSONArray jsonArray = new JSONArray(); for (String key : map.keySet()) { JSONObject jsonObject = new JSONObject(); try { jsonObject.put("key", key); jsonObject.put("value", map.get(key) + ""); jsonArray.put(jsonObject); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return jsonArray.toString(); } public static String mapToJson(Map<String, String> map) { JSONObject jsonObject = new JSONObject(); for (String key : map.keySet()) { try { jsonObject.put(key, map.get(key)); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return jsonObject.toString(); } public static boolean isEmpty(String str) { if (str == null) { return true; } return str.length() == 0; } }
2,344
0.689846
0.688993
96
23.416666
19.71287
69
false
false
0
0
0
0
0
0
2.447917
false
false
5
6f2e2b77eaae7abe93da39eb4195a15ba7fa5036
16,149,077,068,235
ca79d0435ab82540b0d34ca30f267f747e2ffbdb
/src/main/java/scorpio/scorpioblog/mBlog/web/FileController.java
cd63045b6dc037c1f3adddada605f3b5c9de9eed
[]
no_license
fishlikewater/scorpio-blog
https://github.com/fishlikewater/scorpio-blog
82087201a9a0d0c1fc192552bccb4840603af20e
7fdd7becb69b7f533f680ebefac6edbce85d36d2
refs/heads/master
2021-08-28T14:59:10.385000
2017-12-12T14:17:20
2017-12-12T14:17:20
110,125,929
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package scorpio.scorpioblog.mBlog.web; import com.alibaba.fastjson.JSONObject; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.databind.JsonMappingException; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import scorpio.utils.UUIDUtils; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.crypto.Data; import java.io.*; import java.util.ArrayList; import java.util.Date; import java.util.List; @RestController @Api(value = "文件操作类", description = "zhanx") public class FileController { /** * 文件上传 * @param file * @param request * @param response * @return * @throws JsonGenerationException * @throws JsonMappingException * @throws IOException */ @ApiOperation(value = "文件上传接口", notes = "文件上传入口") @PostMapping("/admin/upload") public String sync( @RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws JsonGenerationException, JsonMappingException, IOException { if (request.getParameter("chunk") == null) { //this.getClass().getClassLoader().getResource("/upload").getPath(); String realPath = this.getClass().getResource("/static/images/randimage").getPath(); String fileName = file.getOriginalFilename(); fileName = UUIDUtils.get()+fileName.substring(fileName.lastIndexOf("."), fileName.length()); File targetFile = new File(realPath, fileName); if (!targetFile.exists()) { targetFile.createNewFile(); } file.transferTo(targetFile); // 小文件,直接拷贝 return ""; } else { int chunk = Integer.parseInt(request.getParameter("chunk")); // 当前分片 int chunks = Integer.parseInt(request.getParameter("chunks")); // 分片总计 String realPath = this.getClass().getResource("/static/images/randimage").getPath(); String Ogfilename = file.getOriginalFilename(); File tempFile = new File(realPath, Ogfilename); OutputStream outputStream = new FileOutputStream(tempFile, true); InputStream inputStream = file.getInputStream(); byte buffer[] = new byte[1024]; int len = 0; while ((len = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, len); } inputStream.close(); outputStream.close(); return ""; } } /** * 图片预览 * @param page * @param limit * @return */ @GetMapping("/admin/files") public JSONObject getFiles(@RequestParam("page") Integer page, @RequestParam(value = "limit", defaultValue = "10") Integer limit){ String path = this.getClass().getResource("/static/images/randimage").getPath(); File file = new File(path); String[] list = file.list(); Integer count = list.length; int totalPage = count%limit==0?count/limit:count/limit+1; int begin = (page-1)*limit; int end = (page-1)*limit+limit; if(end>count){ end = count; } List returnList = new ArrayList(); for (int i = end-1; i >= begin; i--) { returnList.add("/images/randimage/" + list[i]); } JSONObject obj = new JSONObject(); obj.put("total", totalPage); obj.put("list", returnList); return obj; } @PostMapping("admin/file/del") public void delFile(String fileName){ String path = this.getClass().getResource("/static/").getPath(); File file = new File(path + fileName); if (file.exists()){ file.delete(); }else{ throw new RuntimeException("文件不存在"); } } }
UTF-8
Java
4,363
java
FileController.java
Java
[]
null
[]
package scorpio.scorpioblog.mBlog.web; import com.alibaba.fastjson.JSONObject; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.databind.JsonMappingException; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import scorpio.utils.UUIDUtils; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.crypto.Data; import java.io.*; import java.util.ArrayList; import java.util.Date; import java.util.List; @RestController @Api(value = "文件操作类", description = "zhanx") public class FileController { /** * 文件上传 * @param file * @param request * @param response * @return * @throws JsonGenerationException * @throws JsonMappingException * @throws IOException */ @ApiOperation(value = "文件上传接口", notes = "文件上传入口") @PostMapping("/admin/upload") public String sync( @RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws JsonGenerationException, JsonMappingException, IOException { if (request.getParameter("chunk") == null) { //this.getClass().getClassLoader().getResource("/upload").getPath(); String realPath = this.getClass().getResource("/static/images/randimage").getPath(); String fileName = file.getOriginalFilename(); fileName = UUIDUtils.get()+fileName.substring(fileName.lastIndexOf("."), fileName.length()); File targetFile = new File(realPath, fileName); if (!targetFile.exists()) { targetFile.createNewFile(); } file.transferTo(targetFile); // 小文件,直接拷贝 return ""; } else { int chunk = Integer.parseInt(request.getParameter("chunk")); // 当前分片 int chunks = Integer.parseInt(request.getParameter("chunks")); // 分片总计 String realPath = this.getClass().getResource("/static/images/randimage").getPath(); String Ogfilename = file.getOriginalFilename(); File tempFile = new File(realPath, Ogfilename); OutputStream outputStream = new FileOutputStream(tempFile, true); InputStream inputStream = file.getInputStream(); byte buffer[] = new byte[1024]; int len = 0; while ((len = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, len); } inputStream.close(); outputStream.close(); return ""; } } /** * 图片预览 * @param page * @param limit * @return */ @GetMapping("/admin/files") public JSONObject getFiles(@RequestParam("page") Integer page, @RequestParam(value = "limit", defaultValue = "10") Integer limit){ String path = this.getClass().getResource("/static/images/randimage").getPath(); File file = new File(path); String[] list = file.list(); Integer count = list.length; int totalPage = count%limit==0?count/limit:count/limit+1; int begin = (page-1)*limit; int end = (page-1)*limit+limit; if(end>count){ end = count; } List returnList = new ArrayList(); for (int i = end-1; i >= begin; i--) { returnList.add("/images/randimage/" + list[i]); } JSONObject obj = new JSONObject(); obj.put("total", totalPage); obj.put("list", returnList); return obj; } @PostMapping("admin/file/del") public void delFile(String fileName){ String path = this.getClass().getResource("/static/").getPath(); File file = new File(path + fileName); if (file.exists()){ file.delete(); }else{ throw new RuntimeException("文件不存在"); } } }
4,363
0.622571
0.619293
128
32.367188
26.379108
104
false
false
0
0
0
0
0
0
0.601563
false
false
5
4678329e8b349da55dbe70f53bd3b62891daf21c
7,687,991,489,272
abd2ca521d4f18df18f3013d05913972ccf5a193
/rpc-client/src/main/java/com/tang/rpc_client/App.java
48cb50535e0d0b3a8bba614d9afaedf8bf074896
[]
no_license
tangbiao0321/rpc-demo
https://github.com/tangbiao0321/rpc-demo
6464ec90baa4b0dba4a02356de51d93fe6008b65
25ef7de4c5079441ed7add4df0d4f1c0f5c04df0
refs/heads/master
2021-09-06T20:17:38.521000
2018-02-11T01:29:52
2018-02-11T01:29:52
119,798,513
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tang.rpc_client; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import com.tang.rpc_client.config.ClientConfig; import com.tang.rpc_client.proxy.RpcProxy; import com.tang.rpc_server.service.HelloService; import junit.framework.Assert; /** * Hello world! * */ @SpringBootApplication public class App { @Autowired private RpcProxy rpcProxy; public static void main( String[] args ) { // SpringApplication.run(App.class, args); AnnotationConfigApplicationContext acac = new AnnotationConfigApplicationContext(ClientConfig.class); RpcProxy rpcProxy = acac.getBean(RpcProxy.class); HelloService helloService = rpcProxy.create(HelloService.class); String result = helloService.hello("World"); Assert.assertEquals("Hello! World", result); acac.close(); } }
UTF-8
Java
1,048
java
App.java
Java
[]
null
[]
package com.tang.rpc_client; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import com.tang.rpc_client.config.ClientConfig; import com.tang.rpc_client.proxy.RpcProxy; import com.tang.rpc_server.service.HelloService; import junit.framework.Assert; /** * Hello world! * */ @SpringBootApplication public class App { @Autowired private RpcProxy rpcProxy; public static void main( String[] args ) { // SpringApplication.run(App.class, args); AnnotationConfigApplicationContext acac = new AnnotationConfigApplicationContext(ClientConfig.class); RpcProxy rpcProxy = acac.getBean(RpcProxy.class); HelloService helloService = rpcProxy.create(HelloService.class); String result = helloService.hello("World"); Assert.assertEquals("Hello! World", result); acac.close(); } }
1,048
0.76813
0.76813
35
28.942858
27.407969
108
false
false
0
0
0
0
0
0
0.742857
false
false
5
d4807fd0cef1e3670e5e0f653b3907b83e950ac0
24,120,536,361,593
276745f5e2581ddc9632aefecb2551a64da8054f
/core/src/main/java/lingvo/movie/core/entity/PhysicalStorage.java
bdc30502f372be4bdd6511de241890afcbecf65c
[]
no_license
yaroslav-nikolaiko/LingvoMovie
https://github.com/yaroslav-nikolaiko/LingvoMovie
57cc9b32752b5bb99a4c0f660a3a96df99027d07
1b66e600736b7ef36b088562f2c2167a8a65d0dd
refs/heads/master
2021-01-15T11:18:44.706000
2015-12-03T18:11:24
2015-12-03T18:11:24
31,180,069
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package lingvo.movie.core.entity; import lombok.Data; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; /** * Created by yaroslav on 01.03.15. */ @Entity @Table(name = "PHYSICAL_STORAGE") @Data public class PhysicalStorage { @Id @GeneratedValue Long id; }
UTF-8
Java
354
java
PhysicalStorage.java
Java
[ { "context": "import javax.persistence.Table;\n\n/**\n * Created by yaroslav on 01.03.15.\n */\n@Entity\n@Table(name = \"PH", "end": 211, "score": 0.5127601623535156, "start": 210, "tag": "USERNAME", "value": "y" }, { "context": "port javax.persistence.Table;\n\n/**\n * Created by yaroslav on 01.03.15.\n */\n@Entity\n@Table(name = \"PHYS", "end": 213, "score": 0.5024734735488892, "start": 211, "tag": "NAME", "value": "ar" }, { "context": "rt javax.persistence.Table;\n\n/**\n * Created by yaroslav on 01.03.15.\n */\n@Entity\n@Table(name = \"PHYSIC", "end": 215, "score": 0.5472332239151001, "start": 213, "tag": "USERNAME", "value": "os" }, { "context": " javax.persistence.Table;\n\n/**\n * Created by yaroslav on 01.03.15.\n */\n@Entity\n@Table(name = \"PHYSICAL_", "end": 218, "score": 0.5431849360466003, "start": 215, "tag": "NAME", "value": "lav" } ]
null
[]
package lingvo.movie.core.entity; import lombok.Data; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; /** * Created by yaroslav on 01.03.15. */ @Entity @Table(name = "PHYSICAL_STORAGE") @Data public class PhysicalStorage { @Id @GeneratedValue Long id; }
354
0.751412
0.734463
19
17.631578
14.31308
40
false
false
0
0
0
0
0
0
0.368421
false
false
5
8a0b1f28a252f8cf1130bc5ca85cbea05627fe6b
24,120,536,360,224
4b5d2d4427681192840bde9adc08c0bbad6910a6
/app/src/main/java/com/hashtags/usman/youtubehashtag/Database_Objects/Realm_Object_History.java
d8daa75d1f2c9a2f9392217e55dd63a966128b4c
[]
no_license
usman14/HashTagVideo
https://github.com/usman14/HashTagVideo
7cc5436ffac8bfa04f12b5d9b34deb6e759555ac
3b56d22d7af6213030164b61278b835221cb86fa
refs/heads/master
2021-01-22T04:01:20.240000
2018-09-01T00:19:22
2018-09-01T00:19:22
92,421,296
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hashtags.usman.youtubehashtag.Database_Objects; import io.realm.RealmObject; /** * Created by usman on three/17/2017. */ public class Realm_Object_History extends RealmObject { String title; String thumbnailurl; String Videoid; public int getId() { return id; } public void setId(int id) { this.id = id; } int id; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getThumbnailurl() { return thumbnailurl; } public void setThumbnailurl(String thumbnailurl) { this.thumbnailurl = thumbnailurl; } public String getVideoid() { return Videoid; } public void setVideoid(String videoid) { Videoid = videoid; } }
UTF-8
Java
843
java
Realm_Object_History.java
Java
[ { "context": ";\n\nimport io.realm.RealmObject;\n\n/**\n * Created by usman on three/17/2017.\n */\n\npublic class Realm_Object_", "end": 114, "score": 0.9995162487030029, "start": 109, "tag": "USERNAME", "value": "usman" } ]
null
[]
package com.hashtags.usman.youtubehashtag.Database_Objects; import io.realm.RealmObject; /** * Created by usman on three/17/2017. */ public class Realm_Object_History extends RealmObject { String title; String thumbnailurl; String Videoid; public int getId() { return id; } public void setId(int id) { this.id = id; } int id; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getThumbnailurl() { return thumbnailurl; } public void setThumbnailurl(String thumbnailurl) { this.thumbnailurl = thumbnailurl; } public String getVideoid() { return Videoid; } public void setVideoid(String videoid) { Videoid = videoid; } }
843
0.615658
0.608541
49
16.204082
17.05092
59
false
false
0
0
0
0
0
0
0.285714
false
false
5
a486404e641d114728d4b384967393160a0c9433
2,894,807,993,525
05116064ddc0c2f6f540f66626b51c4248c30b07
/src/main/java/io/github/jhipster/sample/web/rest/errors/EmailNotFoundException.java
97d4890bceda13b0756e1002f19e9c507f699316
[]
no_license
jhipster/jhipster-sample-app-quarkus
https://github.com/jhipster/jhipster-sample-app-quarkus
e25d1c438c762ac109ba2c0f3fed8da69e2bf88b
ac0fc3050f953330ace4e1ae43194b8aa87b5ef5
refs/heads/main
2023-08-10T08:20:46.360000
2023-04-01T12:49:33
2023-04-01T12:49:33
185,751,542
28
15
null
false
2023-07-22T05:13:37
2019-05-09T07:46:57
2023-06-02T17:25:00
2023-07-22T05:13:33
5,014
27
17
7
TypeScript
false
false
package io.github.jhipster.sample.web.rest.errors; import static javax.ws.rs.core.Response.Status.BAD_REQUEST; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response; public class EmailNotFoundException extends BadRequestAlertException { public EmailNotFoundException() { super("Email address not registered", "userManagement", "emailnotfound"); } }
UTF-8
Java
392
java
EmailNotFoundException.java
Java
[ { "context": "package io.github.jhipster.sample.web.rest.errors;\n\nimport static javax.ws.r", "end": 26, "score": 0.9625184535980225, "start": 18, "tag": "USERNAME", "value": "jhipster" } ]
null
[]
package io.github.jhipster.sample.web.rest.errors; import static javax.ws.rs.core.Response.Status.BAD_REQUEST; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response; public class EmailNotFoundException extends BadRequestAlertException { public EmailNotFoundException() { super("Email address not registered", "userManagement", "emailnotfound"); } }
392
0.778061
0.778061
13
29.153847
28.72374
81
false
false
0
0
0
0
0
0
0.538462
false
false
5
6a75f5b95e7aeef73a8718d634c91058847c1c35
2,061,584,337,122
8ae6f46f0e2d5b7c056edc1e078eb1d183aff06d
/Lab 7/Connection.java
aef790cff79a58fad1059a6eb133349c77745344
[]
no_license
joego2124/1140
https://github.com/joego2124/1140
7cb210ca0ece5515c51bf7ed03c720c2a7491511
612f508f05b76fd20d9234b10fee46a0e366dbbf
refs/heads/main
2023-07-12T18:59:15.208000
2021-08-17T04:12:44
2021-08-17T04:12:44
371,821,813
1
1
null
false
2021-08-05T21:17:22
2021-05-28T21:26:44
2021-08-05T20:33:51
2021-08-05T21:17:21
25,067
1
1
0
JavaScript
false
false
/** Connects a phone to the mail system. The purpose of this class is to keep track of the state of a connection, since the phone itself is just a source of individual key presses. */ public class Connection { /** Construct a Connection object. @param s a MailSystem object @param p a Telephone object */ public Connection(MailSystem s, Telephone p) { system = s; phone = p; resetConnection(); } /** Respond to the user's pressing a key on the phone touchpad @param key the phone key pressed by the user */ public void dial(String key) { if (state == CONNECTED) connect(key); else if (state == RECORDING) login(key); else if (state == CHANGE_PASSCODE) changePasscode(key); else if (state == CHANGE_GREETING) changeGreeting(key); else if (state == MAILBOX_MENU) mailboxMenu(key); else if (state == MESSAGE_MENU) messageMenu(key); } /** Record voice. @param voice voice spoken by the user */ public void record(String voice) { if (state == RECORDING || state == CHANGE_GREETING) currentRecording += voice; } /** The user hangs up the phone. */ public void hangup() { if (state == RECORDING) currentMailbox.addMessage(new Message(currentRecording)); resetConnection(); } /** Reset the connection to the initial state and prompt for mailbox number */ private void resetConnection() { currentRecording = ""; accumulatedKeys = ""; state = CONNECTED; phone.speak(INITIAL_PROMPT); } /** Try to connect the user with the specified mailbox. @param key the phone key pressed by the user */ private void connect(String key) { if (key.equals("#")) { currentMailbox = system.findMailbox(accumulatedKeys); if (currentMailbox != null) { state = RECORDING; phone.speak(currentMailbox.getGreeting()); } else phone.speak("Incorrect mailbox number. Try again!"); accumulatedKeys = ""; } else accumulatedKeys += key; } /** Try to log in the user. @param key the phone key pressed by the user */ private void login(String key) { if (key.equals("#")) { if (currentMailbox.checkPasscode(accumulatedKeys)) { state = MAILBOX_MENU; phone.speak(MAILBOX_MENU_TEXT); } else phone.speak("Incorrect passcode. Try again!"); accumulatedKeys = ""; } else accumulatedKeys += key; } /** Change passcode. @param key the phone key pressed by the user */ private void changePasscode(String key) { if (key.equals("#")) { currentMailbox.setPasscode(accumulatedKeys); state = MAILBOX_MENU; phone.speak(MAILBOX_MENU_TEXT); accumulatedKeys = ""; } else accumulatedKeys += key; } /** Change greeting. @param key the phone key pressed by the user */ private void changeGreeting(String key) { if (key.equals("#")) { currentMailbox.setGreeting(currentRecording); currentRecording = ""; state = MAILBOX_MENU; phone.speak(MAILBOX_MENU_TEXT); } } /** Respond to the user's selection from mailbox menu. @param key the phone key pressed by the user */ private void mailboxMenu(String key) { if (key.equals("1")) { state = MESSAGE_MENU; phone.speak(MESSAGE_MENU_TEXT); } else if (key.equals("2")) { state = CHANGE_PASSCODE; phone.speak("Enter new passcode followed by the # key"); } else if (key.equals("3")) { state = CHANGE_GREETING; phone.speak("Record your greeting, then press the # key"); } } /** Respond to the user's selection from message menu. @param key the phone key pressed by the user */ private void messageMenu(String key) { if (key.equals("1")) { String output = ""; Message m = currentMailbox.getCurrentMessage(); if (m == null) output += "No messages." + "\n"; else output += m.getText() + "\n"; output += MESSAGE_MENU_TEXT; phone.speak(output); } else if (key.equals("2")) { currentMailbox.saveCurrentMessage(); phone.speak(MESSAGE_MENU_TEXT); } else if (key.equals("3")) { currentMailbox.removeCurrentMessage(); phone.speak(MESSAGE_MENU_TEXT); } else if (key.equals("4")) { state = MAILBOX_MENU; phone.speak(MAILBOX_MENU_TEXT); } } private MailSystem system; private Mailbox currentMailbox; private String currentRecording; private String accumulatedKeys; private Telephone phone; private int state; private static final int DISCONNECTED = 0; private static final int CONNECTED = 1; private static final int RECORDING = 2; private static final int MAILBOX_MENU = 3; private static final int MESSAGE_MENU = 4; private static final int CHANGE_PASSCODE = 5; private static final int CHANGE_GREETING = 6; private static final String INITIAL_PROMPT = "Enter mailbox number followed by #"; private static final String MAILBOX_MENU_TEXT = "Enter 1 to listen to your messages\n" + "Enter 2 to change your passcode\n" + "Enter 3 to change your greeting"; private static final String MESSAGE_MENU_TEXT = "Enter 1 to listen to the current message\n" + "Enter 2 to save the current message\n" + "Enter 3 to delete the current message\n" + "Enter 4 to return to the main menu"; }
UTF-8
Java
5,997
java
Connection.java
Java
[]
null
[]
/** Connects a phone to the mail system. The purpose of this class is to keep track of the state of a connection, since the phone itself is just a source of individual key presses. */ public class Connection { /** Construct a Connection object. @param s a MailSystem object @param p a Telephone object */ public Connection(MailSystem s, Telephone p) { system = s; phone = p; resetConnection(); } /** Respond to the user's pressing a key on the phone touchpad @param key the phone key pressed by the user */ public void dial(String key) { if (state == CONNECTED) connect(key); else if (state == RECORDING) login(key); else if (state == CHANGE_PASSCODE) changePasscode(key); else if (state == CHANGE_GREETING) changeGreeting(key); else if (state == MAILBOX_MENU) mailboxMenu(key); else if (state == MESSAGE_MENU) messageMenu(key); } /** Record voice. @param voice voice spoken by the user */ public void record(String voice) { if (state == RECORDING || state == CHANGE_GREETING) currentRecording += voice; } /** The user hangs up the phone. */ public void hangup() { if (state == RECORDING) currentMailbox.addMessage(new Message(currentRecording)); resetConnection(); } /** Reset the connection to the initial state and prompt for mailbox number */ private void resetConnection() { currentRecording = ""; accumulatedKeys = ""; state = CONNECTED; phone.speak(INITIAL_PROMPT); } /** Try to connect the user with the specified mailbox. @param key the phone key pressed by the user */ private void connect(String key) { if (key.equals("#")) { currentMailbox = system.findMailbox(accumulatedKeys); if (currentMailbox != null) { state = RECORDING; phone.speak(currentMailbox.getGreeting()); } else phone.speak("Incorrect mailbox number. Try again!"); accumulatedKeys = ""; } else accumulatedKeys += key; } /** Try to log in the user. @param key the phone key pressed by the user */ private void login(String key) { if (key.equals("#")) { if (currentMailbox.checkPasscode(accumulatedKeys)) { state = MAILBOX_MENU; phone.speak(MAILBOX_MENU_TEXT); } else phone.speak("Incorrect passcode. Try again!"); accumulatedKeys = ""; } else accumulatedKeys += key; } /** Change passcode. @param key the phone key pressed by the user */ private void changePasscode(String key) { if (key.equals("#")) { currentMailbox.setPasscode(accumulatedKeys); state = MAILBOX_MENU; phone.speak(MAILBOX_MENU_TEXT); accumulatedKeys = ""; } else accumulatedKeys += key; } /** Change greeting. @param key the phone key pressed by the user */ private void changeGreeting(String key) { if (key.equals("#")) { currentMailbox.setGreeting(currentRecording); currentRecording = ""; state = MAILBOX_MENU; phone.speak(MAILBOX_MENU_TEXT); } } /** Respond to the user's selection from mailbox menu. @param key the phone key pressed by the user */ private void mailboxMenu(String key) { if (key.equals("1")) { state = MESSAGE_MENU; phone.speak(MESSAGE_MENU_TEXT); } else if (key.equals("2")) { state = CHANGE_PASSCODE; phone.speak("Enter new passcode followed by the # key"); } else if (key.equals("3")) { state = CHANGE_GREETING; phone.speak("Record your greeting, then press the # key"); } } /** Respond to the user's selection from message menu. @param key the phone key pressed by the user */ private void messageMenu(String key) { if (key.equals("1")) { String output = ""; Message m = currentMailbox.getCurrentMessage(); if (m == null) output += "No messages." + "\n"; else output += m.getText() + "\n"; output += MESSAGE_MENU_TEXT; phone.speak(output); } else if (key.equals("2")) { currentMailbox.saveCurrentMessage(); phone.speak(MESSAGE_MENU_TEXT); } else if (key.equals("3")) { currentMailbox.removeCurrentMessage(); phone.speak(MESSAGE_MENU_TEXT); } else if (key.equals("4")) { state = MAILBOX_MENU; phone.speak(MAILBOX_MENU_TEXT); } } private MailSystem system; private Mailbox currentMailbox; private String currentRecording; private String accumulatedKeys; private Telephone phone; private int state; private static final int DISCONNECTED = 0; private static final int CONNECTED = 1; private static final int RECORDING = 2; private static final int MAILBOX_MENU = 3; private static final int MESSAGE_MENU = 4; private static final int CHANGE_PASSCODE = 5; private static final int CHANGE_GREETING = 6; private static final String INITIAL_PROMPT = "Enter mailbox number followed by #"; private static final String MAILBOX_MENU_TEXT = "Enter 1 to listen to your messages\n" + "Enter 2 to change your passcode\n" + "Enter 3 to change your greeting"; private static final String MESSAGE_MENU_TEXT = "Enter 1 to listen to the current message\n" + "Enter 2 to save the current message\n" + "Enter 3 to delete the current message\n" + "Enter 4 to return to the main menu"; }
5,997
0.578456
0.574954
228
25.302631
19.222853
67
false
false
0
0
0
0
0
0
0.328947
false
false
5
e2346139b568316da3575fcc3c5447b6bcb6bc6b
1,254,130,487,696
a4cdeb5ac0f1dd545e6ab7da5e1c4d0459e445c5
/springboot/springboot-04-data/src/main/java/com/joker/controller/JdbcController.java
9ccfd5001b74c9b8d31573bf3babd6b895e390f2
[ "Apache-2.0" ]
permissive
jokerzzccc/joker_FromKuangS
https://github.com/jokerzzccc/joker_FromKuangS
c5bdba794e0065e99e3cc49b09c5bda7fadce32d
6456ce75883eda2b194fd8c39ed1c2ddb026fbf1
refs/heads/master
2023-06-15T02:07:18.768000
2021-06-24T05:21:59
2021-06-24T05:21:59
379,807,589
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.joker.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import java.util.List; import java.util.Map; import java.util.Objects; @RestController public class JdbcController { final JdbcTemplate jdbcTemplate; public JdbcController(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } @GetMapping("/userList") public List<Map<String, Object>> userList(){ String sql ="select * from mybatis.user"; List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql); return maps; } @GetMapping("/addUser") public String addUser(){ String sql="insert into mybatis.user values(10,'小明','111111')"; int update = jdbcTemplate.update(sql); return "insert-ok"; } @GetMapping("/updateUser/{id}") public String updateUser(@PathVariable("id") int id){ String sql="update mybatis.user set name=? ,pwd=? where id="+id; //封装 Object[] objects = new Object[2]; objects[0] = "小明2"; objects[1] = "22222"; jdbcTemplate.update(sql,objects); return "update ok"; } @GetMapping("/deleteUser/{id}") public String deleteUser(@PathVariable("id") int id){ String sql = "delete from mybatis.user where id=?"; jdbcTemplate.update(sql,id); return "delete-ok"; } }
UTF-8
Java
1,613
java
JdbcController.java
Java
[ { "context": " String sql=\"insert into mybatis.user values(10,'小明','111111')\";\n int update = jdbcTemplate.update", "end": 933, "score": 0.9973658323287964, "start": 931, "tag": "NAME", "value": "小明" } ]
null
[]
package com.joker.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import java.util.List; import java.util.Map; import java.util.Objects; @RestController public class JdbcController { final JdbcTemplate jdbcTemplate; public JdbcController(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } @GetMapping("/userList") public List<Map<String, Object>> userList(){ String sql ="select * from mybatis.user"; List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql); return maps; } @GetMapping("/addUser") public String addUser(){ String sql="insert into mybatis.user values(10,'小明','111111')"; int update = jdbcTemplate.update(sql); return "insert-ok"; } @GetMapping("/updateUser/{id}") public String updateUser(@PathVariable("id") int id){ String sql="update mybatis.user set name=? ,pwd=? where id="+id; //封装 Object[] objects = new Object[2]; objects[0] = "小明2"; objects[1] = "22222"; jdbcTemplate.update(sql,objects); return "update ok"; } @GetMapping("/deleteUser/{id}") public String deleteUser(@PathVariable("id") int id){ String sql = "delete from mybatis.user where id=?"; jdbcTemplate.update(sql,id); return "delete-ok"; } }
1,613
0.675828
0.665209
51
29.843138
22.279308
72
false
false
0
0
0
0
0
0
0.647059
false
false
5
97a7e2d633e3a69ee6c6d640399879e889d93f42
27,462,020,926,599
1e8fd404957cce2f112a9c4a5ca28dc8e5cc9f04
/hrms/src/main/java/kodlamaio/hrms/business/abstracts/ConfirmationCodeService.java
a4d87ae59985ccd5b29962730c00dc970f9af92d
[]
no_license
ahmetburakfirat/Human-Resources-Management-System
https://github.com/ahmetburakfirat/Human-Resources-Management-System
98083363e83d1a155cd2cdd3b8a1b48db35f393f
3393aa6def40fb0b1c4457db2b290f5001e5bdff
refs/heads/master
2023-05-18T21:32:13.313000
2021-06-11T00:34:00
2021-06-11T00:34:00
375,838,299
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package kodlamaio.hrms.business.abstracts; import java.util.List; import kodlamaio.hrms.core.utilities.DataResult; import kodlamaio.hrms.core.utilities.Result; import kodlamaio.hrms.entities.abstracts.User; import kodlamaio.hrms.entities.concretes.ConfirmationCode; public interface ConfirmationCodeService { DataResult<List<ConfirmationCode>> getAll(); Result createAndSendCode(int userId); }
UTF-8
Java
412
java
ConfirmationCodeService.java
Java
[]
null
[]
package kodlamaio.hrms.business.abstracts; import java.util.List; import kodlamaio.hrms.core.utilities.DataResult; import kodlamaio.hrms.core.utilities.Result; import kodlamaio.hrms.entities.abstracts.User; import kodlamaio.hrms.entities.concretes.ConfirmationCode; public interface ConfirmationCodeService { DataResult<List<ConfirmationCode>> getAll(); Result createAndSendCode(int userId); }
412
0.808252
0.808252
13
29.692308
21.014225
58
false
false
0
0
0
0
0
0
0.769231
false
false
5
172f3b7ba59ea065d0d56f4fc5fc0cd0486159d2
8,701,603,770,423
e4d15cb01c8cb03737776ebba14f41837e5f0101
/src/main/java/com/lx/service/ShareService.java
933b9ea332217c73951e0f4b156788c7e077141b
[]
no_license
LinRuiiXin/ClubSystem
https://github.com/LinRuiiXin/ClubSystem
6d914e310a9e04d6d226b7c7e06af077f57775cb
5b4174716883bcc00c613b55304b18b5134c258e
refs/heads/master
2022-12-20T23:00:01.263000
2019-12-09T12:12:05
2019-12-09T12:12:05
226,629,614
4
0
null
false
2022-12-16T14:51:12
2019-12-08T07:16:42
2022-10-07T02:29:29
2022-12-16T14:51:09
415
4
0
8
HTML
false
false
package com.lx.service; import com.lx.POJO.Share; import java.util.List; public interface ShareService { void insertShare(String userName,String fileName,int clubId); List<Share> queryByClubId(int clubId); void deleteLostFile(String fileName); }
UTF-8
Java
261
java
ShareService.java
Java
[ { "context": "terface ShareService {\n void insertShare(String userName,String fileName,int clubId);\n List<Share> quer", "end": 144, "score": 0.9855615496635437, "start": 136, "tag": "USERNAME", "value": "userName" } ]
null
[]
package com.lx.service; import com.lx.POJO.Share; import java.util.List; public interface ShareService { void insertShare(String userName,String fileName,int clubId); List<Share> queryByClubId(int clubId); void deleteLostFile(String fileName); }
261
0.762452
0.762452
11
22.727272
20.423208
65
false
false
0
0
0
0
0
0
0.727273
false
false
5
94e8d2defc44f5816a4d703e03aacc2ce7778ce8
18,966,575,615,189
f905f1252ca55db99bb30890ffd0a5e1bef90538
/src/test/java/com/stackroute/testcases/UserLoginValidationTest.java
110a572c7d7105dfcaff16c21b1d992aa060e5e6
[]
no_license
DeepanRamalingam/selenium-complete-testing-framework-demo
https://github.com/DeepanRamalingam/selenium-complete-testing-framework-demo
6d44656af2c60578ab878bd19af940a9312c6630
18fc10ddb380e61ec91366985637a6786ef19fbb
refs/heads/master
2023-05-11T10:54:50.113000
2019-10-29T18:12:08
2019-10-29T18:12:08
218,352,677
0
0
null
false
2023-05-09T18:35:11
2019-10-29T18:10:54
2019-10-29T18:12:42
2023-05-09T18:35:07
221
0
0
2
HTML
false
false
package com.stackroute.testcases; import java.io.IOException; import java.util.Iterator; import org.openqa.selenium.By; import org.openqa.selenium.support.PageFactory; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Ignore; import org.testng.annotations.Test; import com.stackroute.commonclasses.AutomationSetup; import com.stackroute.pageobjects.DashboardPage; import com.stackroute.pageobjects.LoginPage; public class UserLoginValidationTest extends AutomationSetup { @DataProvider(name = "username-provider") public Object[][] provideUserCredentials() { Object[][] credentials = { {"deepan","pass123",false}, {"sachin","pass234",false}, {"dinesh","pas22237",false}, {"Admin","admin123",true} }; return credentials; } @DataProvider(name = "csv-data-provider") public Iterator<String[]> provideUserCredentialsCSV() throws IOException{ return csvReader("./src/test/resources/userCredentials.csv").iterator(); } @DataProvider(name = "excel-data-provider") public String[][] provideUserCredentialsEXCEL() throws IOException{ String filePath = "./src/test/resources/login_data.xlsx"; return excelReader(filePath,"Sheet1",3); } @Ignore @Test(dataProvider = "excel-data-provider") public void validateUser(String user, String pass, String isValidAsString) throws IOException, InterruptedException { Boolean isValid = Boolean.valueOf(isValidAsString); PageFactory.initElements(driver, LoginPage.class); driver.get("https://opensource-demo.orangehrmlive.com/index.php/auth/login"); LoginPage.username.sendKeys(user); LoginPage.password.sendKeys(pass); LoginPage.loginBtn.click(); sleep(3000); if(isValid) { screenShot(user+"-login-status"); PageFactory.initElements(driver, DashboardPage.class); Boolean welcomeElement = DashboardPage.welcome != null; Assert.assertTrue(welcomeElement); } else { screenShot(user+"-login-status"); Boolean errorElement = driver.findElement(By.id("spanMessage")) != null; Assert.assertTrue(errorElement); } } @Test(groups = {"smoke"}) public void sample1_from_user_validation() { Assert.assertTrue(true); } @Test public void sample2_from_user_validation() { Assert.assertTrue(true); } }
UTF-8
Java
2,328
java
UserLoginValidationTest.java
Java
[ { "context": "ials() {\n\t\tObject[][] credentials = \n\t\t\t\t\t\t\t\t{ \t{\"deepan\",\"pass123\",false},\n\t\t\t\t\t\t\t\t\t{\"sachin\",\"pass234\",f", "end": 663, "score": 0.9911391735076904, "start": 657, "tag": "USERNAME", "value": "deepan" }, { "context": "\t\tObject[][] credentials = \n\t\t\t\t\t\t\t\t{ \t{\"deepan\",\"pass123\",false},\n\t\t\t\t\t\t\t\t\t{\"sachin\",\"pass234\",false},\n\t\t\t", "end": 673, "score": 0.9986582398414612, "start": 666, "tag": "PASSWORD", "value": "pass123" }, { "context": "\t\t\t\t\t\t\t\t{ \t{\"deepan\",\"pass123\",false},\n\t\t\t\t\t\t\t\t\t{\"sachin\",\"pass234\",false},\n\t\t\t\t\t\t\t\t\t{\"dinesh\",\"pas22237\",", "end": 700, "score": 0.9778761863708496, "start": 694, "tag": "USERNAME", "value": "sachin" }, { "context": " \t{\"deepan\",\"pass123\",false},\n\t\t\t\t\t\t\t\t\t{\"sachin\",\"pass234\",false},\n\t\t\t\t\t\t\t\t\t{\"dinesh\",\"pas22237\",false},\n\t\t", "end": 710, "score": 0.9989214539527893, "start": 703, "tag": "PASSWORD", "value": "pass234" }, { "context": ",\n\t\t\t\t\t\t\t\t\t{\"sachin\",\"pass234\",false},\n\t\t\t\t\t\t\t\t\t{\"dinesh\",\"pas22237\",false},\n\t\t\t\t\t\t\t\t\t{\"Admin\",\"admin123\",", "end": 737, "score": 0.9373037815093994, "start": 731, "tag": "PASSWORD", "value": "dinesh" }, { "context": "\t\t{\"sachin\",\"pass234\",false},\n\t\t\t\t\t\t\t\t\t{\"dinesh\",\"pas22237\",false},\n\t\t\t\t\t\t\t\t\t{\"Admin\",\"admin123\",true}\n\t\t\t\t\t", "end": 748, "score": 0.998677670955658, "start": 740, "tag": "PASSWORD", "value": "pas22237" }, { "context": "\t\t{\"dinesh\",\"pas22237\",false},\n\t\t\t\t\t\t\t\t\t{\"Admin\",\"admin123\",true}\n\t\t\t\t\t\t\t\t};\n\t\treturn credentials;\n\t}\n\t\n\t@Da", "end": 785, "score": 0.9938610196113586, "start": 777, "tag": "USERNAME", "value": "admin123" }, { "context": "x.php/auth/login\");\n\t\tLoginPage.username.sendKeys(user);\n\t\tLoginPage.password.sendKeys(pass);\n\t\tLoginPag", "end": 1647, "score": 0.9932869672775269, "start": 1643, "tag": "USERNAME", "value": "user" }, { "context": "ame.sendKeys(user);\n\t\tLoginPage.password.sendKeys(pass);\n\t\tLoginPage.loginBtn.click();\n\t\tsleep(3000);\n\t\t", "end": 1684, "score": 0.994881272315979, "start": 1680, "tag": "PASSWORD", "value": "pass" } ]
null
[]
package com.stackroute.testcases; import java.io.IOException; import java.util.Iterator; import org.openqa.selenium.By; import org.openqa.selenium.support.PageFactory; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Ignore; import org.testng.annotations.Test; import com.stackroute.commonclasses.AutomationSetup; import com.stackroute.pageobjects.DashboardPage; import com.stackroute.pageobjects.LoginPage; public class UserLoginValidationTest extends AutomationSetup { @DataProvider(name = "username-provider") public Object[][] provideUserCredentials() { Object[][] credentials = { {"deepan","<PASSWORD>",false}, {"sachin","<PASSWORD>",false}, {"<PASSWORD>","<PASSWORD>",false}, {"Admin","admin123",true} }; return credentials; } @DataProvider(name = "csv-data-provider") public Iterator<String[]> provideUserCredentialsCSV() throws IOException{ return csvReader("./src/test/resources/userCredentials.csv").iterator(); } @DataProvider(name = "excel-data-provider") public String[][] provideUserCredentialsEXCEL() throws IOException{ String filePath = "./src/test/resources/login_data.xlsx"; return excelReader(filePath,"Sheet1",3); } @Ignore @Test(dataProvider = "excel-data-provider") public void validateUser(String user, String pass, String isValidAsString) throws IOException, InterruptedException { Boolean isValid = Boolean.valueOf(isValidAsString); PageFactory.initElements(driver, LoginPage.class); driver.get("https://opensource-demo.orangehrmlive.com/index.php/auth/login"); LoginPage.username.sendKeys(user); LoginPage.password.sendKeys(<PASSWORD>); LoginPage.loginBtn.click(); sleep(3000); if(isValid) { screenShot(user+"-login-status"); PageFactory.initElements(driver, DashboardPage.class); Boolean welcomeElement = DashboardPage.welcome != null; Assert.assertTrue(welcomeElement); } else { screenShot(user+"-login-status"); Boolean errorElement = driver.findElement(By.id("spanMessage")) != null; Assert.assertTrue(errorElement); } } @Test(groups = {"smoke"}) public void sample1_from_user_validation() { Assert.assertTrue(true); } @Test public void sample2_from_user_validation() { Assert.assertTrue(true); } }
2,346
0.731959
0.722509
80
28.1
24.857393
118
false
false
0
0
0
0
0
0
2.3625
false
false
5
8d2718cfbe699611b7414b283cc2b26aa03f11c0
14,018,773,284,840
6384d3199811af7c8a0ed74450772e437cde334c
/appsearch/appsearch/src/androidTest/java/androidx/appsearch/app/GenericDocumentInternalTest.java
b514854ba5e4ac54a9659272717045a2810fa3c4
[ "Apache-2.0" ]
permissive
androidx/androidx
https://github.com/androidx/androidx
1cf2c063d530d2c6cf63899af796c44005ba38f4
7c7be981f7b980738c571998db1128f7a9a1195a
refs/heads/androidx-main
2023-09-06T07:55:17.232000
2023-09-06T06:22:19
2023-09-06T06:22:19
256,589,781
5,035
940
Apache-2.0
false
2023-09-14T17:59:59
2020-04-17T19:17:41
2023-09-14T14:50:43
2023-09-14T17:59:55
761,760
4,735
836
22
Kotlin
false
false
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.appsearch.app; import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import android.os.Bundle; import android.os.Parcel; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; /** Tests for private APIs of {@link GenericDocument}. */ public class GenericDocumentInternalTest { @Test public void testRecreateFromParcel() { GenericDocument inDoc = new GenericDocument.Builder<>("namespace", "id1", "schema1") .setScore(42) .setPropertyString("propString", "Hello") .setPropertyBytes("propBytes", new byte[][]{{1, 2}}) .setPropertyDocument( "propDocument", new GenericDocument.Builder<>("namespace", "id2", "schema2") .setPropertyString("propString", "Goodbye") .setPropertyBytes("propBytes", new byte[][]{{3, 4}}) .build()) .build(); // Serialize the document Parcel inParcel = Parcel.obtain(); inParcel.writeBundle(inDoc.getBundle()); byte[] data = inParcel.marshall(); inParcel.recycle(); // Deserialize the document Parcel outParcel = Parcel.obtain(); outParcel.unmarshall(data, 0, data.length); outParcel.setDataPosition(0); Bundle outBundle = outParcel.readBundle(); outParcel.recycle(); // Compare results GenericDocument outDoc = new GenericDocument(outBundle); assertThat(inDoc).isEqualTo(outDoc); assertThat(outDoc.getPropertyString("propString")).isEqualTo("Hello"); assertThat(outDoc.getPropertyBytesArray("propBytes")).isEqualTo(new byte[][]{{1, 2}}); assertThat(outDoc.getPropertyDocument("propDocument").getPropertyString("propString")) .isEqualTo("Goodbye"); assertThat(outDoc.getPropertyDocument("propDocument").getPropertyBytesArray("propBytes")) .isEqualTo(new byte[][]{{3, 4}}); } @Test public void testRecreateFromParcelWithParentTypes() { GenericDocument inDoc = new GenericDocument.Builder<>("namespace", "id1", "schema1") .setParentTypes(new ArrayList<>(Arrays.asList("Class1", "Class2"))) .setScore(42) .setPropertyString("propString", "Hello") .setPropertyBytes("propBytes", new byte[][]{{1, 2}}) .setPropertyDocument( "propDocument", new GenericDocument.Builder<>("namespace", "id2", "schema2") .setPropertyString("propString", "Goodbye") .setPropertyBytes("propBytes", new byte[][]{{3, 4}}) .build()) .build(); // Serialize the document Parcel inParcel = Parcel.obtain(); inParcel.writeBundle(inDoc.getBundle()); byte[] data = inParcel.marshall(); inParcel.recycle(); // Deserialize the document Parcel outParcel = Parcel.obtain(); outParcel.unmarshall(data, 0, data.length); outParcel.setDataPosition(0); Bundle outBundle = outParcel.readBundle(); outParcel.recycle(); // Compare results GenericDocument outDoc = new GenericDocument(outBundle); assertThat(inDoc).isEqualTo(outDoc); assertThat(outDoc.getParentTypes()).isEqualTo(Arrays.asList("Class1", "Class2")); assertThat(outDoc.getPropertyString("propString")).isEqualTo("Hello"); assertThat(outDoc.getPropertyBytesArray("propBytes")).isEqualTo(new byte[][]{{1, 2}}); assertThat(outDoc.getPropertyDocument("propDocument").getPropertyString("propString")) .isEqualTo("Goodbye"); assertThat(outDoc.getPropertyDocument("propDocument").getPropertyBytesArray("propBytes")) .isEqualTo(new byte[][]{{3, 4}}); } @Test public void testPropertyParcel_onePropertySet_success() { String[] stringValues = {"a", "b"}; long[] longValues = {1L, 2L}; double[] doubleValues = {1.0, 2.0}; boolean[] booleanValues = {true, false}; byte[][] bytesValues = {new byte[1]}; Bundle[] bundleValues = {new Bundle()}; assertThat(new PropertyParcel.Builder("name").setStringValues( stringValues).build().getStringValues()).isEqualTo( Arrays.copyOf(stringValues, stringValues.length)); assertThat(new PropertyParcel.Builder("name").setLongValues( longValues).build().getLongValues()).isEqualTo( Arrays.copyOf(longValues, longValues.length)); assertThat(new PropertyParcel.Builder("name").setDoubleValues( doubleValues).build().getDoubleValues()).isEqualTo( Arrays.copyOf(doubleValues, doubleValues.length)); assertThat(new PropertyParcel.Builder("name").setBooleanValues( booleanValues).build().getBooleanValues()).isEqualTo( Arrays.copyOf(booleanValues, booleanValues.length)); assertThat(new PropertyParcel.Builder("name").setBytesValues( bytesValues).build().getBytesValues()).isEqualTo( Arrays.copyOf(bytesValues, bytesValues.length)); assertThat(new PropertyParcel.Builder("name").setDocumentValues( bundleValues).build().getDocumentValues()).isEqualTo( Arrays.copyOf(bundleValues, bundleValues.length)); } @Test public void testPropertyParcel_moreThanOnePropertySet_exceptionThrown() { String[] stringValues = {"a", "b"}; long[] longValues = {1L, 2L}; PropertyParcel.Builder propertyParcelBuilder = new PropertyParcel.Builder("name") .setStringValues(stringValues) .setLongValues(longValues); IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> propertyParcelBuilder.build()); assertThat(exception.getMessage()).contains("One and only one type array"); } }
UTF-8
Java
6,864
java
GenericDocumentInternalTest.java
Java
[ { "context": " .setPropertyString(\"propString\", \"Goodbye\")\n .setProperty", "end": 3365, "score": 0.6137394905090332, "start": 3361, "tag": "NAME", "value": "Good" } ]
null
[]
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.appsearch.app; import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import android.os.Bundle; import android.os.Parcel; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; /** Tests for private APIs of {@link GenericDocument}. */ public class GenericDocumentInternalTest { @Test public void testRecreateFromParcel() { GenericDocument inDoc = new GenericDocument.Builder<>("namespace", "id1", "schema1") .setScore(42) .setPropertyString("propString", "Hello") .setPropertyBytes("propBytes", new byte[][]{{1, 2}}) .setPropertyDocument( "propDocument", new GenericDocument.Builder<>("namespace", "id2", "schema2") .setPropertyString("propString", "Goodbye") .setPropertyBytes("propBytes", new byte[][]{{3, 4}}) .build()) .build(); // Serialize the document Parcel inParcel = Parcel.obtain(); inParcel.writeBundle(inDoc.getBundle()); byte[] data = inParcel.marshall(); inParcel.recycle(); // Deserialize the document Parcel outParcel = Parcel.obtain(); outParcel.unmarshall(data, 0, data.length); outParcel.setDataPosition(0); Bundle outBundle = outParcel.readBundle(); outParcel.recycle(); // Compare results GenericDocument outDoc = new GenericDocument(outBundle); assertThat(inDoc).isEqualTo(outDoc); assertThat(outDoc.getPropertyString("propString")).isEqualTo("Hello"); assertThat(outDoc.getPropertyBytesArray("propBytes")).isEqualTo(new byte[][]{{1, 2}}); assertThat(outDoc.getPropertyDocument("propDocument").getPropertyString("propString")) .isEqualTo("Goodbye"); assertThat(outDoc.getPropertyDocument("propDocument").getPropertyBytesArray("propBytes")) .isEqualTo(new byte[][]{{3, 4}}); } @Test public void testRecreateFromParcelWithParentTypes() { GenericDocument inDoc = new GenericDocument.Builder<>("namespace", "id1", "schema1") .setParentTypes(new ArrayList<>(Arrays.asList("Class1", "Class2"))) .setScore(42) .setPropertyString("propString", "Hello") .setPropertyBytes("propBytes", new byte[][]{{1, 2}}) .setPropertyDocument( "propDocument", new GenericDocument.Builder<>("namespace", "id2", "schema2") .setPropertyString("propString", "Goodbye") .setPropertyBytes("propBytes", new byte[][]{{3, 4}}) .build()) .build(); // Serialize the document Parcel inParcel = Parcel.obtain(); inParcel.writeBundle(inDoc.getBundle()); byte[] data = inParcel.marshall(); inParcel.recycle(); // Deserialize the document Parcel outParcel = Parcel.obtain(); outParcel.unmarshall(data, 0, data.length); outParcel.setDataPosition(0); Bundle outBundle = outParcel.readBundle(); outParcel.recycle(); // Compare results GenericDocument outDoc = new GenericDocument(outBundle); assertThat(inDoc).isEqualTo(outDoc); assertThat(outDoc.getParentTypes()).isEqualTo(Arrays.asList("Class1", "Class2")); assertThat(outDoc.getPropertyString("propString")).isEqualTo("Hello"); assertThat(outDoc.getPropertyBytesArray("propBytes")).isEqualTo(new byte[][]{{1, 2}}); assertThat(outDoc.getPropertyDocument("propDocument").getPropertyString("propString")) .isEqualTo("Goodbye"); assertThat(outDoc.getPropertyDocument("propDocument").getPropertyBytesArray("propBytes")) .isEqualTo(new byte[][]{{3, 4}}); } @Test public void testPropertyParcel_onePropertySet_success() { String[] stringValues = {"a", "b"}; long[] longValues = {1L, 2L}; double[] doubleValues = {1.0, 2.0}; boolean[] booleanValues = {true, false}; byte[][] bytesValues = {new byte[1]}; Bundle[] bundleValues = {new Bundle()}; assertThat(new PropertyParcel.Builder("name").setStringValues( stringValues).build().getStringValues()).isEqualTo( Arrays.copyOf(stringValues, stringValues.length)); assertThat(new PropertyParcel.Builder("name").setLongValues( longValues).build().getLongValues()).isEqualTo( Arrays.copyOf(longValues, longValues.length)); assertThat(new PropertyParcel.Builder("name").setDoubleValues( doubleValues).build().getDoubleValues()).isEqualTo( Arrays.copyOf(doubleValues, doubleValues.length)); assertThat(new PropertyParcel.Builder("name").setBooleanValues( booleanValues).build().getBooleanValues()).isEqualTo( Arrays.copyOf(booleanValues, booleanValues.length)); assertThat(new PropertyParcel.Builder("name").setBytesValues( bytesValues).build().getBytesValues()).isEqualTo( Arrays.copyOf(bytesValues, bytesValues.length)); assertThat(new PropertyParcel.Builder("name").setDocumentValues( bundleValues).build().getDocumentValues()).isEqualTo( Arrays.copyOf(bundleValues, bundleValues.length)); } @Test public void testPropertyParcel_moreThanOnePropertySet_exceptionThrown() { String[] stringValues = {"a", "b"}; long[] longValues = {1L, 2L}; PropertyParcel.Builder propertyParcelBuilder = new PropertyParcel.Builder("name") .setStringValues(stringValues) .setLongValues(longValues); IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> propertyParcelBuilder.build()); assertThat(exception.getMessage()).contains("One and only one type array"); } }
6,864
0.622232
0.61451
154
43.57143
28.019672
97
false
false
0
0
0
0
0
0
0.701299
false
false
5
f635026bfab5c8a825357b2d141483157d62cd6e
29,102,698,435,428
e61f175080419b19793711c6975f5a898aae3d95
/bitbox/src/main/java/unimelb/bitbox/util/PublicKeyNotFoundException.java
f106cc75a4289eec784b415ee191431640ae9c8f
[]
no_license
MarsXue/DS_BitBox
https://github.com/MarsXue/DS_BitBox
926e596d891e838d041af61033a5e92812b56c25
79c25ddf4024b33bbab1855d1b9435c8db9d50f0
refs/heads/master
2021-03-06T13:13:08.074000
2019-06-01T06:28:12
2019-06-01T06:28:12
246,202,141
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package unimelb.bitbox.util; /** * Exception Wrapper for using Public Key to encrypt AES key * * @author Weizhi Xu (752454) * @author Wenqing Xue (813044) * @author Zijie Shen (741404) * @author Zijun Chen (813190) */ public class PublicKeyNotFoundException extends Exception { public PublicKeyNotFoundException(String errorMessage, Throwable err) { super(errorMessage, err); } }
UTF-8
Java
404
java
PublicKeyNotFoundException.java
Java
[ { "context": " using Public Key to encrypt AES key\n *\n * @author Weizhi Xu (752454)\n * @author Wenqing Xue (813044)\n * @auth", "end": 118, "score": 0.9998170137405396, "start": 109, "tag": "NAME", "value": "Weizhi Xu" }, { "context": "ES key\n *\n * @author Weizhi Xu (752454)\n * @author Wenqing Xue (813044)\n * @author Zijie Shen (741404)\n * @autho", "end": 150, "score": 0.9998325705528259, "start": 139, "tag": "NAME", "value": "Wenqing Xue" }, { "context": "752454)\n * @author Wenqing Xue (813044)\n * @author Zijie Shen (741404)\n * @author Zijun Chen (813190)\n */\npubli", "end": 181, "score": 0.9998491406440735, "start": 171, "tag": "NAME", "value": "Zijie Shen" }, { "context": "(813044)\n * @author Zijie Shen (741404)\n * @author Zijun Chen (813190)\n */\npublic class PublicKeyNotFoundExcept", "end": 212, "score": 0.9998248815536499, "start": 202, "tag": "NAME", "value": "Zijun Chen" } ]
null
[]
package unimelb.bitbox.util; /** * Exception Wrapper for using Public Key to encrypt AES key * * @author <NAME> (752454) * @author <NAME> (813044) * @author <NAME> (741404) * @author <NAME> (813190) */ public class PublicKeyNotFoundException extends Exception { public PublicKeyNotFoundException(String errorMessage, Throwable err) { super(errorMessage, err); } }
388
0.720297
0.660891
15
25.933332
23.296543
75
false
false
0
0
0
0
0
0
0.266667
false
false
5
c287f93c72e5a1cb88190191f897a2ac02683de8
25,907,242,761,219
66b1014a5dffaea4726d19d6c674bef91f397d6b
/app/src/main/java/com/example/pixelgame/GameObjects/Byteable.java
de88b864cd020affe40823198e122cfa637eda88
[]
no_license
facklerh/BSINFO_AP_Projekt
https://github.com/facklerh/BSINFO_AP_Projekt
71726e69bb635471ac0301458111aee3c96324c2
86d515cd59fdebd232987671ffe6258bdd493ad8
refs/heads/master
2022-04-13T07:35:37.655000
2020-03-31T12:57:39
2020-03-31T12:57:39
232,268,316
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.pixelgame.GameObjects; public interface Byteable { public byte[] toBytes(); }
UTF-8
Java
103
java
Byteable.java
Java
[]
null
[]
package com.example.pixelgame.GameObjects; public interface Byteable { public byte[] toBytes(); }
103
0.747573
0.747573
5
19.6
16.475437
42
false
false
0
0
0
0
0
0
0.4
false
false
5
340a6a1a2d4e0d109bdadf22a98d80cec941db5c
31,860,067,435,830
9216483e34c03295197914296f8052cb1b6a54b0
/Bet_1207/src/store/logic/BetStoreLogic.java
20049cb41a865a15d4d970c03654b0b21de63086
[]
no_license
shanghwan/Betrepository
https://github.com/shanghwan/Betrepository
ebada000b737254943524a34203c6e37d47cabe8
16ee21d3cca5e3d0d3a74fb10978828871b89ddf
refs/heads/master
2021-08-27T22:35:25.939000
2017-12-08T02:29:45
2017-12-08T02:29:45
112,135,819
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package store.logic; import java.util.HashMap; import java.util.List; import org.apache.ibatis.session.SqlSession; import org.springframework.stereotype.Repository; import domain.Bet; import store.BetStore; import store.mapper.BetMapper; @Repository public class BetStoreLogic implements BetStore { @Override public String create(Bet bet) { SqlSession session = BetSessionFactory.getinstance().getSession(); try { BetMapper mapper = session.getMapper(BetMapper.class); mapper.create(bet); session.commit(); } finally { session.close(); } return bet.getBetId(); } @Override public List<Bet> searchAllBet() { SqlSession session = BetSessionFactory.getinstance().getSession(); List<Bet> list = null; try { BetMapper mapper = session.getMapper(BetMapper.class); list = mapper.searchAllBet(); } finally { session.close(); } return list; } @Override public Bet searchByBetId(String betId) { SqlSession session = BetSessionFactory.getinstance().getSession(); Bet bet = null; try { BetMapper mapper = session.getMapper(BetMapper.class); bet = mapper.searchByBetId(betId); } finally { session.close(); } return bet; } @Override public List<Bet> searchByBetOwner(String betOwner, String betWay) { SqlSession session = BetSessionFactory.getinstance().getSession(); HashMap<String, String> map = new HashMap<>(); List<Bet> list = null; try { BetMapper mapper = session.getMapper(BetMapper.class); map.put("betOwner", betOwner); map.put("betWay", betWay); list = mapper.searchByBetOwner(map); } finally { session.close(); } return list; } @Override public List<Bet> searchByTitle(String title, String betWay) { SqlSession session = BetSessionFactory.getinstance().getSession(); List<Bet> list = null; HashMap<String, String> map = new HashMap<>(); try { BetMapper mapper = session.getMapper(BetMapper.class); map.put("title", title); map.put("betWay", betWay); list = mapper.searchByTitle(map); } finally { session.close(); } return list; } @Override public List<Bet> searchByState(String state) { SqlSession session = BetSessionFactory.getinstance().getSession(); List<Bet> list = null; try { BetMapper mapper = session.getMapper(BetMapper.class); list = mapper.searchByState(state); } finally { session.close(); } return list; } @Override public List<Bet> searchByBetWay(String betWay) { SqlSession session = BetSessionFactory.getinstance().getSession(); List<Bet> list = null; try { BetMapper mapper = session.getMapper(BetMapper.class); list = mapper.searchByBetWay(betWay); } finally { session.close(); } return list; } @Override public void update(Bet bet) { SqlSession session = BetSessionFactory.getinstance().getSession(); try { BetMapper mapper = session.getMapper(BetMapper.class); mapper.update(bet); session.commit(); } finally { session.close(); } } @Override public void delete(String betId) { SqlSession session = BetSessionFactory.getinstance().getSession(); try { BetMapper mapper = session.getMapper(BetMapper.class); mapper.delete(betId); session.commit(); } finally { session.close(); } } @Override public List<Bet> searchByUserId(String betOwner) { SqlSession session = BetSessionFactory.getinstance().getSession(); List<Bet> list = null; try { BetMapper mapper = session.getMapper(BetMapper.class); list = mapper.searchByUserId(betOwner); } finally { session.close(); } return list; } }
UTF-8
Java
3,767
java
BetStoreLogic.java
Java
[]
null
[]
package store.logic; import java.util.HashMap; import java.util.List; import org.apache.ibatis.session.SqlSession; import org.springframework.stereotype.Repository; import domain.Bet; import store.BetStore; import store.mapper.BetMapper; @Repository public class BetStoreLogic implements BetStore { @Override public String create(Bet bet) { SqlSession session = BetSessionFactory.getinstance().getSession(); try { BetMapper mapper = session.getMapper(BetMapper.class); mapper.create(bet); session.commit(); } finally { session.close(); } return bet.getBetId(); } @Override public List<Bet> searchAllBet() { SqlSession session = BetSessionFactory.getinstance().getSession(); List<Bet> list = null; try { BetMapper mapper = session.getMapper(BetMapper.class); list = mapper.searchAllBet(); } finally { session.close(); } return list; } @Override public Bet searchByBetId(String betId) { SqlSession session = BetSessionFactory.getinstance().getSession(); Bet bet = null; try { BetMapper mapper = session.getMapper(BetMapper.class); bet = mapper.searchByBetId(betId); } finally { session.close(); } return bet; } @Override public List<Bet> searchByBetOwner(String betOwner, String betWay) { SqlSession session = BetSessionFactory.getinstance().getSession(); HashMap<String, String> map = new HashMap<>(); List<Bet> list = null; try { BetMapper mapper = session.getMapper(BetMapper.class); map.put("betOwner", betOwner); map.put("betWay", betWay); list = mapper.searchByBetOwner(map); } finally { session.close(); } return list; } @Override public List<Bet> searchByTitle(String title, String betWay) { SqlSession session = BetSessionFactory.getinstance().getSession(); List<Bet> list = null; HashMap<String, String> map = new HashMap<>(); try { BetMapper mapper = session.getMapper(BetMapper.class); map.put("title", title); map.put("betWay", betWay); list = mapper.searchByTitle(map); } finally { session.close(); } return list; } @Override public List<Bet> searchByState(String state) { SqlSession session = BetSessionFactory.getinstance().getSession(); List<Bet> list = null; try { BetMapper mapper = session.getMapper(BetMapper.class); list = mapper.searchByState(state); } finally { session.close(); } return list; } @Override public List<Bet> searchByBetWay(String betWay) { SqlSession session = BetSessionFactory.getinstance().getSession(); List<Bet> list = null; try { BetMapper mapper = session.getMapper(BetMapper.class); list = mapper.searchByBetWay(betWay); } finally { session.close(); } return list; } @Override public void update(Bet bet) { SqlSession session = BetSessionFactory.getinstance().getSession(); try { BetMapper mapper = session.getMapper(BetMapper.class); mapper.update(bet); session.commit(); } finally { session.close(); } } @Override public void delete(String betId) { SqlSession session = BetSessionFactory.getinstance().getSession(); try { BetMapper mapper = session.getMapper(BetMapper.class); mapper.delete(betId); session.commit(); } finally { session.close(); } } @Override public List<Bet> searchByUserId(String betOwner) { SqlSession session = BetSessionFactory.getinstance().getSession(); List<Bet> list = null; try { BetMapper mapper = session.getMapper(BetMapper.class); list = mapper.searchByUserId(betOwner); } finally { session.close(); } return list; } }
3,767
0.665251
0.665251
175
19.525715
20.991377
68
false
false
0
0
0
0
0
0
1.914286
false
false
5
735b40f5ad25e96d6f8d7a63fdddb0d57a34e30b
31,860,067,436,981
d60d611271a51e147533038e467c9ac48d04a792
/201920/src/tree/BinaryTreeOrderLevelTravel102.java
26d77612bf54ed613fd58a452d9045b0e864a543
[]
no_license
ninepig/201920
https://github.com/ninepig/201920
c0fa164fef3ef6c416615cf015eba7a4516c31ee
0e797e0baaa6c79220c8a7e766fee163699b0f60
refs/heads/master
2020-08-22T09:25:43.452000
2020-01-11T04:18:29
2020-01-11T04:18:29
216,365,208
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package tree; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; /** * Similar to 103 107 . Skipped */ public class BinaryTreeOrderLevelTravel102 { public List<List<Integer>> levelOrder(TreeNode root) { if(root == null) return new ArrayList<>(); List<List<Integer>> res = new ArrayList<>(); Queue<TreeNode> q = new LinkedList<>(); q.offer(root); while (!q.isEmpty()){ int size = q.size(); List<Integer> cur = new ArrayList<>(); for (int i = 0 ; i < size ; i++){ TreeNode curNode = q.poll(); cur.add(curNode.val); if (curNode.left != null){ q.offer(curNode.left); } // we can not use else if !! need if !! have to go through this // TODO go through Queue, it is not ifelse. it need to be if if if !! if (curNode.right != null){ q.offer(curNode.right); } } res.add(cur); } return res; } }
UTF-8
Java
1,138
java
BinaryTreeOrderLevelTravel102.java
Java
[]
null
[]
package tree; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; /** * Similar to 103 107 . Skipped */ public class BinaryTreeOrderLevelTravel102 { public List<List<Integer>> levelOrder(TreeNode root) { if(root == null) return new ArrayList<>(); List<List<Integer>> res = new ArrayList<>(); Queue<TreeNode> q = new LinkedList<>(); q.offer(root); while (!q.isEmpty()){ int size = q.size(); List<Integer> cur = new ArrayList<>(); for (int i = 0 ; i < size ; i++){ TreeNode curNode = q.poll(); cur.add(curNode.val); if (curNode.left != null){ q.offer(curNode.left); } // we can not use else if !! need if !! have to go through this // TODO go through Queue, it is not ifelse. it need to be if if if !! if (curNode.right != null){ q.offer(curNode.right); } } res.add(cur); } return res; } }
1,138
0.503515
0.494728
36
30.611111
20.815697
86
false
false
0
0
0
0
0
0
0.555556
false
false
5
f5994a853c1fceffba8619cf4f9fdd13f6200318
24,747,601,571,649
e615da21d07f419d2d610a08f7b40a587dd75245
/app/src/main/java/com/example/socket_connection/Request.java
2c32b5079c310d65dfa4d9491b9188f0e4ce38de
[]
no_license
e165703/SocketConnection
https://github.com/e165703/SocketConnection
39c18e1cf6e0715a20fa278d08c718157206f943
937d2fde94f732cc67f5525e2ca27cbc24d06799
refs/heads/master
2020-06-07T14:28:19.006000
2019-08-31T13:20:38
2019-08-31T13:20:38
193,041,321
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.socket_connection; import java.util.HashMap; import java.util.regex.Matcher; import java.util.Map; public class Request { Method method; String target; String version; protected Map<String,String> headers; protected byte[] body; public Request(Method method, String target, String version){ super(); this.method = method; this.target = target; this.version = version; this.headers = new HashMap<>(); this.body = new byte[0]; } public Method getMethod(){ return method; } public String getTarget(){ return target; } public String getVersion(){ return version; } public String getStartLine(){ return (method.toString()+" "+target+" "+version); } public void addHeaderField(String name, String value){ this.headers.put(name,value); } public Map<String,String> getHeaders(){ return headers; } public void setBody(byte[] body){ this.body = body; } public byte[] getBody() { return body; } }
UTF-8
Java
1,121
java
Request.java
Java
[]
null
[]
package com.example.socket_connection; import java.util.HashMap; import java.util.regex.Matcher; import java.util.Map; public class Request { Method method; String target; String version; protected Map<String,String> headers; protected byte[] body; public Request(Method method, String target, String version){ super(); this.method = method; this.target = target; this.version = version; this.headers = new HashMap<>(); this.body = new byte[0]; } public Method getMethod(){ return method; } public String getTarget(){ return target; } public String getVersion(){ return version; } public String getStartLine(){ return (method.toString()+" "+target+" "+version); } public void addHeaderField(String name, String value){ this.headers.put(name,value); } public Map<String,String> getHeaders(){ return headers; } public void setBody(byte[] body){ this.body = body; } public byte[] getBody() { return body; } }
1,121
0.603033
0.602141
54
19.75926
16.771818
65
false
false
0
0
0
0
0
0
0.537037
false
false
5
7f3cd6d79be5816b2a162a7602ba2943e3c91f16
1,486,058,734,074
f44cdfcc48296c3378f0916dde11aad1c99657ef
/src/algorithm/SelectionSort.java
e46577b351526643cd147b4716b94045ab189bb6
[]
no_license
joyork/Experiment
https://github.com/joyork/Experiment
ee15e0087f677d5120e88d7569d1237554481c56
fb5a95d26aa66cc874489e8cddaf8165a01fb8e8
refs/heads/master
2021-07-13T20:39:41.325000
2017-05-31T03:14:21
2017-05-31T03:14:21
12,155,754
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package algorithm; public class SelectionSort { public static void selectionSort(int[] a) { int i, j; int n = a.length; for (i = 0; i < n; i++) { int min = i; for (j = i; j < n; j++) { if (a[min] > a[j]) { min = j; } } if (min != i) { int tmp = a[min]; a[min] = a[i]; a[i] = tmp; } } } public static void main(String[] args) { int[] a = new int[] { 2, 14, 44, 3, 9, 6, 13, 8 }; selectionSort(a); for (int i = 0; i < a.length; i++) { System.out.println(a[i] + " "); } int[] b = new int[] { 2, 14, 44, 3, 9, 6, 13, 8 }; selectSort(b); for (int i = 0; i < b.length; i++) { System.out.println(b[i] + " "); } } public static void selectSort(int[] a) { int n = a.length; for (int i = 0; i < n; i++) { int min = a[i]; int mi = i; for (int j = i; j < n; j++) { if (a[j] < min) { min = a[j]; mi = j; } } if (mi != i) { int tmp = a[mi]; a[mi] = a[i]; a[i] = tmp; } } } }
UTF-8
Java
1,053
java
SelectionSort.java
Java
[]
null
[]
package algorithm; public class SelectionSort { public static void selectionSort(int[] a) { int i, j; int n = a.length; for (i = 0; i < n; i++) { int min = i; for (j = i; j < n; j++) { if (a[min] > a[j]) { min = j; } } if (min != i) { int tmp = a[min]; a[min] = a[i]; a[i] = tmp; } } } public static void main(String[] args) { int[] a = new int[] { 2, 14, 44, 3, 9, 6, 13, 8 }; selectionSort(a); for (int i = 0; i < a.length; i++) { System.out.println(a[i] + " "); } int[] b = new int[] { 2, 14, 44, 3, 9, 6, 13, 8 }; selectSort(b); for (int i = 0; i < b.length; i++) { System.out.println(b[i] + " "); } } public static void selectSort(int[] a) { int n = a.length; for (int i = 0; i < n; i++) { int min = a[i]; int mi = i; for (int j = i; j < n; j++) { if (a[j] < min) { min = a[j]; mi = j; } } if (mi != i) { int tmp = a[mi]; a[mi] = a[i]; a[i] = tmp; } } } }
1,053
0.412156
0.387464
55
17.145454
14.025196
52
false
false
0
0
0
0
0
0
3.290909
false
false
5
23f3f0608b35c2d50a661012eb1fc622a438e5bf
1,486,058,732,366
aefbf3d85f0d7031e1c349b96ae747fa9a6a1c48
/app/src/main/java/com/leo/everyday/module/photo/IPhotoItem.java
b7fb5c08ad90ec97ada86e556ff8f8499cf6aeb6
[]
no_license
WeedLi/leo_everyday
https://github.com/WeedLi/leo_everyday
368b01d099de6ad6c0341a7e9d89e32574867df6
4175d1ea5575a390992d43b96e1c8a59ad5db1ea
refs/heads/master
2021-04-12T08:15:58.816000
2018-03-19T06:24:31
2018-03-19T06:24:31
125,799,221
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.leo.everyday.module.photo; import com.leo.everyday.module.base.IBasePresenter; import com.leo.everyday.module.base.IBaseRecyclerView; /** * 作者:Leo on 2018/1/29 11:44 * <p> * 描述: */ public interface IPhotoItem { interface Presenter extends IBasePresenter { /** * 做网络加载 */ void doLoadData(boolean isRefresh, boolean isLoadMore); } interface View extends IBaseRecyclerView<Presenter> { } }
UTF-8
Java
483
java
IPhotoItem.java
Java
[ { "context": "veryday.module.base.IBaseRecyclerView;\n\n/**\n * 作者:Leo on 2018/1/29 11:44\n * <p>\n * 描述:\n */\n\npublic inte", "end": 161, "score": 0.9989723563194275, "start": 158, "tag": "USERNAME", "value": "Leo" } ]
null
[]
package com.leo.everyday.module.photo; import com.leo.everyday.module.base.IBasePresenter; import com.leo.everyday.module.base.IBaseRecyclerView; /** * 作者:Leo on 2018/1/29 11:44 * <p> * 描述: */ public interface IPhotoItem { interface Presenter extends IBasePresenter { /** * 做网络加载 */ void doLoadData(boolean isRefresh, boolean isLoadMore); } interface View extends IBaseRecyclerView<Presenter> { } }
483
0.663774
0.639913
26
16.73077
21.002853
63
false
false
0
0
0
0
0
0
0.192308
false
false
5
bbb78f3be131ee4299b3d960bf2fc3b630aec782
8,366,596,339,387
7f2c987f11101d5ebb8a210d849e05c438622c00
/userGroup/src/com/sendtask/common/thread/TaskThreadPool.java
280110e7101ace4debf8e30406f30474a96e52d7
[]
no_license
moutainhigh/quanquan
https://github.com/moutainhigh/quanquan
afed27cee8aa64ba7ec819ae97534c0b2f17b103
6c04d0a653b4df184f6b53359a202f20e3da8bdf
refs/heads/master
2021-06-17T02:24:03.751000
2017-05-25T15:35:54
2017-05-25T15:35:54
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sendtask.common.thread; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 线程池 * * @author zhoujia * @rewrite qiuxy */ public class TaskThreadPool { public static ExecutorService taskEs;// slave起脚本用 public static ExecutorService scheduleEs;// schedule订阅通道收到消息用 public static ExecutorService spareEs;// 备机订阅通道收到消息用 public static ExecutorService stopEs;// 停机订阅通道收到消息用 // 一共 ABQSIZE 个队列,生产者向 ABQSIZE 个队列轮循发送任务,每个队列ABQSIZE_INNER个线程消费 // public static final int ABQSIZE = 5; // public static final int ABQSIZE_INNER = 10; // public static final int QUESIZE = 2000; // public static ArrayBlockingQueue<String> taskabq[] = new // ArrayBlockingQueue[ABQSIZE]; // static { // for (int i = 0; i < ABQSIZE; i++) { // taskabq[i] = new ArrayBlockingQueue<String>(QUESIZE); // } // } private static Logger logger = LoggerFactory.getLogger(TaskThreadPool.class); /** * 初始化线程池 * * @param threadNum */ public void initThreadPool(int threadNum) { logger.info("初始化线程池aaaaa===="+threadNum); taskEs = Executors.newFixedThreadPool(threadNum);///// scheduleEs = Executors.newFixedThreadPool(threadNum);///// spareEs = Executors.newFixedThreadPool(threadNum);///// stopEs = Executors.newFixedThreadPool(threadNum);///// logger.info("初始化线程池bbbbb===="); } }
UTF-8
Java
1,561
java
TaskThreadPool.java
Java
[ { "context": "rg.slf4j.LoggerFactory;\n\n/**\n * 线程池\n * \n * @author zhoujia\n * @rewrite qiuxy\n */\npublic class TaskThreadPool", "end": 213, "score": 0.9993240237236023, "start": 206, "tag": "USERNAME", "value": "zhoujia" }, { "context": "ry;\n\n/**\n * 线程池\n * \n * @author zhoujia\n * @rewrite qiuxy\n */\npublic class TaskThreadPool {\n\tpublic static ", "end": 231, "score": 0.9995361566543579, "start": 226, "tag": "USERNAME", "value": "qiuxy" } ]
null
[]
package com.sendtask.common.thread; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 线程池 * * @author zhoujia * @rewrite qiuxy */ public class TaskThreadPool { public static ExecutorService taskEs;// slave起脚本用 public static ExecutorService scheduleEs;// schedule订阅通道收到消息用 public static ExecutorService spareEs;// 备机订阅通道收到消息用 public static ExecutorService stopEs;// 停机订阅通道收到消息用 // 一共 ABQSIZE 个队列,生产者向 ABQSIZE 个队列轮循发送任务,每个队列ABQSIZE_INNER个线程消费 // public static final int ABQSIZE = 5; // public static final int ABQSIZE_INNER = 10; // public static final int QUESIZE = 2000; // public static ArrayBlockingQueue<String> taskabq[] = new // ArrayBlockingQueue[ABQSIZE]; // static { // for (int i = 0; i < ABQSIZE; i++) { // taskabq[i] = new ArrayBlockingQueue<String>(QUESIZE); // } // } private static Logger logger = LoggerFactory.getLogger(TaskThreadPool.class); /** * 初始化线程池 * * @param threadNum */ public void initThreadPool(int threadNum) { logger.info("初始化线程池aaaaa===="+threadNum); taskEs = Executors.newFixedThreadPool(threadNum);///// scheduleEs = Executors.newFixedThreadPool(threadNum);///// spareEs = Executors.newFixedThreadPool(threadNum);///// stopEs = Executors.newFixedThreadPool(threadNum);///// logger.info("初始化线程池bbbbb===="); } }
1,561
0.729691
0.722502
47
28.595745
23.089705
78
false
false
0
0
0
0
0
0
1.234043
false
false
5
72411f30313a9a595712b0286f6b3dab00b1d9f5
33,148,557,653,403
cbdf03b6f923ab21a75554d85d316eef7bdc2836
/app/src/main/java/org/dosomething/letsdothis/utils/ViewUtils.java
9dfd1c2082f1f2f658840ce947aecd4309a425be
[ "MIT" ]
permissive
DoSomething/LetsDoThis-Android
https://github.com/DoSomething/LetsDoThis-Android
9801f168d4cbfd44e03a80df0e5189dc4148de39
bb529b1c0fe326513f87951269c9b65aefb30278
refs/heads/master
2021-05-22T04:41:04.273000
2016-09-26T14:51:57
2016-09-26T14:51:57
34,002,812
1
2
null
false
2016-09-26T14:51:58
2015-04-15T15:37:25
2016-05-26T17:34:26
2016-09-26T14:51:58
18,279
1
2
13
Java
null
null
package org.dosomething.letsdothis.utils; import android.content.Context; import android.content.res.Resources; import android.util.Patterns; import android.util.TypedValue; import org.dosomething.letsdothis.R; import java.io.File; /** * Created by izzyoji :) on 5/5/15. */ public class ViewUtils { public static File getAvatarFile(Context context) { return new File(context.getExternalFilesDir("images"), "avatar.jpg"); } public static Float getPxFromDip(Resources r, int dp) { return TypedValue .applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()); } /** * Helper function to format the displayed username. * * @param context Context * @param firstName User first name * @param lastInitial User last initial, if any * @return String */ public static String formatUserDisplayName(Context context, String firstName, String lastInitial) { // Sanitizing the first name because of rare cases where user's email was in that field String first = firstName != null ? firstName : ""; if (Patterns.EMAIL_ADDRESS.matcher(first).matches()) { first = context.getResources().getString(R.string.user_default_fname); } String last = ""; if (lastInitial != null && ! lastInitial.isEmpty()) { last = lastInitial + "."; } return String.format("%s %s", first, last).trim(); } }
UTF-8
Java
1,479
java
ViewUtils.java
Java
[ { "context": "dothis.R;\n\nimport java.io.File;\n\n/**\n * Created by izzyoji :) on 5/5/15.\n */\npublic class ViewUtils\n{\n pu", "end": 260, "score": 0.9997234344482422, "start": 253, "tag": "USERNAME", "value": "izzyoji" } ]
null
[]
package org.dosomething.letsdothis.utils; import android.content.Context; import android.content.res.Resources; import android.util.Patterns; import android.util.TypedValue; import org.dosomething.letsdothis.R; import java.io.File; /** * Created by izzyoji :) on 5/5/15. */ public class ViewUtils { public static File getAvatarFile(Context context) { return new File(context.getExternalFilesDir("images"), "avatar.jpg"); } public static Float getPxFromDip(Resources r, int dp) { return TypedValue .applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()); } /** * Helper function to format the displayed username. * * @param context Context * @param firstName User first name * @param lastInitial User last initial, if any * @return String */ public static String formatUserDisplayName(Context context, String firstName, String lastInitial) { // Sanitizing the first name because of rare cases where user's email was in that field String first = firstName != null ? firstName : ""; if (Patterns.EMAIL_ADDRESS.matcher(first).matches()) { first = context.getResources().getString(R.string.user_default_fname); } String last = ""; if (lastInitial != null && ! lastInitial.isEmpty()) { last = lastInitial + "."; } return String.format("%s %s", first, last).trim(); } }
1,479
0.651792
0.649087
49
29.183674
28.380558
103
false
false
0
0
0
0
0
0
0.469388
false
false
11
85eac40cf59b727684819730e796c6c2e69e2780
21,019,569,976,731
29cb656c7ac857cb0b36a9f3e1206bea8f345695
/IdeaProjects/basicCode/iO/src/iOStreamStudy/Demo18_P_Students.java
d9a37af67469a5e468b059c040055b546c6576f6
[]
no_license
WeiCANADA/Java_Code
https://github.com/WeiCANADA/Java_Code
11dd997f726592b14884c510ac5faf286c1675dd
e4b2186aadf21180ff55abef309155f5f7ed4558
refs/heads/master
2023-05-03T04:00:52.582000
2021-05-25T15:36:04
2021-05-25T15:36:04
370,742,230
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package IOStreamStudy; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.Comparator; import java.util.Scanner; import java.util.TreeSet; /* * 键盘录入5个学生信息(学号,语文成绩,数学成绩,英语成绩),按照总分从高到低存入文本文件 * * 分析: * A:创建学生类 * B:创建集合对象 * TreeSet<Student> * C:键盘录入学生信息存储到集合 * D:遍历集合,把数据写到文本文件 */ public class Demo18_P_Students { public static void main(String[] args) throws IOException { TreeSet<Demo18_P_StudentClass> stuTreeSet = new TreeSet <Demo18_P_StudentClass>(new Comparator<Demo18_P_StudentClass>() { @Override public int compare(Demo18_P_StudentClass s1, Demo18_P_StudentClass s2) { float i = s1.sumSores() - s2.sumSores(); float i1 = i == 0? s1.chineseS - s2.chineseS : i; float i2 = i1 == 0? s1.englishS - s2.englishS : i1; float i3 = i2 == 0? s1.mathS - s2.mathS : i1; float i4 = i3 == 0? s1.getName().compareTo(s2.getName()) : i3; return (int) i4; } }); for (int i = 0; i < 5; i++) { Demo18_P_StudentClass s = new Demo18_P_StudentClass(); Scanner sc = new Scanner(System.in); System.out.println("请输入学生学号:"); s.setName(sc.nextLine()); System.out.println("请输入ChineseScore:"); s.setChineseS(sc.nextFloat()); System.out.println("请输入EnglishScore:"); s.setEnglishS(sc.nextFloat()); System.out.println("请输入ChineseScore:"); s.setMathS(sc.nextFloat()); stuTreeSet.add(s); } BufferedWriter bw = new BufferedWriter(new FileWriter("student.txt")); bw.write("学生信息如下:"); bw.newLine(); bw.flush(); bw.write("Name,Chinese,English,Math"); bw.newLine(); bw.flush(); for (Demo18_P_StudentClass s : stuTreeSet){ StringBuilder sb = new StringBuilder(); sb.append(s.getName()).append(',').append(s.getChineseS()).append(',') .append(s.getEnglishS()).append(',').append(s.getMathS()); bw.write(sb.toString()); bw.newLine(); bw.flush(); } bw.close(); System.out.println("学生信息存储完毕"); } }
UTF-8
Java
2,540
java
Demo18_P_Students.java
Java
[]
null
[]
package IOStreamStudy; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.Comparator; import java.util.Scanner; import java.util.TreeSet; /* * 键盘录入5个学生信息(学号,语文成绩,数学成绩,英语成绩),按照总分从高到低存入文本文件 * * 分析: * A:创建学生类 * B:创建集合对象 * TreeSet<Student> * C:键盘录入学生信息存储到集合 * D:遍历集合,把数据写到文本文件 */ public class Demo18_P_Students { public static void main(String[] args) throws IOException { TreeSet<Demo18_P_StudentClass> stuTreeSet = new TreeSet <Demo18_P_StudentClass>(new Comparator<Demo18_P_StudentClass>() { @Override public int compare(Demo18_P_StudentClass s1, Demo18_P_StudentClass s2) { float i = s1.sumSores() - s2.sumSores(); float i1 = i == 0? s1.chineseS - s2.chineseS : i; float i2 = i1 == 0? s1.englishS - s2.englishS : i1; float i3 = i2 == 0? s1.mathS - s2.mathS : i1; float i4 = i3 == 0? s1.getName().compareTo(s2.getName()) : i3; return (int) i4; } }); for (int i = 0; i < 5; i++) { Demo18_P_StudentClass s = new Demo18_P_StudentClass(); Scanner sc = new Scanner(System.in); System.out.println("请输入学生学号:"); s.setName(sc.nextLine()); System.out.println("请输入ChineseScore:"); s.setChineseS(sc.nextFloat()); System.out.println("请输入EnglishScore:"); s.setEnglishS(sc.nextFloat()); System.out.println("请输入ChineseScore:"); s.setMathS(sc.nextFloat()); stuTreeSet.add(s); } BufferedWriter bw = new BufferedWriter(new FileWriter("student.txt")); bw.write("学生信息如下:"); bw.newLine(); bw.flush(); bw.write("Name,Chinese,English,Math"); bw.newLine(); bw.flush(); for (Demo18_P_StudentClass s : stuTreeSet){ StringBuilder sb = new StringBuilder(); sb.append(s.getName()).append(',').append(s.getChineseS()).append(',') .append(s.getEnglishS()).append(',').append(s.getMathS()); bw.write(sb.toString()); bw.newLine(); bw.flush(); } bw.close(); System.out.println("学生信息存储完毕"); } }
2,540
0.554647
0.533993
69
32.68116
23.8148
84
false
false
0
0
0
0
0
0
0.913043
false
false
11
b33c16cc5e891059d63953022771d12ec328508f
28,226,525,139,009
4a1fe225da16a1809caf407a151d9078c04a6afc
/src/model/M_K.java
f5e794a9ddbeb4b7ab407ff87e4886d693374bcb
[]
no_license
Lotussius/MovieGo
https://github.com/Lotussius/MovieGo
56a17a3e9b0c360aecd738771c70edba47434f34
523741480beef16caac3454c03c1d730db370a7c
refs/heads/master
2022-12-25T08:30:20.101000
2020-09-09T03:13:49
2020-09-09T03:13:49
293,989,745
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package model; public class M_K {}
UTF-8
Java
36
java
M_K.java
Java
[]
null
[]
package model; public class M_K {}
36
0.694444
0.694444
4
8
7.071068
16
false
false
0
0
0
0
0
0
0.25
false
false
11
92b981e0fa4a8f4d30d2902640d4118f135efbd5
17,497,696,813,411
83da434ec4f8b87eefff38c768f888041505f2b9
/src/capsule/pattern/create/abstractfac/FactoryTest.java
59287318a07322c4c8ceadd4ec26c1e7237b4c37
[]
no_license
wushenggit/java-pattern
https://github.com/wushenggit/java-pattern
1cba36ff5c6cdc2afca857e8a6512b7615a8dc9f
24a64bbd8ff3261fa1020d8aa9e2eb7d965ddb91
refs/heads/master
2018-02-07T13:26:19.621000
2017-07-12T02:59:23
2017-07-12T02:59:23
95,875,188
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package capsule.pattern.create.abstractfac; import capsule.pattern.create.abstractfac.holo.HoloFactory; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * Created by hhly-pc on 2017/6/30. */ public class FactoryTest { Factory factory; @Before public void setUp() throws Exception { factory = new HoloFactory(); } @After public void tearDown() throws Exception { } @Test public void createTextView() throws Exception { factory.createTextView().getText(); } @Test public void createEditText() throws Exception { factory.createEditText().onContentChanged(); } @Test public void createButton() throws Exception { factory.createButton().onClick(); } @Test public void createCheckBox() throws Exception { factory.createCheckBox().onCheckChanged(); } }
UTF-8
Java
828
java
FactoryTest.java
Java
[ { "context": ".Before;\nimport org.junit.Test;\n\n/**\n * Created by hhly-pc on 2017/6/30.\n */\npublic class FactoryTest {\n Fa", "end": 203, "score": 0.9996170997619629, "start": 196, "tag": "USERNAME", "value": "hhly-pc" } ]
null
[]
package capsule.pattern.create.abstractfac; import capsule.pattern.create.abstractfac.holo.HoloFactory; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * Created by hhly-pc on 2017/6/30. */ public class FactoryTest { Factory factory; @Before public void setUp() throws Exception { factory = new HoloFactory(); } @After public void tearDown() throws Exception { } @Test public void createTextView() throws Exception { factory.createTextView().getText(); } @Test public void createEditText() throws Exception { factory.createEditText().onContentChanged(); } @Test public void createButton() throws Exception { factory.createButton().onClick(); } @Test public void createCheckBox() throws Exception { factory.createCheckBox().onCheckChanged(); } }
828
0.722222
0.713768
36
22.027779
21.583797
59
false
false
0
0
0
0
0
0
0.305556
false
false
11
44c5535a765d4c1b882120aeeea54852b9fce7b9
29,480,655,559,535
3a6d849edc4bf3ece23919ba15e62a484bcb564f
/src/com/example/sleepstatistic/ICaculator.java
d01cb4baaef0dbe4b947422f3cb7e64babea3f81
[]
no_license
yixzhang/SleepTimeCalculator
https://github.com/yixzhang/SleepTimeCalculator
1e46f76f763b9ba54fe6327c25af9b92eae39135
f4f30b90f6632e8ec4b1b02ba5c4dd42ce0bd31d
refs/heads/master
2016-09-16T15:40:56.233000
2013-06-15T13:33:27
2013-06-15T13:33:27
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.sleepstatistic; public interface ICaculator { public void setTime(int time); public double getAmount(); }
UTF-8
Java
140
java
ICaculator.java
Java
[]
null
[]
package com.example.sleepstatistic; public interface ICaculator { public void setTime(int time); public double getAmount(); }
140
0.721429
0.721429
8
15.5
15.149258
35
false
false
0
0
0
0
0
0
0.75
false
false
11
e7699bbe0881ae12fb2760b5c70222815d0c68b2
18,133,351,964,438
5c8e7ee96cb7809affc560f17d670d9a293584ba
/src/main/java/com/miro/dev/widgets/exceptions/WidgetNotFoundException.java
a25142113680b95a8f957575c6f6f6f8414a17e0
[ "MIT" ]
permissive
devc0unt/widgets
https://github.com/devc0unt/widgets
4113f037d2574c6f07d1e525a8a814bf348d6d76
6c088be8a96ca1601f58371dcee1b430db644b61
refs/heads/main
2022-12-31T22:52:08.878000
2020-10-19T17:01:27
2020-10-19T17:01:27
305,451,381
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.miro.dev.widgets.exceptions; public class WidgetNotFoundException extends RuntimeException { public WidgetNotFoundException() { super("Widget not found!"); } }
UTF-8
Java
189
java
WidgetNotFoundException.java
Java
[]
null
[]
package com.miro.dev.widgets.exceptions; public class WidgetNotFoundException extends RuntimeException { public WidgetNotFoundException() { super("Widget not found!"); } }
189
0.73545
0.73545
7
26
22.462667
63
false
false
0
0
0
0
0
0
0.285714
false
false
11
ba56294c0b4fd83ed404178ed659b0ae05bef05e
32,143,535,308,944
ce0675b63ecc059672338c982331694b100b30c4
/Hw/src/ArrayCalc.java
1f7f32ddaec3b011dcc5b77d06d78189e0292e78
[]
no_license
pranavenzo/JAVAProjects
https://github.com/pranavenzo/JAVAProjects
e713f1d8bc7d841d0937ff1f605e71ac4f00b839
d55647f7497bb5a0f9c048817363cae1207c687d
refs/heads/master
2018-03-21T08:34:05.354000
2017-03-24T07:54:45
2017-03-24T07:54:45
67,652,191
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class ArrayCalc { public static void main(String args[]) { ArrayCalc a = new ArrayCalc(); System.out.println(a.arrayCalc(new int[]{1, 2, 3})); //prints "high: 3, low: 1, average: 2" System.out.println(a.arrayCalc(new int[]{0})); //prints "high: 0, low: 0, average: 0" System.out.println(a.arrayCalc(null)); //prints "" } public String arrayCalc( int array[]) { if (array == null) { return ""; } int highestNumber = array[0]; int lowestNumber = array[0]; int sum = 0; for ( int i = 0; i < array.length; i++) { if ( array[i] > highestNumber ) { highestNumber = array[i]; } else if ( array[i] < lowestNumber ) { lowestNumber = array[i]; } sum = sum + array[i]; } int average = sum / array.length; return ("high: " + highestNumber + ", low: " + lowestNumber + ", average: " + average); } }
UTF-8
Java
1,048
java
ArrayCalc.java
Java
[]
null
[]
public class ArrayCalc { public static void main(String args[]) { ArrayCalc a = new ArrayCalc(); System.out.println(a.arrayCalc(new int[]{1, 2, 3})); //prints "high: 3, low: 1, average: 2" System.out.println(a.arrayCalc(new int[]{0})); //prints "high: 0, low: 0, average: 0" System.out.println(a.arrayCalc(null)); //prints "" } public String arrayCalc( int array[]) { if (array == null) { return ""; } int highestNumber = array[0]; int lowestNumber = array[0]; int sum = 0; for ( int i = 0; i < array.length; i++) { if ( array[i] > highestNumber ) { highestNumber = array[i]; } else if ( array[i] < lowestNumber ) { lowestNumber = array[i]; } sum = sum + array[i]; } int average = sum / array.length; return ("high: " + highestNumber + ", low: " + lowestNumber + ", average: " + average); } }
1,048
0.485687
0.472328
28
35.357143
26.329254
99
false
false
0
0
0
0
0
0
0.821429
false
false
11
d926cd2fa8137b14cb7d052f68ea53c0eadf5f87
20,684,562,527,910
27e84ab19cb91a7627b105d7a558ea7a246d0e65
/src/main/java/training/leetcode/p_0000/p0005/Solution_0005.java
ed96a89640be5633dec6b86e4ea3bbbb8e529245
[]
no_license
ben-dasilva/lc-solutions
https://github.com/ben-dasilva/lc-solutions
f32af07d97d955b03c43657ff4df7844459f5b39
c85c84b250fd46e062ed65f6e1240cd759126798
refs/heads/master
2021-06-30T16:25:45.488000
2020-10-13T21:34:41
2020-10-13T21:34:41
181,308,152
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package training.leetcode.p_0000.p0005; public class Solution_0005 { public String longestPalindrome(String s) { int inputLen = s.length(); boolean[][] palindromeRepository = new boolean[inputLen][inputLen]; char[] str = s.toCharArray(); // find all 1-letter palindromes (hint: ALL 1-letter words are palindromes) markSingleLettersAsPalindrome(palindromeRepository); String longestPalindrome = s.substring(0, Math.min(1, s.length())); longestPalindrome = checkTwoLettersForPalindromes(str, longestPalindrome, palindromeRepository); // find n-letter palindromes (n > 1) for (int n = 3; n <= inputLen; n++) { longestPalindrome = markPalindromesOfSize(n, str, palindromeRepository, longestPalindrome); } return longestPalindrome; } private String checkTwoLettersForPalindromes(char[] str, String longestPalindrome, boolean[][] repo) { boolean found = false; for (int i = 0; i < repo.length-1; i++) { boolean isPalindrome = str[i] == str[i + 1]; repo[i][i+1] = isPalindrome; if (!found && isPalindrome) { found = true; longestPalindrome = String.copyValueOf(str, i, 2); } } return longestPalindrome; } private String markPalindromesOfSize(int n, char[] s, boolean[][] repo, String longestPalindrome) { // iterate in chunks of size n String newLongest = longestPalindrome; for (int i = 0; i+n <= repo.length; i++) { int start = i; int end = i+n-1; // is palidrome if: // [1] string between start and end is palindrome // [2] s[start] == s[end] boolean isCorePalindrome = isKnownPalindrome(repo, start+1, end-1); if (!isCorePalindrome) continue; boolean isPalindrome = s[start] == s[end]; repo[start][end] = isPalindrome; if (repo[start][end] && end-start >= newLongest.length()) { newLongest = String.copyValueOf(s, start, end+1-start); } } return newLongest; } private boolean isKnownPalindrome(boolean[][] repo, int start, int end) { if (start+1 > end) return true; return repo[start][end]; } private void markSingleLettersAsPalindrome(boolean[][] repo) { for (int i = 0; i < repo.length; i++) { repo[i][i] = true; } } }
UTF-8
Java
2,532
java
Solution_0005.java
Java
[]
null
[]
package training.leetcode.p_0000.p0005; public class Solution_0005 { public String longestPalindrome(String s) { int inputLen = s.length(); boolean[][] palindromeRepository = new boolean[inputLen][inputLen]; char[] str = s.toCharArray(); // find all 1-letter palindromes (hint: ALL 1-letter words are palindromes) markSingleLettersAsPalindrome(palindromeRepository); String longestPalindrome = s.substring(0, Math.min(1, s.length())); longestPalindrome = checkTwoLettersForPalindromes(str, longestPalindrome, palindromeRepository); // find n-letter palindromes (n > 1) for (int n = 3; n <= inputLen; n++) { longestPalindrome = markPalindromesOfSize(n, str, palindromeRepository, longestPalindrome); } return longestPalindrome; } private String checkTwoLettersForPalindromes(char[] str, String longestPalindrome, boolean[][] repo) { boolean found = false; for (int i = 0; i < repo.length-1; i++) { boolean isPalindrome = str[i] == str[i + 1]; repo[i][i+1] = isPalindrome; if (!found && isPalindrome) { found = true; longestPalindrome = String.copyValueOf(str, i, 2); } } return longestPalindrome; } private String markPalindromesOfSize(int n, char[] s, boolean[][] repo, String longestPalindrome) { // iterate in chunks of size n String newLongest = longestPalindrome; for (int i = 0; i+n <= repo.length; i++) { int start = i; int end = i+n-1; // is palidrome if: // [1] string between start and end is palindrome // [2] s[start] == s[end] boolean isCorePalindrome = isKnownPalindrome(repo, start+1, end-1); if (!isCorePalindrome) continue; boolean isPalindrome = s[start] == s[end]; repo[start][end] = isPalindrome; if (repo[start][end] && end-start >= newLongest.length()) { newLongest = String.copyValueOf(s, start, end+1-start); } } return newLongest; } private boolean isKnownPalindrome(boolean[][] repo, int start, int end) { if (start+1 > end) return true; return repo[start][end]; } private void markSingleLettersAsPalindrome(boolean[][] repo) { for (int i = 0; i < repo.length; i++) { repo[i][i] = true; } } }
2,532
0.577804
0.565166
81
30.25926
30.130899
106
false
false
0
0
0
0
0
0
0.679012
false
false
11
1aae3ab22c97487bfc12302ee262e43537fc7a91
16,922,171,201,364
e247a3b0bca58f9b669b5677fb8ec06c25a59339
/app/src/main/java/com/lee/iweibo/utils/Contract.java
59456523bf9fc3040ab0a6f18fbc2d53d0e7dd59
[]
no_license
liguotao1/MyWeiBo
https://github.com/liguotao1/MyWeiBo
1d2b52a3166d19420f543a78ccdb6e725123d148
435083fd7f1a95e7cd6a0987aeb9739c17167e77
refs/heads/master
2021-01-19T07:06:20.371000
2016-06-18T15:41:34
2016-06-18T15:41:34
61,440,419
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lee.iweibo.utils; /** * Created by Administrator on 2016/6/18. */ public class Contract { public static final String ISFIRST = "isFirst"; }
UTF-8
Java
159
java
Contract.java
Java
[ { "context": "package com.lee.iweibo.utils;\n\n/**\n * Created by Administrator on 2016/6/18.\n */\npublic class Contract {\n pub", "end": 62, "score": 0.44695425033569336, "start": 49, "tag": "NAME", "value": "Administrator" } ]
null
[]
package com.lee.iweibo.utils; /** * Created by Administrator on 2016/6/18. */ public class Contract { public static final String ISFIRST = "isFirst"; }
159
0.698113
0.654088
8
18.875
18.777895
51
false
false
0
0
0
0
0
0
0.25
false
false
11
df86752d67efa14aed7ad3763598f93521448f10
11,261,404,268,559
582c5276ad9acb7f53fd8da7fbe7b36aef1ce4f9
/src/main/java/com/dtv/des/extractor/WARCLinkExtractorMapper.java
3880a3c0e09073846b2ffdda493597e7ea91bae5
[]
no_license
quangdp/daily
https://github.com/quangdp/daily
070d10db5e106bfc591fdb07dca185a708020dfa
991beaf7ba426044280794a15e415fee2426fe56
refs/heads/master
2016-09-09T23:30:54.425000
2015-04-09T11:13:29
2015-04-09T11:13:29
33,346,539
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.dtv.des.extractor; import java.io.IOException; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.MapReduceBase; import org.apache.hadoop.mapred.Mapper; import org.apache.hadoop.mapred.OutputCollector; import org.apache.hadoop.mapred.Reporter; import org.archive.io.warc.WARCConstants; import org.archive.jbs.arc.ArcReader; import org.archive.jbs.arc.ArchiveRecordProxy; //import org.apache.nutch.parse.Parse; // Don't import due to name conflict. //import org.w3c.dom.Document; public class WARCLinkExtractorMapper extends MapReduceBase implements Mapper<Text, Text, Text, Text> { public static final Log LOG = LogFactory.getLog(WARCLinkExtractorMapper.class); private static Pattern ID = Pattern.compile("\\/title\\/(.+)\\/.*", Pattern.CASE_INSENSITIVE); private JobConf jobConf; /** * <p> * Configures the job. Sets the url filters, scoring filters, url * normalizers and other relevant data. * </p> * * @param job * The job configuration. */ public void configure(JobConf job) { this.jobConf = job; } public void map(Text key, Text value, OutputCollector<Text, Text> output, Reporter reporter) throws IOException { String path = key.toString(); LOG.info("Start: " + path); FSDataInputStream fis = null; // Emit JSON string try { fis = FileSystem.get(new java.net.URI(path), this.jobConf).open(new Path(path)); ArcReader reader = new ArcReader(path, fis); reader.setSizeLimit(jobConf.getInt("jbs.parse.content.limit", -1)); for (ArchiveRecordProxy record : reader) { LOG.info("Record Type: " + record.getWARCRecordType()); // If this is an HTTP response record, do all the parsing and // stuff. if (WARCConstants.WARCRecordType.response.toString().equals(record.getWARCRecordType().toString())) { if (WARCConstants.HTTP_RESPONSE_MIMETYPE.equals(record.getWARCContentType().toString())) { output.collect(new Text(record.getUrl()), new Text(record.getHttpResponseBody())); } } reporter.progress(); } } catch (Exception e) { LOG.error("Error processing archive file: " + path, e); if (jobConf.getBoolean("jbs.parse.abortOnArchiveReadError", true)) { throw new IOException(e); } } finally { LOG.info("Finish: " + path); } } }
UTF-8
Java
2,568
java
WARCLinkExtractorMapper.java
Java
[]
null
[]
package com.dtv.des.extractor; import java.io.IOException; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.MapReduceBase; import org.apache.hadoop.mapred.Mapper; import org.apache.hadoop.mapred.OutputCollector; import org.apache.hadoop.mapred.Reporter; import org.archive.io.warc.WARCConstants; import org.archive.jbs.arc.ArcReader; import org.archive.jbs.arc.ArchiveRecordProxy; //import org.apache.nutch.parse.Parse; // Don't import due to name conflict. //import org.w3c.dom.Document; public class WARCLinkExtractorMapper extends MapReduceBase implements Mapper<Text, Text, Text, Text> { public static final Log LOG = LogFactory.getLog(WARCLinkExtractorMapper.class); private static Pattern ID = Pattern.compile("\\/title\\/(.+)\\/.*", Pattern.CASE_INSENSITIVE); private JobConf jobConf; /** * <p> * Configures the job. Sets the url filters, scoring filters, url * normalizers and other relevant data. * </p> * * @param job * The job configuration. */ public void configure(JobConf job) { this.jobConf = job; } public void map(Text key, Text value, OutputCollector<Text, Text> output, Reporter reporter) throws IOException { String path = key.toString(); LOG.info("Start: " + path); FSDataInputStream fis = null; // Emit JSON string try { fis = FileSystem.get(new java.net.URI(path), this.jobConf).open(new Path(path)); ArcReader reader = new ArcReader(path, fis); reader.setSizeLimit(jobConf.getInt("jbs.parse.content.limit", -1)); for (ArchiveRecordProxy record : reader) { LOG.info("Record Type: " + record.getWARCRecordType()); // If this is an HTTP response record, do all the parsing and // stuff. if (WARCConstants.WARCRecordType.response.toString().equals(record.getWARCRecordType().toString())) { if (WARCConstants.HTTP_RESPONSE_MIMETYPE.equals(record.getWARCContentType().toString())) { output.collect(new Text(record.getUrl()), new Text(record.getHttpResponseBody())); } } reporter.progress(); } } catch (Exception e) { LOG.error("Error processing archive file: " + path, e); if (jobConf.getBoolean("jbs.parse.abortOnArchiveReadError", true)) { throw new IOException(e); } } finally { LOG.info("Finish: " + path); } } }
2,568
0.723131
0.722352
77
32.363636
29.720739
114
false
false
0
0
0
0
0
0
2.038961
false
false
11
3789010f6197dd58d20e36c34126407fa5061eec
2,748,779,084,483
c478ba464a64057a57fb41ce6bcb54b25d004ea2
/app/src/main/com/example/xdcao/diandiapp/UI/songwenqiang/Fragment/ShareFragment.java
182af79aca976cc5653033ad4cc6bf5ceaf2fbfd
[]
no_license
xdZenith/DianDiApp
https://github.com/xdZenith/DianDiApp
105038f530b8a7946d64d3a2b070f0ab38d72941
2878cb78615ed3f30bb6f560514a4b2e6ee751d6
refs/heads/master
2021-01-11T20:17:43.602000
2017-04-14T15:53:00
2017-04-14T15:53:00
79,084,219
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.xdcao.diandiapp.UI.songwenqiang.Fragment; import android.app.Activity; import android.app.Fragment; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.support.annotation.Nullable; import android.support.design.widget.CoordinatorLayout; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.example.xdcao.diandiapp.BackUp.caohao.bean.MyUser; import com.example.xdcao.diandiapp.BackUp.caohao.bean.Post; import com.example.xdcao.diandiapp.BackUp.caohao.cons.HandlerCons; import com.example.xdcao.diandiapp.DdService.liubotao.ninegridlayout.util.ImageLoaderUtil; import com.example.xdcao.diandiapp.R; import com.example.xdcao.diandiapp.UI.songwenqiang.bean.ContactItem; import com.example.xdcao.diandiapp.UI.songwenqiang.bean.SNotes; import com.example.xdcao.diandiapp.UI.songwenqiang.ui.ContactShareActivity; import com.example.xdcao.diandiapp.UI.songwenqiang.ui.DetailActivity; import com.example.xdcao.diandiapp.UI.songwenqiang.ui.MainActivity; import com.example.xdcao.diandiapp.UI.songwenqiang.ui.widget.RoundImageView; import com.example.xdcao.diandiapp.UI.songwenqiang.utils.SnackbarUtil; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import java.io.File; import java.io.FileReader; import java.util.ArrayList; import java.util.List; import cn.bmob.v3.Bmob; import cn.bmob.v3.BmobQuery; import cn.bmob.v3.datatype.BmobPointer; import cn.bmob.v3.exception.BmobException; import cn.bmob.v3.listener.FindListener; /** * Created by wewarrios on 2017/3/14. */ public class ShareFragment extends Fragment{ private static final String TAG = "bmob"; private final static int QUERY_SWIPE = 23; private RecyclerView recyclerView; private CoordinatorLayout coordinatorLayout; private List<Post> notes; private LinearLayoutManager mLayoutManager; private SwipeRefreshLayout swipeRefreshLayout; private Context context; private int frindCounter=0; private int postCounter=0; private int friendSize=0; private int postSize=0; private ImageLoader imageLoader; private NoteAdapter noteAdapter; Handler handler=new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what){ case HandlerCons.QUERY_ALL_SHARE: Log.d("bmob", "handleMessage: "+"get handler mList.size: "+notes.size()); noteAdapter = new NoteAdapter(); recyclerView.setAdapter(noteAdapter); break; case QUERY_SWIPE: swipeRefreshLayout.setRefreshing(false); if (noteAdapter!=null){ noteAdapter.notifyDataSetChanged(); } } super.handleMessage(msg); } }; class QueryForSharesThread extends Thread{ @Override public void run() { queryforShare(); } } private void queryforShare() { MyUser me=MyUser.getCurrentUser(MyUser.class); BmobQuery<MyUser> userQuery=new BmobQuery<>(); userQuery.addWhereRelatedTo("friends",new BmobPointer(me)); userQuery.findObjects(new FindListener<MyUser>() { @Override public void done(List<MyUser> list, BmobException e) { friendSize=list.size(); for (MyUser friend:list){ frindCounter++; BmobQuery<Post> isShareQuery=new BmobQuery<>(); isShareQuery.addWhereEqualTo("isShared",true); BmobQuery<Post> isFirendQuery=new BmobQuery<Post>(); isFirendQuery.addWhereEqualTo("author",friend); List<BmobQuery<Post>> queries=new ArrayList<BmobQuery<Post>>(); queries.add(isShareQuery); queries.add(isFirendQuery); BmobQuery<Post> mainQuery=new BmobQuery<Post>(); mainQuery.and(queries); mainQuery.order("-createdAt"); mainQuery.findObjects(new FindListener<Post>() { @Override public void done(List<Post> list, BmobException e) { if(e==null){ if (list.size()>0){ postSize=list.size(); for (Post post:list){ notes.add(post); postCounter++; if ((postCounter==postSize)&&(frindCounter==friendSize)){ Message message=new Message(); message.what= HandlerCons.QUERY_ALL_SHARE; handler.sendMessage(message); } } } } } }); } } }); } public ShareFragment(){ } private void initImageLoader() { imageLoader= ImageLoader.getInstance(); ImageLoaderConfiguration configuration=new ImageLoaderConfiguration.Builder(this.context).build(); imageLoader.init(configuration); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); notes = new ArrayList<>(); initImageLoader(); new QueryForSharesThread().start(); } @Override public void onAttach(Activity context) { super.onAttach(context); System.out.print(context);// Activity@890778 this.context = context; } @Override public void onDetach() { super.onDetach(); this.context = null; } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_share, container, false); initView(view); return view; } private void initView(View view) { coordinatorLayout = (CoordinatorLayout) view.findViewById(R.id.line_coordinatorLayout); recyclerView = (RecyclerView)view.findViewById(R.id.line_recycler); mLayoutManager = new LinearLayoutManager(context); recyclerView.setLayoutManager(mLayoutManager); swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.line_swipe_refresh); swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary,R.color.colorPrimaryDark,R.color.colorAccent); swipeRefreshLayout.setProgressViewOffset(false,0,(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,24,getResources().getDisplayMetrics())); setListener(); } private void setListener() { swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { frindCounter=0; postCounter=0; friendSize=0; postSize=0; //TODO 开启一个线程刷新数据 notes=new ArrayList<Post>(); Log.d("bmob", "onRefresh: "); MyUser me=MyUser.getCurrentUser(MyUser.class); BmobQuery<MyUser> userQuery=new BmobQuery<>(); userQuery.addWhereRelatedTo("friends",new BmobPointer(me)); userQuery.findObjects(new FindListener<MyUser>() { @Override public void done(List<MyUser> list, BmobException e) { friendSize=list.size(); Log.d(TAG, "done: friendSize"+list.size()); for (MyUser friend:list){ frindCounter++; BmobQuery<Post> isShareQuery=new BmobQuery<>(); isShareQuery.addWhereEqualTo("isShared",true); BmobQuery<Post> isFirendQuery=new BmobQuery<Post>(); isFirendQuery.addWhereEqualTo("author",friend); List<BmobQuery<Post>> queries=new ArrayList<BmobQuery<Post>>(); queries.add(isShareQuery); queries.add(isFirendQuery); BmobQuery<Post> mainQuery=new BmobQuery<Post>(); mainQuery.and(queries); mainQuery.order("-createdAt"); mainQuery.findObjects(new FindListener<Post>() { @Override public void done(List<Post> list, BmobException e) { if(e==null){ if (list.size()>0){ postSize=list.size(); Log.d(TAG, "done: postSize"+list.size()); for (Post post:list){ notes.add(post); postCounter++; if ((postCounter==postSize)&&(frindCounter==friendSize)){ handler.sendEmptyMessage(QUERY_SWIPE); } } } } } }); } } }); } }); // recyclerView.addItemDecoration(new DividerItemDecoration(context,DividerItemDecoration.VERTICAL)); NoteAdapter noteAdapter = new NoteAdapter(); recyclerView.setAdapter(noteAdapter); } class NoteAdapter extends RecyclerView.Adapter<NoteAdapter.NoteViewHolder> implements View.OnClickListener{ @Override public NoteAdapter.NoteViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.share_item_layout,parent,false); NoteViewHolder holder = new NoteViewHolder(view); view.setOnClickListener(this); return holder; } @Override public void onBindViewHolder(NoteViewHolder holder, int position) { holder.tv_label.setText(notes.get(position).getAuthorName()); Log.d("bmob", "onBindViewHolder: username"+notes.get(position).getAuthor().getUsername()); holder.tv_content.setText(notes.get(position).getContent()); holder.tv_time.setText(notes.get(position).getCreatedAt()); if (notes.get(position).getAuthorAvatar()!=null){ ImageLoaderUtil.displayImage(context,holder.mRivPhoto,notes.get(position).getAuthorAvatar(),ImageLoaderUtil.getPhotoImageOption()); } // holder.iv_content.setImageResource(); if(notes.get(position).getImages()!=null){ if (notes.get(position).getImages().size()>0){ Log.d("bmob", "onBindViewHolder: "+notes.get(position).getImages().size()); Log.d("bmob", "onBindViewHolder: "+notes.get(position).getImages().get(0)); Bitmap bitmap= BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()+ File.separator+notes.get(position).getFilenames().get(0)); if(bitmap!=null){ holder.iv_content.setImageBitmap(bitmap); Log.d("bmob", "onBindViewHolder: 本地加载"); }else { Log.d("bmob", "onBindViewHolder: 外部加载"); imageLoader.displayImage(notes.get(position).getImages().get(0),holder.iv_content); } } } } @Override public int getItemCount() { return notes.size(); } @Override public void onClick(View v) { int position = recyclerView.getChildAdapterPosition(v); Post note=notes.get(position); Intent intent = new Intent(getActivity(),DetailActivity.class); Bundle bundle = new Bundle(); bundle.putSerializable("note", note); bundle.putBoolean("user",false); intent.putExtras(bundle); //将数据传到DetailActivity startActivity(intent); } class NoteViewHolder extends RecyclerView.ViewHolder{ private TextView tv_label; private ImageView iv_content; private TextView tv_content; private TextView tv_time; private RoundImageView mRivPhoto; public NoteViewHolder(View view){ super(view); tv_label = (TextView) view.findViewById(R.id.note_label_text); tv_content = (TextView) view.findViewById(R.id.note_content_text); tv_time = (TextView) view.findViewById(R.id.note_last_edit_text); iv_content = (ImageView) view.findViewById(R.id.note_content_image); mRivPhoto = (RoundImageView)view.findViewById(R.id.riv_photo); } } public void addItem(Post note,int position){ notes.add(position,note); notifyItemInserted(position); recyclerView.scrollToPosition(position); } public void removeItem(final int position){ final Post removed = notes.get(position); notes.remove(position); notifyItemRemoved(position); SnackbarUtil.ShortSnackbar(coordinatorLayout,"你删除了第"+position+"个item",SnackbarUtil.Warning).setAction("撤销", new View.OnClickListener() { @Override public void onClick(View v) { addItem(removed,position); SnackbarUtil.ShortSnackbar(coordinatorLayout,"撤销了删除第"+position+"个item",SnackbarUtil.Confirm).show(); } }).setActionTextColor(Color.WHITE).show(); } } }
UTF-8
Java
15,069
java
ShareFragment.java
Java
[ { "context": "bmob.v3.listener.FindListener;\n\n\n/**\n * Created by wewarrios on 2017/3/14.\n */\n\npublic class ShareFragment ext", "end": 2119, "score": 0.9996530413627625, "start": 2110, "tag": "USERNAME", "value": "wewarrios" } ]
null
[]
package com.example.xdcao.diandiapp.UI.songwenqiang.Fragment; import android.app.Activity; import android.app.Fragment; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.support.annotation.Nullable; import android.support.design.widget.CoordinatorLayout; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.example.xdcao.diandiapp.BackUp.caohao.bean.MyUser; import com.example.xdcao.diandiapp.BackUp.caohao.bean.Post; import com.example.xdcao.diandiapp.BackUp.caohao.cons.HandlerCons; import com.example.xdcao.diandiapp.DdService.liubotao.ninegridlayout.util.ImageLoaderUtil; import com.example.xdcao.diandiapp.R; import com.example.xdcao.diandiapp.UI.songwenqiang.bean.ContactItem; import com.example.xdcao.diandiapp.UI.songwenqiang.bean.SNotes; import com.example.xdcao.diandiapp.UI.songwenqiang.ui.ContactShareActivity; import com.example.xdcao.diandiapp.UI.songwenqiang.ui.DetailActivity; import com.example.xdcao.diandiapp.UI.songwenqiang.ui.MainActivity; import com.example.xdcao.diandiapp.UI.songwenqiang.ui.widget.RoundImageView; import com.example.xdcao.diandiapp.UI.songwenqiang.utils.SnackbarUtil; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import java.io.File; import java.io.FileReader; import java.util.ArrayList; import java.util.List; import cn.bmob.v3.Bmob; import cn.bmob.v3.BmobQuery; import cn.bmob.v3.datatype.BmobPointer; import cn.bmob.v3.exception.BmobException; import cn.bmob.v3.listener.FindListener; /** * Created by wewarrios on 2017/3/14. */ public class ShareFragment extends Fragment{ private static final String TAG = "bmob"; private final static int QUERY_SWIPE = 23; private RecyclerView recyclerView; private CoordinatorLayout coordinatorLayout; private List<Post> notes; private LinearLayoutManager mLayoutManager; private SwipeRefreshLayout swipeRefreshLayout; private Context context; private int frindCounter=0; private int postCounter=0; private int friendSize=0; private int postSize=0; private ImageLoader imageLoader; private NoteAdapter noteAdapter; Handler handler=new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what){ case HandlerCons.QUERY_ALL_SHARE: Log.d("bmob", "handleMessage: "+"get handler mList.size: "+notes.size()); noteAdapter = new NoteAdapter(); recyclerView.setAdapter(noteAdapter); break; case QUERY_SWIPE: swipeRefreshLayout.setRefreshing(false); if (noteAdapter!=null){ noteAdapter.notifyDataSetChanged(); } } super.handleMessage(msg); } }; class QueryForSharesThread extends Thread{ @Override public void run() { queryforShare(); } } private void queryforShare() { MyUser me=MyUser.getCurrentUser(MyUser.class); BmobQuery<MyUser> userQuery=new BmobQuery<>(); userQuery.addWhereRelatedTo("friends",new BmobPointer(me)); userQuery.findObjects(new FindListener<MyUser>() { @Override public void done(List<MyUser> list, BmobException e) { friendSize=list.size(); for (MyUser friend:list){ frindCounter++; BmobQuery<Post> isShareQuery=new BmobQuery<>(); isShareQuery.addWhereEqualTo("isShared",true); BmobQuery<Post> isFirendQuery=new BmobQuery<Post>(); isFirendQuery.addWhereEqualTo("author",friend); List<BmobQuery<Post>> queries=new ArrayList<BmobQuery<Post>>(); queries.add(isShareQuery); queries.add(isFirendQuery); BmobQuery<Post> mainQuery=new BmobQuery<Post>(); mainQuery.and(queries); mainQuery.order("-createdAt"); mainQuery.findObjects(new FindListener<Post>() { @Override public void done(List<Post> list, BmobException e) { if(e==null){ if (list.size()>0){ postSize=list.size(); for (Post post:list){ notes.add(post); postCounter++; if ((postCounter==postSize)&&(frindCounter==friendSize)){ Message message=new Message(); message.what= HandlerCons.QUERY_ALL_SHARE; handler.sendMessage(message); } } } } } }); } } }); } public ShareFragment(){ } private void initImageLoader() { imageLoader= ImageLoader.getInstance(); ImageLoaderConfiguration configuration=new ImageLoaderConfiguration.Builder(this.context).build(); imageLoader.init(configuration); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); notes = new ArrayList<>(); initImageLoader(); new QueryForSharesThread().start(); } @Override public void onAttach(Activity context) { super.onAttach(context); System.out.print(context);// Activity@890778 this.context = context; } @Override public void onDetach() { super.onDetach(); this.context = null; } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_share, container, false); initView(view); return view; } private void initView(View view) { coordinatorLayout = (CoordinatorLayout) view.findViewById(R.id.line_coordinatorLayout); recyclerView = (RecyclerView)view.findViewById(R.id.line_recycler); mLayoutManager = new LinearLayoutManager(context); recyclerView.setLayoutManager(mLayoutManager); swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.line_swipe_refresh); swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary,R.color.colorPrimaryDark,R.color.colorAccent); swipeRefreshLayout.setProgressViewOffset(false,0,(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,24,getResources().getDisplayMetrics())); setListener(); } private void setListener() { swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { frindCounter=0; postCounter=0; friendSize=0; postSize=0; //TODO 开启一个线程刷新数据 notes=new ArrayList<Post>(); Log.d("bmob", "onRefresh: "); MyUser me=MyUser.getCurrentUser(MyUser.class); BmobQuery<MyUser> userQuery=new BmobQuery<>(); userQuery.addWhereRelatedTo("friends",new BmobPointer(me)); userQuery.findObjects(new FindListener<MyUser>() { @Override public void done(List<MyUser> list, BmobException e) { friendSize=list.size(); Log.d(TAG, "done: friendSize"+list.size()); for (MyUser friend:list){ frindCounter++; BmobQuery<Post> isShareQuery=new BmobQuery<>(); isShareQuery.addWhereEqualTo("isShared",true); BmobQuery<Post> isFirendQuery=new BmobQuery<Post>(); isFirendQuery.addWhereEqualTo("author",friend); List<BmobQuery<Post>> queries=new ArrayList<BmobQuery<Post>>(); queries.add(isShareQuery); queries.add(isFirendQuery); BmobQuery<Post> mainQuery=new BmobQuery<Post>(); mainQuery.and(queries); mainQuery.order("-createdAt"); mainQuery.findObjects(new FindListener<Post>() { @Override public void done(List<Post> list, BmobException e) { if(e==null){ if (list.size()>0){ postSize=list.size(); Log.d(TAG, "done: postSize"+list.size()); for (Post post:list){ notes.add(post); postCounter++; if ((postCounter==postSize)&&(frindCounter==friendSize)){ handler.sendEmptyMessage(QUERY_SWIPE); } } } } } }); } } }); } }); // recyclerView.addItemDecoration(new DividerItemDecoration(context,DividerItemDecoration.VERTICAL)); NoteAdapter noteAdapter = new NoteAdapter(); recyclerView.setAdapter(noteAdapter); } class NoteAdapter extends RecyclerView.Adapter<NoteAdapter.NoteViewHolder> implements View.OnClickListener{ @Override public NoteAdapter.NoteViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.share_item_layout,parent,false); NoteViewHolder holder = new NoteViewHolder(view); view.setOnClickListener(this); return holder; } @Override public void onBindViewHolder(NoteViewHolder holder, int position) { holder.tv_label.setText(notes.get(position).getAuthorName()); Log.d("bmob", "onBindViewHolder: username"+notes.get(position).getAuthor().getUsername()); holder.tv_content.setText(notes.get(position).getContent()); holder.tv_time.setText(notes.get(position).getCreatedAt()); if (notes.get(position).getAuthorAvatar()!=null){ ImageLoaderUtil.displayImage(context,holder.mRivPhoto,notes.get(position).getAuthorAvatar(),ImageLoaderUtil.getPhotoImageOption()); } // holder.iv_content.setImageResource(); if(notes.get(position).getImages()!=null){ if (notes.get(position).getImages().size()>0){ Log.d("bmob", "onBindViewHolder: "+notes.get(position).getImages().size()); Log.d("bmob", "onBindViewHolder: "+notes.get(position).getImages().get(0)); Bitmap bitmap= BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()+ File.separator+notes.get(position).getFilenames().get(0)); if(bitmap!=null){ holder.iv_content.setImageBitmap(bitmap); Log.d("bmob", "onBindViewHolder: 本地加载"); }else { Log.d("bmob", "onBindViewHolder: 外部加载"); imageLoader.displayImage(notes.get(position).getImages().get(0),holder.iv_content); } } } } @Override public int getItemCount() { return notes.size(); } @Override public void onClick(View v) { int position = recyclerView.getChildAdapterPosition(v); Post note=notes.get(position); Intent intent = new Intent(getActivity(),DetailActivity.class); Bundle bundle = new Bundle(); bundle.putSerializable("note", note); bundle.putBoolean("user",false); intent.putExtras(bundle); //将数据传到DetailActivity startActivity(intent); } class NoteViewHolder extends RecyclerView.ViewHolder{ private TextView tv_label; private ImageView iv_content; private TextView tv_content; private TextView tv_time; private RoundImageView mRivPhoto; public NoteViewHolder(View view){ super(view); tv_label = (TextView) view.findViewById(R.id.note_label_text); tv_content = (TextView) view.findViewById(R.id.note_content_text); tv_time = (TextView) view.findViewById(R.id.note_last_edit_text); iv_content = (ImageView) view.findViewById(R.id.note_content_image); mRivPhoto = (RoundImageView)view.findViewById(R.id.riv_photo); } } public void addItem(Post note,int position){ notes.add(position,note); notifyItemInserted(position); recyclerView.scrollToPosition(position); } public void removeItem(final int position){ final Post removed = notes.get(position); notes.remove(position); notifyItemRemoved(position); SnackbarUtil.ShortSnackbar(coordinatorLayout,"你删除了第"+position+"个item",SnackbarUtil.Warning).setAction("撤销", new View.OnClickListener() { @Override public void onClick(View v) { addItem(removed,position); SnackbarUtil.ShortSnackbar(coordinatorLayout,"撤销了删除第"+position+"个item",SnackbarUtil.Confirm).show(); } }).setActionTextColor(Color.WHITE).show(); } } }
15,069
0.574401
0.571467
367
39.852859
30.437412
161
false
false
0
0
0
0
0
0
0.66485
false
false
11
a81c2a5e9292da6a8ed2cc31275fe25de13201b9
20,804,821,584,886
aaa9649c3e52b2bd8e472a526785f09e55a33840
/EquationCommon/src/com/misys/equation/common/access/EquationStandardSQLPagingList.java
cd0141ba40c6459c3d18d7ce1372c646432e2161
[]
no_license
jcmartin2889/Repo
https://github.com/jcmartin2889/Repo
dbfd02f000e65c96056d4e6bcc540e536516d775
259c51703a2a50061ad3c99b8849477130cde2f4
refs/heads/master
2021-01-10T19:34:17.555000
2014-04-29T06:01:01
2014-04-29T06:01:01
19,265,367
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.misys.equation.common.access; import java.math.BigDecimal; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Types; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import com.misys.equation.common.internal.eapi.core.EQException; import com.misys.equation.common.utilities.EqBeanFactory; import com.misys.equation.common.utilities.EquationLogger; import com.misys.equation.common.utilities.SQLToolbox; import com.misys.equation.common.utilities.Toolbox; /** * This class provides methods for processing SQL select statements over tables with a primary unique key where paging * forward/backward is required. The keys of the first and last row positions are stored. This class can be serialised as XML and * sent in the response and subsequent request so that resuming the query at a specific location in the table is possible. The * requested maximum results will be given unless end of file is reached. * * After the first execution the properties other than callback must not be changed using the set methods. * * If a prompt validate module is called it is assumed a calculated column named DTA will be used. If the prompt validate returns a * error KSM in "DTA" then the row will be ignored. */ public class EquationStandardSQLPagingList { // This attribute is used to store cvs version information. public static final String _revision = "$Id: EquationStandardSQLPagingList.java 17302 2013-09-19 10:46:17Z williae1 $"; private static final EquationLogger LOG = new EquationLogger(EquationStandardSQLPagingList.class); private LinkedHashMap<String, String> keyFieldValues = new LinkedHashMap<String, String>(); private String sqlSelectStart = null; private String sqlSelectFilter = null; // this determines the total number of records required private int numberOfRows = 0; IEquationSQLPagingListCallback callback; private int currentPage = 0; private int totalPages = 0; private int totalNumberOfRecordsCollected = 0; private boolean moreRows = false; private HashMap<String, String> firstRow = new HashMap<String, String>(); private HashMap<String, String> lastRow = new HashMap<String, String>(); // this determines the first or last record read for this result set depending on direction private HashMap<String, String> positionRow; boolean initialisedKeyFields = false; /** * Constructor for deserialisation */ public EquationStandardSQLPagingList() { } /** * Construct a list with SQL select statement that pages * * @param keyFieldValues * - database column names/values to provide information about the primary key and to determine where the selection * starts. This collection can be set to null here and added to before calling the execute query method. There must * be unique keys setup before calling the execute query method. * @param sqlSelectStart * - select statement with columns and file e.q."SELECT SCAB, SCAN, SCAS, SCAB || SCAN || SCAS AS DTAKEY, UTW06RFNC('V','GWR76R', SCAB || SCAN || SCAS,'N','N','G','') AS DTA FROM SC10LF" * . If a prompt validate module is called it is assumed a calculated column named DTA will be used. If the prompt * validate returns a error KSM then the row will be ignored. * @param sqlSelectFilter * - portion of where clause with filtering e.g. "SCAB EQ '0132' AND 'SCAN LIKE '1%'" * @param numberOfRows * - number of rows to return, the number returned could be less if end of file is reached * @param callback * - class to call if rows will be rejected/altered. The setCallback method will need to be used if this instance is * serialised / deserialised. */ public EquationStandardSQLPagingList(LinkedHashMap<String, String> keyFieldValues, String sqlSelectStart, String sqlSelectFilter, int numberOfRows, IEquationSQLPagingListCallback callback) { // Set the starting position... if ((keyFieldValues == null) || (keyFieldValues.equals(""))) { keyFieldValues = new LinkedHashMap<String, String>(); } this.keyFieldValues = keyFieldValues; this.sqlSelectStart = sqlSelectStart; this.sqlSelectFilter = sqlSelectFilter; this.numberOfRows = numberOfRows; this.callback = callback; currentPage = 0; } /** * Execute the query * * @param session * - the session * @param requestedPage * - page number * @throws Exception * */ public ArrayList<HashMap<String, String>> executeQuery(EquationStandardSession session, int requestedPage) throws Exception { ArrayList<HashMap<String, String>> resultData = new ArrayList<HashMap<String, String>>(); // adjust key fields so that if full key is supplied we start 1 row earlier if (initialisedKeyFields == false) { adjustKeyFields(session); initialisedKeyFields = true; } // request for more pages but there are no more records if (requestedPage > currentPage && currentPage != 0 && moreRows == false) { // no result data return resultData; } // determine the direction and start position for the query String direction = determineDirection(requestedPage); // Get the right page boolean eof = false; int calculatedCurrentPage = currentPage; if (direction.equals(">")) { while (calculatedCurrentPage < requestedPage && eof == false) { int numberOfRowsThisStatement = numberOfRows + 1; eof = executeQueryToFullnumberOfRows(session, direction, numberOfRowsThisStatement, resultData); calculatedCurrentPage++; } if (totalNumberOfRecordsCollected >= numberOfRows) { moreRows = true; } else { moreRows = false; } } else { while (calculatedCurrentPage > requestedPage) { executeQueryToFullnumberOfRows(session, direction, numberOfRows, resultData); calculatedCurrentPage--; } // Going backwards there are always more records because you can go forward again. // Being on page one does not mean there are no more records. moreRows = true; } if (calculatedCurrentPage > totalPages) { totalPages = calculatedCurrentPage; } if (calculatedCurrentPage == requestedPage) { if (resultData.size() != 0) { currentPage = requestedPage; } } else { // No data was found for the right page currentPage = 0; resultData.clear(); } if (resultData.size() > 0) { firstRow = resultData.get(0); lastRow = resultData.get(resultData.size() - 1); } else { firstRow = null; lastRow = null; } // cleanup positionRow = null; return resultData; } private String determineDirection(int requestedPage) throws Exception { String direction = null; if (requestedPage == 0) { throw new RuntimeException("Page number must not be zero."); } // forward request - start from where we left off if (requestedPage > currentPage) { direction = ">"; if (currentPage == 0 || lastRow == null) { positionRow = keyFieldValues; } else { positionRow = lastRow; } } else // backward request - start from where we left off if (requestedPage < currentPage && firstRow != null) { direction = "<"; positionRow = firstRow; } else { // Same page - have to start from scratch as we don't keep the result set direction = ">"; positionRow = keyFieldValues; currentPage = 0; } return direction; } private boolean executeQueryToFullnumberOfRows(EquationStandardSession session, String direction, int numberOfRowsThisStatement, ArrayList<HashMap<String, String>> resultData) { boolean eof = false; totalNumberOfRecordsCollected = 0; resultData.clear(); while (totalNumberOfRecordsCollected < numberOfRows) { // Generate the SQL String sqlSelect = generateSQL(direction, numberOfRowsThisStatement); // Perform the query eof = executeQueryForOneResultSet(session, sqlSelect, direction, resultData); // Total number of records read less than the required, then it means no more data if (eof) { break; } } return eof; } private boolean executeQueryForOneResultSet(EquationStandardSession session, String sqlSelect, String direction, ArrayList<HashMap<String, String>> resultData) { ResultSet equationResultSet = null; PreparedStatement equationStatement = null; boolean eof = false; try { Connection equationConnection = session.getConnection(); // Build the result set equationStatement = equationConnection.prepareStatement(sqlSelect, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); if (direction.equals(">")) { equationStatement.setMaxRows(numberOfRows + 1); equationStatement.setFetchSize(numberOfRows + 1); } else { equationStatement.setMaxRows(numberOfRows); equationStatement.setFetchSize(numberOfRows); } // record time // System.out.println(sqlSelect); long startTime = System.nanoTime(); equationResultSet = equationStatement.executeQuery(); if (LOG.isDebugEnabled()) { // record time long endTime = System.nanoTime(); // log the time taken to make the SQL call LOG.debug("EquationStandardSQLPagingList: " + sqlSelect + " (Duration: " + ((endTime - startTime) / 1000000) + "ms)"); } ResultSetMetaData rsMeta = equationResultSet.getMetaData(); positionRow = null; int resultSetRowsReturned = 0; for (int j = 1; equationResultSet.next() && j <= numberOfRows; j++) { resultSetRowsReturned++; if (totalNumberOfRecordsCollected < numberOfRows) { processRow(rsMeta, equationResultSet, direction, resultData); } } if (resultSetRowsReturned < numberOfRows) { eof = true; } // Return true if it only read less than the required return eof; } catch (SQLException sqle) { LOG.error("SQL Statement: " + sqlSelect); LOG.error("Replace this", sqle); throw new RuntimeException("EquationStandardSQLPagingList: " + Toolbox.getExceptionMessage(sqle), sqle); } finally { SQLToolbox.close(equationResultSet); SQLToolbox.close(equationStatement); } } private void processRow(ResultSetMetaData rsMeta, ResultSet equationResultSet, String direction, ArrayList<HashMap<String, String>> resultData) throws SQLException { boolean callbackIncludeInResult = true; String errorText = ""; HashMap<String, String> rowData = new HashMap<String, String>(); for (int i = 0; i < rsMeta.getColumnCount(); i++) { String dbColumnId = rsMeta.getColumnName(i + 1); int type = rsMeta.getColumnType(i + 1); String result = null; if (type == Types.CHAR) { result = equationResultSet.getString(dbColumnId); } else if (type == Types.DECIMAL || type == Types.FLOAT || type == Types.DOUBLE || type == Types.REAL) { BigDecimal bd = equationResultSet.getBigDecimal(dbColumnId); if (bd != null) result = bd.toPlainString(); else result = String.valueOf(0); } else if (type == Types.TINYINT || type == Types.BIGINT || type == Types.NUMERIC || type == Types.INTEGER || type == Types.SMALLINT) { result = String.valueOf(equationResultSet.getLong(dbColumnId)); } else { result = equationResultSet.getString(dbColumnId); } rowData.put(dbColumnId, result); if (dbColumnId.equals("DTA")) { errorText = result.substring(0, 7).trim(); } } positionRow = rowData; if (callback != null) { callbackIncludeInResult = callback.validateRow(rowData); } if (errorText.equals("") && callbackIncludeInResult == true) { if (direction.equals(">")) { resultData.add(rowData); } else { // build the list in the collection backwards resultData.add(0, rowData); } // accumulate total records read totalNumberOfRecordsCollected++; } } /** * Generate the SQL statement * * @param direction * - (<) page down (>) page up */ private String generateSQL(String direction, int numberOfRowsThisStatement) { boolean hasDbKey = hasDbKey(); // SQL statement buffer StringBuffer sqlSelect = new StringBuffer(sqlSelectStart); boolean firstWhere = true; if (sqlSelectFilter != null && sqlSelectFilter.length() > 0) { sqlSelect.append(" WHERE "); sqlSelect.append(sqlSelectFilter); firstWhere = false; } if (firstWhere) { sqlSelect.append(" WHERE "); firstWhere = false; } else { if (hasDbKey) { sqlSelect.append(" AND "); } } if (hasDbKey) { sqlSelect.append(getWhereClauseForDbKey(direction) + " "); } // Append the ordering sqlSelect.append(" ORDER BY " + getOrderBy(direction)); // fetch only this rows sqlSelect.append(" FETCH FIRST " + (numberOfRowsThisStatement) + " ROWS ONLY"); // read uncommitted records sqlSelect.append(" WITH UR"); // Return the statement return sqlSelect.toString(); } /** * Return the where clause * * @param direction * - (<) page down (>) page up * * @return the where clause */ private String getWhereClauseForDbKey(String direction) { StringBuffer whereClause = new StringBuffer(" ("); StringBuffer whereClauseCurrent = null; StringBuffer whereClauseLast = null; String keyField = null; String fieldValue = null; int i = 0; Iterator<String> iterator = keyFieldValues.keySet().iterator(); while (iterator.hasNext()) { keyField = iterator.next(); fieldValue = positionRow.get(keyField); if (fieldValue != null) { if (i == 0) { whereClauseCurrent = new StringBuffer(keyField + direction + "'" + fieldValue + "' "); } else { whereClauseCurrent = new StringBuffer(" (" + whereClauseLast + " AND " + keyField + direction + "'" + fieldValue + "'" + ") "); } if (i == 0) { whereClauseLast = new StringBuffer(keyField + "=" + "'" + fieldValue + "'"); } else { whereClauseLast = whereClauseLast.append(" AND " + keyField + "=" + "'" + fieldValue + "'"); } if (i < keyFieldValues.keySet().size() - 1 && keyFieldValues.keySet().size() > 1) { whereClause = whereClause.append(whereClauseCurrent + "OR"); } else { whereClause = whereClause.append(whereClauseCurrent); } } i++; } whereClause = whereClause.append(")"); return whereClause.toString(); } /** * Return whether any key field values have been supplied * * @return whether any key field values have been supplied */ private boolean hasDbKey() { String keyField = null; String fieldValue = null; Iterator<String> iterator = keyFieldValues.keySet().iterator(); while (iterator.hasNext()) { keyField = iterator.next(); fieldValue = positionRow.get(keyField); if (fieldValue != null) { return true; } } return false; } private void adjustKeyFields(EquationStandardSession session) { // Adjust the supplied key fields to go back 1 record. If we don't do this and the supplied full start key exist the first // record will be skipped on the first page. // record. positionRow = keyFieldValues; if (hasDbKey()) { String direction = "<"; ArrayList<HashMap<String, String>> resultData = new ArrayList<HashMap<String, String>>(); // save of real numberOfRows as we want to go back 1 record to be able to position correctly String keyField = null; String fieldValue = null; boolean eof = executeQueryToFullnumberOfRows(session, direction, 1, resultData); if (!eof && resultData.size() > 0) { Iterator<String> iterator = keyFieldValues.keySet().iterator(); while (iterator.hasNext()) { keyField = iterator.next(); fieldValue = positionRow.get(keyField); keyFieldValues.put(keyField, fieldValue); } } } } /** * Return the order by clause * * @param direction * - (<) page down (>) page up * * @return the order by clause */ private String getOrderBy(String direction) { StringBuffer orderBy = new StringBuffer(); String delimiterOrderBy = ", "; String ascend = " ASC"; String decend = " DESC"; String keyField = null; Iterator<String> iterator = keyFieldValues.keySet().iterator(); while (iterator.hasNext()) { keyField = iterator.next(); // add the delimiter to concatenate all the key fields if (orderBy.length() != 0) { orderBy.append(delimiterOrderBy); } orderBy.append(keyField); if (direction.equals("<")) { orderBy.append(decend); } else { orderBy.append(ascend); } } return orderBy.toString(); } /** * Add field to key fields value collection with padding * * @param columnName * - the primary key column name * @param value * - the primary key column value. If null is supplied the value will be padded to the field length supplied. * @param fieldLength * - the field length * @param isString * - does the column contain Strings */ public void addPrimaryKeyFieldValues(String columnName, String value, int fieldLength, boolean isString) { if (keyFieldValues == null) { keyFieldValues = new LinkedHashMap<String, String>(); } if (value == null) { value = ""; } if (value.trim().equals("")) { if (isString) { value = Toolbox.pad(value, fieldLength); } else { value = Toolbox.padAtFront(value, "0", fieldLength); } } keyFieldValues.put(columnName, value); } /** * Return this instance as an XML String * * @return this instance as an XML String * @throws EQException */ public String serialiseAsXML() throws EQException { EqBeanFactory eqBeanFactory = EqBeanFactory.getEqBeanFactory(); String xml = eqBeanFactory.serialiseBeanAsXML(this); return xml; } /** * return EquationStandardSQLPagingList instance from XML String * * @param xml * @return EquationStandardSQLPagingList instance from XML String * @throws EQException */ public static EquationStandardSQLPagingList deserialiseFromXML(String xml) throws EQException { EquationStandardSQLPagingList pagingList = null; EqBeanFactory beanFactory = EqBeanFactory.getEqBeanFactory(); pagingList = (EquationStandardSQLPagingList) beanFactory.deserialiseXMLAsBean(xml, EquationStandardSQLPagingList.class); return pagingList; } public void addKeyFieldValues(String key, String value) { keyFieldValues.put(key, value); } public void addFirstRow(String key, String value) { firstRow.put(key, value); } public void addLastRow(String key, String value) { lastRow.put(key, value); } public LinkedHashMap<String, String> getKeyFieldValues() { return keyFieldValues; } public void setKeyFieldValues(LinkedHashMap<String, String> keyFieldValues) { this.keyFieldValues = keyFieldValues; } public String getSqlSelectStart() { return sqlSelectStart; } public void setSqlSelectStart(String sqlSelectStart) { this.sqlSelectStart = sqlSelectStart; } public String getSqlSelectFilter() { return sqlSelectFilter; } public void setSqlSelectFilter(String sqlSelectFilter) { this.sqlSelectFilter = sqlSelectFilter; } public int getNumberOfRows() { return numberOfRows; } public void setNumberOfRows(int numberOfRows) { this.numberOfRows = numberOfRows; } public IEquationSQLPagingListCallback getCallback() { return callback; } public void setCallback(IEquationSQLPagingListCallback callback) { this.callback = callback; } public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } public int getTotalPages() { return totalPages; } public void setTotalPages(int totalPages) { this.totalPages = totalPages; } public int getTotalNumberOfRecordsCollected() { return totalNumberOfRecordsCollected; } public void setTotalNumberOfRecordsCollected(int totalNumberOfRecordsCollected) { this.totalNumberOfRecordsCollected = totalNumberOfRecordsCollected; } public boolean isMoreRows() { return moreRows; } public void setMoreRows(boolean moreRows) { this.moreRows = moreRows; } public HashMap<String, String> getFirstRow() { return firstRow; } public void setFirstRow(HashMap<String, String> firstRow) { this.firstRow = firstRow; } public HashMap<String, String> getLastRow() { return lastRow; } public void setLastRow(HashMap<String, String> lastRow) { this.lastRow = lastRow; } public boolean isInitialisedKeyFields() { return initialisedKeyFields; } public void setInitialisedKeyFields(boolean initialisedKeyFields) { this.initialisedKeyFields = initialisedKeyFields; } }
UTF-8
Java
20,873
java
EquationStandardSQLPagingList.java
Java
[ { "context": "ndardSQLPagingList.java 17302 2013-09-19 10:46:17Z williae1 $\";\n\n\tprivate static final EquationLogger LOG = n", "end": 1633, "score": 0.9768657684326172, "start": 1625, "tag": "USERNAME", "value": "williae1" } ]
null
[]
package com.misys.equation.common.access; import java.math.BigDecimal; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Types; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import com.misys.equation.common.internal.eapi.core.EQException; import com.misys.equation.common.utilities.EqBeanFactory; import com.misys.equation.common.utilities.EquationLogger; import com.misys.equation.common.utilities.SQLToolbox; import com.misys.equation.common.utilities.Toolbox; /** * This class provides methods for processing SQL select statements over tables with a primary unique key where paging * forward/backward is required. The keys of the first and last row positions are stored. This class can be serialised as XML and * sent in the response and subsequent request so that resuming the query at a specific location in the table is possible. The * requested maximum results will be given unless end of file is reached. * * After the first execution the properties other than callback must not be changed using the set methods. * * If a prompt validate module is called it is assumed a calculated column named DTA will be used. If the prompt validate returns a * error KSM in "DTA" then the row will be ignored. */ public class EquationStandardSQLPagingList { // This attribute is used to store cvs version information. public static final String _revision = "$Id: EquationStandardSQLPagingList.java 17302 2013-09-19 10:46:17Z williae1 $"; private static final EquationLogger LOG = new EquationLogger(EquationStandardSQLPagingList.class); private LinkedHashMap<String, String> keyFieldValues = new LinkedHashMap<String, String>(); private String sqlSelectStart = null; private String sqlSelectFilter = null; // this determines the total number of records required private int numberOfRows = 0; IEquationSQLPagingListCallback callback; private int currentPage = 0; private int totalPages = 0; private int totalNumberOfRecordsCollected = 0; private boolean moreRows = false; private HashMap<String, String> firstRow = new HashMap<String, String>(); private HashMap<String, String> lastRow = new HashMap<String, String>(); // this determines the first or last record read for this result set depending on direction private HashMap<String, String> positionRow; boolean initialisedKeyFields = false; /** * Constructor for deserialisation */ public EquationStandardSQLPagingList() { } /** * Construct a list with SQL select statement that pages * * @param keyFieldValues * - database column names/values to provide information about the primary key and to determine where the selection * starts. This collection can be set to null here and added to before calling the execute query method. There must * be unique keys setup before calling the execute query method. * @param sqlSelectStart * - select statement with columns and file e.q."SELECT SCAB, SCAN, SCAS, SCAB || SCAN || SCAS AS DTAKEY, UTW06RFNC('V','GWR76R', SCAB || SCAN || SCAS,'N','N','G','') AS DTA FROM SC10LF" * . If a prompt validate module is called it is assumed a calculated column named DTA will be used. If the prompt * validate returns a error KSM then the row will be ignored. * @param sqlSelectFilter * - portion of where clause with filtering e.g. "SCAB EQ '0132' AND 'SCAN LIKE '1%'" * @param numberOfRows * - number of rows to return, the number returned could be less if end of file is reached * @param callback * - class to call if rows will be rejected/altered. The setCallback method will need to be used if this instance is * serialised / deserialised. */ public EquationStandardSQLPagingList(LinkedHashMap<String, String> keyFieldValues, String sqlSelectStart, String sqlSelectFilter, int numberOfRows, IEquationSQLPagingListCallback callback) { // Set the starting position... if ((keyFieldValues == null) || (keyFieldValues.equals(""))) { keyFieldValues = new LinkedHashMap<String, String>(); } this.keyFieldValues = keyFieldValues; this.sqlSelectStart = sqlSelectStart; this.sqlSelectFilter = sqlSelectFilter; this.numberOfRows = numberOfRows; this.callback = callback; currentPage = 0; } /** * Execute the query * * @param session * - the session * @param requestedPage * - page number * @throws Exception * */ public ArrayList<HashMap<String, String>> executeQuery(EquationStandardSession session, int requestedPage) throws Exception { ArrayList<HashMap<String, String>> resultData = new ArrayList<HashMap<String, String>>(); // adjust key fields so that if full key is supplied we start 1 row earlier if (initialisedKeyFields == false) { adjustKeyFields(session); initialisedKeyFields = true; } // request for more pages but there are no more records if (requestedPage > currentPage && currentPage != 0 && moreRows == false) { // no result data return resultData; } // determine the direction and start position for the query String direction = determineDirection(requestedPage); // Get the right page boolean eof = false; int calculatedCurrentPage = currentPage; if (direction.equals(">")) { while (calculatedCurrentPage < requestedPage && eof == false) { int numberOfRowsThisStatement = numberOfRows + 1; eof = executeQueryToFullnumberOfRows(session, direction, numberOfRowsThisStatement, resultData); calculatedCurrentPage++; } if (totalNumberOfRecordsCollected >= numberOfRows) { moreRows = true; } else { moreRows = false; } } else { while (calculatedCurrentPage > requestedPage) { executeQueryToFullnumberOfRows(session, direction, numberOfRows, resultData); calculatedCurrentPage--; } // Going backwards there are always more records because you can go forward again. // Being on page one does not mean there are no more records. moreRows = true; } if (calculatedCurrentPage > totalPages) { totalPages = calculatedCurrentPage; } if (calculatedCurrentPage == requestedPage) { if (resultData.size() != 0) { currentPage = requestedPage; } } else { // No data was found for the right page currentPage = 0; resultData.clear(); } if (resultData.size() > 0) { firstRow = resultData.get(0); lastRow = resultData.get(resultData.size() - 1); } else { firstRow = null; lastRow = null; } // cleanup positionRow = null; return resultData; } private String determineDirection(int requestedPage) throws Exception { String direction = null; if (requestedPage == 0) { throw new RuntimeException("Page number must not be zero."); } // forward request - start from where we left off if (requestedPage > currentPage) { direction = ">"; if (currentPage == 0 || lastRow == null) { positionRow = keyFieldValues; } else { positionRow = lastRow; } } else // backward request - start from where we left off if (requestedPage < currentPage && firstRow != null) { direction = "<"; positionRow = firstRow; } else { // Same page - have to start from scratch as we don't keep the result set direction = ">"; positionRow = keyFieldValues; currentPage = 0; } return direction; } private boolean executeQueryToFullnumberOfRows(EquationStandardSession session, String direction, int numberOfRowsThisStatement, ArrayList<HashMap<String, String>> resultData) { boolean eof = false; totalNumberOfRecordsCollected = 0; resultData.clear(); while (totalNumberOfRecordsCollected < numberOfRows) { // Generate the SQL String sqlSelect = generateSQL(direction, numberOfRowsThisStatement); // Perform the query eof = executeQueryForOneResultSet(session, sqlSelect, direction, resultData); // Total number of records read less than the required, then it means no more data if (eof) { break; } } return eof; } private boolean executeQueryForOneResultSet(EquationStandardSession session, String sqlSelect, String direction, ArrayList<HashMap<String, String>> resultData) { ResultSet equationResultSet = null; PreparedStatement equationStatement = null; boolean eof = false; try { Connection equationConnection = session.getConnection(); // Build the result set equationStatement = equationConnection.prepareStatement(sqlSelect, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); if (direction.equals(">")) { equationStatement.setMaxRows(numberOfRows + 1); equationStatement.setFetchSize(numberOfRows + 1); } else { equationStatement.setMaxRows(numberOfRows); equationStatement.setFetchSize(numberOfRows); } // record time // System.out.println(sqlSelect); long startTime = System.nanoTime(); equationResultSet = equationStatement.executeQuery(); if (LOG.isDebugEnabled()) { // record time long endTime = System.nanoTime(); // log the time taken to make the SQL call LOG.debug("EquationStandardSQLPagingList: " + sqlSelect + " (Duration: " + ((endTime - startTime) / 1000000) + "ms)"); } ResultSetMetaData rsMeta = equationResultSet.getMetaData(); positionRow = null; int resultSetRowsReturned = 0; for (int j = 1; equationResultSet.next() && j <= numberOfRows; j++) { resultSetRowsReturned++; if (totalNumberOfRecordsCollected < numberOfRows) { processRow(rsMeta, equationResultSet, direction, resultData); } } if (resultSetRowsReturned < numberOfRows) { eof = true; } // Return true if it only read less than the required return eof; } catch (SQLException sqle) { LOG.error("SQL Statement: " + sqlSelect); LOG.error("Replace this", sqle); throw new RuntimeException("EquationStandardSQLPagingList: " + Toolbox.getExceptionMessage(sqle), sqle); } finally { SQLToolbox.close(equationResultSet); SQLToolbox.close(equationStatement); } } private void processRow(ResultSetMetaData rsMeta, ResultSet equationResultSet, String direction, ArrayList<HashMap<String, String>> resultData) throws SQLException { boolean callbackIncludeInResult = true; String errorText = ""; HashMap<String, String> rowData = new HashMap<String, String>(); for (int i = 0; i < rsMeta.getColumnCount(); i++) { String dbColumnId = rsMeta.getColumnName(i + 1); int type = rsMeta.getColumnType(i + 1); String result = null; if (type == Types.CHAR) { result = equationResultSet.getString(dbColumnId); } else if (type == Types.DECIMAL || type == Types.FLOAT || type == Types.DOUBLE || type == Types.REAL) { BigDecimal bd = equationResultSet.getBigDecimal(dbColumnId); if (bd != null) result = bd.toPlainString(); else result = String.valueOf(0); } else if (type == Types.TINYINT || type == Types.BIGINT || type == Types.NUMERIC || type == Types.INTEGER || type == Types.SMALLINT) { result = String.valueOf(equationResultSet.getLong(dbColumnId)); } else { result = equationResultSet.getString(dbColumnId); } rowData.put(dbColumnId, result); if (dbColumnId.equals("DTA")) { errorText = result.substring(0, 7).trim(); } } positionRow = rowData; if (callback != null) { callbackIncludeInResult = callback.validateRow(rowData); } if (errorText.equals("") && callbackIncludeInResult == true) { if (direction.equals(">")) { resultData.add(rowData); } else { // build the list in the collection backwards resultData.add(0, rowData); } // accumulate total records read totalNumberOfRecordsCollected++; } } /** * Generate the SQL statement * * @param direction * - (<) page down (>) page up */ private String generateSQL(String direction, int numberOfRowsThisStatement) { boolean hasDbKey = hasDbKey(); // SQL statement buffer StringBuffer sqlSelect = new StringBuffer(sqlSelectStart); boolean firstWhere = true; if (sqlSelectFilter != null && sqlSelectFilter.length() > 0) { sqlSelect.append(" WHERE "); sqlSelect.append(sqlSelectFilter); firstWhere = false; } if (firstWhere) { sqlSelect.append(" WHERE "); firstWhere = false; } else { if (hasDbKey) { sqlSelect.append(" AND "); } } if (hasDbKey) { sqlSelect.append(getWhereClauseForDbKey(direction) + " "); } // Append the ordering sqlSelect.append(" ORDER BY " + getOrderBy(direction)); // fetch only this rows sqlSelect.append(" FETCH FIRST " + (numberOfRowsThisStatement) + " ROWS ONLY"); // read uncommitted records sqlSelect.append(" WITH UR"); // Return the statement return sqlSelect.toString(); } /** * Return the where clause * * @param direction * - (<) page down (>) page up * * @return the where clause */ private String getWhereClauseForDbKey(String direction) { StringBuffer whereClause = new StringBuffer(" ("); StringBuffer whereClauseCurrent = null; StringBuffer whereClauseLast = null; String keyField = null; String fieldValue = null; int i = 0; Iterator<String> iterator = keyFieldValues.keySet().iterator(); while (iterator.hasNext()) { keyField = iterator.next(); fieldValue = positionRow.get(keyField); if (fieldValue != null) { if (i == 0) { whereClauseCurrent = new StringBuffer(keyField + direction + "'" + fieldValue + "' "); } else { whereClauseCurrent = new StringBuffer(" (" + whereClauseLast + " AND " + keyField + direction + "'" + fieldValue + "'" + ") "); } if (i == 0) { whereClauseLast = new StringBuffer(keyField + "=" + "'" + fieldValue + "'"); } else { whereClauseLast = whereClauseLast.append(" AND " + keyField + "=" + "'" + fieldValue + "'"); } if (i < keyFieldValues.keySet().size() - 1 && keyFieldValues.keySet().size() > 1) { whereClause = whereClause.append(whereClauseCurrent + "OR"); } else { whereClause = whereClause.append(whereClauseCurrent); } } i++; } whereClause = whereClause.append(")"); return whereClause.toString(); } /** * Return whether any key field values have been supplied * * @return whether any key field values have been supplied */ private boolean hasDbKey() { String keyField = null; String fieldValue = null; Iterator<String> iterator = keyFieldValues.keySet().iterator(); while (iterator.hasNext()) { keyField = iterator.next(); fieldValue = positionRow.get(keyField); if (fieldValue != null) { return true; } } return false; } private void adjustKeyFields(EquationStandardSession session) { // Adjust the supplied key fields to go back 1 record. If we don't do this and the supplied full start key exist the first // record will be skipped on the first page. // record. positionRow = keyFieldValues; if (hasDbKey()) { String direction = "<"; ArrayList<HashMap<String, String>> resultData = new ArrayList<HashMap<String, String>>(); // save of real numberOfRows as we want to go back 1 record to be able to position correctly String keyField = null; String fieldValue = null; boolean eof = executeQueryToFullnumberOfRows(session, direction, 1, resultData); if (!eof && resultData.size() > 0) { Iterator<String> iterator = keyFieldValues.keySet().iterator(); while (iterator.hasNext()) { keyField = iterator.next(); fieldValue = positionRow.get(keyField); keyFieldValues.put(keyField, fieldValue); } } } } /** * Return the order by clause * * @param direction * - (<) page down (>) page up * * @return the order by clause */ private String getOrderBy(String direction) { StringBuffer orderBy = new StringBuffer(); String delimiterOrderBy = ", "; String ascend = " ASC"; String decend = " DESC"; String keyField = null; Iterator<String> iterator = keyFieldValues.keySet().iterator(); while (iterator.hasNext()) { keyField = iterator.next(); // add the delimiter to concatenate all the key fields if (orderBy.length() != 0) { orderBy.append(delimiterOrderBy); } orderBy.append(keyField); if (direction.equals("<")) { orderBy.append(decend); } else { orderBy.append(ascend); } } return orderBy.toString(); } /** * Add field to key fields value collection with padding * * @param columnName * - the primary key column name * @param value * - the primary key column value. If null is supplied the value will be padded to the field length supplied. * @param fieldLength * - the field length * @param isString * - does the column contain Strings */ public void addPrimaryKeyFieldValues(String columnName, String value, int fieldLength, boolean isString) { if (keyFieldValues == null) { keyFieldValues = new LinkedHashMap<String, String>(); } if (value == null) { value = ""; } if (value.trim().equals("")) { if (isString) { value = Toolbox.pad(value, fieldLength); } else { value = Toolbox.padAtFront(value, "0", fieldLength); } } keyFieldValues.put(columnName, value); } /** * Return this instance as an XML String * * @return this instance as an XML String * @throws EQException */ public String serialiseAsXML() throws EQException { EqBeanFactory eqBeanFactory = EqBeanFactory.getEqBeanFactory(); String xml = eqBeanFactory.serialiseBeanAsXML(this); return xml; } /** * return EquationStandardSQLPagingList instance from XML String * * @param xml * @return EquationStandardSQLPagingList instance from XML String * @throws EQException */ public static EquationStandardSQLPagingList deserialiseFromXML(String xml) throws EQException { EquationStandardSQLPagingList pagingList = null; EqBeanFactory beanFactory = EqBeanFactory.getEqBeanFactory(); pagingList = (EquationStandardSQLPagingList) beanFactory.deserialiseXMLAsBean(xml, EquationStandardSQLPagingList.class); return pagingList; } public void addKeyFieldValues(String key, String value) { keyFieldValues.put(key, value); } public void addFirstRow(String key, String value) { firstRow.put(key, value); } public void addLastRow(String key, String value) { lastRow.put(key, value); } public LinkedHashMap<String, String> getKeyFieldValues() { return keyFieldValues; } public void setKeyFieldValues(LinkedHashMap<String, String> keyFieldValues) { this.keyFieldValues = keyFieldValues; } public String getSqlSelectStart() { return sqlSelectStart; } public void setSqlSelectStart(String sqlSelectStart) { this.sqlSelectStart = sqlSelectStart; } public String getSqlSelectFilter() { return sqlSelectFilter; } public void setSqlSelectFilter(String sqlSelectFilter) { this.sqlSelectFilter = sqlSelectFilter; } public int getNumberOfRows() { return numberOfRows; } public void setNumberOfRows(int numberOfRows) { this.numberOfRows = numberOfRows; } public IEquationSQLPagingListCallback getCallback() { return callback; } public void setCallback(IEquationSQLPagingListCallback callback) { this.callback = callback; } public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } public int getTotalPages() { return totalPages; } public void setTotalPages(int totalPages) { this.totalPages = totalPages; } public int getTotalNumberOfRecordsCollected() { return totalNumberOfRecordsCollected; } public void setTotalNumberOfRecordsCollected(int totalNumberOfRecordsCollected) { this.totalNumberOfRecordsCollected = totalNumberOfRecordsCollected; } public boolean isMoreRows() { return moreRows; } public void setMoreRows(boolean moreRows) { this.moreRows = moreRows; } public HashMap<String, String> getFirstRow() { return firstRow; } public void setFirstRow(HashMap<String, String> firstRow) { this.firstRow = firstRow; } public HashMap<String, String> getLastRow() { return lastRow; } public void setLastRow(HashMap<String, String> lastRow) { this.lastRow = lastRow; } public boolean isInitialisedKeyFields() { return initialisedKeyFields; } public void setInitialisedKeyFields(boolean initialisedKeyFields) { this.initialisedKeyFields = initialisedKeyFields; } }
20,873
0.693575
0.689839
801
25.058676
29.034533
198
false
false
0
0
0
0
0
0
2.282147
false
false
11
89640a1d96af4c901d0dd373f68f03cd63a75538
20,598,663,168,401
b837638333999ad32afc57daf9afffb45f75fb72
/sources/p000a/p001a/p002a/p003a/p013e/p015b/C0818f.java
beffa2b10a88ac30669349d19f739cf1c3aa649b
[]
no_license
FresBlueMan/ikortv
https://github.com/FresBlueMan/ikortv
e2c1e5a36bd263de161b9fb59805080c34201032
a7e3f8cb28422d02ca93e4cc6147d2aa2c0d4da1
refs/heads/master
2021-10-12T04:05:28.424000
2019-02-01T16:17:11
2019-02-01T16:17:11
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package p000a.p001a.p002a.p003a.p013e.p015b; import java.net.InetAddress; import p000a.p001a.p002a.p003a.C0159n; import p000a.p001a.p002a.p003a.p013e.p015b.C0054e.C0052a; import p000a.p001a.p002a.p003a.p013e.p015b.C0054e.C0053b; import p000a.p001a.p002a.p003a.p035o.C0160a; import p000a.p001a.p002a.p003a.p035o.C0161b; import p000a.p001a.p002a.p003a.p035o.C0166g; /* compiled from: RouteTracker */ /* renamed from: a.a.a.a.e.b.f */ public final class C0818f implements C0054e, Cloneable { /* renamed from: a */ private final C0159n f1440a; /* renamed from: b */ private final InetAddress f1441b; /* renamed from: c */ private boolean f1442c; /* renamed from: d */ private C0159n[] f1443d; /* renamed from: e */ private C0053b f1444e; /* renamed from: f */ private C0052a f1445f; /* renamed from: g */ private boolean f1446g; public C0818f(C0159n c0159n, InetAddress inetAddress) { C0160a.m478a((Object) c0159n, "Target host"); this.f1440a = c0159n; this.f1441b = inetAddress; this.f1444e = C0053b.PLAIN; this.f1445f = C0052a.PLAIN; } /* renamed from: h */ public void m1523h() { this.f1442c = false; this.f1443d = null; this.f1444e = C0053b.PLAIN; this.f1445f = C0052a.PLAIN; this.f1446g = false; } public C0818f(C0817b c0817b) { this(c0817b.mo10a(), c0817b.mo12b()); } /* renamed from: a */ public final void m1513a(boolean z) { C0161b.m485a(this.f1442c ^ true, "Already connected"); this.f1442c = true; this.f1446g = z; } /* renamed from: a */ public final void m1512a(C0159n c0159n, boolean z) { C0160a.m478a((Object) c0159n, "Proxy host"); C0161b.m485a(this.f1442c ^ true, "Already connected"); this.f1442c = true; this.f1443d = new C0159n[]{c0159n}; this.f1446g = z; } /* renamed from: b */ public final void m1516b(boolean z) { C0161b.m485a(this.f1442c, "No tunnel unless connected"); C0161b.m484a(this.f1443d, "No tunnel without proxy"); this.f1444e = C0053b.TUNNELLED; this.f1446g = z; } /* renamed from: b */ public final void m1515b(C0159n c0159n, boolean z) { C0160a.m478a((Object) c0159n, "Proxy host"); C0161b.m485a(this.f1442c, "No tunnel unless connected"); C0161b.m484a(this.f1443d, "No tunnel without proxy"); Object obj = new C0159n[(this.f1443d.length + 1)]; System.arraycopy(this.f1443d, 0, obj, 0, this.f1443d.length); obj[obj.length - 1] = c0159n; this.f1443d = obj; this.f1446g = z; } /* renamed from: c */ public final void m1518c(boolean z) { C0161b.m485a(this.f1442c, "No layered protocol unless connected"); this.f1445f = C0052a.LAYERED; this.f1446g = z; } /* renamed from: a */ public final C0159n mo10a() { return this.f1440a; } /* renamed from: b */ public final InetAddress mo12b() { return this.f1441b; } /* renamed from: c */ public final int mo13c() { if (!this.f1442c) { return 0; } if (this.f1443d == null) { return 1; } return 1 + this.f1443d.length; } /* renamed from: a */ public final C0159n mo11a(int i) { C0160a.m482b(i, "Hop index"); int c = mo13c(); C0160a.m480a(i < c, "Hop index exceeds tracked route length"); if (i < c - 1) { return this.f1443d[i]; } return this.f1440a; } /* renamed from: d */ public final C0159n mo14d() { return this.f1443d == null ? null : this.f1443d[0]; } /* renamed from: i */ public final boolean m1524i() { return this.f1442c; } /* renamed from: e */ public final boolean mo15e() { return this.f1444e == C0053b.TUNNELLED; } /* renamed from: f */ public final boolean mo16f() { return this.f1445f == C0052a.LAYERED; } /* renamed from: g */ public final boolean mo17g() { return this.f1446g; } /* renamed from: j */ public final C0817b m1525j() { return !this.f1442c ? null : new C0817b(this.f1440a, this.f1441b, this.f1443d, this.f1446g, this.f1444e, this.f1445f); } public final boolean equals(Object obj) { boolean z = true; if (obj == this) { return true; } if (!(obj instanceof C0818f)) { return false; } C0818f c0818f = (C0818f) obj; if (this.f1442c != c0818f.f1442c || this.f1446g != c0818f.f1446g || this.f1444e != c0818f.f1444e || this.f1445f != c0818f.f1445f || !C0166g.m525a(this.f1440a, c0818f.f1440a) || !C0166g.m525a(this.f1441b, c0818f.f1441b) || C0166g.m526a(this.f1443d, c0818f.f1443d) == null) { z = false; } return z; } public final int hashCode() { int a = C0166g.m523a(C0166g.m523a(17, this.f1440a), this.f1441b); if (this.f1443d != null) { for (Object a2 : this.f1443d) { a = C0166g.m523a(a, a2); } } return C0166g.m523a(C0166g.m523a(C0166g.m524a(C0166g.m524a(a, this.f1442c), this.f1446g), this.f1444e), this.f1445f); } public final String toString() { StringBuilder stringBuilder = new StringBuilder((mo13c() * 30) + 50); stringBuilder.append("RouteTracker["); if (this.f1441b != null) { stringBuilder.append(this.f1441b); stringBuilder.append("->"); } stringBuilder.append('{'); if (this.f1442c) { stringBuilder.append('c'); } if (this.f1444e == C0053b.TUNNELLED) { stringBuilder.append('t'); } if (this.f1445f == C0052a.LAYERED) { stringBuilder.append('l'); } if (this.f1446g) { stringBuilder.append('s'); } stringBuilder.append("}->"); if (this.f1443d != null) { for (Object append : this.f1443d) { stringBuilder.append(append); stringBuilder.append("->"); } } stringBuilder.append(this.f1440a); stringBuilder.append(']'); return stringBuilder.toString(); } public Object clone() { return super.clone(); } }
UTF-8
Java
6,455
java
C0818f.java
Java
[]
null
[]
package p000a.p001a.p002a.p003a.p013e.p015b; import java.net.InetAddress; import p000a.p001a.p002a.p003a.C0159n; import p000a.p001a.p002a.p003a.p013e.p015b.C0054e.C0052a; import p000a.p001a.p002a.p003a.p013e.p015b.C0054e.C0053b; import p000a.p001a.p002a.p003a.p035o.C0160a; import p000a.p001a.p002a.p003a.p035o.C0161b; import p000a.p001a.p002a.p003a.p035o.C0166g; /* compiled from: RouteTracker */ /* renamed from: a.a.a.a.e.b.f */ public final class C0818f implements C0054e, Cloneable { /* renamed from: a */ private final C0159n f1440a; /* renamed from: b */ private final InetAddress f1441b; /* renamed from: c */ private boolean f1442c; /* renamed from: d */ private C0159n[] f1443d; /* renamed from: e */ private C0053b f1444e; /* renamed from: f */ private C0052a f1445f; /* renamed from: g */ private boolean f1446g; public C0818f(C0159n c0159n, InetAddress inetAddress) { C0160a.m478a((Object) c0159n, "Target host"); this.f1440a = c0159n; this.f1441b = inetAddress; this.f1444e = C0053b.PLAIN; this.f1445f = C0052a.PLAIN; } /* renamed from: h */ public void m1523h() { this.f1442c = false; this.f1443d = null; this.f1444e = C0053b.PLAIN; this.f1445f = C0052a.PLAIN; this.f1446g = false; } public C0818f(C0817b c0817b) { this(c0817b.mo10a(), c0817b.mo12b()); } /* renamed from: a */ public final void m1513a(boolean z) { C0161b.m485a(this.f1442c ^ true, "Already connected"); this.f1442c = true; this.f1446g = z; } /* renamed from: a */ public final void m1512a(C0159n c0159n, boolean z) { C0160a.m478a((Object) c0159n, "Proxy host"); C0161b.m485a(this.f1442c ^ true, "Already connected"); this.f1442c = true; this.f1443d = new C0159n[]{c0159n}; this.f1446g = z; } /* renamed from: b */ public final void m1516b(boolean z) { C0161b.m485a(this.f1442c, "No tunnel unless connected"); C0161b.m484a(this.f1443d, "No tunnel without proxy"); this.f1444e = C0053b.TUNNELLED; this.f1446g = z; } /* renamed from: b */ public final void m1515b(C0159n c0159n, boolean z) { C0160a.m478a((Object) c0159n, "Proxy host"); C0161b.m485a(this.f1442c, "No tunnel unless connected"); C0161b.m484a(this.f1443d, "No tunnel without proxy"); Object obj = new C0159n[(this.f1443d.length + 1)]; System.arraycopy(this.f1443d, 0, obj, 0, this.f1443d.length); obj[obj.length - 1] = c0159n; this.f1443d = obj; this.f1446g = z; } /* renamed from: c */ public final void m1518c(boolean z) { C0161b.m485a(this.f1442c, "No layered protocol unless connected"); this.f1445f = C0052a.LAYERED; this.f1446g = z; } /* renamed from: a */ public final C0159n mo10a() { return this.f1440a; } /* renamed from: b */ public final InetAddress mo12b() { return this.f1441b; } /* renamed from: c */ public final int mo13c() { if (!this.f1442c) { return 0; } if (this.f1443d == null) { return 1; } return 1 + this.f1443d.length; } /* renamed from: a */ public final C0159n mo11a(int i) { C0160a.m482b(i, "Hop index"); int c = mo13c(); C0160a.m480a(i < c, "Hop index exceeds tracked route length"); if (i < c - 1) { return this.f1443d[i]; } return this.f1440a; } /* renamed from: d */ public final C0159n mo14d() { return this.f1443d == null ? null : this.f1443d[0]; } /* renamed from: i */ public final boolean m1524i() { return this.f1442c; } /* renamed from: e */ public final boolean mo15e() { return this.f1444e == C0053b.TUNNELLED; } /* renamed from: f */ public final boolean mo16f() { return this.f1445f == C0052a.LAYERED; } /* renamed from: g */ public final boolean mo17g() { return this.f1446g; } /* renamed from: j */ public final C0817b m1525j() { return !this.f1442c ? null : new C0817b(this.f1440a, this.f1441b, this.f1443d, this.f1446g, this.f1444e, this.f1445f); } public final boolean equals(Object obj) { boolean z = true; if (obj == this) { return true; } if (!(obj instanceof C0818f)) { return false; } C0818f c0818f = (C0818f) obj; if (this.f1442c != c0818f.f1442c || this.f1446g != c0818f.f1446g || this.f1444e != c0818f.f1444e || this.f1445f != c0818f.f1445f || !C0166g.m525a(this.f1440a, c0818f.f1440a) || !C0166g.m525a(this.f1441b, c0818f.f1441b) || C0166g.m526a(this.f1443d, c0818f.f1443d) == null) { z = false; } return z; } public final int hashCode() { int a = C0166g.m523a(C0166g.m523a(17, this.f1440a), this.f1441b); if (this.f1443d != null) { for (Object a2 : this.f1443d) { a = C0166g.m523a(a, a2); } } return C0166g.m523a(C0166g.m523a(C0166g.m524a(C0166g.m524a(a, this.f1442c), this.f1446g), this.f1444e), this.f1445f); } public final String toString() { StringBuilder stringBuilder = new StringBuilder((mo13c() * 30) + 50); stringBuilder.append("RouteTracker["); if (this.f1441b != null) { stringBuilder.append(this.f1441b); stringBuilder.append("->"); } stringBuilder.append('{'); if (this.f1442c) { stringBuilder.append('c'); } if (this.f1444e == C0053b.TUNNELLED) { stringBuilder.append('t'); } if (this.f1445f == C0052a.LAYERED) { stringBuilder.append('l'); } if (this.f1446g) { stringBuilder.append('s'); } stringBuilder.append("}->"); if (this.f1443d != null) { for (Object append : this.f1443d) { stringBuilder.append(append); stringBuilder.append("->"); } } stringBuilder.append(this.f1440a); stringBuilder.append(']'); return stringBuilder.toString(); } public Object clone() { return super.clone(); } }
6,455
0.57072
0.426646
215
29.023256
26.748169
281
false
false
0
0
0
0
0
0
0.64186
false
false
11
706bb7be9d784e813aad2571d053c93a606e827c
33,105,607,938,670
9891b2d2da375191a180cd61fb07011e0965fed9
/Galeno_CCEM/JavaSource/cu/transoft/galeno/Entities/Movil.java
4d62ce41f3cef29717421162b29fa5384cd107fb
[]
no_license
yisehn/GalenoCCEMRepository
https://github.com/yisehn/GalenoCCEMRepository
4f85cb7418cb88602828b3c44a517adbc2c7097a
9e25f90fee653d7ba4553e619fe3099f457d709e
refs/heads/master
2019-07-29T12:16:07.604000
2015-03-24T01:03:13
2015-03-24T01:03:13
32,767,269
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cu.transoft.galeno.Entities; // Generated 08-jun-2011 9:21:58 by Hibernate Tools 3.2.1.GA import cu.transoft.galeno.Managers.ClaveManager; import java.math.BigDecimal; import java.util.Date; import java.util.HashSet; import java.util.Set; /** * Movil generated by hbm2java */ public class Movil implements java.io.Serializable , GenericEntitie{ private int id; private BaseAmbulancia baseAmbulancia; private LineaMovil lineaMovil; private String chapa; private BigDecimal velMax; private BigDecimal capacidad; private BigDecimal indiceConsumo; private Date fechaAlta; private BigDecimal kmsRecorridos; private String codigo; private BigDecimal kmUltimoMtto; private Date fechaBaja; private Boolean taller; private Set demandas = new HashSet(0); private Set movilClaves = new HashSet(0); private TipoMovil tipoMovil; private Clave claveActual; public Movil() { } public Movil(int id, LineaMovil lineaMovil) { this.id = id; this.lineaMovil = lineaMovil; } public Movil(int id, BaseAmbulancia baseAmbulancia, LineaMovil lineaMovil, String chapa, BigDecimal velMax, BigDecimal capacidad, BigDecimal indiceConsumo, Date fechaAlta, BigDecimal kmsRecorridos, String codigo, BigDecimal kmUltimoMtto, Date fechaBaja, Boolean taller, Set demandas, Set movilClaves, TipoMovil tipoMovil) { this.id = id; this.baseAmbulancia = baseAmbulancia; this.lineaMovil = lineaMovil; this.chapa = chapa; this.velMax = velMax; this.capacidad = capacidad; this.indiceConsumo = indiceConsumo; this.fechaAlta = fechaAlta; this.kmsRecorridos = kmsRecorridos; this.codigo = codigo; this.kmUltimoMtto = kmUltimoMtto; this.fechaBaja = fechaBaja; this.taller = taller; this.demandas = demandas; this.movilClaves = movilClaves; this.tipoMovil = tipoMovil; } public void setTipoMovil(TipoMovil tipoMovil) { this.tipoMovil = tipoMovil; } public TipoMovil getTipoMovil() { return tipoMovil; } public int getId() { return this.id; } public void setId(int id) { this.id = id; } public BaseAmbulancia getBaseAmbulancia() { return this.baseAmbulancia; } public void setBaseAmbulancia(BaseAmbulancia baseAmbulancia) { this.baseAmbulancia = baseAmbulancia; } public LineaMovil getLineaMovil() { return this.lineaMovil; } public void setLineaMovil(LineaMovil lineaMovil) { this.lineaMovil = lineaMovil; } public String getChapa() { return this.chapa; } public void setChapa(String chapa) { this.chapa = chapa; } public BigDecimal getVelMax() { return this.velMax; } public void setVelMax(BigDecimal velMax) { this.velMax = velMax; } public BigDecimal getCapacidad() { return this.capacidad; } public void setCapacidad(BigDecimal capacidad) { this.capacidad = capacidad; } public BigDecimal getIndiceConsumo() { return this.indiceConsumo; } public void setIndiceConsumo(BigDecimal indiceConsumo) { this.indiceConsumo = indiceConsumo; } public Date getFechaAlta() { return this.fechaAlta; } public void setFechaAlta(Date fechaAlta) { this.fechaAlta = fechaAlta; } public BigDecimal getKmsRecorridos() { return this.kmsRecorridos; } public void setKmsRecorridos(BigDecimal kmsRecorridos) { this.kmsRecorridos = kmsRecorridos; } public String getCodigo() { return this.codigo; } public void setCodigo(String codigo) { this.codigo = codigo; } public BigDecimal getKmUltimoMtto() { return this.kmUltimoMtto; } public void setKmUltimoMtto(BigDecimal kmUltimoMtto) { this.kmUltimoMtto = kmUltimoMtto; } public Date getFechaBaja() { return this.fechaBaja; } public void setFechaBaja(Date fechaBaja) { this.fechaBaja = fechaBaja; } public Boolean getTaller() { return this.taller; } public void setTaller(Boolean taller) { this.taller = taller; } public Set getDemandas() { return this.demandas; } public void setDemandas(Set demandas) { this.demandas = demandas; } public Set getMovilClaves() { return this.movilClaves; } public void setMovilClaves(Set movilClaves) { this.movilClaves = movilClaves; } public Clave getClaveActual() { for(Object cm: movilClaves) { if(((MovilClave)cm).getFechaHasta() == null) { return ((MovilClave)cm).getClave(); } } return null; } @Override public String toString(){ return codigo; } }
UTF-8
Java
5,025
java
Movil.java
Java
[]
null
[]
package cu.transoft.galeno.Entities; // Generated 08-jun-2011 9:21:58 by Hibernate Tools 3.2.1.GA import cu.transoft.galeno.Managers.ClaveManager; import java.math.BigDecimal; import java.util.Date; import java.util.HashSet; import java.util.Set; /** * Movil generated by hbm2java */ public class Movil implements java.io.Serializable , GenericEntitie{ private int id; private BaseAmbulancia baseAmbulancia; private LineaMovil lineaMovil; private String chapa; private BigDecimal velMax; private BigDecimal capacidad; private BigDecimal indiceConsumo; private Date fechaAlta; private BigDecimal kmsRecorridos; private String codigo; private BigDecimal kmUltimoMtto; private Date fechaBaja; private Boolean taller; private Set demandas = new HashSet(0); private Set movilClaves = new HashSet(0); private TipoMovil tipoMovil; private Clave claveActual; public Movil() { } public Movil(int id, LineaMovil lineaMovil) { this.id = id; this.lineaMovil = lineaMovil; } public Movil(int id, BaseAmbulancia baseAmbulancia, LineaMovil lineaMovil, String chapa, BigDecimal velMax, BigDecimal capacidad, BigDecimal indiceConsumo, Date fechaAlta, BigDecimal kmsRecorridos, String codigo, BigDecimal kmUltimoMtto, Date fechaBaja, Boolean taller, Set demandas, Set movilClaves, TipoMovil tipoMovil) { this.id = id; this.baseAmbulancia = baseAmbulancia; this.lineaMovil = lineaMovil; this.chapa = chapa; this.velMax = velMax; this.capacidad = capacidad; this.indiceConsumo = indiceConsumo; this.fechaAlta = fechaAlta; this.kmsRecorridos = kmsRecorridos; this.codigo = codigo; this.kmUltimoMtto = kmUltimoMtto; this.fechaBaja = fechaBaja; this.taller = taller; this.demandas = demandas; this.movilClaves = movilClaves; this.tipoMovil = tipoMovil; } public void setTipoMovil(TipoMovil tipoMovil) { this.tipoMovil = tipoMovil; } public TipoMovil getTipoMovil() { return tipoMovil; } public int getId() { return this.id; } public void setId(int id) { this.id = id; } public BaseAmbulancia getBaseAmbulancia() { return this.baseAmbulancia; } public void setBaseAmbulancia(BaseAmbulancia baseAmbulancia) { this.baseAmbulancia = baseAmbulancia; } public LineaMovil getLineaMovil() { return this.lineaMovil; } public void setLineaMovil(LineaMovil lineaMovil) { this.lineaMovil = lineaMovil; } public String getChapa() { return this.chapa; } public void setChapa(String chapa) { this.chapa = chapa; } public BigDecimal getVelMax() { return this.velMax; } public void setVelMax(BigDecimal velMax) { this.velMax = velMax; } public BigDecimal getCapacidad() { return this.capacidad; } public void setCapacidad(BigDecimal capacidad) { this.capacidad = capacidad; } public BigDecimal getIndiceConsumo() { return this.indiceConsumo; } public void setIndiceConsumo(BigDecimal indiceConsumo) { this.indiceConsumo = indiceConsumo; } public Date getFechaAlta() { return this.fechaAlta; } public void setFechaAlta(Date fechaAlta) { this.fechaAlta = fechaAlta; } public BigDecimal getKmsRecorridos() { return this.kmsRecorridos; } public void setKmsRecorridos(BigDecimal kmsRecorridos) { this.kmsRecorridos = kmsRecorridos; } public String getCodigo() { return this.codigo; } public void setCodigo(String codigo) { this.codigo = codigo; } public BigDecimal getKmUltimoMtto() { return this.kmUltimoMtto; } public void setKmUltimoMtto(BigDecimal kmUltimoMtto) { this.kmUltimoMtto = kmUltimoMtto; } public Date getFechaBaja() { return this.fechaBaja; } public void setFechaBaja(Date fechaBaja) { this.fechaBaja = fechaBaja; } public Boolean getTaller() { return this.taller; } public void setTaller(Boolean taller) { this.taller = taller; } public Set getDemandas() { return this.demandas; } public void setDemandas(Set demandas) { this.demandas = demandas; } public Set getMovilClaves() { return this.movilClaves; } public void setMovilClaves(Set movilClaves) { this.movilClaves = movilClaves; } public Clave getClaveActual() { for(Object cm: movilClaves) { if(((MovilClave)cm).getFechaHasta() == null) { return ((MovilClave)cm).getClave(); } } return null; } @Override public String toString(){ return codigo; } }
5,025
0.639204
0.635821
193
25.025908
27.898861
327
false
false
0
0
0
0
0
0
0.487047
false
false
11
7c54bbac0befc5df78be1e2ad2b4e0670edd77b8
4,054,449,149,145
a9e4e8938b1553073cb40481e8d130d9ccbc22c4
/Ns.java/src/verification_commands/Page_Verificationcommands.java
f4a0dd8e666c8984683a00be69a6fa18b5bbe8e4
[]
no_license
Noorsultan03/SeleniumNS
https://github.com/Noorsultan03/SeleniumNS
6872ea95c36476dc2a218a7ca35a8c8034639e6a
93d1da4717590376975e63fdc64ea87127ae53d1
refs/heads/master
2020-04-02T02:08:24.180000
2018-10-20T10:25:54
2018-10-20T10:25:54
153,893,531
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package verification_commands; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class Page_Verificationcommands { public static void main(String[] args) { WebDriver driver=new ChromeDriver(); driver.get("https://www.cleartrip.com/"); driver.manage().window().maximize(); //Get Runtime page title String runtime_page_title=driver.getTitle(); System.out.println("Runtime page title is -->"+runtime_page_title); //Get RuntimeUrl String Runtime_url=driver.getCurrentUrl(); System.out.println("Runtime url is -->"+Runtime_url); //Get Runtime Window ID String Runtime_win_ID=driver.getWindowHandle(); System.out.println("Runtime window ID is -->"+Runtime_win_ID); //Get pageSource String Runtime_page_Source=driver.getPageSource(); System.out.println("Runtimme Page Source is -->"+Runtime_page_Source); } }
UTF-8
Java
936
java
Page_Verificationcommands.java
Java
[]
null
[]
package verification_commands; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class Page_Verificationcommands { public static void main(String[] args) { WebDriver driver=new ChromeDriver(); driver.get("https://www.cleartrip.com/"); driver.manage().window().maximize(); //Get Runtime page title String runtime_page_title=driver.getTitle(); System.out.println("Runtime page title is -->"+runtime_page_title); //Get RuntimeUrl String Runtime_url=driver.getCurrentUrl(); System.out.println("Runtime url is -->"+Runtime_url); //Get Runtime Window ID String Runtime_win_ID=driver.getWindowHandle(); System.out.println("Runtime window ID is -->"+Runtime_win_ID); //Get pageSource String Runtime_page_Source=driver.getPageSource(); System.out.println("Runtimme Page Source is -->"+Runtime_page_Source); } }
936
0.695513
0.695513
34
25.529411
23.321583
72
false
false
0
0
0
0
0
0
1.676471
false
false
11
138f7f71c9969779cbfbb7b37c8523fc190ed415
9,311,489,128,495
1f53634aceb01737bd17d5e0b11096c86983f873
/src/com/tju/bluetoothlegatt52/DeviceScanActivity.java
ebaa4e6bd133b7881cecdfe5c76230f5521bc7c5
[]
no_license
BZZYTGTD/BLE_ECG_BMD101_wifi_Server_2
https://github.com/BZZYTGTD/BLE_ECG_BMD101_wifi_Server_2
6e7c76ed8c78b982399e939f55ba0f04c75d7f87
7fb5bf8569b9ca2d58bf35fd25b18e64ff0e5afe
refs/heads/master
2015-09-24T11:35:46.588000
2015-07-28T01:50:55
2015-07-28T01:50:55
37,465,875
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tju.bluetoothlegatt52; import android.app.Activity; import android.app.Dialog; import android.content.BroadcastReceiver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.DialogFragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.tju.SQLiteUtils.SQLite; import com.tju.SQLiteUtils.SQLiteUtils; import com.tju.ecglogin.CustomDialog; import com.tju.ecglogin.UserInfoActivity; /** * Activity for scanning and displaying available Bluetooth LE devices. */ public class DeviceScanActivity extends FragmentActivity implements CustomDialog.NoticeDialogListener { DialogFragment dialogFragment = null; FragmentManager fm = null; SQLite sqliteHelper = null; private boolean login = false; private Dialog dialog = null; // private LeDeviceListAdapter mLeDeviceListAdapter; private boolean mScanning; private Handler mHandler; public static final String ACTION_WIFI_CONNECTED = "com.example.bluetooth52.WIFI_CONNECTED"; private static final int REQUEST_ENABLE_BT = 1; private static final int REQUEST_ACTIVITY = 2; // Stops scanning after 10 seconds. private static final long SCAN_PERIOD = 10000; private BroadcastReceiver wificonnectedReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub dialog.dismiss(); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, // WindowManager.LayoutParams.FLAG_FULLSCREEN); // this.requestWindowFeature(Window.FEATURE_NO_TITLE); System.out.println("test Activity"); String action = getIntent().getStringExtra("name"); if(action == null){ System.out.println("Null"); }else{ System.out.println("Name:"); System.out.print(action); } dialogFragment = new CustomDialog(); fm = getSupportFragmentManager(); dialogFragment.show(fm, "Sign in"); sqliteHelper = SQLite.getInstence(DeviceScanActivity.this, "ecgdb", null, 3); getActionBar().setTitle(R.string.title_devices); mHandler = new Handler(); registerReceiver(wificonnectedReceiver, new IntentFilter(ACTION_WIFI_CONNECTED)); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { Context context = DeviceScanActivity.this; Toast toast = new Toast(context); switch (item.getItemId()) { case R.id.menu_pair: dialog = new PairDialog(DeviceScanActivity.this, R.style.PairDialog); dialog.show(); break; case R.id.wifi: if (!login) { dialogFragment.show(fm, "Sign in"); } WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); if (wifiManager != null) { int wifiState = wifiManager.getWifiState(); if (wifiState == WifiManager.WIFI_STATE_DISABLED) { Toast.makeText(context, "Please open the WIFI", Toast.LENGTH_SHORT).show(); break; } } else { break; } WifiInfo wifiInfo = wifiManager.getConnectionInfo(); if (wifiInfo == null) { Toast.makeText(context, " Please connect to WIFI", Toast.LENGTH_SHORT).show(); toast.show(); break; } else { if (wifiInfo.getIpAddress() == 0) { Toast.makeText(context, " Please connect to WIFI", Toast.LENGTH_SHORT).show(); break; } } startDrawActivity(); break; } return true; } @Override protected void onResume() { super.onResume(); // Ensures Bluetooth is enabled on the device. If Bluetooth is not // currently enabled, // fire an intent to display a dialog asking the user to grant // permission to enable it. // Initializes list view adapter. // mLeDeviceListAdapter = new LeDeviceListAdapter(); // setListAdapter(mLeDeviceListAdapter); scanLeDevice(true); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // User chose not to enable Bluetooth. if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_CANCELED) { finish(); return; } } @Override protected void onPause() { super.onPause(); scanLeDevice(false); } private void scanLeDevice(final boolean enable) { if (enable) { // Stops scanning after a pre-defined scan period. mHandler.postDelayed(new Runnable() { @Override public void run() { mScanning = false; invalidateOptionsMenu(); } }, SCAN_PERIOD); mScanning = true; } else { mScanning = false; } invalidateOptionsMenu(); } // Adapter for holding devices found through scanning. private class LeDeviceListAdapter extends BaseAdapter { private LayoutInflater mInflator; public LeDeviceListAdapter() { super(); mInflator = DeviceScanActivity.this.getLayoutInflater(); } @Override public long getItemId(int i) { return i; } @Override public View getView(int i, View view, ViewGroup viewGroup) { ViewHolder viewHolder; // General ListView optimization code. if (view == null) { view = mInflator.inflate(R.layout.listitem_device, null); viewHolder = new ViewHolder(); viewHolder.deviceAddress = (TextView) view.findViewById(R.id.device_address); viewHolder.deviceName = (TextView) view.findViewById(R.id.device_name); view.setTag(viewHolder); } else { viewHolder = (ViewHolder) view.getTag(); } return view; } @Override public int getCount() { // TODO Auto-generated method stub return 0; } @Override public Object getItem(int arg0) { // TODO Auto-generated method stub return null; } } // Device scan callback. // private BluetoothAdapter.LeScanCallback mLeScanCallback = // new BluetoothAdapter.LeScanCallback() { // // @Override // public void onLeScan(final BluetoothDevice device, int rssi, byte[] // scanRecord) { // runOnUiThread(new Runnable() { // @Override // public void run() { // mLeDeviceListAdapter.addDevice(device); // mLeDeviceListAdapter.notifyDataSetChanged(); // } // }); // } // }; static class ViewHolder { TextView deviceName; TextView deviceAddress; } @Override public void onDialogPositiveClick(DialogFragment dialog, View view) { // TODO Auto-generated method stub startActivity(new Intent(DeviceScanActivity.this, UserInfoActivity.class)); } @Override public void onDialogNegativeClick(DialogFragment dialog, View view) { // TODO Auto-generated method stub String name = ((EditText) view.findViewById(R.id.username)).getText().toString(); String password = ((EditText) view.findViewById(R.id.password)).getText().toString(); if (SQLiteUtils.verifyAndget(sqliteHelper, "user", name, password)) { login = true; Toast.makeText(this, "登陆成功", 1000).show(); startDrawActivity(); } else { Toast.makeText(this, "登陆失败", 1000).show(); } } private void startDrawActivity() { if (login) { final Intent intent = new Intent(this, DeviceControlActivity.class); intent.putExtra(DeviceControlActivity.EXTRAS_SERVER_ADDRESS, "192.168.1.3"); intent.putExtra(DeviceControlActivity.EXTRAS_SERVER_PORT, 5001); startActivity(intent); } } }
UTF-8
Java
8,790
java
DeviceScanActivity.java
Java
[ { "context": "tra(DeviceControlActivity.EXTRAS_SERVER_ADDRESS, \"192.168.1.3\");\r\n\t\t\tintent.putExtra(DeviceControlActivity.EXTR", "end": 8663, "score": 0.9995797872543335, "start": 8652, "tag": "IP_ADDRESS", "value": "192.168.1.3" } ]
null
[]
/* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tju.bluetoothlegatt52; import android.app.Activity; import android.app.Dialog; import android.content.BroadcastReceiver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.DialogFragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.tju.SQLiteUtils.SQLite; import com.tju.SQLiteUtils.SQLiteUtils; import com.tju.ecglogin.CustomDialog; import com.tju.ecglogin.UserInfoActivity; /** * Activity for scanning and displaying available Bluetooth LE devices. */ public class DeviceScanActivity extends FragmentActivity implements CustomDialog.NoticeDialogListener { DialogFragment dialogFragment = null; FragmentManager fm = null; SQLite sqliteHelper = null; private boolean login = false; private Dialog dialog = null; // private LeDeviceListAdapter mLeDeviceListAdapter; private boolean mScanning; private Handler mHandler; public static final String ACTION_WIFI_CONNECTED = "com.example.bluetooth52.WIFI_CONNECTED"; private static final int REQUEST_ENABLE_BT = 1; private static final int REQUEST_ACTIVITY = 2; // Stops scanning after 10 seconds. private static final long SCAN_PERIOD = 10000; private BroadcastReceiver wificonnectedReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub dialog.dismiss(); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, // WindowManager.LayoutParams.FLAG_FULLSCREEN); // this.requestWindowFeature(Window.FEATURE_NO_TITLE); System.out.println("test Activity"); String action = getIntent().getStringExtra("name"); if(action == null){ System.out.println("Null"); }else{ System.out.println("Name:"); System.out.print(action); } dialogFragment = new CustomDialog(); fm = getSupportFragmentManager(); dialogFragment.show(fm, "Sign in"); sqliteHelper = SQLite.getInstence(DeviceScanActivity.this, "ecgdb", null, 3); getActionBar().setTitle(R.string.title_devices); mHandler = new Handler(); registerReceiver(wificonnectedReceiver, new IntentFilter(ACTION_WIFI_CONNECTED)); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { Context context = DeviceScanActivity.this; Toast toast = new Toast(context); switch (item.getItemId()) { case R.id.menu_pair: dialog = new PairDialog(DeviceScanActivity.this, R.style.PairDialog); dialog.show(); break; case R.id.wifi: if (!login) { dialogFragment.show(fm, "Sign in"); } WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); if (wifiManager != null) { int wifiState = wifiManager.getWifiState(); if (wifiState == WifiManager.WIFI_STATE_DISABLED) { Toast.makeText(context, "Please open the WIFI", Toast.LENGTH_SHORT).show(); break; } } else { break; } WifiInfo wifiInfo = wifiManager.getConnectionInfo(); if (wifiInfo == null) { Toast.makeText(context, " Please connect to WIFI", Toast.LENGTH_SHORT).show(); toast.show(); break; } else { if (wifiInfo.getIpAddress() == 0) { Toast.makeText(context, " Please connect to WIFI", Toast.LENGTH_SHORT).show(); break; } } startDrawActivity(); break; } return true; } @Override protected void onResume() { super.onResume(); // Ensures Bluetooth is enabled on the device. If Bluetooth is not // currently enabled, // fire an intent to display a dialog asking the user to grant // permission to enable it. // Initializes list view adapter. // mLeDeviceListAdapter = new LeDeviceListAdapter(); // setListAdapter(mLeDeviceListAdapter); scanLeDevice(true); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // User chose not to enable Bluetooth. if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_CANCELED) { finish(); return; } } @Override protected void onPause() { super.onPause(); scanLeDevice(false); } private void scanLeDevice(final boolean enable) { if (enable) { // Stops scanning after a pre-defined scan period. mHandler.postDelayed(new Runnable() { @Override public void run() { mScanning = false; invalidateOptionsMenu(); } }, SCAN_PERIOD); mScanning = true; } else { mScanning = false; } invalidateOptionsMenu(); } // Adapter for holding devices found through scanning. private class LeDeviceListAdapter extends BaseAdapter { private LayoutInflater mInflator; public LeDeviceListAdapter() { super(); mInflator = DeviceScanActivity.this.getLayoutInflater(); } @Override public long getItemId(int i) { return i; } @Override public View getView(int i, View view, ViewGroup viewGroup) { ViewHolder viewHolder; // General ListView optimization code. if (view == null) { view = mInflator.inflate(R.layout.listitem_device, null); viewHolder = new ViewHolder(); viewHolder.deviceAddress = (TextView) view.findViewById(R.id.device_address); viewHolder.deviceName = (TextView) view.findViewById(R.id.device_name); view.setTag(viewHolder); } else { viewHolder = (ViewHolder) view.getTag(); } return view; } @Override public int getCount() { // TODO Auto-generated method stub return 0; } @Override public Object getItem(int arg0) { // TODO Auto-generated method stub return null; } } // Device scan callback. // private BluetoothAdapter.LeScanCallback mLeScanCallback = // new BluetoothAdapter.LeScanCallback() { // // @Override // public void onLeScan(final BluetoothDevice device, int rssi, byte[] // scanRecord) { // runOnUiThread(new Runnable() { // @Override // public void run() { // mLeDeviceListAdapter.addDevice(device); // mLeDeviceListAdapter.notifyDataSetChanged(); // } // }); // } // }; static class ViewHolder { TextView deviceName; TextView deviceAddress; } @Override public void onDialogPositiveClick(DialogFragment dialog, View view) { // TODO Auto-generated method stub startActivity(new Intent(DeviceScanActivity.this, UserInfoActivity.class)); } @Override public void onDialogNegativeClick(DialogFragment dialog, View view) { // TODO Auto-generated method stub String name = ((EditText) view.findViewById(R.id.username)).getText().toString(); String password = ((EditText) view.findViewById(R.id.password)).getText().toString(); if (SQLiteUtils.verifyAndget(sqliteHelper, "user", name, password)) { login = true; Toast.makeText(this, "登陆成功", 1000).show(); startDrawActivity(); } else { Toast.makeText(this, "登陆失败", 1000).show(); } } private void startDrawActivity() { if (login) { final Intent intent = new Intent(this, DeviceControlActivity.class); intent.putExtra(DeviceControlActivity.EXTRAS_SERVER_ADDRESS, "192.168.1.3"); intent.putExtra(DeviceControlActivity.EXTRAS_SERVER_PORT, 5001); startActivity(intent); } } }
8,790
0.702872
0.697401
300
27.253334
24.357391
103
false
false
0
0
0
0
0
0
2.113333
false
false
11
f1c6907718a6dba7b63b8363789b6709c17d5306
13,615,046,342,659
65d5f243e7b0f5fc96b90088bc7a631aa97679c1
/app/src/main/java/com/app/nevada/nevadaapp/RatingReport.java
eac818f037b234f88447adecad7fb5d6ce85db35
[]
no_license
SuhaibNofal/android-dyabe
https://github.com/SuhaibNofal/android-dyabe
44e409d8b21adf709f83204081042ef0c4f608b7
2e79833f688ddd34c11b7bc6514e6648fd22bc08
refs/heads/master
2020-03-29T13:18:40.097000
2018-12-06T09:19:50
2018-12-06T09:19:50
149,951,473
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.app.nevada.nevadaapp; import android.app.DatePickerDialog; import android.app.Dialog; import android.app.VoiceInteractor; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Configuration; import android.content.res.Resources; import android.graphics.Rect; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.InputType; import android.text.format.DateFormat; import android.view.LayoutInflater; import android.view.View; import android.view.Window; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.DatePicker; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.RadioGroup; import android.widget.RatingBar; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import org.ksoap2.SoapEnvelope; import org.ksoap2.SoapFault; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapSerializationEnvelope; import org.ksoap2.transport.HttpTransportSE; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.net.SocketTimeoutException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Locale; import static com.app.nevada.nevadaapp.Constants.CUS_FIFTH_COLUMN; import static com.app.nevada.nevadaapp.Constants.CUS_FIRST_COLUMN; import static com.app.nevada.nevadaapp.Constants.CUS_FOURTH_COLUMN; import static com.app.nevada.nevadaapp.Constants.CUS_SECOND_COLUMN; import static com.app.nevada.nevadaapp.Constants.CUS_SEVENTH_COLUMN; import static com.app.nevada.nevadaapp.Constants.CUS_SIXTH_COLUMN; import static com.app.nevada.nevadaapp.Constants.CUS_THIRD_COLUMN; public class RatingReport extends AppCompatActivity { private static final String METHOD_NAME = "getAllCustomer"; private static final String NAMESPACE = "http://37.224.24.195"; private static final String URL = "http://37.224.24.195/AndroidWS/GetInfo.asmx"; final String SOAP_ACTION = "http://37.224.24.195/getAllCustomer"; private ArrayList<HashMap<String, String>> list; SoapObject responseObject; private DatePickerDialog fromDatePickerDialog; private DatePickerDialog toDatePickerDialog; private String varFromDate; private String varToDate; private TextView fromDateEtxt; private TextView toDateEtxt; private SimpleDateFormat dateFormatter; String VarCustomerAccNumber = "0"; String VarIsLate = "0"; String VarIsQtyNotGood = "0"; String VarIsItemNotGood = "0"; String VarRate = "0"; String languges = ""; @Override protected void onDestroy() { Locale locale = new Locale(languges); forceLocale(this, locale); super.onDestroy(); } @Override protected void onResume() { Locale locale = new Locale(languges); forceLocale(this, locale); super.onResume(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_rating_report); new GetAllCustomerTask().execute(); Intent intent = getIntent(); languges = intent.getStringExtra("lang"); Locale locale = new Locale(languges); forceLocale(this, locale); Spinner ddlAllCustomers = (Spinner) findViewById(R.id.spCustomers); ddlAllCustomers.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { if (pos > 0) { StringWithTag sel = (StringWithTag) parent.getItemAtPosition(pos); VarCustomerAccNumber = sel.tag.toString(); } else { VarCustomerAccNumber = "0"; } } public void onNothingSelected(AdapterView<?> parent) { } }); dateFormatter = new SimpleDateFormat("dd-MM-yyyy", Locale.US); findViewsById(); setDateTimeField(); } private void setDateTimeField() { Calendar newCalendar = Calendar.getInstance(); fromDatePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() { public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { Calendar cal = Calendar.getInstance(); cal.set(year, monthOfYear, dayOfMonth); CharSequence output = DateFormat.format("dd-MM-yyyy", cal); fromDateEtxt.setText(output); varFromDate = fromDateEtxt.getText().toString(); varToDate = toDateEtxt.getText().toString(); } }, newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH)); toDatePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() { public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { Calendar cal = Calendar.getInstance(); cal.set(year, monthOfYear, dayOfMonth); CharSequence output = DateFormat.format("dd-MM-yyyy", cal); toDateEtxt.setText(output); varFromDate = fromDateEtxt.getText().toString(); varToDate = toDateEtxt.getText().toString(); } }, newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH)); varFromDate = fromDateEtxt.getText().toString(); varToDate = toDateEtxt.getText().toString(); Locale locale = new Locale(languges); forceLocale(this, locale); } private void findViewsById() { Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); fromDateEtxt = (TextView) findViewById(R.id.tranDateFromFilter); fromDateEtxt.setInputType(InputType.TYPE_NULL); toDateEtxt = (TextView) findViewById(R.id.tranDateToFilter); toDateEtxt.setInputType(InputType.TYPE_NULL); fromDateEtxt.setText("01-01-" + year); Calendar cal = Calendar.getInstance(); CharSequence output = DateFormat.format("dd-MM-yyyy", cal); String[] VarDateVal = (String.valueOf(output).split("-")); int day = Integer.valueOf(VarDateVal[0]); int month = Integer.valueOf(VarDateVal[1]); if (month < 10) { if (day < 10) { toDateEtxt.setText("0" + day + "-0" + month + "-" + year); } else { toDateEtxt.setText(day + "-0" + month + "-" + year); } } else { if (day < 10) { toDateEtxt.setText("0" + day + "-" + month + "-" + year); } else { toDateEtxt.setText(day + "-" + month + "-" + year); } } varFromDate = fromDateEtxt.getText().toString(); varToDate = toDateEtxt.getText().toString(); } public void callDate(View view) { String languageToLoad = "EN-US"; Locale locale = new Locale(languageToLoad); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale; getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics()); if (view == fromDateEtxt) { fromDatePickerDialog.show(); } else if (view == toDateEtxt) { toDatePickerDialog.show(); } } public void SearchOrders(View v) { RadioGroup Access_radioGroup = (RadioGroup) findViewById(R.id.Access_radio_group); RadioGroup dealing_radioGroup = (RadioGroup) findViewById(R.id.dealing_radio_group); RadioGroup view_radiogroup = (RadioGroup) findViewById(R.id.View_radio_group); Access_radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId) { case R.id.late: VarIsItemNotGood = "3"; break; case R.id.latesome: VarIsItemNotGood = "2"; break; default: VarIsItemNotGood = "1"; } } }); dealing_radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId) { case R.id.dealing_goodMiddel: VarIsQtyNotGood = "2"; break; case R.id.dealing_not_good: VarIsQtyNotGood = "3"; break; default: VarIsQtyNotGood = "1"; } } }); view_radiogroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId) { case R.id.view_not_good: VarIsLate = "2"; break; default: VarIsLate = "1"; } } }); RatingBar simpleRatingBar = (RatingBar) findViewById(R.id.repRatingBar); VarRate = String.valueOf(Math.round(simpleRatingBar.getRating())); ImageView imgCurrentSearch = (ImageView) findViewById(R.id.imgCurrentSearch); imgCurrentSearch.setVisibility(View.VISIBLE); new GetSearchResult().execute(); } public void OpenDetails(View v) { ImageView btn = ((ImageView) v); final String[] cuurentValues = btn.getTag().toString().split(",&,"); final Dialog dialog = new Dialog(RatingReport.this); if (languges.contains("en")) { dialog.setTitle("Information"); } else { dialog.setTitle("معلومات"); } Rect displayRectangle = new Rect(); Window window = RatingReport.this.getWindow(); window.getDecorView().getWindowVisibleDisplayFrame(displayRectangle); LayoutInflater inflater = (LayoutInflater) RatingReport.this.getSystemService(RatingReport.this.LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout.search_info_dialog, null); layout.setMinimumWidth((int) (displayRectangle.width() * 0.9f)); layout.setMinimumHeight((int) (displayRectangle.height() * 0.4f)); dialog.setContentView(layout); TextView txtNotes = (TextView) dialog.findViewById(R.id.txtDNote); TextView txtDLate = (TextView) dialog.findViewById(R.id.txtDLate); TextView txtDQNG = (TextView) dialog.findViewById(R.id.txtDQNG); TextView txtDING = (TextView) dialog.findViewById(R.id.txtDING); txtNotes.setText(cuurentValues[0]); Locale locale = Locale.getDefault(); String language = String.valueOf(locale); if (language.contains("en")) { if (cuurentValues[1].equals("1")) { txtDLate.setText("seemly"); } else { txtDLate.setText("unseemly"); } if (cuurentValues[2].equals("1")) { txtDQNG.setText("seemly"); } else if (cuurentValues[2].equals("2")) { txtDQNG.setText("fine"); } else { txtDQNG.setText("unseemly"); } if (cuurentValues[3].equals("1")) { txtDING.setText("on time"); } else if (cuurentValues[3].equals("2")) { txtDING.setText("Delayed slightly"); } else { txtDING.setText("too late"); } } else { if (cuurentValues[1].equals("1")) { txtDLate.setText("لائق"); } else { txtDLate.setText("غير لائق"); } if (cuurentValues[2].equals("1")) { txtDQNG.setText("لائق"); } else if (cuurentValues[2].equals("2")) { txtDQNG.setText("جيد"); } else { txtDQNG.setText("غير لائق"); } if (cuurentValues[3].equals("1")) { txtDING.setText("في الوقت المحدد"); } else if (cuurentValues[3].equals("2")) { txtDING.setText("تاخر قليلا"); } else { txtDING.setText("تاخر كثيرا"); } } dialog.show(); } public void deleteSearsh(View view) { RadioGroup Access_radioGroup = (RadioGroup) findViewById(R.id.Access_radio_group); RadioGroup dealing_radioGroup = (RadioGroup) findViewById(R.id.dealing_radio_group); RadioGroup view_radiogroup = (RadioGroup) findViewById(R.id.View_radio_group); Access_radioGroup.clearCheck(); dealing_radioGroup.clearCheck(); view_radiogroup.clearCheck(); VarIsLate = "0"; VarIsQtyNotGood = "0"; VarIsItemNotGood = "0"; } class GetAllCustomerTask extends AsyncTask<Integer, Integer, String> { @Override protected String doInBackground(Integer... params) { try { SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.dotNet = true; envelope.setOutputSoapObject(request); HttpTransportSE androidHttpTransport = new HttpTransportSE(URL, 1000000000); androidHttpTransport.debug = true; androidHttpTransport.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); androidHttpTransport.call(SOAP_ACTION, envelope); responseObject = (SoapObject) envelope.getResponse(); Integer x = 1; } catch (SoapFault soapFault) { soapFault.printStackTrace(); } catch (XmlPullParserException e) { e.printStackTrace(); } catch (SocketTimeoutException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return "Task Completed."; } @Override protected void onPostExecute(String result) { Spinner ddlAllCustomers = (Spinner) findViewById(R.id.spCustomers); List<StringWithTag> AllCustomers = new ArrayList<StringWithTag>(); AllCustomers.add(new StringWithTag("جميع العملاء", "0")); for (int i = 0; i < responseObject.getPropertyCount(); i++) { String[] reponseArrayString = responseObject.getProperty(i).toString().split("&&"); if (reponseArrayString.length == 3) { AllCustomers.add(new StringWithTag(reponseArrayString[1].toString(), reponseArrayString[2].toString())); } } ArrayAdapter<StringWithTag> spLocationAdapter = new ArrayAdapter<StringWithTag>(RatingReport.this, android.R.layout.simple_spinner_dropdown_item, AllCustomers); ddlAllCustomers.setAdapter(spLocationAdapter); } @Override protected void onPreExecute() { } @Override protected void onProgressUpdate(Integer... values) { } } class GetSearchResult extends AsyncTask<Integer, Integer, String> { @Override protected String doInBackground(Integer... params) { try { SoapObject request = new SoapObject(NAMESPACE, "getComplaints"); request.addProperty("VarCustID", VarCustomerAccNumber); request.addProperty("VarRate", VarRate); request.addProperty("VarIsLate", VarIsLate); request.addProperty("VarIsQtyNotGood", VarIsQtyNotGood); request.addProperty("VarIsItemNotGood", VarIsItemNotGood); request.addProperty("VarFromDate", varFromDate); request.addProperty("VarToDate", varToDate); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.dotNet = true; envelope.setOutputSoapObject(request); HttpTransportSE androidHttpTransport = new HttpTransportSE(URL, 1000000000); androidHttpTransport.debug = true; androidHttpTransport.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); androidHttpTransport.call("http://37.224.24.195/getComplaints", envelope); responseObject = (SoapObject) envelope.getResponse(); Integer x = 1; } catch (SoapFault soapFault) { soapFault.printStackTrace(); } catch (XmlPullParserException e) { e.printStackTrace(); } catch (SocketTimeoutException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return "Task Completed."; } @Override protected void onPostExecute(String result) { ListView listView = (ListView) findViewById(R.id.lvSearchResults); list = new ArrayList<HashMap<String, String>>(); ListViewAdaptersSearch adapter = new ListViewAdaptersSearch(RatingReport.this, list); listView.setAdapter(adapter); for (int i = 0; i < responseObject.getPropertyCount(); i++) { String[] reponseArrayString = responseObject.getProperty(i).toString().split("&&"); HashMap<String, String> temp = new HashMap<String, String>(); int count = reponseArrayString.length; temp.put(CUS_FIRST_COLUMN, reponseArrayString[0]); temp.put(CUS_SECOND_COLUMN, reponseArrayString[1]); temp.put(CUS_THIRD_COLUMN, reponseArrayString[2]); temp.put(CUS_FOURTH_COLUMN, reponseArrayString[3]); temp.put(CUS_FIFTH_COLUMN, reponseArrayString[4]); temp.put(CUS_SIXTH_COLUMN, reponseArrayString[5]); temp.put(CUS_SEVENTH_COLUMN, reponseArrayString[6]); list.add(temp); } adapter = new ListViewAdaptersSearch(RatingReport.this, list); listView.setAdapter(adapter); ImageView imgCurrentSearch = (ImageView) findViewById(R.id.imgCurrentSearch); imgCurrentSearch.setVisibility(View.INVISIBLE); } @Override protected void onPreExecute() { } @Override protected void onProgressUpdate(Integer... values) { } } public static void forceLocale(Context ctx, Locale locale) { Configuration conf = ctx.getResources().getConfiguration(); conf.locale = locale; ctx.getResources().updateConfiguration(conf, ctx.getResources().getDisplayMetrics()); Configuration systemConf = Resources.getSystem().getConfiguration(); systemConf.locale = locale; Resources.getSystem().updateConfiguration(systemConf, Resources.getSystem().getDisplayMetrics()); Locale.setDefault(locale); } }
UTF-8
Java
20,137
java
RatingReport.java
Java
[ { "context": " private static final String NAMESPACE = \"http://37.224.24.195\";\n private static final String URL = \"http://3", "end": 2306, "score": 0.9973660707473755, "start": 2293, "tag": "IP_ADDRESS", "value": "37.224.24.195" }, { "context": "5\";\n private static final String URL = \"http://37.224.24.195/AndroidWS/GetInfo.asmx\";\n final String SOAP_AC", "end": 2368, "score": 0.9932259321212769, "start": 2355, "tag": "IP_ADDRESS", "value": "37.224.24.195" }, { "context": "nfo.asmx\";\n final String SOAP_ACTION = \"http://37.224.24.195/getAllCustomer\";\n private ArrayList<HashMap<St", "end": 2446, "score": 0.9883782863616943, "start": 2433, "tag": "IP_ADDRESS", "value": "37.224.24.195" }, { "context": " androidHttpTransport.call(\"http://37.224.24.195/getComplaints\", envelope);\n respon", "end": 17389, "score": 0.9711114764213562, "start": 17377, "tag": "IP_ADDRESS", "value": "7.224.24.195" } ]
null
[]
package com.app.nevada.nevadaapp; import android.app.DatePickerDialog; import android.app.Dialog; import android.app.VoiceInteractor; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Configuration; import android.content.res.Resources; import android.graphics.Rect; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.InputType; import android.text.format.DateFormat; import android.view.LayoutInflater; import android.view.View; import android.view.Window; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.DatePicker; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.RadioGroup; import android.widget.RatingBar; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import org.ksoap2.SoapEnvelope; import org.ksoap2.SoapFault; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapSerializationEnvelope; import org.ksoap2.transport.HttpTransportSE; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.net.SocketTimeoutException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Locale; import static com.app.nevada.nevadaapp.Constants.CUS_FIFTH_COLUMN; import static com.app.nevada.nevadaapp.Constants.CUS_FIRST_COLUMN; import static com.app.nevada.nevadaapp.Constants.CUS_FOURTH_COLUMN; import static com.app.nevada.nevadaapp.Constants.CUS_SECOND_COLUMN; import static com.app.nevada.nevadaapp.Constants.CUS_SEVENTH_COLUMN; import static com.app.nevada.nevadaapp.Constants.CUS_SIXTH_COLUMN; import static com.app.nevada.nevadaapp.Constants.CUS_THIRD_COLUMN; public class RatingReport extends AppCompatActivity { private static final String METHOD_NAME = "getAllCustomer"; private static final String NAMESPACE = "http://192.168.127.12"; private static final String URL = "http://192.168.127.12/AndroidWS/GetInfo.asmx"; final String SOAP_ACTION = "http://192.168.127.12/getAllCustomer"; private ArrayList<HashMap<String, String>> list; SoapObject responseObject; private DatePickerDialog fromDatePickerDialog; private DatePickerDialog toDatePickerDialog; private String varFromDate; private String varToDate; private TextView fromDateEtxt; private TextView toDateEtxt; private SimpleDateFormat dateFormatter; String VarCustomerAccNumber = "0"; String VarIsLate = "0"; String VarIsQtyNotGood = "0"; String VarIsItemNotGood = "0"; String VarRate = "0"; String languges = ""; @Override protected void onDestroy() { Locale locale = new Locale(languges); forceLocale(this, locale); super.onDestroy(); } @Override protected void onResume() { Locale locale = new Locale(languges); forceLocale(this, locale); super.onResume(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_rating_report); new GetAllCustomerTask().execute(); Intent intent = getIntent(); languges = intent.getStringExtra("lang"); Locale locale = new Locale(languges); forceLocale(this, locale); Spinner ddlAllCustomers = (Spinner) findViewById(R.id.spCustomers); ddlAllCustomers.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { if (pos > 0) { StringWithTag sel = (StringWithTag) parent.getItemAtPosition(pos); VarCustomerAccNumber = sel.tag.toString(); } else { VarCustomerAccNumber = "0"; } } public void onNothingSelected(AdapterView<?> parent) { } }); dateFormatter = new SimpleDateFormat("dd-MM-yyyy", Locale.US); findViewsById(); setDateTimeField(); } private void setDateTimeField() { Calendar newCalendar = Calendar.getInstance(); fromDatePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() { public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { Calendar cal = Calendar.getInstance(); cal.set(year, monthOfYear, dayOfMonth); CharSequence output = DateFormat.format("dd-MM-yyyy", cal); fromDateEtxt.setText(output); varFromDate = fromDateEtxt.getText().toString(); varToDate = toDateEtxt.getText().toString(); } }, newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH)); toDatePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() { public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { Calendar cal = Calendar.getInstance(); cal.set(year, monthOfYear, dayOfMonth); CharSequence output = DateFormat.format("dd-MM-yyyy", cal); toDateEtxt.setText(output); varFromDate = fromDateEtxt.getText().toString(); varToDate = toDateEtxt.getText().toString(); } }, newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH)); varFromDate = fromDateEtxt.getText().toString(); varToDate = toDateEtxt.getText().toString(); Locale locale = new Locale(languges); forceLocale(this, locale); } private void findViewsById() { Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); fromDateEtxt = (TextView) findViewById(R.id.tranDateFromFilter); fromDateEtxt.setInputType(InputType.TYPE_NULL); toDateEtxt = (TextView) findViewById(R.id.tranDateToFilter); toDateEtxt.setInputType(InputType.TYPE_NULL); fromDateEtxt.setText("01-01-" + year); Calendar cal = Calendar.getInstance(); CharSequence output = DateFormat.format("dd-MM-yyyy", cal); String[] VarDateVal = (String.valueOf(output).split("-")); int day = Integer.valueOf(VarDateVal[0]); int month = Integer.valueOf(VarDateVal[1]); if (month < 10) { if (day < 10) { toDateEtxt.setText("0" + day + "-0" + month + "-" + year); } else { toDateEtxt.setText(day + "-0" + month + "-" + year); } } else { if (day < 10) { toDateEtxt.setText("0" + day + "-" + month + "-" + year); } else { toDateEtxt.setText(day + "-" + month + "-" + year); } } varFromDate = fromDateEtxt.getText().toString(); varToDate = toDateEtxt.getText().toString(); } public void callDate(View view) { String languageToLoad = "EN-US"; Locale locale = new Locale(languageToLoad); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale; getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics()); if (view == fromDateEtxt) { fromDatePickerDialog.show(); } else if (view == toDateEtxt) { toDatePickerDialog.show(); } } public void SearchOrders(View v) { RadioGroup Access_radioGroup = (RadioGroup) findViewById(R.id.Access_radio_group); RadioGroup dealing_radioGroup = (RadioGroup) findViewById(R.id.dealing_radio_group); RadioGroup view_radiogroup = (RadioGroup) findViewById(R.id.View_radio_group); Access_radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId) { case R.id.late: VarIsItemNotGood = "3"; break; case R.id.latesome: VarIsItemNotGood = "2"; break; default: VarIsItemNotGood = "1"; } } }); dealing_radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId) { case R.id.dealing_goodMiddel: VarIsQtyNotGood = "2"; break; case R.id.dealing_not_good: VarIsQtyNotGood = "3"; break; default: VarIsQtyNotGood = "1"; } } }); view_radiogroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId) { case R.id.view_not_good: VarIsLate = "2"; break; default: VarIsLate = "1"; } } }); RatingBar simpleRatingBar = (RatingBar) findViewById(R.id.repRatingBar); VarRate = String.valueOf(Math.round(simpleRatingBar.getRating())); ImageView imgCurrentSearch = (ImageView) findViewById(R.id.imgCurrentSearch); imgCurrentSearch.setVisibility(View.VISIBLE); new GetSearchResult().execute(); } public void OpenDetails(View v) { ImageView btn = ((ImageView) v); final String[] cuurentValues = btn.getTag().toString().split(",&,"); final Dialog dialog = new Dialog(RatingReport.this); if (languges.contains("en")) { dialog.setTitle("Information"); } else { dialog.setTitle("معلومات"); } Rect displayRectangle = new Rect(); Window window = RatingReport.this.getWindow(); window.getDecorView().getWindowVisibleDisplayFrame(displayRectangle); LayoutInflater inflater = (LayoutInflater) RatingReport.this.getSystemService(RatingReport.this.LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout.search_info_dialog, null); layout.setMinimumWidth((int) (displayRectangle.width() * 0.9f)); layout.setMinimumHeight((int) (displayRectangle.height() * 0.4f)); dialog.setContentView(layout); TextView txtNotes = (TextView) dialog.findViewById(R.id.txtDNote); TextView txtDLate = (TextView) dialog.findViewById(R.id.txtDLate); TextView txtDQNG = (TextView) dialog.findViewById(R.id.txtDQNG); TextView txtDING = (TextView) dialog.findViewById(R.id.txtDING); txtNotes.setText(cuurentValues[0]); Locale locale = Locale.getDefault(); String language = String.valueOf(locale); if (language.contains("en")) { if (cuurentValues[1].equals("1")) { txtDLate.setText("seemly"); } else { txtDLate.setText("unseemly"); } if (cuurentValues[2].equals("1")) { txtDQNG.setText("seemly"); } else if (cuurentValues[2].equals("2")) { txtDQNG.setText("fine"); } else { txtDQNG.setText("unseemly"); } if (cuurentValues[3].equals("1")) { txtDING.setText("on time"); } else if (cuurentValues[3].equals("2")) { txtDING.setText("Delayed slightly"); } else { txtDING.setText("too late"); } } else { if (cuurentValues[1].equals("1")) { txtDLate.setText("لائق"); } else { txtDLate.setText("غير لائق"); } if (cuurentValues[2].equals("1")) { txtDQNG.setText("لائق"); } else if (cuurentValues[2].equals("2")) { txtDQNG.setText("جيد"); } else { txtDQNG.setText("غير لائق"); } if (cuurentValues[3].equals("1")) { txtDING.setText("في الوقت المحدد"); } else if (cuurentValues[3].equals("2")) { txtDING.setText("تاخر قليلا"); } else { txtDING.setText("تاخر كثيرا"); } } dialog.show(); } public void deleteSearsh(View view) { RadioGroup Access_radioGroup = (RadioGroup) findViewById(R.id.Access_radio_group); RadioGroup dealing_radioGroup = (RadioGroup) findViewById(R.id.dealing_radio_group); RadioGroup view_radiogroup = (RadioGroup) findViewById(R.id.View_radio_group); Access_radioGroup.clearCheck(); dealing_radioGroup.clearCheck(); view_radiogroup.clearCheck(); VarIsLate = "0"; VarIsQtyNotGood = "0"; VarIsItemNotGood = "0"; } class GetAllCustomerTask extends AsyncTask<Integer, Integer, String> { @Override protected String doInBackground(Integer... params) { try { SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.dotNet = true; envelope.setOutputSoapObject(request); HttpTransportSE androidHttpTransport = new HttpTransportSE(URL, 1000000000); androidHttpTransport.debug = true; androidHttpTransport.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); androidHttpTransport.call(SOAP_ACTION, envelope); responseObject = (SoapObject) envelope.getResponse(); Integer x = 1; } catch (SoapFault soapFault) { soapFault.printStackTrace(); } catch (XmlPullParserException e) { e.printStackTrace(); } catch (SocketTimeoutException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return "Task Completed."; } @Override protected void onPostExecute(String result) { Spinner ddlAllCustomers = (Spinner) findViewById(R.id.spCustomers); List<StringWithTag> AllCustomers = new ArrayList<StringWithTag>(); AllCustomers.add(new StringWithTag("جميع العملاء", "0")); for (int i = 0; i < responseObject.getPropertyCount(); i++) { String[] reponseArrayString = responseObject.getProperty(i).toString().split("&&"); if (reponseArrayString.length == 3) { AllCustomers.add(new StringWithTag(reponseArrayString[1].toString(), reponseArrayString[2].toString())); } } ArrayAdapter<StringWithTag> spLocationAdapter = new ArrayAdapter<StringWithTag>(RatingReport.this, android.R.layout.simple_spinner_dropdown_item, AllCustomers); ddlAllCustomers.setAdapter(spLocationAdapter); } @Override protected void onPreExecute() { } @Override protected void onProgressUpdate(Integer... values) { } } class GetSearchResult extends AsyncTask<Integer, Integer, String> { @Override protected String doInBackground(Integer... params) { try { SoapObject request = new SoapObject(NAMESPACE, "getComplaints"); request.addProperty("VarCustID", VarCustomerAccNumber); request.addProperty("VarRate", VarRate); request.addProperty("VarIsLate", VarIsLate); request.addProperty("VarIsQtyNotGood", VarIsQtyNotGood); request.addProperty("VarIsItemNotGood", VarIsItemNotGood); request.addProperty("VarFromDate", varFromDate); request.addProperty("VarToDate", varToDate); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.dotNet = true; envelope.setOutputSoapObject(request); HttpTransportSE androidHttpTransport = new HttpTransportSE(URL, 1000000000); androidHttpTransport.debug = true; androidHttpTransport.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); androidHttpTransport.call("http://3172.16.31.10/getComplaints", envelope); responseObject = (SoapObject) envelope.getResponse(); Integer x = 1; } catch (SoapFault soapFault) { soapFault.printStackTrace(); } catch (XmlPullParserException e) { e.printStackTrace(); } catch (SocketTimeoutException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return "Task Completed."; } @Override protected void onPostExecute(String result) { ListView listView = (ListView) findViewById(R.id.lvSearchResults); list = new ArrayList<HashMap<String, String>>(); ListViewAdaptersSearch adapter = new ListViewAdaptersSearch(RatingReport.this, list); listView.setAdapter(adapter); for (int i = 0; i < responseObject.getPropertyCount(); i++) { String[] reponseArrayString = responseObject.getProperty(i).toString().split("&&"); HashMap<String, String> temp = new HashMap<String, String>(); int count = reponseArrayString.length; temp.put(CUS_FIRST_COLUMN, reponseArrayString[0]); temp.put(CUS_SECOND_COLUMN, reponseArrayString[1]); temp.put(CUS_THIRD_COLUMN, reponseArrayString[2]); temp.put(CUS_FOURTH_COLUMN, reponseArrayString[3]); temp.put(CUS_FIFTH_COLUMN, reponseArrayString[4]); temp.put(CUS_SIXTH_COLUMN, reponseArrayString[5]); temp.put(CUS_SEVENTH_COLUMN, reponseArrayString[6]); list.add(temp); } adapter = new ListViewAdaptersSearch(RatingReport.this, list); listView.setAdapter(adapter); ImageView imgCurrentSearch = (ImageView) findViewById(R.id.imgCurrentSearch); imgCurrentSearch.setVisibility(View.INVISIBLE); } @Override protected void onPreExecute() { } @Override protected void onProgressUpdate(Integer... values) { } } public static void forceLocale(Context ctx, Locale locale) { Configuration conf = ctx.getResources().getConfiguration(); conf.locale = locale; ctx.getResources().updateConfiguration(conf, ctx.getResources().getDisplayMetrics()); Configuration systemConf = Resources.getSystem().getConfiguration(); systemConf.locale = locale; Resources.getSystem().updateConfiguration(systemConf, Resources.getSystem().getDisplayMetrics()); Locale.setDefault(locale); } }
20,140
0.611823
0.604296
488
40.112705
27.681398
172
false
false
0
0
0
0
0
0
0.731557
false
false
11
e4bcdc3f879b940e173cd3cf8ac6062b35b61960
11,811,160,073,469
b2cf625e9cb2e0bc3db26ef71f08eaa729d05cc2
/portal-corretor-servico/src/main/java/br/com/odontoprev/portal/corretor/model/TbodResponsavelContratual.java
6541825172460ed9ab0baee97a7f3d6af8f78fbe
[]
no_license
jeanantunes/projetocorapi
https://github.com/jeanantunes/projetocorapi
81aa4eee3066151f94166fd589518373891aec46
6109fa19edd65ab810947687cc9ee46a6996c02e
refs/heads/master
2020-04-04T12:28:00.346000
2018-04-24T14:03:56
2018-04-24T14:03:56
155,927,194
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.odontoprev.portal.corretor.model; import java.io.Serializable; import javax.persistence.*; import java.util.Date; import java.util.List; /** * The persistent class for the TBOD_RESPONSAVEL_CONTRATUAL database table. * */ @Entity @Table(name="TBOD_RESPONSAVEL_CONTRATUAL") @NamedQuery(name="TbodResponsavelContratual.findAll", query="SELECT t FROM TbodResponsavelContratual t") public class TbodResponsavelContratual implements Serializable { private static final long serialVersionUID = 1L; @Id @SequenceGenerator(name = "SEQ_TBOD_RESP_CONTR", sequenceName = "SEQ_TBOD_RESP_CONTR", allocationSize = 1, initialValue = 1) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_TBOD_RESP_CONTR") @Column(name="CD_RESPONSAVEL_CONTRATUAL") private Long cdResponsavelContratual; private String celular; private String cpf; @Temporal(TemporalType.DATE) @Column(name="DATA_NASCIMENTO") private Date dataNascimento; private String email; private String nome; private String sexo; //bi-directional many-to-one association to TbodEndereco @ManyToOne @JoinColumn(name="CD_ENDERECO") private TbodEndereco tbodEndereco; //bi-directional many-to-one association to TbodVenda @OneToMany(mappedBy="tbodResponsavelContratual") private List<TbodVenda> tbodVendas; public TbodResponsavelContratual() { } public Long getCdResponsavelContratual() { return this.cdResponsavelContratual; } public void setCdResponsavelContratual(Long cdResponsavelContratual) { this.cdResponsavelContratual = cdResponsavelContratual; } public String getCelular() { return this.celular; } public void setCelular(String celular) { this.celular = celular; } public String getCpf() { return this.cpf; } public void setCpf(String cpf) { this.cpf = cpf; } public Date getDataNascimento() { return this.dataNascimento; } public void setDataNascimento(Date dataNascimento) { this.dataNascimento = dataNascimento; } public String getEmail() { return this.email; } public void setEmail(String email) { this.email = email; } public String getNome() { return this.nome; } public void setNome(String nome) { this.nome = nome; } public String getSexo() { return this.sexo; } public void setSexo(String sexo) { this.sexo = sexo; } public TbodEndereco getTbodEndereco() { return this.tbodEndereco; } public void setTbodEndereco(TbodEndereco tbodEndereco) { this.tbodEndereco = tbodEndereco; } public List<TbodVenda> getTbodVendas() { return this.tbodVendas; } public void setTbodVendas(List<TbodVenda> tbodVendas) { this.tbodVendas = tbodVendas; } public TbodVenda addTbodVenda(TbodVenda tbodVenda) { getTbodVendas().add(tbodVenda); tbodVenda.setTbodResponsavelContratual(this); return tbodVenda; } public TbodVenda removeTbodVenda(TbodVenda tbodVenda) { getTbodVendas().remove(tbodVenda); tbodVenda.setTbodResponsavelContratual(null); return tbodVenda; } }
UTF-8
Java
3,116
java
TbodResponsavelContratual.java
Java
[]
null
[]
package br.com.odontoprev.portal.corretor.model; import java.io.Serializable; import javax.persistence.*; import java.util.Date; import java.util.List; /** * The persistent class for the TBOD_RESPONSAVEL_CONTRATUAL database table. * */ @Entity @Table(name="TBOD_RESPONSAVEL_CONTRATUAL") @NamedQuery(name="TbodResponsavelContratual.findAll", query="SELECT t FROM TbodResponsavelContratual t") public class TbodResponsavelContratual implements Serializable { private static final long serialVersionUID = 1L; @Id @SequenceGenerator(name = "SEQ_TBOD_RESP_CONTR", sequenceName = "SEQ_TBOD_RESP_CONTR", allocationSize = 1, initialValue = 1) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_TBOD_RESP_CONTR") @Column(name="CD_RESPONSAVEL_CONTRATUAL") private Long cdResponsavelContratual; private String celular; private String cpf; @Temporal(TemporalType.DATE) @Column(name="DATA_NASCIMENTO") private Date dataNascimento; private String email; private String nome; private String sexo; //bi-directional many-to-one association to TbodEndereco @ManyToOne @JoinColumn(name="CD_ENDERECO") private TbodEndereco tbodEndereco; //bi-directional many-to-one association to TbodVenda @OneToMany(mappedBy="tbodResponsavelContratual") private List<TbodVenda> tbodVendas; public TbodResponsavelContratual() { } public Long getCdResponsavelContratual() { return this.cdResponsavelContratual; } public void setCdResponsavelContratual(Long cdResponsavelContratual) { this.cdResponsavelContratual = cdResponsavelContratual; } public String getCelular() { return this.celular; } public void setCelular(String celular) { this.celular = celular; } public String getCpf() { return this.cpf; } public void setCpf(String cpf) { this.cpf = cpf; } public Date getDataNascimento() { return this.dataNascimento; } public void setDataNascimento(Date dataNascimento) { this.dataNascimento = dataNascimento; } public String getEmail() { return this.email; } public void setEmail(String email) { this.email = email; } public String getNome() { return this.nome; } public void setNome(String nome) { this.nome = nome; } public String getSexo() { return this.sexo; } public void setSexo(String sexo) { this.sexo = sexo; } public TbodEndereco getTbodEndereco() { return this.tbodEndereco; } public void setTbodEndereco(TbodEndereco tbodEndereco) { this.tbodEndereco = tbodEndereco; } public List<TbodVenda> getTbodVendas() { return this.tbodVendas; } public void setTbodVendas(List<TbodVenda> tbodVendas) { this.tbodVendas = tbodVendas; } public TbodVenda addTbodVenda(TbodVenda tbodVenda) { getTbodVendas().add(tbodVenda); tbodVenda.setTbodResponsavelContratual(this); return tbodVenda; } public TbodVenda removeTbodVenda(TbodVenda tbodVenda) { getTbodVendas().remove(tbodVenda); tbodVenda.setTbodResponsavelContratual(null); return tbodVenda; } }
3,116
0.72561
0.724647
137
20.759125
23.304562
125
false
false
0
0
0
0
0
0
1.131387
false
false
11
55a4b46ff6870cff5b057b131a5175901bd40760
5,214,090,320,685
0658955d5566b747cd39f5815ac5298354c4548c
/src/main/java/com/cn/message/chapter04/demo02/StartApplication.java
445cacb0b699529909bac71b1fac1dd8d62f5ded
[]
no_license
yangzhongming/message-learn
https://github.com/yangzhongming/message-learn
95c585bf84ca6277879edb702186bd4ef006d250
104d774f7d140e960ac7dd8cfe65b5b75a1a2c83
refs/heads/master
2021-07-18T16:41:23.853000
2019-11-15T02:10:17
2019-11-15T02:10:17
218,186,794
0
0
null
false
2020-10-13T17:25:23
2019-10-29T02:24:24
2019-11-15T02:10:26
2020-10-13T17:25:22
76
0
0
1
Java
false
false
package com.cn.message.chapter04.demo02; import org.springframework.context.ApplicationContext; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * @author:Alex * @date:2019/11/5 * @version:1.0 * @description: */ public class StartApplication { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-jms.xml"); MessageService messageService = (MessageService) ctx.getBean("messageService"); messageService.sendQueueMessage("我的测试消息1..."); messageService.sendTopicMessage("我的测试消息2..."); messageService.sendTopicMessage("我的测试消息3..."); } }
UTF-8
Java
781
java
StartApplication.java
Java
[ { "context": "t.ClassPathXmlApplicationContext;\n\n/**\n * @author:Alex\n * @date:2019/11/5\n * @version:1.0\n * @descriptio", "end": 263, "score": 0.9987047910690308, "start": 259, "tag": "NAME", "value": "Alex" } ]
null
[]
package com.cn.message.chapter04.demo02; import org.springframework.context.ApplicationContext; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * @author:Alex * @date:2019/11/5 * @version:1.0 * @description: */ public class StartApplication { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-jms.xml"); MessageService messageService = (MessageService) ctx.getBean("messageService"); messageService.sendQueueMessage("我的测试消息1..."); messageService.sendTopicMessage("我的测试消息2..."); messageService.sendTopicMessage("我的测试消息3..."); } }
781
0.746309
0.724832
21
34.476189
28.962404
87
false
false
0
0
0
0
0
0
0.428571
false
false
11
0c07a1507457d604314ebbe3c7b8ef0aa8b063da
24,678,882,105,695
71e2b41ab2f5ed6d10039fddc1e38d53704d5156
/src/main/java/com/am/cs12/config/AmLogVO.java
9332cc99bde90b4ddabc031f75f4bf635f7cc8ce
[]
no_license
huaxbo/door
https://github.com/huaxbo/door
aa6a0ac45e0a3b014e8d66f60e8412afc273ccf7
9d4ad42abcfb69e38607877dabc5473a1aa4f6a2
refs/heads/master
2020-03-21T10:38:31.353000
2018-07-26T14:20:48
2018-07-26T14:20:48
138,462,734
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.am.cs12.config; import java.io.File; public class AmLogVO { //日志文件存储目录(相对目录) --> public String logDir ; //日志文件最大字节数(KB) public int fileMaxSize ; //日志文件最大文件数 public int fileMaxNum ; public AmLogVO(){ this.logDir = "amLog/"; this.fileMaxSize = 1000 ; this.fileMaxNum = 2 ; } }
UTF-8
Java
387
java
AmLogVO.java
Java
[]
null
[]
package com.am.cs12.config; import java.io.File; public class AmLogVO { //日志文件存储目录(相对目录) --> public String logDir ; //日志文件最大字节数(KB) public int fileMaxSize ; //日志文件最大文件数 public int fileMaxNum ; public AmLogVO(){ this.logDir = "amLog/"; this.fileMaxSize = 1000 ; this.fileMaxNum = 2 ; } }
387
0.633027
0.611621
20
14.35
10.673682
27
false
false
0
0
0
0
0
0
1.15
false
false
11
3a2f6ca9fa16887aaa3612bb8e58de05cc1ab82d
18,545,668,809,950
2917a3312b73cf74b19f1846cf0618dc28359eb8
/encryptor/src/main/java/encryptor/encryptor/algorithms/appliers/DecryptionApplier.java
a7ebdc7859373bd253719f24058191b7d0aa632b
[]
no_license
Sergey7773/Encryptor
https://github.com/Sergey7773/Encryptor
19dc735c7835bc45d77bc5d07f3e356602cff4b8
0b21ad16d06ba4034eb4288150ea97e0b93bdf41
refs/heads/master
2021-01-20T19:36:22.007000
2016-08-10T17:28:19
2016-08-10T17:28:19
64,579,205
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package encryptor.encryptor.algorithms.appliers; import lombok.NonNull; import encryptor.encryptor.algorithms.EncryptionAlgorithm; import encryptor.encryptor.interfaces.Key; public class DecryptionApplier implements ActionApplier { private EncryptionAlgorithm m_algorithm; public DecryptionApplier(@NonNull EncryptionAlgorithm alg) { this.m_algorithm=alg; } public Byte apply(Byte val,Key key) { return m_algorithm.decrypt(val, key); } }
UTF-8
Java
453
java
DecryptionApplier.java
Java
[]
null
[]
package encryptor.encryptor.algorithms.appliers; import lombok.NonNull; import encryptor.encryptor.algorithms.EncryptionAlgorithm; import encryptor.encryptor.interfaces.Key; public class DecryptionApplier implements ActionApplier { private EncryptionAlgorithm m_algorithm; public DecryptionApplier(@NonNull EncryptionAlgorithm alg) { this.m_algorithm=alg; } public Byte apply(Byte val,Key key) { return m_algorithm.decrypt(val, key); } }
453
0.80574
0.80574
18
24.166666
23.044041
61
false
false
0
0
0
0
0
0
1.055556
false
false
11
51764131a54eb5c26d66459a9280f1e0da1bc56a
27,590,869,935,545
6fcfbf492a9d327bb65d6de2c8c47f4e0487157e
/changgou/chougou-parent/changgou-service/changgou-service-file/src/main/java/com/changgou/FileApplication.java
b695b0b7a83887ad4c7bcd82e45fbd7c2a067999
[]
no_license
gigihuangM/mypro-changgou
https://github.com/gigihuangM/mypro-changgou
42cf0f8eb1a0bf4c57c0576dd14e5cce52032562
3f1a07ddcd82e8990d5592a1716c539589b692df
refs/heads/master
2022-12-17T13:12:24.128000
2020-09-29T05:44:16
2020-09-29T05:44:16
299,510,093
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.changgou; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; @EnableEurekaClient @SpringBootApplication(exclude = DataSourceAutoConfiguration.class) public class FileApplication { public static void main(String[] args) { SpringApplication.run(FileApplication.class,args); } }
UTF-8
Java
525
java
FileApplication.java
Java
[]
null
[]
package com.changgou; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; @EnableEurekaClient @SpringBootApplication(exclude = DataSourceAutoConfiguration.class) public class FileApplication { public static void main(String[] args) { SpringApplication.run(FileApplication.class,args); } }
525
0.828571
0.828571
16
31.8125
28.699345
79
false
false
0
0
0
0
0
0
0.4375
false
false
11
7aa455ae7b6ac4b805df777ac251bf3b34c95692
16,277,926,094,157
565ae0e4b864a79d661c7fa476c9f470b0662f89
/Java/hw1/UserName.java
0d45f4e8662b29f6123fcd07ad6992fe72e5c2a0
[]
no_license
chjlarson/Classwork
https://github.com/chjlarson/Classwork
4a01e46bd22fb0aee1d58f2132e66d8306ebe39f
59bef084c0eeb643c24f6b4b2d5b536fdf788cf1
refs/heads/master
2021-07-11T22:44:50.048000
2017-10-10T20:51:10
2017-10-10T20:51:10
106,466,079
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// Christopher Larson // CSCI 239 Homework #1, Poblem #2 // UserName.java // 1/22/14 // // This program computes a user name for the user. import java.util.Scanner; public class UserName { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("To determine your user name, "); System.out.print("Enter your first name: "); String firstName = scan.nextLine(); System.out.print("Enter your last name: "); String lastName = scan.nextLine(); System.out.println(firstName + " " + lastName + " has the user name " + firstName.toLowerCase().charAt(0) + lastName.toLowerCase().substring(0,6) + "."); } }
UTF-8
Java
737
java
UserName.java
Java
[ { "context": "// Christopher Larson\n// CSCI 239 Homework #1, Poblem #2\n// UserName.ja", "end": 21, "score": 0.9998258352279663, "start": 3, "tag": "NAME", "value": "Christopher Larson" } ]
null
[]
// <NAME> // CSCI 239 Homework #1, Poblem #2 // UserName.java // 1/22/14 // // This program computes a user name for the user. import java.util.Scanner; public class UserName { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("To determine your user name, "); System.out.print("Enter your first name: "); String firstName = scan.nextLine(); System.out.print("Enter your last name: "); String lastName = scan.nextLine(); System.out.println(firstName + " " + lastName + " has the user name " + firstName.toLowerCase().charAt(0) + lastName.toLowerCase().substring(0,6) + "."); } }
725
0.614654
0.597015
24
29.583334
22.901814
77
false
false
0
0
0
0
0
0
0.458333
false
false
11
28efd3207eab7072f217d481a920e94c2950a8aa
30,571,577,266,272
56cd6c71083ea0ca4df72bf957bd7d637b575309
/mediatek/stereo/photopicker/src/com/mediatek/photopicker/utils/Utils.java
d5d32df41577f3e3c83da2f89cdb6088fb613755
[]
no_license
fuchao/mtkgalleryO
https://github.com/fuchao/mtkgalleryO
2c69623a3901828a31de04fd2430686fb8653aec
8fd356b42b95006efb57d1a7e75ad2c5a7044411
refs/heads/master
2020-04-12T18:52:40.440000
2018-05-22T08:20:06
2018-05-22T08:20:06
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mediatek.photopicker.utils; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.ResolveInfo; import android.content.res.Resources; import android.database.Cursor; import android.database.sqlite.SQLiteException; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.net.Uri; import android.provider.MediaStore; import android.provider.MediaStore.Images; import android.view.LayoutInflater; import android.view.View; import com.mediatek.photopicker.PhotoPicker; import com.mediatek.photopicker.PhotoPicker.Config; import com.mediatek.photopicker.data.AlbumItem; import com.mediatek.photopicker.data.FileItem; import com.mediatek.photopicker.data.Item; import com.mediatek.photopicker.hook.AlbumModelHook; import com.mediatek.photopicker.hook.AlbumSetModelHook; import com.mediatek.photopicker.hook.DefaultControlHook; import com.mediatek.photopicker.hook.DefaultViewHook; import com.mediatek.photopicker.hook.IControlHook; import com.mediatek.photopicker.hook.IViewHook; import java.util.List; /** * Common tools for PhotoPicker. */ public class Utils { private static final String TAG = "PhotoPicker/Utils"; private static final String TAG_PPDEBUG = "PPDEBUG"; public static final String BEGIN = "begin ..."; public static final String END = "end"; public static final String PPISSUE = "/sdcard/.photopickerIssue"; public static final boolean ISTRACE = android.util.Log.isLoggable(TAG_PPDEBUG, android.util.Log.VERBOSE); // For identity ID in Glide public static final String ID_PP_GLIDE = "ID_PhotoPicker"; public static final String PACKAGE_PHOTOPICKER = "com.mediatek.photopicker"; public static final String ACTION_PP_PICK = "com.mediatek.action.photopicker.PICK"; // For cursor performance optimization public static final Uri URIBASE = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; public static final String ORDER_ASC = "datetaken ASC"; public static final String ORDER_DESC = "datetaken DESC"; public static final String CUR_ID = Images.Media._ID; public static final String CUR_DATA = Images.Media.DATA; public static final String CUR_BUCKET_ID = Images.Media.BUCKET_ID; public static final String CUR_BUCKET_NAME = Images.Media.BUCKET_DISPLAY_NAME; private static Paint sTextPaint = null; private static Paint sStripPaint = null; private static Bitmap sFolderIcon = null; // Cache size public static final int ARRAY_SIZE = 80; // Visual item in gridView on screen public static final int SCREEN_VIS_SIZE = 18; // Show subtitle name under each item public static final int SUBTITLE_SIZE = 12; /** * Append albums into list after query database. * @param list The query result * @param context The context * @param projection null * @param selection null * @param selectionArgs null * @param sortOrder null * @param queryStart Query start position * @param queryEnd Query end position */ public static void appendAlbumItems(List<Item> list, Context context, String[] projection, String selection, String[] selectionArgs, String sortOrder, int queryStart, int queryEnd) { Log.d(TAG, "<appendAlbumItems> " + "queryStart-queryEnd: " + queryStart + "-" + queryEnd); Uri uri = URIBASE.buildUpon() .appendQueryParameter("limit", queryStart + "," + (queryEnd - queryStart + 1)) .build(); projection = new String[] { "distinct " + CUR_BUCKET_ID, CUR_BUCKET_NAME }; Cursor cursor = getCursor(context, uri, projection, selection, selectionArgs, sortOrder); if (!checkCursor(cursor)) { Log.d(TAG, "<appendAlbumItems> cursor invalid, do nothing."); return; } cursor.moveToFirst(); while (!cursor.isAfterLast()) { int bucketId = cursor.getInt(cursor.getColumnIndex(CUR_BUCKET_ID)); String bucketName = cursor.getString(cursor.getColumnIndex(CUR_BUCKET_NAME)); Log.d(TAG, "<appendAlbumItems> " + "bucketId & Name: " + bucketId + " " + bucketName); if (null != bucketName) { AlbumItem albumItem = new AlbumItem(); albumItem.bucketId = bucketId; albumItem.bucketName = bucketName; list.add(albumItem); } cursor.moveToNext(); } if (null != cursor) { cursor.close(); } // Do query again projection = new String[] { CUR_ID, CUR_DATA, CUR_BUCKET_ID }; String selectionOfItem = selection + " AND " + CUR_BUCKET_ID + " = ?"; int size = selectionArgs.length; String [] selectionArgsOfItem = new String[size+1]; for (int index = 0; index < size; index++) { selectionArgsOfItem[index] = selectionArgs[index]; } for (Item item : list) { Log.d(TAG, "<appendAlbumItems> " + "list size: " + list.size()); selectionArgsOfItem[size] = String.valueOf(((AlbumItem) item).bucketId); uri = URIBASE.buildUpon().appendQueryParameter("limit", 0 + "," + 1).build(); cursor = getCursor(context, uri, projection, selectionOfItem, selectionArgsOfItem, Utils.ORDER_DESC); if (!checkCursor(cursor)) { Log.d(TAG, "<appendAlbumItems> cursor invalid, do nothing."); return; } cursor.moveToFirst(); while (!cursor.isAfterLast()) { String path = cursor.getString(cursor.getColumnIndex(CUR_DATA)); if (null != path) { String id = cursor.getString(cursor.getColumnIndex(CUR_ID)); Uri uri2 = URIBASE.buildUpon().appendPath(id).build(); item.pathUri = uri2; } cursor.moveToNext(); } if (null != cursor) { cursor.close(); } } } /** * Append files into list after query database. * @param list The query result * @param context The context * @param projection null * @param selection null * @param selectionArgs null * @param sortOrder null * @param queryStart Query start position * @param queryEnd Query end position */ public static void appendFileItems(List<Item> list, Context context, String[] projection, String selection, String[] selectionArgs, String sortOrder, int queryStart, int queryEnd) { Log.d(TAG, "<appendFileItems> queryStart & queryEnd: " + queryStart + " " + queryEnd); Uri uri = URIBASE.buildUpon() .appendQueryParameter("limit", queryStart + "," + (queryEnd - queryStart + 1)) .build(); FileItem fileItem = null; projection = new String[] { CUR_ID, CUR_DATA }; Cursor cursor = getCursor(context, uri, projection, selection, selectionArgs, sortOrder); if (!checkCursor(cursor)) { Log.d(TAG, "<appendFileItems> cursor invalid, do nothing."); return; } cursor.moveToFirst(); while (!cursor.isAfterLast()) { String id = cursor.getString(cursor.getColumnIndex(CUR_ID)); String filePath = cursor.getString(cursor.getColumnIndex(CUR_DATA)); Uri uri2 = URIBASE.buildUpon().appendPath(id).build(); Log.d(TAG, "<appendFileItems> uri2 & filePath: " + uri2 + " " + filePath); if (null != filePath) { fileItem = new FileItem(); fileItem.pathUri = uri2; list.add(fileItem); } cursor.moveToNext(); } if (null != cursor) { cursor.close(); } } /** * Draw over lay on each item. * @param context Current context * @param canvas To be drew * @param title The text was shown at the corner of each item */ public static void drawSlotLabel(Context context, Canvas canvas, String title) { // Basic setup for drawing float canvasSize = canvas.getHeight(); canvas.translate(0, canvasSize); // Draw transparent strip RectF rect = new RectF(0, -canvasSize / 5, canvasSize, canvasSize); canvas.drawRect(rect, getStripPaint(context)); // Draw icon rect = new RectF(0, -canvasSize / 5, canvasSize / 5, 0); canvas.drawBitmap(getBitmapIconFolder(context), null, rect, null); // Draw text canvas.drawText(title, canvasSize / 5, -canvasSize / 15, getTextPaint(context)); } /** * Get instance of AlbumSetModelHook. * @param context Current context * @return AlbumSetModelHook */ public static AlbumSetModelHook getAlbumSetModelHook(Context context) { return new AlbumSetModelHook(context); } /** * Get instance of AlbumModeHook. * @param context Current context * @param bucketId Click bucket_id * @return AlbumModeHook */ public static AlbumModelHook getAlbumModelHook(Context context, int bucketId) { return new AlbumModelHook(context, bucketId); } /** * Get default viewHook. * @param context Current context * @return IViewHook */ public static IViewHook getViewHook(Context context) { IViewHook viewHook = new DefaultViewHook(context); return viewHook; } /** * Get default controlHook. * @return IControlHook. */ public static IControlHook getControlHook() { return new DefaultControlHook(); } /** * Get cursor by context and conditions. * @param context Current context * @param uri null * @param projection null * @param selection null * @param selectionArgs null * @param sortOrder null * @return Cursor Return cursor */ public static Cursor getCursor(Context context, Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { if (ISTRACE) { Log.d(TAG, "<getCursor> " + "cursor infos as follow: " + "\n\t" + "<getCursor> " + "projection: " + projection + "\n\t" + "<getCursor> " + "selection: " + selection + "\n\t" + "<getCursor> " + "selectionArgs: " + selectionArgs + "\n\t" + "<getCursor> " + "sortOrder: " + sortOrder + "\n"); } Cursor cursor = null; try { cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder); Log.d(TAG, "<getCursor> cursor: " + cursor); } catch (IllegalStateException e) { Log.d(TAG, "<getCursor> query IllegalStateException: " + e.getMessage()); } catch (SQLiteException e) { Log.d(TAG, "<getCursor> query SQLiteException: " + e.getMessage()); } return cursor; } /** * For check the state of PhotoPicker.Config. * @param config PhotoPicker.Config */ public static void debugConfig(Config config) { if (ISTRACE) { Log.d(TAG, "<debugConfig> " + "config infos as follow: " + "\n\t" + "<debugConfig> " + "config.titleId: " + config.title + "\n\t" + "<debugConfig> " + "config.subTitleId: " + config.subTitle + "\n\t" + "<debugConfig> " + "config.controlHook: " + config.controlHook + "\n\t" + "<debugConfig> " + "config.viewHook: " + config.viewHook + "\n\t" + "<debugConfig> " + "config.modelHook: " + config.modelHook + "\n"); } else { Log.d(TAG, "<debugConfig> " + "ISDEBUG: " + ISTRACE + ", show nothing"); } } /** * Launch PhotoPicker from 3rd apps, Can launch PhotoPicker as follow code. * {@code * Intent intent = new Intent(ACTION_PP_PICK); * startActivityForResult(intent, PhotoPicker.REQUEST_CODE); * }, Or luanch PhotoPicker by function {@code launchPhotoPicker3rd} * @param context Current context */ public static void launchPhotoPicker3rd(Context context) { PackageInfo packageInfo = null; try { packageInfo = context.getPackageManager().getPackageInfo(PACKAGE_PHOTOPICKER, 0); } catch (NameNotFoundException e) { packageInfo = null; e.printStackTrace(); } if (packageInfo == null) { Log.d(TAG, "<launchPhotoPicker3rd> " + PACKAGE_PHOTOPICKER + " haven't installed"); } else { Intent resolveIntent = new Intent(ACTION_PP_PICK, null); resolveIntent.setPackage(packageInfo.packageName); Log.d(TAG, "<launchPhotoPicker3rd> " + "resolveIntent: " + resolveIntent); List<ResolveInfo> apps = context.getPackageManager().queryIntentActivities(resolveIntent, 0); ResolveInfo resolveInfo = apps.iterator().next(); if (resolveInfo != null) { Log.d(TAG, "<launchPhotoPicker3rd> " + "resolveInfo: " + resolveInfo); String packageNameTemp = resolveInfo.activityInfo.packageName; String className = resolveInfo.activityInfo.name; Log.d(TAG, "<launchPhotoPicker3rd> " + "packageNameTemp & className: " + packageNameTemp + "-" + className); Intent intent = new Intent(ACTION_PP_PICK); ComponentName cn = new ComponentName(packageNameTemp, className); intent.setComponent(cn); ((Activity) context).startActivityForResult(intent, PhotoPicker.REQUEST_CODE); } } } /** * Return a resource identifier for the given resource name in PhotoPicker package. * @param context the Android Context * @param name resource name * @param defType resource type * @return resource identifier */ public static int getMyResId(Context context, String name, String defType) { return getMyResources(context).getIdentifier(name, defType, PACKAGE_PHOTOPICKER); } /** * Get view by inflating a layout file in PhotoPicker package.<br/> * Warning: layout is unsafe to write in xml file for a library PhotoPicker.<br/> * e.g. it's unsafe to use xml properties defined in non-android namespace. * @param context the Android Context * @param name layout file name * @return view for the layout file */ public static View getMyLayout(Context context, String name) { LayoutInflater inflater = LayoutInflater.from(context); View view = inflater.inflate( getMyResources(context).getLayout( getMyResId(context, name, "layout")), null); return view; } /** * Get drawable in PhotoPicker package. * @param context the Android Context * @param name drawable name * @return drawable of the given name */ public static Drawable getMyDrawable(Context context, String name) { int id = getMyResId(context, name, "drawable"); return getMyResources(context).getDrawable(id); } /** * Get string in PhotoPicker package. * @param context the Android Context * @param name string name * @return string of the given name */ public static String getMyString(Context context, String name) { int id = getMyResId(context, name, "string"); return getMyResources(context).getString(id); } /** * Get dimension in PhotoPicker package. * @param context the Android Context * @param name dimension name * @return dimension of the given name */ public static float getMyDimension(Context context, String name) { int id = getMyResId(context, name, "dimen"); return getMyResources(context).getDimension(id); } /** * Get dimension in PhotoPicker package. * @param context the Android Context * @param name dimension name * @return dimension of the given name */ public static int getMyDimensionPixelSize(Context context, String name) { int id = getMyResId(context, name, "dimen"); return getMyResources(context).getDimensionPixelSize(id); } /** * Get color in PhotoPicker package. * @param context the Android Context * @param name color name * @return color of the given name */ public static int getMyColor(Context context, String name) { int id = getMyResId(context, name, "color"); return getMyResources(context).getColor(id); } private static Resources getMyResources(Context context) { Resources myResources = null; PackageManager pm = context.getPackageManager(); try { myResources = pm.getResourcesForApplication(PACKAGE_PHOTOPICKER); } catch (NameNotFoundException e) { Log.e(TAG, "No resources found in PhotoPicker"); } return myResources; } private static Paint getTextPaint(Context context) { if (null == sTextPaint) { sTextPaint = new Paint(); sTextPaint.setAntiAlias(true); sTextPaint.setColor(getMyColor(context, "label_text")); sTextPaint.setTextSize(getMyDimension(context, "label_font_size")); sTextPaint.setStrokeWidth(1.5f); } return sTextPaint; } private static Paint getStripPaint(Context context) { if (null == sStripPaint) { Resources res = getMyResources(context); sStripPaint = new Paint(); int colorId = getMyResId(context, "label_background", "color"); sStripPaint.setColor(res.getColor(colorId)); } return sStripPaint; } private static Bitmap getBitmapIconFolder(Context context) { if (null == sFolderIcon) { int id = getMyResId(context, "ic_folder", "drawable"); Resources res = getMyResources(context); sFolderIcon = BitmapFactory.decodeResource(res, id); } return sFolderIcon; } private static boolean checkCursor(Cursor cursor) { if (cursor == null ) { Log.d(TAG, "<checkCursor> cursor is null, do nothing"); return false; } else { if (!cursor.moveToFirst()) { Log.d(TAG, "<checkCursor> cursor is not null, but it's empty."); return false; } return true; } } }
UTF-8
Java
19,146
java
Utils.java
Java
[]
null
[]
package com.mediatek.photopicker.utils; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.ResolveInfo; import android.content.res.Resources; import android.database.Cursor; import android.database.sqlite.SQLiteException; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.net.Uri; import android.provider.MediaStore; import android.provider.MediaStore.Images; import android.view.LayoutInflater; import android.view.View; import com.mediatek.photopicker.PhotoPicker; import com.mediatek.photopicker.PhotoPicker.Config; import com.mediatek.photopicker.data.AlbumItem; import com.mediatek.photopicker.data.FileItem; import com.mediatek.photopicker.data.Item; import com.mediatek.photopicker.hook.AlbumModelHook; import com.mediatek.photopicker.hook.AlbumSetModelHook; import com.mediatek.photopicker.hook.DefaultControlHook; import com.mediatek.photopicker.hook.DefaultViewHook; import com.mediatek.photopicker.hook.IControlHook; import com.mediatek.photopicker.hook.IViewHook; import java.util.List; /** * Common tools for PhotoPicker. */ public class Utils { private static final String TAG = "PhotoPicker/Utils"; private static final String TAG_PPDEBUG = "PPDEBUG"; public static final String BEGIN = "begin ..."; public static final String END = "end"; public static final String PPISSUE = "/sdcard/.photopickerIssue"; public static final boolean ISTRACE = android.util.Log.isLoggable(TAG_PPDEBUG, android.util.Log.VERBOSE); // For identity ID in Glide public static final String ID_PP_GLIDE = "ID_PhotoPicker"; public static final String PACKAGE_PHOTOPICKER = "com.mediatek.photopicker"; public static final String ACTION_PP_PICK = "com.mediatek.action.photopicker.PICK"; // For cursor performance optimization public static final Uri URIBASE = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; public static final String ORDER_ASC = "datetaken ASC"; public static final String ORDER_DESC = "datetaken DESC"; public static final String CUR_ID = Images.Media._ID; public static final String CUR_DATA = Images.Media.DATA; public static final String CUR_BUCKET_ID = Images.Media.BUCKET_ID; public static final String CUR_BUCKET_NAME = Images.Media.BUCKET_DISPLAY_NAME; private static Paint sTextPaint = null; private static Paint sStripPaint = null; private static Bitmap sFolderIcon = null; // Cache size public static final int ARRAY_SIZE = 80; // Visual item in gridView on screen public static final int SCREEN_VIS_SIZE = 18; // Show subtitle name under each item public static final int SUBTITLE_SIZE = 12; /** * Append albums into list after query database. * @param list The query result * @param context The context * @param projection null * @param selection null * @param selectionArgs null * @param sortOrder null * @param queryStart Query start position * @param queryEnd Query end position */ public static void appendAlbumItems(List<Item> list, Context context, String[] projection, String selection, String[] selectionArgs, String sortOrder, int queryStart, int queryEnd) { Log.d(TAG, "<appendAlbumItems> " + "queryStart-queryEnd: " + queryStart + "-" + queryEnd); Uri uri = URIBASE.buildUpon() .appendQueryParameter("limit", queryStart + "," + (queryEnd - queryStart + 1)) .build(); projection = new String[] { "distinct " + CUR_BUCKET_ID, CUR_BUCKET_NAME }; Cursor cursor = getCursor(context, uri, projection, selection, selectionArgs, sortOrder); if (!checkCursor(cursor)) { Log.d(TAG, "<appendAlbumItems> cursor invalid, do nothing."); return; } cursor.moveToFirst(); while (!cursor.isAfterLast()) { int bucketId = cursor.getInt(cursor.getColumnIndex(CUR_BUCKET_ID)); String bucketName = cursor.getString(cursor.getColumnIndex(CUR_BUCKET_NAME)); Log.d(TAG, "<appendAlbumItems> " + "bucketId & Name: " + bucketId + " " + bucketName); if (null != bucketName) { AlbumItem albumItem = new AlbumItem(); albumItem.bucketId = bucketId; albumItem.bucketName = bucketName; list.add(albumItem); } cursor.moveToNext(); } if (null != cursor) { cursor.close(); } // Do query again projection = new String[] { CUR_ID, CUR_DATA, CUR_BUCKET_ID }; String selectionOfItem = selection + " AND " + CUR_BUCKET_ID + " = ?"; int size = selectionArgs.length; String [] selectionArgsOfItem = new String[size+1]; for (int index = 0; index < size; index++) { selectionArgsOfItem[index] = selectionArgs[index]; } for (Item item : list) { Log.d(TAG, "<appendAlbumItems> " + "list size: " + list.size()); selectionArgsOfItem[size] = String.valueOf(((AlbumItem) item).bucketId); uri = URIBASE.buildUpon().appendQueryParameter("limit", 0 + "," + 1).build(); cursor = getCursor(context, uri, projection, selectionOfItem, selectionArgsOfItem, Utils.ORDER_DESC); if (!checkCursor(cursor)) { Log.d(TAG, "<appendAlbumItems> cursor invalid, do nothing."); return; } cursor.moveToFirst(); while (!cursor.isAfterLast()) { String path = cursor.getString(cursor.getColumnIndex(CUR_DATA)); if (null != path) { String id = cursor.getString(cursor.getColumnIndex(CUR_ID)); Uri uri2 = URIBASE.buildUpon().appendPath(id).build(); item.pathUri = uri2; } cursor.moveToNext(); } if (null != cursor) { cursor.close(); } } } /** * Append files into list after query database. * @param list The query result * @param context The context * @param projection null * @param selection null * @param selectionArgs null * @param sortOrder null * @param queryStart Query start position * @param queryEnd Query end position */ public static void appendFileItems(List<Item> list, Context context, String[] projection, String selection, String[] selectionArgs, String sortOrder, int queryStart, int queryEnd) { Log.d(TAG, "<appendFileItems> queryStart & queryEnd: " + queryStart + " " + queryEnd); Uri uri = URIBASE.buildUpon() .appendQueryParameter("limit", queryStart + "," + (queryEnd - queryStart + 1)) .build(); FileItem fileItem = null; projection = new String[] { CUR_ID, CUR_DATA }; Cursor cursor = getCursor(context, uri, projection, selection, selectionArgs, sortOrder); if (!checkCursor(cursor)) { Log.d(TAG, "<appendFileItems> cursor invalid, do nothing."); return; } cursor.moveToFirst(); while (!cursor.isAfterLast()) { String id = cursor.getString(cursor.getColumnIndex(CUR_ID)); String filePath = cursor.getString(cursor.getColumnIndex(CUR_DATA)); Uri uri2 = URIBASE.buildUpon().appendPath(id).build(); Log.d(TAG, "<appendFileItems> uri2 & filePath: " + uri2 + " " + filePath); if (null != filePath) { fileItem = new FileItem(); fileItem.pathUri = uri2; list.add(fileItem); } cursor.moveToNext(); } if (null != cursor) { cursor.close(); } } /** * Draw over lay on each item. * @param context Current context * @param canvas To be drew * @param title The text was shown at the corner of each item */ public static void drawSlotLabel(Context context, Canvas canvas, String title) { // Basic setup for drawing float canvasSize = canvas.getHeight(); canvas.translate(0, canvasSize); // Draw transparent strip RectF rect = new RectF(0, -canvasSize / 5, canvasSize, canvasSize); canvas.drawRect(rect, getStripPaint(context)); // Draw icon rect = new RectF(0, -canvasSize / 5, canvasSize / 5, 0); canvas.drawBitmap(getBitmapIconFolder(context), null, rect, null); // Draw text canvas.drawText(title, canvasSize / 5, -canvasSize / 15, getTextPaint(context)); } /** * Get instance of AlbumSetModelHook. * @param context Current context * @return AlbumSetModelHook */ public static AlbumSetModelHook getAlbumSetModelHook(Context context) { return new AlbumSetModelHook(context); } /** * Get instance of AlbumModeHook. * @param context Current context * @param bucketId Click bucket_id * @return AlbumModeHook */ public static AlbumModelHook getAlbumModelHook(Context context, int bucketId) { return new AlbumModelHook(context, bucketId); } /** * Get default viewHook. * @param context Current context * @return IViewHook */ public static IViewHook getViewHook(Context context) { IViewHook viewHook = new DefaultViewHook(context); return viewHook; } /** * Get default controlHook. * @return IControlHook. */ public static IControlHook getControlHook() { return new DefaultControlHook(); } /** * Get cursor by context and conditions. * @param context Current context * @param uri null * @param projection null * @param selection null * @param selectionArgs null * @param sortOrder null * @return Cursor Return cursor */ public static Cursor getCursor(Context context, Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { if (ISTRACE) { Log.d(TAG, "<getCursor> " + "cursor infos as follow: " + "\n\t" + "<getCursor> " + "projection: " + projection + "\n\t" + "<getCursor> " + "selection: " + selection + "\n\t" + "<getCursor> " + "selectionArgs: " + selectionArgs + "\n\t" + "<getCursor> " + "sortOrder: " + sortOrder + "\n"); } Cursor cursor = null; try { cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder); Log.d(TAG, "<getCursor> cursor: " + cursor); } catch (IllegalStateException e) { Log.d(TAG, "<getCursor> query IllegalStateException: " + e.getMessage()); } catch (SQLiteException e) { Log.d(TAG, "<getCursor> query SQLiteException: " + e.getMessage()); } return cursor; } /** * For check the state of PhotoPicker.Config. * @param config PhotoPicker.Config */ public static void debugConfig(Config config) { if (ISTRACE) { Log.d(TAG, "<debugConfig> " + "config infos as follow: " + "\n\t" + "<debugConfig> " + "config.titleId: " + config.title + "\n\t" + "<debugConfig> " + "config.subTitleId: " + config.subTitle + "\n\t" + "<debugConfig> " + "config.controlHook: " + config.controlHook + "\n\t" + "<debugConfig> " + "config.viewHook: " + config.viewHook + "\n\t" + "<debugConfig> " + "config.modelHook: " + config.modelHook + "\n"); } else { Log.d(TAG, "<debugConfig> " + "ISDEBUG: " + ISTRACE + ", show nothing"); } } /** * Launch PhotoPicker from 3rd apps, Can launch PhotoPicker as follow code. * {@code * Intent intent = new Intent(ACTION_PP_PICK); * startActivityForResult(intent, PhotoPicker.REQUEST_CODE); * }, Or luanch PhotoPicker by function {@code launchPhotoPicker3rd} * @param context Current context */ public static void launchPhotoPicker3rd(Context context) { PackageInfo packageInfo = null; try { packageInfo = context.getPackageManager().getPackageInfo(PACKAGE_PHOTOPICKER, 0); } catch (NameNotFoundException e) { packageInfo = null; e.printStackTrace(); } if (packageInfo == null) { Log.d(TAG, "<launchPhotoPicker3rd> " + PACKAGE_PHOTOPICKER + " haven't installed"); } else { Intent resolveIntent = new Intent(ACTION_PP_PICK, null); resolveIntent.setPackage(packageInfo.packageName); Log.d(TAG, "<launchPhotoPicker3rd> " + "resolveIntent: " + resolveIntent); List<ResolveInfo> apps = context.getPackageManager().queryIntentActivities(resolveIntent, 0); ResolveInfo resolveInfo = apps.iterator().next(); if (resolveInfo != null) { Log.d(TAG, "<launchPhotoPicker3rd> " + "resolveInfo: " + resolveInfo); String packageNameTemp = resolveInfo.activityInfo.packageName; String className = resolveInfo.activityInfo.name; Log.d(TAG, "<launchPhotoPicker3rd> " + "packageNameTemp & className: " + packageNameTemp + "-" + className); Intent intent = new Intent(ACTION_PP_PICK); ComponentName cn = new ComponentName(packageNameTemp, className); intent.setComponent(cn); ((Activity) context).startActivityForResult(intent, PhotoPicker.REQUEST_CODE); } } } /** * Return a resource identifier for the given resource name in PhotoPicker package. * @param context the Android Context * @param name resource name * @param defType resource type * @return resource identifier */ public static int getMyResId(Context context, String name, String defType) { return getMyResources(context).getIdentifier(name, defType, PACKAGE_PHOTOPICKER); } /** * Get view by inflating a layout file in PhotoPicker package.<br/> * Warning: layout is unsafe to write in xml file for a library PhotoPicker.<br/> * e.g. it's unsafe to use xml properties defined in non-android namespace. * @param context the Android Context * @param name layout file name * @return view for the layout file */ public static View getMyLayout(Context context, String name) { LayoutInflater inflater = LayoutInflater.from(context); View view = inflater.inflate( getMyResources(context).getLayout( getMyResId(context, name, "layout")), null); return view; } /** * Get drawable in PhotoPicker package. * @param context the Android Context * @param name drawable name * @return drawable of the given name */ public static Drawable getMyDrawable(Context context, String name) { int id = getMyResId(context, name, "drawable"); return getMyResources(context).getDrawable(id); } /** * Get string in PhotoPicker package. * @param context the Android Context * @param name string name * @return string of the given name */ public static String getMyString(Context context, String name) { int id = getMyResId(context, name, "string"); return getMyResources(context).getString(id); } /** * Get dimension in PhotoPicker package. * @param context the Android Context * @param name dimension name * @return dimension of the given name */ public static float getMyDimension(Context context, String name) { int id = getMyResId(context, name, "dimen"); return getMyResources(context).getDimension(id); } /** * Get dimension in PhotoPicker package. * @param context the Android Context * @param name dimension name * @return dimension of the given name */ public static int getMyDimensionPixelSize(Context context, String name) { int id = getMyResId(context, name, "dimen"); return getMyResources(context).getDimensionPixelSize(id); } /** * Get color in PhotoPicker package. * @param context the Android Context * @param name color name * @return color of the given name */ public static int getMyColor(Context context, String name) { int id = getMyResId(context, name, "color"); return getMyResources(context).getColor(id); } private static Resources getMyResources(Context context) { Resources myResources = null; PackageManager pm = context.getPackageManager(); try { myResources = pm.getResourcesForApplication(PACKAGE_PHOTOPICKER); } catch (NameNotFoundException e) { Log.e(TAG, "No resources found in PhotoPicker"); } return myResources; } private static Paint getTextPaint(Context context) { if (null == sTextPaint) { sTextPaint = new Paint(); sTextPaint.setAntiAlias(true); sTextPaint.setColor(getMyColor(context, "label_text")); sTextPaint.setTextSize(getMyDimension(context, "label_font_size")); sTextPaint.setStrokeWidth(1.5f); } return sTextPaint; } private static Paint getStripPaint(Context context) { if (null == sStripPaint) { Resources res = getMyResources(context); sStripPaint = new Paint(); int colorId = getMyResId(context, "label_background", "color"); sStripPaint.setColor(res.getColor(colorId)); } return sStripPaint; } private static Bitmap getBitmapIconFolder(Context context) { if (null == sFolderIcon) { int id = getMyResId(context, "ic_folder", "drawable"); Resources res = getMyResources(context); sFolderIcon = BitmapFactory.decodeResource(res, id); } return sFolderIcon; } private static boolean checkCursor(Cursor cursor) { if (cursor == null ) { Log.d(TAG, "<checkCursor> cursor is null, do nothing"); return false; } else { if (!cursor.moveToFirst()) { Log.d(TAG, "<checkCursor> cursor is not null, but it's empty."); return false; } return true; } } }
19,146
0.616265
0.614228
484
38.55785
27.072117
98
false
false
0
0
0
0
0
0
0.665289
false
false
11
978e60121324211f24246d2944c5d71aa3049625
31,963,146,676,530
057e673b3b964dd02c485a5336d210f6faa14053
/Core/src/main/java/com/github/jolice/metro/route/report/part/Subway.java
3c544db06ebfed53fe03b149fe2ae1997a7a4714
[ "MIT" ]
permissive
jolice/MoscowMetroBot
https://github.com/jolice/MoscowMetroBot
d29c7bfc1e723611015f1710d89bf5cd0339023b
eb0afeef9276d24442a8afd18d98093537247c77
refs/heads/master
2022-11-27T21:33:24.621000
2020-06-14T13:16:30
2020-06-14T13:16:30
200,784,317
0
0
MIT
false
2022-11-23T23:48:53
2019-08-06T05:45:15
2022-10-06T11:12:41
2022-11-23T23:48:52
257
0
0
1
Java
false
false
package com.github.jolice.metro.route.report.part; import com.github.jolice.metro.model.Station; public class Subway extends RoutePart { public Subway(Station from, Station to, int distance) { super(from, to, distance); } @Override public String description() { return String.format("Move from station %s to station %s without changes (%d min)", getFrom(), getTo(), getDistance() / 60); } }
UTF-8
Java
431
java
Subway.java
Java
[ { "context": "package com.github.jolice.metro.route.report.part;\n\nimport com.github.jolic", "end": 25, "score": 0.8987655639648438, "start": 19, "tag": "USERNAME", "value": "jolice" }, { "context": "olice.metro.route.report.part;\n\nimport com.github.jolice.metro.model.Station;\n\npublic class Subway extends", "end": 76, "score": 0.8725959658622742, "start": 70, "tag": "USERNAME", "value": "jolice" } ]
null
[]
package com.github.jolice.metro.route.report.part; import com.github.jolice.metro.model.Station; public class Subway extends RoutePart { public Subway(Station from, Station to, int distance) { super(from, to, distance); } @Override public String description() { return String.format("Move from station %s to station %s without changes (%d min)", getFrom(), getTo(), getDistance() / 60); } }
431
0.679814
0.675174
15
27.733334
34.524323
132
false
false
0
0
0
0
0
0
0.733333
false
false
11
3b637931b80dd3cbb217072f37d404f9f4663a38
26,491,358,316,307
7541f7bf16b86dd00f43cf6c6a3ae4dfeb1ded07
/java/j8study/src/main/java/net/x841bc/j8study/asm/Mesurable.java
05779cec9498732a019bce0bf50d8556899befe5
[ "MIT" ]
permissive
sillyemperor/langstudy
https://github.com/sillyemperor/langstudy
382fd026b19676426b3023b49e5a485d5bc12b56
937a11d97984e10e4ead54f3b7b7d6a1f2ef24a1
refs/heads/master
2021-06-18T21:39:48.682000
2019-10-30T11:19:45
2019-10-30T11:19:45
206,315,555
0
0
MIT
false
2021-04-26T19:29:50
2019-09-04T12:36:55
2019-10-30T11:20:09
2021-04-26T19:29:50
3,337
0
0
4
Python
false
false
package net.x841bc.j8study.asm; public interface Mesurable { }
UTF-8
Java
65
java
Mesurable.java
Java
[]
null
[]
package net.x841bc.j8study.asm; public interface Mesurable { }
65
0.769231
0.707692
5
12
14.324803
31
false
false
0
0
0
0
0
0
0.2
false
false
11
0918fbec02c0117df89f8dd2bf9a1efc5c3764d1
17,343,077,987,867
0e17e563b753329ba32bdc535a2a005bb728c3f4
/src/main/java/com/lti/am/model/CustomerPasswordModel.java
2f09f9417f7d80c3029460cca61a536689840922
[]
no_license
raghavyash/LTIDemoAdmin
https://github.com/raghavyash/LTIDemoAdmin
c9f6c7a7782d84a6bfa4de0f2a6bd22417817593
c560c0b510ef9037099a62532deabd2557a6d96b
refs/heads/master
2023-04-27T12:20:27.581000
2021-05-09T11:35:08
2021-05-09T11:35:08
365,441,677
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lti.am.model; public class CustomerPasswordModel { private String password; public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
UTF-8
Java
220
java
CustomerPasswordModel.java
Java
[]
null
[]
package com.lti.am.model; public class CustomerPasswordModel { private String password; public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
220
0.75
0.75
11
19
14.727834
43
false
false
0
0
0
0
0
0
1.181818
false
false
11
02f95bdd2e66ba5dc5dafbc2d2efb11d155cd06c
27,084,063,797,261
e5ded6bc6d4106e9d2e6041ae191eb9b8ed7b5ea
/spring-partybuild/spring-partybuild-web/src/main/java/com/cn/wisdom/base/controller/BaseRoleResourceController.java
0422e5f852f9372a31fd2549a7889290bf17a1d5
[]
no_license
zhaoandpeng/spring-partybuild
https://github.com/zhaoandpeng/spring-partybuild
15ca1e9e201cacc5d9565b76ce972f841aa2f622
7b5c7fc8db8dde9e62aef135f27f66a3252197b7
refs/heads/master
2020-05-29T12:33:50.360000
2019-06-25T09:24:14
2019-06-25T09:24:14
189,131,343
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cn.wisdom.base.controller; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.cn.wisdom.base.model.BaseRoleResources; import com.cn.wisdom.base.service.BaseRoleResourceService; import com.cn.wisdom.utils.EventType; import io.netty.util.internal.StringUtil; @Controller @RequestMapping("/api/v1/sys/role/resources") public class BaseRoleResourceController extends BaseController{ @Resource private BaseRoleResourceService baseRoleResourceService; @ResponseBody @RequestMapping("/update") public String update() { boolean saveOrUpdate = false; ConcurrentHashMap<String,Object> resultMap = new ConcurrentHashMap<>(); ConcurrentHashMap<String,Object> map = new ConcurrentHashMap<>(); String roleId = getRequest().getParameter("roleId"); String menus = getRequest().getParameter("menus"); if(StringUtil.isNullOrEmpty(roleId)) { resultMap.put("status", false); resultMap.put("message", "参数为空,请检查所传参数"); return toJson(resultMap); } if(!StringUtil.isNullOrEmpty(roleId)&&!StringUtil.isNullOrEmpty(menus)) { map.put("role_id", roleId); List<BaseRoleResources> listModel = baseRoleResourceService.getList(BaseRoleResources.class, map); if(null!=listModel) { int deleteCount = baseRoleResourceService.deleteBatch(listModel,map); if(deleteCount == listModel.size()) { String[] menu = menus.split(","); for (String menuId : menu) { BaseRoleResources model = new BaseRoleResources(); model.setRoleId(roleId); model.setMenuId(menuId); saveOrUpdate = baseRoleResourceService.saveOrUpdate(model, EventType.EVENT_ADD); } }else { resultMap.put("status", false); resultMap.put("message", "权限分配异常"); } } } resultMap.put("status", saveOrUpdate); return toJson(resultMap); } }
UTF-8
Java
2,235
java
BaseRoleResourceController.java
Java
[]
null
[]
package com.cn.wisdom.base.controller; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.cn.wisdom.base.model.BaseRoleResources; import com.cn.wisdom.base.service.BaseRoleResourceService; import com.cn.wisdom.utils.EventType; import io.netty.util.internal.StringUtil; @Controller @RequestMapping("/api/v1/sys/role/resources") public class BaseRoleResourceController extends BaseController{ @Resource private BaseRoleResourceService baseRoleResourceService; @ResponseBody @RequestMapping("/update") public String update() { boolean saveOrUpdate = false; ConcurrentHashMap<String,Object> resultMap = new ConcurrentHashMap<>(); ConcurrentHashMap<String,Object> map = new ConcurrentHashMap<>(); String roleId = getRequest().getParameter("roleId"); String menus = getRequest().getParameter("menus"); if(StringUtil.isNullOrEmpty(roleId)) { resultMap.put("status", false); resultMap.put("message", "参数为空,请检查所传参数"); return toJson(resultMap); } if(!StringUtil.isNullOrEmpty(roleId)&&!StringUtil.isNullOrEmpty(menus)) { map.put("role_id", roleId); List<BaseRoleResources> listModel = baseRoleResourceService.getList(BaseRoleResources.class, map); if(null!=listModel) { int deleteCount = baseRoleResourceService.deleteBatch(listModel,map); if(deleteCount == listModel.size()) { String[] menu = menus.split(","); for (String menuId : menu) { BaseRoleResources model = new BaseRoleResources(); model.setRoleId(roleId); model.setMenuId(menuId); saveOrUpdate = baseRoleResourceService.saveOrUpdate(model, EventType.EVENT_ADD); } }else { resultMap.put("status", false); resultMap.put("message", "权限分配异常"); } } } resultMap.put("status", saveOrUpdate); return toJson(resultMap); } }
2,235
0.690141
0.689686
79
25.86076
27.131062
104
false
false
0
0
0
0
0
0
2.911392
false
false
11
c885211d9262f361707d6a7f682be71da6a110db
30,863,635,056,392
c05c06f85960e6a71a1dfc28addd757073747065
/jcondo-account-portlet/docroot/WEB-INF/src/br/com/abware/jcondo/account/AccountBean.java
83627e727e1d9c9779720f62bcfcf5550301cca5
[]
no_license
andersonboechat/jcondo-widgets
https://github.com/andersonboechat/jcondo-widgets
3ede3143c0fca3a36a0c1a91907caae35dde45b9
801dde9a8c3c1f0919bb1be1b54e1705f67759ac
refs/heads/master
2020-12-24T15:58:24.482000
2015-05-28T23:32:06
2015-05-28T23:32:06
23,148,140
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.abware.jcondo.account; import java.io.File; import java.io.Serializable; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.ResourceBundle; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import javax.faces.event.AjaxBehaviorEvent; import javax.faces.event.ValueChangeEvent; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.log4j.Logger; import org.apache.myfaces.commons.util.MessageUtils; import org.primefaces.event.FileUploadEvent; import org.primefaces.model.UploadedFile; import br.com.abware.jcondo.core.Permission; import br.com.abware.jcondo.core.RoleType; import br.com.abware.jcondo.core.model.Domain; import br.com.abware.jcondo.core.model.Flat; import br.com.abware.jcondo.core.model.Image; import br.com.abware.jcondo.core.model.Person; import br.com.abware.jcondo.core.model.Role; import br.com.abware.jcondo.core.service.FlatService; import br.com.abware.jcondo.core.service.PersonService; import br.com.abware.jcondo.core.service.RoleService; import br.com.abware.jcondo.exception.ApplicationException; @ManagedBean @ViewScoped public class AccountBean implements Serializable { private static final long serialVersionUID = 1L; private static final Logger LOGGER = Logger.getLogger(AccountBean.class); protected static ResourceBundle rb = ResourceBundle.getBundle("Language", new Locale("pt", "BR")); @EJB(lookup="java:global/jcondo/jcondo-impl/personService") private PersonService personService; @EJB(lookup="java:global/jcondo/jcondo-impl/flatService") private FlatService flatService; @EJB(lookup="java:global/jcondo/jcondo-impl/roleService") private RoleService roleService; private PersonDataModel model; /** cache das tabelas carregadas */ private List<RoleshipDataModel> models; /** apartamento selecionado */ private Flat flat; /** apartamentos associados ao usuário logado */ private List<Flat> flats; /** usuario logado */ private Person person; @PostConstruct public void init() { try { person = personService.getPerson(); flats = flatService.getFlats(person); if (!CollectionUtils.isEmpty(flats)) { flat = flats.get(0); buildModel(); } else { //setModel(new PersonDataModel(new ArrayList<Person>())); } } catch (ApplicationException e) { LOGGER.fatal("Falha ao inicializar bean", e); } } private void buildModel() throws ApplicationException { // List<Roleship> roleships = new ArrayList<Roleship>(); // // for (Person person : personService.getPeople(flat)) { // for (Roleship roleship : person.getRoleships()) { // if (flat.equals(roleship.getOrganization())) { // roleships.add(roleship); // } // } // // } // // model = new RoleshipDataModel(flat, roleships); // models.add(model); } public boolean canAddPeople() { // try { // return personService.hasPermission(null, Permission.ADD_USER); // } catch (ApplicationException e) { // LOGGER.error(e.getMessage(), e); // } return false; } public boolean hasPermission(Person person) { try { return personService.hasPermission(person, Permission.UPDATE_PERSON); } catch (ApplicationException e) { LOGGER.error(e.getMessage(), e); } return false; } public void onSelectRole(ValueChangeEvent event) { // Role role = (Role) event.getNewValue(); // Roleship data = model.getRowData(); // Person person = data.getPerson(); // try { // roleService.save(person, role); // data.setRole(role); // } catch (ApplicationException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } } public void onSelectFlat(AjaxBehaviorEvent event) { // try { // int i; // // if ((i = models.indexOf(new RoleshipDataModel(flat, null))) < 0) { // buildModel(); // } else { // model = models.get(i); // } // // } catch (Exception e) { // LOGGER.error("Unexpected Failure", e); // MessageUtils.addMessage(FacesMessage.SEVERITY_FATAL, "register.runtime.failure", null); // } } public void onSave(Person person) { // try { // Person p = personService.register(person); // roleship.setPerson(p); // // if (person.getId() == 0) { // model.add(roleship); // MessageUtils.addMessage(FacesMessage.SEVERITY_INFO, "flats.user.add.success", null); // } else { // MessageUtils.addMessage(FacesMessage.SEVERITY_INFO, "global.sucess", null); // } // } catch (ApplicationException e) { // LOGGER.error(e.getMessage(), e); // //FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, e.getLocalizedMessage(), null)); // MessageUtils.addMessage(FacesMessage.SEVERITY_FATAL, e.getLocalizedMessage(), null); // } catch (Exception e) { // LOGGER.error("Unexpected Failure", e); // MessageUtils.addMessage(FacesMessage.SEVERITY_FATAL, "register.runtime.failure", null); // } } public void onCreate() { } public void onEdit(String rowKey) { try { } catch (Exception e) { LOGGER.error("Unexpected Failure", e); MessageUtils.addMessage(FacesMessage.SEVERITY_FATAL, "register.runtime.failure", null); } } public void onRemove() { } public void onUpload(FileUploadEvent event) { try { UploadedFile uploadedFile = event.getFile(); File temp = File.createTempFile("usr_pic_", FilenameUtils.getExtension(uploadedFile.getFileName()), new File("/temp/")); FileUtils.copyInputStreamToFile(uploadedFile.getInputstream(), temp); Person person; String clientId = null; if ("myAccount".equalsIgnoreCase(clientId)) { person = this.person; } else { } } catch (Exception e) { LOGGER.error("Unexpected Failure", e); MessageUtils.addMessage(FacesMessage.SEVERITY_FATAL, "register.runtime.failure", null); } } public void onCancel(Person person) { try { if (person.getPicture() != null && person.getPicture().getId() == 0) { FileUtils.deleteQuietly(new File(new URL(person.getPicture().getPath()).toURI())); } } catch (Exception e) { LOGGER.error("Unexpected Failure", e); MessageUtils.addMessage(FacesMessage.SEVERITY_FATAL, "register.runtime.failure", null); } } public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } public Flat getFlat() { return flat; } public void setFlat(Flat flat) { this.flat = flat; } public List<Flat> getFlats() { return flats; } public void setFlats(List<Flat> flats) { this.flats = flats; } }
WINDOWS-1250
Java
6,968
java
AccountBean.java
Java
[]
null
[]
package br.com.abware.jcondo.account; import java.io.File; import java.io.Serializable; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.ResourceBundle; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import javax.faces.event.AjaxBehaviorEvent; import javax.faces.event.ValueChangeEvent; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.log4j.Logger; import org.apache.myfaces.commons.util.MessageUtils; import org.primefaces.event.FileUploadEvent; import org.primefaces.model.UploadedFile; import br.com.abware.jcondo.core.Permission; import br.com.abware.jcondo.core.RoleType; import br.com.abware.jcondo.core.model.Domain; import br.com.abware.jcondo.core.model.Flat; import br.com.abware.jcondo.core.model.Image; import br.com.abware.jcondo.core.model.Person; import br.com.abware.jcondo.core.model.Role; import br.com.abware.jcondo.core.service.FlatService; import br.com.abware.jcondo.core.service.PersonService; import br.com.abware.jcondo.core.service.RoleService; import br.com.abware.jcondo.exception.ApplicationException; @ManagedBean @ViewScoped public class AccountBean implements Serializable { private static final long serialVersionUID = 1L; private static final Logger LOGGER = Logger.getLogger(AccountBean.class); protected static ResourceBundle rb = ResourceBundle.getBundle("Language", new Locale("pt", "BR")); @EJB(lookup="java:global/jcondo/jcondo-impl/personService") private PersonService personService; @EJB(lookup="java:global/jcondo/jcondo-impl/flatService") private FlatService flatService; @EJB(lookup="java:global/jcondo/jcondo-impl/roleService") private RoleService roleService; private PersonDataModel model; /** cache das tabelas carregadas */ private List<RoleshipDataModel> models; /** apartamento selecionado */ private Flat flat; /** apartamentos associados ao usuário logado */ private List<Flat> flats; /** usuario logado */ private Person person; @PostConstruct public void init() { try { person = personService.getPerson(); flats = flatService.getFlats(person); if (!CollectionUtils.isEmpty(flats)) { flat = flats.get(0); buildModel(); } else { //setModel(new PersonDataModel(new ArrayList<Person>())); } } catch (ApplicationException e) { LOGGER.fatal("Falha ao inicializar bean", e); } } private void buildModel() throws ApplicationException { // List<Roleship> roleships = new ArrayList<Roleship>(); // // for (Person person : personService.getPeople(flat)) { // for (Roleship roleship : person.getRoleships()) { // if (flat.equals(roleship.getOrganization())) { // roleships.add(roleship); // } // } // // } // // model = new RoleshipDataModel(flat, roleships); // models.add(model); } public boolean canAddPeople() { // try { // return personService.hasPermission(null, Permission.ADD_USER); // } catch (ApplicationException e) { // LOGGER.error(e.getMessage(), e); // } return false; } public boolean hasPermission(Person person) { try { return personService.hasPermission(person, Permission.UPDATE_PERSON); } catch (ApplicationException e) { LOGGER.error(e.getMessage(), e); } return false; } public void onSelectRole(ValueChangeEvent event) { // Role role = (Role) event.getNewValue(); // Roleship data = model.getRowData(); // Person person = data.getPerson(); // try { // roleService.save(person, role); // data.setRole(role); // } catch (ApplicationException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } } public void onSelectFlat(AjaxBehaviorEvent event) { // try { // int i; // // if ((i = models.indexOf(new RoleshipDataModel(flat, null))) < 0) { // buildModel(); // } else { // model = models.get(i); // } // // } catch (Exception e) { // LOGGER.error("Unexpected Failure", e); // MessageUtils.addMessage(FacesMessage.SEVERITY_FATAL, "register.runtime.failure", null); // } } public void onSave(Person person) { // try { // Person p = personService.register(person); // roleship.setPerson(p); // // if (person.getId() == 0) { // model.add(roleship); // MessageUtils.addMessage(FacesMessage.SEVERITY_INFO, "flats.user.add.success", null); // } else { // MessageUtils.addMessage(FacesMessage.SEVERITY_INFO, "global.sucess", null); // } // } catch (ApplicationException e) { // LOGGER.error(e.getMessage(), e); // //FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, e.getLocalizedMessage(), null)); // MessageUtils.addMessage(FacesMessage.SEVERITY_FATAL, e.getLocalizedMessage(), null); // } catch (Exception e) { // LOGGER.error("Unexpected Failure", e); // MessageUtils.addMessage(FacesMessage.SEVERITY_FATAL, "register.runtime.failure", null); // } } public void onCreate() { } public void onEdit(String rowKey) { try { } catch (Exception e) { LOGGER.error("Unexpected Failure", e); MessageUtils.addMessage(FacesMessage.SEVERITY_FATAL, "register.runtime.failure", null); } } public void onRemove() { } public void onUpload(FileUploadEvent event) { try { UploadedFile uploadedFile = event.getFile(); File temp = File.createTempFile("usr_pic_", FilenameUtils.getExtension(uploadedFile.getFileName()), new File("/temp/")); FileUtils.copyInputStreamToFile(uploadedFile.getInputstream(), temp); Person person; String clientId = null; if ("myAccount".equalsIgnoreCase(clientId)) { person = this.person; } else { } } catch (Exception e) { LOGGER.error("Unexpected Failure", e); MessageUtils.addMessage(FacesMessage.SEVERITY_FATAL, "register.runtime.failure", null); } } public void onCancel(Person person) { try { if (person.getPicture() != null && person.getPicture().getId() == 0) { FileUtils.deleteQuietly(new File(new URL(person.getPicture().getPath()).toURI())); } } catch (Exception e) { LOGGER.error("Unexpected Failure", e); MessageUtils.addMessage(FacesMessage.SEVERITY_FATAL, "register.runtime.failure", null); } } public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } public Flat getFlat() { return flat; } public void setFlat(Flat flat) { this.flat = flat; } public List<Flat> getFlats() { return flats; } public void setFlats(List<Flat> flats) { this.flats = flats; } }
6,968
0.686379
0.685517
250
25.868
25.570189
136
false
false
0
0
0
0
0
0
1.988
false
false
11
dedc7786ee15996d647305231bbe59c6da763e17
35,416,300,327,392
34122cae867cff6ad14f71aef923fea841c67ce5
/app/src/main/java/com/example/utente/finalnoteapp/activities/NoteActivity.java
6a38f8e81d2217417475b3daab881cd42e0d6444
[]
no_license
francescostella97/FinalNoteAppEs
https://github.com/francescostella97/FinalNoteAppEs
60a1ffaeca37d7e55eee9a6aa21a778b78e45f3f
4316f0406f709307f6295e4f60f4155ae34782d4
refs/heads/master
2020-05-23T05:45:33.672000
2017-03-12T19:46:57
2017-03-12T19:46:57
84,752,383
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.utente.finalnoteapp.activities; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.FloatingActionButton; import android.support.v4.view.ViewCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.TextView; import com.example.utente.finalnoteapp.R; import org.w3c.dom.Text; /** * Created by ${Francesco} on 11/03/2017. */ public class NoteActivity extends AppCompatActivity { //type of action static int action; static final int ACTION_ADD = 1; static final int ACTION_EDIT = 2; static final int DELETE_FLAG = 200; Toolbar toolbar; int position; //declaring UI controls TextView titleTv, bodyTv, dueDateTv, editDateTv, creationDateTv; @Override public boolean onKeyDown( int keyCode, KeyEvent event ) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { if(action==ACTION_ADD) createAddIntent(); else if(action==ACTION_EDIT) createEditIntent(); finish(); return true; } return super.onKeyDown( keyCode, event ); } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_view_note); action = ACTION_ADD; //toolbar-------------------------------------------- toolbar = (Toolbar)findViewById(R.id.toolbar_layout); ViewCompat.setElevation(toolbar,0); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); //--------------------------------------------------- //UI control titleTv = (TextView) findViewById(R.id.view_note_title); bodyTv = (TextView) findViewById(R.id.view_note_body); //---------------------------------------------------- action = ACTION_ADD; //managing intent Intent intent = getIntent(); if(intent != null){ if(intent.getStringExtra("title")!=null){ //editing a note action = ACTION_EDIT; position = Integer.parseInt(intent.getStringExtra("position")); titleTv.setText(intent.getStringExtra("title")); bodyTv.setText(intent.getStringExtra("body")); } } } @Override protected void onDestroy() { super.onDestroy(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); if(action == ACTION_ADD){ inflater.inflate(R.menu.add_note_menu,menu); } else { inflater.inflate(R.menu.view_note_menu,menu); } return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch (id){ case R.id.view_note_delete: Intent intent = new Intent(); intent.putExtra("position", String.valueOf(position)); intent.addFlags(DELETE_FLAG); setResult(RESULT_OK, intent); finish(); break; case R.id.add_note_save: createAddIntent (); finish(); break; case R.id.view_note_save: createEditIntent(); finish(); break; case android.R.id.home : if(action==ACTION_ADD) createAddIntent(); else if(action==ACTION_EDIT) createEditIntent(); finish(); break; } return super.onOptionsItemSelected(item); } public void createAddIntent(){ Log.d("MAIN ACTIVITY ","going to add "); Intent intent = new Intent(); intent.putExtra("position",String.valueOf(position)); intent.putExtra("title",titleTv.getText().toString()); intent.putExtra("body",bodyTv.getText().toString()); setResult(RESULT_OK,intent); } public void createEditIntent(){ Log.d("MAIN ACTIVITY ","going to edit "); Intent intent = new Intent(); intent.putExtra("position",String.valueOf(position)); intent.putExtra("title",titleTv.getText().toString()); intent.putExtra("body",bodyTv.getText().toString()); intent.setFlags(DELETE_FLAG); setResult(RESULT_OK,intent); } }
UTF-8
Java
4,712
java
NoteActivity.java
Java
[ { "context": "R;\n\nimport org.w3c.dom.Text;\n\n/**\n * Created by ${Francesco} on 11/03/2017.\n */\n\npublic class NoteActivity ex", "end": 623, "score": 0.9437602162361145, "start": 614, "tag": "NAME", "value": "Francesco" } ]
null
[]
package com.example.utente.finalnoteapp.activities; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.FloatingActionButton; import android.support.v4.view.ViewCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.TextView; import com.example.utente.finalnoteapp.R; import org.w3c.dom.Text; /** * Created by ${Francesco} on 11/03/2017. */ public class NoteActivity extends AppCompatActivity { //type of action static int action; static final int ACTION_ADD = 1; static final int ACTION_EDIT = 2; static final int DELETE_FLAG = 200; Toolbar toolbar; int position; //declaring UI controls TextView titleTv, bodyTv, dueDateTv, editDateTv, creationDateTv; @Override public boolean onKeyDown( int keyCode, KeyEvent event ) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { if(action==ACTION_ADD) createAddIntent(); else if(action==ACTION_EDIT) createEditIntent(); finish(); return true; } return super.onKeyDown( keyCode, event ); } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_view_note); action = ACTION_ADD; //toolbar-------------------------------------------- toolbar = (Toolbar)findViewById(R.id.toolbar_layout); ViewCompat.setElevation(toolbar,0); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); //--------------------------------------------------- //UI control titleTv = (TextView) findViewById(R.id.view_note_title); bodyTv = (TextView) findViewById(R.id.view_note_body); //---------------------------------------------------- action = ACTION_ADD; //managing intent Intent intent = getIntent(); if(intent != null){ if(intent.getStringExtra("title")!=null){ //editing a note action = ACTION_EDIT; position = Integer.parseInt(intent.getStringExtra("position")); titleTv.setText(intent.getStringExtra("title")); bodyTv.setText(intent.getStringExtra("body")); } } } @Override protected void onDestroy() { super.onDestroy(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); if(action == ACTION_ADD){ inflater.inflate(R.menu.add_note_menu,menu); } else { inflater.inflate(R.menu.view_note_menu,menu); } return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch (id){ case R.id.view_note_delete: Intent intent = new Intent(); intent.putExtra("position", String.valueOf(position)); intent.addFlags(DELETE_FLAG); setResult(RESULT_OK, intent); finish(); break; case R.id.add_note_save: createAddIntent (); finish(); break; case R.id.view_note_save: createEditIntent(); finish(); break; case android.R.id.home : if(action==ACTION_ADD) createAddIntent(); else if(action==ACTION_EDIT) createEditIntent(); finish(); break; } return super.onOptionsItemSelected(item); } public void createAddIntent(){ Log.d("MAIN ACTIVITY ","going to add "); Intent intent = new Intent(); intent.putExtra("position",String.valueOf(position)); intent.putExtra("title",titleTv.getText().toString()); intent.putExtra("body",bodyTv.getText().toString()); setResult(RESULT_OK,intent); } public void createEditIntent(){ Log.d("MAIN ACTIVITY ","going to edit "); Intent intent = new Intent(); intent.putExtra("position",String.valueOf(position)); intent.putExtra("title",titleTv.getText().toString()); intent.putExtra("body",bodyTv.getText().toString()); intent.setFlags(DELETE_FLAG); setResult(RESULT_OK,intent); } }
4,712
0.602716
0.598684
136
33.64706
22.063255
79
false
false
0
0
0
0
0
0
0.742647
false
false
11
a42efe37b5924d399f32b475c812ed87cf122b2b
24,988,119,770,934
44be87f9b40bd922d69712e6342f0e8b7ca1b901
/src/Backtracking.java
be45a855342b227db2040a84f01269be7ec2d026
[]
no_license
wizzlerr/ProblemSudoku
https://github.com/wizzlerr/ProblemSudoku
4f1761caa21e3b2e8fadf0325248ba7c58757a9c
bd3434a95c675695e70a60d54ff609de22a174f9
refs/heads/master
2016-09-13T09:14:56.001000
2016-04-11T17:59:45
2016-04-11T17:59:45
55,994,969
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Backtracking extends Common { public Backtracking() { super(); } public Backtracking(String path) { super(path.toLowerCase()); } private boolean isSolved() { depth++; int[] empty = findEmpty(); if (empty != null) { int x = empty[0]; int y = empty[1]; for (int i = 1; i <= 9; i++) { if (isInsertable(x, y, i)) { logic.sudoku[x][y] = i; if (isSolved()) { return true; } logic.sudoku[x][y] = 0; } } } else { return true; } return false; } public void solveSudoku() { System.out.println("BACKTRACKING"); System.out.println("LOADED SUDOKU: " + path); logic.printSudoku(); long startTime = System.nanoTime(); if (isSolved()) { commonSolutionFound(startTime); } else { commonNoSolution(); } System.out.println("---------------"); } }
UTF-8
Java
1,128
java
Backtracking.java
Java
[]
null
[]
public class Backtracking extends Common { public Backtracking() { super(); } public Backtracking(String path) { super(path.toLowerCase()); } private boolean isSolved() { depth++; int[] empty = findEmpty(); if (empty != null) { int x = empty[0]; int y = empty[1]; for (int i = 1; i <= 9; i++) { if (isInsertable(x, y, i)) { logic.sudoku[x][y] = i; if (isSolved()) { return true; } logic.sudoku[x][y] = 0; } } } else { return true; } return false; } public void solveSudoku() { System.out.println("BACKTRACKING"); System.out.println("LOADED SUDOKU: " + path); logic.printSudoku(); long startTime = System.nanoTime(); if (isSolved()) { commonSolutionFound(startTime); } else { commonNoSolution(); } System.out.println("---------------"); } }
1,128
0.426418
0.421986
47
22.978724
15.972702
53
false
false
0
0
0
0
0
0
0.468085
false
false
11
5524be12cece60d696474c75aa8c921e7e8df63c
25,185,688,271,875
da9f10f820447ce15c5e43301bb4a82e66c81ef7
/trunk/unified-user-system/micro-service/src/main/java/com/taiji/cma/uus/service/dic/DicService.java
818c8d38566ed811853cab2745e8b5fecf37177e
[]
no_license
sunyi9999/QXJ
https://github.com/sunyi9999/QXJ
fefede96755ccaa1c771404acf68889373ff4701
61fc4ea8e9f55982b58a7e869e21b6085f293a82
refs/heads/master
2020-06-07T19:01:36.965000
2019-06-25T12:31:06
2019-06-25T12:31:06
193,076,471
0
0
null
false
2020-07-01T23:35:44
2019-06-21T10:06:27
2019-06-25T12:32:50
2020-07-01T23:35:43
19,613
0
0
1
Java
false
false
package com.taiji.cma.uus.service.dic; import com.taiji.cma.uus.mapper.dic.NationDicMapper; import com.taiji.cma.uus.mapper.dic.ProvinceDicMapper; import com.taiji.cma.uus.entity.dic.Dic; import com.taiji.cma.uus.entity.dic.NationDic; import com.taiji.cma.uus.entity.dic.ProvinceDic; import com.taiji.cma.uus.repository.dic.DicRepository; import com.taiji.cma.uus.repository.dic.NationDicRepository; import com.taiji.cma.uus.repository.dic.ProvinceDicRepository; import com.taiji.cma.uus.vo.dic.DicVo; import com.taiji.micro.common.service.BaseService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.MultiValueMap; import org.springframework.util.StringUtils; import javax.annotation.Nonnull; import java.util.List; /** * @author tang * @date 2018/3/26 11:26. */ @Service public class DicService extends BaseService<Dic,String> { @Autowired private DicRepository dicRepository; @Autowired private NationDicRepository nationDicRepository; @Autowired private ProvinceDicRepository provinceDicRepository; @Autowired NationDicMapper nationDicMapper; @Autowired ProvinceDicMapper provinceDicMapper; /** * 获取类型相同的字典表值 * @param params * @return */ public List<Dic> getDicByType( MultiValueMap<String, Object> params){ List<Dic> dicList = dicRepository.getDicByType(params); return dicList; } /** * 根据type 和 code获取到字典表信息 * @param params * @return */ public String getDicNameByCode( MultiValueMap<String, Object> params){ Dic dicByCode = dicRepository.getDicByCode(params); if (!StringUtils.isEmpty(dicByCode)){ return dicByCode.getName(); }else { return null; } } /** *@param clazz *获得某个字典类的字典项 */ public List<DicVo> getDicList(@Nonnull String clazz) { if(clazz.equalsIgnoreCase("nationDic")){ List<NationDic> list = nationDicRepository.findAll(); return nationDicMapper.entityListToVoList(list); }else if(clazz.equalsIgnoreCase("provinceDic")){ List<ProvinceDic> list1 = provinceDicRepository.findAllWithProvince(); return provinceDicMapper.entityListToVoList(list1); }else { return null; } } /** * 根据code查询 * @param code * @return */ public ProvinceDic findByCode(String code){ return provinceDicRepository.findByCode(code); } }
UTF-8
Java
2,647
java
DicService.java
Java
[]
null
[]
package com.taiji.cma.uus.service.dic; import com.taiji.cma.uus.mapper.dic.NationDicMapper; import com.taiji.cma.uus.mapper.dic.ProvinceDicMapper; import com.taiji.cma.uus.entity.dic.Dic; import com.taiji.cma.uus.entity.dic.NationDic; import com.taiji.cma.uus.entity.dic.ProvinceDic; import com.taiji.cma.uus.repository.dic.DicRepository; import com.taiji.cma.uus.repository.dic.NationDicRepository; import com.taiji.cma.uus.repository.dic.ProvinceDicRepository; import com.taiji.cma.uus.vo.dic.DicVo; import com.taiji.micro.common.service.BaseService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.MultiValueMap; import org.springframework.util.StringUtils; import javax.annotation.Nonnull; import java.util.List; /** * @author tang * @date 2018/3/26 11:26. */ @Service public class DicService extends BaseService<Dic,String> { @Autowired private DicRepository dicRepository; @Autowired private NationDicRepository nationDicRepository; @Autowired private ProvinceDicRepository provinceDicRepository; @Autowired NationDicMapper nationDicMapper; @Autowired ProvinceDicMapper provinceDicMapper; /** * 获取类型相同的字典表值 * @param params * @return */ public List<Dic> getDicByType( MultiValueMap<String, Object> params){ List<Dic> dicList = dicRepository.getDicByType(params); return dicList; } /** * 根据type 和 code获取到字典表信息 * @param params * @return */ public String getDicNameByCode( MultiValueMap<String, Object> params){ Dic dicByCode = dicRepository.getDicByCode(params); if (!StringUtils.isEmpty(dicByCode)){ return dicByCode.getName(); }else { return null; } } /** *@param clazz *获得某个字典类的字典项 */ public List<DicVo> getDicList(@Nonnull String clazz) { if(clazz.equalsIgnoreCase("nationDic")){ List<NationDic> list = nationDicRepository.findAll(); return nationDicMapper.entityListToVoList(list); }else if(clazz.equalsIgnoreCase("provinceDic")){ List<ProvinceDic> list1 = provinceDicRepository.findAllWithProvince(); return provinceDicMapper.entityListToVoList(list1); }else { return null; } } /** * 根据code查询 * @param code * @return */ public ProvinceDic findByCode(String code){ return provinceDicRepository.findByCode(code); } }
2,647
0.691799
0.686747
92
26.967392
23.015331
83
false
false
0
0
0
0
0
0
0.391304
false
false
11
939ac35216acf9a14dcc848bbcd48143b6def8b7
3,341,484,626,460
67063d7cb2cf752da753f95a6eed0fe9dff87190
/build/generated-sources/ap-source-output/model/UserFunctionItem_.java
50df4d204762abd8a40fff925b68f8bbbe1a84f0
[]
no_license
c2kmasood/LoginExample
https://github.com/c2kmasood/LoginExample
f55798f409d80ad77bc7594d11d70d8c17974e73
a86267dd36b0efcb30043f55a59bb281084fe2ae
refs/heads/master
2021-01-19T06:35:12.164000
2014-01-14T15:23:33
2014-01-14T15:23:33
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package model; import javax.annotation.Generated; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; import model.LogUser; @Generated(value="EclipseLink-2.5.1.v20130918-rNA", date="2014-01-14T15:58:27") @StaticMetamodel(UserFunctionItem.class) public class UserFunctionItem_ { public static volatile SingularAttribute<UserFunctionItem, Long> id; public static volatile SingularAttribute<UserFunctionItem, LogUser> userName; public static volatile SingularAttribute<UserFunctionItem, String> functionName; }
UTF-8
Java
578
java
UserFunctionItem_.java
Java
[]
null
[]
package model; import javax.annotation.Generated; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; import model.LogUser; @Generated(value="EclipseLink-2.5.1.v20130918-rNA", date="2014-01-14T15:58:27") @StaticMetamodel(UserFunctionItem.class) public class UserFunctionItem_ { public static volatile SingularAttribute<UserFunctionItem, Long> id; public static volatile SingularAttribute<UserFunctionItem, LogUser> userName; public static volatile SingularAttribute<UserFunctionItem, String> functionName; }
578
0.820069
0.776817
16
35.1875
30.745363
84
false
false
0
0
0
0
0
0
0.75
false
false
11
7181967e20576e3b1d0bbd084aad78b7ed66e262
6,562,710,098,553
f6b90fae50ea0cd37c457994efadbd5560a5d663
/android/nut-dex2jar.src/u/aly/b.java
4469d88699b412adc8ca847795672aabfe4e5604
[]
no_license
dykdykdyk/decompileTools
https://github.com/dykdykdyk/decompileTools
5925ae91f588fefa7c703925e4629c782174cd68
4de5c1a23f931008fa82b85046f733c1439f06cf
refs/heads/master
2020-01-27T09:56:48.099000
2016-09-14T02:47:11
2016-09-14T02:47:11
66,894,502
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package u.aly; import android.content.Context; public final class b extends fc { private Context d; public b(Context paramContext) { super("idmd5"); this.d = paramContext; } public final String a() { return cr.d(this.d); } } /* Location: C:\crazyd\work\ustone\odm2016031702\baidu\android\nut-dex2jar.jar * Qualified Name: u.aly.b * JD-Core Version: 0.6.2 */
UTF-8
Java
408
java
b.java
Java
[]
null
[]
package u.aly; import android.content.Context; public final class b extends fc { private Context d; public b(Context paramContext) { super("idmd5"); this.d = paramContext; } public final String a() { return cr.d(this.d); } } /* Location: C:\crazyd\work\ustone\odm2016031702\baidu\android\nut-dex2jar.jar * Qualified Name: u.aly.b * JD-Core Version: 0.6.2 */
408
0.639706
0.602941
24
16.041666
19.449677
88
false
false
0
0
0
0
0
0
0.25
false
false
11
31267ee0f4a9bf4e91ff7d4f05b3b6e817faf297
1,005,022,394,552
e217eb9e75570530fda05270fc67894e19654197
/src/com/mall/hlcloundposproject/fragments/PayDialogFragment.java
11df6a3ade23997167a7c5349af3ac5d9d8719da
[]
no_license
huaLongChuangXinYunPos/huaLongChuangXinYunPos
https://github.com/huaLongChuangXinYunPos/huaLongChuangXinYunPos
b2e089ebce7093715d0cd49fe7e2551dabb85de0
85ccb71fd06223c574d99b189e34d270e080aa97
refs/heads/master
2021-01-10T10:07:06.339000
2016-04-14T10:07:10
2016-04-14T10:07:10
50,021,337
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mall.hlcloundposproject.fragments; import java.util.ArrayList; import com.mall.hlcloundposproject.Configs; import com.mall.hlcloundposproject.R; import com.mall.hlcloundposproject.adapter.PayListViewAdapter; import com.mall.hlcloundposproject.entity.PayWayMap; import com.lidroid.xutils.ViewUtils; import com.lidroid.xutils.view.annotation.ViewInject; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.GridView; import android.widget.TextView; /** * 自定义 dialog警告框 弹出后 用于用户选择需要 的支付方式: * @author hl * zhaoq_hero@163.com */ public class PayDialogFragment extends DialogFragment implements OnItemClickListener{ /** * 用volatile修饰的变量 * 线程在每次使用变量的时候 都会读取变量修改后的值 * volatile用来进行原子性操作 */ private static volatile PayDialogFragment dialog = null; @ViewInject(R.id.pay_caculate_way) private GridView gridView; private ArrayList<String> list; private ArrayList<PayWayMap> payWays; @ViewInject(R.id.pay_fragment_money) private TextView payMon; /* * 使用 onCreateView() */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { /** * 先设置 无标题样式的 对话框 */ getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE); View view = inflater.inflate(R.layout.pay_dialog_fragment, container,true); ViewUtils.inject(this, view); list = getArguments().getStringArrayList("list"); payWays = new ArrayList<PayWayMap>(); payMon.setText("确认付款:"+getArguments().getString("payMoney")+"元"); initPayWays(); PayListViewAdapter adapter = new PayListViewAdapter(getActivity(),payWays); gridView.setAdapter(adapter); adapter.notifyDataSetChanged(); gridView.setOnItemClickListener(this); return view; } /** * 初始化 map对象: */ private void initPayWays() { for(String str : list){ PayWayMap payWayMap = new PayWayMap(); if(str.equals("人民币")){ payWayMap.setImageView(R.drawable.pay_qianbaokoukuan);//pay_qianbaokoukuan payWayMap.setTextView(str); }else if(str.equals("微信")){ payWayMap.setImageView(R.drawable.weixin); payWayMap.setTextView(str); }else if(str.equals("支付宝")){ payWayMap.setImageView(R.drawable.pay_zhifubao); payWayMap.setTextView(str); }else if(str.equals("银联卡")){ payWayMap.setImageView(R.drawable.pay_bank_card); payWayMap.setTextView(str); }else if(str.equals("钱包扣款")){ payWayMap.setImageView(R.drawable.pay_chuzhihuanbi);//pay_chuzhihuanbi payWayMap.setTextView(str); }else if(str.equals("礼金扣款")){ payWayMap.setImageView(R.drawable.pay_lijinkoukuan); payWayMap.setTextView(str); }else if(str.equals("礼券")){ payWayMap.setImageView(R.drawable.pay_liquan); payWayMap.setTextView(str); }else if(str.equals("储值换货")){ payWayMap.setImageView(R.drawable.pay_rmb); payWayMap.setTextView(str); }else if(str.equals("现金卡")){ payWayMap.setImageView(R.drawable.pay_xianjincard); payWayMap.setTextView(str); }else if(str.equals("京东到家")){ payWayMap.setImageView(R.drawable.pay_jingdong_to_home); payWayMap.setTextView(str); }else if(str.equals("京东差价")){ payWayMap.setImageView(R.drawable.pay_jingdong_chajia); payWayMap.setTextView(str); }else if(str.equals("京东补价")){ payWayMap.setImageView(R.drawable.pay_jingdong_bujia); payWayMap.setTextView(str); }else{ payWayMap.setImageView(R.drawable.ic_launcher); payWayMap.setTextView(str); } payWays.add(payWayMap); } } public static PayDialogFragment getInstance(ArrayList<String> list,String payMoney) { dialog = new PayDialogFragment(); Bundle bundle = new Bundle(); bundle.putStringArrayList("list", list); bundle.putString("payMoney",payMoney); dialog.setArguments(bundle); return dialog; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); callback = (FragmentCallback) getActivity(); } private FragmentCallback callback; @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { callback.fragmentCallback(arg2+"", Configs.GET_CALCULATE_WAY_AUTHORITY); onDestroyView(); } }
GB18030
Java
4,962
java
PayDialogFragment.java
Java
[ { "context": "自定义 dialog警告框 弹出后 用于用户选择需要 的支付方式:\r\n * @author hl\r\n * zhaoq_hero@163.com\r\n */\r\npublic class PayDial", "end": 798, "score": 0.3451114296913147, "start": 796, "tag": "USERNAME", "value": "hl" }, { "context": "alog警告框 弹出后 用于用户选择需要 的支付方式:\r\n * @author hl\r\n * zhaoq_hero@163.com\r\n */\r\npublic class PayDialogFragment extends Dial", "end": 821, "score": 0.9999240636825562, "start": 803, "tag": "EMAIL", "value": "zhaoq_hero@163.com" } ]
null
[]
package com.mall.hlcloundposproject.fragments; import java.util.ArrayList; import com.mall.hlcloundposproject.Configs; import com.mall.hlcloundposproject.R; import com.mall.hlcloundposproject.adapter.PayListViewAdapter; import com.mall.hlcloundposproject.entity.PayWayMap; import com.lidroid.xutils.ViewUtils; import com.lidroid.xutils.view.annotation.ViewInject; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.GridView; import android.widget.TextView; /** * 自定义 dialog警告框 弹出后 用于用户选择需要 的支付方式: * @author hl * <EMAIL> */ public class PayDialogFragment extends DialogFragment implements OnItemClickListener{ /** * 用volatile修饰的变量 * 线程在每次使用变量的时候 都会读取变量修改后的值 * volatile用来进行原子性操作 */ private static volatile PayDialogFragment dialog = null; @ViewInject(R.id.pay_caculate_way) private GridView gridView; private ArrayList<String> list; private ArrayList<PayWayMap> payWays; @ViewInject(R.id.pay_fragment_money) private TextView payMon; /* * 使用 onCreateView() */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { /** * 先设置 无标题样式的 对话框 */ getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE); View view = inflater.inflate(R.layout.pay_dialog_fragment, container,true); ViewUtils.inject(this, view); list = getArguments().getStringArrayList("list"); payWays = new ArrayList<PayWayMap>(); payMon.setText("确认付款:"+getArguments().getString("payMoney")+"元"); initPayWays(); PayListViewAdapter adapter = new PayListViewAdapter(getActivity(),payWays); gridView.setAdapter(adapter); adapter.notifyDataSetChanged(); gridView.setOnItemClickListener(this); return view; } /** * 初始化 map对象: */ private void initPayWays() { for(String str : list){ PayWayMap payWayMap = new PayWayMap(); if(str.equals("人民币")){ payWayMap.setImageView(R.drawable.pay_qianbaokoukuan);//pay_qianbaokoukuan payWayMap.setTextView(str); }else if(str.equals("微信")){ payWayMap.setImageView(R.drawable.weixin); payWayMap.setTextView(str); }else if(str.equals("支付宝")){ payWayMap.setImageView(R.drawable.pay_zhifubao); payWayMap.setTextView(str); }else if(str.equals("银联卡")){ payWayMap.setImageView(R.drawable.pay_bank_card); payWayMap.setTextView(str); }else if(str.equals("钱包扣款")){ payWayMap.setImageView(R.drawable.pay_chuzhihuanbi);//pay_chuzhihuanbi payWayMap.setTextView(str); }else if(str.equals("礼金扣款")){ payWayMap.setImageView(R.drawable.pay_lijinkoukuan); payWayMap.setTextView(str); }else if(str.equals("礼券")){ payWayMap.setImageView(R.drawable.pay_liquan); payWayMap.setTextView(str); }else if(str.equals("储值换货")){ payWayMap.setImageView(R.drawable.pay_rmb); payWayMap.setTextView(str); }else if(str.equals("现金卡")){ payWayMap.setImageView(R.drawable.pay_xianjincard); payWayMap.setTextView(str); }else if(str.equals("京东到家")){ payWayMap.setImageView(R.drawable.pay_jingdong_to_home); payWayMap.setTextView(str); }else if(str.equals("京东差价")){ payWayMap.setImageView(R.drawable.pay_jingdong_chajia); payWayMap.setTextView(str); }else if(str.equals("京东补价")){ payWayMap.setImageView(R.drawable.pay_jingdong_bujia); payWayMap.setTextView(str); }else{ payWayMap.setImageView(R.drawable.ic_launcher); payWayMap.setTextView(str); } payWays.add(payWayMap); } } public static PayDialogFragment getInstance(ArrayList<String> list,String payMoney) { dialog = new PayDialogFragment(); Bundle bundle = new Bundle(); bundle.putStringArrayList("list", list); bundle.putString("payMoney",payMoney); dialog.setArguments(bundle); return dialog; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); callback = (FragmentCallback) getActivity(); } private FragmentCallback callback; @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { callback.fragmentCallback(arg2+"", Configs.GET_CALCULATE_WAY_AUTHORITY); onDestroyView(); } }
4,951
0.687261
0.68535
152
28.986841
22.021217
86
false
false
0
0
0
0
0
0
2.039474
false
false
11
569fea3ed7ae011103a2a6743fb4098792c6525b
33,097,017,996,956
7e3bc7b4e71438fb4aa4be795ef1eb11eacbaff5
/app/src/main/java/com/snow/crazydemo/json/model/Model_FromJson_Gson.java
09a5f1f87ca4918fd919327aa3ee8c716f62d97b
[]
no_license
snow888ak/CrazyDemo
https://github.com/snow888ak/CrazyDemo
9094085752f4a88860e4923af02b3350fab9bd17
387bffc74ce991a02dce9e2a5772a1719eb98e02
refs/heads/master
2016-09-16T13:41:25.444000
2016-07-12T14:51:18
2016-07-12T14:51:18
59,874,039
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.snow.crazydemo.json.model; import android.printservice.PrintService; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.snow.crazydemo.json.entity.Person; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; /** * Created by Snow.ZhK on 2016/5/28. */ public class Model_FromJson_Gson implements Model_FromJson { @Override public String getJsonData() { Person person = new Person(); person.setName("小李"); person.setAge(25); person.setSex("女"); return new Gson().toJson(person); } @Override public String getJsonDatas() { List<Person> result = new ArrayList<>(); for(int i = 0; i < 5; i++){ Person person = new Person(); person.setName("小钱"+i); person.setAge(20+2*i); if(i % 2 == 0) { person.setSex("女"); }else { person.setSex("男"); } result.add(person); } return new Gson().toJson(result); } @Override public Object parseJsonData(String json) { Gson gson = new Gson(); return gson.fromJson(json, Person.class); } @Override public List<Person> parseJsonDatas(String json) { Gson gson = new Gson(); Type tyep = new TypeToken<List<Person>>(){}.getType(); return gson.fromJson(json, tyep); } }
UTF-8
Java
1,460
java
Model_FromJson_Gson.java
Java
[ { "context": "rayList;\nimport java.util.List;\n\n/**\n * Created by Snow.ZhK on 2016/5/28.\n */\npublic class Model_FromJson_Gso", "end": 310, "score": 0.9543852806091309, "start": 302, "tag": "USERNAME", "value": "Snow.ZhK" }, { "context": "on person = new Person();\n person.setName(\"小李\");\n person.setAge(25);\n person.setS", "end": 502, "score": 0.9989464282989502, "start": 500, "tag": "NAME", "value": "小李" }, { "context": "erson = new Person();\n person.setName(\"小钱\"+i);\n person.setAge(20+2*i);\n ", "end": 816, "score": 0.9979032874107361, "start": 814, "tag": "NAME", "value": "小钱" } ]
null
[]
package com.snow.crazydemo.json.model; import android.printservice.PrintService; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.snow.crazydemo.json.entity.Person; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; /** * Created by Snow.ZhK on 2016/5/28. */ public class Model_FromJson_Gson implements Model_FromJson { @Override public String getJsonData() { Person person = new Person(); person.setName("小李"); person.setAge(25); person.setSex("女"); return new Gson().toJson(person); } @Override public String getJsonDatas() { List<Person> result = new ArrayList<>(); for(int i = 0; i < 5; i++){ Person person = new Person(); person.setName("小钱"+i); person.setAge(20+2*i); if(i % 2 == 0) { person.setSex("女"); }else { person.setSex("男"); } result.add(person); } return new Gson().toJson(result); } @Override public Object parseJsonData(String json) { Gson gson = new Gson(); return gson.fromJson(json, Person.class); } @Override public List<Person> parseJsonDatas(String json) { Gson gson = new Gson(); Type tyep = new TypeToken<List<Person>>(){}.getType(); return gson.fromJson(json, tyep); } }
1,460
0.582296
0.571231
55
25.290909
17.389311
62
false
false
0
0
0
0
0
0
0.545455
false
false
11
98bd7fb5f9019745d085e8cc97c04929d9769216
33,792,802,714,991
a4628d113b6e6cf9a91e699c88c5de7abc013bfe
/src/threadSketch/ThreadReport.java
2210b2152c749a13f247b542d5acab851acf5b8d
[ "Apache-2.0" ]
permissive
yin8686/threadSketch
https://github.com/yin8686/threadSketch
bbcc78d4980ee0989feba475eccc356ba565955f
b5a5cb477139ef2866c5fb502eaf8f799eb67ad6
refs/heads/master
2021-06-19T01:31:05.634000
2017-07-05T10:51:38
2017-07-05T10:51:38
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package threadSketch; import java.text.SimpleDateFormat; import java.util.Date; /** * * @author Melvin S. Metzger */ public class ThreadReport { static final String REPORT_REASON_CONSTRUCTOR_END = "CONSTRUCTOR_END"; static final String REPORT_REASON_INTERRUPT_START = "INTERRUPT_START"; static final String REPORT_REASON_INTERRUPT_END = "INTERRUPT_END"; static final String REPORT_REASON_JOIN_START = "JOIN_START"; static final String REPORT_REASON_JOIN_END = "JOIN_END"; static final String REPORT_REASON_RUN_START = "RUN_START"; static final String REPORT_REASON_RUN_END = "RUN_END"; static final String REPORT_REASON_SET_DAEMON_START = "SET_DAEMON_START"; static final String REPORT_REASON_SET_DAEMON_END = "SET_DAEMON_END"; static final String REPORT_REASON_SET_NAME_START = "SET_NAME_START"; static final String REPORT_REASON_SET_NAME_END = "SET_NAME_END"; static final String REPORT_REASON_SET_PRIO_START = "SET_PRIO_START"; static final String REPORT_REASON_SET_PRIO_END = "SET_PRIO_END"; static final String REPORT_REASON_SLEEP_START = "SLEEP_START"; static final String REPORT_REASON_SLEEP_END = "SLEEP_END"; static final String REPORT_REASON_START_START = "START_START"; static final String REPORT_REASON_START_END = "START_END"; static final String REPORT_REASON_YIELD_START = "YIELD_START"; static final String REPORT_REASON_YIELD_END = "YIELD_END"; static final String REPORT_REASON_POST = "POST"; private final String reportReason; private final long threadId; private final String name; private final int priority; private final Thread.State state; private final boolean isAlive; private final boolean isDaemon; private final boolean isInterrupted; private final Date timestamp; private final String post; private final long currentThreadId; public ThreadReport(String reportReason, long threadId, String name, int priority, Thread.State state, boolean isAlive, boolean isDaemon, boolean isInterrupted, Date timestamp, long currentThreadId) { this.reportReason = reportReason; this.threadId = threadId; this.name = name; this.priority = priority; this.state = state; this.isAlive = isAlive; this.isDaemon = isDaemon; this.isInterrupted = isInterrupted; this.timestamp = timestamp; this.currentThreadId = currentThreadId; this.post = null; } public ThreadReport(String reportReason, Thread reportingThread) { this.reportReason = reportReason; this.threadId = reportingThread.getId(); this.name = reportingThread.getName(); this.priority = reportingThread.getPriority(); this.state = reportingThread.getState(); this.isAlive = reportingThread.isAlive(); this.isDaemon = reportingThread.isDaemon(); this.isInterrupted = reportingThread.isInterrupted(); this.timestamp = new Date(); this.currentThreadId = reportingThread.currentThread().getId(); this.post = null; } public ThreadReport(Thread reportingThread, String post) { this.reportReason = REPORT_REASON_POST; this.threadId = reportingThread.getId(); this.name = reportingThread.getName(); this.priority = reportingThread.getPriority(); this.state = reportingThread.getState(); this.isAlive = reportingThread.isAlive(); this.isDaemon = reportingThread.isDaemon(); this.isInterrupted = reportingThread.isInterrupted(); this.timestamp = new Date(); this.currentThreadId = reportingThread.currentThread().getId(); this.post = post; } public String csvString(){ SimpleDateFormat stf = new SimpleDateFormat("HH:mm:ss:SS"); return("" + threadId + ";" + name + ";" + reportReason + ";" + priority + ";" + state.toString() + ";" + isAlive + ";" + isDaemon + ";" + isInterrupted + ";" + stf.format(timestamp)+ ";" + Long.toString(currentThreadId)); } public String toString() { SimpleDateFormat stf = new SimpleDateFormat("HH:mm:ss:SS"); return ("threadId: " + threadId + "\nname: " + name + "\nreport reason: " + reportReason + "\npriority: " + priority + "\nstate: " + state.toString() + "\nisAlive: " + isAlive + "\nisDaemon: " + isDaemon + "\nisInterrupted: " + isInterrupted + "\ntimestamp: " + stf.format(timestamp) + "\ncurrentThreadId: " + Long.toString(currentThreadId)); } public long getThreadId() { return threadId; } public long getCurrentThreadId() { return currentThreadId; } public String getName() { return name; } public int getPriority() { return priority; } public String getPost() { return post; } public Thread.State getState() { return state; } public String getReportReason() { return reportReason; } public boolean isIsAlive() { return isAlive; } public boolean isIsDaemon() { return isDaemon; } public boolean isIsInterrupted() { return isInterrupted; } public Date getTimestamp() { return timestamp; } }
UTF-8
Java
5,317
java
ThreadReport.java
Java
[ { "context": "eFormat;\nimport java.util.Date;\n\n/**\n *\n * @author Melvin S. Metzger\n */\npublic class ThreadReport {\n\n static final", "end": 119, "score": 0.9998862147331238, "start": 102, "tag": "NAME", "value": "Melvin S. Metzger" }, { "context": " this.threadId = threadId;\n this.name = name;\n this.priority = priority;\n this.s", "end": 2197, "score": 0.9910687804222107, "start": 2193, "tag": "NAME", "value": "name" } ]
null
[]
package threadSketch; import java.text.SimpleDateFormat; import java.util.Date; /** * * @author <NAME> */ public class ThreadReport { static final String REPORT_REASON_CONSTRUCTOR_END = "CONSTRUCTOR_END"; static final String REPORT_REASON_INTERRUPT_START = "INTERRUPT_START"; static final String REPORT_REASON_INTERRUPT_END = "INTERRUPT_END"; static final String REPORT_REASON_JOIN_START = "JOIN_START"; static final String REPORT_REASON_JOIN_END = "JOIN_END"; static final String REPORT_REASON_RUN_START = "RUN_START"; static final String REPORT_REASON_RUN_END = "RUN_END"; static final String REPORT_REASON_SET_DAEMON_START = "SET_DAEMON_START"; static final String REPORT_REASON_SET_DAEMON_END = "SET_DAEMON_END"; static final String REPORT_REASON_SET_NAME_START = "SET_NAME_START"; static final String REPORT_REASON_SET_NAME_END = "SET_NAME_END"; static final String REPORT_REASON_SET_PRIO_START = "SET_PRIO_START"; static final String REPORT_REASON_SET_PRIO_END = "SET_PRIO_END"; static final String REPORT_REASON_SLEEP_START = "SLEEP_START"; static final String REPORT_REASON_SLEEP_END = "SLEEP_END"; static final String REPORT_REASON_START_START = "START_START"; static final String REPORT_REASON_START_END = "START_END"; static final String REPORT_REASON_YIELD_START = "YIELD_START"; static final String REPORT_REASON_YIELD_END = "YIELD_END"; static final String REPORT_REASON_POST = "POST"; private final String reportReason; private final long threadId; private final String name; private final int priority; private final Thread.State state; private final boolean isAlive; private final boolean isDaemon; private final boolean isInterrupted; private final Date timestamp; private final String post; private final long currentThreadId; public ThreadReport(String reportReason, long threadId, String name, int priority, Thread.State state, boolean isAlive, boolean isDaemon, boolean isInterrupted, Date timestamp, long currentThreadId) { this.reportReason = reportReason; this.threadId = threadId; this.name = name; this.priority = priority; this.state = state; this.isAlive = isAlive; this.isDaemon = isDaemon; this.isInterrupted = isInterrupted; this.timestamp = timestamp; this.currentThreadId = currentThreadId; this.post = null; } public ThreadReport(String reportReason, Thread reportingThread) { this.reportReason = reportReason; this.threadId = reportingThread.getId(); this.name = reportingThread.getName(); this.priority = reportingThread.getPriority(); this.state = reportingThread.getState(); this.isAlive = reportingThread.isAlive(); this.isDaemon = reportingThread.isDaemon(); this.isInterrupted = reportingThread.isInterrupted(); this.timestamp = new Date(); this.currentThreadId = reportingThread.currentThread().getId(); this.post = null; } public ThreadReport(Thread reportingThread, String post) { this.reportReason = REPORT_REASON_POST; this.threadId = reportingThread.getId(); this.name = reportingThread.getName(); this.priority = reportingThread.getPriority(); this.state = reportingThread.getState(); this.isAlive = reportingThread.isAlive(); this.isDaemon = reportingThread.isDaemon(); this.isInterrupted = reportingThread.isInterrupted(); this.timestamp = new Date(); this.currentThreadId = reportingThread.currentThread().getId(); this.post = post; } public String csvString(){ SimpleDateFormat stf = new SimpleDateFormat("HH:mm:ss:SS"); return("" + threadId + ";" + name + ";" + reportReason + ";" + priority + ";" + state.toString() + ";" + isAlive + ";" + isDaemon + ";" + isInterrupted + ";" + stf.format(timestamp)+ ";" + Long.toString(currentThreadId)); } public String toString() { SimpleDateFormat stf = new SimpleDateFormat("HH:mm:ss:SS"); return ("threadId: " + threadId + "\nname: " + name + "\nreport reason: " + reportReason + "\npriority: " + priority + "\nstate: " + state.toString() + "\nisAlive: " + isAlive + "\nisDaemon: " + isDaemon + "\nisInterrupted: " + isInterrupted + "\ntimestamp: " + stf.format(timestamp) + "\ncurrentThreadId: " + Long.toString(currentThreadId)); } public long getThreadId() { return threadId; } public long getCurrentThreadId() { return currentThreadId; } public String getName() { return name; } public int getPriority() { return priority; } public String getPost() { return post; } public Thread.State getState() { return state; } public String getReportReason() { return reportReason; } public boolean isIsAlive() { return isAlive; } public boolean isIsDaemon() { return isDaemon; } public boolean isIsInterrupted() { return isInterrupted; } public Date getTimestamp() { return timestamp; } }
5,306
0.656009
0.656009
149
34.684563
33.071224
229
false
false
0
0
0
0
0
0
0.684564
false
false
11
8c1fa6adfae6923dfbf8c6594bd7bf8fc847673b
37,580,963,847,643
b585a4ef62d44b7e2635f74ec9a579dc333086f4
/modules/web/src/com/company/dealer/web/screens/person/PersonEdit.java
58e1c16a9d815ac8e75245eb6e90ac7ce135de79
[]
no_license
pavel-alshev/autodealer
https://github.com/pavel-alshev/autodealer
e2832708cebc4b79ac6af6fe41fe790d29bc0e3b
4ebfe058f5ca10e8f676734cc779ff59c962da75
refs/heads/master
2022-10-24T16:43:46.024000
2020-06-16T12:37:29
2020-06-16T12:37:29
272,700,867
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.company.dealer.web.screens.person; import com.haulmont.cuba.gui.screen.*; import com.company.dealer.entity.Person; @UiController("dealer_Person.edit") @UiDescriptor("person-edit.xml") @EditedEntityContainer("personDc") @LoadDataBeforeShow public class PersonEdit extends StandardEditor<Person> { }
UTF-8
Java
311
java
PersonEdit.java
Java
[]
null
[]
package com.company.dealer.web.screens.person; import com.haulmont.cuba.gui.screen.*; import com.company.dealer.entity.Person; @UiController("dealer_Person.edit") @UiDescriptor("person-edit.xml") @EditedEntityContainer("personDc") @LoadDataBeforeShow public class PersonEdit extends StandardEditor<Person> { }
311
0.807074
0.807074
11
27.363636
18.651213
56
false
false
0
0
0
0
0
0
0.272727
false
false
11
526d6d9bb80490822aef2286ed3c69276b989ed6
14,310,831,094,042
01601cd19614f16a87f331af3b43078dd5721352
/src/test/java/org/apache/sling/pipes/internal/PlumberServletTest.java
9c8d978d788d5865a15ae451a15c7e2a2884d4ec
[ "Apache-2.0" ]
permissive
apache/sling-org-apache-sling-pipes
https://github.com/apache/sling-org-apache-sling-pipes
267dd0e135faca5766b227cb3309908a1f457960
9c0687f0e7a650edb10f77cf6752c8d88a6be495
refs/heads/master
2023-08-20T17:36:11.306000
2023-04-04T21:12:55
2023-04-04T21:12:55
107,434,909
9
23
Apache-2.0
false
2023-09-08T12:20:33
2017-10-18T16:33:55
2022-11-21T03:25:51
2023-09-08T12:20:32
763
8
19
2
Java
false
false
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.sling.pipes.internal; import org.apache.commons.lang3.StringUtils; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.request.RequestPathInfo; import org.apache.sling.api.resource.PersistenceException; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.api.resource.ValueMap; import org.apache.sling.pipes.AbstractPipeTest; import org.apache.sling.pipes.BasePipe; import org.apache.sling.pipes.ContainerPipeTest; import org.apache.sling.pipes.OutputWriter; import org.junit.Before; import org.junit.Test; import javax.json.Json; import javax.json.JsonArray; import javax.json.JsonObject; import javax.servlet.ServletException; import java.io.IOException; import java.io.PrintWriter; import java.io.StringReader; import java.io.StringWriter; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * testing the servlet logic (parameters & output) */ public class PlumberServletTest extends AbstractPipeTest { static final int DUMMYTREE_TEST_SIZE = 4; String containersPath = PATH_PIPE + "/" + "containers"; String dummyTreePath = containersPath + "/" + ContainerPipeTest.NN_DUMMYTREE; String writePath = PATH_PIPE + "/" + "write"; String pipedWritePath = writePath + "/" + WritePipeTest.NN_PIPED; StringWriter stringResponse; SlingHttpServletResponse response; PlumberServlet servlet = new PlumberServlet(); @Before public void setup() throws PersistenceException { super.setup(); context.load().json("/plumber.json", PATH_PIPE); context.load().json("/container.json", containersPath); context.load().json("/write.json", writePath); servlet.plumber = plumber; servlet.enabled = true; stringResponse = new StringWriter(); try { response = mockPlumberServletResponse(stringResponse); } catch (Exception e){ } } private void assertDummyTree(int size) { String finalResponse = stringResponse.toString(); assertFalse("There should be a response", StringUtils.isBlank(finalResponse)); JsonObject object = Json.createReader(new StringReader(finalResponse)).readObject(); assertEquals("response should be an obj with size value equals to " + DUMMYTREE_TEST_SIZE, object.getInt(OutputWriter.KEY_SIZE), DUMMYTREE_TEST_SIZE); assertEquals("response should be an obj with items value equals to a " + size + " valued array", object.getJsonArray(OutputWriter.KEY_ITEMS).size(), size); } private void assertDummyTree() { assertDummyTree(DUMMYTREE_TEST_SIZE); } @Test public void testDummyTreeThroughRT() throws Exception { SlingHttpServletRequest request = mockPlumberServletRequest(context.resourceResolver(), "json", dummyTreePath, null, null, null, null, null); servlet.execute(request, response, false); assertDummyTree(); } @Test public void testDummyTreeThroughPlumber() throws Exception { SlingHttpServletRequest request = mockPlumberServletRequest(context.resourceResolver(), "json", PATH_PIPE, dummyTreePath, null, null, null, null); servlet.execute(request, response, false); assertDummyTree(); } @Test public void testWriteExecute() throws ServletException { SlingHttpServletRequest request = mockPlumberServletRequest(context.resourceResolver(), "json", pipedWritePath, null, null, null, null, null); servlet.execute(request, response, true); String finalResponse = stringResponse.toString(); assertFalse("There should be a response", StringUtils.isBlank(finalResponse)); assertFalse("There should be no more pending changes", context.resourceResolver().hasChanges()); } /** * in this test we execute a pipe that modifies content, with a flag mocking the GET request: * the execution should fail. */ @Test public void testGetOnWriteExecute() { SlingHttpServletRequest request = mockPlumberServletRequest(context.resourceResolver(), "json", pipedWritePath, null, null, null, null, null); boolean hasFailed = true; try { servlet.execute(request, response, false); hasFailed = false; } catch (Exception e){ } assertTrue("Execution should have failed", hasFailed); } /** * in this test we execute a pipe that modifies content, with a flag mocking the GET request, but with a dryRun parameter * the execution should *not* fail. */ @Test public void testGetOnOnDryRUnWriteExecute() { SlingHttpServletRequest request = mockPlumberServletRequest(context.resourceResolver(), "json", pipedWritePath, null, null, null, "true", "-1"); boolean hasFailed = true; try { servlet.execute(request, response, false); hasFailed = false; } catch (Exception e){} assertFalse("Execution should not have failed", hasFailed); } @Test public void testAdditionalBindingsAndWriter() throws Exception { String bindings = "{\"testBinding\":\"testBindingValue\"}"; String respObject = "pathLength=path.get(\"dummyGrandChild\").length(),testBindingValue=testBinding.length()"; SlingHttpServletRequest request = mockPlumberServletRequest(context.resourceResolver(), "json", dummyTreePath, null, bindings, respObject, null, null); servlet.execute(request, response, false); assertDummyTree(); JsonObject response = Json.createReader(new StringReader(stringResponse.toString())).readObject(); JsonArray array = response.getJsonArray(OutputWriter.KEY_ITEMS); for (int i = 0; i < array.size(); i++) { JsonObject object = array.getJsonObject(i); assertNotNull("there should be an object returned at each time", object); String path = object.getString(OutputWriter.PATH_KEY); assertNotNull("the string path should be returned for each item, containing the path of the resource"); String pathLength = object.getString("pathLength"); assertNotNull("there should be a pathLength param, as specified in the writer", pathLength); assertEquals("Pathlength should be the string representation of the path length", path.length() + "", pathLength); String testBindingLengthValue = object.getString("testBindingValue", null); assertNotNull("testBindingLength should be there", testBindingLengthValue); assertEquals("testBindingLength should be the string representation of the additional binding length", "testBindingValue".length() + "", testBindingLengthValue); } } @Test public void testDryRun() throws Exception { SlingHttpServletRequest dryRunRequest = mockPlumberServletRequest(context.resourceResolver(), "json", pipedWritePath, null, null, null, "true", null); servlet.execute(dryRunRequest, response, true); Resource resource = context.resourceResolver().getResource("/content/fruits"); ValueMap properties = resource.adaptTo(ValueMap.class); assertFalse("property fruits shouldn't have been written", properties.containsKey("fruits")); SlingHttpServletRequest request = mockPlumberServletRequest(context.resourceResolver(), "json", pipedWritePath, null, null, null, "false", null); servlet.execute(request, response, true); WritePipeTest.assertPiped(resource); } @Test public void testDummyTreeSizeLimit() throws Exception { SlingHttpServletRequest request = mockPlumberServletRequest(context.resourceResolver(), "json", dummyTreePath, null, null, null, null, "2"); servlet.execute(request, response, false); assertDummyTree(2); } @Test public void testDummyTreeInfiniteSize() throws Exception { SlingHttpServletRequest request = mockPlumberServletRequest(context.resourceResolver(), "json", dummyTreePath, null, null, null, null, "-1"); servlet.execute(request, response, false); assertDummyTree(DUMMYTREE_TEST_SIZE); } public static SlingHttpServletRequest mockPlumberServletRequest(ResourceResolver resolver, String extension, String path, String pathParam, String bindings, String writer, String dryRun, String size) { SlingHttpServletRequest request = mock(SlingHttpServletRequest.class); RequestPathInfo pathInfo = mock(RequestPathInfo.class); when(pathInfo.getExtension()).thenReturn(extension); when(request.getRequestPathInfo()).thenReturn(pathInfo); Resource resource = resolver.getResource(path); when(request.getResourceResolver()).thenReturn(resolver); when(request.getResource()).thenReturn(resource); when(request.getParameter(PlumberServlet.PARAM_PATH)).thenReturn(pathParam); when(request.getParameter(PlumberServlet.PARAM_BINDINGS)).thenReturn(bindings); when(request.getParameter(OutputWriter.PARAM_WRITER)).thenReturn(writer); when(request.getParameter(BasePipe.DRYRUN_KEY)).thenReturn(dryRun); when(request.getParameter(OutputWriter.PARAM_SIZE)).thenReturn(size); return request; } public static SlingHttpServletResponse mockPlumberServletResponse(StringWriter writer) throws IOException { SlingHttpServletResponse response = mock(SlingHttpServletResponse.class); PrintWriter printWriter = new PrintWriter(writer); when(response.getWriter()).thenReturn(printWriter); return response; } }
UTF-8
Java
11,260
java
PlumberServletTest.java
Java
[]
null
[]
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.sling.pipes.internal; import org.apache.commons.lang3.StringUtils; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.request.RequestPathInfo; import org.apache.sling.api.resource.PersistenceException; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.api.resource.ValueMap; import org.apache.sling.pipes.AbstractPipeTest; import org.apache.sling.pipes.BasePipe; import org.apache.sling.pipes.ContainerPipeTest; import org.apache.sling.pipes.OutputWriter; import org.junit.Before; import org.junit.Test; import javax.json.Json; import javax.json.JsonArray; import javax.json.JsonObject; import javax.servlet.ServletException; import java.io.IOException; import java.io.PrintWriter; import java.io.StringReader; import java.io.StringWriter; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * testing the servlet logic (parameters & output) */ public class PlumberServletTest extends AbstractPipeTest { static final int DUMMYTREE_TEST_SIZE = 4; String containersPath = PATH_PIPE + "/" + "containers"; String dummyTreePath = containersPath + "/" + ContainerPipeTest.NN_DUMMYTREE; String writePath = PATH_PIPE + "/" + "write"; String pipedWritePath = writePath + "/" + WritePipeTest.NN_PIPED; StringWriter stringResponse; SlingHttpServletResponse response; PlumberServlet servlet = new PlumberServlet(); @Before public void setup() throws PersistenceException { super.setup(); context.load().json("/plumber.json", PATH_PIPE); context.load().json("/container.json", containersPath); context.load().json("/write.json", writePath); servlet.plumber = plumber; servlet.enabled = true; stringResponse = new StringWriter(); try { response = mockPlumberServletResponse(stringResponse); } catch (Exception e){ } } private void assertDummyTree(int size) { String finalResponse = stringResponse.toString(); assertFalse("There should be a response", StringUtils.isBlank(finalResponse)); JsonObject object = Json.createReader(new StringReader(finalResponse)).readObject(); assertEquals("response should be an obj with size value equals to " + DUMMYTREE_TEST_SIZE, object.getInt(OutputWriter.KEY_SIZE), DUMMYTREE_TEST_SIZE); assertEquals("response should be an obj with items value equals to a " + size + " valued array", object.getJsonArray(OutputWriter.KEY_ITEMS).size(), size); } private void assertDummyTree() { assertDummyTree(DUMMYTREE_TEST_SIZE); } @Test public void testDummyTreeThroughRT() throws Exception { SlingHttpServletRequest request = mockPlumberServletRequest(context.resourceResolver(), "json", dummyTreePath, null, null, null, null, null); servlet.execute(request, response, false); assertDummyTree(); } @Test public void testDummyTreeThroughPlumber() throws Exception { SlingHttpServletRequest request = mockPlumberServletRequest(context.resourceResolver(), "json", PATH_PIPE, dummyTreePath, null, null, null, null); servlet.execute(request, response, false); assertDummyTree(); } @Test public void testWriteExecute() throws ServletException { SlingHttpServletRequest request = mockPlumberServletRequest(context.resourceResolver(), "json", pipedWritePath, null, null, null, null, null); servlet.execute(request, response, true); String finalResponse = stringResponse.toString(); assertFalse("There should be a response", StringUtils.isBlank(finalResponse)); assertFalse("There should be no more pending changes", context.resourceResolver().hasChanges()); } /** * in this test we execute a pipe that modifies content, with a flag mocking the GET request: * the execution should fail. */ @Test public void testGetOnWriteExecute() { SlingHttpServletRequest request = mockPlumberServletRequest(context.resourceResolver(), "json", pipedWritePath, null, null, null, null, null); boolean hasFailed = true; try { servlet.execute(request, response, false); hasFailed = false; } catch (Exception e){ } assertTrue("Execution should have failed", hasFailed); } /** * in this test we execute a pipe that modifies content, with a flag mocking the GET request, but with a dryRun parameter * the execution should *not* fail. */ @Test public void testGetOnOnDryRUnWriteExecute() { SlingHttpServletRequest request = mockPlumberServletRequest(context.resourceResolver(), "json", pipedWritePath, null, null, null, "true", "-1"); boolean hasFailed = true; try { servlet.execute(request, response, false); hasFailed = false; } catch (Exception e){} assertFalse("Execution should not have failed", hasFailed); } @Test public void testAdditionalBindingsAndWriter() throws Exception { String bindings = "{\"testBinding\":\"testBindingValue\"}"; String respObject = "pathLength=path.get(\"dummyGrandChild\").length(),testBindingValue=testBinding.length()"; SlingHttpServletRequest request = mockPlumberServletRequest(context.resourceResolver(), "json", dummyTreePath, null, bindings, respObject, null, null); servlet.execute(request, response, false); assertDummyTree(); JsonObject response = Json.createReader(new StringReader(stringResponse.toString())).readObject(); JsonArray array = response.getJsonArray(OutputWriter.KEY_ITEMS); for (int i = 0; i < array.size(); i++) { JsonObject object = array.getJsonObject(i); assertNotNull("there should be an object returned at each time", object); String path = object.getString(OutputWriter.PATH_KEY); assertNotNull("the string path should be returned for each item, containing the path of the resource"); String pathLength = object.getString("pathLength"); assertNotNull("there should be a pathLength param, as specified in the writer", pathLength); assertEquals("Pathlength should be the string representation of the path length", path.length() + "", pathLength); String testBindingLengthValue = object.getString("testBindingValue", null); assertNotNull("testBindingLength should be there", testBindingLengthValue); assertEquals("testBindingLength should be the string representation of the additional binding length", "testBindingValue".length() + "", testBindingLengthValue); } } @Test public void testDryRun() throws Exception { SlingHttpServletRequest dryRunRequest = mockPlumberServletRequest(context.resourceResolver(), "json", pipedWritePath, null, null, null, "true", null); servlet.execute(dryRunRequest, response, true); Resource resource = context.resourceResolver().getResource("/content/fruits"); ValueMap properties = resource.adaptTo(ValueMap.class); assertFalse("property fruits shouldn't have been written", properties.containsKey("fruits")); SlingHttpServletRequest request = mockPlumberServletRequest(context.resourceResolver(), "json", pipedWritePath, null, null, null, "false", null); servlet.execute(request, response, true); WritePipeTest.assertPiped(resource); } @Test public void testDummyTreeSizeLimit() throws Exception { SlingHttpServletRequest request = mockPlumberServletRequest(context.resourceResolver(), "json", dummyTreePath, null, null, null, null, "2"); servlet.execute(request, response, false); assertDummyTree(2); } @Test public void testDummyTreeInfiniteSize() throws Exception { SlingHttpServletRequest request = mockPlumberServletRequest(context.resourceResolver(), "json", dummyTreePath, null, null, null, null, "-1"); servlet.execute(request, response, false); assertDummyTree(DUMMYTREE_TEST_SIZE); } public static SlingHttpServletRequest mockPlumberServletRequest(ResourceResolver resolver, String extension, String path, String pathParam, String bindings, String writer, String dryRun, String size) { SlingHttpServletRequest request = mock(SlingHttpServletRequest.class); RequestPathInfo pathInfo = mock(RequestPathInfo.class); when(pathInfo.getExtension()).thenReturn(extension); when(request.getRequestPathInfo()).thenReturn(pathInfo); Resource resource = resolver.getResource(path); when(request.getResourceResolver()).thenReturn(resolver); when(request.getResource()).thenReturn(resource); when(request.getParameter(PlumberServlet.PARAM_PATH)).thenReturn(pathParam); when(request.getParameter(PlumberServlet.PARAM_BINDINGS)).thenReturn(bindings); when(request.getParameter(OutputWriter.PARAM_WRITER)).thenReturn(writer); when(request.getParameter(BasePipe.DRYRUN_KEY)).thenReturn(dryRun); when(request.getParameter(OutputWriter.PARAM_SIZE)).thenReturn(size); return request; } public static SlingHttpServletResponse mockPlumberServletResponse(StringWriter writer) throws IOException { SlingHttpServletResponse response = mock(SlingHttpServletResponse.class); PrintWriter printWriter = new PrintWriter(writer); when(response.getWriter()).thenReturn(printWriter); return response; } }
11,260
0.68286
0.681883
236
46.711864
38.611298
163
false
false
0
0
0
0
0
0
1.063559
false
false
11
9ac966268418c8b5a93f8ac7e71019fe5b8678a0
34,376,918,269,488
6e61622a781ccc0d8aabccd4e15a4733eb8c552f
/src/main/java/com/softwareengineering/temperaturecms/dao/RoomStatusMapper.java
1512a50399270c3fad224983a1e7f5a5f12e3390
[]
no_license
humveea6/DistributeTemperatureCMS-Backend
https://github.com/humveea6/DistributeTemperatureCMS-Backend
502cb9052597eafd7e4e87af95f7ba27493f432a
2ee4901db578924979d6ddfd1ef004ed4aa59ec7
refs/heads/master
2022-10-18T10:41:12.376000
2020-06-14T04:19:23
2020-06-14T04:19:23
266,374,830
1
0
null
false
2020-06-14T04:19:24
2020-05-23T16:23:41
2020-06-14T02:40:14
2020-06-14T04:19:23
133
1
0
0
Java
false
false
package com.softwareengineering.temperaturecms.dao; import com.softwareengineering.temperaturecms.pojo.RoomStatus; import com.softwareengineering.temperaturecms.pojo.RoomStatusExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface RoomStatusMapper { long countByExample(RoomStatusExample example); int deleteByExample(RoomStatusExample example); int deleteByPrimaryKey(Integer id); int insert(RoomStatus record); int insertSelective(RoomStatus record); List<RoomStatus> selectByExample(RoomStatusExample example); RoomStatus selectByPrimaryKey(Integer id); int updateByExampleSelective(@Param("record") RoomStatus record, @Param("example") RoomStatusExample example); int updateByExample(@Param("record") RoomStatus record, @Param("example") RoomStatusExample example); int updateByPrimaryKeySelective(RoomStatus record); int updateByPrimaryKey(RoomStatus record); }
UTF-8
Java
960
java
RoomStatusMapper.java
Java
[]
null
[]
package com.softwareengineering.temperaturecms.dao; import com.softwareengineering.temperaturecms.pojo.RoomStatus; import com.softwareengineering.temperaturecms.pojo.RoomStatusExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface RoomStatusMapper { long countByExample(RoomStatusExample example); int deleteByExample(RoomStatusExample example); int deleteByPrimaryKey(Integer id); int insert(RoomStatus record); int insertSelective(RoomStatus record); List<RoomStatus> selectByExample(RoomStatusExample example); RoomStatus selectByPrimaryKey(Integer id); int updateByExampleSelective(@Param("record") RoomStatus record, @Param("example") RoomStatusExample example); int updateByExample(@Param("record") RoomStatus record, @Param("example") RoomStatusExample example); int updateByPrimaryKeySelective(RoomStatus record); int updateByPrimaryKey(RoomStatus record); }
960
0.8
0.8
30
31.033333
32.132523
114
false
false
0
0
0
0
0
0
0.6
false
false
11
55673cbc6ac7b36f6a13cee6b992151dd9dadb09
19,782,619,373,731
b20b0ee69b17bbd90c89d424312b059a53ad69e3
/main/src/main/java/cgeo/geocaching/unifiedmap/tileproviders/CyclosmSource.java
888aaad6f19428f7e5b1ce10d688793dd0cf2d58
[ "Apache-2.0" ]
permissive
cgeo/cgeo
https://github.com/cgeo/cgeo
a79d26c2e916c4cd4a7acff8ec5cc2e65a42cc37
53c04cbcdc363f9c7e6e2992745f4ef83743b76b
refs/heads/master
2023-08-30T17:04:11.322000
2023-02-02T22:15:46
2023-08-30T11:06:55
2,028,724
943
504
Apache-2.0
false
2023-09-14T20:46:55
2011-07-11T06:02:47
2023-09-12T09:43:12
2023-09-14T20:46:53
446,923
1,293
581
721
Java
false
false
package cgeo.geocaching.unifiedmap.tileproviders; import android.net.Uri; class CyclosmSource extends AbstractMapsforgeOnlineTileProvider { CyclosmSource() { super("CyclOSM", Uri.parse("https://a.tile-cyclosm.openstreetmap.fr"), "/cyclosm/{Z}/{X}/{Y}.png", 0, 18); } }
UTF-8
Java
287
java
CyclosmSource.java
Java
[]
null
[]
package cgeo.geocaching.unifiedmap.tileproviders; import android.net.Uri; class CyclosmSource extends AbstractMapsforgeOnlineTileProvider { CyclosmSource() { super("CyclOSM", Uri.parse("https://a.tile-cyclosm.openstreetmap.fr"), "/cyclosm/{Z}/{X}/{Y}.png", 0, 18); } }
287
0.710801
0.700348
9
30.888889
36.561802
114
false
false
0
0
0
0
0
0
0.777778
false
false
11
2eb5206c29dc1d8d72c6bb55b9ae59cfef05d6cf
17,944,373,417,699
4e8685a50538bb982d16f56134f5cf55fce492a5
/HOMEWORKS/HW1/src/task14.java
b35aa8238cf949d72eda780c053604d395fe9bb4
[]
no_license
PavelLyutov/IT_TALANTS
https://github.com/PavelLyutov/IT_TALANTS
9aa2c7fbeec6fcf821169188e0d8a5c8a29eda44
c93a3933cabd7e66c0e2deab8831ade930daefba
refs/heads/main
2023-03-20T18:35:22.434000
2021-03-14T19:17:27
2021-03-14T19:17:27
320,243,108
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.Scanner; public class task14 { public static void main(String[] args) { System.out.println("Въведете координата за позиция в шах [1,8]:"); Scanner sc1 = new Scanner(System.in); int x1 = sc1.nextInt(); System.out.println("Въведете координата за позиция в шах [1,8]"); Scanner sc2 = new Scanner(System.in); int y1 = sc2.nextInt(); System.out.println("Въведете координата за позиция в шах [1,8]:"); Scanner sc3 = new Scanner(System.in); int x2 = sc3.nextInt(); System.out.println("Въведете координата за позиция в шах [1,8]"); Scanner s4 = new Scanner(System.in); int y2 = s4.nextInt(); if((x1 < 1 || x1>8) || (x2 < 1 || x2>8) || (y1 < 1 || y1>8) || (y2 < 1 || y2>8) ) { System.out.println("Някоя от координатите е извън интерва !"); }else { boolean z1 = false; ; boolean z2 = false; ; if ((x1 % 2 == 0) == (y1 % 2 == 0)) { z1 = true; } if ((x2 % 2 == 0) == (y2 % 2 == 0)) { z2 = true; } if (z1 == z2) { System.out.println("еднакъв цвят са !"); } else { System.out.println("не са еднакъв цвят са !"); } } } }
UTF-8
Java
1,562
java
task14.java
Java
[]
null
[]
import java.util.Scanner; public class task14 { public static void main(String[] args) { System.out.println("Въведете координата за позиция в шах [1,8]:"); Scanner sc1 = new Scanner(System.in); int x1 = sc1.nextInt(); System.out.println("Въведете координата за позиция в шах [1,8]"); Scanner sc2 = new Scanner(System.in); int y1 = sc2.nextInt(); System.out.println("Въведете координата за позиция в шах [1,8]:"); Scanner sc3 = new Scanner(System.in); int x2 = sc3.nextInt(); System.out.println("Въведете координата за позиция в шах [1,8]"); Scanner s4 = new Scanner(System.in); int y2 = s4.nextInt(); if((x1 < 1 || x1>8) || (x2 < 1 || x2>8) || (y1 < 1 || y1>8) || (y2 < 1 || y2>8) ) { System.out.println("Някоя от координатите е извън интерва !"); }else { boolean z1 = false; ; boolean z2 = false; ; if ((x1 % 2 == 0) == (y1 % 2 == 0)) { z1 = true; } if ((x2 % 2 == 0) == (y2 % 2 == 0)) { z2 = true; } if (z1 == z2) { System.out.println("еднакъв цвят са !"); } else { System.out.println("не са еднакъв цвят са !"); } } } }
1,562
0.468023
0.427326
46
28.913044
25.018103
89
false
false
0
0
0
0
0
0
0.869565
false
false
11
2d786e94b7d38656d1f57121cf2c4291d6a29473
1,889,785,639,892
0e20c0c9e690646d5e20e10afe71e3db44854d0f
/src/com/my_oa/entities/Department.java
c52ba38c95037e453c79edf0fa2ac33155887e70
[]
no_license
bieren/My_OA
https://github.com/bieren/My_OA
b44ad4c8789387c48daaf4b63216a4a346ce132d
dcf24bf58b876a515022fbdbe520129100d86c1a
refs/heads/master
2020-07-24T14:27:41.861000
2016-11-17T19:21:00
2016-11-17T19:21:00
73,788,197
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.my_oa.entities; import java.util.HashSet; import java.util.Set; public class Department { //id private Integer departmentId; //部门名称 private String departmentName; //部门经理 private Employee manager; //员工 private Set<Employee> employees = new HashSet<>(); public Integer getDepartmentId() { return departmentId; } public void setDepartmentId(Integer departmentId) { this.departmentId = departmentId; } public String getDepartmentName() { return departmentName; } public void setDepartmentName(String departmentName) { this.departmentName = departmentName; } public Employee getManager() { return manager; } public void setManager(Employee manager) { this.manager = manager; } public Set<Employee> getEmployees() { return employees; } public void setEmployees(Set<Employee> employees) { this.employees = employees; } }
UTF-8
Java
952
java
Department.java
Java
[]
null
[]
package com.my_oa.entities; import java.util.HashSet; import java.util.Set; public class Department { //id private Integer departmentId; //部门名称 private String departmentName; //部门经理 private Employee manager; //员工 private Set<Employee> employees = new HashSet<>(); public Integer getDepartmentId() { return departmentId; } public void setDepartmentId(Integer departmentId) { this.departmentId = departmentId; } public String getDepartmentName() { return departmentName; } public void setDepartmentName(String departmentName) { this.departmentName = departmentName; } public Employee getManager() { return manager; } public void setManager(Employee manager) { this.manager = manager; } public Set<Employee> getEmployees() { return employees; } public void setEmployees(Set<Employee> employees) { this.employees = employees; } }
952
0.696352
0.696352
50
16.639999
17.33639
55
false
false
0
0
0
0
0
0
1.16
false
false
11
6872c2d71fa9de054de76fe87606df82f21ef8bd
17,755,394,828,767
07b408a90ba5f9cee26c5b627eea7509cbc3eea3
/pushclient/src/main/java/com/example/Bean/FreshNewsDetailsBean.java
f325066e078c266554088fe8e806708e71cf6ebf
[]
no_license
fangchao3652/Myapp12
https://github.com/fangchao3652/Myapp12
639f911afb2668d1e8c038f0183618ef9bb31c86
961df04637a28c54b9be1694d7a5354a2b21bd14
refs/heads/master
2021-01-23T07:33:47.365000
2015-06-11T09:42:44
2015-06-11T09:42:44
33,713,013
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.Bean; /** * 新鲜事详情 * Created by supumall on 2015/4/28. */ public class FreshNewsDetailsBean extends BaseBean{ String content; public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
UTF-8
Java
310
java
FreshNewsDetailsBean.java
Java
[ { "context": "kage com.example.Bean;\n\n/**\n * 新鲜事详情\n * Created by supumall on 2015/4/28.\n */\npublic class FreshNewsDetailsBe", "end": 62, "score": 0.99965900182724, "start": 54, "tag": "USERNAME", "value": "supumall" } ]
null
[]
package com.example.Bean; /** * 新鲜事详情 * Created by supumall on 2015/4/28. */ public class FreshNewsDetailsBean extends BaseBean{ String content; public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
310
0.656667
0.633333
17
16.647058
16.666067
52
false
false
0
0
0
0
0
0
0.235294
false
false
11
1e020ee4cb3edf46f389b78971e358f387eda1ee
2,980,707,349,401
e66dba1d9f7194d4dadb2edea17b943b354ab4d1
/SerialTerminal-Android-master7/app/src/main/java/com/devmel/apps/serialterminal/MapsActivity.java
6cf393019d381fbb86bb929464fcc9eb2b16aea6
[ "MIT", "Apache-2.0" ]
permissive
axydavid/ElecTrip
https://github.com/axydavid/ElecTrip
e4d7889e42bd7db39e17e688b2a71b8fb57ec951
26f8485015477bddbef0ba6af07a512e7b6dfdfe
refs/heads/master
2021-06-04T19:53:19.176000
2021-05-06T19:16:12
2021-05-06T19:16:12
85,300,722
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.sushi.mapsapplication; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import java.util.concurrent.ExecutionException; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { String[] directionsDemo; String startPoint; String snappedRoad; private GoogleMap mMap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); } /** * Manipulates the map once available. * This callback is triggered when the map is ready to be used. * This is where we can add markers or lines, add listeners or move the camera. In this case, * we just add a marker near Sydney, Australia. * If Google Play services is not installed on the device, the user will be prompted to install * it inside the SupportMapFragment. This method will only be triggered once the user has * installed Google Play services and returned to the app. */ @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; //the format should be ("Lat,Long|Lat,Long|.........|Lat,Long") -> 1 parameter per position point! //ElevationAPI().execute(directionsDemo[0]).get(); //the format should be ("origin=copenhagen&destination=herlev") try { directionsDemo = new DirectionsAPI().execute("origin=copenhagen&destination=norrebro").get(); //a little logistick, choose 1st road alternative, split the stringso you get only lat long, not road name, distance or time directionsDemo[0] = directionsDemo[0].substring(directionsDemo[0].indexOf("#")+ "#".length()); //makes sure the lines follow the road snappedRoad = new RoadsAPI().execute(directionsDemo[0]).get(); //finally, show on the map mMap.addPolyline(new mapsAPI().onmapsAPIReady(directionsDemo[0])); //a little logistick, get the first pair of lat/long coordinates and focus the map on it startPoint = snappedRoad.substring(0,snappedRoad.indexOf("|")); String[] valuesParts = startPoint.split(",",2); LatLng sydney = new LatLng(Double.parseDouble(valuesParts[0]),Double.parseDouble(valuesParts[1])); mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(sydney,10)); } catch (InterruptedException e1) { e1.printStackTrace(); } catch (ExecutionException e1) { e1.printStackTrace(); } } }
UTF-8
Java
3,146
java
MapsActivity.java
Java
[]
null
[]
package com.example.sushi.mapsapplication; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import java.util.concurrent.ExecutionException; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { String[] directionsDemo; String startPoint; String snappedRoad; private GoogleMap mMap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); } /** * Manipulates the map once available. * This callback is triggered when the map is ready to be used. * This is where we can add markers or lines, add listeners or move the camera. In this case, * we just add a marker near Sydney, Australia. * If Google Play services is not installed on the device, the user will be prompted to install * it inside the SupportMapFragment. This method will only be triggered once the user has * installed Google Play services and returned to the app. */ @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; //the format should be ("Lat,Long|Lat,Long|.........|Lat,Long") -> 1 parameter per position point! //ElevationAPI().execute(directionsDemo[0]).get(); //the format should be ("origin=copenhagen&destination=herlev") try { directionsDemo = new DirectionsAPI().execute("origin=copenhagen&destination=norrebro").get(); //a little logistick, choose 1st road alternative, split the stringso you get only lat long, not road name, distance or time directionsDemo[0] = directionsDemo[0].substring(directionsDemo[0].indexOf("#")+ "#".length()); //makes sure the lines follow the road snappedRoad = new RoadsAPI().execute(directionsDemo[0]).get(); //finally, show on the map mMap.addPolyline(new mapsAPI().onmapsAPIReady(directionsDemo[0])); //a little logistick, get the first pair of lat/long coordinates and focus the map on it startPoint = snappedRoad.substring(0,snappedRoad.indexOf("|")); String[] valuesParts = startPoint.split(",",2); LatLng sydney = new LatLng(Double.parseDouble(valuesParts[0]),Double.parseDouble(valuesParts[1])); mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(sydney,10)); } catch (InterruptedException e1) { e1.printStackTrace(); } catch (ExecutionException e1) { e1.printStackTrace(); } } }
3,146
0.68754
0.6815
75
40.933334
35.375824
136
false
false
0
0
0
0
0
0
0.68
false
false
11
7833e3897458176c2df5bbf27736f0f42d7e73bc
22,308,060,170,820
b90200604cc5ff80765bba483ef2f963fadb18bb
/phonograph/src/main/java/com/ninovanhooff/phonograph/data/FileRepositoryImpl.java
25d10256819239e003fe4032b36b573bf88c781f
[ "Apache-2.0" ]
permissive
ninovanhooff/Phonograph
https://github.com/ninovanhooff/Phonograph
81fdafb4ba4ad76f22ab93e889afdf18ac14b35c
c62b06730bbf01ecbfc0fcf81d7ec43d690b5e8b
refs/heads/master
2021-01-05T13:20:26.197000
2020-05-11T15:31:04
2020-05-11T15:31:04
241,033,385
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright 2018 Dmitriy Ponomarenko * * 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.ninovanhooff.phonograph.data; import android.content.Context; import com.ninovanhooff.phonograph.PhonographConstants; import com.ninovanhooff.phonograph.exception.CantCreateFileException; import com.ninovanhooff.phonograph.util.FileUtil; import java.io.File; import java.io.FileNotFoundException; import timber.log.Timber; public class FileRepositoryImpl implements FileRepository { private File recordDirectory; private PhonographPrefs prefs; private volatile static FileRepositoryImpl instance; private FileRepositoryImpl(Context context, PhonographPrefs prefs) { updateRecordingDir(context, prefs); this.prefs = prefs; } public static FileRepositoryImpl getInstance(Context context, PhonographPrefs prefs) { if (instance == null) { synchronized (FileRepositoryImpl.class) { if (instance == null) { instance = new FileRepositoryImpl(context, prefs); } } } return instance; } @Override public File provideRecordFile() throws CantCreateFileException { prefs.incrementRecordCounter(); File recordFile; String recordName; if (prefs.getNamingFormat() == PhonographConstants.NAMING_COUNTED) { recordName = FileUtil.generateRecordNameCounted(prefs.getRecordCounter()); } else { recordName = FileUtil.generateRecordNameDate(); } if (prefs.getFormat() == PhonographConstants.RECORDING_FORMAT_WAV) { recordFile = FileUtil.createFile(recordDirectory, FileUtil.addExtension(recordName, PhonographConstants.WAV_EXTENSION)); } else { recordFile = FileUtil.createFile(recordDirectory, FileUtil.addExtension(recordName, PhonographConstants.M4A_EXTENSION)); } if (recordFile != null) { return recordFile; } throw new CantCreateFileException(); } @Override public File provideRecordFile(String name) throws CantCreateFileException { File recordFile = FileUtil.createFile(recordDirectory, name); if (recordFile != null) { return recordFile; } throw new CantCreateFileException(); } @Override public File getRecordingDir() { return recordDirectory; } @Override public boolean deleteRecordFile(String path) { if (path != null) { return FileUtil.deleteFile(new File(path)); } return false; } @Override public boolean renameFile(String path, String newName, String extension) { return FileUtil.renameFile(new File(path), newName, extension); } public void updateRecordingDir(Context context, PhonographPrefs prefs) { if (prefs.isStoreDirPublic()) { recordDirectory = getAppDir(); if (recordDirectory == null) { //Try to init private dir try { recordDirectory = FileUtil.getPrivateRecordsDir(context); } catch (FileNotFoundException e) { Timber.e(e); //If nothing helped then hardcode recording dir recordDirectory = context.getFilesDir(); } } } else { try { recordDirectory = FileUtil.getPrivateRecordsDir(context); } catch (FileNotFoundException e) { Timber.e(e); //Try to init public dir recordDirectory = getAppDir(); if (recordDirectory == null) { //If nothing helped then hardcode recording dir recordDirectory = context.getFilesDir(); // todo test } } } } private File getAppDir() { return FileUtil.getStorageDir(prefs.getPublicRecordingDirName()); } }
UTF-8
Java
3,884
java
FileRepositoryImpl.java
Java
[ { "context": "/*\n * Copyright 2018 Dmitriy Ponomarenko\n *\n * Licensed under the Apache License, Version ", "end": 40, "score": 0.9998212456703186, "start": 21, "tag": "NAME", "value": "Dmitriy Ponomarenko" } ]
null
[]
/* * Copyright 2018 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ninovanhooff.phonograph.data; import android.content.Context; import com.ninovanhooff.phonograph.PhonographConstants; import com.ninovanhooff.phonograph.exception.CantCreateFileException; import com.ninovanhooff.phonograph.util.FileUtil; import java.io.File; import java.io.FileNotFoundException; import timber.log.Timber; public class FileRepositoryImpl implements FileRepository { private File recordDirectory; private PhonographPrefs prefs; private volatile static FileRepositoryImpl instance; private FileRepositoryImpl(Context context, PhonographPrefs prefs) { updateRecordingDir(context, prefs); this.prefs = prefs; } public static FileRepositoryImpl getInstance(Context context, PhonographPrefs prefs) { if (instance == null) { synchronized (FileRepositoryImpl.class) { if (instance == null) { instance = new FileRepositoryImpl(context, prefs); } } } return instance; } @Override public File provideRecordFile() throws CantCreateFileException { prefs.incrementRecordCounter(); File recordFile; String recordName; if (prefs.getNamingFormat() == PhonographConstants.NAMING_COUNTED) { recordName = FileUtil.generateRecordNameCounted(prefs.getRecordCounter()); } else { recordName = FileUtil.generateRecordNameDate(); } if (prefs.getFormat() == PhonographConstants.RECORDING_FORMAT_WAV) { recordFile = FileUtil.createFile(recordDirectory, FileUtil.addExtension(recordName, PhonographConstants.WAV_EXTENSION)); } else { recordFile = FileUtil.createFile(recordDirectory, FileUtil.addExtension(recordName, PhonographConstants.M4A_EXTENSION)); } if (recordFile != null) { return recordFile; } throw new CantCreateFileException(); } @Override public File provideRecordFile(String name) throws CantCreateFileException { File recordFile = FileUtil.createFile(recordDirectory, name); if (recordFile != null) { return recordFile; } throw new CantCreateFileException(); } @Override public File getRecordingDir() { return recordDirectory; } @Override public boolean deleteRecordFile(String path) { if (path != null) { return FileUtil.deleteFile(new File(path)); } return false; } @Override public boolean renameFile(String path, String newName, String extension) { return FileUtil.renameFile(new File(path), newName, extension); } public void updateRecordingDir(Context context, PhonographPrefs prefs) { if (prefs.isStoreDirPublic()) { recordDirectory = getAppDir(); if (recordDirectory == null) { //Try to init private dir try { recordDirectory = FileUtil.getPrivateRecordsDir(context); } catch (FileNotFoundException e) { Timber.e(e); //If nothing helped then hardcode recording dir recordDirectory = context.getFilesDir(); } } } else { try { recordDirectory = FileUtil.getPrivateRecordsDir(context); } catch (FileNotFoundException e) { Timber.e(e); //Try to init public dir recordDirectory = getAppDir(); if (recordDirectory == null) { //If nothing helped then hardcode recording dir recordDirectory = context.getFilesDir(); // todo test } } } } private File getAppDir() { return FileUtil.getStorageDir(prefs.getPublicRecordingDirName()); } }
3,871
0.742019
0.739701
132
28.424242
27.500172
123
false
false
0
0
0
0
0
0
2.068182
false
false
11